diff --git a/DEPS b/DEPS index 33ff72b..e8af060 100644 --- a/DEPS +++ b/DEPS
@@ -138,7 +138,7 @@ # 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': 'c8f285a7077effb2dc43043873d48f8d00247abb', + 'skia_revision': '6a07591a5577b63893dc4018a7c54fc4bb28dbb2', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. @@ -150,15 +150,15 @@ # 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': 'bc30e72cb429c30fc762689554ba8d27a2b08dbb', + 'angle_revision': 'f7106d16306ae3a98a37100ee028b5aaeca63586', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. - 'swiftshader_revision': 'c0d7ee45d45f22772ceca9e961c1ab4cfc9322d9', + 'swiftshader_revision': '95b1db9619fb0f5f232c09995bc00729273f74ee', # 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': '78f6819b0e70edfac5a7b31a4645efb92e7f2c10', + 'pdfium_revision': '8fa6a209221b41c841c6b646bc4c55825c20682f', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling BoringSSL # and whatever else without interference from each other. @@ -257,7 +257,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'spv_tools_revision': '7919b877c3c10f1fecfdab79e66120a28fede0d1', + 'spv_tools_revision': '699e167d78eee66232f140d4dcf5e9453de2dc74', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -807,7 +807,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '8b079d6881fc304ce89d6f55993e061434048a2a', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '09fad2edc8250ba00e3a4c20447e10104d205292', 'condition': 'checkout_linux', }, @@ -980,7 +980,7 @@ Var('chromium_git') + '/chromium/deps/hunspell_dictionaries.git' + '@' + '3874188bd69fe67a825d07584c74451e45063e95', 'src/third_party/icu': - Var('chromium_git') + '/chromium/deps/icu.git' + '@' + '64e5d7d43a1ff205e3787ab6150bbc1a1837332b', + Var('chromium_git') + '/chromium/deps/icu.git' + '@' + '9f0f47b1e410b137762f2e3699359f0dbfcdbc05', 'src/third_party/icu4j': { 'packages': [ @@ -1159,7 +1159,7 @@ Var('chromium_git') + '/external/github.com/cisco/openh264' + '@' + '6f26bce0b1c4e8ce0e13332f7c0083788def5fdf', 'src/third_party/openscreen/src': - Var('chromium_git') + '/openscreen' + '@' + '6dcfbb6577554933548255799ed7b58bfbfc51fd', + Var('chromium_git') + '/openscreen' + '@' + '7bc7f102467b395fbf4963ac34e4844564c783d3', 'src/third_party/ow2_asm': { 'packages': [ @@ -1350,7 +1350,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + '6f0b34abee8dba611c253738d955c59f703c147a', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + 'd7e2fb330924314554ae80a3a2d3849d61ab93e8', + Var('webrtc_git') + '/src.git' + '@' + '85b8ce2ab95bea71bebd5238f86df04183ac4025', 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -1391,7 +1391,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@0817a0661743adce9777db369f67c833bb828973', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@261cefc6693a5217e6f9af7b05b762c1cee2a433', 'condition': 'checkout_src_internal', },
diff --git a/WATCHLISTS b/WATCHLISTS index f0d7df53..45699aaf 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -2484,8 +2484,10 @@ 'payments': ['rouslan+payments@chromium.org', 'gogerald+paymentswatch@chromium.org', 'mahmadi+paymentswatch@chromium.org', - 'anthonyvd+paymentswatch@chromium.org'], - 'payments_ios': ['mahmadi+paymentsioswatch@chromium.org'], + 'anthonyvd+paymentswatch@chromium.org', + 'danyao+paymentswatch@chromium.org'], + 'payments_ios': ['mahmadi+paymentsioswatch@chromium.org', + 'danyao+paymentswatch@chromium.org'], 'pepper_api': ['binji+watch@chromium.org', 'bradnelson+warch@chromium.org', 'ihf+watch@chromium.org',
diff --git a/android_webview/docs/quick-start.md b/android_webview/docs/quick-start.md index 6a5ac503..4d2a305 100644 --- a/android_webview/docs/quick-start.md +++ b/android_webview/docs/quick-start.md
@@ -43,7 +43,8 @@ ## Setting up the build -Assuming you took the advice from above: +Assuming you took the advice from above, configure GN args (run `gn args +out/Default`) as follows: ```gn # Minimal
diff --git a/android_webview/test/shell/AndroidManifest.xml b/android_webview/test/shell/AndroidManifest.xml index 1f2874d4..5fcaa9b 100644 --- a/android_webview/test/shell/AndroidManifest.xml +++ b/android_webview/test/shell/AndroidManifest.xml
@@ -30,6 +30,7 @@ android:configChanges="orientation|keyboardHidden|keyboard|screenSize"> <intent-filter> <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
diff --git a/android_webview/tools/system_webview_shell/apk/AndroidManifest.xml b/android_webview/tools/system_webview_shell/apk/AndroidManifest.xml index a3d028f6..7dc4b34 100644 --- a/android_webview/tools/system_webview_shell/apk/AndroidManifest.xml +++ b/android_webview/tools/system_webview_shell/apk/AndroidManifest.xml
@@ -75,6 +75,7 @@ android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|density"> <intent-filter> <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <!-- Catch intents which do not specify a MIME type -->
diff --git a/ash/accelerators/accelerator_controller_impl.cc b/ash/accelerators/accelerator_controller_impl.cc index 5945ff4..46d4994 100644 --- a/ash/accelerators/accelerator_controller_impl.cc +++ b/ash/accelerators/accelerator_controller_impl.cc
@@ -32,6 +32,7 @@ #include "ash/metrics/user_metrics_recorder.h" #include "ash/multi_profile_uma.h" #include "ash/public/cpp/ash_features.h" +#include "ash/public/cpp/ash_switches.h" #include "ash/public/cpp/new_window_delegate.h" #include "ash/public/cpp/notification_utils.h" #include "ash/public/interfaces/accessibility_controller.mojom.h" @@ -69,6 +70,7 @@ #include "ash/wm/window_util.h" #include "ash/wm/wm_event.h" #include "base/bind.h" +#include "base/command_line.h" #include "base/json/json_reader.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" @@ -1941,19 +1943,26 @@ } void AcceleratorControllerImpl::ParseSideVolumeButtonLocationInfo() { - if (!base::PathExists(side_volume_button_location_file_path_)) - return; - std::string location_info; - if (!base::ReadFileToString(side_volume_button_location_file_path_, - &location_info) || - location_info.empty()) { + const base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); + if (cl->HasSwitch(switches::kAshSideVolumeButtonPosition)) { + location_info = + cl->GetSwitchValueASCII(switches::kAshSideVolumeButtonPosition); + } else if (!base::PathExists(side_volume_button_location_file_path_) || + !base::ReadFileToString(side_volume_button_location_file_path_, + &location_info) || + location_info.empty()) { return; } std::unique_ptr<base::DictionaryValue> info_in_dict = base::DictionaryValue::From( base::JSONReader::ReadDeprecated(location_info)); + if (!info_in_dict) { + LOG(ERROR) << "JSONReader failed reading side volume button location info: " + << location_info; + return; + } info_in_dict->GetString(kVolumeButtonRegion, &side_volume_button_location_.region); info_in_dict->GetString(kVolumeButtonSide,
diff --git a/ash/public/cpp/ash_switches.cc b/ash/public/cpp/ash_switches.cc index efe2ea7f..b93aa484 100644 --- a/ash/public/cpp/ash_switches.cc +++ b/ash/public/cpp/ash_switches.cc
@@ -90,6 +90,12 @@ // Enables the heads-up display for tracking touch points. const char kAshTouchHud[] = "ash-touch-hud"; +// The physical position info of the side volume button while in landscape +// primary screen orientation. The value is a JSON object containing a "region" +// property with the value "keyboard", "screen" and a "side" property with the +// value "left", "right", "top", "bottom". +const char kAshSideVolumeButtonPosition[] = "ash-side-volume-button-position"; + // (Most) Chrome OS hardware reports ACPI power button releases correctly. // Standard hardware reports releases immediately after presses. If set, we // lock the screen or shutdown the system immediately in response to a press
diff --git a/ash/public/cpp/ash_switches.h b/ash/public/cpp/ash_switches.h index f373a06d..00279851 100644 --- a/ash/public/cpp/ash_switches.h +++ b/ash/public/cpp/ash_switches.h
@@ -44,6 +44,7 @@ ASH_PUBLIC_EXPORT extern const char kAshShelfColorSchemeNormalVibrant[]; ASH_PUBLIC_EXPORT extern const char kAshShelfColorSchemeDarkMuted[]; ASH_PUBLIC_EXPORT extern const char kAshShelfColorSchemeDarkVibrant[]; +ASH_PUBLIC_EXPORT extern const char kAshSideVolumeButtonPosition[]; ASH_PUBLIC_EXPORT extern const char kAshTouchHud[]; ASH_PUBLIC_EXPORT extern const char kAuraLegacyPowerButton[]; ASH_PUBLIC_EXPORT extern const char kForceTabletPowerButton[];
diff --git a/base/BUILD.gn b/base/BUILD.gn index f84d803..c7f96f21 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -3420,6 +3420,7 @@ "android/junit/src/org/chromium/base/util/GarbageCollectionTestUtil.java", "test/android/junit/src/org/chromium/base/task/test/BackgroundShadowAsyncTask.java", "test/android/junit/src/org/chromium/base/task/test/CustomShadowAsyncTask.java", + "test/android/junit/src/org/chromium/base/task/test/ShadowPostTask.java", "test/android/junit/src/org/chromium/base/test/BaseRobolectricTestRunner.java", "test/android/junit/src/org/chromium/base/test/util/TestRunnerTestRule.java", "//third_party/robolectric/custom_asynctask/java/src/org/chromium/base/task/test/ShadowAsyncTask.java",
diff --git a/base/test/android/junit/src/org/chromium/base/task/test/ShadowPostTask.java b/base/test/android/junit/src/org/chromium/base/task/test/ShadowPostTask.java new file mode 100644 index 0000000..00513276 --- /dev/null +++ b/base/test/android/junit/src/org/chromium/base/task/test/ShadowPostTask.java
@@ -0,0 +1,43 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.base.task.test; + +import org.robolectric.Robolectric; +import org.robolectric.annotation.Implementation; +import org.robolectric.annotation.Implements; +import org.robolectric.annotation.Resetter; + +import org.chromium.base.task.PostTask; +import org.chromium.base.task.TaskTraits; + +/** + * Shadow implementation for {@link PostTask}. + */ +@Implements(PostTask.class) +public class ShadowPostTask { + private static TestImpl sTestImpl = new TestImpl(); + + /** Set implementation for tests. Don't forget to call {@link #reset} later. */ + public static void setTestImpl(TestImpl testImpl) { + sTestImpl = testImpl; + } + + @Resetter + public static void reset() { + sTestImpl = new TestImpl(); + } + + @Implementation + public static void postDelayedTask(TaskTraits taskTraits, Runnable task, long delay) { + sTestImpl.postDelayedTask(taskTraits, task, delay); + } + + /** Default implementation for tests. Override methods or add new ones as necessary. */ + public static class TestImpl { + public void postDelayedTask(TaskTraits taskTraits, Runnable task, long delay) { + Robolectric.getForegroundThreadScheduler().postDelayed(task, delay); + } + } +}
diff --git a/build/chromeos/test_runner.py b/build/chromeos/test_runner.py index 93459a8..f4e2f3c 100755 --- a/build/chromeos/test_runner.py +++ b/build/chromeos/test_runner.py
@@ -366,6 +366,11 @@ if not suite_results.DidRunPass(): return 1 + elif return_code: + logging.warning( + 'No failed tests found, but exit code of %d was returned from ' + 'cros_run_test.', return_code) + return return_code return 0 @@ -397,6 +402,7 @@ self._test_launcher_total_shards = args.test_launcher_total_shards self._on_device_script = None + self._stop_ui = args.stop_ui @property def suite_name(self): @@ -464,9 +470,7 @@ if self._additional_args: test_invocation += ' %s' % ' '.join(self._additional_args) - if self._test_exe == 'interactive_ui_tests': - # interactive_ui_tests needs some special setup. See crbug.com/946685#c4 - # TODO(bpastene): Put all this behind a flag if more suites need it. + if self._stop_ui: device_test_script_contents += [ 'stop ui', ] @@ -767,6 +771,9 @@ '--test-launcher-total-shards', type=int, default=os.environ.get('GTEST_TOTAL_SHARDS', 1), help='Total number of external shards.') + gtest_parser.add_argument( + '--stop-ui', action='store_true', + help='Will stop the UI service in the device before running the test.') # Tast test args. # pylint: disable=line-too-long
diff --git a/build/toolchain/mac/BUILD.gn b/build/toolchain/mac/BUILD.gn index 22316c9..b9c65b0 100644 --- a/build/toolchain/mac/BUILD.gn +++ b/build/toolchain/mac/BUILD.gn
@@ -432,10 +432,21 @@ # constructed using shell variable $OLDPWD (automatically set when # cd is used) as computing the relative path is a bit complex and # using pwd would requires a sub-shell to be created. + # + # A special case exists for copying symbolic links. The pax command, + # as noted above, preserves symbolic links but only if they are a child + # node of source. But if the source itself is a symbolic link to a + # directory, the cd into it will copy it as a logical tree rather than + # a symbolic link. Similarly, if source is a symbolic link to a file, + # then the copy_command hard link will not produce a symbolic link, it + # would hard link the file pointed to by the symbolic link. _copydir = "mkdir -p {{output}} && cd {{source}} && " + "pax -rwl . \"\$OLDPWD\"/{{output}}" - command = "rm -rf {{output}} && if [[ -d {{source}} ]]; then " + - _copydir + "; else " + copy_command + "; fi" + _copylink = "ln -s \$(readlink {{source}}) {{output}}" + command = "rm -rf {{output}} && " + + "if [[ -L {{source}} ]]; then $_copylink; " + + "elif [[ -d {{source}} ]]; then $_copydir; " + + "else $copy_command; fi" description = "COPY_BUNDLE_DATA {{source}} {{output}}" pool = ":bundle_pool($default_toolchain)"
diff --git a/cc/trees/layer_tree_host_pixeltest_blending.cc b/cc/trees/layer_tree_host_pixeltest_blending.cc index 3f0c28b4..091881f5 100644 --- a/cc/trees/layer_tree_host_pixeltest_blending.cc +++ b/cc/trees/layer_tree_host_pixeltest_blending.cc
@@ -268,15 +268,6 @@ ::testing::Combine(::testing::Values(SOFTWARE, ZERO_COPY, SKIA_GL), ::testing::ValuesIn(kBlendModes))); -using LayerTreeHostBlendingPixelTestNonSkia = LayerTreeHostBlendingPixelTest; - -// TODO(crbug.com/948128): Enable these tests for Skia. -INSTANTIATE_TEST_SUITE_P(B, - LayerTreeHostBlendingPixelTestNonSkia, - ::testing::Combine(::testing::Values(SOFTWARE, - ZERO_COPY), - ::testing::ValuesIn(kBlendModes))); - TEST_P(LayerTreeHostBlendingPixelTest, BlendingWithRoot) { const int kRootWidth = 2; const int kRootHeight = 2; @@ -304,7 +295,7 @@ RunPixelResourceTest(background, expected); } -TEST_P(LayerTreeHostBlendingPixelTestNonSkia, BlendingWithBackdropFilter) { +TEST_P(LayerTreeHostBlendingPixelTest, BlendingWithBackdropFilter) { const int kRootWidth = 2; const int kRootHeight = 2; InitializeFromTestCase(resource_type());
diff --git a/cc/trees/layer_tree_host_pixeltest_filters.cc b/cc/trees/layer_tree_host_pixeltest_filters.cc index f65f0b7f..670b82e 100644 --- a/cc/trees/layer_tree_host_pixeltest_filters.cc +++ b/cc/trees/layer_tree_host_pixeltest_filters.cc
@@ -81,14 +81,6 @@ LayerTreeTest::RENDERER_SKIA_GL, LayerTreeTest::RENDERER_SOFTWARE)); -using LayerTreeHostFiltersPixelTestNonSkia = LayerTreeHostFiltersPixelTest; - -// TODO(crbug.com/948128): Enable these tests for Skia. -INSTANTIATE_TEST_SUITE_P(, - LayerTreeHostFiltersPixelTestNonSkia, - ::testing::Values(LayerTreeTest::RENDERER_GL, - LayerTreeTest::RENDERER_SOFTWARE)); - using LayerTreeHostFiltersPixelTestGL = LayerTreeHostFiltersPixelTest; // TODO(crbug.com/948128): Enable these tests for Skia. @@ -662,7 +654,7 @@ .InsertBeforeExtensionASCII(GetRendererSuffix())); } -TEST_P(LayerTreeHostFiltersPixelTestNonSkia, ZoomFilter) { +TEST_P(LayerTreeHostFiltersPixelTest, ZoomFilter) { scoped_refptr<SolidColorLayer> root = CreateSolidColorLayer(gfx::Rect(300, 300), SK_ColorWHITE); @@ -939,8 +931,7 @@ base::FilePath(FILE_PATH_LITERAL("enlarged_texture_on_crop_offset.png"))); } -// TODO(crbug.com/948128): Enable this test for SkiaRenderer. -TEST_P(LayerTreeHostFiltersPixelTestNonSkia, BlurFilterWithClip) { +TEST_P(LayerTreeHostFiltersPixelTest, BlurFilterWithClip) { scoped_refptr<SolidColorLayer> child1 = CreateSolidColorLayer(gfx::Rect(200, 200), SK_ColorBLUE); scoped_refptr<SolidColorLayer> child2 =
diff --git a/cc/trees/layer_tree_host_pixeltest_masks.cc b/cc/trees/layer_tree_host_pixeltest_masks.cc index 9e125057e..832657e 100644 --- a/cc/trees/layer_tree_host_pixeltest_masks.cc +++ b/cc/trees/layer_tree_host_pixeltest_masks.cc
@@ -820,18 +820,6 @@ INSTANTIATE_PIXEL_RESOURCE_TEST_SUITE_P( LayerTreeHostMasksForBackdropFiltersPixelTest); -using LayerTreeHostMasksForBackdropFiltersPixelTestNonSkia = - ParameterizedPixelResourceTest; - -// TODO(crbug.com/948128): Enable these tests for Skia. -INSTANTIATE_TEST_SUITE_P( - PixelResourceTest, - LayerTreeHostMasksForBackdropFiltersPixelTestNonSkia, - ::testing::Combine( - ::testing::Values(SOFTWARE, GPU, ONE_COPY, ZERO_COPY), - ::testing::Values(Layer::LayerMaskType::SINGLE_TEXTURE_MASK, - Layer::LayerMaskType::MULTI_TEXTURE_MASK))); - TEST_P(LayerTreeHostMasksForBackdropFiltersPixelTest, MaskOfLayerWithBackdropFilter) { scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer( @@ -1284,7 +1272,7 @@ RunPixelResourceTest(root, image_name); } -TEST_P(LayerTreeHostMasksForBackdropFiltersPixelTestNonSkia, +TEST_P(LayerTreeHostMasksForBackdropFiltersPixelTest, MaskOfLayerWithBackdropFilterAndBlend) { scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(gfx::Rect(128, 128), SK_ColorWHITE);
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index ece85734..db75a65 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -121,6 +121,7 @@ "//third_party/android_deps:android_support_v7_appcompat_java", "//third_party/android_deps:com_android_support_design_java", "//third_party/android_deps:com_android_support_gridlayout_v7_java", + "//third_party/android_deps:com_android_support_preference_v7_java", "//third_party/android_deps:com_android_support_recyclerview_v7_java", ] custom_package = "org.chromium.chrome" @@ -818,6 +819,7 @@ "//third_party/android_deps:android_arch_lifecycle_common_java", "//third_party/android_deps:android_support_v7_appcompat_java", "//third_party/android_deps:com_android_support_design_java", + "//third_party/android_deps:com_android_support_preference_v7_java", "//third_party/android_deps:com_android_support_recyclerview_v7_java", "//third_party/android_deps:com_android_support_support_annotations_java", "//third_party/android_deps:com_google_ar_core_java",
diff --git a/chrome/android/chrome_junit_test_java_sources.gni b/chrome/android/chrome_junit_test_java_sources.gni index aa7afa46..5d4bbee7 100644 --- a/chrome/android/chrome_junit_test_java_sources.gni +++ b/chrome/android/chrome_junit_test_java_sources.gni
@@ -57,7 +57,6 @@ "junit/src/org/chromium/chrome/browser/customtabs/content/CustomTabActivityTabControllerTest.java", "junit/src/org/chromium/chrome/browser/customtabs/content/CustomTabActivityUrlLoadingTest.java", "junit/src/org/chromium/chrome/browser/customtabs/shadows/ShadowExternalNavigationDelegateImpl.java", - "junit/src/org/chromium/chrome/browser/customtabs/shadows/ShadowPostTask.java", "junit/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutControllerTest.java", "junit/src/org/chromium/chrome/browser/download/DownloadResumptionSchedulerTest.java", "junit/src/org/chromium/chrome/browser/download/DownloadSharedPreferenceEntryTest.java",
diff --git a/chrome/android/java/res/drawable/list_divider_compat.xml b/chrome/android/java/res/drawable/list_divider_compat.xml new file mode 100644 index 0000000..dddef8e --- /dev/null +++ b/chrome/android/java/res/drawable/list_divider_compat.xml
@@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright 2019 The Chromium Authors. All rights reserved. + Use of this source code is governed by a BSD-style license that can be + found in the LICENSE file. --> + +<!-- KitKat Preference Fragments should have a slightly inset divider to match the system + preferences styling. On Lollipop+, the ?android:attr/listDivider (which extends edge-to-edge) + can be used. --> +<inset xmlns:android="http://schemas.android.com/apk/res/android" + android:insetLeft="@dimen/pref_list_padding_kitkat" + android:insetRight="@dimen/pref_list_padding_kitkat"> + <shape> + <solid android:color="@color/divider_bg_color" /> + <size + android:width="1dp" + android:height="1dp" /> + </shape> +</inset> \ No newline at end of file
diff --git a/chrome/android/java/res/layout/omnibox_answer_suggestion.xml b/chrome/android/java/res/layout/omnibox_answer_suggestion.xml index 07607e8..72d5bb7 100644 --- a/chrome/android/java/res/layout/omnibox_answer_suggestion.xml +++ b/chrome/android/java/res/layout/omnibox_answer_suggestion.xml
@@ -22,8 +22,7 @@ android:layout_toStartOf="@+id/omnibox_answer_refine_icon" android:layout_width="0dp"> - <org.chromium.ui.widget.RoundedCornerImageView - style="@style/RoundedCornerImageViewDefault" + <ImageView android:contentDescription="@null" android:id="@+id/omnibox_answer_icon" android:layout_centerVertical="true"
diff --git a/chrome/android/java/res/layout/omnibox_entity_suggestion.xml b/chrome/android/java/res/layout/omnibox_entity_suggestion.xml index 9d4cf7f..2f76cf0 100644 --- a/chrome/android/java/res/layout/omnibox_entity_suggestion.xml +++ b/chrome/android/java/res/layout/omnibox_entity_suggestion.xml
@@ -20,15 +20,14 @@ android:focusable="true" android:paddingVertical="10dp"> - <org.chromium.ui.widget.RoundedCornerImageView - style="@style/RoundedCornerImageViewDefault" + <ImageView android:id="@+id/omnibox_entity_image" android:layout_width="@dimen/omnibox_suggestion_entity_icon_size" android:layout_height="@dimen/omnibox_suggestion_entity_icon_size" android:layout_centerVertical="true" android:layout_marginEnd="8dp" android:layout_marginStart="@dimen/omnibox_suggestion_icon_margin_start" - android:contentDescription="@null"/> + android:contentDescription="@null" /> <TextView android:id="@+id/omnibox_entity_subject_text"
diff --git a/chrome/android/java/res/layout/os_version_unsupported_preference.xml b/chrome/android/java/res/layout/os_version_unsupported_preference.xml index da81d15..f216fc6 100644 --- a/chrome/android/java/res/layout/os_version_unsupported_preference.xml +++ b/chrome/android/java/res/layout/os_version_unsupported_preference.xml
@@ -8,6 +8,7 @@ style="@style/PreferenceLayout" android:layout_width="match_parent" android:layout_height="wrap_content" + android:background="?android:attr/selectableItemBackground" android:orientation="vertical"> <TextView
diff --git a/chrome/android/java/res/layout/preference_compat.xml b/chrome/android/java/res/layout/preference_compat.xml new file mode 100644 index 0000000..c718494 --- /dev/null +++ b/chrome/android/java/res/layout/preference_compat.xml
@@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright 2019 The Chromium Authors. All rights reserved. + Use of this source code is governed by a BSD-style license that can be + found in the LICENSE file. --> + +<!-- TODO(chouinard): For now this supports simple text-only preferences, but more children will be + added to this layout in the near future as we migrate more complex preferences. --> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + style="@style/PreferenceLayout" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:gravity="center_vertical" + android:background="?android:attr/selectableItemBackground" + android:focusable="true" + android:baselineAligned="false"> + + <RelativeLayout + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1"> + + <TextView android:id="@android:id/title" + style="@style/PreferenceTitle" + android:layout_width="wrap_content" + android:layout_height="wrap_content" /> + + <TextView android:id="@android:id/summary" + style="@style/PreferenceSummary" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_below="@android:id/title" + android:layout_alignStart="@android:id/title" /> + + </RelativeLayout> + +</LinearLayout>
diff --git a/chrome/android/java/res/values-v17/styles.xml b/chrome/android/java/res/values-v17/styles.xml index afaebbbe..97207adf 100644 --- a/chrome/android/java/res/values-v17/styles.xml +++ b/chrome/android/java/res/values-v17/styles.xml
@@ -3,8 +3,7 @@ Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> -<resources - xmlns:tools="http://schemas.android.com/tools"> +<resources xmlns:tools="http://schemas.android.com/tools"> <!-- Q: Why put style resources under values-v17/ ? A: Problem: 1. paddingStart causes a crash on Galaxy Tab&Note b/8351339. @@ -155,6 +154,7 @@ <item name="android:textAppearanceSmall">@style/TextAppearance.BlackBody</item> <item name="android:preferenceCategoryStyle">@style/PreferenceCategory</item> <item name="android:windowContentOverlay">@null</item> + <item name="preferenceTheme">@style/Theme.Chromium.PreferenceTheme</item> </style> <style name="Theme.Chromium.Preferences.ManageSpace"> @@ -241,6 +241,25 @@ <style name="OverflowMenuThemeOverlay" parent="Base.OverflowMenuThemeOverlay" /> <!-- Preferences styles --> + <style name="Theme.Chromium.PreferenceTheme"> + <item name="preferenceStyle">@style/Theme.Chromium.PreferenceItem</item> + <item name="preferenceFragmentCompatStyle">@style/Theme.Chromium.PreferenceFragment</item> + <item name="preferenceFragmentListStyle">@style/Theme.Chromium.PreferenceFragmentList</item> + </style> + + <style name="Theme.Chromium.PreferenceFragment"> + <item name="android:divider">@drawable/list_divider_compat</item> + </style> + + <style name="Theme.Chromium.PreferenceItem"> + <item name="android:layout">@layout/preference_compat</item> + </style> + + <style name="Theme.Chromium.PreferenceFragmentList"> + <item name="android:paddingStart">@dimen/pref_list_padding_kitkat</item> + <item name="android:paddingEnd">@dimen/pref_list_padding_kitkat</item> + </style> + <style name="PreferenceActionBarModern" parent="@style/Widget.AppCompat.Light.ActionBar.Solid"> <item name="titleTextStyle">@style/TextAppearance.BlackHeadline</item> </style> @@ -266,7 +285,7 @@ <style name="PreferenceTitle"> <item name="android:ellipsize">end</item> <item name="android:singleLine">true</item> - <item name="android:textAppearance">?android:attr/textAppearanceMedium</item> + <item name="android:textAppearance">@style/TextAppearance.PreferenceMediumText</item> </style> <style name="PreferenceSummary"> <item name="android:textAppearance">@style/TextAppearance.BlackBody</item> @@ -930,10 +949,4 @@ <item name="android:layout_height">@dimen/omnibox_suggestion_edit_url_min_height</item> <item name="tint">@color/default_icon_color</item> </style> - <style name="RoundedCornerImageViewDefault"> - <item name="cornerRadiusTopStart">@dimen/default_rounded_corner_radius</item> - <item name="cornerRadiusTopEnd">@dimen/default_rounded_corner_radius</item> - <item name="cornerRadiusBottomStart">@dimen/default_rounded_corner_radius</item> - <item name="cornerRadiusBottomEnd">@dimen/default_rounded_corner_radius</item> - </style> </resources>
diff --git a/chrome/android/java/res/values-v21/styles.xml b/chrome/android/java/res/values-v21/styles.xml index 9aefa9a..2272d729 100644 --- a/chrome/android/java/res/values-v21/styles.xml +++ b/chrome/android/java/res/values-v21/styles.xml
@@ -22,7 +22,18 @@ <!-- Overriding alertDialogTheme pre-v21 with our custom AlertDialog theme causes bad visual states on ListPreference because we don't use the support library ListPreference. --> <item name="android:alertDialogTheme">@style/Theme.Chromium.AlertDialog</item> + <item name="preferenceTheme">@style/Theme.Chromium.PreferenceTheme</item> </style> + + <style name="Theme.Chromium.PreferenceFragment"> + <item name="android:divider">?android:attr/listDivider</item> + </style> + + <style name="Theme.Chromium.PreferenceFragmentList"> + <item name="android:paddingStart">0dp</item> + <item name="android:paddingEnd">0dp</item> + </style> + <style name="PreferenceCategoryWithButtonStyle"> <item name="android:paddingStart">?android:attr/listPreferredItemPaddingStart</item> <item name="android:paddingEnd">4dp</item>
diff --git a/chrome/android/java/res/values/dimens.xml b/chrome/android/java/res/values/dimens.xml index 1ac2935..13c4232 100644 --- a/chrome/android/java/res/values/dimens.xml +++ b/chrome/android/java/res/values/dimens.xml
@@ -482,6 +482,7 @@ <dimen name="pref_autofill_touch_target_padding">15dp</dimen> <dimen name="pref_icon_padding">4.6dp</dimen> + <dimen name="pref_list_padding_kitkat">16dp</dimen> <dimen name="pref_spinner_padding_end">8dp</dimen> <dimen name="pref_languages_padding">16dp</dimen>
diff --git a/chrome/android/java/res/xml/about_chrome_preferences.xml b/chrome/android/java/res/xml/about_chrome_preferences.xml index e1ddc30..a24c0ee2 100644 --- a/chrome/android/java/res/xml/about_chrome_preferences.xml +++ b/chrome/android/java/res/xml/about_chrome_preferences.xml
@@ -3,15 +3,15 @@ Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> -<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> - <Preference +<android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> + <android.support.v7.preference.Preference android:key="application_version" android:title="@string/application_version_title" /> <org.chromium.chrome.browser.preferences.AboutChromePreferenceOSVersion android:key="os_version" android:title="@string/os_version_title" /> - <Preference + <android.support.v7.preference.Preference android:fragment="org.chromium.chrome.browser.preferences.LegalInformationPreferences" android:key="legal_information" android:title="@string/legal_information_title" /> -</PreferenceScreen> +</android.support.v7.preference.PreferenceScreen>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java index 989f200..ac1dc06e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java
@@ -242,7 +242,6 @@ public static final String HORIZONTAL_TAB_SWITCHER_ANDROID = "HorizontalTabSwitcherAndroid"; public static final String IDENTITY_DISC = "IdentityDisc"; public static final String IMMERSIVE_UI_MODE = "ImmersiveUiMode"; - public static final String INCOGNITO_STRINGS = "IncognitoStrings"; public static final String INLINE_UPDATE_FLOW = "InlineUpdateFlow"; public static final String INSTALLABLE_AMBIENT_BADGE_INFOBAR = "InstallableAmbientBadgeInfoBar"; public static final String INTENT_BLOCK_EXTERNAL_FORM_REDIRECT_NO_GESTURE =
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/KeyboardShortcuts.java b/chrome/android/java/src/org/chromium/chrome/browser/KeyboardShortcuts.java index a7859226..0dfed7ae 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/KeyboardShortcuts.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/KeyboardShortcuts.java
@@ -120,10 +120,7 @@ KeyEvent.KEYCODE_N, KeyEvent.META_CTRL_ON); addShortcut(context, tabShortcutGroup, R.string.keyboard_shortcut_reopen_new_tab, KeyEvent.KEYCODE_T, ctrlShift); - addShortcut(context, tabShortcutGroup, - ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS) - ? R.string.keyboard_shortcut_new_private_tab - : R.string.keyboard_shortcut_new_incognito_tab, + addShortcut(context, tabShortcutGroup, R.string.keyboard_shortcut_new_incognito_tab, KeyEvent.KEYCODE_N, ctrlShift); addShortcut(context, tabShortcutGroup, R.string.keyboard_shortcut_next_tab, KeyEvent.KEYCODE_TAB, KeyEvent.META_CTRL_ON);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/LauncherShortcutActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/LauncherShortcutActivity.java index 5c4a5a0..02b0293 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/LauncherShortcutActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/LauncherShortcutActivity.java
@@ -97,17 +97,12 @@ intent.setPackage(context.getPackageName()); intent.setClass(context, LauncherShortcutActivity.class); - boolean useAlternativeIncognitoStrings = - ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS); ShortcutInfo shortcut = new ShortcutInfo.Builder(context, DYNAMIC_OPEN_NEW_INCOGNITO_TAB_ID) .setShortLabel(context.getResources().getString( - useAlternativeIncognitoStrings - ? R.string.accessibility_tabstrip_private_identifier - : R.string.accessibility_tabstrip_incognito_identifier)) - .setLongLabel(context.getResources().getString( - useAlternativeIncognitoStrings ? R.string.menu_new_private_tab - : R.string.menu_new_incognito_tab)) + R.string.accessibility_tabstrip_incognito_identifier)) + .setLongLabel( + context.getResources().getString(R.string.menu_new_incognito_tab)) .setIcon(Icon.createWithResource(context, R.drawable.shortcut_incognito)) .setIntent(intent) .build();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/appmenu/AppMenuHandlerImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/appmenu/AppMenuHandlerImpl.java index 58baa20..acb717ef 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/appmenu/AppMenuHandlerImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/appmenu/AppMenuHandlerImpl.java
@@ -96,8 +96,10 @@ mActivityLifecycleDispatcher = activityLifecycleDispatcher; mActivityLifecycleDispatcher.register(this); + // TODO(twellington): Move overview mode/app menu logic to parent root UI coordinator (to + // control interaction between peer components)? mOverviewModeBehaviorSupplier = overviewModeBehaviorSupplier; - if (mOverviewModeBehavior != null) { + if (mOverviewModeBehaviorSupplier != null) { mOverviewModeSupplierCallback = overviewModeBehavior -> { if (mOverviewModeBehavior != null) { mOverviewModeBehavior.removeOverviewModeObserver(this); @@ -305,7 +307,15 @@ } @Override - public void onOverviewModeFinishedShowing() {} + public void onOverviewModeFinishedShowing() { + // Ideally we wouldn't allow the app menu to show while animating the overview mode. This is + // hard to track, however, because in some instances #onOverviewModeStartedShowing is called + // after #onOverviewModeFinishedShowing (see https://crbug.com/969047). + // Once that bug is fixed, we can remove this call to hide in favor of disallowing app + // menu shows during animation. Alternatively, we could expose a way to query whether an + // animation is in progress. + hideAppMenu(); + } @Override public void onOverviewModeStartedHiding(boolean showToolbar, boolean delayAnimation) { @@ -313,7 +323,9 @@ } @Override - public void onOverviewModeFinishedHiding() {} + public void onOverviewModeFinishedHiding() { + hideAppMenu(); + } @VisibleForTesting public void onOptionsItemSelected(MenuItem item) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/appmenu/AppMenuPropertiesDelegateImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/appmenu/AppMenuPropertiesDelegateImpl.java index 375c623..a496d1e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/appmenu/AppMenuPropertiesDelegateImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/appmenu/AppMenuPropertiesDelegateImpl.java
@@ -267,17 +267,12 @@ // We have to iterate all menu items since same menu item ID may be associated with more // than one menu items. - boolean useAlternativeIncognitoStrings = - ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS); for (int i = 0; i < menu.size(); ++i) { MenuItem item = menu.getItem(i); if (item.getItemId() == R.id.new_incognito_tab_menu_id) { - item.setTitle(useAlternativeIncognitoStrings ? R.string.menu_new_private_tab - : R.string.menu_new_incognito_tab); + item.setTitle(R.string.menu_new_incognito_tab); } else if (item.getItemId() == R.id.close_all_incognito_tabs_menu_id) { - item.setTitle(useAlternativeIncognitoStrings - ? R.string.menu_close_all_private_tabs - : R.string.menu_close_all_incognito_tabs); + item.setTitle(R.string.menu_close_all_incognito_tabs); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkActionBar.java b/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkActionBar.java index db9902ea..63f6cba 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkActionBar.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/bookmarks/BookmarkActionBar.java
@@ -12,7 +12,6 @@ import android.view.View.OnClickListener; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.bookmarks.BookmarkBridge.BookmarkItem; import org.chromium.chrome.browser.bookmarks.BookmarkBridge.BookmarkModelObserver; import org.chromium.chrome.browser.preferences.PrefServiceBridge; @@ -56,9 +55,7 @@ getMenu() .findItem(R.id.selection_open_in_incognito_tab_id) - .setTitle(ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS) - ? R.string.contextmenu_open_in_private_tab - : R.string.contextmenu_open_in_incognito_tab); + .setTitle(R.string.contextmenu_open_in_incognito_tab); // Wait to enable the selection mode group until the BookmarkDelegate is set. The // SelectionDelegate is retrieved from the BookmarkDelegate.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/ephemeraltab/EphemeralTabPanel.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/ephemeraltab/EphemeralTabPanel.java index 1e4ee160..51e7fc9 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/ephemeraltab/EphemeralTabPanel.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/ephemeraltab/EphemeralTabPanel.java
@@ -107,11 +107,18 @@ stopListeningForCloseConditions(); } + private class EphemeralTabPanelContentDelegate extends OverlayContentDelegate { + @Override + public void onMainFrameNavigation(String url, boolean isExternalUrl, boolean isFailure) { + if (!isFailure) mUrl = url; + } + } + @Override public OverlayPanelContent createNewOverlayPanelContent() { if (mTabModelObserver == null) startListeningForCloseConditions(); - return new OverlayPanelContent(new OverlayContentDelegate(), new PanelProgressObserver(), - mActivity, mIsIncognito, getBarHeight()); + return new OverlayPanelContent(new EphemeralTabPanelContentDelegate(), + new PanelProgressObserver(), mActivity, mIsIncognito, getBarHeight()); } private void startListeningForCloseConditions() {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java index f7b25d2..c57df591 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java
@@ -26,7 +26,6 @@ import org.chromium.base.VisibleForTesting; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.compositor.animation.CompositorAnimator; import org.chromium.chrome.browser.compositor.layouts.LayoutRenderHost; import org.chromium.chrome.browser.compositor.layouts.LayoutUpdateHost; @@ -197,14 +196,10 @@ // Create tab menu mTabMenu = new ListPopupWindow(mContext); - boolean userAlternativeIncognitoStrings = ChromeFeatureList.isInitialized() - && ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS); mTabMenu.setAdapter(new ArrayAdapter<String>(mContext, R.layout.list_menu_item, - new String[] {mContext.getString(!mIncognito - ? R.string.menu_close_all_tabs - : (userAlternativeIncognitoStrings - ? R.string.menu_close_all_private_tabs - : R.string.menu_close_all_incognito_tabs))})); + new String[] { + mContext.getString(!mIncognito ? R.string.menu_close_all_tabs + : R.string.menu_close_all_incognito_tabs)})); mTabMenu.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { @@ -1770,14 +1765,8 @@ @StringRes int resId; if (mIncognito) { - if (ChromeFeatureList.isInitialized() - && ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS)) { - resId = isHidden ? R.string.accessibility_tabstrip_private_identifier - : R.string.accessibility_tabstrip_private_identifier_selected; - } else { - resId = isHidden ? R.string.accessibility_tabstrip_incognito_identifier - : R.string.accessibility_tabstrip_incognito_identifier_selected; - } + resId = isHidden ? R.string.accessibility_tabstrip_incognito_identifier + : R.string.accessibility_tabstrip_incognito_identifier_selected; } else { resId = isHidden ? R.string.accessibility_tabstrip_identifier
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelperManager.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelperManager.java index ff24a05..f8f973d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelperManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelperManager.java
@@ -11,7 +11,6 @@ import org.chromium.base.VisibleForTesting; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.compositor.LayerTitleCache; import org.chromium.chrome.browser.compositor.layouts.LayoutManager; import org.chromium.chrome.browser.compositor.layouts.LayoutRenderHost; @@ -163,15 +162,9 @@ Resources res = context.getResources(); mHeight = res.getDimension(R.dimen.tab_strip_height) / res.getDisplayMetrics().density; - boolean useAlternativeIncognitoStrings = - ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS); mModelSelectorButton.setAccessibilityDescription( - res.getString(useAlternativeIncognitoStrings - ? R.string.accessibility_tabstrip_btn_private_toggle_standard - : R.string.accessibility_tabstrip_btn_incognito_toggle_standard), - res.getString(useAlternativeIncognitoStrings - ? R.string.accessibility_tabstrip_btn_private_toggle_private - : R.string.accessibility_tabstrip_btn_incognito_toggle_incognito)); + res.getString(R.string.accessibility_tabstrip_btn_incognito_toggle_standard), + res.getString(R.string.accessibility_tabstrip_btn_incognito_toggle_incognito)); onContextChanged(context); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuItem.java b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuItem.java index 946ddf55..a4e1458 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuItem.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuItem.java
@@ -15,7 +15,6 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.Callback; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.DefaultBrowserInfo; import org.chromium.chrome.browser.search_engines.TemplateUrlService; import org.chromium.chrome.browser.util.FeatureUtilities; @@ -163,18 +162,6 @@ private static @StringRes int getStringID(@Item int item) { assert STRING_IDS.length == Item.NUM_ENTRIES; - if (ChromeFeatureList.isInitialized() - && ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS)) { - switch (item) { - case Item.OPEN_IN_CHROME_INCOGNITO_TAB: - return R.string.contextmenu_open_in_chrome_private_tab; - case Item.OPEN_IN_INCOGNITO_TAB: - return R.string.contextmenu_open_in_private_tab; - case Item.BROWSER_ACTIONS_OPEN_IN_INCOGNITO_TAB: - return R.string.browser_actions_open_in_private_tab; - } - } - if (FeatureUtilities.isTabGroupsAndroidEnabled() && item == Item.OPEN_IN_NEW_TAB) { return R.string.contextmenu_open_in_new_tab_group; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryManagerToolbar.java b/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryManagerToolbar.java index 6a75878..564ecbb6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryManagerToolbar.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryManagerToolbar.java
@@ -12,7 +12,6 @@ import org.chromium.base.VisibleForTesting; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.preferences.Pref; import org.chromium.chrome.browser.preferences.PrefServiceBridge; import org.chromium.chrome.browser.widget.selection.SelectableListToolbar; @@ -31,9 +30,7 @@ getMenu() .findItem(R.id.selection_mode_open_in_incognito) - .setTitle(ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS) - ? R.string.contextmenu_open_in_private_tab - : R.string.contextmenu_open_in_incognito_tab); + .setTitle(R.string.contextmenu_open_in_incognito_tab); updateMenuItemVisibility(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/incognito/IncognitoNotificationManager.java b/chrome/android/java/src/org/chromium/chrome/browser/incognito/IncognitoNotificationManager.java index 27cc222..f197f1c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/incognito/IncognitoNotificationManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/incognito/IncognitoNotificationManager.java
@@ -10,7 +10,6 @@ import org.chromium.base.ContextUtils; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.notifications.ChromeNotification; import org.chromium.chrome.browser.notifications.ChromeNotificationBuilder; import org.chromium.chrome.browser.notifications.NotificationBuilderFactory; @@ -33,10 +32,8 @@ */ public static void showIncognitoNotification() { Context context = ContextUtils.getApplicationContext(); - String actionMessage = context.getResources().getString( - ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS) - ? R.string.close_all_private_notification - : R.string.close_all_incognito_notification); + String actionMessage = + context.getResources().getString(R.string.close_all_incognito_notification); String title = context.getResources().getString(R.string.app_name); ChromeNotificationBuilder builder =
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/native_page/ContextMenuManager.java b/chrome/android/java/src/org/chromium/chrome/browser/native_page/ContextMenuManager.java index 1b3f796..373f5e0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/native_page/ContextMenuManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/native_page/ContextMenuManager.java
@@ -14,7 +14,6 @@ import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.offlinepages.OfflinePageBridge; import org.chromium.chrome.browser.util.FeatureUtilities; import org.chromium.ui.base.WindowAndroid.OnCloseContextMenuListener; @@ -256,10 +255,7 @@ ? R.string.contextmenu_open_in_new_tab_group : R.string.contextmenu_open_in_new_tab; case ContextMenuItemId.OPEN_IN_INCOGNITO_TAB: - return ChromeFeatureList.isInitialized() - && ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS) - ? R.string.contextmenu_open_in_private_tab - : R.string.contextmenu_open_in_incognito_tab; + return R.string.contextmenu_open_in_incognito_tab; case ContextMenuItemId.OPEN_IN_NEW_WINDOW: return R.string.contextmenu_open_in_other_window; case ContextMenuItemId.SAVE_FOR_OFFLINE:
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPage.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPage.java index e43af6ec..d54ef2fd 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPage.java
@@ -16,7 +16,6 @@ import org.chromium.base.VisibleForTesting; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.UrlConstants; import org.chromium.chrome.browser.compositor.layouts.content.InvalidationAwareThumbnailProvider; import org.chromium.chrome.browser.help.HelpAndFeedback; @@ -97,12 +96,9 @@ mIncognitoNewTabPageView.initialize(mIncognitoNewTabPageManager); mIncognitoNewTabPageView.setNavigationDelegate(host.createHistoryNavigationDelegate()); - boolean useAlternateIncognitoStrings = - ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS); TextView newTabIncognitoHeader = (TextView) mIncognitoNewTabPageView.findViewById(R.id.new_tab_incognito_title); - newTabIncognitoHeader.setText(useAlternateIncognitoStrings ? R.string.new_tab_private_title - : R.string.new_tab_otr_title); + newTabIncognitoHeader.setText(R.string.new_tab_otr_title); } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPageView.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPageView.java index 361da50..ed0049c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPageView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoNewTabPageView.java
@@ -23,7 +23,6 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.gesturenav.HistoryNavigationLayout; import org.chromium.chrome.browser.util.ViewUtils; import org.chromium.ui.text.NoUnderlineClickableSpan; @@ -82,10 +81,8 @@ mScrollView = (NewTabPageScrollView) findViewById(R.id.ntp_scrollview); mScrollView.setBackgroundColor( ApiCompatibilityUtils.getColor(getResources(), R.color.ntp_bg_incognito)); - setContentDescription(getResources().getText( - ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS) - ? R.string.accessibility_new_private_tab_page - : R.string.accessibility_new_incognito_tab_page)); + setContentDescription( + getResources().getText(R.string.accessibility_new_incognito_tab_page)); // FOCUS_BEFORE_DESCENDANTS is needed to support keyboard shortcuts. Otherwise, pressing // any shortcut causes the UrlBar to be focused. See ViewRootImpl.leaveTouchMode().
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteController.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteController.java index 69b91a6..ee91760 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteController.java
@@ -97,15 +97,14 @@ * * @param profile The profile to use for starting the AutocompleteController * @param url The URL of the current tab, used to suggest query refinements. + * @param pageClassification The page classification of the current tab. * @param text The text to query autocomplete suggestions for. * @param cursorPosition The position of the cursor within the text. Set to -1 if the cursor is * not focused on the text. * @param preventInlineAutocomplete Whether autocomplete suggestions should be prevented. - * @param focusedFromFakebox Whether the user entered the omnibox by tapping the fakebox on the - * native NTP. This should be false on all other pages. */ - public void start(Profile profile, String url, String text, int cursorPosition, - boolean preventInlineAutocomplete, boolean focusedFromFakebox) { + public void start(Profile profile, String url, int pageClassification, String text, + int cursorPosition, boolean preventInlineAutocomplete) { // crbug.com/764749 Log.w(TAG, "starting autocomplete controller..[%b][%b]", profile == null, TextUtils.isEmpty(url)); @@ -115,7 +114,7 @@ // Initializing the native counterpart might still fail. if (mNativeAutocompleteControllerAndroid != 0) { nativeStart(mNativeAutocompleteControllerAndroid, text, cursorPosition, null, url, - preventInlineAutocomplete, false, false, true, focusedFromFakebox); + pageClassification, preventInlineAutocomplete, false, false, true); mWaitingForSuggestionsToCache = false; } } @@ -148,12 +147,11 @@ * @param profile The profile to use for starting the AutocompleteController. * @param omniboxText The text displayed in the omnibox. * @param url The url of the currently loaded web page. + * @param pageClassification The page classification of the current tab. * @param title The title of the currently loaded web page. - * @param focusedFromFakebox Whether the user entered the omnibox by tapping the fakebox on the - * native NTP. This should be false on all other pages. */ - public void startZeroSuggest(Profile profile, String omniboxText, String url, String title, - boolean focusedFromFakebox) { + public void startZeroSuggest( + Profile profile, String omniboxText, String url, int pageClassification, String title) { if (profile == null || TextUtils.isEmpty(url)) return; if (!NewTabPage.isNTPUrl(url)) { @@ -164,8 +162,8 @@ mNativeAutocompleteControllerAndroid = nativeInit(profile); if (mNativeAutocompleteControllerAndroid != 0) { if (mUseCachedZeroSuggestResults) mWaitingForSuggestionsToCache = true; - nativeOnOmniboxFocused(mNativeAutocompleteControllerAndroid, omniboxText, url, title, - focusedFromFakebox); + nativeOnOmniboxFocused(mNativeAutocompleteControllerAndroid, omniboxText, url, + pageClassification, title); } } @@ -252,21 +250,20 @@ * @param selectedIndex The index of the suggestion that was selected. * @param type The type of the selected suggestion. * @param currentPageUrl The URL of the current page. - * @param focusedFromFakebox Whether the user entered the omnibox by tapping the fakebox on the - * native NTP. This should be false on all other pages. + * @param pageClassification The page classification of the current tab. * @param elapsedTimeSinceModified The number of ms that passed between the user first * modifying text in the omnibox and selecting a suggestion. * @param completedLength The length of the default match's inline autocompletion if any. * @param webContents The web contents for the tab where the selected suggestion will be shown. */ public void onSuggestionSelected(int selectedIndex, int hashCode, int type, - String currentPageUrl, boolean focusedFromFakebox, long elapsedTimeSinceModified, + String currentPageUrl, int pageClassification, long elapsedTimeSinceModified, int completedLength, WebContents webContents) { assert mNativeAutocompleteControllerAndroid != 0; // Don't natively log voice suggestion results as we add them in Java. if (type == OmniboxSuggestionType.VOICE_SUGGEST) return; nativeOnSuggestionSelected(mNativeAutocompleteControllerAndroid, selectedIndex, hashCode, - currentPageUrl, focusedFromFakebox, elapsedTimeSinceModified, completedLength, + currentPageUrl, pageClassification, elapsedTimeSinceModified, completedLength, webContents); } @@ -349,19 +346,18 @@ @VisibleForTesting protected native long nativeInit(Profile profile); private native void nativeStart(long nativeAutocompleteControllerAndroid, String text, - int cursorPosition, String desiredTld, String currentUrl, + int cursorPosition, String desiredTld, String currentUrl, int pageClassification, boolean preventInlineAutocomplete, boolean preferKeyword, - boolean allowExactKeywordMatch, boolean wantAsynchronousMatches, - boolean focusedFromFakebox); + boolean allowExactKeywordMatch, boolean wantAsynchronousMatches); private native OmniboxSuggestion nativeClassify( long nativeAutocompleteControllerAndroid, String text, boolean focusedFromFakebox); private native void nativeStop(long nativeAutocompleteControllerAndroid, boolean clearResults); private native void nativeResetSession(long nativeAutocompleteControllerAndroid); private native void nativeOnSuggestionSelected(long nativeAutocompleteControllerAndroid, - int selectedIndex, int hashCode, String currentPageUrl, boolean focusedFromFakebox, + int selectedIndex, int hashCode, String currentPageUrl, int pageClassification, long elapsedTimeSinceModified, int completedLength, WebContents webContents); private native void nativeOnOmniboxFocused(long nativeAutocompleteControllerAndroid, - String omniboxText, String currentUrl, String currentTitle, boolean focusedFromFakebox); + String omniboxText, String currentUrl, int pageClassification, String currentTitle); private native void nativeDeleteSuggestion( long nativeAutocompleteControllerAndroid, int selectedIndex, int hashCode); private native String nativeUpdateMatchDestinationURLWithQueryFormulationTime(
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteMediator.java index 4ad9d8e..acf3ee44 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteMediator.java
@@ -693,8 +693,10 @@ // position. Hence, there's no need to check for -1 here explicitly. cursorPosition = mUrlBarEditingTextProvider.getSelectionStart(); } - mAutocomplete.start(profile, mDataProvider.getCurrentUrl(), textWithoutAutocomplete, - cursorPosition, preventAutocomplete, mDelegate.didFocusUrlFromFakebox()); + int pageClassification = + mDataProvider.getPageClassification(mDelegate.didFocusUrlFromFakebox()); + mAutocomplete.start(profile, mDataProvider.getCurrentUrl(), pageClassification, + textWithoutAutocomplete, cursorPosition, preventAutocomplete); }; if (mNativeInitialized) { mHandler.postDelayed(mRequestSuggestions, OMNIBOX_SUGGESTION_START_DELAY_MS); @@ -860,8 +862,10 @@ if (!shouldSkipNativeLog) { int autocompleteLength = mUrlBarEditingTextProvider.getTextWithAutocomplete().length() - mUrlBarEditingTextProvider.getTextWithoutAutocomplete().length(); + int pageClassification = + mDataProvider.getPageClassification(mDelegate.didFocusUrlFromFakebox()); mAutocomplete.onSuggestionSelected(matchPosition, suggestion.hashCode(), type, - currentPageUrl, mDelegate.didFocusUrlFromFakebox(), elapsedTimeSinceModified, + currentPageUrl, pageClassification, elapsedTimeSinceModified, autocompleteLength, webContents); } if (((transition & PageTransition.CORE_MASK) == PageTransition.TYPED) @@ -900,10 +904,11 @@ mHasStartedNewOmniboxEditSession = false; mNewOmniboxEditSessionTimestamp = -1; if (mNativeInitialized && mDelegate.isUrlBarFocused() && mDataProvider.hasTab()) { + int pageClassification = + mDataProvider.getPageClassification(mDelegate.didFocusUrlFromFakebox()); mAutocomplete.startZeroSuggest(mDataProvider.getProfile(), mUrlBarEditingTextProvider.getTextWithAutocomplete(), - mDataProvider.getCurrentUrl(), mDataProvider.getTitle(), - mDelegate.didFocusUrlFromFakebox()); + mDataProvider.getCurrentUrl(), pageClassification, mDataProvider.getTitle()); } } @@ -969,8 +974,8 @@ void startAutocompleteForQuery(String query) { stopAutocomplete(false); if (mDataProvider.hasTab()) { - mAutocomplete.start(mDataProvider.getProfile(), mDataProvider.getCurrentUrl(), query, - -1, false, false); + mAutocomplete.start(mDataProvider.getProfile(), mDataProvider.getCurrentUrl(), + mDataProvider.getPageClassification(false), query, -1, false); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/AndroidPaymentApp.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/AndroidPaymentApp.java index 6c88820b..ab971c8 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/AndroidPaymentApp.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/AndroidPaymentApp.java
@@ -25,7 +25,6 @@ import org.chromium.base.ThreadUtils; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.components.url_formatter.UrlFormatter; import org.chromium.content_public.browser.WebContents; import org.chromium.payments.mojom.PaymentCurrencyAmount; @@ -296,9 +295,7 @@ new UiUtils.CompatibleAlertDialogBuilder(activity, R.style.Theme_Chromium_AlertDialog) .setTitle(R.string.external_app_leave_incognito_warning_title) - .setMessage(ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS) - ? R.string.external_payment_app_leave_private_warning - : R.string.external_payment_app_leave_incognito_warning) + .setMessage(R.string.external_payment_app_leave_incognito_warning) .setPositiveButton(R.string.ok, (OnClickListener) (dialog, which) -> launchPaymentApp(id, merchantName, schemelessOrigin,
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/AboutChromePreferenceOSVersion.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/AboutChromePreferenceOSVersion.java index ba5c625..b66357f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/AboutChromePreferenceOSVersion.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/AboutChromePreferenceOSVersion.java
@@ -5,7 +5,8 @@ package org.chromium.chrome.browser.preferences; import android.content.Context; -import android.preference.Preference; +import android.support.v7.preference.Preference; +import android.support.v7.preference.PreferenceViewHolder; import android.util.AttributeSet; import android.view.View; @@ -26,11 +27,11 @@ } @Override - protected void onBindView(View view) { - super.onBindView(view); + public void onBindViewHolder(PreferenceViewHolder holder) { + super.onBindViewHolder(holder); // Show additional information only if the OS version is not supported. if (VersionNumberGetter.isCurrentOsVersionSupported()) return; - view.findViewById(R.id.os_deprecation_warning).setVisibility(View.VISIBLE); + holder.findViewById(R.id.os_deprecation_warning).setVisibility(View.VISIBLE); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/AboutChromePreferences.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/AboutChromePreferences.java index f19d3c9..9d26f41 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/AboutChromePreferences.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/AboutChromePreferences.java
@@ -8,8 +8,8 @@ import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; -import android.preference.Preference; -import android.preference.PreferenceFragment; +import android.support.v7.preference.Preference; +import android.support.v7.preference.PreferenceFragmentCompat; import android.text.format.DateUtils; import org.chromium.chrome.R; @@ -24,7 +24,7 @@ * Settings fragment that displays information about Chrome. */ public class AboutChromePreferences - extends PreferenceFragment implements Preference.OnPreferenceClickListener { + extends PreferenceFragmentCompat implements Preference.OnPreferenceClickListener { private static final int TAPS_FOR_DEVELOPER_PREFERENCES = 7; private static final String PREF_APPLICATION_VERSION = "application_version"; @@ -46,8 +46,7 @@ private Toast mToast; @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + public void onCreatePreferences(Bundle bundle, String s) { getActivity().setTitle(R.string.prefs_about_chrome); PreferenceUtils.addPreferencesFromResource(this, R.xml.about_chrome_preferences);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/PreferenceUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/PreferenceUtils.java index 966b09b..ed45a7a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/PreferenceUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/PreferenceUtils.java
@@ -14,6 +14,7 @@ import android.support.annotation.Nullable; import android.support.annotation.XmlRes; import android.support.v7.content.res.AppCompatResources; +import android.support.v7.preference.PreferenceFragmentCompat; import android.support.v7.widget.ActionMenuView; import android.view.View; import android.view.ViewGroup; @@ -31,7 +32,10 @@ * A helper that is used to load preferences from XML resources without causing a * StrictModeViolation. See http://crbug.com/692125. * - * @param preferenceFragment A PreferenceFragment. + * TODO(crbug.com/967022): Once all {@link PreferenceFragment}s are migrated to the Support + * Library {@link PreferenceFragmentCompat}s, remove this method in favor of the below method. + * + * @param preferenceFragment A Framework {@link PreferenceFragment}. * @param preferencesResId The id of the XML resource to add to the PreferenceFragment. */ public static void addPreferencesFromResource( @@ -45,6 +49,23 @@ } /** + * A helper that is used to load preferences from XML resources without causing a + * StrictModeViolation. See http://crbug.com/692125. + * + * @param preferenceFragment A Support Library {@link PreferenceFragmentCompat}. + * @param preferencesResId The id of the XML resource to add to the PreferenceFragment. + */ + public static void addPreferencesFromResource( + PreferenceFragmentCompat preferenceFragment, @XmlRes int preferencesResId) { + StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); + try { + preferenceFragment.addPreferencesFromResource(preferencesResId); + } finally { + StrictMode.setThreadPolicy(oldPolicy); + } + } + + /** * Returns a view tree observer to show the shadow if and only if the view is scrolled. * @param view The view whose scroll will be detected to determine the shadow's visibility. * @param shadow The shadow to show/hide.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/Preferences.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/Preferences.java index 69a847d..0114ed0e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/Preferences.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/Preferences.java
@@ -21,6 +21,8 @@ import android.preference.PreferenceFragment; import android.preference.PreferenceFragment.OnPreferenceStartFragmentCallback; import android.support.graphics.drawable.VectorDrawableCompat; +import android.support.v7.preference.PreferenceFragmentCompat; +import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Menu; import android.view.MenuItem; @@ -52,8 +54,9 @@ * 2) an OnScrollChangedListener to the main content's view's view tree observer via * PreferenceUtils.getShowShadowOnScrollListener(...). */ -public class Preferences - extends ChromeBaseAppCompatActivity implements OnPreferenceStartFragmentCallback { +public class Preferences extends ChromeBaseAppCompatActivity + implements OnPreferenceStartFragmentCallback, + PreferenceFragmentCompat.OnPreferenceStartFragmentCallback { /** * Preference fragments may implement this interface to intercept "Back" button taps in this * activity. @@ -115,10 +118,22 @@ // recreated and super.onCreate() has already recreated the fragment. if (savedInstanceState == null) { if (initialFragment == null) initialFragment = MainPreferences.class.getName(); - Fragment fragment = Fragment.instantiate(this, initialFragment, initialArguments); - getFragmentManager().beginTransaction() - .replace(android.R.id.content, fragment) - .commit(); + + if (isCompat(initialFragment)) { + android.support.v4.app.Fragment fragment = + android.support.v4.app.Fragment.instantiate( + this, initialFragment, initialArguments); + getSupportFragmentManager() + .beginTransaction() + .replace(android.R.id.content, fragment) + .commit(); + } else { + Fragment fragment = Fragment.instantiate(this, initialFragment, initialArguments); + getFragmentManager() + .beginTransaction() + .replace(android.R.id.content, fragment) + .commit(); + } } if (ApiCompatibilityUtils.checkPermission( @@ -130,18 +145,45 @@ if (nfcAdapter != null) nfcAdapter.setNdefPushMessage(null, this); } - Resources res = getResources(); ApiCompatibilityUtils.setTaskDescription(this, res.getString(R.string.app_name), BitmapFactory.decodeResource(res, R.mipmap.app_icon), ApiCompatibilityUtils.getColor(res, R.color.default_primary_color)); } + /** + * Given a Fragment class name (as a string), determine whether it is a Support Library Fragment + * class, as opposed to a Framework Fragment. + * + * TODO(crbug.com/967022): Remove this method once all fragments are migrated to the Support + * Library. + * + * @param fragmentClass The fully qualified class name of a Fragment. + * @return Whether the class represents a Support Library Fragment. + */ + private boolean isCompat(String fragmentClass) { + try { + return android.support.v4.app.Fragment.class.isAssignableFrom( + Class.forName(fragmentClass)); + } catch (ClassNotFoundException e) { + return false; + } + } + // OnPreferenceStartFragmentCallback: @Override - public boolean onPreferenceStartFragment(PreferenceFragment preferenceFragment, - Preference preference) { + // TODO(crbug.com/967022): Remove this method once all fragments are migrated to the Support + // Library. + public boolean onPreferenceStartFragment( + PreferenceFragment preferenceFragment, Preference preference) { + startFragment(preference.getFragment(), preference.getExtras()); + return true; + } + + @Override + public boolean onPreferenceStartFragment( + PreferenceFragmentCompat caller, android.support.v7.preference.Preference preference) { startFragment(preference.getFragment(), preference.getExtras()); return true; } @@ -164,16 +206,20 @@ public void onAttachedToWindow() { super.onAttachedToWindow(); Fragment fragment = getMainFragment(); + if (fragment == null) { + onAttachedToWindowCompat(); + return; + } + if (fragment.getView() == null + || fragment.getView().findViewById(android.R.id.list) == null) { + return; + } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (fragment instanceof PreferenceFragment && fragment.getView() != null) { // Set list view padding to 0 so dividers are the full width of the screen. fragment.getView().findViewById(android.R.id.list).setPadding(0, 0, 0, 0); } } - if (fragment == null || fragment.getView() == null - || fragment.getView().findViewById(android.R.id.list) == null) { - return; - } View contentView = fragment.getActivity().findViewById(android.R.id.content); if (contentView == null || !(contentView instanceof FrameLayout)) { return; @@ -187,6 +233,36 @@ listView, inflatedView.findViewById(R.id.shadow))); } + /** + * This method performs similar actions to {@link #onAttachedToWindow()}, but modified for the + * case where the main fragment is a Support Library fragment. + * + * Differences include: + * * List ID reference is R.id.list instead of android.R.id.list. + * * The {@link ListView} is now a {@link RecyclerView}. + * + * TODO(crbug.com/967022): Once all fragments are migrated to the Support Library, replace + * {@link #onAttachedToWindow()} with this method body. + */ + public void onAttachedToWindowCompat() { + super.onAttachedToWindow(); + android.support.v4.app.Fragment fragment = getMainFragmentCompat(); + if (fragment == null || fragment.getView() == null + || fragment.getView().findViewById(R.id.list) == null) { + return; + } + View contentView = fragment.getActivity().findViewById(android.R.id.content); + if (contentView == null || !(contentView instanceof FrameLayout)) { + return; + } + View inflatedView = View.inflate(getApplicationContext(), + R.layout.preferences_action_bar_shadow, (ViewGroup) contentView); + RecyclerView recyclerView = fragment.getView().findViewById(R.id.list); + recyclerView.getViewTreeObserver().addOnScrollChangedListener( + PreferenceUtils.getShowShadowOnScrollListener( + recyclerView, inflatedView.findViewById(R.id.shadow))); + } + @Override protected void onResume() { super.onResume(); @@ -229,13 +305,29 @@ } /** - * Returns the fragment showing as this activity's main content, typically a PreferenceFragment. - * This does not include DialogFragments or other Fragments shown on top of the main content. + * Returns the fragment showing as this activity's main content, typically a {@link + * PreferenceFragment}. This does not include {@link android.app.DialogFragment}s or other + * {@link Fragment}s shown on top of the main content. + * + * This method only returns Framework {@link Fragment}s. If the main fragment is a Support + * Library fragment (of type {@link android.support.v4.app.Fragment}), this method returns null. + * + * TODO(crbug.com/967022): Remove this method once all fragments are migrated to the Support + * Library. */ private Fragment getMainFragment() { return getFragmentManager().findFragmentById(android.R.id.content); } + /** + * This method should be called to retrieve the activity's main content if {@link + * #getMainFragment()} returned null, which may indicate that the main fragment is a Support + * Library fragment. + */ + private android.support.v4.app.Fragment getMainFragmentCompat() { + return getSupportFragmentManager().findFragmentById(android.R.id.content); + } + @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/SadTab.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/SadTab.java index 6b7385d..31a1f55 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/SadTab.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/SadTab.java
@@ -21,7 +21,6 @@ import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.help.HelpAndFeedback; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.components.ui_metrics.SadTabEvent; @@ -255,10 +254,7 @@ SpannableStringBuilder spannableString = new SpannableStringBuilder(); if (!isIncognito) { spannableString - .append(generateBulletedString(context, - ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS) - ? R.string.sad_tab_reload_private - : R.string.sad_tab_reload_incognito)) + .append(generateBulletedString(context, R.string.sad_tab_reload_incognito)) .append("\n"); } spannableString
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/IncognitoToggleTabLayout.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/IncognitoToggleTabLayout.java index 8172c77..5506bab 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/IncognitoToggleTabLayout.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/IncognitoToggleTabLayout.java
@@ -13,7 +13,6 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.tabmodel.EmptyTabModelSelectorObserver; import org.chromium.chrome.browser.tabmodel.TabModel; import org.chromium.chrome.browser.tabmodel.TabModelSelector; @@ -62,10 +61,8 @@ getResources().getString(R.string.accessibility_tab_switcher_standard_stack)); mIncognitoButtonIcon = new ChromeImageView(getContext()); mIncognitoButtonIcon.setImageResource(R.drawable.incognito_small); - mIncognitoButtonIcon.setContentDescription(getResources().getString( - ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS) - ? R.string.accessibility_tab_switcher_private_stack - : R.string.accessibility_tab_switcher_incognito_stack)); + mIncognitoButtonIcon.setContentDescription( + getResources().getString(R.string.accessibility_tab_switcher_incognito_stack)); mStandardButton = newTab().setCustomView(mStandardButtonIcon); addTab(mStandardButton); @@ -158,9 +155,7 @@ mTabModelSelector.selectModel(incognitoSelected); final int stackAnnouncementId = incognitoSelected - ? (ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS) - ? R.string.accessibility_tab_switcher_private_stack_selected - : R.string.accessibility_tab_switcher_incognito_stack_selected) + ? R.string.accessibility_tab_switcher_incognito_stack_selected : R.string.accessibility_tab_switcher_standard_stack_selected; announceForAccessibility(getResources().getString(stackAnnouncementId)); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/LocationBarModel.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/LocationBarModel.java index ebcb26e..542879d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/LocationBarModel.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/LocationBarModel.java
@@ -352,6 +352,12 @@ } @Override + public int getPageClassification(boolean isFocusedFromFakebox) { + if (mNativeLocationBarModelAndroid == 0) return 0; + return nativeGetPageClassification(mNativeLocationBarModelAndroid, isFocusedFromFakebox); + } + + @Override public int getSecurityIconResource(boolean isTablet) { // If we're showing a query in the omnibox, and the security level is high enough to show // the search icon, return that instead of the security icon. @@ -486,4 +492,6 @@ private native String nativeGetFormattedFullURL(long nativeLocationBarModelAndroid); private native String nativeGetURLForDisplay(long nativeLocationBarModelAndroid); private native String nativeGetDisplaySearchTerms(long nativeLocationBarModelAndroid); + private native int nativeGetPageClassification( + long nativeLocationBarModelAndroid, boolean isFocusedFromFakebox); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/NewTabButton.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/NewTabButton.java index f4b6622..c7ef55a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/NewTabButton.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/NewTabButton.java
@@ -52,9 +52,7 @@ @Override public boolean onLongClick(View v) { CharSequence description = getResources().getString(mIsIncognito - ? (ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS) - ? org.chromium.chrome.R.string.button_new_private_tab - : org.chromium.chrome.R.string.button_new_incognito_tab) + ? org.chromium.chrome.R.string.button_new_incognito_tab : org.chromium.chrome.R.string.button_new_tab); return AccessibilityUtil.showAccessibilityToast(getContext(), v, description); } @@ -70,14 +68,8 @@ mIsIncognito = isIncognito; @StringRes - int resId; - if (ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS)) { - resId = mIsIncognito ? R.string.accessibility_toolbar_btn_new_private_tab + int resId = mIsIncognito ? R.string.accessibility_toolbar_btn_new_incognito_tab : R.string.accessibility_toolbar_btn_new_tab; - } else { - resId = mIsIncognito ? R.string.accessibility_toolbar_btn_new_incognito_tab - : R.string.accessibility_toolbar_btn_new_tab; - } setContentDescription(getResources().getText(resId)); updateDrawableTint();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarDataProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarDataProvider.java index 4059509..623becb 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarDataProvider.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarDataProvider.java
@@ -102,6 +102,14 @@ int getSecurityLevel(); /** + * @param isFocusedFromFakebox If the omnibox focus originated from the fakebox. + * @return The current page classification. + */ + default int getPageClassification(boolean isFocusedFromFakebox) { + return 0; + } + + /** * @return The resource ID of the icon that should be displayed or 0 if no icon should be shown. */ @DrawableRes
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomToolbarNewTabButton.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomToolbarNewTabButton.java index 4be16cb..f7757212 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomToolbarNewTabButton.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/BottomToolbarNewTabButton.java
@@ -18,7 +18,6 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ThemeColorProvider; import org.chromium.chrome.browser.ThemeColorProvider.ThemeColorObserver; import org.chromium.chrome.browser.ThemeColorProvider.TintObserver; @@ -105,14 +104,8 @@ @Override public void onIncognitoStateChanged(boolean isIncognito) { @StringRes - int resId; - if (ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS)) { - resId = isIncognito ? R.string.accessibility_toolbar_btn_new_private_tab + int resId = isIncognito ? R.string.accessibility_toolbar_btn_new_incognito_tab : R.string.accessibility_toolbar_btn_new_tab; - } else { - resId = isIncognito ? R.string.accessibility_toolbar_btn_new_incognito_tab - : R.string.accessibility_toolbar_btn_new_tab; - } setContentDescription(getResources().getText(resId)); updateBackground(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/CloseAllTabsButton.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/CloseAllTabsButton.java index 64e17f2..e83158d5 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/CloseAllTabsButton.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/CloseAllTabsButton.java
@@ -11,7 +11,6 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ThemeColorProvider; import org.chromium.chrome.browser.ThemeColorProvider.TintObserver; import org.chromium.chrome.browser.toolbar.IncognitoStateProvider; @@ -74,14 +73,8 @@ @Override public void onIncognitoStateChanged(boolean isIncognito) { @StringRes - int resId; - if (ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS)) { - resId = isIncognito ? R.string.accessibility_toolbar_btn_close_all_private_tabs + int resId = isIncognito ? R.string.accessibility_toolbar_btn_close_all_incognito_tabs : R.string.accessibility_toolbar_btn_close_all_tabs; - } else { - resId = isIncognito ? R.string.accessibility_toolbar_btn_close_all_incognito_tabs - : R.string.accessibility_toolbar_btn_close_all_tabs; - } setContentDescription(getResources().getText(resId)); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/accessibility/AccessibilityTabModelWrapper.java b/chrome/android/java/src/org/chromium/chrome/browser/widget/accessibility/AccessibilityTabModelWrapper.java index c498f64..e33be68 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/accessibility/AccessibilityTabModelWrapper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/widget/accessibility/AccessibilityTabModelWrapper.java
@@ -17,7 +17,6 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.VisibleForTesting; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabmodel.EmptyTabModelSelectorObserver; import org.chromium.chrome.browser.tabmodel.TabModelSelector; @@ -115,10 +114,8 @@ mIncognitoButtonIcon = new ChromeImageView(getContext()); mIncognitoButtonIcon.setImageResource(R.drawable.btn_incognito_tabs); mIncognitoButtonIcon.setScaleY(-1.0f); - mIncognitoButtonIcon.setContentDescription(getResources().getString( - ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS) - ? R.string.accessibility_tab_switcher_private_stack - : R.string.accessibility_tab_switcher_incognito_stack)); + mIncognitoButtonIcon.setContentDescription( + getResources().getString(R.string.accessibility_tab_switcher_incognito_stack)); setDividerDrawable(null); ((ListView) findViewById(R.id.list_view)).setDivider(null); @@ -200,11 +197,9 @@ mAccessibilityView.setContentDescription(incognitoSelected ? getContext().getString( - ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS) - ? R.string.accessibility_tab_switcher_private_stack - : R.string.accessibility_tab_switcher_incognito_stack) + R.string.accessibility_tab_switcher_incognito_stack) : getContext().getString( - R.string.accessibility_tab_switcher_standard_stack)); + R.string.accessibility_tab_switcher_standard_stack)); getAdapter().setTabModel(mTabModelSelector.getModel(incognitoSelected)); } @@ -228,9 +223,7 @@ setStateBasedOnModel(); int stackAnnouncementId = incognitoSelected - ? (ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS) - ? R.string.accessibility_tab_switcher_private_stack_selected - : R.string.accessibility_tab_switcher_incognito_stack_selected) + ? R.string.accessibility_tab_switcher_incognito_stack_selected : R.string.accessibility_tab_switcher_standard_stack_selected; AccessibilityTabModelWrapper.this.announceForAccessibility( getResources().getString(stackAnnouncementId));
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/incognitotoggle/IncognitoToggleButton.java b/chrome/android/java/src/org/chromium/chrome/browser/widget/incognitotoggle/IncognitoToggleButton.java index 01bd279..bd31f94f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/incognitotoggle/IncognitoToggleButton.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/widget/incognitotoggle/IncognitoToggleButton.java
@@ -12,7 +12,6 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.tabmodel.EmptyTabModelSelectorObserver; import org.chromium.chrome.browser.tabmodel.TabModel; import org.chromium.chrome.browser.tabmodel.TabModelSelector; @@ -83,16 +82,10 @@ private void updateButtonResource() { if (mTabModelSelector == null || mTabModelSelector.getCurrentModel() == null) return; - boolean useAlternativeIncognitoStrings = - ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS); @StringRes int resId = mTabModelSelector.isIncognitoSelected() - ? (useAlternativeIncognitoStrings - ? R.string.accessibility_tabstrip_btn_private_toggle_private - : R.string.accessibility_tabstrip_btn_incognito_toggle_incognito) - : (useAlternativeIncognitoStrings - ? R.string.accessibility_tabstrip_btn_private_toggle_standard - : R.string.accessibility_tabstrip_btn_incognito_toggle_standard); + ? R.string.accessibility_tabstrip_btn_incognito_toggle_incognito + : R.string.accessibility_tabstrip_btn_incognito_toggle_standard; setContentDescription(getContext().getString(resId)); setImage(mTabModelSelector.isIncognitoSelected()); }
diff --git a/chrome/android/java/strings/android_chrome_strings.grd b/chrome/android/java/strings/android_chrome_strings.grd index fd8c52c7..bb08c7d 100644 --- a/chrome/android/java/strings/android_chrome_strings.grd +++ b/chrome/android/java/strings/android_chrome_strings.grd
@@ -1893,18 +1893,12 @@ <message name="IDS_ACCESSIBILITY_TAB_SWITCHER_INCOGNITO_STACK" desc="Content description for the incognito stack selection 'button'."> Incognito tabs </message> - <message name="IDS_ACCESSIBILITY_TAB_SWITCHER_PRIVATE_STACK" desc="Content description for the private stack selection 'button'."> - Private tabs - </message> <message name="IDS_ACCESSIBILITY_TAB_SWITCHER_STANDARD_STACK_SELECTED" desc="Announcement when the standard tab stack is selected."> Switched to standard tabs </message> <message name="IDS_ACCESSIBILITY_TAB_SWITCHER_INCOGNITO_STACK_SELECTED" desc="Announcement when the incognito tab stack is selected."> Switched to incognito tabs </message> - <message name="IDS_ACCESSIBILITY_TAB_SWITCHER_PRIVATE_STACK_SELECTED" desc="Announcement when the private tab stack is selected."> - Switched to private tabs - </message> <message name="IDS_ACCESSIBILITY_TAB_SWITCHER_UNDO_TAB_CLOSED" desc="Content description for the undo tab closed 'button."> Reopen closed tab </message> @@ -2124,9 +2118,6 @@ <message name="IDS_CONTEXTMENU_OPEN_IN_INCOGNITO_TAB" desc="Context sensitive menu item to open the selected link in a new incognito tab. [CHAR-LIMIT=30]"> Open in incognito tab </message> - <message name="IDS_CONTEXTMENU_OPEN_IN_PRIVATE_TAB" desc="Context sensitive menu item to open the selected link in a new private tab. [CHAR-LIMIT=30]"> - Open in private tab - </message> <message name="IDS_CONTEXTMENU_CALL" desc="Context sensitive menu for calling phone number. [CHAR-LIMIT=30]"> Call </message> @@ -2181,9 +2172,6 @@ <message name="IDS_CONTEXTMENU_OPEN_IN_CHROME_INCOGNITO_TAB" desc="Context sensitive menu item to open the selected link in a Chrome incognito tab from Chrome Custom Tab. [CHAR-LIMIT=30]"> Open in incognito tab </message> - <message name="IDS_CONTEXTMENU_OPEN_IN_CHROME_PRIVATE_TAB" desc="Context sensitive menu item to open the selected link in a Chrome private tab from Chrome Custom Tab. [CHAR-LIMIT=30]"> - Open in private tab - </message> <message name="IDS_CONTEXTMENU_OPEN_IN_EPHEMERAL_TAB" desc="Context-sensitive menu item to open a quick preview of the selected linked page. Note that 'preview' is a verb, not a noun. We're also labeling it *New* to draw attention to it when first released. The selected link will open in an overlay panel on top of the current tab which will go away easily too. [CHAR-LIMIT=30]"> Preview page <ph name="BEGIN_NEW"><new></ph>New<ph name="END_NEW"></new></ph> </message> @@ -2200,9 +2188,6 @@ <message name="IDS_BROWSER_ACTIONS_OPEN_IN_INCOGNITO_TAB" desc="Browser Actions menu item to open the selected link in a Chrome incognito tab. [CHAR-LIMIT=30]"> Open in incognito tab </message> - <message name="IDS_BROWSER_ACTIONS_OPEN_IN_PRIVATE_TAB" desc="Browser Actions menu item to open the selected link in a Chrome private tab. [CHAR-LIMIT=30]"> - Open in private tab - </message> <message name="IDS_BROWSER_ACTIONS_SAVE_LINK_AS" desc="Browser Actions menu item to download the page of the selected link. [CHAR-LIMIT=30]"> Download link </message> @@ -2683,9 +2668,6 @@ <message name="IDS_CLOSE_ALL_INCOGNITO_NOTIFICATION" desc="Message on the notification that closes all incognito tabs in document mode"> Close all incognito tabs </message> - <message name="IDS_CLOSE_ALL_PRIVATE_NOTIFICATION" desc="Message on the notification that closes all private tabs in document mode"> - Close all private tabs - </message> <!-- Autofill/Wallet integration prompt --> <message name="IDS_CARD_UNMASK_INPUT_HINT" desc="Hint text for an input field containing the user's credit card CVC (card verification code)."> @@ -2984,9 +2966,6 @@ <message name="IDS_BUTTON_NEW_INCOGNITO_TAB" desc="Tooltip for the button to open a new incognito browser tab."> New incognito tab </message> - <message name="IDS_BUTTON_NEW_PRIVATE_TAB" desc="Tooltip for the button to open a new private browser tab."> - New private tab - </message> <message name="IDS_CUSTOM_TAB_AMP_PUBLISHER_URL" desc="Text shown in a Custom Tab toolbar for a web page that is hosted by the Google content delivery network but was originally published by someone else."> From <ph name="PUBLISHER_ORIGIN"><pub>%1$s</pub><ex>example.com</ex></ph> – <ph name="BEGIN_DEEMPHASIZED"><bg></ph>delivered by Google<ph name="END_DEEMPHASIZED"></bg></ph> </message> @@ -3043,9 +3022,6 @@ <message name="IDS_MENU_NEW_INCOGNITO_TAB" desc="Menu item for opening a new incognito tab that facilitates pseudononymous browsing. [CHAR-LIMIT=27]" meaning="Android menu"> New incognito tab </message> - <message name="IDS_MENU_NEW_PRIVATE_TAB" desc="Menu item for opening a new private tab that facilitates pseudononymous browsing. [CHAR-LIMIT=27]" meaning="Android menu"> - New private tab - </message> <message name="IDS_MENU_BOOKMARKS" desc="Menu item for opening the bookmarks page that contains all the user's bookmarks. [CHAR-LIMIT=27]"> Bookmarks </message> @@ -3082,9 +3058,6 @@ <message name="IDS_MENU_CLOSE_ALL_INCOGNITO_TABS" desc="Menu item for closing all open incognito tabs. [CHAR-LIMIT=27]"> Close incognito tabs </message> - <message name="IDS_MENU_CLOSE_ALL_PRIVATE_TABS" desc="Menu item for closing all open private tabs. [CHAR-LIMIT=27]"> - Close private tabs - </message> <!-- Bookmarks strings --> <message name="IDS_BOOKMARKS" desc="Title of the bookmarks page, which shows a list of the user's bookmarks. [CHAR-LIMIT=18]"> @@ -3304,27 +3277,18 @@ <message name="IDS_ACCESSIBILITY_NEW_INCOGNITO_TAB_PAGE" desc="Accessibility text to read aloud when the user focuses the new incognito tab view."> New incognito tab </message> - <message name="IDS_ACCESSIBILITY_NEW_PRIVATE_TAB_PAGE" desc="Accessibility text to read aloud when the user focuses the new private tab view."> - New private tab - </message> <message name="IDS_ACCESSIBILITY_TOOLBAR_BTN_NEW_TAB" desc="Content description for the new tab button."> New tab </message> <message name="IDS_ACCESSIBILITY_TOOLBAR_BTN_NEW_INCOGNITO_TAB" desc="Content description for the new incognito tab button."> New incognito tab </message> - <message name="IDS_ACCESSIBILITY_TOOLBAR_BTN_NEW_PRIVATE_TAB" desc="Content description for the new private tab button."> - New private tab - </message> <message name="IDS_ACCESSIBILITY_TOOLBAR_BTN_CLOSE_ALL_TABS" desc="Content description for the close all tabs button."> Close all tabs </message> <message name="IDS_ACCESSIBILITY_TOOLBAR_BTN_CLOSE_ALL_INCOGNITO_TABS" desc="Content description for the close all incognito tabs button."> Close all incognito tabs </message> - <message name="IDS_ACCESSIBILITY_TOOLBAR_BTN_CLOSE_ALL_PRIVATE_TABS" desc="Content description for the close all private tabs button."> - Close all private tabs - </message> <message name="IDS_ACCESSIBILITY_INCOGNITO_BADGE" desc="Content description for the badge indicating that the user is in Incognito mode."> Incognito mode </message> @@ -3361,15 +3325,9 @@ <message name="IDS_ACCESSIBILITY_TABSTRIP_BTN_INCOGNITO_TOGGLE_STANDARD" desc="Content description for the incognito tabs toggle button when viewing standard tabs."> Enter incognito mode </message> - <message name="IDS_ACCESSIBILITY_TABSTRIP_BTN_PRIVATE_TOGGLE_STANDARD" desc="Content description for the private tabs toggle button when viewing standard tabs."> - Enter private mode - </message> <message name="IDS_ACCESSIBILITY_TABSTRIP_BTN_INCOGNITO_TOGGLE_INCOGNITO" desc="Content description for the incognito tabs toggle button when viewing incognito tabs."> Leave incognito mode </message> - <message name="IDS_ACCESSIBILITY_TABSTRIP_BTN_PRIVATE_TOGGLE_PRIVATE" desc="Content description for the private tabs toggle button when viewing private tabs."> - Leave private mode - </message> <message name="IDS_ACCESSIBILITY_TABSTRIP_IDENTIFIER" desc="Content description for tabs that are not selected"> Tab </message> @@ -3379,15 +3337,9 @@ <message name="IDS_ACCESSIBILITY_TABSTRIP_INCOGNITO_IDENTIFIER" desc="Content description for tabs that are not selected in incognito mode"> Incognito Tab </message> - <message name="IDS_ACCESSIBILITY_TABSTRIP_PRIVATE_IDENTIFIER" desc="Content description for tabs that are not selected in private mode"> - Private Tab - </message> <message name="IDS_ACCESSIBILITY_TABSTRIP_INCOGNITO_IDENTIFIER_SELECTED" desc="Content description for the tab that is selected in incognito mode"> Selected Incognito Tab </message> - <message name="IDS_ACCESSIBILITY_TABSTRIP_PRIVATE_IDENTIFIER_SELECTED" desc="Content description for the tab that is selected in private mode"> - Selected Private Tab - </message> <message name="IDS_ACCESSIBILITY_OMNIBOX_BTN_REFINE" desc="Content description for the omnibox refine button."> Refine </message> @@ -3730,9 +3682,6 @@ <message name="IDS_KEYBOARD_SHORTCUT_NEW_INCOGNITO_TAB" desc="A text label that appears next to a keyboard shortcut to open a new tab in incognito mode in Chrome. The shortcut description is shown in a system dialog along with all other supported shortcuts. [CHAR-LIMIT=55]"> Open a new tab in Incognito mode </message> - <message name="IDS_KEYBOARD_SHORTCUT_NEW_PRIVATE_TAB" desc="A text label that appears next to a keyboard shortcut to open a new tab in private mode in Chrome. The shortcut description is shown in a system dialog along with all other supported shortcuts. [CHAR-LIMIT=55]"> - Open a new tab in Private mode - </message> <message name="IDS_KEYBOARD_SHORTCUT_OPEN_MENU" desc="A text label that appears next to a keyboard shortcut that opens the overflow menu in Chrome. The shortcut description is shown in a system dialog along with all other supported shortcuts. [CHAR-LIMIT=55]"> Open the menu </message>
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/appmenu/AppMenuTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/appmenu/AppMenuTest.java index cc8be1c..023f036 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/appmenu/AppMenuTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/appmenu/AppMenuTest.java
@@ -20,22 +20,25 @@ import org.chromium.base.ObservableSupplier; import org.chromium.base.task.PostTask; +import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.RetryOnFailure; import org.chromium.base.test.util.UrlUtils; -import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.ChromeTabbedActivity; import org.chromium.chrome.browser.compositor.layouts.OverviewModeBehavior; import org.chromium.chrome.browser.lifecycle.ActivityLifecycleDispatcher; -import org.chromium.chrome.test.ChromeActivityTestRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; +import org.chromium.chrome.test.ChromeTabbedActivityTestRule; import org.chromium.chrome.test.util.ChromeTabUtils; import org.chromium.content_public.browser.UiThreadTaskTraits; import org.chromium.content_public.browser.test.util.Criteria; import org.chromium.content_public.browser.test.util.CriteriaHelper; +import org.chromium.content_public.browser.test.util.TestThreadUtils; + +import java.util.concurrent.TimeoutException; /** * Tests AppMenu popup @@ -45,8 +48,7 @@ @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) public class AppMenuTest { @Rule - public ChromeActivityTestRule<ChromeActivity> mActivityTestRule = - new ChromeActivityTestRule<>(ChromeActivity.class); + public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule(); private static final String TEST_URL = UrlUtils.encodeHtmlDataUri("<html>foo</html>"); @@ -227,9 +229,59 @@ }); } + @Test + @SmallTest + @Feature({"Browser", "Main"}) + public void testHideMenuOnToggleOverview() throws TimeoutException, InterruptedException { + CallbackHelper overviewModeFinishedShowingCallback = new CallbackHelper(); + OverviewModeBehavior.OverviewModeObserver overviewModeObserver = + new OverviewModeBehavior.OverviewModeObserver() { + @Override + public void onOverviewModeStartedShowing(boolean showToolbar) {} + + @Override + public void onOverviewModeFinishedShowing() { + overviewModeFinishedShowingCallback.notifyCalled(); + } + + @Override + public void onOverviewModeStartedHiding( + boolean showToolbar, boolean delayAnimation) {} + + @Override + public void onOverviewModeFinishedHiding() {} + }; + // App menu is shown during setup. + Assert.assertTrue("App menu should be showing.", mAppMenu.isShowing()); + Assert.assertFalse("Overview shouldn't be showing.", + mActivityTestRule.getActivity().getOverviewModeBehavior().overviewVisible()); + + TestThreadUtils.runOnUiThreadBlocking(() -> { + mActivityTestRule.getActivity().getLayoutManager().addOverviewModeObserver( + overviewModeObserver); + mActivityTestRule.getActivity().getLayoutManager().showOverview(false); + }); + overviewModeFinishedShowingCallback.waitForCallback(0); + + Assert.assertTrue("Overview should be showing.", + mActivityTestRule.getActivity().getOverviewModeBehavior().overviewVisible()); + Assert.assertFalse("App menu shouldn't be showing.", mAppMenu.isShowing()); + TestThreadUtils.runOnUiThreadBlocking(() -> { + Assert.assertTrue( + "App menu should be allowed to show.", mAppMenuHandler.shouldShowAppMenu()); + }); + showAppMenuAndAssertMenuShown(); + + TestThreadUtils.runOnUiThreadBlocking( + () -> mActivityTestRule.getActivity().getLayoutManager().hideOverview(false)); + Assert.assertFalse("Overview shouldn't be showing.", + mActivityTestRule.getActivity().getOverviewModeBehavior().overviewVisible()); + Assert.assertFalse("App menu shouldn't be showing.", mAppMenu.isShowing()); + } + private void showAppMenuAndAssertMenuShown() { PostTask.runOrPostTask(UiThreadTaskTraits.DEFAULT, - (Runnable) () -> mAppMenuHandler.showAppMenu(null, false, false)); + () -> { mAppMenuHandler.showAppMenu(null, false, false); }); CriteriaHelper.pollInstrumentationThread(new Criteria("AppMenu did not show") { @Override public boolean isSatisfied() {
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulatorTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulatorTest.java index 8a4bc19..f61b3848 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulatorTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulatorTest.java
@@ -48,7 +48,6 @@ */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE, shadows = {ShadowUrlUtilities.class}) -@DisableFeatures(ChromeFeatureList.INCOGNITO_STRINGS) public class ChromeContextMenuPopulatorTest { private static final String PAGE_URL = "http://www.blah.com"; private static final String LINK_URL = "http://www.blah.com/other_blah";
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/content/CustomTabActivityNavigationControllerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/content/CustomTabActivityNavigationControllerTest.java index 4b698d1..156df2a 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/content/CustomTabActivityNavigationControllerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/content/CustomTabActivityNavigationControllerTest.java
@@ -15,6 +15,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -25,11 +26,12 @@ import org.mockito.stubbing.Answer; import org.robolectric.annotation.Config; +import org.chromium.base.task.TaskTraits; +import org.chromium.base.task.test.ShadowPostTask; import org.chromium.chrome.browser.customtabs.content.CustomTabActivityNavigationController.BackHandler; import org.chromium.chrome.browser.customtabs.content.CustomTabActivityNavigationController.FinishHandler; import org.chromium.chrome.browser.customtabs.content.CustomTabActivityNavigationController.FinishReason; import org.chromium.chrome.browser.customtabs.shadows.ShadowExternalNavigationDelegateImpl; -import org.chromium.chrome.browser.customtabs.shadows.ShadowPostTask; import org.chromium.chrome.browser.tab.Tab; import org.chromium.testing.local.LocalRobolectricTestRunner; @@ -55,6 +57,10 @@ @Before public void setUp() { + ShadowPostTask.setTestImpl(new ShadowPostTask.TestImpl() { + @Override + public void postDelayedTask(TaskTraits taskTraits, Runnable task, long delay) {} + }); MockitoAnnotations.initMocks(this); mNavigationController = env.createNavigationController(mTabController); mNavigationController.setFinishHandler(mFinishHandler); @@ -139,4 +145,9 @@ verify(mTabController, never()).detachAndStartReparenting(any(), any(), any()); verify(env.activity).startActivity(any(), any()); } + + @After + public void tearDown() { + ShadowPostTask.reset(); + } }
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/shadows/ShadowPostTask.java b/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/shadows/ShadowPostTask.java deleted file mode 100644 index dbc8bee..0000000 --- a/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/shadows/ShadowPostTask.java +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.customtabs.shadows; - -import org.robolectric.annotation.Implementation; -import org.robolectric.annotation.Implements; - -import org.chromium.base.task.PostTask; -import org.chromium.base.task.TaskTraits; - -/** - * TODO(pshmakov): make a more elaborate shadow, or perhaps a non-static wrapper for PostTask - * to be injected. - */ -@Implements(PostTask.class) -public class ShadowPostTask { - - @Implementation - public static void postDelayedTask(TaskTraits taskTraits, Runnable task, long delay) { - } -}
diff --git a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/OpenLastTabMediator.java b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/OpenLastTabMediator.java index 50ee47e..1cb7c16 100644 --- a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/OpenLastTabMediator.java +++ b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/OpenLastTabMediator.java
@@ -19,6 +19,9 @@ import org.chromium.chrome.browser.history.HistoryProvider; import org.chromium.chrome.browser.native_page.NativePageHost; import org.chromium.chrome.browser.profiles.Profile; +import org.chromium.chrome.browser.tab.EmptyTabObserver; +import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.tabmodel.TabSelectionType; import org.chromium.chrome.browser.util.UrlUtilities; import org.chromium.chrome.browser.util.ViewUtils; import org.chromium.chrome.browser.widget.RoundedIconGenerator; @@ -34,7 +37,8 @@ * Mediator used to look for history events and update the model accordingly. */ // TODO(crbug.com/948858): Add unit tests for this behavior. -class OpenLastTabMediator implements HistoryProvider.BrowsingHistoryObserver, FocusableComponent { +class OpenLastTabMediator extends EmptyTabObserver + implements HistoryProvider.BrowsingHistoryObserver, FocusableComponent { private static final String FIRST_LAUNCHED_KEY = "TOUCHLESS_WAS_FIRST_LAUNCHED"; private final Context mContext; @@ -49,14 +53,15 @@ OpenLastTabMediator(Context context, Profile profile, NativePageHost nativePageHost, PropertyModel model, OpenLastTabView view) { + mModel = model; mContext = context; mProfile = profile; mNativePageHost = nativePageHost; - mModel = model; - mHistoryBridge = new BrowsingHistoryBridge(false); mHistoryBridge.setObserver(this); + mNativePageHost.getActiveTab().addObserver(this); + mIconGenerator = ViewUtils.createDefaultRoundedIconGenerator(mContext.getResources(), false); mIconBridge = new LargeIconBridge(mProfile); @@ -74,7 +79,7 @@ // TODO(wylieb):Investigate adding an item limit to the API. // Query the history for everything (no API exists to only query for the most recent). - mHistoryBridge.queryHistory(""); + refreshHistoryData(); } void destroy() { @@ -82,6 +87,18 @@ mHistoryBridge.destroy(); mHistoryBridge = null; } + mNativePageHost.getActiveTab().removeObserver(this); + } + + void refreshHistoryData() { + mHistoryBridge.queryHistory(""); + } + + @Override + public void onShown(Tab tab, @TabSelectionType int type) { + // Query the history as it may have been cleared while the app was hidden. This could happen + // via the Android settings. + refreshHistoryData(); } @Override
diff --git a/chrome/android/touchless/junit/src/org/chromium/chrome/browser/touchless/ui/progressbar/ProgressBarMediatorTest.java b/chrome/android/touchless/junit/src/org/chromium/chrome/browser/touchless/ui/progressbar/ProgressBarMediatorTest.java new file mode 100644 index 0000000..bec31b7 --- /dev/null +++ b/chrome/android/touchless/junit/src/org/chromium/chrome/browser/touchless/ui/progressbar/ProgressBarMediatorTest.java
@@ -0,0 +1,133 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.touchless.ui.progressbar; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.robolectric.annotation.Config; +import org.robolectric.shadows.ShadowLooper; + +import org.chromium.base.task.test.ShadowPostTask; +import org.chromium.base.test.BaseRobolectricTestRunner; +import org.chromium.chrome.browser.ActivityTabProvider; +import org.chromium.chrome.browser.UrlConstants; +import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.tab.TabObserver; +import org.chromium.chrome.browser.util.test.ShadowUrlUtilities; +import org.chromium.ui.modelutil.PropertyModel; + +/** + * Unit tests for the {@link ProgressBarMediator} class. + */ +@RunWith(BaseRobolectricTestRunner.class) +@Config(manifest = Config.NONE, shadows = {ShadowUrlUtilities.class, ShadowPostTask.class}) +public class ProgressBarMediatorTest { + private static final String SAMPLE_URL = "https://www.google.com/chrome"; + private static final String SAMPLE_URL_SHORT = "google.com"; + + private PropertyModel mModel; + private ArgumentCaptor<TabObserver> mTabObserver; + private Tab mTab; + + @Before + public void setUp() { + ShadowUrlUtilities.setTestImpl(new ShadowUrlUtilities.TestImpl() { + @Override + public String getDomainAndRegistry(String uri, boolean includePrivateRegistries) { + return SAMPLE_URL_SHORT; + } + }); + } + + private ProgressBarMediator initProgressBarMediator() { + mModel = spy(new PropertyModel.Builder(ProgressBarProperties.ALL_KEYS).build()); + mTabObserver = ArgumentCaptor.forClass(TabObserver.class); + mTab = mock(Tab.class); + ActivityTabProvider activityTabProvider = spy(ActivityTabProvider.class); + when(activityTabProvider.get()).thenReturn(mTab); + ProgressBarMediator progressBarMediator = + new ProgressBarMediator(mModel, activityTabProvider); + verify(mTab).addObserver(mTabObserver.capture()); + return progressBarMediator; + } + + @Test + public void visibilityTest() { + ProgressBarMediator progressBarMediator = initProgressBarMediator(); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_ENABLED), false); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_VISIBLE), false); + + mTabObserver.getValue().onPageLoadStarted(mTab, SAMPLE_URL); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_ENABLED), true); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_VISIBLE), true); + + // Mock page load finish, but not display timeout. The progress bar should still be visible. + mTabObserver.getValue().onPageLoadFinished(mTab, SAMPLE_URL); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_ENABLED), true); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_VISIBLE), true); + + // Mock display timeout. The progress bar should not be visible at this point. + ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_ENABLED), true); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_VISIBLE), false); + + // The progress bar should be shown on activity resume. + progressBarMediator.onActivityResume(); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_ENABLED), true); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_VISIBLE), true); + + // And should disappear after the timeout. + ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_ENABLED), true); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_VISIBLE), false); + + // The progress bar should be disabled for native pages. + mTabObserver.getValue().onPageLoadStarted(mTab, UrlConstants.NTP_URL); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_ENABLED), false); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_VISIBLE), false); + + // Mock key press before timeout and page load finish. + mTabObserver.getValue().onPageLoadStarted(mTab, SAMPLE_URL); + progressBarMediator.onKeyEvent(); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_ENABLED), true); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_VISIBLE), true); + + // Mock display timeout before page load finish, and after key press. + ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_ENABLED), true); + Assert.assertEquals(mModel.get(ProgressBarProperties.IS_VISIBLE), false); + } + + @Test + public void progressAndUrlTest() { + initProgressBarMediator(); + Assert.assertNull(mModel.get(ProgressBarProperties.URL)); + + when(mTab.getUrl()).thenReturn(SAMPLE_URL); + mTabObserver.getValue().onLoadProgressChanged(mTab, 10); + Assert.assertEquals(mModel.get(ProgressBarProperties.PROGRESS_FRACTION), .1, .001); + Assert.assertEquals(mModel.get(ProgressBarProperties.URL), SAMPLE_URL_SHORT); + + // Progress and URL should not be updated for native pages. + when(mTab.getUrl()).thenReturn(UrlConstants.NTP_URL); + mTabObserver.getValue().onLoadProgressChanged(mTab, 20); + Assert.assertEquals(mModel.get(ProgressBarProperties.PROGRESS_FRACTION), .1, .001); + Assert.assertEquals(mModel.get(ProgressBarProperties.URL), SAMPLE_URL_SHORT); + } + + @After + public void tearDown() { + ShadowUrlUtilities.reset(); + } +}
diff --git a/chrome/android/touchless/touchless_java_sources.gni b/chrome/android/touchless/touchless_java_sources.gni index d7fc170..fbba84c6 100644 --- a/chrome/android/touchless/touchless_java_sources.gni +++ b/chrome/android/touchless/touchless_java_sources.gni
@@ -75,6 +75,7 @@ touchless_junit_test_java_sources = [ "touchless/junit/src/org/chromium/chrome/browser/touchless/ScrollPositionInfoTest.java", "touchless/junit/src/org/chromium/chrome/browser/touchless/TouchlessActionItemViewHolderTest.java", + "touchless/junit/src/org/chromium/chrome/browser/touchless/ui/progressbar/ProgressBarMediatorTest.java", ] touchess_fallback_java_sources = [
diff --git a/chrome/android/webapk/shell_apk/current_version/current_version.gni b/chrome/android/webapk/shell_apk/current_version/current_version.gni index 225f280..3123c861 100644 --- a/chrome/android/webapk/shell_apk/current_version/current_version.gni +++ b/chrome/android/webapk/shell_apk/current_version/current_version.gni
@@ -12,4 +12,4 @@ # //chrome/android/webapk/shell_apk:webapk is changed. This includes # Java files, Android resource files and AndroidManifest.xml. Does not affect # Chrome.apk -current_shell_apk_version = 90 +current_shell_apk_version = 91
diff --git a/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/H2OLauncher.java b/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/H2OLauncher.java index 5a7b834..e659588 100644 --- a/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/H2OLauncher.java +++ b/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/H2OLauncher.java
@@ -22,7 +22,7 @@ /** Contains methods for launching host browser where ShellAPK shows the splash screen. */ public class H2OLauncher { // Lowest version of Chromium which supports ShellAPK showing the splash screen. - static final int MINIMUM_REQUIRED_CHROMIUM_VERSION_NEW_SPLASH = Integer.MAX_VALUE; + static final int MINIMUM_REQUIRED_CHROMIUM_VERSION_NEW_SPLASH = 76; private static final String TAG = "cr_H2OLauncher";
diff --git a/chrome/app/vr_strings.grdp b/chrome/app/vr_strings.grdp index f0f0856..a6ba9729 100644 --- a/chrome/app/vr_strings.grdp +++ b/chrome/app/vr_strings.grdp
@@ -149,18 +149,12 @@ <message name="IDS_VR_MENU_NEW_INCOGNITO_TAB" desc="Menu item for opening a new incognito tab that facilitates pseudononymous browsing. [CHAR-LIMIT=27]"> New incognito tab </message> - <message name="IDS_VR_MENU_NEW_PRIVATE_TAB" desc="Menu item for opening a new private tab that facilitates pseudononymous browsing. [CHAR-LIMIT=27]"> - New private tab - </message> <message name="IDS_VR_MENU_PREFERENCES" desc="Menu item for opening browser preferences. [CHAR-LIMIT=27]"> Settings </message> <message name="IDS_VR_MENU_CLOSE_INCOGNITO_TABS" desc="Menu item for closing all open incognito tabs. [CHAR-LIMIT=27]"> Close incognito tabs </message> - <message name="IDS_VR_MENU_CLOSE_PRIVATE_TABS" desc="Menu item for closing all open private tabs. [CHAR-LIMIT=27]"> - Close private tabs - </message> <message name="IDS_VR_TABS_BUTTON_REGULAR" desc="Text on button for selecting regular tabs"> Tabs </message>
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index ef26d7d..616c5bb 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -313,8 +313,6 @@ "component_updater/chrome_component_updater_configurator.h", "component_updater/component_updater_prefs.cc", "component_updater/component_updater_prefs.h", - "component_updater/component_updater_resource_throttle.cc", - "component_updater/component_updater_resource_throttle.h", "component_updater/component_updater_utils.cc", "component_updater/component_updater_utils.h", "component_updater/crl_set_component_installer.cc", @@ -433,8 +431,6 @@ "download/download_query.h", "download/download_request_limiter.cc", "download/download_request_limiter.h", - "download/download_resource_throttle.cc", - "download/download_resource_throttle.h", "download/download_service_factory.cc", "download/download_service_factory.h", "download/download_started_animation.h", @@ -634,8 +630,6 @@ "lifetime/browser_shutdown.h", "loader/chrome_navigation_data.cc", "loader/chrome_navigation_data.h", - "loader/chrome_resource_dispatcher_host_delegate.cc", - "loader/chrome_resource_dispatcher_host_delegate.h", "lookalikes/lookalike_url_allowlist.cc", "lookalikes/lookalike_url_allowlist.h", "lookalikes/lookalike_url_controller_client.cc", @@ -2328,8 +2322,6 @@ "android/download/download_utils.h", "android/download/duplicate_download_infobar_delegate.cc", "android/download/duplicate_download_infobar_delegate.h", - "android/download/intercept_download_resource_throttle.cc", - "android/download/intercept_download_resource_throttle.h", "android/download/intercept_oma_download_navigation_throttle.cc", "android/download/intercept_oma_download_navigation_throttle.h", "android/download/items/offline_content_aggregator_factory_android.cc", @@ -4489,8 +4481,6 @@ "offline_pages/background_loader_offliner.h", "offline_pages/download_archive_manager.cc", "offline_pages/download_archive_manager.h", - "offline_pages/downloads/resource_throttle.cc", - "offline_pages/downloads/resource_throttle.h", "offline_pages/fresh_offline_content_observer.cc", "offline_pages/fresh_offline_content_observer.h", "offline_pages/offline_page_bookmark_observer.cc",
diff --git a/chrome/browser/android/chrome_feature_list.cc b/chrome/browser/android/chrome_feature_list.cc index e89a3b2..c3914564 100644 --- a/chrome/browser/android/chrome_feature_list.cc +++ b/chrome/browser/android/chrome_feature_list.cc
@@ -66,7 +66,6 @@ &features::kClearOldBrowsingData, &features::kDownloadsLocationChange, &features::kGenericSensorExtraClasses, - &features::kIncognitoStrings, &features::kInstallableAmbientBadgeInfoBar, &features::kOverscrollHistoryNavigation, &features::kPermissionDelegation,
diff --git a/chrome/browser/android/compositor/layer/ephemeral_tab_layer.cc b/chrome/browser/android/compositor/layer/ephemeral_tab_layer.cc index 536e6259..8b02af0 100644 --- a/chrome/browser/android/compositor/layer/ephemeral_tab_layer.cc +++ b/chrome/browser/android/compositor/layer/ephemeral_tab_layer.cc
@@ -9,7 +9,9 @@ #include "cc/layers/ui_resource_layer.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/profiles/profile.h" +#include "components/favicon/content/content_favicon_driver.h" #include "components/favicon/core/favicon_service.h" +#include "content/public/browser/web_contents.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/android/resources/resource_manager.h" #include "ui/base/l10n/l10n_util_android.h" @@ -18,6 +20,26 @@ namespace { +void DisplayFavicon(scoped_refptr<cc::UIResourceLayer> layer, + scoped_refptr<cc::UIResourceLayer> icon_layer, + const SkBitmap& favicon, + const float dp_to_px, + const float panel_width, + const float bar_height, + const float padding) { + const float icon_width = + android::OverlayPanelLayer::kDefaultIconWidthDp * dp_to_px; + layer->SetBitmap(favicon); + layer->SetBounds(gfx::Size(icon_width, icon_width)); + + bool is_rtl = l10n_util::IsLayoutRtl(); + float icon_x = is_rtl ? panel_width - icon_width - padding : padding; + float icon_y = (bar_height - layer->bounds().height()) / 2; + icon_layer->SetIsDrawable(false); + layer->SetIsDrawable(true); + layer->SetPosition(gfx::PointF(icon_x, icon_y)); +} + void OnLocalFaviconAvailable( scoped_refptr<cc::UIResourceLayer> layer, scoped_refptr<cc::UIResourceLayer> icon_layer, @@ -33,18 +55,9 @@ &favicon_bitmap); if (favicon_bitmap.isNull()) return; - const float icon_width = - android::OverlayPanelLayer::kDefaultIconWidthDp * dp_to_px; favicon_bitmap.setImmutable(); - layer->SetBitmap(favicon_bitmap); - layer->SetBounds(gfx::Size(icon_width, icon_width)); - - bool is_rtl = l10n_util::IsLayoutRtl(); - float icon_x = is_rtl ? panel_width - icon_width - padding : padding; - float icon_y = (bar_height - layer->bounds().height()) / 2; - icon_layer->SetIsDrawable(false); - layer->SetIsDrawable(true); - layer->SetPosition(gfx::PointF(icon_x, icon_y)); + DisplayFavicon(layer, icon_layer, favicon_bitmap, dp_to_px, panel_width, + bar_height, padding); } } // namespace @@ -57,6 +70,7 @@ } void EphemeralTabLayer::SetProperties( + content::WebContents* web_contents, int title_view_resource_id, int caption_view_resource_id, jfloat caption_animation_percentage, @@ -85,6 +99,18 @@ float progress_bar_height, float progress_bar_opacity, int progress_bar_completion) { + if (web_contents_ != web_contents) { + web_contents_ = web_contents; + if (web_contents_) { + auto* favicon_driver = + favicon::ContentFaviconDriver::FromWebContents(web_contents_); + if (favicon_driver) + favicon_driver->AddObserver(this); + // No need to remove the observer from the previous WebContents since + // it is already destroyed by the time it reaches this point. + } + } + // Round values to avoid pixel gap between layers. bar_height = floor(bar_height); float bar_top = 0.f; @@ -215,6 +241,26 @@ caption_->SetPosition(gfx::PointF(0.f, caption_top)); } +void EphemeralTabLayer::OnFaviconUpdated( + favicon::FaviconDriver* favicon_driver, + NotificationIconType notification_icon_type, + const GURL& icon_url, + bool icon_url_changed, + const gfx::Image& image) { + if (notification_icon_type != NON_TOUCH_LARGEST && + notification_icon_type != TOUCH_LARGEST) { + return; + } + + SkBitmap favicon_bitmap = + image.AsImageSkia().GetRepresentation(1.0f).GetBitmap(); + if (favicon_bitmap.empty()) + return; + favicon_bitmap.setImmutable(); + DisplayFavicon(favicon_layer_, panel_icon_, favicon_bitmap, dp_to_px_, + panel_width_, bar_height_, bar_margin_side_); +} + void EphemeralTabLayer::GetLocalFaviconImageForURL(Profile* profile, const std::string& url, int size) {
diff --git a/chrome/browser/android/compositor/layer/ephemeral_tab_layer.h b/chrome/browser/android/compositor/layer/ephemeral_tab_layer.h index b6b1e72..87046b6 100644 --- a/chrome/browser/android/compositor/layer/ephemeral_tab_layer.h +++ b/chrome/browser/android/compositor/layer/ephemeral_tab_layer.h
@@ -7,6 +7,8 @@ #include "chrome/browser/android/compositor/layer/overlay_panel_layer.h" +#include "components/favicon/core/favicon_driver_observer.h" + class Profile; namespace base { @@ -17,16 +19,26 @@ class Layer; } +namespace content { +class WebContents; +} + +namespace favicon { +class FaviconDriver; +} + namespace ui { class ResourceManager; } namespace android { -class EphemeralTabLayer : public OverlayPanelLayer { +class EphemeralTabLayer : public OverlayPanelLayer, + public favicon::FaviconDriverObserver { public: static scoped_refptr<EphemeralTabLayer> Create( ui::ResourceManager* resource_manager); - void SetProperties(int title_view_resource_id, + void SetProperties(content::WebContents* web_contents, + int title_view_resource_id, int caption_view_resource_id, jfloat caption_animation_percentage, jfloat text_layer_min_height, @@ -67,11 +79,19 @@ const std::string& url, int size); + // favicon::FaviconDriverObserver + void OnFaviconUpdated(favicon::FaviconDriver* favicon_driver, + NotificationIconType notification_icon_type, + const GURL& icon_url, + bool icon_url_changed, + const gfx::Image& image) override; + protected: explicit EphemeralTabLayer(ui::ResourceManager* resource_manager); ~EphemeralTabLayer() override; private: + content::WebContents* web_contents_ = nullptr; float dp_to_px_; float panel_width_; float bar_height_;
diff --git a/chrome/browser/android/compositor/scene_layer/ephemeral_tab_scene_layer.cc b/chrome/browser/android/compositor/scene_layer/ephemeral_tab_scene_layer.cc index 9cbcbc02..0728d4a 100644 --- a/chrome/browser/android/compositor/scene_layer/ephemeral_tab_scene_layer.cc +++ b/chrome/browser/android/compositor/scene_layer/ephemeral_tab_scene_layer.cc
@@ -124,7 +124,7 @@ // Move the base page contents up. content_container_->SetPosition(gfx::PointF(0.0f, base_page_offset)); ephemeral_tab_layer_->SetProperties( - title_view_resource_id, caption_view_resource_id, + web_contents, title_view_resource_id, caption_view_resource_id, caption_animation_percentage, text_layer_min_height, title_caption_spacing, caption_visible, progress_bar_background_resource_id, progress_bar_resource_id, dp_to_px,
diff --git a/chrome/browser/android/download/intercept_download_resource_throttle.cc b/chrome/browser/android/download/intercept_download_resource_throttle.cc deleted file mode 100644 index 61b3715f..0000000 --- a/chrome/browser/android/download/intercept_download_resource_throttle.cc +++ /dev/null
@@ -1,91 +0,0 @@ -// Copyright (c) 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/android/download/intercept_download_resource_throttle.h" - -#include "base/bind.h" -#include "base/strings/string_util.h" -#include "chrome/browser/android/download/download_controller_base.h" -#include "net/cookies/canonical_cookie.h" -#include "net/cookies/cookie_store.h" -#include "net/http/http_request_headers.h" -#include "net/http/http_response_headers.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_context.h" - -InterceptDownloadResourceThrottle::InterceptDownloadResourceThrottle( - net::URLRequest* request, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter) - : request_(request), - wc_getter_(wc_getter), - weak_factory_(this) { -} - -InterceptDownloadResourceThrottle::~InterceptDownloadResourceThrottle() = - default; - -void InterceptDownloadResourceThrottle::WillProcessResponse(bool* defer) { - if (request_->url_chain().empty()) - return; - - GURL url = request_->url_chain().back(); - if (!url.SchemeIsHTTPOrHTTPS()) - return; - - if (request_->method() != net::HttpRequestHeaders::kGetMethod) - return; - - net::HttpRequestHeaders headers; - if (!request_->GetFullRequestHeaders(&headers)) - return; - - std::string mime_type; - request_->response_headers()->GetMimeType(&mime_type); - if (!base::EqualsCaseInsensitiveASCII(mime_type, kOMADrmMessageMimeType) && - !base::EqualsCaseInsensitiveASCII(mime_type, kOMADrmContentMimeType) && - !base::EqualsCaseInsensitiveASCII(mime_type, kOMADrmRightsMimeType1) && - !base::EqualsCaseInsensitiveASCII(mime_type, kOMADrmRightsMimeType2)) { - return; - } - - net::CookieStore* cookie_store = request_->context()->cookie_store(); - if (cookie_store) { - // Cookie is obtained via asynchonous call. Setting |*defer| to true - // keeps the throttle alive in the meantime. - *defer = true; - net::CookieOptions options; - options.set_include_httponly(); - cookie_store->GetCookieListWithOptionsAsync( - request_->url(), options, - base::BindOnce(&InterceptDownloadResourceThrottle::CheckCookiePolicy, - weak_factory_.GetWeakPtr())); - } else { - // Can't get any cookies, start android download. - StartDownload(DownloadInfo(request_)); - } -} - -const char* InterceptDownloadResourceThrottle::GetNameForLogging() { - return "InterceptDownloadResourceThrottle"; -} - -void InterceptDownloadResourceThrottle::CheckCookiePolicy( - const net::CookieList& cookie_list, - const net::CookieStatusList& excluded_cookies) { - DownloadInfo info(request_); - if (request_->context()->network_delegate()->CanGetCookies( - *request_, cookie_list, - /*allowed_from_caller=*/true)) { - std::string cookie = net::CanonicalCookie::BuildCookieLine(cookie_list); - if (!cookie.empty()) - info.cookie = cookie; - } - StartDownload(info); -} - -void InterceptDownloadResourceThrottle::StartDownload( - const DownloadInfo& info) { - DownloadControllerBase::Get()->CreateAndroidDownload(wc_getter_, info); - Cancel(); -}
diff --git a/chrome/browser/android/download/intercept_download_resource_throttle.h b/chrome/browser/android/download/intercept_download_resource_throttle.h deleted file mode 100644 index f146d56..0000000 --- a/chrome/browser/android/download/intercept_download_resource_throttle.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_ANDROID_DOWNLOAD_INTERCEPT_DOWNLOAD_RESOURCE_THROTTLE_H_ -#define CHROME_BROWSER_ANDROID_DOWNLOAD_INTERCEPT_DOWNLOAD_RESOURCE_THROTTLE_H_ - -#include "base/memory/weak_ptr.h" -#include "chrome/browser/android/download/download_controller_base.h" -#include "content/public/browser/resource_request_info.h" -#include "content/public/browser/resource_throttle.h" -#include "net/cookies/canonical_cookie.h" - -namespace net { -class URLRequest; -} - -// InterceptDownloadResourceThrottle checks if a download request should be -// handled by Chrome or passsed to the Android Download Manager. -class InterceptDownloadResourceThrottle : public content::ResourceThrottle { - public: - InterceptDownloadResourceThrottle( - net::URLRequest* request, - const content::ResourceRequestInfo::WebContentsGetter& wc_getter); - ~InterceptDownloadResourceThrottle() override; - - // content::ResourceThrottle implementation: - void WillProcessResponse(bool* defer) override; - const char* GetNameForLogging() override; - - private: - void CheckCookiePolicy(const net::CookieList& cookie_list, - const net::CookieStatusList& excluded_cookies); - void StartDownload(const DownloadInfo& info); - - const net::URLRequest* request_; - content::ResourceRequestInfo::WebContentsGetter wc_getter_; - - base::WeakPtrFactory<InterceptDownloadResourceThrottle> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(InterceptDownloadResourceThrottle); -}; - -#endif // CHROME_BROWSER_ANDROID_DOWNLOAD_INTERCEPT_DOWNLOAD_RESOURCE_THROTTLE_H_
diff --git a/chrome/browser/android/omnibox/autocomplete_controller_android.cc b/chrome/browser/android/omnibox/autocomplete_controller_android.cc index 3cf090c..01c2a00 100644 --- a/chrome/browser/android/omnibox/autocomplete_controller_android.cc +++ b/chrome/browser/android/omnibox/autocomplete_controller_android.cc
@@ -157,11 +157,11 @@ jint j_cursor_pos, const JavaRef<jstring>& j_desired_tld, const JavaRef<jstring>& j_current_url, + jint j_page_classification, bool prevent_inline_autocomplete, bool prefer_keyword, bool allow_exact_keyword_match, - bool want_asynchronous_matches, - bool focused_from_fakebox) { + bool want_asynchronous_matches) { if (!autocomplete_controller_) return; @@ -172,11 +172,11 @@ if (!j_desired_tld.is_null()) desired_tld = base::android::ConvertJavaStringToUTF8(env, j_desired_tld); base::string16 text = ConvertJavaStringToUTF16(env, j_text); - OmniboxEventProto::PageClassification page_classification = - ClassifyPage(current_url, focused_from_fakebox); size_t cursor_pos = j_cursor_pos == -1 ? base::string16::npos : j_cursor_pos; - input_ = AutocompleteInput(text, cursor_pos, desired_tld, page_classification, - ChromeAutocompleteSchemeClassifier(profile_)); + input_ = AutocompleteInput( + text, cursor_pos, desired_tld, + OmniboxEventProto::PageClassification(j_page_classification), + ChromeAutocompleteSchemeClassifier(profile_)); input_.set_current_url(current_url); input_.set_prevent_inline_autocomplete(prevent_inline_autocomplete); input_.set_prefer_keyword(prefer_keyword); @@ -198,8 +198,8 @@ const JavaParamRef<jobject>& obj, const JavaParamRef<jstring>& j_omnibox_text, const JavaParamRef<jstring>& j_current_url, - const JavaParamRef<jstring>& j_current_title, - jboolean focused_from_fakebox) { + jint j_page_classification, + const JavaParamRef<jstring>& j_current_title) { if (!autocomplete_controller_) return; @@ -220,9 +220,10 @@ !current_url.SchemeIs(chrome::kChromeUINativeScheme)) omnibox_text = url; - input_ = AutocompleteInput(omnibox_text, - ClassifyPage(current_url, focused_from_fakebox), - ChromeAutocompleteSchemeClassifier(profile_)); + input_ = AutocompleteInput( + omnibox_text, + OmniboxEventProto::PageClassification(j_page_classification), + ChromeAutocompleteSchemeClassifier(profile_)); input_.set_current_url(current_url); input_.set_current_title(current_title); input_.set_from_omnibox_focus(true); @@ -249,7 +250,7 @@ jint selected_index, jint hash_code, const JavaParamRef<jstring>& j_current_url, - jboolean focused_from_fakebox, + jint j_page_classification, jlong elapsed_time_since_first_modified, jint completed_length, const JavaParamRef<jobject>& j_web_contents) { @@ -258,8 +259,6 @@ base::string16 url = ConvertJavaStringToUTF16(env, j_current_url); const GURL current_url = GURL(url); - OmniboxEventProto::PageClassification current_page_classification = - ClassifyPage(current_url, focused_from_fakebox); const base::TimeTicks& now(base::TimeTicks::Now()); content::WebContents* web_contents = content::WebContents::FromJavaWebContents(j_web_contents); @@ -280,16 +279,12 @@ // For zero suggest, record an empty input string instead of the // current URL. input_.from_omnibox_focus() ? base::string16() : input_.text(), - false, /* don't know */ - input_.type(), - false, /* not keyword mode */ - OmniboxEventProto::INVALID, - true, - selected_index, - WindowOpenDisposition::CURRENT_TAB, - false, + false, /* don't know */ + input_.type(), false, /* not keyword mode */ + OmniboxEventProto::INVALID, true, selected_index, + WindowOpenDisposition::CURRENT_TAB, false, SessionTabHelper::IdForTab(web_contents), - current_page_classification, + OmniboxEventProto::PageClassification(j_page_classification), base::TimeDelta::FromMilliseconds(elapsed_time_since_first_modified), completed_length, now - autocomplete_controller_->last_time_default_match_changed(), @@ -431,49 +426,6 @@ j_autocomplete_result); } -OmniboxEventProto::PageClassification -AutocompleteControllerAndroid::ClassifyPage(const GURL& gurl, - bool focused_from_fakebox) const { - if (!gurl.is_valid()) - return OmniboxEventProto::INVALID_SPEC; - - const std::string& url = gurl.spec(); - - if (gurl.SchemeIs(content::kChromeUIScheme) && - gurl.host_piece() == chrome::kChromeUINewTabHost) { - return OmniboxEventProto::NTP; - } - - if (url == chrome::kChromeUINativeNewTabURL) { - // On phones, the omnibox is not initially shown on the NTP. In this case, - // treat the fakebox like the omnibox. - if (ui::GetDeviceFormFactor() == ui::DEVICE_FORM_FACTOR_PHONE) - return OmniboxEventProto::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS; - - // On tablets, the user can choose to focus either the fakebox or the - // omnibox. Chrome distinguishes between the two in order to apply URL - // demotion when the user focuses the fakebox (which looks more like a - // search box) but not when they focus the omnibox (which looks more - // like a URL bar). - return focused_from_fakebox ? - OmniboxEventProto::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS : - OmniboxEventProto::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS; - } - - if (url == url::kAboutBlankURL) - return OmniboxEventProto::BLANK; - - if (url == profile_->GetPrefs()->GetString(prefs::kHomePage)) - return OmniboxEventProto::HOME_PAGE; - - bool is_search_url = TemplateURLServiceFactory::GetForProfile(profile_)-> - IsSearchResultsPageFromDefaultSearchProvider(gurl); - if (is_search_url) - return OmniboxEventProto::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT; - - return OmniboxEventProto::OTHER; -} - namespace { // Updates the formatting of Android omnibox suggestions where we intentionally
diff --git a/chrome/browser/android/omnibox/autocomplete_controller_android.h b/chrome/browser/android/omnibox/autocomplete_controller_android.h index 141eff78..d90a88e 100644 --- a/chrome/browser/android/omnibox/autocomplete_controller_android.h +++ b/chrome/browser/android/omnibox/autocomplete_controller_android.h
@@ -38,11 +38,11 @@ jint j_cursor_pos, const base::android::JavaRef<jstring>& j_desired_tld, const base::android::JavaRef<jstring>& j_current_url, + jint j_page_classification, bool prevent_inline_autocomplete, bool prefer_keyword, bool allow_exact_keyword_match, - bool want_asynchronous_matches, - bool focused_from_fakebox); + bool want_asynchronous_matches); base::android::ScopedJavaLocalRef<jobject> Classify( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, @@ -53,8 +53,8 @@ const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jstring>& j_omnibox_text, const base::android::JavaParamRef<jstring>& j_current_url, - const base::android::JavaParamRef<jstring>& j_current_title, - jboolean focused_from_fakebox); + jint j_page_classification, + const base::android::JavaParamRef<jstring>& j_current_title); void Stop(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, bool clear_result); @@ -66,7 +66,7 @@ jint selected_index, jint hash_code, const base::android::JavaParamRef<jstring>& j_current_url, - jboolean focused_from_fakebox, + jint j_page_classification, jlong elapsed_time_since_first_modified, jint completed_length, const base::android::JavaParamRef<jobject>& j_web_contents); @@ -120,11 +120,6 @@ void NotifySuggestionsReceived( const AutocompleteResult& autocomplete_result); - // Classifies the type of page we are on. - metrics::OmniboxEventProto::PageClassification ClassifyPage( - const GURL& gurl, - bool focused_from_fakebox) const; - base::android::ScopedJavaLocalRef<jobject> BuildOmniboxSuggestion( JNIEnv* env, const AutocompleteMatch& match);
diff --git a/chrome/browser/android/shortcut_info.cc b/chrome/browser/android/shortcut_info.cc index b7a73e1..6282507 100644 --- a/chrome/browser/android/shortcut_info.cc +++ b/chrome/browser/android/shortcut_info.cc
@@ -92,18 +92,8 @@ if (manifest.share_target) { share_target = ShareTarget(); share_target->action = manifest.share_target->action; - if (manifest.share_target->method == - blink::Manifest::ShareTarget::Method::kPost) { - share_target->method = ShareTarget::Method::kPost; - } else { - share_target->method = ShareTarget::Method::kGet; - } - if (manifest.share_target->enctype == - blink::Manifest::ShareTarget::Enctype::kMultipart) { - share_target->enctype = ShareTarget::Enctype::kMultipart; - } else { - share_target->enctype = ShareTarget::Enctype::kApplication; - } + share_target->method = manifest.share_target->method; + share_target->enctype = manifest.share_target->enctype; if (!manifest.share_target->params.text.is_null()) share_target->params.text = manifest.share_target->params.text.string(); if (!manifest.share_target->params.title.is_null())
diff --git a/chrome/browser/android/shortcut_info.h b/chrome/browser/android/shortcut_info.h index d787b47..1a05dd5 100644 --- a/chrome/browser/android/shortcut_info.h +++ b/chrome/browser/android/shortcut_info.h
@@ -38,18 +38,9 @@ // https://wicg.github.io/web-share-target/#dom-sharetarget struct ShareTarget { - // This enum is used to indicate the HTTP method used by the share target. - // kGet stands for GET request, and kPost stands for POST request. - enum Method { kGet = 0, kPost = 1 }; - - // This enum is used to indicate the HTTP enctype used by the share target. - // kApplication stands for application/x-www-form-urlencoded enctype, and - // kMultipart stands for multipart/form-data enctype. - enum Enctype { kApplication = 0, kMultipart = 1 }; - GURL action; - Method method; - Enctype enctype; + blink::Manifest::ShareTarget::Method method; + blink::Manifest::ShareTarget::Enctype enctype; ShareTargetParams params; ShareTarget(); ~ShareTarget();
diff --git a/chrome/browser/android/vr/vr_shell.cc b/chrome/browser/android/vr/vr_shell.cc index 094f664..2d7424c 100644 --- a/chrome/browser/android/vr/vr_shell.cc +++ b/chrome/browser/android/vr/vr_shell.cc
@@ -47,7 +47,6 @@ #include "chrome/browser/vr/ui_test_input.h" #include "chrome/browser/vr/vr_tab_helper.h" #include "chrome/browser/vr/vr_web_contents_observer.h" -#include "chrome/common/chrome_features.h" #include "chrome/common/url_constants.h" #include "components/language/core/browser/pref_names.h" #include "components/prefs/pref_service.h" @@ -1380,8 +1379,6 @@ has_or_can_request_record_audio_permission; ui_initial_state.assets_supported = AssetsLoader::AssetsSupported(); ui_initial_state.is_standalone_vr_device = is_standalone_vr_device; - ui_initial_state.use_new_incognito_strings = - base::FeatureList::IsEnabled(features::kIncognitoStrings); return reinterpret_cast<intptr_t>(new VrShell( env, obj, ui_initial_state,
diff --git a/chrome/browser/android/webapk/webapk_installer.cc b/chrome/browser/android/webapk/webapk_installer.cc index 2f74028..9e8119e 100644 --- a/chrome/browser/android/webapk/webapk_installer.cc +++ b/chrome/browser/android/webapk/webapk_installer.cc
@@ -48,6 +48,7 @@ #include "services/network/public/cpp/resource_request.h" #include "services/network/public/cpp/resource_response_info.h" #include "services/network/public/cpp/simple_url_loader.h" +#include "third_party/blink/public/common/manifest/manifest.h" #include "third_party/blink/public/common/manifest/manifest_util.h" #include "ui/gfx/android/java_bitmap.h" #include "ui/gfx/codec/png_codec.h" @@ -210,13 +211,14 @@ if (shortcut_info.share_target) { webapk::ShareTarget* share_target = web_app_manifest->add_share_targets(); share_target->set_action(shortcut_info.share_target->action.spec()); - if (shortcut_info.share_target->method == ShareTarget::Method::kPost) { + if (shortcut_info.share_target->method == + blink::Manifest::ShareTarget::Method::kPost) { share_target->set_method("POST"); } else { share_target->set_method("GET"); } if (shortcut_info.share_target->enctype == - ShareTarget::Enctype::kMultipart) { + blink::Manifest::ShareTarget::Enctype::kMultipartFormData) { share_target->set_enctype("multipart/form-data"); } else { share_target->set_enctype("application/x-www-form-urlencoded");
diff --git a/chrome/browser/android/webapk/webapk_update_data_fetcher.cc b/chrome/browser/android/webapk/webapk_update_data_fetcher.cc index 08e8682..7bd52ac9 100644 --- a/chrome/browser/android/webapk/webapk_update_data_fetcher.cc +++ b/chrome/browser/android/webapk/webapk_update_data_fetcher.cc
@@ -242,9 +242,11 @@ env, info_.share_target->params.url); java_share_params_is_method_post = - (info_.share_target->method == ShareTarget::kPost); + (info_.share_target->method == + blink::Manifest::ShareTarget::Method::kPost); java_share_params_is_enctype_multipart = - (info_.share_target->enctype == ShareTarget::kMultipart); + (info_.share_target->enctype == + blink::Manifest::ShareTarget::Enctype::kMultipartFormData); std::vector<base::string16> file_names; std::vector<std::vector<base::string16>> accepts;
diff --git a/chrome/browser/android/webapk/webapk_update_manager.cc b/chrome/browser/android/webapk/webapk_update_manager.cc index 9bacd43..b8b4a85 100644 --- a/chrome/browser/android/webapk/webapk_update_manager.cc +++ b/chrome/browser/android/webapk/webapk_update_manager.cc
@@ -25,8 +25,8 @@ #include "ui/gfx/android/java_bitmap.h" #include "url/gurl.h" -using base::android::JavaRef; using base::android::JavaParamRef; +using base::android::JavaRef; using base::android::ScopedJavaGlobalRef; namespace { @@ -108,13 +108,14 @@ info.share_target->params.url = ConvertJavaStringToUTF16(java_share_target_param_url); info.share_target->method = - java_share_target_param_is_method_post == JNI_TRUE ? ShareTarget::kPost - : ShareTarget::kGet; + java_share_target_param_is_method_post == JNI_TRUE + ? blink::Manifest::ShareTarget::Method::kPost + : blink::Manifest::ShareTarget::Method::kGet; info.share_target->enctype = java_share_target_param_is_enctype_multipart == JNI_TRUE - ? ShareTarget::kMultipart - : ShareTarget::kApplication; + ? blink::Manifest::ShareTarget::Enctype::kMultipartFormData + : blink::Manifest::ShareTarget::Enctype::kFormUrlEncoded; std::vector<base::string16> fileNames; base::android::AppendJavaStringArrayToStringVector(
diff --git a/chrome/browser/background_fetch/background_fetch_browsertest.cc b/chrome/browser/background_fetch/background_fetch_browsertest.cc index 03ab326..93160bee 100644 --- a/chrome/browser/background_fetch/background_fetch_browsertest.cc +++ b/chrome/browser/background_fetch/background_fetch_browsertest.cc
@@ -242,7 +242,8 @@ download_observer_ = std::make_unique<WaitableDownloadLoggerObserver>(); - download_service_ = DownloadServiceFactory::GetForBrowserContext(profile); + download_service_ = + DownloadServiceFactory::GetForKey(profile->GetProfileKey()); download_service_->GetLogger()->AddObserver(download_observer_.get()); // Register our observer for the offline items collection.
diff --git a/chrome/browser/background_fetch/background_fetch_delegate_impl.cc b/chrome/browser/background_fetch/background_fetch_delegate_impl.cc index 41daf80..866ea78 100644 --- a/chrome/browser/background_fetch/background_fetch_delegate_impl.cc +++ b/chrome/browser/background_fetch/background_fetch_delegate_impl.cc
@@ -71,8 +71,8 @@ if (download_service_) return download_service_; - download_service_ = - DownloadServiceFactory::GetInstance()->GetForBrowserContext(profile_); + download_service_ = DownloadServiceFactory::GetInstance()->GetForKey( + profile_->GetProfileKey()); return download_service_; }
diff --git a/chrome/browser/browser_process.h b/chrome/browser/browser_process.h index 761d300..c2f0bc6 100644 --- a/chrome/browser/browser_process.h +++ b/chrome/browser/browser_process.h
@@ -129,9 +129,6 @@ BrowserProcess(); virtual ~BrowserProcess(); - // Called when the ResourceDispatcherHost object is created by content. - virtual void ResourceDispatcherHostCreated() = 0; - // Invoked when the user is logging out/shutting down. When logging off we may // not have enough time to do a normal shutdown. This method is invoked prior // to normal shutdown and saves any state that must be saved before system
diff --git a/chrome/browser/browser_process_impl.cc b/chrome/browser/browser_process_impl.cc index 19c10046..5c707ec 100644 --- a/chrome/browser/browser_process_impl.cc +++ b/chrome/browser/browser_process_impl.cc
@@ -52,7 +52,6 @@ #include "chrome/browser/io_thread.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/lifetime/switch_utils.h" -#include "chrome/browser/loader/chrome_resource_dispatcher_host_delegate.h" #include "chrome/browser/media/webrtc/webrtc_event_log_manager.h" #include "chrome/browser/media/webrtc/webrtc_log_uploader.h" #include "chrome/browser/metrics/chrome_feature_list_creator.h" @@ -129,7 +128,6 @@ #include "content/public/browser/notification_details.h" #include "content/public/browser/plugin_service.h" #include "content/public/browser/render_process_host.h" -#include "content/public/browser/resource_dispatcher_host.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/content_features.h" @@ -221,7 +219,6 @@ using content::BrowserThread; using content::ChildProcessSecurityPolicy; using content::PluginService; -using content::ResourceDispatcherHost; rappor::RapporService* GetBrowserRapporService() { if (g_browser_process != nullptr) @@ -1098,13 +1095,6 @@ return supervised_user_whitelist_installer_.get(); } -void BrowserProcessImpl::ResourceDispatcherHostCreated() { - resource_dispatcher_host_delegate_ = - std::make_unique<ChromeResourceDispatcherHostDelegate>(); - ResourceDispatcherHost::Get()->SetDelegate( - resource_dispatcher_host_delegate_.get()); -} - void BrowserProcessImpl::OnKeepAliveStateChanged(bool is_keeping_alive) { if (is_keeping_alive) Pin();
diff --git a/chrome/browser/browser_process_impl.h b/chrome/browser/browser_process_impl.h index f7d7dbd..206ede7 100644 --- a/chrome/browser/browser_process_impl.h +++ b/chrome/browser/browser_process_impl.h
@@ -39,7 +39,6 @@ class ChromeChildProcessWatcher; class ChromeFeatureListCreator; class ChromeMetricsServicesManagerClient; -class ChromeResourceDispatcherHostDelegate; class DevToolsAutoOpener; class RemoteDebuggingServer; class PrefRegistrySimple; @@ -136,7 +135,6 @@ metrics_services_manager::MetricsServicesManagerClient* client); // BrowserProcess implementation. - void ResourceDispatcherHostCreated() override; void EndSession() override; void FlushLocalStateAndReply(base::OnceClosure reply) override; metrics_services_manager::MetricsServicesManager* GetMetricsServicesManager() @@ -370,9 +368,6 @@ std::unique_ptr<BatteryMetrics> battery_metrics_; - std::unique_ptr<ChromeResourceDispatcherHostDelegate> - resource_dispatcher_host_delegate_; - #if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) base::RepeatingTimer autoupdate_timer_;
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index b5c53b09..99141ce 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -51,6 +51,8 @@ #include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/content_settings/tab_specific_content_settings.h" +#include "chrome/browser/custom_handlers/protocol_handler_registry.h" +#include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h" #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings.h" #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings_factory.h" #include "chrome/browser/data_use_measurement/chrome_data_use_measurement.h" @@ -1055,6 +1057,14 @@ return; } + // Do not launch external requests for schemes that have a handler registered. + ProtocolHandlerRegistry* protocol_handler_registry = + ProtocolHandlerRegistryFactory::GetForBrowserContext( + web_contents->GetBrowserContext()); + if (protocol_handler_registry && + protocol_handler_registry->IsHandledProtocol(url.scheme())) + return; + bool is_whitelisted = false; PolicyBlacklistService* service = PolicyBlacklistFactory::GetForBrowserContext( @@ -3108,12 +3118,8 @@ void ChromeContentBrowserClient::ResourceDispatcherHostCreated() { DCHECK_CURRENTLY_ON(BrowserThread::UI); + // TODO(jam): move this creation elsewhere so we can remove this method. safe_browsing_service_ = g_browser_process->safe_browsing_service(); - - for (size_t i = 0; i < extra_parts_.size(); ++i) - extra_parts_[i]->ResourceDispatcherHostCreated(); - - return g_browser_process->ResourceDispatcherHostCreated(); } content::SpeechRecognitionManagerDelegate*
diff --git a/chrome/browser/chrome_content_browser_client_parts.h b/chrome/browser/chrome_content_browser_client_parts.h index d794bff8..aa9976ef 100644 --- a/chrome/browser/chrome_content_browser_client_parts.h +++ b/chrome/browser/chrome_content_browser_client_parts.h
@@ -65,9 +65,6 @@ content::RenderProcessHost* process, Profile* profile) {} - // Called when the ResourceDispatcherHost is created. - virtual void ResourceDispatcherHostCreated() {} - // Allows to register browser interfaces exposed through the // RenderProcessHost. Note that interface factory callbacks added to // |registry| will by default be run immediately on the IO thread, unless a
diff --git a/chrome/browser/chromeos/arc/print/arc_print_service.cc b/chrome/browser/chromeos/arc/print/arc_print_service.cc index ce039a3..e0d2f89 100644 --- a/chrome/browser/chromeos/arc/print/arc_print_service.cc +++ b/chrome/browser/chromeos/arc/print/arc_print_service.cc
@@ -27,6 +27,7 @@ #include "chrome/browser/chromeos/printing/printer_configurer.h" #include "chrome/browser/printing/print_job.h" #include "chrome/browser/printing/print_job_worker.h" +#include "chrome/browser/printing/printer_query.h" #include "chrome/browser/profiles/profile.h" #include "components/arc/arc_browser_context_keyed_service_factory_base.h" #include "components/arc/session/arc_bridge_service.h"
diff --git a/chrome/browser/chromeos/kiosk_next_home/kiosk_next_home_browsertest.cc b/chrome/browser/chromeos/kiosk_next_home/kiosk_next_home_browsertest.cc new file mode 100644 index 0000000..5a89363 --- /dev/null +++ b/chrome/browser/chromeos/kiosk_next_home/kiosk_next_home_browsertest.cc
@@ -0,0 +1,307 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <memory> + +#include "apps/launcher.h" +#include "apps/test/app_window_waiter.h" +#include "ash/public/cpp/ash_features.h" +#include "base/strings/utf_string_conversions.h" +#include "base/test/test_timeouts.h" +#include "chrome/browser/chromeos/login/mixin_based_in_process_browser_test.h" +#include "chrome/browser/chromeos/login/session/user_session_manager.h" +#include "chrome/browser/chromeos/login/session/user_session_manager_test_api.h" +#include "chrome/browser/chromeos/login/test/embedded_test_server_mixin.h" +#include "chrome/browser/chromeos/login/test/fake_gaia_mixin.h" +#include "chrome/browser/chromeos/login/test/login_manager_mixin.h" +#include "chrome/browser/chromeos/profiles/profile_helper.h" +#include "chrome/browser/extensions/component_loader.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/common/extensions/extension_constants.h" +#include "chromeos/login/auth/user_context.h" +#include "components/account_id/account_id.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 "content/public/test/browser_test_utils.h" +#include "content/public/test/test_utils.h" +#include "extensions/browser/app_window/app_window.h" +#include "extensions/browser/app_window/app_window_registry.h" +#include "extensions/browser/extension_registry.h" +#include "extensions/common/constants.h" +#include "net/dns/mock_host_resolver.h" + +namespace chromeos { +namespace kiosk_next_home { + +namespace { + +const char* kTestUserGivenName = "Test User"; +const char* kTestUserDisplayName = "Test User Full Name"; +const char* kTestUser = "test-user@gmail.com"; +const char* kTestUserGaiaId = "1234567890"; + +// Helper class to wait until WebContents finishes loading. +class WebContentsLoadFinishedWaiter : public content::WebContentsObserver { + public: + explicit WebContentsLoadFinishedWaiter(content::WebContents* web_contents) + : content::WebContentsObserver(web_contents) {} + ~WebContentsLoadFinishedWaiter() override = default; + + void Wait() { + if (!web_contents()->IsLoading()) + return; + + run_loop_ = std::make_unique<base::RunLoop>(); + run_loop_->Run(); + } + + private: + void DidFinishLoad(content::RenderFrameHost* render_frame_host, + const GURL& url) override { + if (run_loop_) + run_loop_->Quit(); + } + + std::unique_ptr<base::RunLoop> run_loop_; + + DISALLOW_COPY_AND_ASSIGN(WebContentsLoadFinishedWaiter); +}; + +} // namespace + +// Integration test for Kiosk Next Home app, exercising the Chrome <-> Mojo <-> +// JavaScript bridge interaction. This ensures the services backing Kiosk Next +// Home are accessible and that the generated Mojo JS code is working. +class KioskNextHomeBrowserTest : public MixinBasedInProcessBrowserTest { + public: + KioskNextHomeBrowserTest() { set_exit_when_last_browser_closes(false); } + + void SetUp() override { + feature_list_.InitAndEnableFeature(ash::features::kKioskNextShell); + MixinBasedInProcessBrowserTest::SetUp(); + } + + void SetUpOnMainThread() override { + host_resolver()->AddRule("*", "127.0.0.1"); + + // Enable all component extensions. + extensions::ComponentLoader::EnableBackgroundExtensionsForTesting(); + + test::UserSessionManagerTestApi session_manager_test_api( + UserSessionManager::GetInstance()); + session_manager_test_api.SetShouldObtainTokenHandleInTests(false); + login_manager_mixin_.LoginAndWaitForActiveSession(GetUserContext()); + + MixinBasedInProcessBrowserTest::SetUpOnMainThread(); + + LaunchKioskNextHome(); + } + + protected: + virtual UserContext GetUserContext() const { + return LoginManagerMixin::CreateDefaultUserContext(test_user_); + } + + void RunJS(const std::string& js_script) { + EXPECT_TRUE(content::ExecuteScript(app_render_frame_host_, js_script)); + } + + // Runs JavaScript code in the app's render frame host. To extract the string + // result, the code must call 'domAutomationController.send(result)' with the + // desired result, otherwise it will hang until timeout. + std::string RunJSAndGetStringResult(const std::string& js_script) { + std::string result; + EXPECT_TRUE(content::ExecuteScriptAndExtractString(app_render_frame_host_, + js_script, &result)); + return result; + } + + LoginManagerMixin::TestUserInfo test_user_{ + AccountId::FromUserEmailGaiaId(kTestUser, kTestUserGaiaId)}; + + private: + void LaunchKioskNextHome() { + Profile* profile = ProfileManager::GetActiveUserProfile(); + // Get reference to Kiosk Next Home app. + const extensions::Extension* app = + extensions::ExtensionRegistry::Get(profile)->GetInstalledExtension( + extension_misc::kKioskNextHomeAppId); + ASSERT_TRUE(app); + + // Launch app and wait for its window. + apps::LaunchPlatformApp( + profile, app, extensions::AppLaunchSource::SOURCE_CHROME_INTERNAL); + apps::AppWindowWaiter app_waiter( + extensions::AppWindowRegistry::Get(profile), + extension_misc::kKioskNextHomeAppId); + extensions::AppWindow* window = + app_waiter.WaitForShownWithTimeout(TestTimeouts::action_timeout()); + ASSERT_TRUE(window); + + // Wait for web contents to fully load. + WebContentsLoadFinishedWaiter web_contents_waiter( + window->app_window_contents_for_test()->GetWebContents()); + web_contents_waiter.Wait(); + app_render_frame_host_ = window->app_window_contents_for_test() + ->GetWebContents() + ->GetMainFrame(); + ASSERT_TRUE(app_render_frame_host_); + } + + base::test::ScopedFeatureList feature_list_; + LoginManagerMixin login_manager_mixin_{&mixin_host_, {test_user_}}; + EmbeddedTestServerSetupMixin embedded_test_server_{&mixin_host_, + embedded_test_server()}; + content::RenderFrameHost* app_render_frame_host_; + + DISALLOW_COPY_AND_ASSIGN(KioskNextHomeBrowserTest); +}; + +IN_PROC_BROWSER_TEST_F(KioskNextHomeBrowserTest, LaunchIntent) { + // Intents are not allowed by default. + std::string error_message = RunJSAndGetStringResult( + R"(kioskNextHome.getChromeOsBridge().launchIntent('test.intent') + .catch(error => domAutomationController.send(error)))"); + EXPECT_EQ("Intent not allowed.", error_message); +} + +IN_PROC_BROWSER_TEST_F(KioskNextHomeBrowserTest, GetApps) { + // Perform checks on apps on JS side and verify a summary of possible errors, + // which is simpler than piping apps and representing them in C++ code. + std::string error_message = RunJSAndGetStringResult( + R"(kioskNextHome.getChromeOsBridge().getApps().then(apps => { + const errorMessages = []; + if (!apps) { + errorMessages.push('No apps returned.'); + } + apps.forEach(app => { + if (!app.appId) { + errorMessages.push('Missing app id.'); + } + if (!app.displayName) { + errorMessages.push('Missing app display name.'); + } + if (!app.thumbnailImage || + !app.thumbnailImage.startsWith('chrome://app-icon')) { + errorMessages.push('Invalid or missing app thumbnail: ' + + app.thumbnailImage); + } + if (app.readiness == kioskNextHome.AppReadiness.UNKNOWN) { + errorMessages.push( + 'Got unknown readiness for app id ' + app.appId); + } + if (app.type == kioskNextHome.AppType.UNKNOWN) { + errorMessages.push( + 'Got unknown type for app id ' + app.appId); + } + }); + domAutomationController.send(errorMessages.join('\n')); + }))"); + EXPECT_TRUE(error_message.empty()) + << "Found errors in GetApps response: " << std::endl + << error_message; + + // Get a semicolon separated list of app ids. + std::string app_ids = RunJSAndGetStringResult( + R"(kioskNextHome.getChromeOsBridge().getApps().then(apps => { + const appIds = []; + apps.forEach(app => appIds.push(app.appId)); + domAutomationController.send(appIds.join(';')); + }))"); + // Check that Files Manager's id is present. + EXPECT_TRUE(app_ids.find(extension_misc::kFilesManagerAppId) != + std::string::npos); + // Check that Kiosk Next Home's own id is *not* present. + EXPECT_TRUE(app_ids.find(extension_misc::kKioskNextHomeAppId) == + std::string::npos); +} + +IN_PROC_BROWSER_TEST_F(KioskNextHomeBrowserTest, LaunchApp) { + RunJS(content::JsReplace("kioskNextHome.getChromeOsBridge().launchApp($1)", + extension_misc::kFilesManagerAppId)); + apps::AppWindowWaiter files_manager_waiter( + extensions::AppWindowRegistry::Get( + ProfileManager::GetActiveUserProfile()), + extension_misc::kFilesManagerAppId); + EXPECT_TRUE(files_manager_waiter.WaitForShownWithTimeout( + TestTimeouts::action_timeout())); +} + +// Fixture variant that sets up additional user information for +// GetUser(Given|Display)Name methods. +class KioskNextHomeUserInfoBrowserTest : public KioskNextHomeBrowserTest { + public: + KioskNextHomeUserInfoBrowserTest() = default; + + void SetUpOnMainThread() override { + user_manager::UserManager::Get()->UpdateUserAccountData( + test_user_.account_id, user_manager::UserManager::UserAccountData( + base::ASCIIToUTF16(kTestUserDisplayName), + base::ASCIIToUTF16(kTestUserGivenName), + std::string() /* locale */)); + + KioskNextHomeBrowserTest::SetUpOnMainThread(); + } + + private: + DISALLOW_COPY_AND_ASSIGN(KioskNextHomeUserInfoBrowserTest); +}; + +IN_PROC_BROWSER_TEST_F(KioskNextHomeUserInfoBrowserTest, GetUserGivenName) { + std::string given_name = RunJSAndGetStringResult( + R"(kioskNextHome.getChromeOsBridge().getUserGivenName() + .then(name => domAutomationController.send(name)))"); + EXPECT_EQ(kTestUserGivenName, given_name); +} + +IN_PROC_BROWSER_TEST_F(KioskNextHomeUserInfoBrowserTest, GetUserDisplayName) { + std::string display_name = RunJSAndGetStringResult( + R"(kioskNextHome.getChromeOsBridge().getUserDisplayName() + .then(name => domAutomationController.send(name)))"); + EXPECT_EQ(kTestUserDisplayName, display_name); +} + +// Fixture variant that sets up a fake refresh token needed to issue access +// tokens and access account info via IdentityAccessor. +class KioskNextHomeRefreshTokenBrowserTest : public KioskNextHomeBrowserTest { + public: + KioskNextHomeRefreshTokenBrowserTest() = default; + + void SetUpOnMainThread() override { + fake_gaia_.SetupFakeGaiaForLogin(kTestUser, kTestUserGaiaId, + FakeGaiaMixin::kFakeRefreshToken); + + KioskNextHomeBrowserTest::SetUpOnMainThread(); + } + + UserContext GetUserContext() const override { + UserContext user_context = KioskNextHomeBrowserTest::GetUserContext(); + user_context.SetRefreshToken(FakeGaiaMixin::kFakeRefreshToken); + return user_context; + } + + private: + FakeGaiaMixin fake_gaia_{&mixin_host_, embedded_test_server()}; + + DISALLOW_COPY_AND_ASSIGN(KioskNextHomeRefreshTokenBrowserTest); +}; + +IN_PROC_BROWSER_TEST_F(KioskNextHomeRefreshTokenBrowserTest, GetAccessToken) { + std::string access_token = RunJSAndGetStringResult( + R"(kioskNextHome.getChromeOsBridge().getAccessToken(['fake_scope']) + .then(token => domAutomationController.send(token)))"); + EXPECT_EQ(access_token, FakeGaiaMixin::kFakeAllScopeAccessToken); +} + +IN_PROC_BROWSER_TEST_F(KioskNextHomeRefreshTokenBrowserTest, GetAccountId) { + std::string id = RunJSAndGetStringResult( + R"(kioskNextHome.getChromeOsBridge().getAccountId() + .then(id => domAutomationController.send(id)))"); + EXPECT_EQ(kTestUserGaiaId, id); +} + +} // namespace kiosk_next_home +} // namespace chromeos
diff --git a/chrome/browser/chromeos/plugin_vm/plugin_vm_image_download_client.cc b/chrome/browser/chromeos/plugin_vm/plugin_vm_image_download_client.cc index 320c16d..6b94100d 100644 --- a/chrome/browser/chromeos/plugin_vm/plugin_vm_image_download_client.cc +++ b/chrome/browser/chromeos/plugin_vm/plugin_vm_image_download_client.cc
@@ -34,8 +34,8 @@ for (const auto& download : downloads) { VLOG(1) << "Download tracked by DownloadService: " << download.guid; old_downloads_.insert(download.guid); - DownloadServiceFactory::GetForBrowserContext(profile_)->CancelDownload( - download.guid); + DownloadServiceFactory::GetForKey(profile_->GetProfileKey()) + ->CancelDownload(download.guid); } } @@ -51,8 +51,8 @@ // We do not want downloads that are tracked by download service from its // initialization to proceed. if (old_downloads_.find(guid) != old_downloads_.end()) { - DownloadServiceFactory::GetForBrowserContext(profile_)->CancelDownload( - guid); + DownloadServiceFactory::GetForKey(profile_->GetProfileKey()) + ->CancelDownload(guid); return; }
diff --git a/chrome/browser/chromeos/plugin_vm/plugin_vm_image_manager.cc b/chrome/browser/chromeos/plugin_vm/plugin_vm_image_manager.cc index d96bee7..4aadc6da 100644 --- a/chrome/browser/chromeos/plugin_vm/plugin_vm_image_manager.cc +++ b/chrome/browser/chromeos/plugin_vm/plugin_vm_image_manager.cc
@@ -413,7 +413,8 @@ PluginVmImageManager::PluginVmImageManager(Profile* profile) : profile_(profile), - download_service_(DownloadServiceFactory::GetForBrowserContext(profile)), + download_service_( + DownloadServiceFactory::GetForKey(profile->GetProfileKey())), weak_ptr_factory_(this) {} GURL PluginVmImageManager::GetPluginVmImageDownloadUrl() {
diff --git a/chrome/browser/component_updater/component_updater_resource_throttle.cc b/chrome/browser/component_updater/component_updater_resource_throttle.cc deleted file mode 100644 index ebe0c626d..0000000 --- a/chrome/browser/component_updater/component_updater_resource_throttle.cc +++ /dev/null
@@ -1,112 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/component_updater/component_updater_resource_throttle.h" - -#include <vector> - -#include "base/bind.h" -#include "base/location.h" -#include "base/memory/weak_ptr.h" -#include "base/task/post_task.h" -#include "components/component_updater/component_updater_service.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/resource_throttle.h" - -using content::BrowserThread; - -namespace component_updater { - -namespace { - -/////////////////////////////////////////////////////////////////////////////// -// In charge of blocking url requests until the |crx_id| component has been -// updated. This class is touched solely from the IO thread. The UI thread -// can post tasks to it via weak pointers. By default the request is blocked -// unless the CrxUpdateService calls Unblock(). -// The lifetime is controlled by Chrome's resource loader so the component -// updater cannot touch objects from this class except via weak pointers. -class CUResourceThrottle : public content::ResourceThrottle, - public base::SupportsWeakPtr<CUResourceThrottle> { - public: - CUResourceThrottle(); - ~CUResourceThrottle() override; - - // Overriden from ResourceThrottle. - void WillStartRequest(bool* defer) override; - void WillRedirectRequest(const net::RedirectInfo& redirect_info, - bool* defer) override; - const char* GetNameForLogging() override; - - // Component updater calls this function via PostTask to unblock the request. - void Unblock(); - - typedef std::vector<base::WeakPtr<CUResourceThrottle> > WeakPtrVector; - - private: - enum State { NEW, BLOCKED, UNBLOCKED }; - - State state_; -}; - -CUResourceThrottle::CUResourceThrottle() : state_(NEW) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); -} - -CUResourceThrottle::~CUResourceThrottle() { - DCHECK_CURRENTLY_ON(BrowserThread::IO); -} - -void CUResourceThrottle::WillStartRequest(bool* defer) { - if (state_ != UNBLOCKED) { - state_ = BLOCKED; - *defer = true; - } else { - *defer = false; - } -} - -void CUResourceThrottle::WillRedirectRequest( - const net::RedirectInfo& redirect_info, bool* defer) { - WillStartRequest(defer); -} - -const char* CUResourceThrottle::GetNameForLogging() { - return "ComponentUpdateResourceThrottle"; -} - -void CUResourceThrottle::Unblock() { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - if (state_ == BLOCKED) - Resume(); - state_ = UNBLOCKED; -} - -void UnblockThrottleOnUIThread(base::WeakPtr<CUResourceThrottle> rt) { - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}) - ->PostTask(FROM_HERE, base::BindOnce(&CUResourceThrottle::Unblock, rt)); -} - -} // namespace - -content::ResourceThrottle* GetOnDemandResourceThrottle( - ComponentUpdateService* cus, - const std::string& crx_id) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - - // We give the raw pointer to the caller, who will delete it at will - // and we keep for ourselves a weak pointer to it so we can post tasks - // from the UI thread without having to track lifetime directly. - CUResourceThrottle* rt = new CUResourceThrottle; - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI}) - ->PostTask(FROM_HERE, - base::BindOnce(&ComponentUpdateService::MaybeThrottle, - base::Unretained(cus), crx_id, - base::BindOnce(&UnblockThrottleOnUIThread, - rt->AsWeakPtr()))); - return rt; -} - -} // namespace component_updater
diff --git a/chrome/browser/component_updater/component_updater_resource_throttle.h b/chrome/browser/component_updater/component_updater_resource_throttle.h deleted file mode 100644 index 5a9f0a62..0000000 --- a/chrome/browser/component_updater/component_updater_resource_throttle.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_COMPONENT_UPDATER_COMPONENT_UPDATER_RESOURCE_THROTTLE_H_ -#define CHROME_BROWSER_COMPONENT_UPDATER_COMPONENT_UPDATER_RESOURCE_THROTTLE_H_ - -#include <string> - -namespace content { -class ResourceThrottle; -} - -namespace component_updater { - -class ComponentUpdateService; - -// Returns a network resource throttle. It means that a component will be -// downloaded and installed before the resource is unthrottled. This function -// can be called from the IO thread. -content::ResourceThrottle* GetOnDemandResourceThrottle( - ComponentUpdateService* cus, - const std::string& crx_id); - -} // namespace component_updater - -#endif // CHROME_BROWSER_COMPONENT_UPDATER_COMPONENT_UPDATER_RESOURCE_THROTTLE_H_
diff --git a/chrome/browser/download/download_frame_policy_browsertest.cc b/chrome/browser/download/download_frame_policy_browsertest.cc index 113957c..6d2f412 100644 --- a/chrome/browser/download/download_frame_policy_browsertest.cc +++ b/chrome/browser/download/download_frame_policy_browsertest.cc
@@ -32,7 +32,6 @@ #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/controllable_http_response.h" #include "net/test/embedded_test_server/embedded_test_server.h" -#include "services/network/public/cpp/features.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/features.h" #include "url/gurl.h" @@ -766,48 +765,6 @@ SandboxOption::kAllowDownloadsWithoutUserActivation), ::testing::Bool())); -class DefaultBlockSandboxDownloadBrowserTest - : public DownloadFramePolicyBrowserTest { - public: - DefaultBlockSandboxDownloadBrowserTest() { - scoped_feature_list_.InitAndDisableFeature( - network::features::kNetworkService); - } - - ~DefaultBlockSandboxDownloadBrowserTest() override = default; - - void SetUpCommandLine(base::CommandLine* command_line) override { - SetRuntimeFeatureCommand( - true, "BlockingDownloadsInSandboxWithoutUserActivation", command_line); - } - - private: - base::test::ScopedFeatureList scoped_feature_list_; -}; - -// To test PDF works fine when the policy disallows just download, which -// essentially tests that the appropriate ResourceInterceptPolicy -// |kAllowPluginOnly| is set for resource handling. -// -// When NetworkService is disabled and when ResourceInterceptPolicy has been -// incorrectly set to |kAllowNone|, no stream interceptor will be set up to -// handle the PDF content, and the content will instead be sent to the renderer -// where a UTF-8 GUID is expected to arrive. It'll then hit a DCHECK checking -// the UTF-8-ness of the GUID. -// -// TODO(yaoxia): Use a more straightforward approach to assert that the pdf -// content displays fine rather than relying on the DCHECK failure that would -// happen with an incorrect implementation. -IN_PROC_BROWSER_TEST_F(DefaultBlockSandboxDownloadBrowserTest, PdfNotBlocked) { - InitializeOneSubframeSetup( - SandboxOption::kDisallowDownloadsWithoutUserActivation, - false /* is_ad_frame */, false /* is_cross_origin */); - content::TestNavigationObserver navigation_observer(web_contents()); - EXPECT_TRUE(ExecuteScriptWithoutUserGesture(GetSubframeRfh(), - "top.location = 'test.pdf';")); - navigation_observer.Wait(); -} - // Download gets blocked when LoadPolicy is DISALLOW for the navigation to // download. This test is technically unrelated to policy on frame, but stays // here for convenience.
diff --git a/chrome/browser/download/download_resource_throttle.cc b/chrome/browser/download/download_resource_throttle.cc deleted file mode 100644 index 6b0f71a5..0000000 --- a/chrome/browser/download/download_resource_throttle.cc +++ /dev/null
@@ -1,163 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/download/download_resource_throttle.h" - -#include <utility> - -#include "base/bind.h" -#include "base/task/post_task.h" -#include "build/build_config.h" -#include "chrome/browser/download/download_stats.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" - -#if defined(OS_ANDROID) -#include "chrome/browser/android/download/download_controller_base.h" -#include "content/public/browser/render_view_host.h" -#endif - -using content::BrowserThread; - -namespace { - -void OnCanDownloadDecided(base::WeakPtr<DownloadResourceThrottle> throttle, - bool storage_permission_granted, bool allow) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&DownloadResourceThrottle::ContinueDownload, throttle, - storage_permission_granted, allow)); -} - -void CanDownload( - std::unique_ptr<DownloadResourceThrottle::DownloadRequestInfo> info) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - info->limiter->CanDownload(info->web_contents_getter, info->url, - info->request_method, - base::Bind(info->continue_callback, true)); -} - -#if defined(OS_ANDROID) -void OnThrottleAcquireFileAccessPermissionDone( - std::unique_ptr<DownloadResourceThrottle::DownloadRequestInfo> info, - bool granted) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (granted) - CanDownload(std::move(info)); - else - info->continue_callback.Run(false, false); -} -#endif - -void CanDownloadOnUIThread( - std::unique_ptr<DownloadResourceThrottle::DownloadRequestInfo> info) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); -#if defined(OS_ANDROID) - const content::ResourceRequestInfo::WebContentsGetter& web_contents_getter = - info->web_contents_getter; - DownloadControllerBase::Get()->AcquireFileAccessPermission( - web_contents_getter, - base::Bind(&OnThrottleAcquireFileAccessPermissionDone, - base::Passed(std::move(info)))); -#else - CanDownload(std::move(info)); -#endif -} - -} // namespace - -DownloadResourceThrottle::DownloadRequestInfo::DownloadRequestInfo( - scoped_refptr<DownloadRequestLimiter> limiter, - const content::ResourceRequestInfo::WebContentsGetter& web_contents_getter, - const GURL& url, - const std::string& request_method, - const DownloadRequestInfo::Callback& continue_callback) - : limiter(limiter), - web_contents_getter(web_contents_getter), - url(url), - request_method(request_method), - continue_callback(continue_callback) {} - -DownloadResourceThrottle::DownloadRequestInfo::~DownloadRequestInfo() {} - -DownloadResourceThrottle::DownloadResourceThrottle( - scoped_refptr<DownloadRequestLimiter> limiter, - const content::ResourceRequestInfo::WebContentsGetter& web_contents_getter, - const GURL& url, - const std::string& request_method) - : querying_limiter_(true), - request_allowed_(false), - request_deferred_(false) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce( - &CanDownloadOnUIThread, - std::unique_ptr<DownloadRequestInfo>(new DownloadRequestInfo( - limiter, web_contents_getter, url, request_method, - base::Bind(&OnCanDownloadDecided, AsWeakPtr()))))); -} - -DownloadResourceThrottle::~DownloadResourceThrottle() { -} - -void DownloadResourceThrottle::WillStartRequest(bool* defer) { - WillDownload(defer); -} - -void DownloadResourceThrottle::WillRedirectRequest( - const net::RedirectInfo& redirect_info, - bool* defer) { - WillDownload(defer); -} - -void DownloadResourceThrottle::WillProcessResponse(bool* defer) { - WillDownload(defer); -} - -const char* DownloadResourceThrottle::GetNameForLogging() { - return "DownloadResourceThrottle"; -} - -void DownloadResourceThrottle::WillDownload(bool* defer) { - DCHECK(!request_deferred_); - - // Defer the download until we have the DownloadRequestLimiter result. - if (querying_limiter_) { - request_deferred_ = true; - *defer = true; - return; - } - - if (!request_allowed_) { - RecordDownloadCount(CHROME_DOWNLOAD_COUNT_BLOCKED_BY_THROTTLING); - Cancel(); - } -} - -void DownloadResourceThrottle::ContinueDownload( - bool storage_permission_granted, bool allow) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - querying_limiter_ = false; - request_allowed_ = allow; - - if (!storage_permission_granted) { - // UMA for this will be recorded in MobileDownload.StoragePermission. - } else if (allow) { - // Presumes all downloads initiated by navigation use this throttle and - // nothing else does. - RecordDownloadSource(DOWNLOAD_INITIATED_BY_NAVIGATION); - } else { - RecordDownloadCount(CHROME_DOWNLOAD_COUNT_BLOCKED_BY_THROTTLING); - } - - if (request_deferred_) { - request_deferred_ = false; - if (allow) { - Resume(); - } else { - Cancel(); - } - } -}
diff --git a/chrome/browser/download/download_resource_throttle.h b/chrome/browser/download/download_resource_throttle.h deleted file mode 100644 index fc451416..0000000 --- a/chrome/browser/download/download_resource_throttle.h +++ /dev/null
@@ -1,84 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_DOWNLOAD_DOWNLOAD_RESOURCE_THROTTLE_H_ -#define CHROME_BROWSER_DOWNLOAD_DOWNLOAD_RESOURCE_THROTTLE_H_ - -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "chrome/browser/download/download_request_limiter.h" -#include "content/public/browser/resource_throttle.h" - -class GURL; - -// DownloadResourceThrottle is used to determine if a download should be -// allowed. When a DownloadResourceThrottle is created it pauses the download -// and asks the DownloadRequestLimiter if the download should be allowed. The -// DownloadRequestLimiter notifies us asynchronously as to whether the download -// is allowed or not. If the download is allowed the request is resumed. If -// the download is not allowed the request is canceled. - -class DownloadResourceThrottle - : public content::ResourceThrottle, - public base::SupportsWeakPtr<DownloadResourceThrottle> { - public: - // Information passed between callbacks to check whether download can proceed. - struct DownloadRequestInfo { - // Callback that is called on whether download can proceed. - // The boolean parameters indicate whether or not the download is allowed, - // and whether storage permission is granted - typedef base::Callback<void( - bool /* storage permission granted */, bool /*allow*/)> Callback; - - DownloadRequestInfo( - scoped_refptr<DownloadRequestLimiter> limiter, - const content::ResourceRequestInfo::WebContentsGetter& - web_contents_getter, - const GURL& url, - const std::string& request_method, - const Callback& continue_callback); - ~DownloadRequestInfo(); - - scoped_refptr<DownloadRequestLimiter> limiter; - content::ResourceRequestInfo::WebContentsGetter web_contents_getter; - GURL url; - std::string request_method; - Callback continue_callback; - private: - DISALLOW_COPY_AND_ASSIGN(DownloadRequestInfo); - }; - - DownloadResourceThrottle( - scoped_refptr<DownloadRequestLimiter> limiter, - const content::ResourceRequestInfo::WebContentsGetter& - web_contents_getter, - const GURL& url, - const std::string& request_method); - ~DownloadResourceThrottle() override; - - // content::ResourceThrottle implementation: - void WillStartRequest(bool* defer) override; - void WillRedirectRequest(const net::RedirectInfo& redirect_info, - bool* defer) override; - void WillProcessResponse(bool* defer) override; - const char* GetNameForLogging() override; - - void ContinueDownload(bool storage_permission_granted, bool allow); - - private: - void WillDownload(bool* defer); - - // Set to true when we are querying the DownloadRequestLimiter. - bool querying_limiter_; - - // Set to true when we know that the request is allowed to start. - bool request_allowed_; - - // Set to true when we have deferred the request. - bool request_deferred_; - - DISALLOW_COPY_AND_ASSIGN(DownloadResourceThrottle); -}; - -#endif // CHROME_BROWSER_DOWNLOAD_DOWNLOAD_RESOURCE_THROTTLE_H_
diff --git a/chrome/browser/download/download_resource_throttle_unittest.cc b/chrome/browser/download/download_resource_throttle_unittest.cc deleted file mode 100644 index b1b3c7a..0000000 --- a/chrome/browser/download/download_resource_throttle_unittest.cc +++ /dev/null
@@ -1,128 +0,0 @@ -// Copyright (c) 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 "chrome/browser/download/download_resource_throttle.h" -#include "base/bind.h" -#include "base/run_loop.h" -#include "base/task/post_task.h" -#include "chrome/browser/download/download_request_limiter.h" -#include "chrome/browser/tab_contents/tab_util.h" -#include "chrome/test/base/chrome_render_view_host_test_harness.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/render_process_host.h" -#include "content/public/browser/resource_throttle.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_contents_delegate.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -#if defined(OS_ANDROID) -#include "chrome/browser/android/download/mock_download_controller.h" -#endif - -namespace { - -const char kTestUrl[] = "http://www.example.com/"; - -} // namespace - -class MockWebContentsDelegate : public content::WebContentsDelegate { - public: - MockWebContentsDelegate() {} - ~MockWebContentsDelegate() override {} -}; - -class MockResourceThrottleDelegate - : public content::ResourceThrottle::Delegate { - public: - MOCK_METHOD0(Cancel, void()); - MOCK_METHOD0(CancelAndIgnore, void()); - MOCK_METHOD1(CancelWithError, void(int)); - MOCK_METHOD0(Resume, void()); -}; - -// Posts |quit_closure| to UI thread. -ACTION_P(QuitLoop, quit_closure) { - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - quit_closure); -} - -class DownloadResourceThrottleTest : public ChromeRenderViewHostTestHarness { - public: - DownloadResourceThrottleTest() - : ChromeRenderViewHostTestHarness( - content::TestBrowserThreadBundle::REAL_IO_THREAD), - throttle_(nullptr), - limiter_(new DownloadRequestLimiter()) {} - - ~DownloadResourceThrottleTest() override {} - - void SetUp() override { - ChromeRenderViewHostTestHarness::SetUp(); - web_contents()->SetDelegate(&delegate_); - run_loop_.reset(new base::RunLoop()); -#if defined(OS_ANDROID) - DownloadControllerBase::SetDownloadControllerBase(&download_controller_); -#endif - } - - void TearDown() override { - content::BrowserThread::DeleteSoon(content::BrowserThread::IO, FROM_HERE, - throttle_); -#if defined(OS_ANDROID) - DownloadControllerBase::SetDownloadControllerBase(nullptr); -#endif - ChromeRenderViewHostTestHarness::TearDown(); - } - - void StartThrottleOnIOThread(int process_id, int render_view_id) { - throttle_ = new DownloadResourceThrottle( - limiter_, - base::Bind(&tab_util::GetWebContentsByID, process_id, render_view_id), - GURL(kTestUrl), "GET"); - throttle_->set_delegate_for_testing(&resource_throttle_delegate_); - bool defer; - throttle_->WillStartRequest(&defer); - EXPECT_EQ(true, defer); - } - - void StartThrottle() { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce( - &DownloadResourceThrottleTest::StartThrottleOnIOThread, - base::Unretained(this), - web_contents()->GetRenderViewHost()->GetProcess()->GetID(), - web_contents()->GetRenderViewHost()->GetRoutingID())); - run_loop_->Run(); - } - - protected: - content::ResourceThrottle* throttle_; - MockWebContentsDelegate delegate_; - scoped_refptr<DownloadRequestLimiter> limiter_; - ::testing::NiceMock<MockResourceThrottleDelegate> resource_throttle_delegate_; - std::unique_ptr<base::RunLoop> run_loop_; -#if defined(OS_ANDROID) - chrome::android::MockDownloadController download_controller_; -#endif -}; - -TEST_F(DownloadResourceThrottleTest, StartDownloadThrottle_Basic) { - EXPECT_CALL(resource_throttle_delegate_, Resume()) - .WillOnce(QuitLoop(run_loop_->QuitClosure())); - StartThrottle(); -} - -#if defined(OS_ANDROID) -TEST_F(DownloadResourceThrottleTest, DownloadWithFailedFileAcecssRequest) { - DownloadControllerBase::Get() - ->SetApproveFileAccessRequestForTesting(false); - EXPECT_CALL(resource_throttle_delegate_, Cancel()) - .WillOnce(QuitLoop(run_loop_->QuitClosure())); - StartThrottle(); -} -#endif
diff --git a/chrome/browser/download/download_service_factory.cc b/chrome/browser/download/download_service_factory.cc index 9d060c5..4ad6462 100644 --- a/chrome/browser/download/download_service_factory.cc +++ b/chrome/browser/download/download_service_factory.cc
@@ -109,13 +109,6 @@ GetInstance()->GetServiceForKey(key, true)); } -// static -download::DownloadService* DownloadServiceFactory::GetForBrowserContext( - content::BrowserContext* context) { - Profile* profile = Profile::FromBrowserContext(context); - return GetForKey(profile->GetProfileKey()); -} - DownloadServiceFactory::DownloadServiceFactory() : SimpleKeyedServiceFactory("download::DownloadService", SimpleDependencyManager::GetInstance()) {
diff --git a/chrome/browser/download/download_service_factory.h b/chrome/browser/download/download_service_factory.h index 36db493..0bd46ecd 100644 --- a/chrome/browser/download/download_service_factory.h +++ b/chrome/browser/download/download_service_factory.h
@@ -17,10 +17,6 @@ struct DefaultSingletonTraits; } // namespace base -namespace content { -class BrowserContext; -} // namespace content - namespace download { class DownloadService; } // namespace download @@ -35,12 +31,6 @@ // Returns the DownloadService associated with |key|. static download::DownloadService* GetForKey(SimpleFactoryKey* key); - // Helper method that calls GetForKey(). - // Returns the DownloadService associated with the key associated with - // |context|. - static download::DownloadService* GetForBrowserContext( - content::BrowserContext* context); - private: friend struct base::DefaultSingletonTraits<DownloadServiceFactory>;
diff --git a/chrome/browser/download/save_page_browsertest.cc b/chrome/browser/download/save_page_browsertest.cc index 5f45081..318c8407 100644 --- a/chrome/browser/download/save_page_browsertest.cc +++ b/chrome/browser/download/save_page_browsertest.cc
@@ -495,7 +495,7 @@ content::SAVE_PAGE_TYPE_AS_ONLY_HTML)); std::vector<DownloadItem*> items; creation_observer.WaitForDownloadItem(&items); - ASSERT_TRUE(items.size() == 1); + ASSERT_EQ(1u, items.size()); // Close the tab; does this cancel the download? GetCurrentTab(browser())->Close(); @@ -1096,14 +1096,19 @@ void RunObjectElementsTest(GURL url) { content::SavePageType save_page_type = GetParam(); - // 7 comes from: + // The |expected_number_of_frames| comes from: // - main frame (frames-objects.htm) // - object with frame-nested.htm + 2 subframes (frames-nested2.htm + b.htm) // - iframe with a.htm // - object with svg.svg // - object with text.txt - // (pdf and png objects do not get a separate frame) + // - (in presence of MimeHandlerViewMode::UsesCrossProcessFrame) object with + // pdf.pdf is responsible for presence of 2 extra frames (about:blank + + // one frame for the actual pdf.pdf). These frames are an implementation + // detail and are not web-exposed (e.g. via window.frames). int expected_number_of_frames = 7; + if (content::MimeHandlerViewMode::UsesCrossProcessFrame()) + expected_number_of_frames = 9; std::vector<std::string> expected_substrings = { "frames-objects.htm: 8da13db4-a512-4d9b-b1c5-dc1c134234b9", @@ -1113,6 +1118,10 @@ "frames-nested2.htm: 6d23dc47-f283-4977-96ec-66bcf72301a4", "text-object.txt: ae52dd09-9746-4b7e-86a6-6ada5e2680c2", "svg: 0875fd06-131d-4708-95e1-861853c6b8dc", + + // TODO(lukasza): Consider also verifying presence of "PDF test file" + // from <object data="pdf.pdf">. This requires ensuring that the PDF is + // loaded before continuing with the test. }; // TODO(lukasza): crbug.com/553478: Enable <object> testing of MHTML. @@ -1135,8 +1144,8 @@ for (const auto& expected_substring : expected_substrings) { int actual_number_of_matches = ui_test_utils::FindInPage( GetCurrentTab(browser()), base::UTF8ToUTF16(expected_substring), - true, // |forward| - true, // |case_sensitive| + true, // |forward| + false, // |case_sensitive| nullptr, nullptr); EXPECT_EQ(1, actual_number_of_matches) @@ -1145,16 +1154,16 @@ } std::string forbidden_substrings[] = { - "head", // Html markup should not be visible. - "err", // "err" is a prefix of error messages + is strategically - // included in some tests in contents that should not render - // (i.e. inside of an object element and/or inside of a frame - // that should be hidden). + "head", // Html markup should not be visible. + "err", // "err" is a prefix of error messages + is strategically + // included in some tests in contents that should not render + // (i.e. inside of an object element and/or inside of a frame + // that should be hidden). }; for (const auto& forbidden_substring : forbidden_substrings) { int actual_number_of_matches = ui_test_utils::FindInPage( GetCurrentTab(browser()), base::UTF8ToUTF16(forbidden_substring), - true, // |forward| + true, // |forward| false, // |case_sensitive| nullptr, nullptr); EXPECT_EQ(0, actual_number_of_matches) @@ -1205,10 +1214,6 @@ // (see crbug.com/553478). IN_PROC_BROWSER_TEST_P(SavePageOriginalVsSavedComparisonTest, ObjectElementsViaHttp) { - // TODO(lukasza): https://crbug.com/964364: Re-enable the test. - if (content::MimeHandlerViewMode::UsesCrossProcessFrame()) - return; - GURL url( embedded_test_server()->GetURL("a.com", "/save_page/frames-objects.htm"));
diff --git a/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc b/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc index dad19b6..7ce6643 100644 --- a/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc +++ b/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc
@@ -183,85 +183,6 @@ return PRIV_EXTENSION; } -// Determines whether the extension |origin| is legal to use in an Origin header -// from the process identified by |child_id|. Returns CONTINUE if so, FAIL if -// the extension is not recognized (and may recently have been uninstalled), and -// KILL if the origin is from a platform app but the request does not come from -// that app. -content::HeaderInterceptorResult CheckOriginHeader( - content::ResourceContext* resource_context, - int child_id, - const GURL& origin) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - - // Consider non-extension URLs safe; they will be checked elsewhere. - if (!origin.SchemeIs(kExtensionScheme)) - return content::HeaderInterceptorResult::CONTINUE; - - // If there is no extension installed for the origin, it may be from a - // recently uninstalled extension. The tabs of such extensions are - // automatically closed, but subframes and content scripts may stick around. - // Fail such requests without killing the process. - // TODO(rdevlin.cronin, creis): Track which extensions have been uninstalled - // and use HeaderInterceptorResult::KILL for anything not on the list. - // See https://crbug.com/705128. - ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context); - InfoMap* extension_info_map = io_data->GetExtensionInfoMap(); - const Extension* extension = - extension_info_map->extensions().GetExtensionOrAppByURL(origin); - if (!extension) - return content::HeaderInterceptorResult::FAIL; - - // Check for platform app origins. These can only be committed by the app - // itself, or by one if its guests if it has the webview permission. - // Processes that incorrectly claim to be an app should be killed. - const ProcessMap& process_map = extension_info_map->process_map(); - if (extension->is_platform_app() && - !process_map.Contains(extension->id(), child_id)) { - // This is a platform app origin not in the app's own process. If it cannot - // create webviews, this is illegal. - if (!extension->permissions_data()->HasAPIPermission( - extensions::APIPermission::kWebView)) { - return content::HeaderInterceptorResult::KILL; - } - - // If there are accessible resources, the origin is only legal if the - // given process is a guest of the app. - std::string owner_extension_id; - int owner_process_id; - WebViewRendererState::GetInstance()->GetOwnerInfo( - child_id, &owner_process_id, &owner_extension_id); - const Extension* owner_extension = - extension_info_map->extensions().GetByID(owner_extension_id); - if (!owner_extension || owner_extension != extension) - return content::HeaderInterceptorResult::KILL; - - // It's a valid guest of the app, so allow it to proceed. - return content::HeaderInterceptorResult::CONTINUE; - } - - // With only the origin and not the full URL, we don't have enough - // information to validate hosted apps or web_accessible_resources in normal - // extensions. Assume they're legal. - return content::HeaderInterceptorResult::CONTINUE; -} - -// This callback is registered on the ResourceDispatcherHost for the chrome -// extension Origin scheme. We determine whether the extension origin is -// valid. Please see the CheckOriginHeader() function. -void OnHttpHeaderReceived(const std::string& header, - const std::string& value, - int child_id, - content::ResourceContext* resource_context, - content::OnHeaderProcessedCallback callback) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - - GURL origin(value); - DCHECK(origin.SchemeIs(extensions::kExtensionScheme)); - - callback.Run(CheckOriginHeader(resource_context, child_id, origin)); -} - const Extension* GetEnabledExtensionFromEffectiveURL( BrowserContext* context, const GURL& effective_url) { @@ -1081,9 +1002,4 @@ } } -void ChromeContentBrowserClientExtensionsPart::ResourceDispatcherHostCreated() { - content::ResourceDispatcherHost::Get()->RegisterInterceptor( - "Origin", kExtensionScheme, base::Bind(&OnHttpHeaderReceived)); -} - } // namespace extensions
diff --git a/chrome/browser/extensions/chrome_content_browser_client_extensions_part.h b/chrome/browser/extensions/chrome_content_browser_client_extensions_part.h index af99524..6dd388b 100644 --- a/chrome/browser/extensions/chrome_content_browser_client_extensions_part.h +++ b/chrome/browser/extensions/chrome_content_browser_client_extensions_part.h
@@ -155,7 +155,6 @@ base::CommandLine* command_line, content::RenderProcessHost* process, Profile* profile) override; - void ResourceDispatcherHostCreated() override; DISALLOW_COPY_AND_ASSIGN(ChromeContentBrowserClientExtensionsPart); };
diff --git a/chrome/browser/loader/chrome_resource_dispatcher_host_delegate.cc b/chrome/browser/loader/chrome_resource_dispatcher_host_delegate.cc deleted file mode 100644 index b33a3297..0000000 --- a/chrome/browser/loader/chrome_resource_dispatcher_host_delegate.cc +++ /dev/null
@@ -1,594 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/loader/chrome_resource_dispatcher_host_delegate.h" - -#include <stdint.h> -#include <string> -#include <utility> -#include <vector> - -#include "base/base64.h" -#include "base/bind.h" -#include "base/guid.h" -#include "base/logging.h" -#include "base/memory/ptr_util.h" -#include "base/metrics/histogram_macros.h" -#include "base/strings/string_util.h" -#include "base/task/post_task.h" -#include "build/build_config.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/chrome_notification_types.h" -#include "chrome/browser/component_updater/component_updater_resource_throttle.h" -#include "chrome/browser/download/download_request_limiter.h" -#include "chrome/browser/download/download_resource_throttle.h" -#include "chrome/browser/loader/chrome_navigation_data.h" -#include "chrome/browser/loader/safe_browsing_resource_throttle.h" -#include "chrome/browser/page_load_metrics/metrics_web_contents_observer.h" -#include "chrome/browser/plugins/plugin_prefs.h" -#include "chrome/browser/plugins/plugin_utils.h" -#include "chrome/browser/prerender/prerender_manager.h" -#include "chrome/browser/prerender/prerender_manager_factory.h" -#include "chrome/browser/prerender/prerender_util.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/profiles/profile_io_data.h" -#include "chrome/browser/renderer_host/chrome_navigation_ui_data.h" -#include "chrome/browser/safe_browsing/safe_browsing_service.h" -#include "chrome/browser/signin/chrome_signin_helper.h" -#include "chrome/browser/tab_contents/tab_util.h" -#include "chrome/common/buildflags.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/url_constants.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/content/browser/content_lofi_decider.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_config.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_data.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_io_data.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_util.h" -#include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h" -#include "components/google/core/common/google_util.h" -#include "components/nacl/common/buildflags.h" -#include "components/offline_pages/buildflags/buildflags.h" -#include "components/offline_pages/core/request_header/offline_page_navigation_ui_data.h" -#include "components/policy/content/policy_blacklist_navigation_throttle.h" -#include "components/safe_browsing/features.h" -#include "components/variations/net/variations_http_headers.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/navigation_data.h" -#include "content/public/browser/notification_service.h" -#include "content/public/browser/plugin_service.h" -#include "content/public/browser/plugin_service_filter.h" -#include "content/public/browser/render_frame_host.h" -#include "content/public/browser/render_process_host.h" -#include "content/public/browser/render_view_host.h" -#include "content/public/browser/resource_context.h" -#include "content/public/browser/resource_dispatcher_host.h" -#include "content/public/browser/resource_request_info.h" -#include "content/public/browser/service_worker_context.h" -#include "content/public/browser/stream_info.h" -#include "content/public/browser/web_contents.h" -#include "content/public/common/content_features.h" -#include "extensions/buildflags/buildflags.h" -#include "net/base/host_port_pair.h" -#include "net/base/ip_endpoint.h" -#include "net/base/load_flags.h" -#include "net/base/load_timing_info.h" -#include "net/base/request_priority.h" -#include "net/http/http_response_headers.h" -#include "net/url_request/url_request.h" -#include "services/network/public/cpp/features.h" -#include "services/network/public/cpp/resource_response.h" -#include "third_party/protobuf/src/google/protobuf/repeated_field.h" - -#if BUILDFLAG(ENABLE_NACL) -#include "chrome/browser/component_updater/pnacl_component_installer.h" -#endif - -#if BUILDFLAG(ENABLE_EXTENSIONS) -#include "chrome/browser/extensions/api/streams_private/streams_private_api.h" -#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_attach_helper.h" -#include "extensions/browser/guest_view/web_view/web_view_renderer_state.h" -#include "extensions/common/extension.h" -#include "extensions/common/extension_urls.h" -#include "extensions/common/user_script.h" -#endif - -#if BUILDFLAG(ENABLE_OFFLINE_PAGES) -#include "chrome/browser/offline_pages/downloads/resource_throttle.h" -#include "chrome/browser/offline_pages/offliner_user_data.h" -#include "chrome/browser/offline_pages/resource_loading_observer.h" -#endif - -#if defined(OS_ANDROID) -#include "chrome/browser/android/download/intercept_download_resource_throttle.h" -#endif - -using content::BrowserThread; -using content::RenderViewHost; -using content::ResourceRequestInfo; -using content::ResourceType; - -#if BUILDFLAG(ENABLE_EXTENSIONS) -using extensions::Extension; -using extensions::StreamsPrivateAPI; -#endif - -namespace { - -prerender::PrerenderManager* GetPrerenderManager( - content::WebContents* web_contents) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (!web_contents) - return NULL; - - content::BrowserContext* browser_context = web_contents->GetBrowserContext(); - if (!browser_context) - return NULL; - - return prerender::PrerenderManagerFactory::GetForBrowserContext( - browser_context); -} - -void UpdatePrerenderNetworkBytesCallback(content::WebContents* web_contents, - int64_t bytes) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - // PrerenderContents::FromWebContents handles the NULL case. - prerender::PrerenderContents* prerender_contents = - prerender::PrerenderContents::FromWebContents(web_contents); - - if (prerender_contents) - prerender_contents->AddNetworkBytes(bytes); - - prerender::PrerenderManager* prerender_manager = - GetPrerenderManager(web_contents); - if (prerender_manager) - prerender_manager->AddProfileNetworkBytesIfEnabled(bytes); -} - -#if BUILDFLAG(ENABLE_NACL) -void AppendComponentUpdaterThrottles( - net::URLRequest* request, - ResourceRequestInfo* info, - content::ResourceContext* resource_context, - ResourceType resource_type, - std::vector<std::unique_ptr<content::ResourceThrottle>>* throttles) { - if (info->IsPrerendering()) - return; - - const char* crx_id = NULL; - component_updater::ComponentUpdateService* cus = - g_browser_process->component_updater(); - if (!cus) - return; - // Check for PNaCl pexe request. - if (resource_type == content::ResourceType::kObject) { - const net::HttpRequestHeaders& headers = request->extra_request_headers(); - std::string accept_headers; - if (headers.GetHeader("Accept", &accept_headers)) { - if (accept_headers.find("application/x-pnacl") != std::string::npos && - pnacl::NeedsOnDemandUpdate()) - crx_id = "hnimpnehoodheedghdeeijklkeaacbdc"; - } - } - - if (crx_id) { - // We got a component we need to install, so throttle the resource - // until the component is installed. - throttles->push_back(base::WrapUnique( - component_updater::GetOnDemandResourceThrottle(cus, crx_id))); - } -} -#endif // BUILDFLAG(ENABLE_NACL) - -#if BUILDFLAG(ENABLE_OFFLINE_PAGES) -// Translate content::ResourceType to a type to use for Offliners. -offline_pages::ResourceLoadingObserver::ResourceDataType -ConvertResourceTypeToResourceDataType(content::ResourceType type) { - switch (type) { - case content::ResourceType::kStylesheet: - return offline_pages::ResourceLoadingObserver::ResourceDataType::TEXT_CSS; - case content::ResourceType::kImage: - return offline_pages::ResourceLoadingObserver::ResourceDataType::IMAGE; - case content::ResourceType::kXhr: - return offline_pages::ResourceLoadingObserver::ResourceDataType::XHR; - default: - return offline_pages::ResourceLoadingObserver::ResourceDataType::OTHER; - } -} - -void NotifyUIThreadOfRequestStarted( - const content::ResourceRequestInfo::WebContentsGetter& web_contents_getter, - ResourceType resource_type) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - // TODO(petewil) We're not sure why yet, but we do sometimes see that - // web_contents_getter returning null. Until we find out why, avoid crashing. - // crbug.com/742370 - if (web_contents_getter.is_null()) - return; - - content::WebContents* web_contents = web_contents_getter.Run(); - if (!web_contents) - return; - - // If we are producing an offline version of the page, track resource loading. - offline_pages::ResourceLoadingObserver* resource_tracker = - offline_pages::OfflinerUserData::ResourceLoadingObserverFromWebContents( - web_contents); - if (resource_tracker) { - offline_pages::ResourceLoadingObserver::ResourceDataType data_type = - ConvertResourceTypeToResourceDataType(resource_type); - resource_tracker->ObserveResourceLoading(data_type, true /* STARTED */); - } -} -#endif - -void NotifyUIThreadOfRequestComplete( - const content::ResourceRequestInfo::WebContentsGetter& web_contents_getter, - const content::ResourceRequestInfo::FrameTreeNodeIdGetter& - frame_tree_node_id_getter, - const GURL& url, - const net::IPEndPoint& remote_endpoint, - const content::GlobalRequestID& request_id, - int render_process_id, - int render_frame_id, - ResourceType resource_type, - bool is_download, - bool was_cached, - std::unique_ptr<data_reduction_proxy::DataReductionProxyData> - data_reduction_proxy_data, - int net_error, - int64_t total_received_bytes, - int64_t raw_body_bytes, - int64_t original_content_length, - base::TimeTicks request_creation_time, - std::unique_ptr<net::LoadTimingInfo> load_timing_info) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - content::WebContents* web_contents = web_contents_getter.Run(); - if (!web_contents) - return; - - if (!was_cached) { - UpdatePrerenderNetworkBytesCallback(web_contents, total_received_bytes); - } - -#if BUILDFLAG(ENABLE_OFFLINE_PAGES) - // If we are producing an offline version of the page, track resource loading. - offline_pages::ResourceLoadingObserver* resource_tracker = - offline_pages::OfflinerUserData::ResourceLoadingObserverFromWebContents( - web_contents); - if (resource_tracker) { - offline_pages::ResourceLoadingObserver::ResourceDataType data_type = - ConvertResourceTypeToResourceDataType(resource_type); - resource_tracker->ObserveResourceLoading(data_type, false /* COMPLETED */); - if (!was_cached) - resource_tracker->OnNetworkBytesChanged(total_received_bytes); - } -#endif // BUILDFLAG(ENABLE_OFFLINE_PAGES) - - if (!is_download) { - page_load_metrics::MetricsWebContentsObserver* metrics_observer = - page_load_metrics::MetricsWebContentsObserver::FromWebContents( - web_contents); - if (metrics_observer) { - // Will be null for main or sub frame resources, when browser-side - // navigation is enabled. - content::RenderFrameHost* render_frame_host_or_null = - content::RenderFrameHost::FromID(render_process_id, render_frame_id); - metrics_observer->OnRequestComplete( - url, remote_endpoint, frame_tree_node_id_getter.Run(), request_id, - render_frame_host_or_null, resource_type, was_cached, - std::move(data_reduction_proxy_data), raw_body_bytes, - original_content_length, request_creation_time, net_error, - std::move(load_timing_info)); - } - } -} - -} // namespace - -ChromeResourceDispatcherHostDelegate::ChromeResourceDispatcherHostDelegate() - : download_request_limiter_(g_browser_process->download_request_limiter()), - safe_browsing_(g_browser_process->safe_browsing_service()) {} - -ChromeResourceDispatcherHostDelegate::~ChromeResourceDispatcherHostDelegate() { -#if BUILDFLAG(ENABLE_EXTENSIONS) - CHECK(stream_target_info_.empty()); -#endif -} - -void ChromeResourceDispatcherHostDelegate::RequestBeginning( - net::URLRequest* request, - content::ResourceContext* resource_context, - content::AppCacheService* appcache_service, - ResourceType resource_type, - std::vector<std::unique_ptr<content::ResourceThrottle>>* throttles) { - if (safe_browsing_.get()) - safe_browsing_->OnResourceRequest(request); - ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context); - -#if BUILDFLAG(ENABLE_OFFLINE_PAGES) || BUILDFLAG(ENABLE_NACL) - ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request); -#endif - -#if BUILDFLAG(ENABLE_OFFLINE_PAGES) - // TODO(petewil): Unify the safe browsing request and the metrics observer - // request if possible so we only have to cross to the main thread once. - // http://crbug.com/712312. - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&NotifyUIThreadOfRequestStarted, - info->GetWebContentsGetterForRequest(), - info->GetResourceType())); -#endif // BUILDFLAG(ENABLE_OFFLINE_PAGES) - - // Don't attempt to append headers to requests that have already started. - // TODO(stevet): Remove this once the request ordering issues are resolved - // in crbug.com/128048. - if (!request->is_pending()) { - net::HttpRequestHeaders headers; - headers.CopyFrom(request->extra_request_headers()); - request->SetExtraRequestHeaders(headers); - bool is_off_the_record = io_data->IsOffTheRecord(); - bool is_signed_in = - !is_off_the_record && - !io_data->google_services_account_id()->GetValue().empty(); - variations::AppendVariationsHeader( - request->url(), - is_off_the_record ? variations::InIncognito::kYes - : variations::InIncognito::kNo, - is_signed_in ? variations::SignedIn::kYes : variations::SignedIn::kNo, - request); - } - - signin::ChromeRequestAdapter signin_request_adapter(request); - signin::FixAccountConsistencyRequestHeader( - &signin_request_adapter, GURL() /* redirect_url */, io_data); - - AppendStandardResourceThrottles(request, - resource_context, - resource_type, - throttles); -#if BUILDFLAG(ENABLE_NACL) - AppendComponentUpdaterThrottles(request, info, resource_context, - resource_type, throttles); -#endif // BUILDFLAG(ENABLE_NACL) -} - -void ChromeResourceDispatcherHostDelegate::DownloadStarting( - net::URLRequest* request, - content::ResourceContext* resource_context, - bool is_content_initiated, - bool must_download, - bool is_new_request, - std::vector<std::unique_ptr<content::ResourceThrottle>>* throttles) { - content::ResourceRequestInfo* info = - content::ResourceRequestInfo::ForRequest(request); - // If it's from the web, we don't trust it, so we push the throttle on. - if (is_content_initiated) { - throttles->push_back(std::make_unique<DownloadResourceThrottle>( - download_request_limiter_, info->GetWebContentsGetterForRequest(), - request->url(), request->method())); - } - - // If this isn't a new request, the standard resource throttles have already - // been added, so no need to add them again. - if (is_new_request) { - AppendStandardResourceThrottles(request, resource_context, - content::ResourceType::kMainFrame, - throttles); -#if defined(OS_ANDROID) - // On Android, forward text/html downloads to OfflinePages backend. - throttles->push_back( - std::make_unique<offline_pages::downloads::ResourceThrottle>(request)); -#endif - } - -#if defined(OS_ANDROID) - // Add the InterceptDownloadResourceThrottle after calling - // AppendStandardResourceThrottles so the download will not bypass - // safebrowsing checks. - if (is_content_initiated) { - throttles->push_back(std::make_unique<InterceptDownloadResourceThrottle>( - request, info->GetWebContentsGetterForRequest())); - } -#endif -} - -void ChromeResourceDispatcherHostDelegate::AppendStandardResourceThrottles( - net::URLRequest* request, - content::ResourceContext* resource_context, - ResourceType resource_type, - std::vector<std::unique_ptr<content::ResourceThrottle>>* throttles) { - ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context); - - // Insert safe browsing to decide if the resource is safe. - content::ResourceThrottle* first_throttle = NULL; - -#if defined(SAFE_BROWSING_DB_LOCAL) || defined(SAFE_BROWSING_DB_REMOTE) - if (io_data->safe_browsing_enabled()->GetValue() && - !base::FeatureList::IsEnabled(safe_browsing::kCheckByURLLoaderThrottle)) { - first_throttle = MaybeCreateSafeBrowsingResourceThrottle( - request, resource_type, safe_browsing_.get(), io_data); - } -#endif // defined(SAFE_BROWSING_DB_LOCAL) || defined(SAFE_BROWSING_DB_REMOTE) - - if (first_throttle) - throttles->push_back(base::WrapUnique(first_throttle)); -} - -bool ChromeResourceDispatcherHostDelegate::ShouldInterceptResourceAsStream( - net::URLRequest* request, - const std::string& mime_type, - GURL* origin, - std::string* payload) { -#if BUILDFLAG(ENABLE_EXTENSIONS) - ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request); - std::string extension_id = - PluginUtils::GetExtensionIdForMimeType(info->GetContext(), mime_type); - if (!extension_id.empty()) { - StreamTargetInfo target_info; - *origin = Extension::GetBaseURLFromExtensionId(extension_id); - target_info.extension_id = extension_id; - target_info.view_id = base::GenerateGUID(); - *payload = target_info.view_id; - // Provide the MimeHandlerView code a chance to override the payload. This - // is the case where the resource is handled by frame-based MimeHandlerView. - uint32_t unused_data_pipe_size; - extensions::MimeHandlerViewAttachHelper::OverrideBodyForInterceptedResponse( - info->GetFrameTreeNodeId(), request->url(), mime_type, - target_info.view_id, payload, &unused_data_pipe_size); - stream_target_info_[request] = target_info; - return true; - } -#endif - return false; -} - -void ChromeResourceDispatcherHostDelegate::OnStreamCreated( - net::URLRequest* request, - std::unique_ptr<content::StreamInfo> stream) { -#if BUILDFLAG(ENABLE_EXTENSIONS) - ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request); - auto ix = stream_target_info_.find(request); - CHECK(ix != stream_target_info_.end()); - bool embedded = info->GetResourceType() != content::ResourceType::kMainFrame; - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce( - &extensions::StreamsPrivateAPI::SendExecuteMimeTypeHandlerEvent, - ix->second.extension_id, ix->second.view_id, embedded, - info->GetFrameTreeNodeId(), info->GetChildID(), - info->GetRenderFrameID(), std::move(stream), - nullptr /* transferrable_loader */, GURL())); - stream_target_info_.erase(request); -#endif -} - -void ChromeResourceDispatcherHostDelegate::OnResponseStarted( - net::URLRequest* request, - content::ResourceContext* resource_context, - network::ResourceResponse* response) { - ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context); - - signin::ResponseAdapter signin_response_adapter(request); - signin::ProcessAccountConsistencyResponseHeaders( - &signin_response_adapter, GURL(), io_data->IsOffTheRecord()); - - // Built-in additional protection for the chrome web store origin. -#if BUILDFLAG(ENABLE_EXTENSIONS) - GURL webstore_url(extension_urls::GetWebstoreLaunchURL()); - if (request->url().SchemeIsHTTPOrHTTPS() && - request->url().DomainIs(webstore_url.host_piece())) { - net::HttpResponseHeaders* response_headers = request->response_headers(); - if (response_headers && - !response_headers->HasHeaderValue("x-frame-options", "deny") && - !response_headers->HasHeaderValue("x-frame-options", "sameorigin")) { - response_headers->RemoveHeader("x-frame-options"); - response_headers->AddHeader("x-frame-options: sameorigin"); - } - } -#endif -} - -void ChromeResourceDispatcherHostDelegate::OnRequestRedirected( - const GURL& redirect_url, - net::URLRequest* request, - content::ResourceContext* resource_context, - network::ResourceResponse* response) { - ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context); - - // Chrome tries to ensure that the identity is consistent between Chrome and - // the content area. - // - // For example, on Android, for users that are signed in to Chrome, the - // identity is mirrored into the content area. To do so, Chrome appends a - // X-Chrome-Connected header to all Gaia requests from a connected profile so - // Gaia could return a 204 response and let Chrome handle the action with - // native UI. - signin::ChromeRequestAdapter signin_request_adapter(request); - signin::FixAccountConsistencyRequestHeader(&signin_request_adapter, - redirect_url, io_data); - signin::ResponseAdapter signin_response_adapter(request); - signin::ProcessAccountConsistencyResponseHeaders( - &signin_response_adapter, redirect_url, io_data->IsOffTheRecord()); -} - -// Notification that a request has completed. -void ChromeResourceDispatcherHostDelegate::RequestComplete( - net::URLRequest* url_request) { - if (!url_request) - return; - // TODO(maksims): remove this and use net_error argument in RequestComplete - // once ResourceDispatcherHostDelegate is modified. - int net_error = url_request->status().error(); - ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(url_request); - - ProfileIOData* io_data = - ProfileIOData::FromResourceContext(info->GetContext()); - data_reduction_proxy::DataReductionProxyIOData* data_reduction_proxy_io_data = - io_data->data_reduction_proxy_io_data(); - data_reduction_proxy::LoFiDecider* lofi_decider = nullptr; - if (data_reduction_proxy_io_data) - lofi_decider = data_reduction_proxy_io_data->lofi_decider(); - - data_reduction_proxy::DataReductionProxyData* data = - data_reduction_proxy::DataReductionProxyData::GetData(*url_request); - std::unique_ptr<data_reduction_proxy::DataReductionProxyData> - data_reduction_proxy_data; - if (data) - data_reduction_proxy_data = data->DeepCopy(); - int64_t original_content_length = - data && data->used_data_reduction_proxy() - ? data_reduction_proxy::util::EstimateOriginalBodySize(*url_request, - lofi_decider) - : url_request->GetRawBodyBytes(); - - net::IPEndPoint remote_endpoint; - // We want to get the IP address of the response if it was returned, and the - // last endpoint that was checked if it failed. - if (url_request->response_headers()) - remote_endpoint = url_request->GetResponseRemoteEndpoint(); - if (!remote_endpoint.address().IsValid() && - !url_request->GetTransactionRemoteEndpoint(&remote_endpoint)) { - remote_endpoint = net::IPEndPoint(); - } - - auto load_timing_info = std::make_unique<net::LoadTimingInfo>(); - url_request->GetLoadTimingInfo(load_timing_info.get()); - - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce( - &NotifyUIThreadOfRequestComplete, - info->GetWebContentsGetterForRequest(), - info->GetFrameTreeNodeIdGetterForRequest(), url_request->url(), - remote_endpoint, info->GetGlobalRequestID(), info->GetChildID(), - info->GetRenderFrameID(), info->GetResourceType(), info->IsDownload(), - url_request->was_cached(), std::move(data_reduction_proxy_data), - net_error, url_request->GetTotalReceivedBytes(), - url_request->GetRawBodyBytes(), original_content_length, - url_request->creation_time(), std::move(load_timing_info))); -} - -content::NavigationData* -ChromeResourceDispatcherHostDelegate::GetNavigationData( - net::URLRequest* request) const { - ChromeNavigationData* data = - ChromeNavigationData::GetDataAndCreateIfNecessary(request); - if (!request) - return data; - - data_reduction_proxy::DataReductionProxyData* data_reduction_proxy_data = - data_reduction_proxy::DataReductionProxyData::GetData(*request); - // DeepCopy the DataReductionProxyData from the URLRequest to prevent the - // URLRequest and DataReductionProxyData from both having ownership of the - // same object. This copy will be shortlived as it will be deep copied again - // when content makes a clone of NavigationData for the UI thread. - if (data_reduction_proxy_data) - data->SetDataReductionProxyData(data_reduction_proxy_data->DeepCopy()); - - return data; -}
diff --git a/chrome/browser/loader/chrome_resource_dispatcher_host_delegate.h b/chrome/browser/loader/chrome_resource_dispatcher_host_delegate.h deleted file mode 100644 index b6085c8..0000000 --- a/chrome/browser/loader/chrome_resource_dispatcher_host_delegate.h +++ /dev/null
@@ -1,100 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_LOADER_CHROME_RESOURCE_DISPATCHER_HOST_DELEGATE_H_ -#define CHROME_BROWSER_LOADER_CHROME_RESOURCE_DISPATCHER_HOST_DELEGATE_H_ - -#include <map> -#include <memory> -#include <set> -#include <vector> - -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "chrome/browser/external_protocol/external_protocol_handler.h" -#include "content/public/browser/resource_dispatcher_host_delegate.h" -#include "extensions/buildflags/buildflags.h" - -class DownloadRequestLimiter; - -namespace content { -class NavigationData; -} - -namespace net { -class URLRequest; -} - -namespace safe_browsing { -class SafeBrowsingService; -} - -// Implements ResourceDispatcherHostDelegate. Currently used by the Prerender -// system to abort requests and add to the load flags when a request begins. -class ChromeResourceDispatcherHostDelegate - : public content::ResourceDispatcherHostDelegate { - public: - ChromeResourceDispatcherHostDelegate(); - ~ChromeResourceDispatcherHostDelegate() override; - - // ResourceDispatcherHostDelegate implementation. - void RequestBeginning(net::URLRequest* request, - content::ResourceContext* resource_context, - content::AppCacheService* appcache_service, - content::ResourceType resource_type, - std::vector<std::unique_ptr<content::ResourceThrottle>>* - throttles) override; - void DownloadStarting(net::URLRequest* request, - content::ResourceContext* resource_context, - bool is_content_initiated, - bool must_download, - bool is_new_request, - std::vector<std::unique_ptr<content::ResourceThrottle>>* - throttles) override; - bool ShouldInterceptResourceAsStream(net::URLRequest* request, - const std::string& mime_type, - GURL* origin, - std::string* payload) override; - void OnStreamCreated(net::URLRequest* request, - std::unique_ptr<content::StreamInfo> stream) override; - void OnResponseStarted(net::URLRequest* request, - content::ResourceContext* resource_context, - network::ResourceResponse* response) override; - void OnRequestRedirected(const GURL& redirect_url, - net::URLRequest* request, - content::ResourceContext* resource_context, - network::ResourceResponse* response) override; - void RequestComplete(net::URLRequest* url_request) override; - content::NavigationData* GetNavigationData( - net::URLRequest* request) const override; - - protected: - // Virtual for testing. - virtual void AppendStandardResourceThrottles( - net::URLRequest* request, - content::ResourceContext* resource_context, - content::ResourceType resource_type, - std::vector<std::unique_ptr<content::ResourceThrottle>>* throttles); - - private: - friend class ChromeResourceDispatcherHostDelegateTest; - -#if BUILDFLAG(ENABLE_EXTENSIONS) - struct StreamTargetInfo { - std::string extension_id; - std::string view_id; - }; -#endif - - scoped_refptr<DownloadRequestLimiter> download_request_limiter_; - scoped_refptr<safe_browsing::SafeBrowsingService> safe_browsing_; -#if BUILDFLAG(ENABLE_EXTENSIONS) - std::map<net::URLRequest*, StreamTargetInfo> stream_target_info_; -#endif - - DISALLOW_COPY_AND_ASSIGN(ChromeResourceDispatcherHostDelegate); -}; - -#endif // CHROME_BROWSER_LOADER_CHROME_RESOURCE_DISPATCHER_HOST_DELEGATE_H_
diff --git a/chrome/browser/loader/chrome_resource_dispatcher_host_delegate_browsertest.cc b/chrome/browser/loader/chrome_resource_dispatcher_host_delegate_browsertest.cc deleted file mode 100644 index 6e49883..0000000 --- a/chrome/browser/loader/chrome_resource_dispatcher_host_delegate_browsertest.cc +++ /dev/null
@@ -1,257 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/loader/chrome_resource_dispatcher_host_delegate.h" - -#include <stddef.h> - -#include <map> -#include <memory> -#include <utility> -#include <vector> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/command_line.h" -#include "base/files/scoped_temp_dir.h" -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "base/run_loop.h" -#include "base/stl_util.h" -#include "base/strings/string_util.h" -#include "base/task/post_task.h" -#include "base/test/scoped_command_line.h" -#include "build/buildflag.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/download/download_browsertest.h" -#include "chrome/browser/loader/chrome_navigation_data.h" -#include "chrome/browser/policy/cloud/policy_header_service_factory.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/common/pref_names.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/base/ui_test_utils.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_data.h" -#include "components/policy/core/common/cloud/cloud_policy_constants.h" -#include "components/policy/core/common/cloud/policy_header_service.h" -#include "components/policy/core/common/policy_switches.h" -#include "components/prefs/pref_service.h" -#include "components/signin/core/browser/signin_buildflags.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/navigation_data.h" -#include "content/public/browser/navigation_handle.h" -#include "content/public/browser/resource_dispatcher_host.h" -#include "content/public/browser/resource_dispatcher_host_delegate.h" -#include "content/public/browser/web_contents_observer.h" -#include "content/public/test/browser_test_utils.h" -#include "net/http/http_request_headers.h" -#include "net/test/embedded_test_server/embedded_test_server.h" -#include "net/test/embedded_test_server/http_request.h" -#include "net/test/embedded_test_server/http_response.h" -#include "net/test/url_request/url_request_mock_http_job.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_filter.h" -#include "services/network/public/cpp/features.h" -#include "testing/gmock/include/gmock/gmock-matchers.h" - -using content::ResourceType; - -namespace { - -std::unique_ptr<net::test_server::HttpResponse> HandleTestRequest( - const net::test_server::HttpRequest& request) { - if (request.relative_url == "/") { - std::unique_ptr<net::test_server::BasicHttpResponse> http_response( - new net::test_server::BasicHttpResponse); - http_response->set_code(net::HTTP_OK); - http_response->set_content("Success"); - return std::move(http_response); - } - return nullptr; -} - -class TestDispatcherHostDelegate : public ChromeResourceDispatcherHostDelegate { - public: - TestDispatcherHostDelegate() : should_add_data_reduction_proxy_data_(false) {} - ~TestDispatcherHostDelegate() override {} - - // ResourceDispatcherHostDelegate implementation: - content::NavigationData* GetNavigationData( - net::URLRequest* request) const override { - if (request && should_add_data_reduction_proxy_data_) { - data_reduction_proxy::DataReductionProxyData* data = - data_reduction_proxy::DataReductionProxyData:: - GetDataAndCreateIfNecessary(request); - data->set_used_data_reduction_proxy(true); - } - return ChromeResourceDispatcherHostDelegate::GetNavigationData(request); - } - - // ChromeResourceDispatcherHost implementation: - void AppendStandardResourceThrottles( - net::URLRequest* request, - content::ResourceContext* resource_context, - ResourceType resource_type, - std::vector<std::unique_ptr<content::ResourceThrottle>>* throttles) - override { - ++times_stardard_throttles_added_for_url_[request->url()]; - ChromeResourceDispatcherHostDelegate::AppendStandardResourceThrottles( - request, resource_context, resource_type, throttles); - } - - void set_should_add_data_reduction_proxy_data( - bool should_add_data_reduction_proxy_data) { - should_add_data_reduction_proxy_data_ = - should_add_data_reduction_proxy_data; - } - - // Writes the number of times the standard set of throttles have been added - // for requests for the speficied URL to |count|. - void GetTimesStandardThrottlesAddedForURL(const GURL& url, int* count) { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - *count = times_stardard_throttles_added_for_url_[url]; - } - - private: - bool should_add_data_reduction_proxy_data_; - - std::map<GURL, int> times_stardard_throttles_added_for_url_; - - DISALLOW_COPY_AND_ASSIGN(TestDispatcherHostDelegate); -}; - -// Helper class to track DidFinishNavigation and verify that NavigationData is -// added to NavigationHandle and pause/resume execution of the test. -class DidFinishNavigationObserver : public content::WebContentsObserver { - public: - DidFinishNavigationObserver(content::WebContents* web_contents, - bool add_data_reduction_proxy_data) - : content::WebContentsObserver(web_contents), - add_data_reduction_proxy_data_(add_data_reduction_proxy_data) {} - ~DidFinishNavigationObserver() override {} - - void DidFinishNavigation( - content::NavigationHandle* navigation_handle) override { - ChromeNavigationData* data = static_cast<ChromeNavigationData*>( - navigation_handle->GetNavigationData()); - if (add_data_reduction_proxy_data_) { - EXPECT_TRUE(data->GetDataReductionProxyData()); - EXPECT_TRUE( - data->GetDataReductionProxyData()->used_data_reduction_proxy()); - } else { - EXPECT_FALSE(data->GetDataReductionProxyData()); - } - } - - private: - bool add_data_reduction_proxy_data_; - DISALLOW_COPY_AND_ASSIGN(DidFinishNavigationObserver); -}; - -} // namespace - -class ChromeResourceDispatcherHostDelegateBrowserTest : - public InProcessBrowserTest { - public: - ChromeResourceDispatcherHostDelegateBrowserTest() {} - - void SetUpOnMainThread() override { - // Hook navigations with our delegate. - dispatcher_host_delegate_.reset(new TestDispatcherHostDelegate); - content::ResourceDispatcherHost::Get()->SetDelegate( - dispatcher_host_delegate_.get()); - - embedded_test_server()->RegisterRequestHandler( - base::Bind(&HandleTestRequest)); - ASSERT_TRUE(embedded_test_server()->Start()); - } - - void TearDownOnMainThread() override { - content::ResourceDispatcherHost::Get()->SetDelegate(NULL); - dispatcher_host_delegate_.reset(); - } - - void SetShouldAddDataReductionProxyData(bool add_data) { - dispatcher_host_delegate_->set_should_add_data_reduction_proxy_data( - add_data); - } - - int GetTimesStandardThrottlesAddedForURL(const GURL& url) { - int count; - base::RunLoop run_loop; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce( - &TestDispatcherHostDelegate::GetTimesStandardThrottlesAddedForURL, - base::Unretained(dispatcher_host_delegate_.get()), url, &count), - run_loop.QuitClosure()); - run_loop.Run(); - return count; - } - - protected: - std::unique_ptr<TestDispatcherHostDelegate> dispatcher_host_delegate_; - - private: - DISALLOW_COPY_AND_ASSIGN(ChromeResourceDispatcherHostDelegateBrowserTest); -}; - -// Check that exactly one set of throttles is added to smaller downloads, which -// have their mime type determined only after the response is completely -// received. -// See https://crbug.com/640545 -IN_PROC_BROWSER_TEST_F(ChromeResourceDispatcherHostDelegateBrowserTest, - ThrottlesAddedExactlyOnceToTinySniffedDownloads) { - // This code path isn't used when the network service is enabled. - if (base::FeatureList::IsEnabled(network::features::kNetworkService)) - return; - - GURL url = embedded_test_server()->GetURL("/downloads/tiny_binary.bin"); - DownloadTestObserverNotInProgress download_observer( - content::BrowserContext::GetDownloadManager(browser()->profile()), 1); - download_observer.StartObserving(); - ui_test_utils::NavigateToURL(browser(), url); - download_observer.WaitForFinished(); - EXPECT_EQ(1, GetTimesStandardThrottlesAddedForURL(url)); -} - -// Check that exactly one set of throttles is added to larger downloads, which -// have their mime type determined before the end of the response is reported. -IN_PROC_BROWSER_TEST_F(ChromeResourceDispatcherHostDelegateBrowserTest, - ThrottlesAddedExactlyOnceToLargeSniffedDownloads) { - // This code path isn't used when the network service is enabled. - if (base::FeatureList::IsEnabled(network::features::kNetworkService)) - return; - - GURL url = embedded_test_server()->GetURL("/downloads/thisdayinhistory.xls"); - DownloadTestObserverNotInProgress download_observer( - content::BrowserContext::GetDownloadManager(browser()->profile()), 1); - download_observer.StartObserving(); - ui_test_utils::NavigateToURL(browser(), url); - download_observer.WaitForFinished(); - EXPECT_EQ(1, GetTimesStandardThrottlesAddedForURL(url)); -} - -// Check that exactly one set of throttles is added to downloads started by an -// <a download> click. -IN_PROC_BROWSER_TEST_F(ChromeResourceDispatcherHostDelegateBrowserTest, - ThrottlesAddedExactlyOnceToADownloads) { - // This code path isn't used when the network service is enabled. - if (base::FeatureList::IsEnabled(network::features::kNetworkService)) - return; - - DownloadTestObserverNotInProgress download_observer( - content::BrowserContext::GetDownloadManager(browser()->profile()), 1); - download_observer.StartObserving(); - ui_test_utils::NavigateToURL(browser(), embedded_test_server()->GetURL( - "/download-anchor-attrib.html")); - download_observer.WaitForFinished(); - EXPECT_EQ(1, - GetTimesStandardThrottlesAddedForURL( - embedded_test_server()->GetURL("/anchor_download_test.png"))); -}
diff --git a/chrome/browser/loader/chrome_resource_dispatcher_host_delegate_unittest.cc b/chrome/browser/loader/chrome_resource_dispatcher_host_delegate_unittest.cc deleted file mode 100644 index 11f644da..0000000 --- a/chrome/browser/loader/chrome_resource_dispatcher_host_delegate_unittest.cc +++ /dev/null
@@ -1,79 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/loader/chrome_resource_dispatcher_host_delegate.h" - -#include <memory> - -#include "chrome/browser/loader/chrome_navigation_data.h" -#include "chrome/browser/loader/chrome_resource_dispatcher_host_delegate.h" -#include "chrome/test/base/testing_browser_process.h" -#include "chrome/test/base/testing_profile_manager.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_data.h" -#include "content/public/browser/navigation_data.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "net/base/request_priority.h" -#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_context.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -class ChromeResourceDispatcherHostDelegateTest : public testing::Test { - public: - ChromeResourceDispatcherHostDelegateTest() - : profile_manager_( - new TestingProfileManager(TestingBrowserProcess::GetGlobal())) {} - ~ChromeResourceDispatcherHostDelegateTest() override {} - - void SetUp() override { ASSERT_TRUE(profile_manager_->SetUp()); } - - private: - content::TestBrowserThreadBundle thread_bundle_; - // Set up TestingProfileManager for extensions::UserScriptListener. - std::unique_ptr<TestingProfileManager> profile_manager_; -}; - -TEST_F(ChromeResourceDispatcherHostDelegateTest, - GetNavigationDataWithDataReductionProxyData) { - std::unique_ptr<net::URLRequestContext> context = - std::make_unique<net::URLRequestContext>(); - std::unique_ptr<net::URLRequest> fake_request( - context->CreateRequest(GURL("google.com"), net::RequestPriority::IDLE, - nullptr, TRAFFIC_ANNOTATION_FOR_TESTS)); - // Add DataReductionProxyData to URLRequest - data_reduction_proxy::DataReductionProxyData* data_reduction_proxy_data = - data_reduction_proxy::DataReductionProxyData::GetDataAndCreateIfNecessary( - fake_request.get()); - data_reduction_proxy_data->set_used_data_reduction_proxy(true); - std::unique_ptr<ChromeResourceDispatcherHostDelegate> delegate = - std::make_unique<ChromeResourceDispatcherHostDelegate>(); - ChromeNavigationData* chrome_navigation_data = - static_cast<ChromeNavigationData*>( - delegate->GetNavigationData(fake_request.get())); - data_reduction_proxy::DataReductionProxyData* data_reduction_proxy_data_copy = - chrome_navigation_data->GetDataReductionProxyData(); - // The DataReductionProxyData should be a copy of the one on URLRequest - EXPECT_NE(data_reduction_proxy_data_copy, data_reduction_proxy_data); - // Make sure DataReductionProxyData was copied. - EXPECT_TRUE(data_reduction_proxy_data_copy->used_data_reduction_proxy()); - EXPECT_EQ( - chrome_navigation_data, - ChromeNavigationData::GetDataAndCreateIfNecessary(fake_request.get())); -} - -TEST_F(ChromeResourceDispatcherHostDelegateTest, - GetNavigationDataWithoutDataReductionProxyData) { - std::unique_ptr<net::URLRequestContext> context = - std::make_unique<net::URLRequestContext>(); - std::unique_ptr<net::URLRequest> fake_request( - context->CreateRequest(GURL("google.com"), net::RequestPriority::IDLE, - nullptr, TRAFFIC_ANNOTATION_FOR_TESTS)); - std::unique_ptr<ChromeResourceDispatcherHostDelegate> delegate = - std::make_unique<ChromeResourceDispatcherHostDelegate>(); - ChromeNavigationData* chrome_navigation_data = - static_cast<ChromeNavigationData*>( - delegate->GetNavigationData(fake_request.get())); - EXPECT_FALSE(chrome_navigation_data->GetDataReductionProxyData()); -}
diff --git a/chrome/browser/loader/safe_browsing_resource_throttle.cc b/chrome/browser/loader/safe_browsing_resource_throttle.cc deleted file mode 100644 index 751db53c..0000000 --- a/chrome/browser/loader/safe_browsing_resource_throttle.cc +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/loader/safe_browsing_resource_throttle.h" - -#include "chrome/browser/profiles/profile_io_data.h" -#include "chrome/browser/safe_browsing/safe_browsing_service.h" -#include "chrome/browser/safe_browsing/ui_manager.h" -#include "chrome/browser/safe_browsing/url_checker_delegate_impl.h" -#include "components/safe_browsing/common/safe_browsing_prefs.h" -#include "components/safe_browsing/db/database_manager.h" -#include "components/safe_browsing/db/v4_protocol_manager_util.h" - -content::ResourceThrottle* MaybeCreateSafeBrowsingResourceThrottle( - net::URLRequest* request, - content::ResourceType resource_type, - safe_browsing::SafeBrowsingService* sb_service, - const ProfileIOData* io_data) { - if (!sb_service->database_manager()->IsSupported()) - return nullptr; - - // No need to create resource throttle if request url is whitelisted by - // enterprise policy. - if (io_data && - safe_browsing::IsURLWhitelistedByPolicy( - request->url(), io_data->safe_browsing_whitelist_domains())) { - return nullptr; - } - - return new SafeBrowsingParallelResourceThrottle(request, resource_type, - sb_service); -} - -SafeBrowsingParallelResourceThrottle::SafeBrowsingParallelResourceThrottle( - const net::URLRequest* request, - content::ResourceType resource_type, - safe_browsing::SafeBrowsingService* sb_service) - : safe_browsing::BaseParallelResourceThrottle( - request, - resource_type, - base::MakeRefCounted<safe_browsing::UrlCheckerDelegateImpl>( - sb_service->database_manager(), - sb_service->ui_manager())) {} - -SafeBrowsingParallelResourceThrottle::~SafeBrowsingParallelResourceThrottle() = - default; - -const char* SafeBrowsingParallelResourceThrottle::GetNameForLogging() { - return "SafeBrowsingParallelResourceThrottle"; -}
diff --git a/chrome/browser/loader/safe_browsing_resource_throttle.h b/chrome/browser/loader/safe_browsing_resource_throttle.h deleted file mode 100644 index 9cb1c2b..0000000 --- a/chrome/browser/loader/safe_browsing_resource_throttle.h +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_LOADER_SAFE_BROWSING_RESOURCE_THROTTLE_H_ -#define CHROME_BROWSER_LOADER_SAFE_BROWSING_RESOURCE_THROTTLE_H_ - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "components/safe_browsing/browser/base_parallel_resource_throttle.h" -#include "content/public/browser/resource_throttle.h" -#include "content/public/common/resource_type.h" - -namespace net { -class URLRequest; -} - -namespace safe_browsing { -class SafeBrowsingService; -} - -class ProfileIOData; - -// Contructs a resource throttle for SafeBrowsing. -// It could return nullptr if URL checking is not supported on this -// build+device. -content::ResourceThrottle* MaybeCreateSafeBrowsingResourceThrottle( - net::URLRequest* request, - content::ResourceType resource_type, - safe_browsing::SafeBrowsingService* sb_service, - const ProfileIOData* io_data); - -// SafeBrowsingParallelResourceThrottle uses a Chrome-specific -// safe_browsing::UrlCheckerDelegate implementation with its base class -// safe_browsing::BaseParallelResourceThrottle. -class SafeBrowsingParallelResourceThrottle - : public safe_browsing::BaseParallelResourceThrottle { - private: - friend content::ResourceThrottle* MaybeCreateSafeBrowsingResourceThrottle( - net::URLRequest* request, - content::ResourceType resource_type, - safe_browsing::SafeBrowsingService* sb_service, - const ProfileIOData* io_data); - - SafeBrowsingParallelResourceThrottle( - const net::URLRequest* request, - content::ResourceType resource_type, - safe_browsing::SafeBrowsingService* sb_service); - - ~SafeBrowsingParallelResourceThrottle() override; - - const char* GetNameForLogging() override; - - DISALLOW_COPY_AND_ASSIGN(SafeBrowsingParallelResourceThrottle); -}; - -#endif // CHROME_BROWSER_LOADER_SAFE_BROWSING_RESOURCE_THROTTLE_H_
diff --git a/chrome/browser/notifications/chrome_ash_message_center_client.cc b/chrome/browser/notifications/chrome_ash_message_center_client.cc index ef8c850..d1374f63 100644 --- a/chrome/browser/notifications/chrome_ash_message_center_client.cc +++ b/chrome/browser/notifications/chrome_ash_message_center_client.cc
@@ -7,6 +7,7 @@ #include "ash/public/interfaces/constants.mojom.h" #include "base/i18n/string_compare.h" #include "base/stl_util.h" +#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/arc/arc_session_manager.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/notifications/arc_application_notifier_controller.h" @@ -17,6 +18,7 @@ #include "chrome/browser/ui/settings_window_manager_chromeos.h" #include "chrome/common/webui_url_constants.h" #include "components/user_manager/user_manager.h" +#include "content/public/browser/notification_service.h" #include "content/public/common/service_manager_connection.h" #include "services/service_manager/public/cpp/connector.h" #include "ui/message_center/public/cpp/notifier_id.h" @@ -33,7 +35,6 @@ // profile, so this just returns the active profile. Profile* GetProfileForNotifiers() { const auto* user = user_manager::UserManager::Get()->GetActiveUser(); - CHECK(user->is_profile_created()); return chromeos::ProfileHelper::Get()->GetProfileByUser(user); } @@ -92,6 +93,10 @@ ChromeAshMessageCenterClient::~ChromeAshMessageCenterClient() { DCHECK_EQ(this, g_chrome_ash_message_center_client); g_chrome_ash_message_center_client = nullptr; + if (deferred_notifier_list_callback_) { + std::move(deferred_notifier_list_callback_) + .Run(std::vector<ash::mojom::NotifierUiDataPtr>()); + } } void ChromeAshMessageCenterClient::Display( @@ -159,7 +164,26 @@ void ChromeAshMessageCenterClient::GetNotifierList( GetNotifierListCallback callback) { + if (deferred_notifier_list_callback_) { + std::move(deferred_notifier_list_callback_) + .Run(std::vector<ash::mojom::NotifierUiDataPtr>()); + registrar_.RemoveAll(); + } Profile* profile = GetProfileForNotifiers(); + if (profile) { + RespondWithNotifierList(profile, std::move(callback)); + } else { + LOG(ERROR) << "GetNotifierList called before profile fully loaded, see " + "https://crbug.com/968825"; + deferred_notifier_list_callback_ = std::move(callback); + registrar_.Add(this, chrome::NOTIFICATION_PROFILE_ADDED, + content::NotificationService::AllSources()); + } +} + +void ChromeAshMessageCenterClient::RespondWithNotifierList( + Profile* profile, + GetNotifierListCallback callback) const { CHECK(profile); std::vector<ash::mojom::NotifierUiDataPtr> notifiers; for (auto& source : sources_) { @@ -177,6 +201,26 @@ std::move(callback).Run(std::move(notifiers)); } +void ChromeAshMessageCenterClient::Observe( + int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) { + switch (type) { + case chrome::NOTIFICATION_PROFILE_ADDED: { + Profile* profile = GetProfileForNotifiers(); + if (profile) { + CHECK(deferred_notifier_list_callback_); + RespondWithNotifierList(profile, + std::move(deferred_notifier_list_callback_)); + registrar_.RemoveAll(); + } + break; + } + default: + NOTREACHED(); + } +} + void ChromeAshMessageCenterClient::GetArcAppIdByPackageName( const std::string& package_name, GetArcAppIdByPackageNameCallback callback) {
diff --git a/chrome/browser/notifications/chrome_ash_message_center_client.h b/chrome/browser/notifications/chrome_ash_message_center_client.h index 3d93c3a..112f944 100644 --- a/chrome/browser/notifications/chrome_ash_message_center_client.h +++ b/chrome/browser/notifications/chrome_ash_message_center_client.h
@@ -10,6 +10,8 @@ #include "chrome/browser/notifications/notification_platform_bridge.h" #include "chrome/browser/notifications/notification_platform_bridge_chromeos.h" #include "chrome/browser/notifications/notifier_controller.h" +#include "content/public/browser/notification_observer.h" +#include "content/public/browser/notification_registrar.h" #include "mojo/public/cpp/bindings/associated_binding.h" #include "ui/message_center/public/cpp/notifier_id.h" @@ -19,7 +21,8 @@ // NotifierControllers to provide notifier settings information to Ash (visible // in NotifierSettingsView). class ChromeAshMessageCenterClient : public ash::mojom::AshMessageCenterClient, - public NotifierController::Observer { + public NotifierController::Observer, + public content::NotificationObserver { public: explicit ChromeAshMessageCenterClient( NotificationPlatformBridgeDelegate* delegate); @@ -57,6 +60,14 @@ static void FlushForTesting(); private: + void RespondWithNotifierList(Profile* profile, + GetNotifierListCallback callback) const; + + // content::NotificationObserver override. + void Observe(int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) override; + NotificationPlatformBridgeDelegate* delegate_; // A mapping from display token to notification ID. The display token is @@ -73,6 +84,8 @@ ash::mojom::AshMessageCenterControllerPtr controller_; mojo::AssociatedBinding<ash::mojom::AshMessageCenterClient> binding_; + content::NotificationRegistrar registrar_; + GetNotifierListCallback deferred_notifier_list_callback_; DISALLOW_COPY_AND_ASSIGN(ChromeAshMessageCenterClient); };
diff --git a/chrome/browser/offline_pages/downloads/resource_throttle.cc b/chrome/browser/offline_pages/downloads/resource_throttle.cc deleted file mode 100644 index 8da0fef..0000000 --- a/chrome/browser/offline_pages/downloads/resource_throttle.cc +++ /dev/null
@@ -1,73 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/offline_pages/downloads/resource_throttle.h" - -#include "base/bind.h" -#include "base/logging.h" -#include "base/task/post_task.h" -#include "chrome/browser/offline_pages/offline_page_utils.h" -#include "components/offline_pages/core/client_namespace_constants.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/download_request_utils.h" -#include "content/public/browser/resource_request_info.h" -#include "content/public/browser/web_contents.h" - -namespace { -void WillStartOfflineRequestOnUIThread( - const GURL& url, - const std::string& request_origin, - const content::ResourceRequestInfo::WebContentsGetter& contents_getter) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - content::WebContents* web_contents = contents_getter.Run(); - if (!web_contents) - return; - offline_pages::OfflinePageUtils::ScheduleDownload( - web_contents, offline_pages::kDownloadNamespace, url, - offline_pages::OfflinePageUtils::DownloadUIActionFlags::ALL, - request_origin); -} -} // namespace - -namespace offline_pages { -namespace downloads { - -ResourceThrottle::ResourceThrottle(const net::URLRequest* request) - : request_(request) { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); -} - -ResourceThrottle::~ResourceThrottle() { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); -} - -void ResourceThrottle::WillProcessResponse(bool* defer) { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - std::string mime_type; - request_->GetMimeType(&mime_type); - if (offline_pages::OfflinePageUtils::CanDownloadAsOfflinePage(request_->url(), - mime_type)) { - content::ResourceRequestInfo* info = - content::ResourceRequestInfo::ForRequest(request_); - if (!info) - return; - - std::string request_origin = - content::DownloadRequestUtils::GetRequestOriginFromRequest(request_); - - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&WillStartOfflineRequestOnUIThread, request_->url(), - request_origin, info->GetWebContentsGetterForRequest())); - Cancel(); - } -} - -const char* ResourceThrottle::GetNameForLogging() { - return "offline_pages::downloads::ResourceThrottle"; -} - -} // namespace downloads -} // namespace offline_pages
diff --git a/chrome/browser/offline_pages/downloads/resource_throttle.h b/chrome/browser/offline_pages/downloads/resource_throttle.h deleted file mode 100644 index 91326e0..0000000 --- a/chrome/browser/offline_pages/downloads/resource_throttle.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_OFFLINE_PAGES_DOWNLOADS_RESOURCE_THROTTLE_H_ -#define CHROME_BROWSER_OFFLINE_PAGES_DOWNLOADS_RESOURCE_THROTTLE_H_ - -#include "content/public/browser/resource_throttle.h" -#include "net/url_request/url_request.h" - -namespace offline_pages { -namespace downloads { - -// This ResourceThrottle is used to hook up into the loading process at the -// moment when headers are available (WillProcessResponse) to determine if the -// download has text/html mime type and should be canceled as a download and -// re-scheduled as a OfflinePage download request. This will be handled by -// Offline Page backend as a full page download rather than a single .html -// file download. -class ResourceThrottle : public content::ResourceThrottle { - public: - explicit ResourceThrottle(const net::URLRequest* request); - ~ResourceThrottle() override; - - // content::ResourceThrottle implementation: - void WillProcessResponse(bool* defer) override; - const char* GetNameForLogging() override; - - private: - const net::URLRequest* request_; - - DISALLOW_COPY_AND_ASSIGN(ResourceThrottle); -}; - -} // namespace downloads -} // namespace offline_pages - -#endif // CHROME_BROWSER_OFFLINE_PAGES_DOWNLOADS_RESOURCE_THROTTLE_H_
diff --git a/chrome/browser/pdf/pdf_extension_test.cc b/chrome/browser/pdf/pdf_extension_test.cc index 0ca9876..4a09d85 100644 --- a/chrome/browser/pdf/pdf_extension_test.cc +++ b/chrome/browser/pdf/pdf_extension_test.cc
@@ -19,8 +19,10 @@ #include "base/run_loop.h" #include "base/strings/pattern.h" #include "base/strings/utf_string_conversions.h" +#include "base/synchronization/lock.h" #include "base/task/post_task.h" #include "base/test/test_timeouts.h" +#include "base/thread_annotations.h" #include "base/threading/thread_restrictions.h" #include "build/build_config.h" #include "chrome/browser/chrome_notification_types.h" @@ -71,6 +73,7 @@ #include "content/public/test/browser_test_utils.h" #include "content/public/test/hit_test_region_observer.h" #include "content/public/test/test_navigation_observer.h" +#include "content/public/test/url_loader_interceptor.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/manifest_handlers/mime_types_handler.h" #include "extensions/test/result_catcher.h" @@ -2175,3 +2178,92 @@ run_loop.Run(); } } + +// A helper for waiting for the first request for |url_to_intercept|. +class RequestWaiter { + public: + // Start intercepting requests to |url_to_intercept|. + explicit RequestWaiter(const GURL& url_to_intercept) + : url_to_intercept_(url_to_intercept), + interceptor_(base::BindRepeating(&RequestWaiter::InterceptorCallback, + base::Unretained(this))) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK(url_to_intercept.is_valid()); + } + + void WaitForRequest() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (!IsAlreadyIntercepted()) + run_loop_.Run(); + DCHECK(IsAlreadyIntercepted()); + } + + private: + bool InterceptorCallback( + content::URLLoaderInterceptor::RequestParams* params) { + // This method may be called either on the IO or UI thread. + DCHECK(params); + + base::AutoLock lock(lock_); + if (url_to_intercept_ != params->url_request.url || already_intercepted_) + return false; + + already_intercepted_ = true; + run_loop_.Quit(); + return false; + } + + bool IsAlreadyIntercepted() { + base::AutoLock lock(lock_); + return already_intercepted_; + } + + const GURL url_to_intercept_; + content::URLLoaderInterceptor interceptor_; + base::RunLoop run_loop_; + + base::Lock lock_; + bool already_intercepted_ GUARDED_BY(lock_) = false; + + DISALLOW_COPY_AND_ASSIGN(RequestWaiter); +}; + +// This is a regression test for a problem where DidStopLoading didn't get +// propagated from a remote frame into the main frame. See also +// https://crbug.com/964364. +IN_PROC_BROWSER_TEST_F(PDFExtensionTest, DidStopLoading) { + // Prepare to wait for requests for the main page of the MimeHandlerView for + // PDFs. + RequestWaiter interceptor( + GURL("chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html")); + + // Navigate to a page with: + // <embed type="application/pdf" src="test.pdf"></embed> + // <iframe src="/hung"></iframe> + // Afterwards, the main page should be still loading because of the hung + // subframe (but the subframe for the OOPIF-based PDF MimeHandlerView might or + // might not be created at this point). + GURL url = embedded_test_server()->GetURL( + "/pdf/pdf_embed_with_hung_sibling_subframe.html"); + ui_test_utils::NavigateToURLWithDisposition( + browser(), url, WindowOpenDisposition::CURRENT_TAB, + ui_test_utils::BROWSER_TEST_NONE); // Don't wait for completion. + + // Wait for the request for the MimeHandlerView extension. Afterwards, the + // main page should be still loading because of + // 1) the MimeHandlerView frame is loading + // 2) the hung subframe is loading. + interceptor.WaitForRequest(); + + // Remove the hung subframe. Afterwards the main page should stop loading as + // soon as the MimeHandlerView frame stops loading (assumming we have not bugs + // similar to https://crbug.com/964364). + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(content::ExecJs( + web_contents, "document.getElementById('hung_subframe').remove();")); + + // MAIN VERIFICATION: Wait for the main frame to report that is has stopped + // loading. + content::WaitForLoadStop(web_contents); +}
diff --git a/chrome/browser/printing/print_job.cc b/chrome/browser/printing/print_job.cc index 61163cb..e82aa4d7 100644 --- a/chrome/browser/printing/print_job.cc +++ b/chrome/browser/printing/print_job.cc
@@ -16,6 +16,7 @@ #include "build/build_config.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/printing/print_job_worker.h" +#include "chrome/browser/printing/printer_query.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h"
diff --git a/chrome/browser/printing/print_job_unittest.cc b/chrome/browser/printing/print_job_unittest.cc index 2192bf7..e531aa2 100644 --- a/chrome/browser/printing/print_job_unittest.cc +++ b/chrome/browser/printing/print_job_unittest.cc
@@ -26,10 +26,9 @@ class TestPrintJobWorker : public PrintJobWorker { public: - explicit TestPrintJobWorker(PrinterQuery* query) + TestPrintJobWorker() : PrintJobWorker(content::ChildProcessHost::kInvalidUniqueID, - content::ChildProcessHost::kInvalidUniqueID, - query) {} + content::ChildProcessHost::kInvalidUniqueID) {} friend class TestQuery; }; @@ -52,7 +51,7 @@ // We're screwing up here since we're calling worker from the main thread. // That's fine for testing. It is actually simulating PrinterQuery behavior. - auto worker = std::make_unique<TestPrintJobWorker>(this); + auto worker = std::make_unique<TestPrintJobWorker>(); EXPECT_TRUE(worker->Start()); worker->printing_context()->UseDefaultSettings(); settings_ = worker->printing_context()->settings();
diff --git a/chrome/browser/printing/print_job_worker.cc b/chrome/browser/printing/print_job_worker.cc index 691c4767..88a6142 100644 --- a/chrome/browser/printing/print_job_worker.cc +++ b/chrome/browser/printing/print_job_worker.cc
@@ -105,20 +105,6 @@ content::Details<JobEventDetails>(details.get())); } -// Helper function to ensure |query| is valid until at least |callback| returns. -void WorkerHoldRefCallback(scoped_refptr<PrinterQuery> query, - base::OnceClosure callback) { - std::move(callback).Run(); -} - -void PostOnQueryThread(scoped_refptr<PrinterQuery> query, - PrintingContext::PrintSettingsCallback callback, - PrintingContext::Result result) { - query->PostTask(FROM_HERE, - base::BindOnce(&WorkerHoldRefCallback, query, - base::BindOnce(std::move(callback), result))); -} - #if defined(OS_WIN) void PageNotificationCallback(PrintJob* print_job, JobEventDetails::Type detail_type, @@ -136,15 +122,12 @@ } // namespace -PrintJobWorker::PrintJobWorker(int render_process_id, - int render_frame_id, - PrinterQuery* query) +PrintJobWorker::PrintJobWorker(int render_process_id, int render_frame_id) : printing_context_delegate_( std::make_unique<PrintingContextDelegate>(render_process_id, render_frame_id)), printing_context_( PrintingContext::Create(printing_context_delegate_.get())), - query_(query), thread_("Printing_Worker"), weak_factory_(this) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); @@ -154,12 +137,10 @@ // The object is normally deleted by PrintJob in the UI thread, but when the // user cancels printing or in the case of print preview, the worker is // destroyed with the PrinterQuery, which is on the I/O thread. - if (query_) { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - DCHECK(!print_job_); - } else { + if (print_job_) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(print_job_); + } else { + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); } Stop(); } @@ -167,9 +148,6 @@ void PrintJobWorker::SetPrintJob(PrintJob* print_job) { DCHECK_EQ(page_number_, PageNumber::npos()); print_job_ = print_job; - - // Release the Printer Query reference. It is no longer needed. - query_ = nullptr; } void PrintJobWorker::GetSettings(bool ask_user_for_settings, @@ -177,19 +155,11 @@ bool has_selection, MarginType margin_type, bool is_scripted, - bool is_modifiable) { + bool is_modifiable, + SettingsCallback callback) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); DCHECK_EQ(page_number_, PageNumber::npos()); - // This function is only called by the PrinterQuery. - DCHECK(query_); - - // Recursive task processing is needed for the dialog in case it needs to be - // destroyed by a task. - // TODO(thestig): This code is wrong. SetNestableTasksAllowed(true) is needed - // on the thread where the PrintDlgEx is called, and definitely both calls - // should happen on the same thread. See http://crbug.com/73466 - // MessageLoopCurrent::Get()->SetNestableTasksAllowed(true); printing_context_->set_margin_type(margin_type); printing_context_->set_is_modifiable(is_modifiable); @@ -198,85 +168,70 @@ if (ask_user_for_settings) { base::PostTaskWithTraits( FROM_HERE, {BrowserThread::UI}, - base::BindOnce( - &WorkerHoldRefCallback, base::WrapRefCounted(query_), - base::BindOnce(&PrintJobWorker::GetSettingsWithUI, - base::Unretained(this), document_page_count, - has_selection, is_scripted))); + base::BindOnce(&PrintJobWorker::GetSettingsWithUI, + base::Unretained(this), document_page_count, + has_selection, is_scripted, std::move(callback))); } else { base::PostTaskWithTraits( FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&WorkerHoldRefCallback, base::WrapRefCounted(query_), - base::BindOnce(&PrintJobWorker::UseDefaultSettings, - base::Unretained(this)))); + base::BindOnce(&PrintJobWorker::UseDefaultSettings, + base::Unretained(this), std::move(callback))); } } -void PrintJobWorker::SetSettings(base::Value new_settings) { +void PrintJobWorker::SetSettings(base::Value new_settings, + SettingsCallback callback) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); - DCHECK(query_); base::PostTaskWithTraits( FROM_HERE, {BrowserThread::UI}, - base::BindOnce( - &WorkerHoldRefCallback, base::WrapRefCounted(query_), - base::BindOnce(&PrintJobWorker::UpdatePrintSettings, - base::Unretained(this), std::move(new_settings)))); + base::BindOnce(&PrintJobWorker::UpdatePrintSettings, + base::Unretained(this), std::move(new_settings), + std::move(callback))); } #if defined(OS_CHROMEOS) void PrintJobWorker::SetSettingsFromPOD( - std::unique_ptr<printing::PrintSettings> new_settings) { + std::unique_ptr<printing::PrintSettings> new_settings, + SettingsCallback callback) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); - DCHECK(query_); base::PostTaskWithTraits( FROM_HERE, {BrowserThread::UI}, - base::BindOnce( - &WorkerHoldRefCallback, base::WrapRefCounted(query_), - base::BindOnce(&PrintJobWorker::UpdatePrintSettingsFromPOD, - base::Unretained(this), std::move(new_settings)))); + base::BindOnce(&PrintJobWorker::UpdatePrintSettingsFromPOD, + base::Unretained(this), std::move(new_settings), + std::move(callback))); } #endif -void PrintJobWorker::UpdatePrintSettings(base::Value new_settings) { +void PrintJobWorker::UpdatePrintSettings(base::Value new_settings, + SettingsCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); PrintingContext::Result result = printing_context_->UpdatePrintSettings(std::move(new_settings)); - GetSettingsDone(result); + GetSettingsDone(std::move(callback), result); } #if defined(OS_CHROMEOS) void PrintJobWorker::UpdatePrintSettingsFromPOD( - std::unique_ptr<printing::PrintSettings> new_settings) { + std::unique_ptr<printing::PrintSettings> new_settings, + SettingsCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); PrintingContext::Result result = printing_context_->UpdatePrintSettingsFromPOD(std::move(new_settings)); - GetSettingsDone(result); + GetSettingsDone(std::move(callback), result); } #endif -void PrintJobWorker::GetSettingsDone(PrintingContext::Result result) { - // Most PrintingContext functions may start a message loop and process - // message recursively, so disable recursive task processing. - // TODO(thestig): See above comment. SetNestableTasksAllowed(false) needs to - // be called on the same thread as the previous call. See - // http://crbug.com/73466 - // MessageLoopCurrent::Get()->SetNestableTasksAllowed(false); - - // We can't use OnFailure() here since query_ does not support notifications. - - DCHECK(query_); - query_->PostTask(FROM_HERE, - base::BindOnce(&PrinterQuery::GetSettingsDone, - base::WrapRefCounted(query_), - printing_context_->settings(), result)); +void PrintJobWorker::GetSettingsDone(SettingsCallback callback, + PrintingContext::Result result) { + std::move(callback).Run(printing_context_->settings(), result); } -void PrintJobWorker::GetSettingsWithUI( - int document_page_count, - bool has_selection, - bool is_scripted) { +void PrintJobWorker::GetSettingsWithUI(int document_page_count, + bool has_selection, + bool is_scripted, + SettingsCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); PrintingContextDelegate* printing_context_delegate = @@ -307,17 +262,15 @@ if (web_contents && web_contents->IsFullscreenForCurrentTab()) web_contents->ExitFullscreen(true); - // weak_factory_ creates pointers valid only on query_ thread. printing_context_->AskUserForSettings( document_page_count, has_selection, is_scripted, - base::BindOnce(&PostOnQueryThread, base::WrapRefCounted(query_), - base::BindOnce(&PrintJobWorker::GetSettingsDone, - weak_factory_.GetWeakPtr()))); + base::BindOnce(&PrintJobWorker::GetSettingsDone, + weak_factory_.GetWeakPtr(), std::move(callback))); } -void PrintJobWorker::UseDefaultSettings() { +void PrintJobWorker::UseDefaultSettings(SettingsCallback callback) { PrintingContext::Result result = printing_context_->UseDefaultSettings(); - GetSettingsDone(result); + GetSettingsDone(std::move(callback), result); } void PrintJobWorker::StartPrinting(PrintedDocument* new_document) {
diff --git a/chrome/browser/printing/print_job_worker.h b/chrome/browser/printing/print_job_worker.h index 95341c40..a711d9f 100644 --- a/chrome/browser/printing/print_job_worker.h +++ b/chrome/browser/printing/print_job_worker.h
@@ -13,7 +13,6 @@ #include "base/threading/thread.h" #include "base/values.h" #include "build/build_config.h" -#include "chrome/browser/printing/printer_query.h" #include "content/public/browser/browser_thread.h" #include "printing/page_number.h" #include "printing/print_job_constants.h" @@ -24,7 +23,6 @@ class PrintJob; class PrintedDocument; class PrintedPage; -class PrinterQuery; // Worker thread code. It manages the PrintingContext, which can be blocking // and/or run a message loop. This is the object that generates most @@ -33,9 +31,10 @@ // PrintJob always outlives its worker instance. class PrintJobWorker { public: - PrintJobWorker(int render_process_id, - int render_frame_id, - PrinterQuery* query); + using SettingsCallback = + base::OnceCallback<void(const PrintSettings&, PrintingContext::Result)>; + + PrintJobWorker(int render_process_id, int render_frame_id); virtual ~PrintJobWorker(); void SetPrintJob(PrintJob* print_job); @@ -51,15 +50,16 @@ bool has_selection, MarginType margin_type, bool is_scripted, - bool is_modifiable); + bool is_modifiable, + SettingsCallback callback); // Set the new print settings from a dictionary value. - void SetSettings(base::Value new_settings); + void SetSettings(base::Value new_settings, SettingsCallback callback); #if defined(OS_CHROMEOS) // Set the new print settings from a POD type. - void SetSettingsFromPOD( - std::unique_ptr<printing::PrintSettings> new_settings); + void SetSettingsFromPOD(std::unique_ptr<printing::PrintSettings> new_settings, + SettingsCallback callback); #endif /* The following functions may only be called after calling SetPrintJob(). */ @@ -130,27 +130,29 @@ // Asks the user for print settings. Must be called on the UI thread. // Required on Mac and Linux. Windows can display UI from non-main threads, // but sticks with this for consistency. - void GetSettingsWithUI( - int document_page_count, - bool has_selection, - bool is_scripted); + void GetSettingsWithUI(int document_page_count, + bool has_selection, + bool is_scripted, + SettingsCallback callback); // Called on the UI thread to update the print settings. - void UpdatePrintSettings(base::Value new_settings); + void UpdatePrintSettings(base::Value new_settings, SettingsCallback callback); #if defined(OS_CHROMEOS) // Called on the UI thread to update the print settings. void UpdatePrintSettingsFromPOD( - std::unique_ptr<printing::PrintSettings> new_settings); + std::unique_ptr<printing::PrintSettings> new_settings, + SettingsCallback callback); #endif - // Reports settings back to |query_|. - void GetSettingsDone(PrintingContext::Result result); + // Reports settings back to |callback|. + void GetSettingsDone(SettingsCallback callback, + PrintingContext::Result result); // Use the default settings. When using GTK+ or Mac, this can still end up // displaying a dialog. So this needs to happen from the UI thread on these // systems. - void UseDefaultSettings(); + void UseDefaultSettings(SettingsCallback callback); // Printing context delegate. const std::unique_ptr<PrintingContext::Delegate> printing_context_delegate_; @@ -161,10 +163,6 @@ // The printed document. Only has read-only access. scoped_refptr<PrintedDocument> document_; - // The printer query that owns this worker thread at creation. It will own - // the object until DetachWorker() is called. - PrinterQuery* query_ = nullptr; - // The print job owning this worker thread. It is guaranteed to outlive this // object and should be set with SetPrintJob(). PrintJob* print_job_ = nullptr;
diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc index 309477ec..7ba43aa 100644 --- a/chrome/browser/printing/print_view_manager_base.cc +++ b/chrome/browser/printing/print_view_manager_base.cc
@@ -624,17 +624,13 @@ static constexpr base::TimeDelta kPrinterSettingsTimeout = base::TimeDelta::FromSeconds(60); base::OneShotTimer quit_timer; - base::RunLoop run_loop; + base::RunLoop run_loop{base::RunLoop::Type::kNestableTasksAllowed}; quit_timer.Start(FROM_HERE, kPrinterSettingsTimeout, run_loop.QuitWhenIdleClosure()); quit_inner_loop_ = run_loop.QuitClosure(); - // Need to enable recursive task. - { - base::MessageLoopCurrent::ScopedNestableTaskAllower allow; - run_loop.Run(); - } + run_loop.Run(); // If the inner-loop quit closure is still set then we timed out. bool success = !quit_inner_loop_;
diff --git a/chrome/browser/printing/printer_query.cc b/chrome/browser/printing/printer_query.cc index 2abaa6e..f06f9b9e 100644 --- a/chrome/browser/printing/printer_query.cc +++ b/chrome/browser/printing/printer_query.cc
@@ -27,8 +27,7 @@ base::ThreadTaskRunnerHandle::Get()), cookie_(PrintSettings::NewCookie()), worker_(std::make_unique<PrintJobWorker>(render_process_id, - render_frame_id, - this)) { + render_frame_id)) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); } @@ -59,6 +58,13 @@ } } +void PrinterQuery::PostSettingsDoneToIO(const PrintSettings& new_settings, + PrintingContext::Result result) { + base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&PrinterQuery::GetSettingsDone, this, + new_settings, result)); +} + std::unique_ptr<PrintJobWorker> PrinterQuery::DetachWorker() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(!callback_); @@ -96,10 +102,11 @@ ask_user_for_settings == GetSettingsAskParam::ASK_USER; worker_->PostTask( FROM_HERE, - base::BindOnce(&PrintJobWorker::GetSettings, - base::Unretained(worker_.get()), - is_print_dialog_box_shown_, expected_page_count, - has_selection, margin_type, is_scripted, is_modifiable)); + base::BindOnce( + &PrintJobWorker::GetSettings, base::Unretained(worker_.get()), + is_print_dialog_box_shown_, expected_page_count, has_selection, + margin_type, is_scripted, is_modifiable, + base::BindOnce(&PrinterQuery::PostSettingsDoneToIO, this))); } void PrinterQuery::SetSettings(base::Value new_settings, @@ -107,9 +114,12 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::IO); StartWorker(std::move(callback)); - worker_->PostTask(FROM_HERE, base::BindOnce(&PrintJobWorker::SetSettings, - base::Unretained(worker_.get()), - std::move(new_settings))); + worker_->PostTask( + FROM_HERE, + base::BindOnce( + &PrintJobWorker::SetSettings, base::Unretained(worker_.get()), + std::move(new_settings), + base::BindOnce(&PrinterQuery::PostSettingsDoneToIO, this))); } #if defined(OS_CHROMEOS) @@ -121,8 +131,10 @@ StartWorker(std::move(callback)); worker_->PostTask( FROM_HERE, - base::BindOnce(&PrintJobWorker::SetSettingsFromPOD, - base::Unretained(worker_.get()), std::move(new_settings))); + base::BindOnce( + &PrintJobWorker::SetSettingsFromPOD, base::Unretained(worker_.get()), + std::move(new_settings), + base::BindOnce(&PrinterQuery::PostSettingsDoneToIO, this))); } #endif
diff --git a/chrome/browser/printing/printer_query.h b/chrome/browser/printing/printer_query.h index b6d8e222..5d00327 100644 --- a/chrome/browser/printing/printer_query.h +++ b/chrome/browser/printing/printer_query.h
@@ -35,10 +35,6 @@ // Can only be called on the IO thread. PrinterQuery(int render_process_id, int render_frame_id); - // Virtual so that tests can override. - virtual void GetSettingsDone(const PrintSettings& new_settings, - PrintingContext::Result result); - // Detach the PrintJobWorker associated to this object. Virtual so that tests // can override. // Called on the UI thread. @@ -92,6 +88,13 @@ virtual ~PrinterQuery(); + // Virtual so that tests can override. + virtual void GetSettingsDone(const PrintSettings& new_settings, + PrintingContext::Result result); + + void PostSettingsDoneToIO(const PrintSettings& new_settings, + PrintingContext::Result result); + // For unit tests to manually set the print callback. void set_callback(base::OnceClosure callback);
diff --git a/chrome/browser/resources/chromeos/add_supervision/add_supervision.js b/chrome/browser/resources/chromeos/add_supervision/add_supervision.js index ffe8344b..d2b3afa5 100644 --- a/chrome/browser/resources/chromeos/add_supervision/add_supervision.js +++ b/chrome/browser/resources/chromeos/add_supervision/add_supervision.js
@@ -2,6 +2,36 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/** + * List of URL hosts that can be requested by the webview. + * @const {!Array<string>} + */ +const ALLOWED_HOSTS = [ + 'families.google.com', + 'play.google.com', + 'google.com', + 'accounts.google.com', + 'gstatic.com', + 'fonts.gstatic.com', + // FIFE avatar images (lh3-lh6). See http://go/fife-domains + 'lh3.googleusercontent.com', + 'lh4.googleusercontent.com', + 'lh5.googleusercontent.com', + 'lh6.googleusercontent.com', +]; + +/** + * Returns whether the provided request should be allowed, based on whether + * its URL matches the list of allowed hosts. + * @param {!{url: string}} requestDetails Request that is issued by the webview. + * @return {boolean} Whether the request should be allowed. + */ +function isAllowedRequest(requestDetails) { + const requestUrl = new URL(requestDetails.url); + return requestUrl.protocol == 'https' && + ALLOWED_HOSTS.includes(requestUrl.host); +} + let server = null; const proxy = addSupervision.mojom.AddSupervisionHandler.getProxy(); @@ -28,7 +58,7 @@ // Block any requests to URLs other than one specified // by eventOriginFilter. webview.request.onBeforeRequest.addListener(function(details) { - return {cancel: !details.url.startsWith(eventOriginFilter)}; + return {cancel: !isAllowedRequest(details)}; }, {urls: ['<all_urls>']}, ['blocking']); webview.src = url.toString();
diff --git a/chrome/browser/resources/downloads/item.html b/chrome/browser/resources/downloads/item.html index 4534ece..9a2060d 100644 --- a/chrome/browser/resources/downloads/item.html +++ b/chrome/browser/resources/downloads/item.html
@@ -5,12 +5,12 @@ <link rel="import" href="i18n_setup.html"> <link rel="import" href="icon_loader.html"> <link rel="import" href="icons.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html"> <link rel="import" href="chrome://resources/cr_elements/cr_icon_button/cr_icon_button.html"> <link rel="import" href="chrome://resources/cr_elements/cr_icons_css.html"> <link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast_manager.html"> <link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html"> <link rel="import" href="chrome://resources/cr_elements/icons.html"> -<link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html"> <link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> <link rel="import" href="chrome://resources/html/action_link.html"> <link rel="import" href="chrome://resources/html/action_link_css.html"> @@ -19,13 +19,12 @@ <link rel="import" href="chrome://resources/html/cr/ui/focus_row_behavior.html"> <link rel="import" href="chrome://resources/html/cr/ui/focus_without_ink.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.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-progress/paper-progress.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html"> <dom-module id="downloads-item"> <template> - <style include="action-link cr-hidden-style cr-icons paper-button-style"> + <style include="action-link cr-hidden-style cr-icons"> :host { --controlled-by-active-color: #333; --controlled-by-active-link-color: var(--google-blue-600); @@ -41,7 +40,7 @@ --controlled-by-inactive-color: inherit; } - paper-button { + cr-button { font-weight: 500; margin: 0; min-width: auto; @@ -326,22 +325,22 @@ hidden="[[!completelyOnDisk_]]" focus-row-control focus-type="show">$i18n{controlShowInFolder}</a> <template is="dom-if" if="[[data.retry]]"> - <paper-button class="action-button" on-click="onRetryTap_" + <cr-button class="action-button" on-click="onRetryTap_" focus-row-control focus-type="retry"> $i18n{controlRetry} - </paper-button> + </cr-button> </template> <template is="dom-if" if="[[pauseOrResumeText_]]"> - <paper-button on-click="onPauseOrResumeTap_" id="pauseOrResume" + <cr-button on-click="onPauseOrResumeTap_" id="pauseOrResume" focus-row-control focus-type="pauseOrResume"> [[pauseOrResumeText_]] - </paper-button> + </cr-button> </template> <template is="dom-if" if="[[showCancel_]]"> - <paper-button on-click="onCancelTap_" focus-row-control + <cr-button on-click="onCancelTap_" focus-row-control focus-type="cancel"> $i18n{controlCancel} - </paper-button> + </cr-button> </template> <span id="controlled-by"><!-- Text populated dynamically. --></span> </div> @@ -350,22 +349,22 @@ <div id="dangerous" class="controls"> <!-- Dangerous file types (e.g. .exe, .jar). --> <template is="dom-if" if="[[!isMalware_]]"> - <paper-button on-click="onDiscardDangerousTap_" + <cr-button on-click="onDiscardDangerousTap_" class="action-button" focus-row-control - focus-type="discard">$i18n{dangerDiscard}</paper-button> - <paper-button on-click="onSaveDangerousTap_" focus-row-control + focus-type="discard">$i18n{dangerDiscard}</cr-button> + <cr-button on-click="onSaveDangerousTap_" focus-row-control focus-type="save"> - $i18n{dangerSave}</paper-button> + $i18n{dangerSave}</cr-button> </template> <!-- Things that safe browsing has determined to be dangerous. --> <template is="dom-if" if="[[isMalware_]]"> - <paper-button on-click="onDiscardDangerousTap_" + <cr-button on-click="onDiscardDangerousTap_" class="action-button" focus-row-control focus-type="discard"> - $i18n{controlRemoveFromList}</paper-button> - <paper-button on-click="onSaveDangerousTap_" focus-row-control + $i18n{controlRemoveFromList}</cr-button> + <cr-button on-click="onSaveDangerousTap_" focus-row-control focus-type="save"> - $i18n{dangerRestore}</paper-button> + $i18n{dangerRestore}</cr-button> </template> </div> </template>
diff --git a/chrome/browser/resources/local_ntp/custom_backgrounds.js b/chrome/browser/resources/local_ntp/custom_backgrounds.js index 8b5ddd3..15d1206 100644 --- a/chrome/browser/resources/local_ntp/custom_backgrounds.js +++ b/chrome/browser/resources/local_ntp/custom_backgrounds.js
@@ -107,6 +107,8 @@ RESTORE_DEFAULT_TEXT: 'edit-bg-restore-default-text', SHORTCUTS_BUTTON: 'shortcuts-button', SHORTCUTS_MENU: 'shortcuts-menu', + SHORTCUTS_OPTION_CUSTOM_LINKS: 'sh-option-cl', + SHORTCUTS_OPTION_MOST_VISITED: 'sh-option-mv', UPLOAD_IMAGE: 'edit-bg-upload-image', UPLOAD_IMAGE_TEXT: 'edit-bg-upload-image-text', TILES: 'bg-sel-tiles', @@ -587,9 +589,12 @@ /** * Apply styling to a selected tile in the richer picker and enable the done * button. - * @param {!Element} tile The tile to apply styling to. + * @param {?Element} tile The tile to apply styling to. */ customBackgrounds.richerPicker_selectTile = function(tile) { + if (!tile) { + return; + } tile.parentElement.classList.toggle(customBackgrounds.CLASSES.SELECTED, true); $(customBackgrounds.IDS.MENU_DONE).disabled = false; customBackgrounds.selectedTile = tile; @@ -610,7 +615,7 @@ * @param {?Element} tile The tile to remove styling from. */ customBackgrounds.richerPicker_deselectTile = function(tile) { - if (tile === null) { + if (!tile) { return; } tile.parentElement.classList.toggle( @@ -631,6 +636,21 @@ } }; +/** + * Apply styling to a selected shortcut option in the richer picker and enable + * the done button. + * @param {?Element} option The option to apply styling to. + */ +customBackgrounds.richerPicker_selectShortcutOption = function(option) { + if (!option || customBackgrounds.selectedTile === option) { + return; // The option has already been selected. + } + // Clear the previous selection, if any. + if (customBackgrounds.selectedTile) { + customBackgrounds.richerPicker_deselectTile(customBackgrounds.selectedTile); + } + customBackgrounds.richerPicker_selectTile(option); +}; /** * Apply border and checkmark when a tile is selected @@ -1436,6 +1456,28 @@ } }; + const clOption = $(customBackgrounds.IDS.SHORTCUTS_OPTION_CUSTOM_LINKS); + clOption.onclick = function() { + customBackgrounds.richerPicker_selectShortcutOption(clOption); + }; + clOption.onkeydown = function(event) { + if (event.keyCode === customBackgrounds.KEYCODES.ENTER || + event.keyCode === customBackgrounds.KEYCODES.SPACE) { + customBackgrounds.richerPicker_selectShortcutOption(clOption); + } + }; + + const mvOption = $(customBackgrounds.IDS.SHORTCUTS_OPTION_MOST_VISITED); + mvOption.onclick = function() { + customBackgrounds.richerPicker_selectShortcutOption(mvOption); + }; + mvOption.onkeydown = function(event) { + if (event.keyCode === customBackgrounds.KEYCODES.ENTER || + event.keyCode === customBackgrounds.KEYCODES.SPACE) { + customBackgrounds.richerPicker_selectShortcutOption(mvOption); + } + }; + const richerPickerOpenShortcuts = function() { customBackgrounds.richerPicker_resetCustomizationMenu(); customBackgrounds.richerPicker_selectMenuOption(
diff --git a/chrome/browser/resources/local_ntp/local_ntp.css b/chrome/browser/resources/local_ntp/local_ntp.css index 37fd1f4..c834317 100644 --- a/chrome/browser/resources/local_ntp/local_ntp.css +++ b/chrome/browser/resources/local_ntp/local_ntp.css
@@ -1244,16 +1244,8 @@ } .sh-option { - width: 268px; -} - -#sh-option-cl { margin-inline-end: 9px; -} - -.sh-option-select { - position: absolute; - visibility: none; + width: 268px; } .sh-option-image { @@ -1266,6 +1258,11 @@ width: 268px; } +.selected .sh-option-image { + background-color: rgb(var(--GB050-rgb)); + border-color: rgb(var(--GB600-rgb)); +} + .sh-option-mini { background-color: white; border: 1px solid rgb(var(--GG300-rgb)); @@ -1283,10 +1280,19 @@ right: unset; } +.selected .sh-option-mini { + box-shadow: 0 1px 3px 0 rgba(var(--GG800-rgb), .3), + 0 4px 8px 3px rgba(var(--GG800-rgb), .15); +} + .sh-option-mini .mini-shortcuts { background-color: rgb(var(--GG500-rgb)); } +.selected .sh-option-mini .mini-shortcuts { + background-color: rgb(var(--GB600-rgb)); +} + .sh-option-icon { -webkit-mask-repeat: no-repeat; -webkit-mask-size: 100%; @@ -1310,7 +1316,34 @@ right: 16px; } -.sh-title { +.selected .sh-option-icon { + background-color: rgba(var(--GB600-rgb), .24); +} + +.sh-option-image .selected-circle { + box-shadow: 0 3px 6px rgba(0, 0, 0, .16), 0 1px 2px rgba(0, 0, 0, .23); + height: 24px; + left: 208px; + top: 8px; + width: 24px; +} + +html[dir=rtl] .sh-option-image .selected-circle { + left: 0; + right: 208px; +} + +.sh-option-image .selected-check { + left: -2px; + top: -2px; +} + +html[dir=rtl] .sh-option-image .selected-check { + left: 0; + right: -2px; +} + +.sh-option-title { font-weight: bold; margin: 8px 0; }
diff --git a/chrome/browser/resources/local_ntp/local_ntp.html b/chrome/browser/resources/local_ntp/local_ntp.html index e7691c87..186659b8 100644 --- a/chrome/browser/resources/local_ntp/local_ntp.html +++ b/chrome/browser/resources/local_ntp/local_ntp.html
@@ -219,8 +219,8 @@ <div id="backgrounds-image-menu" class="menu-panel"></div> <div id="shortcuts-menu" class="menu-panel"> <div id="sh-options"> - <div id="sh-option-cl" class="sh-option"> - <div class="sh-option-image"> + <div class="sh-option"> + <div id="sh-option-cl" class="sh-option-image" tabindex="0" role="button"> <div class="sh-option-icon"></div> <div class="sh-option-mini"> <div class="mini-page"> @@ -228,13 +228,12 @@ <div class="mini-shortcuts"></div> </div> </div> - <div class="sh-option-select"></div> </div> - <div class="sh-title">$i18n{myShortcuts}</div> + <div class="sh-option-title">$i18n{myShortcuts}</div> $i18n{shortcutsCurated} </div> - <div id="sh-option-mv" class="sh-option"> - <div class="sh-option-image"> + <div class="sh-option"> + <div id="sh-option-mv" class="sh-option-image" tabindex="0" role="button"> <div class="sh-option-icon"></div> <div class="sh-option-mini"> <div class="mini-page"> @@ -242,9 +241,8 @@ <div class="mini-shortcuts"></div> </div> </div> - <div class="sh-option-select"></div> </div> - <div class="sh-title">$i18n{mostVisited}</div> + <div class="sh-option-title">$i18n{mostVisited}</div> $i18n{shortcutsSuggested} </div> </div>
diff --git a/chrome/browser/resources/local_ntp/local_ntp.js b/chrome/browser/resources/local_ntp/local_ntp.js index b0cb002..bcfd06e 100644 --- a/chrome/browser/resources/local_ntp/local_ntp.js +++ b/chrome/browser/resources/local_ntp/local_ntp.js
@@ -46,18 +46,30 @@ /** * Specifications for an NTP design (not comprehensive). * + * backgroundColor: The 4-component color of default background, + * darkBackgroundColor: The 4-component color of default dark background, + * iconBackgroundColor: The 4-component color of default dark icon background, + * iconDarkBackgroundColor: The 4-component color of default icon background, * numTitleLines: Number of lines to display in titles. * titleColor: The 4-component color of title text. * titleColorAgainstDark: The 4-component color of title text against a dark * theme. * * @type {{ + * backgroundColor: Array<number>, + * darkBackgroundColor: Array<number>, + * iconBackgroundColor: Array<number>, + * iconDarkBackgroundColor: Array<number>, * numTitleLines: number, * titleColor: Array<number>, * titleColorAgainstDark: Array<number>, * }} */ const NTP_DESIGN = { + backgroundColor: [255, 255, 255, 255], + darkBackgroundColor: [50, 54, 57, 255], + iconBackgroundColor: [241, 243, 244, 255], /** GG100 */ + iconDarkBackgroundColor: [32, 33, 36, 255], /** GG900 */ numTitleLines: 1, titleColor: [60, 64, 67, 255], /** GG800 */ titleColorAgainstDark: [248, 249, 250, 255], /** GG050 */ @@ -332,9 +344,19 @@ return { alternateLogo: false, backgroundColorRgba: - (isDarkModeEnabled ? [50, 54, 57, 255] : [255, 255, 255, 255]), + (isDarkModeEnabled ? NTP_DESIGN.darkBackgroundColor : + NTP_DESIGN.backgroundColor), + customBackgroundConfigured: false, + iconBackgroundColor: + (isDarkModeEnabled ? NTP_DESIGN.iconDarkBackgroundColor : + NTP_DESIGN.iconBackgroundColor), + isNtpBackgroundDark: isDarkModeEnabled, textColorLightRgba: [102, 102, 102, 255], - textColorRgba: [0, 0, 0, 255], + textColorRgba: + (isDarkModeEnabled ? NTP_DESIGN.titleColorAgainstDark : + NTP_DESIGN.titleColor), + useTitleContainer: false, + useWhiteAddIcon: isDarkModeEnabled, usingDarkMode: isDarkModeEnabled, usingDefaultTheme: true, };
diff --git a/chrome/browser/safe_browsing/BUILD.gn b/chrome/browser/safe_browsing/BUILD.gn index cc98a0b..22604a5 100644 --- a/chrome/browser/safe_browsing/BUILD.gn +++ b/chrome/browser/safe_browsing/BUILD.gn
@@ -112,8 +112,6 @@ sources += [ "../download/download_completion_blocker.cc", "../download/download_completion_blocker.h", - "../loader/safe_browsing_resource_throttle.cc", - "../loader/safe_browsing_resource_throttle.h", "browser_feature_extractor.cc", "browser_feature_extractor.h", "browser_features.cc", @@ -219,8 +217,6 @@ } } else if (safe_browsing_mode == 2) { sources += [ - "../loader/safe_browsing_resource_throttle.cc", - "../loader/safe_browsing_resource_throttle.h", "android/file_type_policies.cc", "android/services_delegate_android.cc", "android/services_delegate_android.h", @@ -233,8 +229,6 @@ ] } else if (safe_browsing_mode == 3) { sources += [ - "../loader/safe_browsing_resource_throttle.cc", - "../loader/safe_browsing_resource_throttle.h", "android/file_type_policies.cc", "android/services_delegate_android.cc", "android/services_delegate_android.h",
diff --git a/chrome/browser/ui/android/toolbar/location_bar_model_android.cc b/chrome/browser/ui/android/toolbar/location_bar_model_android.cc index e7300c12..b994b6c 100644 --- a/chrome/browser/ui/android/toolbar/location_bar_model_android.cc +++ b/chrome/browser/ui/android/toolbar/location_bar_model_android.cc
@@ -5,12 +5,15 @@ #include "chrome/browser/ui/android/toolbar/location_bar_model_android.h" #include "base/android/jni_string.h" +#include "chrome/common/url_constants.h" +#include "chrome/common/webui_url_constants.h" #include "components/omnibox/browser/location_bar_model_impl.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/ssl_status.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_constants.h" #include "jni/LocationBarModel_jni.h" +#include "ui/base/device_form_factor.h" using base::android::JavaParamRef; using base::android::JavaRef; @@ -54,6 +57,29 @@ return base::android::ConvertUTF16ToJavaString(env, result); } +jint LocationBarModelAndroid::GetPageClassification( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj, + bool is_focused_from_fakebox) { + // On phones, the omnibox is not initially shown on the NTP. In this case, + // treat the fakebox like the omnibox. + if (ui::GetDeviceFormFactor() == ui::DEVICE_FORM_FACTOR_PHONE) + is_focused_from_fakebox = false; + + // On tablets, the user can choose to focus either the fakebox or the + // omnibox. Chrome distinguishes between the two in order to apply URL + // demotion when the user focuses the fakebox (which looks more like a + // search box) but not when they focus the omnibox (which looks more + // like a URL bar). + OmniboxFocusSource source = is_focused_from_fakebox + ? OmniboxFocusSource::FAKEBOX + : OmniboxFocusSource::OMNIBOX; + + // TODO: Android does not save the homepage to the native pref, so we will + // never get the HOME_PAGE classification. Fix this by overriding IsHomePage. + return location_bar_model_->GetPageClassification(source); +} + content::WebContents* LocationBarModelAndroid::GetActiveWebContents() const { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jobject> jweb_contents = @@ -61,6 +87,20 @@ return content::WebContents::FromJavaWebContents(jweb_contents); } +bool LocationBarModelAndroid::IsInstantNTP() const { + GURL url; + if (!GetURL(&url)) + return false; + + // Android Chrome has its own Instant NTP page implementation. + if (url.SchemeIs(chrome::kChromeNativeScheme) && + url.host_piece() == chrome::kChromeUINewTabHost) { + return true; + } + + return false; +} + // static jlong JNI_LocationBarModel_Init(JNIEnv* env, const JavaParamRef<jobject>& obj) { return reinterpret_cast<intptr_t>(new LocationBarModelAndroid(env, obj));
diff --git a/chrome/browser/ui/android/toolbar/location_bar_model_android.h b/chrome/browser/ui/android/toolbar/location_bar_model_android.h index bc7f538..48c1af4 100644 --- a/chrome/browser/ui/android/toolbar/location_bar_model_android.h +++ b/chrome/browser/ui/android/toolbar/location_bar_model_android.h
@@ -34,9 +34,13 @@ base::android::ScopedJavaLocalRef<jstring> GetDisplaySearchTerms( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); + jint GetPageClassification(JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj, + bool is_focused_from_fakebox); // ChromeLocationBarModelDelegate: content::WebContents* GetActiveWebContents() const override; + bool IsInstantNTP() const override; private: std::unique_ptr<LocationBarModel> location_bar_model_;
diff --git a/chrome/browser/ui/android/toolbar/location_bar_model_android_unittest.cc b/chrome/browser/ui/android/toolbar/location_bar_model_android_unittest.cc new file mode 100644 index 0000000..73104b91 --- /dev/null +++ b/chrome/browser/ui/android/toolbar/location_bar_model_android_unittest.cc
@@ -0,0 +1,47 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/android/toolbar/location_bar_model_android.h" + +#include "chrome/common/webui_url_constants.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +class TestLocationBarModelAndroid : public LocationBarModelAndroid { + public: + TestLocationBarModelAndroid() + : LocationBarModelAndroid(nullptr, base::android::JavaRef<jobject>()) {} + ~TestLocationBarModelAndroid() override = default; + + // LocationBarModelDelegate: + bool GetURL(GURL* url) const override { + *url = url_; + return true; + } + + void SetURL(const GURL& url) { url_ = url; } + + private: + GURL url_; +}; + +} // namespace + +TEST(LocationBarModelAndroidTest, ClassifyAndroidNativeNewTabPage) { + TestLocationBarModelAndroid location_bar_model_android; + location_bar_model_android.SetURL(GURL(chrome::kChromeUINativeNewTabURL)); + EXPECT_EQ( + metrics::OmniboxEventProto::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS, + location_bar_model_android.GetPageClassification( + nullptr, base::android::JavaParamRef<jobject>(nullptr), false)); + + std::string ntp_with_path_and_query = + std::string(chrome::kChromeUINativeNewTabURL) + "foopath?foo=bar"; + location_bar_model_android.SetURL(GURL(ntp_with_path_and_query)); + EXPECT_EQ( + metrics::OmniboxEventProto::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS, + location_bar_model_android.GetPageClassification( + nullptr, base::android::JavaParamRef<jobject>(nullptr), false)); +}
diff --git a/chrome/browser/ui/ash/assistant/device_actions.cc b/chrome/browser/ui/ash/assistant/device_actions.cc index 006ba96c..57aa628 100644 --- a/chrome/browser/ui/ash/assistant/device_actions.cc +++ b/chrome/browser/ui/ash/assistant/device_actions.cc
@@ -106,7 +106,7 @@ } void NotifyAndroidAppListRefreshed( - mojo::InterfacePtrSet<chromeos::assistant::mojom::AppListEventSubscriber> + mojo::InterfacePtrSet<chromeos::assistant::mojom::AppListEventSubscriber>& subscribers) { std::vector<AndroidAppInfoPtr> android_apps_info = GetAppsInfo(); @@ -206,14 +206,6 @@ std::move(callback).Run(!!app); } -void DeviceActions::VerifyAndroidApp(std::vector<AndroidAppInfoPtr> apps_info, - VerifyAndroidAppCallback callback) { - for (const auto& app_info : apps_info) { - app_info->status = GetAndroidAppStatus(app_info->package_name); - } - std::move(callback).Run(std::move(apps_info)); -} - void DeviceActions::LaunchAndroidIntent(const std::string& intent) { auto* app = ARC_GET_INSTANCE_FOR_METHOD( arc::ArcServiceManager::Get()->arc_bridge_service()->app(), LaunchIntent);
diff --git a/chrome/browser/ui/ash/assistant/device_actions.h b/chrome/browser/ui/ash/assistant/device_actions.h index df934cc..15b0029 100644 --- a/chrome/browser/ui/ash/assistant/device_actions.h +++ b/chrome/browser/ui/ash/assistant/device_actions.h
@@ -28,9 +28,6 @@ void SetNightLightEnabled(bool enabled) override; void OpenAndroidApp(chromeos::assistant::mojom::AndroidAppInfoPtr app_info, OpenAndroidAppCallback callback) override; - void VerifyAndroidApp( - std::vector<chromeos::assistant::mojom::AndroidAppInfoPtr> apps_info, - VerifyAndroidAppCallback callback) override; void LaunchAndroidIntent(const std::string& intent) override; void AddAppListEventSubscriber( chromeos::assistant::mojom::AppListEventSubscriberPtr subscriber)
diff --git a/chrome/browser/ui/toolbar/chrome_location_bar_model_delegate.h b/chrome/browser/ui/toolbar/chrome_location_bar_model_delegate.h index 3766482..2def55dd 100644 --- a/chrome/browser/ui/toolbar/chrome_location_bar_model_delegate.h +++ b/chrome/browser/ui/toolbar/chrome_location_bar_model_delegate.h
@@ -27,20 +27,11 @@ bool ShouldPreventElision() const override; // LocationBarModelDelegate: - bool ShouldDisplayURL() const override; - - protected: - ChromeLocationBarModelDelegate(); - ~ChromeLocationBarModelDelegate() override; - - // Helper method to get the navigation entry from the navigation controller. - content::NavigationEntry* GetNavigationEntry() const; - - private: base::string16 FormattedStringWithEquivalentMeaning( const GURL& url, const base::string16& formatted_url) const override; bool GetURL(GURL* url) const override; + bool ShouldDisplayURL() const override; security_state::SecurityLevel GetSecurityLevel() const override; std::unique_ptr<security_state::VisibleSecurityState> GetVisibleSecurityState() const override; @@ -53,6 +44,14 @@ AutocompleteClassifier* GetAutocompleteClassifier() override; TemplateURLService* GetTemplateURLService() override; + protected: + ChromeLocationBarModelDelegate(); + ~ChromeLocationBarModelDelegate() override; + + // Helper method to get the navigation entry from the navigation controller. + content::NavigationEntry* GetNavigationEntry() const; + + private: // Returns the navigation controller used to retrieve the navigation entry // from which the states are retrieved. If this returns null, default values // are used.
diff --git a/chrome/browser/ui/views/location_bar/icon_label_bubble_view.cc b/chrome/browser/ui/views/location_bar/icon_label_bubble_view.cc index e8515d3..d1ad648 100644 --- a/chrome/browser/ui/views/location_bar/icon_label_bubble_view.cc +++ b/chrome/browser/ui/views/location_bar/icon_label_bubble_view.cc
@@ -213,16 +213,6 @@ return false; } -void IconLabelBubbleView::UpdateBorder() { - // Bubbles are given the full internal height of the location bar so that all - // child views in the location bar have the same height. The visible height of - // the bubble should be smaller, so use an empty border to shrink down the - // content bounds so the background gets painted correctly. - SetBorder(views::CreateEmptyBorder( - gfx::Insets(GetLayoutConstant(LOCATION_BAR_CHILD_INTERIOR_PADDING), - GetLayoutInsets(LOCATION_BAR_ICON_INTERIOR_PADDING).left()))); -} - gfx::Size IconLabelBubbleView::CalculatePreferredSize() const { // Height will be ignored by the LocationBarView. return GetSizeForLabelWidth(label()->GetPreferredSize().width()); @@ -511,3 +501,13 @@ focus_ring()->SchedulePaint(); } } + +void IconLabelBubbleView::UpdateBorder() { + // Bubbles are given the full internal height of the location bar so that all + // child views in the location bar have the same height. The visible height of + // the bubble should be smaller, so use an empty border to shrink down the + // content bounds so the background gets painted correctly. + SetBorder(views::CreateEmptyBorder( + gfx::Insets(GetLayoutConstant(LOCATION_BAR_CHILD_INTERIOR_PADDING), + GetLayoutInsets(LOCATION_BAR_ICON_INTERIOR_PADDING).left()))); +}
diff --git a/chrome/browser/ui/views/location_bar/icon_label_bubble_view.h b/chrome/browser/ui/views/location_bar/icon_label_bubble_view.h index 77ea88e..88d4429 100644 --- a/chrome/browser/ui/views/location_bar/icon_label_bubble_view.h +++ b/chrome/browser/ui/views/location_bar/icon_label_bubble_view.h
@@ -122,9 +122,6 @@ // prevent the bubble from reshowing on a mouse release. virtual bool IsBubbleShowing() const; - // Sets the border padding around this view. - virtual void UpdateBorder(); - // views::LabelButton: gfx::Size CalculatePreferredSize() const override; void Layout() override; @@ -217,6 +214,9 @@ // bounds and the separator visibility. void UpdateHighlightPath(); + // Sets the border padding around this view. + void UpdateBorder(); + // The contents of the bubble. SeparatorView* separator_view_;
diff --git a/chrome/browser/ui/views/page_action/page_action_icon_view.cc b/chrome/browser/ui/views/page_action/page_action_icon_view.cc index 2cbf433..426b1ea 100644 --- a/chrome/browser/ui/views/page_action/page_action_icon_view.cc +++ b/chrome/browser/ui/views/page_action/page_action_icon_view.cc
@@ -50,6 +50,7 @@ SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY); // Only shows bubble after mouse is released. set_notify_action(NotifyAction::NOTIFY_ON_RELEASE); + UpdateBorder(); } PageActionIconView::~PageActionIconView() {} @@ -178,12 +179,9 @@ void PageActionIconView::OnTouchUiChanged() { icon_size_ = GetLayoutConstant(LOCATION_BAR_ICON_SIZE); UpdateIconImage(); - IconLabelBubbleView::OnTouchUiChanged(); -} - -void PageActionIconView::UpdateBorder() { - SetBorder(views::CreateEmptyBorder( - GetLayoutInsets(LOCATION_BAR_ICON_INTERIOR_PADDING))); + UpdateBorder(); + if (GetVisible()) + PreferredSizeChanged(); } void PageActionIconView::SetIconColor(SkColor icon_color) { @@ -211,3 +209,8 @@ content::WebContents* PageActionIconView::GetWebContents() const { return delegate_->GetWebContentsForPageActionIconView(); } + +void PageActionIconView::UpdateBorder() { + SetBorder(views::CreateEmptyBorder( + GetLayoutInsets(LOCATION_BAR_ICON_INTERIOR_PADDING))); +}
diff --git a/chrome/browser/ui/views/page_action/page_action_icon_view.h b/chrome/browser/ui/views/page_action/page_action_icon_view.h index 24a1fa5..b9b0a03 100644 --- a/chrome/browser/ui/views/page_action/page_action_icon_view.h +++ b/chrome/browser/ui/views/page_action/page_action_icon_view.h
@@ -125,7 +125,6 @@ // IconLabelBubbleView: void OnBoundsChanged(const gfx::Rect& previous_bounds) override; void OnTouchUiChanged() override; - void UpdateBorder() override; // Updates the icon image after some state has changed. virtual void UpdateIconImage(); @@ -143,6 +142,8 @@ Delegate* delegate() const { return delegate_; } private: + void UpdateBorder(); + // The size of the icon image (excluding the ink drop). int icon_size_ = GetLayoutConstant(LOCATION_BAR_ICON_SIZE);
diff --git a/chrome/browser/ui/views/tabs/new_tab_button.cc b/chrome/browser/ui/views/tabs/new_tab_button.cc index 480a20f2..cf9ea00a 100644 --- a/chrome/browser/ui/views/tabs/new_tab_button.cc +++ b/chrome/browser/ui/views/tabs/new_tab_button.cc
@@ -24,6 +24,7 @@ #include "ui/gfx/color_utils.h" #include "ui/gfx/scoped_canvas.h" #include "ui/views/animation/flood_fill_ink_drop_ripple.h" +#include "ui/views/animation/ink_drop.h" #include "ui/views/animation/ink_drop_impl.h" #include "ui/views/animation/ink_drop_mask.h" #include "ui/views/view_class_properties.h" @@ -60,6 +61,9 @@ } // namespace // static +constexpr char NewTabButton::kClassName[]; + +// static const gfx::Size NewTabButton::kButtonSize{28, 28}; NewTabButton::NewTabButton(TabStrip* tab_strip, views::ButtonListener* listener) @@ -70,6 +74,9 @@ ui::EF_MIDDLE_MOUSE_BUTTON); #endif + ink_drop_container = + AddChildView(std::make_unique<views::InkDropContainerView>()); + SetInkDropMode(InkDropMode::ON); set_ink_drop_visible_opacity(0.08f); set_ink_drop_highlight_opacity(0.1f); @@ -121,6 +128,22 @@ GetInkDrop()->AnimateToState(state); } +const char* NewTabButton::GetClassName() const { + return kClassName; +} + +void NewTabButton::Layout() { + ink_drop_container->SetBoundsRect(GetLocalBounds()); +} + +void NewTabButton::AddLayerBeneathView(ui::Layer* new_layer) { + ink_drop_container->AddLayerBeneathView(new_layer); +} + +void NewTabButton::RemoveLayerBeneathView(ui::Layer* old_layer) { + ink_drop_container->RemoveLayerBeneathView(old_layer); +} + #if defined(OS_WIN) void NewTabButton::OnMouseReleased(const ui::MouseEvent& event) { if (!event.IsOnlyRightMouseButton()) {
diff --git a/chrome/browser/ui/views/tabs/new_tab_button.h b/chrome/browser/ui/views/tabs/new_tab_button.h index 344125c..4e0ebf7 100644 --- a/chrome/browser/ui/views/tabs/new_tab_button.h +++ b/chrome/browser/ui/views/tabs/new_tab_button.h
@@ -14,6 +14,10 @@ class FeaturePromoBubbleView; +namespace views { +class InkDropContainerView; +} + /////////////////////////////////////////////////////////////////////////////// // NewTabButton // @@ -25,6 +29,8 @@ public views::MaskedTargeterDelegate, public views::WidgetObserver { public: + static constexpr char kClassName[] = "NewTabButton"; + static const gfx::Size kButtonSize; NewTabButton(TabStrip* tab_strip, views::ButtonListener* listener); @@ -59,6 +65,12 @@ FeaturePromoBubbleView* new_tab_promo() { return new_tab_promo_; } + // views::View: + const char* GetClassName() const override; + void Layout() override; + void AddLayerBeneathView(ui::Layer* new_layer) override; + void RemoveLayerBeneathView(ui::Layer* old_layer) override; + private: // views::ImageButton: #if defined(OS_WIN) @@ -98,6 +110,9 @@ // Tab strip that contains this button. TabStrip* tab_strip_; + // Contains our ink drop layer so it can paint above our background. + views::InkDropContainerView* ink_drop_container; + // Promotional UI that appears next to the NewTabButton and encourages its // use. Owned by its NativeWidget. FeaturePromoBubbleView* new_tab_promo_ = nullptr;
diff --git a/chrome/browser/ui/webui/download_internals/download_internals_ui_message_handler.cc b/chrome/browser/ui/webui/download_internals/download_internals_ui_message_handler.cc index 9988db2..5c2ef62 100644 --- a/chrome/browser/ui/webui/download_internals/download_internals_ui_message_handler.cc +++ b/chrome/browser/ui/webui/download_internals/download_internals_ui_message_handler.cc
@@ -42,7 +42,8 @@ weak_ptr_factory_.GetWeakPtr())); Profile* profile = Profile::FromWebUI(web_ui()); - download_service_ = DownloadServiceFactory::GetForBrowserContext(profile); + download_service_ = + DownloadServiceFactory::GetForKey(profile->GetProfileKey()); download_service_->GetLogger()->AddObserver(this); }
diff --git a/chrome/browser/vr/metrics/session_metrics_helper.cc b/chrome/browser/vr/metrics/session_metrics_helper.cc index 7de15203..846b9323 100644 --- a/chrome/browser/vr/metrics/session_metrics_helper.cc +++ b/chrome/browser/vr/metrics/session_metrics_helper.cc
@@ -355,11 +355,10 @@ case Mode::kVrBrowsing: case Mode::kVrBrowsingRegular: case Mode::kVrBrowsingFullscreen: + case Mode::kWebXrVrPresentation: RecordPresentationStartAction( PresentationStartAction::kRequestFromVrBrowsing, options); return; - case Mode::kWebXrVrPresentation: - break; } NOTREACHED();
diff --git a/chrome/browser/vr/model/model.h b/chrome/browser/vr/model/model.h index 4a04fbe4..fe7ced5 100644 --- a/chrome/browser/vr/model/model.h +++ b/chrome/browser/vr/model/model.h
@@ -58,7 +58,6 @@ bool standalone_vr_device = false; bool menu_button_long_pressed = false; float floor_height = 0.0f; - bool use_new_incognito_strings = false; // WebVR state. WebVrModel web_vr;
diff --git a/chrome/browser/vr/ui.cc b/chrome/browser/vr/ui.cc index 64b08dbd..a24b9d5 100644 --- a/chrome/browser/vr/ui.cc +++ b/chrome/browser/vr/ui.cc
@@ -613,8 +613,6 @@ model_->supports_selection = ui_initial_state.supports_selection; model_->needs_keyboard_update = ui_initial_state.needs_keyboard_update; model_->standalone_vr_device = ui_initial_state.is_standalone_vr_device; - model_->use_new_incognito_strings = - ui_initial_state.use_new_incognito_strings; model_->controllers.push_back(ControllerModel()); }
diff --git a/chrome/browser/vr/ui_initial_state.h b/chrome/browser/vr/ui_initial_state.h index af7dc56..26df3d0 100644 --- a/chrome/browser/vr/ui_initial_state.h +++ b/chrome/browser/vr/ui_initial_state.h
@@ -22,7 +22,6 @@ bool needs_keyboard_update = false; bool is_standalone_vr_device = false; bool create_tabs_view = false; - bool use_new_incognito_strings = false; }; } // namespace vr
diff --git a/chrome/browser/vr/ui_scene_creator.cc b/chrome/browser/vr/ui_scene_creator.cc index d9de1128..b6992b9 100644 --- a/chrome/browser/vr/ui_scene_creator.cc +++ b/chrome/browser/vr/ui_scene_creator.cc
@@ -2449,12 +2449,8 @@ button_region->AddChild(std::move(button)); } - int new_incognito_tab_res_id = IDS_VR_MENU_NEW_PRIVATE_TAB; - int close_incognito_tabs_res_id = IDS_VR_MENU_CLOSE_PRIVATE_TABS; - if (!model_->use_new_incognito_strings) { - new_incognito_tab_res_id = IDS_VR_MENU_NEW_INCOGNITO_TAB; - close_incognito_tabs_res_id = IDS_VR_MENU_CLOSE_INCOGNITO_TABS; - } + int new_incognito_tab_res_id = IDS_VR_MENU_NEW_INCOGNITO_TAB; + int close_incognito_tabs_res_id = IDS_VR_MENU_CLOSE_INCOGNITO_TABS; struct MenuItem { UiElementName name;
diff --git a/chrome/common/chrome_features.cc b/chrome/common/chrome_features.cc index 4617f3d..9330a6c 100644 --- a/chrome/common/chrome_features.cc +++ b/chrome/common/chrome_features.cc
@@ -763,10 +763,4 @@ const base::Feature kWriteBasicSystemProfileToPersistentHistogramsFile{ "WriteBasicSystemProfileToPersistentHistogramsFile", base::FEATURE_ENABLED_BY_DEFAULT}; - -#if defined(OS_ANDROID) -// Enables showing alternative incognito strings. -const base::Feature kIncognitoStrings{"IncognitoStrings", - base::FEATURE_DISABLED_BY_DEFAULT}; -#endif // defined(OS_ANDROID) } // namespace features
diff --git a/chrome/common/chrome_features.h b/chrome/common/chrome_features.h index ec1a2a2f..7d65ddc8 100644 --- a/chrome/common/chrome_features.h +++ b/chrome/common/chrome_features.h
@@ -479,10 +479,6 @@ COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kWriteBasicSystemProfileToPersistentHistogramsFile; -#if defined(OS_ANDROID) -COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kIncognitoStrings; -#endif // defined(OS_ANDROID) - bool PrefServiceEnabled(); // DON'T ADD RANDOM STUFF HERE. Put it in the main section above in
diff --git a/chrome/common/extensions/api/proxy.json b/chrome/common/extensions/api/proxy.json index b7ab7e61..26f8855 100644 --- a/chrome/common/extensions/api/proxy.json +++ b/chrome/common/extensions/api/proxy.json
@@ -23,7 +23,7 @@ "description": "An object encapsulating a single proxy server's specification.", "properties": { "scheme": {"$ref": "Scheme", "optional": true, "description": "The scheme (protocol) of the proxy server itself. Defaults to 'http'."}, - "host": {"type": "string", "description": "The URI of the proxy server. This must be an ASCII hostname (in Punycode format). IDNA is not supported, yet."}, + "host": {"type": "string", "description": "The hostname or IP address of the proxy server. Hostnames must be in ASCII (in Punycode format). IDNA is not supported, yet."}, "port": {"type": "integer", "optional": true, "description": "The port of the proxy server. Defaults to a port that depends on the scheme."} } },
diff --git a/chrome/services/cups_proxy/BUILD.gn b/chrome/services/cups_proxy/BUILD.gn index 898f6d31..fcfb01ac 100644 --- a/chrome/services/cups_proxy/BUILD.gn +++ b/chrome/services/cups_proxy/BUILD.gn
@@ -18,6 +18,7 @@ deps = [ "//base", + "//chrome/services/cups_proxy/public/cpp", "//chrome/services/cups_proxy/public/mojom", "//chromeos/dbus", "//net", @@ -28,6 +29,10 @@ # We stub this service if libCUPS is not present. if (use_cups) { configs += [ "//printing:cups" ] + sources += [ + "printer_installer.cc", + "printer_installer.h", + ] } public_deps = [ @@ -46,3 +51,20 @@ ":cups_proxy", ] } + +source_set("unit_tests") { + testonly = true + + if (use_cups) { + sources = [ + "printer_installer_unittest.cc", + ] + + deps = [ + ":cups_proxy", + ":test_support", + "//base", + "//testing/gtest", + ] + } +}
diff --git a/chrome/services/cups_proxy/printer_installer.cc b/chrome/services/cups_proxy/printer_installer.cc new file mode 100644 index 0000000..b0800841 --- /dev/null +++ b/chrome/services/cups_proxy/printer_installer.cc
@@ -0,0 +1,104 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/services/cups_proxy/printer_installer.h" + +#include <algorithm> +#include <memory> +#include <string> +#include <utility> + +#include "base/macros.h" +#include "base/memory/scoped_refptr.h" +#include "base/memory/weak_ptr.h" +#include "base/sequence_checker.h" +#include "base/task/post_task.h" +#include "base/threading/sequenced_task_runner_handle.h" +#include "chrome/services/cups_proxy/public/cpp/cups_util.h" +#include "chromeos/printing/printer_configuration.h" + +namespace cups_proxy { +namespace { + +using CupsProxyServiceDelegate = chromeos::printing::CupsProxyServiceDelegate; + +class PrinterInstallerImpl : public PrinterInstaller { + public: + explicit PrinterInstallerImpl( + base::WeakPtr<CupsProxyServiceDelegate> delegate); + ~PrinterInstallerImpl() override = default; + + void InstallPrinterIfNeeded(ipp_t* ipp, InstallPrinterCallback cb) override; + + private: + void OnInstallPrinter(InstallPrinterCallback cb, bool success); + + void Finish(InstallPrinterCallback cb, InstallPrinterResult res); + + // Service delegate granting access to printing stack dependencies. + base::WeakPtr<CupsProxyServiceDelegate> delegate_; + + SEQUENCE_CHECKER(sequence_checker_); + base::WeakPtrFactory<PrinterInstallerImpl> weak_factory_; +}; + +} // namespace + +PrinterInstallerImpl::PrinterInstallerImpl( + base::WeakPtr<CupsProxyServiceDelegate> delegate) + : delegate_(std::move(delegate)), weak_factory_(this) { + DETACH_FROM_SEQUENCE(sequence_checker_); +} + +void PrinterInstallerImpl::InstallPrinterIfNeeded(ipp_t* ipp, + InstallPrinterCallback cb) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + auto printer_uuid = GetPrinterId(ipp); + if (!printer_uuid) { + Finish(std::move(cb), InstallPrinterResult::kNoPrintersFound); + return; + } + + auto printer = delegate_->GetPrinter(*printer_uuid); + if (!printer) { + // If the requested printer DNE, we proxy to CUPSd and allow it to + // handle the error. + Finish(std::move(cb), InstallPrinterResult::kUnknownPrinterFound); + return; + } + + if (delegate_->IsPrinterInstalled(*printer)) { + Finish(std::move(cb), InstallPrinterResult::kSuccess); + return; + } + + // Install printer. + delegate_->SetupPrinter( + *printer, base::BindOnce(&PrinterInstallerImpl::OnInstallPrinter, + weak_factory_.GetWeakPtr(), std::move(cb))); +} + +void PrinterInstallerImpl::OnInstallPrinter(InstallPrinterCallback cb, + bool success) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + Finish(std::move(cb), + success ? InstallPrinterResult::kSuccess + : InstallPrinterResult::kPrinterInstallationFailure); +} + +void PrinterInstallerImpl::Finish(InstallPrinterCallback cb, + InstallPrinterResult res) { + base::SequencedTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(cb), res)); +} + +// static +std::unique_ptr<PrinterInstaller> PrinterInstaller::Create( + base::WeakPtr<CupsProxyServiceDelegate> delegate) { + return std::make_unique<PrinterInstallerImpl>(std::move(delegate)); +} + +} // namespace cups_proxy
diff --git a/chrome/services/cups_proxy/printer_installer.h b/chrome/services/cups_proxy/printer_installer.h new file mode 100644 index 0000000..27fef78 --- /dev/null +++ b/chrome/services/cups_proxy/printer_installer.h
@@ -0,0 +1,51 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_SERVICES_CUPS_PROXY_PRINTER_INSTALLER_H_ +#define CHROME_SERVICES_CUPS_PROXY_PRINTER_INSTALLER_H_ + +#include <cups/cups.h> + +#include <memory> + +#include "base/callback_forward.h" +#include "base/memory/weak_ptr.h" +#include "chrome/services/cups_proxy/cups_proxy_service_delegate.h" + +namespace cups_proxy { + +enum class InstallPrinterResult { + kSuccess = 0, + + // Couldn't find any printers referenced by the incoming request. + kNoPrintersFound, + + // Referenced printer is unknown to Chrome. + kUnknownPrinterFound, + kPrinterInstallationFailure, +}; + +using InstallPrinterCallback = base::OnceCallback<void(InstallPrinterResult)>; + +// This CupsProxyService internal manager ensures that any printers referenced +// by an incoming IPP request are installed into the CUPS daemon prior to +// proxying. This class can be created anywhere, but must be accessed from a +// sequenced context. +class PrinterInstaller { + public: + // Factory function. + static std::unique_ptr<PrinterInstaller> Create( + base::WeakPtr<chromeos::printing::CupsProxyServiceDelegate> delegate); + + virtual ~PrinterInstaller() = default; + + // Pre-installs any printers required by |ipp| into the CUPS daemon, as + // needed. |cb| will be run on this instance's sequenced context. + virtual void InstallPrinterIfNeeded(ipp_t* ipp, + InstallPrinterCallback cb) = 0; +}; + +} // namespace cups_proxy + +#endif // CHROME_SERVICES_CUPS_PROXY_PRINTER_INSTALLER_H_
diff --git a/chrome/services/cups_proxy/printer_installer_unittest.cc b/chrome/services/cups_proxy/printer_installer_unittest.cc new file mode 100644 index 0000000..3d2b432 --- /dev/null +++ b/chrome/services/cups_proxy/printer_installer_unittest.cc
@@ -0,0 +1,165 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <cups/cups.h> + +#include <map> +#include <string> +#include <utility> + +#include "base/bind.h" +#include "base/guid.h" +#include "base/memory/weak_ptr.h" +#include "base/test/scoped_task_environment.h" +#include "chrome/services/cups_proxy/fake_cups_proxy_service_delegate.h" +#include "chrome/services/cups_proxy/printer_installer.h" +#include "printing/backend/cups_ipp_util.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace cups_proxy { +namespace { + +using Printer = chromeos::Printer; + +// Generated via base::GenerateGUID. +const char kGenericGUID[] = "fd4c5f2e-7549-43d5-b931-9bf4e4f1bf51"; + +// Faked delegate gives control over PrinterInstaller's printing stack +// dependencies. +class FakeServiceDelegate + : public chromeos::printing::FakeCupsProxyServiceDelegate { + public: + FakeServiceDelegate() = default; + ~FakeServiceDelegate() override = default; + + void AddPrinter(const Printer& printer) { + installed_printers_.insert({printer.id(), false}); + } + + // Service delegate overrides. + bool IsPrinterInstalled(const Printer& printer) override { + if (!base::ContainsKey(installed_printers_, printer.id())) { + return false; + } + + return installed_printers_.at(printer.id()); + } + + base::Optional<Printer> GetPrinter(const std::string& id) override { + if (!base::ContainsKey(installed_printers_, id)) { + return base::nullopt; + } + + return Printer(id); + } + + void SetupPrinter( + const Printer& printer, + chromeos::printing::PrinterSetupCallback callback) override { + // PrinterInstaller is expected to have checked if |printer| is already + // installed before trying setup. + if (IsPrinterInstalled(printer)) { + return std::move(callback).Run(false); + } + + // Install printer. + installed_printers_[printer.id()] = true; + return std::move(callback).Run(true); + } + + private: + std::map<std::string, bool> installed_printers_; +}; + +class PrinterInstallerTest : public testing::Test { + public: + PrinterInstallerTest() : weak_factory_(this) { + delegate_ = std::make_unique<FakeServiceDelegate>(); + printer_installer_ = PrinterInstaller::Create(delegate_->GetWeakPtr()); + } + + ~PrinterInstallerTest() override = default; + + bool RunInstallPrinterIfNeeded(ipp_t* ipp, Printer to_install) { + bool success = false; + printer_installer_->InstallPrinterIfNeeded( + ipp, base::BindOnce(&PrinterInstallerTest::OnRunInstallPrinterIfNeeded, + weak_factory_.GetWeakPtr(), &success, + std::move(to_install))); + scoped_task_environment_.RunUntilIdle(); + return success; + } + + protected: + base::test::ScopedTaskEnvironment scoped_task_environment_; + + void OnRunInstallPrinterIfNeeded(bool* ret, + Printer to_install, + InstallPrinterResult result) { + if (result != InstallPrinterResult::kSuccess) { + return; + } + + // If printer wasn't installed, fail. + if (!delegate_->IsPrinterInstalled(to_install)) { + return; + } + + *ret = true; + } + + // Backend fake driving the PrinterInstaller. + std::unique_ptr<FakeServiceDelegate> delegate_; + + // The class being tested. This must be declared after the fakes, as its + // initialization must come after that of the fakes. + std::unique_ptr<PrinterInstaller> printer_installer_; + + base::WeakPtrFactory<PrinterInstallerTest> weak_factory_; +}; + +// Return a valid ScopedIppPtr that correctly references |id| in +// the printer-uri field. +::printing::ScopedIppPtr MakeIppReferencingPrinters(const std::string& id) { + ::printing::ScopedIppPtr ret = ::printing::WrapIpp(ippNew()); + + std::string uri = "ipp://localhost/printers/" + id; + ippAddString(ret.get(), IPP_TAG_PRINTER, IPP_TAG_URI, "printer-uri", NULL, + uri.c_str()); + + return ret; +} + +// Standard install known printer workflow. +TEST_F(PrinterInstallerTest, SimpleSanityTest) { + Printer to_install(kGenericGUID); + delegate_->AddPrinter(to_install); + + auto ipp = MakeIppReferencingPrinters(to_install.id()); + EXPECT_TRUE(RunInstallPrinterIfNeeded(ipp.get(), std::move(to_install))); +} + +// Should fail to install an unknown(previously unseen) printer. +TEST_F(PrinterInstallerTest, UnknownPrinter) { + Printer to_install(kGenericGUID); + + auto ipp = MakeIppReferencingPrinters(to_install.id()); + EXPECT_FALSE(RunInstallPrinterIfNeeded(ipp.get(), std::move(to_install))); +} + +// Ensure we never setup a printer that's already installed. +TEST_F(PrinterInstallerTest, InstallPrinterTwice) { + Printer to_install(kGenericGUID); + delegate_->AddPrinter(to_install); + + auto ipp = MakeIppReferencingPrinters(to_install.id()); + EXPECT_TRUE(RunInstallPrinterIfNeeded(ipp.get(), to_install)); + + // |printer_installer_| should notice printer is already installed and bail + // out. If it attempts setup, FakeServiceDelegate will fail the request. + EXPECT_TRUE(RunInstallPrinterIfNeeded(ipp.get(), to_install)); +} + +} // namespace +} // namespace cups_proxy
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 1fb3cf7..3812d68 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -44,6 +44,10 @@ include_js_tests = !(is_asan || is_msan || is_tsan) } +if (is_chromeos) { + import("//chrome/browser/chromeos/kiosk_next_home/kiosk_next.gni") +} + # This target exists to reference other test executables to bring these files # into the build. group("test") { @@ -759,7 +763,6 @@ "../browser/io_thread_browsertest.cc", "../browser/lifetime/browser_close_manager_browsertest.cc", "../browser/lifetime/browser_shutdown_browsertest.cc", - "../browser/loader/chrome_resource_dispatcher_host_delegate_browsertest.cc", "../browser/loader/cors_origin_access_list_browsertest.cc", "../browser/loader/signed_exchange_policy_browsertest.cc", "../browser/loadtimes_extension_bindings_browsertest.cc", @@ -2110,9 +2113,9 @@ sources += [ "../browser/ui/ash/assistant/assistant_context_browsertest.cc" ] } - if (is_chrome_branded) { + if (enable_kiosk_next) { sources += [ - # The KioskNext app is available in Chrome-branded builds only. + "../browser/chromeos/kiosk_next_home/kiosk_next_home_browsertest.cc", "../browser/ui/ash/kiosk_next_shell_client_browsertest.cc", ] } @@ -2710,7 +2713,6 @@ "../browser/download/download_prefs_unittest.cc", "../browser/download/download_query_unittest.cc", "../browser/download/download_request_limiter_unittest.cc", - "../browser/download/download_resource_throttle_unittest.cc", "../browser/download/download_status_updater_unittest.cc", "../browser/download/download_target_determiner_unittest.cc", "../browser/download/download_ui_controller_unittest.cc", @@ -2749,7 +2751,6 @@ "../browser/language/language_model_manager_factory_unittest.cc", "../browser/language/url_language_histogram_factory_unittest.cc", "../browser/loader/chrome_navigation_data_unittest.cc", - "../browser/loader/chrome_resource_dispatcher_host_delegate_unittest.cc", "../browser/logging_chrome_unittest.cc", "../browser/mac/exception_processor_unittest.mm", "../browser/mac/keystone_glue_unittest.mm", @@ -3013,6 +3014,7 @@ "../browser/translate/translate_service_unittest.cc", "../browser/ui/android/tab_model/tab_model_list_unittest.cc", "../browser/ui/android/tab_model/tab_model_unittest.cc", + "../browser/ui/android/toolbar/location_bar_model_android_unittest.cc", "../browser/ui/autofill/autofill_popup_layout_model_unittest.cc", "../browser/ui/autofill/popup_view_common_unittest.cc", "../browser/ui/autofill/popup_view_test_helpers.cc", @@ -4484,6 +4486,7 @@ if (is_chromeos) { deps += [ "//chrome/browser/chromeos:unit_tests", + "//chrome/services/cups_proxy:unit_tests", "//chromeos/ime:gencode", ] sources -=
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/OmniboxTestUtils.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/OmniboxTestUtils.java index f114bbed..f2c63a73 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/OmniboxTestUtils.java +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/OmniboxTestUtils.java
@@ -144,8 +144,8 @@ } @Override - public void start(Profile profile, String url, final String text, int cursorPosition, - boolean preventInlineAutocomplete, boolean focusedFromFakebox) { + public void start(Profile profile, String url, int pageClassification, final String text, + int cursorPosition, boolean preventInlineAutocomplete) { mStartAutocompleteCalled = true; mSuggestionsDispatcher = new Runnable() { @Override @@ -166,8 +166,8 @@ } @Override - public void startZeroSuggest(Profile profile, String omniboxText, String url, String title, - boolean focusedFromFakebox) { + public void startZeroSuggest(Profile profile, String omniboxText, String url, + int pageClassification, String title) { mZeroSuggestCalledCount++; } @@ -209,12 +209,12 @@ } @Override - public void start(Profile profile, String url, String text, int cursorPosition, - boolean preventInlineAutocomplete, boolean focusedFromFakebox) {} + public void start(Profile profile, String url, int pageClassification, String text, + int cursorPosition, boolean preventInlineAutocomplete) {} @Override - public void startZeroSuggest(Profile profile, String omniboxText, String url, String title, - boolean focusedFromFakebox) {} + public void startZeroSuggest(Profile profile, String omniboxText, String url, + int pageClassification, String title) {} @Override public void stop(boolean clear) {}
diff --git a/chrome/test/base/testing_browser_process.cc b/chrome/test/base/testing_browser_process.cc index 69aae880..93016b48 100644 --- a/chrome/test/base/testing_browser_process.cc +++ b/chrome/test/base/testing_browser_process.cc
@@ -125,9 +125,6 @@ DCHECK_EQ(static_cast<BrowserProcess*>(nullptr), g_browser_process); } -void TestingBrowserProcess::ResourceDispatcherHostCreated() { -} - void TestingBrowserProcess::FlushLocalStateAndReply(base::OnceClosure reply) { // This could be implemented the same way as in BrowserProcessImpl but it's // not currently expected to be used by TestingBrowserProcess users so we
diff --git a/chrome/test/base/testing_browser_process.h b/chrome/test/base/testing_browser_process.h index a01b7e7..07a4ad31 100644 --- a/chrome/test/base/testing_browser_process.h +++ b/chrome/test/base/testing_browser_process.h
@@ -69,7 +69,6 @@ static TestingBrowserProcess* GetGlobal(); // BrowserProcess overrides: - void ResourceDispatcherHostCreated() override; void EndSession() override; void FlushLocalStateAndReply(base::OnceClosure reply) override; metrics_services_manager::MetricsServicesManager* GetMetricsServicesManager()
diff --git a/chrome/test/chromedriver/BUILD.gn b/chrome/test/chromedriver/BUILD.gn index ab46b4e2..54d09b3 100644 --- a/chrome/test/chromedriver/BUILD.gn +++ b/chrome/test/chromedriver/BUILD.gn
@@ -14,6 +14,7 @@ "js/call_function.js", "js/dispatch_touch_event.js", "js/execute_async_script.js", + "js/execute_script.js", "js/focus.js", "js/get_element_location.js", "js/get_element_region.js",
diff --git a/chrome/test/chromedriver/chrome/stub_web_view.cc b/chrome/test/chromedriver/chrome/stub_web_view.cc index a762b621..21c8ea3 100644 --- a/chrome/test/chromedriver/chrome/stub_web_view.cc +++ b/chrome/test/chromedriver/chrome/stub_web_view.cc
@@ -94,11 +94,11 @@ return Status(kOk); } -Status StubWebView::CallUserSyncFunction(const std::string& frame, - const std::string& function, - const base::ListValue& args, - const base::TimeDelta& timeout, - std::unique_ptr<base::Value>* result) { +Status StubWebView::CallUserSyncScript(const std::string& frame, + const std::string& script, + const base::ListValue& args, + const base::TimeDelta& timeout, + std::unique_ptr<base::Value>* result) { return Status(kOk); }
diff --git a/chrome/test/chromedriver/chrome/stub_web_view.h b/chrome/test/chromedriver/chrome/stub_web_view.h index d8b61690..9443b53 100644 --- a/chrome/test/chromedriver/chrome/stub_web_view.h +++ b/chrome/test/chromedriver/chrome/stub_web_view.h
@@ -50,11 +50,11 @@ const base::ListValue& args, const base::TimeDelta& timeout, std::unique_ptr<base::Value>* result) override; - Status CallUserSyncFunction(const std::string& frame, - const std::string& function, - const base::ListValue& args, - const base::TimeDelta& timeout, - std::unique_ptr<base::Value>* result) override; + Status CallUserSyncScript(const std::string& frame, + const std::string& script, + const base::ListValue& args, + const base::TimeDelta& timeout, + std::unique_ptr<base::Value>* result) override; Status GetFrameByFunction(const std::string& frame, const std::string& function, const base::ListValue& args,
diff --git a/chrome/test/chromedriver/chrome/web_view.h b/chrome/test/chromedriver/chrome/web_view.h index dc2f82f..6468c832 100644 --- a/chrome/test/chromedriver/chrome/web_view.h +++ b/chrome/test/chromedriver/chrome/web_view.h
@@ -121,11 +121,11 @@ // used as the error code instead of |kUnknownError| in appropriate cases, and // respects timeout. // |result| will never be NULL on success. - virtual Status CallUserSyncFunction(const std::string& frame, - const std::string& function, - const base::ListValue& args, - const base::TimeDelta& timeout, - std::unique_ptr<base::Value>* result) = 0; + virtual Status CallUserSyncScript(const std::string& frame, + const std::string& script, + const base::ListValue& args, + const base::TimeDelta& timeout, + std::unique_ptr<base::Value>* result) = 0; // Gets the frame ID for a frame element returned by invoking the given // JavaScript function. |frame| is a frame ID or an empty string for the main
diff --git a/chrome/test/chromedriver/chrome/web_view_impl.cc b/chrome/test/chromedriver/chrome/web_view_impl.cc index 0d78d94..740ef9e 100644 --- a/chrome/test/chromedriver/chrome/web_view_impl.cc +++ b/chrome/test/chromedriver/chrome/web_view_impl.cc
@@ -404,12 +404,17 @@ frame, function, args, false, timeout, result); } -Status WebViewImpl::CallUserSyncFunction(const std::string& frame, - const std::string& function, - const base::ListValue& args, - const base::TimeDelta& timeout, - std::unique_ptr<base::Value>* result) { - return CallFunctionWithTimeout(frame, function, args, timeout, result); +Status WebViewImpl::CallUserSyncScript(const std::string& frame, + const std::string& script, + const base::ListValue& args, + const base::TimeDelta& timeout, + std::unique_ptr<base::Value>* result) { + base::ListValue sync_args; + sync_args.AppendString(script); + // Deep-copy needed since ListValue only accepts unique_ptrs of Values. + sync_args.Append(args.CreateDeepCopy()); + return CallFunctionWithTimeout(frame, kExecuteScriptScript, sync_args, + timeout, result); } Status WebViewImpl::CallUserAsyncFunction( @@ -1137,6 +1142,7 @@ if (context_id) params.SetInteger("contextId", context_id); params.SetBoolean("returnByValue", return_type == ReturnByValue); + params.SetBoolean("awaitPromise", true); std::unique_ptr<base::DictionaryValue> cmd_result; Timeout local_timeout(timeout);
diff --git a/chrome/test/chromedriver/chrome/web_view_impl.h b/chrome/test/chromedriver/chrome/web_view_impl.h index ff01978..802a99a 100644 --- a/chrome/test/chromedriver/chrome/web_view_impl.h +++ b/chrome/test/chromedriver/chrome/web_view_impl.h
@@ -84,11 +84,11 @@ const base::ListValue& args, const base::TimeDelta& timeout, std::unique_ptr<base::Value>* result) override; - Status CallUserSyncFunction(const std::string& frame, - const std::string& function, - const base::ListValue& args, - const base::TimeDelta& timeout, - std::unique_ptr<base::Value>* result) override; + Status CallUserSyncScript(const std::string& frame, + const std::string& script, + const base::ListValue& args, + const base::TimeDelta& timeout, + std::unique_ptr<base::Value>* result) override; Status CallUserAsyncFunction(const std::string& frame, const std::string& function, const base::ListValue& args,
diff --git a/chrome/test/chromedriver/js/call_function.js b/chrome/test/chromedriver/js/call_function.js index 4ff5d86..5b63746 100644 --- a/chrome/test/chromedriver/js/call_function.js +++ b/chrome/test/chromedriver/js/call_function.js
@@ -415,20 +415,28 @@ const cache = getPageCache(null, w3cEnabled); cache.clearStale(); + function buildError(error) { + return { + status: error.code || StatusCode.JAVA_SCRIPT_ERROR, + value: error.message || error + }; + } + let status = 0; let returnValue; try { const unwrappedArgs = jsonDeserialize(args, [], cache); - if (opt_unwrappedReturn) - return func.apply(null, unwrappedArgs); - const tmp = jsonSerialize(func.apply(null, unwrappedArgs), []); - returnValue = tmp; + const tmp = func.apply(null, unwrappedArgs); + return Promise.resolve(tmp).then((result) => { + if (opt_unwrappedReturn) + return result; + const clone = jsonSerialize(result, []); + return { + status: 0, + value: clone + }; + }).catch(buildError); } catch (error) { - status = error.code || StatusCode.JAVA_SCRIPT_ERROR; - returnValue = error.message; + return buildError(error); } - return { - status: status, - value: returnValue - }; }
diff --git a/chrome/test/chromedriver/js/call_function_test.html b/chrome/test/chromedriver/js/call_function_test.html index d54eb8e0..e4ae49e2 100644 --- a/chrome/test/chromedriver/js/call_function_test.html +++ b/chrome/test/chromedriver/js/call_function_test.html
@@ -3,7 +3,6 @@ <script src='test.js'></script> <script src='call_function.js'></script> <script> - function wrap(value) { return jsonSerialize(value, []); } @@ -38,53 +37,70 @@ } } -function testCallFunctionNoArgs() { +function testCallFunctionNoArgs(runner) { clearCache(); - var result = callFunction(function() { return 1; }, []); - assertEquals(0, result.status); - assertEquals(1, result.value); + callFunction(function() { return 1; }, []).then((result) => { + assertEquals(0, result.status); + assertEquals(1, result.value); + runner.continueTesting(); + }); + runner.waitForAsync(); } -function testCallFunctionThrows() { +function testCallFunctionThrows(runner) { clearCache(); - - var result = callFunction(function() { throw new Error('fake error'); }, - []); - assertEquals(StatusCode.JAVA_SCRIPT_ERROR, result.status); - assertEquals('fake error', result.value); - - result = callFunction(function() { - var e = new Error('fake error'); - e.code = 77; - e.message = 'CUSTOM'; - throw e; - }, []); - assertEquals(77, result.status); - assertEquals('CUSTOM', result.value); + let allComplete = 0; + callFunction(function() { throw new Error('fake error'); }, + []).then((result) => { + assertEquals(StatusCode.JAVA_SCRIPT_ERROR, result.status); + assertEquals('fake error', result.value); + if (allComplete) + runner.continueTesting(); + allComplete += 1; + }); + callFunction(function() { + var e = new Error('fake error'); + e.code = 77; + e.message = 'CUSTOM'; + throw e; + }, []).then((result) => { + assertEquals(77, result.status); + assertEquals('CUSTOM', result.value); + if (allComplete) + runner.continueTesting(); + allComplete += 1; + }); + runner.waitForAsync(); } -function testCallFunctionArgs() { +function testCallFunctionArgs(runner) { clearCache(); function func(primitive, elem) { return [primitive, elem.querySelector('div')]; } - var result = callFunction(func, [1, wrap(document)]); - assertEquals(0, result.status); - assertEquals(1, result.value[0]); - var cache = getPageCache(); - assertEquals(document.querySelector('div'), unwrap(result.value[1], cache)); + callFunction(func, [1, wrap(document)]).then((result) => { + assertEquals(0, result.status); + assertEquals(1, result.value[0]); + const cache = getPageCache(); + assertEquals(document.querySelector('div'), unwrap(result.value[1], cache)); + runner.continueTesting(); + }); + runner.waitForAsync(); } -function testCallFunctionArgsUnwrappedReturn() { +function testCallFunctionArgsUnwrappedReturn(runner) { clearCache(); function func(elem) { return elem.querySelector('div'); } - var result = callFunction(func, [wrap(document)], false, true); - assertEquals(document.querySelector('div'), result); + callFunction(func, [wrap(document)], false, true).then((result) => { + assertEquals(document.querySelector('div'), result); + runner.continueTesting(); + }); + runner.waitForAsync(); } function testCacheWrap() { @@ -206,7 +222,7 @@ } } -function testCallFunctionWithShadowHost() { +function testCallFunctionWithShadowHost(runner) { clearCache(); // Set up something in the shadow DOM. @@ -218,17 +234,18 @@ return element; } var wrappedHost = wrap(host); - - var result = callFunction(func, [wrappedHost]); - assertEquals(0, result.status); - assertEquals(wrappedHost['ELEMENT'], result.value['ELEMENT']); - var cache = getPageCache(); - assertEquals(host, unwrap(result.value, cache)); - - document.body.removeChild(host); + callFunction(func, [wrappedHost]).then((result) => { + assertEquals(0, result.status); + assertEquals(wrappedHost['ELEMENT'], result.value['ELEMENT']); + var cache = getPageCache(); + assertEquals(host, unwrap(result.value, cache)); + document.body.removeChild(host); + runner.continueTesting(); + }); + runner.waitForAsync(); } -function testCallFunctionWithShadowRoot() { +function testCallFunctionWithShadowRoot(runner) { clearCache(); // Set up something in the shadow DOM. @@ -243,18 +260,21 @@ var wrappedRoot = wrap(root); // Should handle shadow root as an argument. - result = callFunction(func, [wrappedRoot]); - assertEquals(0, result.status); - assertEquals(wrappedRoot['ELEMENT'], result.value['ELEMENT']); - var cache = getPageCache(); - assertEquals(root, unwrap(result.value, cache)); - - document.body.removeChild(host); + callFunction(func, [wrappedRoot]).then((result) => { + assertEquals(0, result.status); + assertEquals(wrappedRoot['ELEMENT'], result.value['ELEMENT']); + var cache = getPageCache(); + assertEquals(root, unwrap(result.value, cache)); + + document.body.removeChild(host); + runner.continueTesting(); + }); + runner.waitForAsync(); } function testCacheWithShadowDomAttached() { clearCache(); - var pageCache = getPageCache(); + const pageCache = getPageCache(); // Set up something in the shadow DOM. var host = document.body.appendChild(document.createElement('div'));
diff --git a/chrome/test/chromedriver/js/execute_script.js b/chrome/test/chromedriver/js/execute_script.js new file mode 100644 index 0000000..7e149a5 --- /dev/null +++ b/chrome/test/chromedriver/js/execute_script.js
@@ -0,0 +1,20 @@ +// Copyright (c) 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** +* Execute the given script following the Execute-Script specification laid out +* in the W3C WebDriver spec, except for serialization/deserialization of args, +* which is handled by callFunction. +* +* @param {string} script The script to be executed. +* @param {!Array<*>} args Arguments to be passed to the script. +*/ +function executeScript(script, args) { + const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor; + try { + return Promise.resolve(new AsyncFunction(script).apply(null, args)); + } catch (e) { + return Promise.reject(e); + } +}
diff --git a/chrome/test/chromedriver/js/execute_script_test.html b/chrome/test/chromedriver/js/execute_script_test.html new file mode 100644 index 0000000..dedf471 --- /dev/null +++ b/chrome/test/chromedriver/js/execute_script_test.html
@@ -0,0 +1,62 @@ +<!DOCTYPE HTML> +<html> +<script src='test.js'></script> +<script src='execute_script.js'></script> +<script> + +function assertThrowsError(promise, opt_error) { + promise.then((result) => { assert(false); }) + .catch((error) => { + if (opt_error) + assertEquals(error, opt_error); + }); +} + +async function testScriptThrows() { + const promise = executeScript('f(123);', []); + assertThrowsError(promise); +} + +async function testScriptThrowingReturnsJSError() { + let script = 'let args = arguments; throw new Error(args[0]);'; + let script_args = ['foo error', 'unused']; + executeScript(script, script_args).then((result) => { assert(false); }) + .catch((error) => { + assert(error.message.indexOf('foo error') != -1); + }); +} + +async function testAwaitResolveSucceeds() { + let script = 'return await Promise.resolve(arguments[0]);'; + let script_args = ['bar success', 'unused']; + let result = await executeScript(script, script_args); + assertEquals('bar success', result); +} + +async function testAwaitRejectFails() { + let script = 'return await Promise.reject(arguments[0]);'; + let script_args = ['foo failure', 'unused']; + assertThrowsError(executeScript(script, script_args), 'foo failure'); +} + +async function testScriptWithArgs() { + var injectedArgs = null; + function captureArguments(args) { + injectedArgs = args; + } + // Pass function captureArguments as the first argument. It is used to capture + // the injected arguments to the following script. + var script = + 'var args = arguments; args[0](args); return args[1]'; + var script_args = [captureArguments, 1]; + var result = await executeScript(script, script_args); + assertEquals(2, injectedArgs.length); + assertEquals(captureArguments, injectedArgs[0]); + assertEquals(1, injectedArgs[1]); + assertEquals(1, result); +} + +</script> +<body> +</body> +</html>
diff --git a/chrome/test/chromedriver/window_commands.cc b/chrome/test/chromedriver/window_commands.cc index a85a4da..626c0d4 100644 --- a/chrome/test/chromedriver/window_commands.cc +++ b/chrome/test/chromedriver/window_commands.cc
@@ -575,9 +575,9 @@ if (script.find("//") != std::string::npos) script = script + "\n"; - Status status = web_view->CallUserSyncFunction( - session->GetCurrentFrameId(), "function(){" + script + "}", *args, - session->script_timeout, value); + Status status = + web_view->CallUserSyncScript(session->GetCurrentFrameId(), script, + *args, session->script_timeout, value); if (status.code() == kTimeout) return Status(kScriptTimeout); return status;
diff --git a/chrome/test/data/local_ntp/local_ntp_browsertest.html b/chrome/test/data/local_ntp/local_ntp_browsertest.html index b69acff..837fcf4 100644 --- a/chrome/test/data/local_ntp/local_ntp_browsertest.html +++ b/chrome/test/data/local_ntp/local_ntp_browsertest.html
@@ -205,8 +205,8 @@ <div id="backgrounds-image-menu" class="menu-panel"></div> <div id="shortcuts-menu" class="menu-panel"> <div id="sh-options"> - <div id="sh-option-cl" class="sh-option"> - <div class="sh-option-image"> + <div class="sh-option"> + <div id="sh-option-cl" class="sh-option-image" tabindex="0" role="button"> <div class="sh-option-icon"></div> <div class="sh-option-mini"> <div class="mini-page"> @@ -214,13 +214,12 @@ <div class="mini-shortcuts"></div> </div> </div> - <div class="sh-option-select"></div> </div> - <div class="sh-title">$i18n{myShortcuts}</div> + <div class="sh-option-title">$i18n{myShortcuts}</div> $i18n{shortcutsCurated} </div> - <div id="sh-option-mv" class="sh-option"> - <div class="sh-option-image"> + <div class="sh-option"> + <div id="sh-option-mv" class="sh-option-image" tabindex="0" role="button"> <div class="sh-option-icon"></div> <div class="sh-option-mini"> <div class="mini-page"> @@ -228,9 +227,8 @@ <div class="mini-shortcuts"></div> </div> </div> - <div class="sh-option-select"></div> </div> - <div class="sh-title">$i18n{mostVisited}</div> + <div class="sh-option-title">$i18n{mostVisited}</div> $i18n{shortcutsSuggested} </div> </div>
diff --git a/chrome/test/data/pdf/pdf_embed_with_hung_sibling_subframe.html b/chrome/test/data/pdf/pdf_embed_with_hung_sibling_subframe.html new file mode 100644 index 0000000..4cd3f80 --- /dev/null +++ b/chrome/test/data/pdf/pdf_embed_with_hung_sibling_subframe.html
@@ -0,0 +1,3 @@ +<!doctype html> +<embed type="application/pdf" src="test.pdf"></embed> +<iframe id="hung_subframe" src="/hung"></iframe>
diff --git a/chrome/test/data/webui/async_gen.js b/chrome/test/data/webui/async_gen.js index fe4a9e6..e6bea9d 100644 --- a/chrome/test/data/webui/async_gen.js +++ b/chrome/test/data/webui/async_gen.js
@@ -190,24 +190,6 @@ testRan = true; } -// Test overriding globals. -TEST_F('WebUIBrowserAsyncGenTest', 'TestRegisterMockGlobals', function() { - this.makeAndRegisterMockGlobals(['setTestRanTrue']); - - // Mock the setTestRanTrue global function. - this.mockGlobals.expects(once()).setTestRanTrue().will(runAllActionsAsync( - WhenTestDone.ALWAYS, callGlobalWithSavedArgs(null, 'setTestRanTrue'), - callFunction(function() { - assertTrue(testRan); - }))); - - // Cause setTestRanTrue to be invoked asynchronously. - chrome.send('callJS', ['setTestRanTrue']); - - // In case the global isn't called, call testDone to collect the results. - chrome.send('callJS', ['testDone']); -}); - /** * Will be set to the runTest continuation by the following test fixture. * @type {Function} @@ -258,31 +240,3 @@ TEST_F('WebUIBrowserAsyncGenDeferredTest', 'TestDeferRunTest', function() { this.ranTest_ = true; }); - -/** - * Test fixture for testing async tests are deferred until global is called. - * @constructor - */ -function WebUIBrowserAsyncGenDeferredToGlobalTest() {} - -WebUIBrowserAsyncGenDeferredToGlobalTest.prototype = { - __proto__: WebUIBrowserAsyncGenDeferredTest.prototype, - - /** @inheritDoc */ - setUp: function() { - this.makeAndRegisterMockGlobals(['setTestRanTrue']); - this.mockGlobals.expects(once()).setTestRanTrue().will(runAllActionsAsync( - WhenTestDone.ALWAYS, callGlobalWithSavedArgs(null, 'setTestRanTrue'), - callFunction(deferRunTest))); - - // Cause setTestRanTrue to be invoked asynchronously. - chrome.send('callJS', ['setTestRanTrue']); - }, -}; - -TEST_F( - 'WebUIBrowserAsyncGenDeferredToGlobalTest', 'TestDeferRunTestToGlobal', - function() { - this.ranTest_ = true; - assertTrue(testRan); - });
diff --git a/chrome/test/data/webui/cr_elements/cr_button_tests.js b/chrome/test/data/webui/cr_elements/cr_button_tests.js new file mode 100644 index 0000000..4a18f84 --- /dev/null +++ b/chrome/test/data/webui/cr_elements/cr_button_tests.js
@@ -0,0 +1,80 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +suite('cr-button', function() { + let button; + + setup(() => { + PolymerTest.clearBody(); + button = document.createElement('cr-button'); + document.body.appendChild(button); + }); + + /** @param {string} key */ + function press(key) { + button.dispatchEvent(new KeyboardEvent('keydown', {key: key})); + button.dispatchEvent(new KeyboardEvent('keyup', {key: key})); + } + + test('label is displayed', async () => { + const widthWithoutLabel = button.offsetWidth; + document.body.innerHTML = '<cr-button>Long Label</cr-button>'; + button = document.body.querySelector('cr-button'); + assertTrue(widthWithoutLabel < button.offsetWidth); + }); + + test('tabindex and aria-disabled', () => { + assertFalse(button.disabled); + assertFalse(button.hasAttribute('disabled')); + assertEquals('0', button.getAttribute('tabindex')); + assertEquals('false', button.getAttribute('aria-disabled')); + button.disabled = true; + assertTrue(button.hasAttribute('disabled')); + assertEquals('-1', button.getAttribute('tabindex')); + assertEquals('true', button.getAttribute('aria-disabled')); + }); + + test('enter/space/click events and programmatic click() calls', async () => { + let clickCount = 0; + const clickHandler = () => { + clickCount++; + }; + button.addEventListener('click', clickHandler); + + const checkClicks = expectedCount => { + clickCount = 0; + press('Enter'); + press(' '); + button.dispatchEvent(new MouseEvent('click')); + button.click(); + assertEquals(expectedCount, clickCount); + }; + + checkClicks(4); + button.disabled = true; + checkClicks(0); + button.disabled = false; + checkClicks(4); + + button.removeEventListener('click', clickHandler); + }); + + test('when tabindex is -1, it stays -1', async () => { + document.body.innerHTML = '<cr-button tabindex="-1"></cr-button>'; + button = document.body.querySelector('cr-button'); + assertEquals('-1', button.getAttribute('tabindex')); + }); + + test('hidden', () => { + assertFalse(button.hidden); + assertFalse(button.hasAttribute('hidden')); + assertNotEquals('none', getComputedStyle(button).display); + button.hidden = true; + assertTrue(button.hasAttribute('hidden')); + assertEquals('none', getComputedStyle(button).display); + button.hidden = false; + assertFalse(button.hasAttribute('hidden')); + assertNotEquals('none', getComputedStyle(button).display); + }); +});
diff --git a/chrome/test/data/webui/cr_elements/cr_elements_browsertest.js b/chrome/test/data/webui/cr_elements/cr_elements_browsertest.js index 315e50d..a5b25dab6 100644 --- a/chrome/test/data/webui/cr_elements/cr_elements_browsertest.js +++ b/chrome/test/data/webui/cr_elements/cr_elements_browsertest.js
@@ -478,6 +478,28 @@ * @constructor * @extends {CrElementsBrowserTest} */ +function CrElementsButtonTest() {} + +CrElementsButtonTest.prototype = { + __proto__: CrElementsBrowserTest.prototype, + + /** @override */ + browsePreload: 'chrome://resources/cr_elements/cr_button/cr_button.html', + + /** @override */ + extraLibraries: CrElementsBrowserTest.prototype.extraLibraries.concat([ + 'cr_button_tests.js', + ]), +}; + +TEST_F('CrElementsButtonTest', 'All', function() { + mocha.run(); +}); + +/** + * @constructor + * @extends {CrElementsBrowserTest} + */ function CrElementsIconButtonTest() {} CrElementsIconButtonTest.prototype = { @@ -572,7 +594,8 @@ //////////////////////////////////////////////////////////////////////////////// // View Manager Tests -CrElementsViewManagerTest = class extends CrElementsBrowserTest { +// eslint-disable-next-line no-var +var CrElementsViewManagerTest = class extends CrElementsBrowserTest { /** @override */ get browsePreload() { return 'chrome://resources/cr_elements/cr_view_manager/cr_view_manager.html';
diff --git a/chrome/test/data/webui/extensions/a11y/extensions_a11y_test.js b/chrome/test/data/webui/extensions/a11y/extensions_a11y_test.js index c8bcf0b..fcb77c0 100644 --- a/chrome/test/data/webui/extensions/a11y/extensions_a11y_test.js +++ b/chrome/test/data/webui/extensions/a11y/extensions_a11y_test.js
@@ -15,7 +15,8 @@ * @constructor * @extends {PolymerTest} */ -CrExtensionsA11yTest = class extends PolymerTest { +// eslint-disable-next-line no-var +var CrExtensionsA11yTest = class extends PolymerTest { /** @override */ get browsePreload() { return 'chrome://extensions/';
diff --git a/chrome/test/data/webui/extensions/cr_extensions_browsertest.js b/chrome/test/data/webui/extensions/cr_extensions_browsertest.js index a8c87d3..8d59d2d2 100644 --- a/chrome/test/data/webui/extensions/cr_extensions_browsertest.js +++ b/chrome/test/data/webui/extensions/cr_extensions_browsertest.js
@@ -73,7 +73,7 @@ /** * Test fixture with one installed extension. */ -CrExtensionsBrowserTestWithInstalledExtension = +const CrExtensionsBrowserTestWithInstalledExtension = class extends CrExtensionsBrowserTest { /** @override */ testGenPreamble() { @@ -85,7 +85,8 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Sidebar Tests -CrExtensionsSidebarTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsSidebarTest = class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/sidebar.html'; @@ -115,7 +116,8 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Toolbar Tests -CrExtensionsToolbarTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsToolbarTest = class extends CrExtensionsBrowserTest { /** @override */ get extraLibraries() { return super.extraLibraries.concat([ @@ -156,7 +158,8 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Item Tests -CrExtensionsItemsTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsItemsTest = class extends CrExtensionsBrowserTest { get browsePreload() { return 'chrome://extensions/item.html'; } @@ -215,7 +218,8 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Activity Log Tests -CrExtensionsActivityLogTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsActivityLogTest = class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/activity_log/activity_log.html'; @@ -241,7 +245,8 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Activity Log History Tests -CrExtensionsActivityLogHistoryTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsActivityLogHistoryTest = class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/activity_log/activity_log_history.html'; @@ -261,7 +266,9 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Activity Log Item Tests -CrExtensionsActivityLogHistoryItemTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsActivityLogHistoryItemTest = + class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/activity_log/activity_log_history_item.html'; @@ -281,7 +288,8 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Activity Log Stream Tests -CrExtensionsActivityLogStreamTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsActivityLogStreamTest = class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/activity_log/activity_log_stream.html'; @@ -301,7 +309,9 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Activity Log Stream Item Tests -CrExtensionsActivityLogStreamItemTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsActivityLogStreamItemTest = + class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/activity_log/activity_log_stream_item.html'; @@ -321,7 +331,8 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Detail View Tests -CrExtensionsDetailViewTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsDetailViewTest = class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/detail_view.html'; @@ -363,7 +374,8 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Item List Tests -CrExtensionsItemListTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsItemListTest = class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/item_list.html'; @@ -413,7 +425,8 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Load Error Tests -CrExtensionsLoadErrorTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsLoadErrorTest = class extends CrExtensionsBrowserTest { /** @override */ get extraLibraries() { return super.extraLibraries.concat([ @@ -442,7 +455,8 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Manager Tests -CrExtensionsManagerUnitTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsManagerUnitTest = class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/manager.html'; @@ -502,7 +516,8 @@ }); GEN('#endif'); -CrExtensionsManagerUnitTestWithActivityLogFlag = +// eslint-disable-next-line no-var +var CrExtensionsManagerUnitTestWithActivityLogFlag = class extends CrExtensionsManagerUnitTest { /** @override */ get commandLineSwitches() { @@ -519,7 +534,8 @@ extension_manager_tests.TestNames.UpdateFromActivityLog); }); -CrExtensionsManagerTestWithMultipleExtensionTypesInstalled = +// eslint-disable-next-line no-var +var CrExtensionsManagerTestWithMultipleExtensionTypesInstalled = class extends CrExtensionsBrowserTest { /** @override */ get extraLibraries() { @@ -561,7 +577,8 @@ this.runMochaTest(extension_manager_tests.TestNames.ChangePages); }); -CrExtensionsManagerTestWithIdQueryParam = +// eslint-disable-next-line no-var +var CrExtensionsManagerTestWithIdQueryParam = class extends CrExtensionsBrowserTestWithInstalledExtension { /** @override */ get browsePreload() { @@ -616,7 +633,8 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Keyboard Shortcuts Tests -CrExtensionsShortcutTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsShortcutTest = class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/keyboard_shortcuts.html'; @@ -651,7 +669,8 @@ this.runMochaTest(extension_shortcut_tests.TestNames.ScopeChange); }); -CrExtensionsShortcutInputTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsShortcutInputTest = class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/keyboard_shortcuts.html'; @@ -677,7 +696,8 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Pack Dialog Tests -CrExtensionsPackDialogTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsPackDialogTest = class extends CrExtensionsBrowserTest { /** @override */ get extraLibraries() { return super.extraLibraries.concat([ @@ -725,7 +745,8 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Options Dialog Tests -CrExtensionsOptionsDialogTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsOptionsDialogTest = class extends CrExtensionsBrowserTest { /** @override */ testGenPreamble() { GEN(' InstallExtensionWithInPageOptions();'); @@ -752,7 +773,8 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Error Page Tests -CrExtensionsErrorPageTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsErrorPageTest = class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/error_page.html'; @@ -786,7 +808,8 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Code Section Tests -CrExtensionsCodeSectionTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsCodeSectionTest = class extends CrExtensionsBrowserTest { /** @override */ get extraLibraries() { return super.extraLibraries.concat([ @@ -811,7 +834,8 @@ //////////////////////////////////////////////////////////////////////////////// // Extension Navigation Helper Tests -CrExtensionsNavigationHelperTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsNavigationHelperTest = class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/navigation_helper.html'; @@ -857,7 +881,8 @@ //////////////////////////////////////////////////////////////////////////////// // Error Console tests -CrExtensionsErrorConsoleTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsErrorConsoleTest = class extends CrExtensionsBrowserTest { /** @override */ get extraLibraries() { return super.extraLibraries.concat([ @@ -891,7 +916,8 @@ //////////////////////////////////////////////////////////////////////////////// // extensions-toggle-row tests. -CrExtensionsToggleRowTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsToggleRowTest = class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/toggle_row.html'; @@ -914,7 +940,8 @@ GEN('#if defined(OS_CHROMEOS)'); -CrExtensionsKioskModeTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsKioskModeTest = class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/kiosk_dialog.html'; @@ -962,7 +989,8 @@ //////////////////////////////////////////////////////////////////////////////// // RuntimeHostsDialog tests -CrExtensionsRuntimeHostsDialogTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsRuntimeHostsDialogTest = class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/runtime_hosts_dialog.html'; @@ -982,7 +1010,9 @@ //////////////////////////////////////////////////////////////////////////////// // RuntimeHostPermissions tests -CrExtensionsRuntimeHostPermissionsTest = class extends CrExtensionsBrowserTest { +// eslint-disable-next-line no-var +var CrExtensionsRuntimeHostPermissionsTest = + class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() { return 'chrome://extensions/runtime_host_permissions.html'; @@ -1002,7 +1032,8 @@ //////////////////////////////////////////////////////////////////////////////// // HostPermissionsToggleList tests -CrExtensionsHostPermissionsToggleListTest = +// eslint-disable-next-line no-var +var CrExtensionsHostPermissionsToggleListTest = class extends CrExtensionsBrowserTest { /** @override */ get browsePreload() {
diff --git a/chrome/test/data/webui/extensions/cr_extensions_interactive_ui_tests.js b/chrome/test/data/webui/extensions/cr_extensions_interactive_ui_tests.js index 881c5d9..d659f1a 100644 --- a/chrome/test/data/webui/extensions/cr_extensions_interactive_ui_tests.js +++ b/chrome/test/data/webui/extensions/cr_extensions_interactive_ui_tests.js
@@ -36,7 +36,8 @@ /** Test fixture for Sync Page. */ -CrExtensionsOptionsPageTest = class extends CrExtensionsInteractiveUITest { +// eslint-disable-next-line no-var +var CrExtensionsOptionsPageTest = class extends CrExtensionsInteractiveUITest { /** @override */ get browsePreload() { return 'chrome://extensions/?id=ibbpngabdmdpednkhonkkobdeccpkiff';
diff --git a/chrome/test/data/webui/management/.eslintrc.js b/chrome/test/data/webui/management/.eslintrc.js new file mode 100644 index 0000000..cce1973 --- /dev/null +++ b/chrome/test/data/webui/management/.eslintrc.js
@@ -0,0 +1,9 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module.exports = { + 'rules': { + 'no-var': 'error', + }, +};
diff --git a/chrome/test/data/webui/management/a11y/management_a11y_test.js b/chrome/test/data/webui/management/a11y/management_a11y_test.js index 75842b1..a89088c 100644 --- a/chrome/test/data/webui/management/a11y/management_a11y_test.js +++ b/chrome/test/data/webui/management/a11y/management_a11y_test.js
@@ -15,7 +15,8 @@ * @constructor * @extends {PolymerTest} */ -CrManagementA11yTest = class extends PolymerTest { +// eslint-disable-next-line no-var +var CrManagementA11yTest = class extends PolymerTest { /** @override */ get browsePreload() { return 'chrome://management/';
diff --git a/chrome/test/data/webui/print_preview/print_preview_interactive_ui_tests.js b/chrome/test/data/webui/print_preview/print_preview_interactive_ui_tests.js index bacc14745..2066a7f7 100644 --- a/chrome/test/data/webui/print_preview/print_preview_interactive_ui_tests.js +++ b/chrome/test/data/webui/print_preview/print_preview_interactive_ui_tests.js
@@ -45,7 +45,8 @@ } }; -PrintPreviewPrintHeaderInteractiveTest = +// eslint-disable-next-line no-var +var PrintPreviewPrintHeaderInteractiveTest = class extends PrintPreviewInteractiveUITest { /** @override */ get browsePreload() { @@ -72,7 +73,8 @@ print_header_interactive_test.TestNames.FocusPrintOnReady); }); -PrintPreviewButtonStripInteractiveTest = +// eslint-disable-next-line no-var +var PrintPreviewButtonStripInteractiveTest = class extends PrintPreviewInteractiveUITest { /** @override */ get browsePreload() { @@ -106,7 +108,8 @@ button_strip_interactive_test.TestNames.FocusPrintOnReady); }); -PrintPreviewDestinationDialogInteractiveTest = +// eslint-disable-next-line no-var +var PrintPreviewDestinationDialogInteractiveTest = class extends PrintPreviewInteractiveUITest { /** @override */ get browsePreload() { @@ -145,7 +148,9 @@ destination_dialog_interactive_test.TestNames.EscapeSearchBox); }); -PrintPreviewPagesSettingsTest = class extends PrintPreviewInteractiveUITest { +// eslint-disable-next-line no-var +var PrintPreviewPagesSettingsTest = + class extends PrintPreviewInteractiveUITest { /** @override */ get browsePreload() { return 'chrome://print/ui/pages_settings.html'; @@ -183,7 +188,8 @@ pages_settings_test.TestNames.EnterOnInputTriggersPrint); }); -PrintPreviewNumberSettingsSectionInteractiveTest = +// eslint-disable-next-line no-var +var PrintPreviewNumberSettingsSectionInteractiveTest = class extends PrintPreviewInteractiveUITest { /** @override */ get browsePreload() { @@ -212,7 +218,8 @@ .BlurResetsEmptyInput); }); -PrintPreviewScalingSettingsInteractiveTest = +// eslint-disable-next-line no-var +var PrintPreviewScalingSettingsInteractiveTest = class extends PrintPreviewInteractiveUITest { /** @override */ get browsePreload() {
diff --git a/chrome/test/data/webui/print_preview/print_preview_ui_browsertest.js b/chrome/test/data/webui/print_preview/print_preview_ui_browsertest.js index 46ff25a..ca316ca9 100644 --- a/chrome/test/data/webui/print_preview/print_preview_ui_browsertest.js +++ b/chrome/test/data/webui/print_preview/print_preview_ui_browsertest.js
@@ -44,7 +44,8 @@ } }; -PrintPreviewAppTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewAppTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/app.html'; @@ -77,7 +78,8 @@ this.runMochaTest(print_preview_app_test.TestNames.PrintPresets); }); -PrintPreviewSidebarTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewSidebarTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/sidebar.html'; @@ -107,7 +109,8 @@ .SettingsSectionsVisibilityChange); }); -PrintPreviewPagesSettingsTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewPagesSettingsTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/pages_settings.html'; @@ -144,7 +147,8 @@ this.runMochaTest(pages_settings_test.TestNames.NupChangesPages); }); -PrintPreviewPolicyTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewPolicyTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/app.html'; @@ -184,7 +188,8 @@ this.runMochaTest(policy_tests.TestNames.DisableHeaderFooterByPolicy); }); -PrintPreviewSettingsSelectTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewSettingsSelectTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/settings_select.html'; @@ -204,7 +209,8 @@ mocha.run(); }); -PrintPreviewSelectBehaviorTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewSelectBehaviorTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/select_behavior.html'; @@ -234,7 +240,8 @@ this.runMochaTest(select_behavior_test.TestNames.CallProcessSelectChange); }); -PrintPreviewNumberSettingsSectionTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewNumberSettingsSectionTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/number_settings_section.html'; @@ -260,7 +267,8 @@ number_settings_section_test.TestNames.BlocksInvalidKeys); }); -PrintPreviewRestoreStateTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewRestoreStateTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/app.html'; @@ -295,7 +303,8 @@ this.runMochaTest(restore_state_test.TestNames.SaveValues); }); -PrintPreviewModelTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewModelTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/data/model.html'; @@ -336,7 +345,8 @@ this.runMochaTest(model_test.TestNames.ChangeDestination); }); -PrintPreviewModelSettingsAvailabilityTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewModelSettingsAvailabilityTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/data/model.html'; @@ -357,7 +367,8 @@ }); GEN('#if defined(OS_CHROMEOS)'); -PrintPreviewModelSettingsPolicyTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewModelSettingsPolicyTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/data/model.html'; @@ -378,7 +389,8 @@ }); GEN('#endif'); -PrintPreviewPreviewGenerationTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewPreviewGenerationTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/app.html'; @@ -467,7 +479,8 @@ }); GEN('#if !defined(OS_CHROMEOS)'); -PrintPreviewLinkContainerTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewLinkContainerTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/link_container.html'; @@ -508,7 +521,8 @@ GEN('#endif'); // defined(OS_MACOSX) GEN('#if defined(OS_WIN) || defined(OS_MACOSX)'); -PrintPreviewSystemDialogBrowserTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewSystemDialogBrowserTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/app.html'; @@ -547,7 +561,8 @@ }); GEN('#endif'); // defined(OS_WIN) || defined(OS_MACOSX) -PrintPreviewInvalidSettingsBrowserTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewInvalidSettingsBrowserTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/app.html'; @@ -600,7 +615,8 @@ .InvalidCertificateErrorReselectDestination); }); -PrintPreviewDestinationSelectTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewDestinationSelectTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/destination_settings.html'; @@ -691,7 +707,8 @@ destination_select_test.TestNames.MultipleRecentDestinationsAccounts); }); -PrintPreviewDestinationDialogTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewDestinationDialogTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/destination_dialog.html'; @@ -737,7 +754,8 @@ this.runMochaTest(destination_dialog_test.TestNames.UserAccounts); }); -PrintPreviewAdvancedDialogTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewAdvancedDialogTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/advanced_settings_dialog.html'; @@ -780,7 +798,8 @@ this.runMochaTest(advanced_dialog_test.TestNames.AdvancedSettingsFilter); }); -PrintPreviewPreviewAreaTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewPreviewAreaTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/preview_area.html'; @@ -808,7 +827,8 @@ this.runMochaTest(preview_area_test.TestNames.StateChanges); }); -PrintPreviewCustomMarginsTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewCustomMarginsTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/margin_control_container.html'; @@ -890,7 +910,8 @@ this.runMochaTest(custom_margins_test.TestNames.ControlsDisabledOnError); }); -PrintPreviewDestinationSearchTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewDestinationSearchTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/destination_dialog.html'; @@ -945,7 +966,8 @@ this.runMochaTest(destination_search_test.TestNames.CloudKioskPrinter); }); -PrintPreviewHeaderTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewHeaderTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/header.html'; @@ -989,7 +1011,8 @@ this.runMochaTest(header_test.TestNames.EnterprisePolicy); }); -PrintPreviewHeaderNewTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewHeaderNewTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/header_new.html'; @@ -1029,7 +1052,8 @@ this.runMochaTest(header_new_test.TestNames.EnterprisePolicy); }); -PrintPreviewButtonStripTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewButtonStripTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/button_strip.html'; @@ -1061,7 +1085,8 @@ this.runMochaTest(button_strip_test.TestNames.ButtonStripFiresEvents); }); -PrintPreviewDestinationItemTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewDestinationItemTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/destination_list_item.html'; @@ -1101,7 +1126,8 @@ this.runMochaTest(destination_item_test.TestNames.QueryDescription); }); -PrintPreviewAdvancedItemTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewAdvancedItemTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/advanced_settings_item.html'; @@ -1146,7 +1172,8 @@ this.runMochaTest(advanced_item_test.TestNames.QueryOption); }); -PrintPreviewDestinationListTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewDestinationListTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/destination_list.html'; @@ -1176,7 +1203,8 @@ destination_list_test.TestNames.FireDestinationSelected); }); -PrintPreviewPrintButtonTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewPrintButtonTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/app.html'; @@ -1207,7 +1235,8 @@ this.runMochaTest(print_button_test.TestNames.PDFPrintVisiblePreview); }); -PrintPreviewKeyEventTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewKeyEventTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/app.html'; @@ -1269,7 +1298,8 @@ this.runMochaTest(key_event_test.TestNames.CtrlShiftPOpensSystemDialog); }); -PrintPreviewDestinationSettingsTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewDestinationSettingsTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/destination_settings.html'; @@ -1352,7 +1382,8 @@ destination_settings_test.TestNames.UpdateRecentDestinations); }); -PrintPreviewScalingSettingsTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewScalingSettingsTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/scaling_settings.html'; @@ -1391,7 +1422,8 @@ scaling_settings_test.TestNames.InputNotDisabledOnValidityChange); }); -PrintPreviewCopiesSettingsTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewCopiesSettingsTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/copies_settings.html'; @@ -1411,7 +1443,8 @@ mocha.run(); }); -PrintPreviewMediaSizeSettingsTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewMediaSizeSettingsTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/media_size_settings.html'; @@ -1431,7 +1464,8 @@ mocha.run(); }); -PrintPreviewDpiSettingsTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewDpiSettingsTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/dpi_settings.html'; @@ -1451,7 +1485,8 @@ mocha.run(); }); -PrintPreviewOtherOptionsSettingsTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewOtherOptionsSettingsTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/other_options_settings.html'; @@ -1471,7 +1506,8 @@ mocha.run(); }); -PrintPreviewLayoutSettingsTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewLayoutSettingsTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/layout_settings.html'; @@ -1491,7 +1527,8 @@ mocha.run(); }); -PrintPreviewColorSettingsTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewColorSettingsTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/color_settings.html'; @@ -1511,7 +1548,8 @@ mocha.run(); }); -PrintPreviewMarginsSettingsTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewMarginsSettingsTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/margins_settings.html'; @@ -1531,7 +1569,8 @@ mocha.run(); }); -PrintPreviewPagesPerSheetSettingsTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewPagesPerSheetSettingsTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/pages_per_sheet_settings.html'; @@ -1551,7 +1590,8 @@ mocha.run(); }); -PrintPreviewDuplexSettingsTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewDuplexSettingsTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/duplex_settings.html'; @@ -1572,7 +1612,8 @@ }); GEN('#if defined(OS_CHROMEOS)'); -PrintPreviewPinSettingsTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewPinSettingsTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/ui/pin_settings.html'; @@ -1593,7 +1634,8 @@ }); GEN('#endif'); -PrintPreviewUserManagerTest = class extends PrintPreviewTest { +// eslint-disable-next-line no-var +var PrintPreviewUserManagerTest = class extends PrintPreviewTest { /** @override */ get browsePreload() { return 'chrome://print/data/user_manager.html';
diff --git a/chrome/test/data/webui/settings/a11y/tts_subpage_a11y_test.js b/chrome/test/data/webui/settings/a11y/tts_subpage_a11y_test.js index 84e3a319..cd0e10a 100644 --- a/chrome/test/data/webui/settings/a11y/tts_subpage_a11y_test.js +++ b/chrome/test/data/webui/settings/a11y/tts_subpage_a11y_test.js
@@ -12,7 +12,8 @@ 'settings_accessibility_test.js', ]); -TtsAccessibilityTest = class extends SettingsAccessibilityTest { +// eslint-disable-next-line no-var +var TtsAccessibilityTest = class extends SettingsAccessibilityTest { /** @override */ get commandLineSwitches() { return ['enable-experimental-a11y-features'];
diff --git a/chrome/test/data/webui/settings/chromeos/os_settings_browsertest.js b/chrome/test/data/webui/settings/chromeos/os_settings_browsertest.js index dcdab14..37eb3d3 100644 --- a/chrome/test/data/webui/settings/chromeos/os_settings_browsertest.js +++ b/chrome/test/data/webui/settings/chromeos/os_settings_browsertest.js
@@ -42,7 +42,8 @@ }; // Test fixture for the Smb Shares page. -OSSettingsSmbPageTest = class extends OSSettingsBrowserTest { +// eslint-disable-next-line no-var +var OSSettingsSmbPageTest = class extends OSSettingsBrowserTest { /** @override */ get browsePreload() { return super.browsePreload + 'os_downloads_page/smb_shares_page.html'; @@ -58,6 +59,13 @@ } }; -TEST_F('OSSettingsSmbPageTest', 'All', function() { +// OSSettingsSmbPageTest.All is flaky on debug. See https://crbug.com/968608. +GEN('#if !defined(NDEBUG)'); +GEN('#define MAYBE_All DISABLED_All'); +GEN('#else'); +GEN('#define MAYBE_All All'); +GEN('#endif'); + +TEST_F('OSSettingsSmbPageTest', 'MAYBE_All', function() { mocha.run(); });
diff --git a/chrome/test/data/webui/settings/chromeos/os_settings_ui_browsertest.js b/chrome/test/data/webui/settings/chromeos/os_settings_ui_browsertest.js index e0bfc15..2ccd49ec 100644 --- a/chrome/test/data/webui/settings/chromeos/os_settings_ui_browsertest.js +++ b/chrome/test/data/webui/settings/chromeos/os_settings_ui_browsertest.js
@@ -10,7 +10,8 @@ GEN('#include "chromeos/constants/chromeos_features.h"'); // Test fixture for the top-level OS settings UI. -OSSettingsUIBrowserTest = class extends PolymerTest { +// eslint-disable-next-line no-var +var OSSettingsUIBrowserTest = class extends PolymerTest { /** @override */ get browsePreload() { return 'chrome://os-settings/';
diff --git a/chrome/test/data/webui/settings/cr_settings_browsertest.js b/chrome/test/data/webui/settings/cr_settings_browsertest.js index 9718a9f..54f8876 100644 --- a/chrome/test/data/webui/settings/cr_settings_browsertest.js +++ b/chrome/test/data/webui/settings/cr_settings_browsertest.js
@@ -2557,7 +2557,8 @@ mocha.run(); }); -CrSettingsSplitSettingsFlagTest = class extends CrSettingsBrowserTest { +// eslint-disable-next-line no-var +var CrSettingsSplitSettingsFlagTest = class extends CrSettingsBrowserTest { /** @override */ get browsePreload() { return 'chrome://settings/basic_page/basic_page.html';
diff --git a/chrome/test/data/webui/signin/signin_browsertest.js b/chrome/test/data/webui/signin/signin_browsertest.js index ec4c5e9..49c483a6 100644 --- a/chrome/test/data/webui/signin/signin_browsertest.js +++ b/chrome/test/data/webui/signin/signin_browsertest.js
@@ -14,7 +14,7 @@ * chrome/browser/resources/signin/dice_sync_confirmation/sync_confirmation.html. * This has to be declared as a variable for TEST_F to find it correctly. */ -var SigninSyncConfirmationTest = class extends PolymerTest { +SigninSyncConfirmationTest = class extends PolymerTest { /** @override */ get typedefCppFixture() { return 'SigninBrowserTest';
diff --git a/chrome/test/data/webui/test_api.js b/chrome/test/data/webui/test_api.js index 4ebd611..fb056a6f 100644 --- a/chrome/test/data/webui/test_api.js +++ b/chrome/test/data/webui/test_api.js
@@ -144,13 +144,6 @@ mockHandler: null, /** - * This should be initialized by the test fixture and can be referenced - * during the test run. It holds any mocked global functions. - * @type {?Mock4JS.Mock} - */ - mockGlobals: null, - - /** * Value is passed through call to C++ RunJavascriptF to invoke this test. * @type {boolean} */ @@ -281,37 +274,6 @@ }, /** - * Create a new class to handle |functionNames|, assign it to - * |this.mockGlobals|, register its global overrides, and return it. - * @return {Mock} Mock handler class assigned to |this.mockGlobals|. - * @see registerMockGlobals - */ - makeAndRegisterMockGlobals: function(functionNames) { - var MockClass = makeMockClass(functionNames); - this.mockGlobals = mock(MockClass); - registerMockGlobals(this.mockGlobals, MockClass); - return this.mockGlobals; - }, - - /** - * Create a container of mocked standalone functions to handle - * '.'-separated |apiNames|, assign it to |this.mockApis|, register its API - * overrides and return it. - * @return {Mock} Mock handler class. - * @see makeMockFunctions - * @see registerMockApis - */ - makeAndRegisterMockApis: function(apiNames) { - var apiMockNames = apiNames.map(function(name) { - return name.replace(/\./g, '_'); - }); - - this.mockApis = makeMockFunctions(apiMockNames); - registerMockApis(this.mockApis); - return this.mockApis; - }, - - /** * Create a container of mocked standalone functions to handle * |functionNames|, assign it to |this.mockLocalFunctions| and return it. * @param {!Array<string>} functionNames @@ -612,12 +574,6 @@ } /** - * Holds the mapping of name -> global override information. - * @type {Object} - */ -var globalOverrides = {}; - -/** * When preloading JavaScript libraries, this is true until the * DOMContentLoaded event has been received as globals cannot be overridden * until the page has loaded its JavaScript. @@ -626,61 +582,6 @@ var deferGlobalOverrides = false; /** - * Override the global function |funcName| with its registered mock. This - * should not be called twice for the same |funcName|. - * @param {string} funcName The name of the global function to override. - */ -function overrideGlobal(funcName) { - assertNotEquals(undefined, this[funcName]); - var globalOverride = globalOverrides[funcName]; - assertNotEquals(undefined, globalOverride); - assertEquals(undefined, globalOverride.original); - globalOverride.original = this[funcName]; - this[funcName] = globalOverride.callback.bind(globalOverride.object); -} - -/** - * Registers the global function name, object and callback. - * @param {string} name The name of the message to route to this |callback|. - * @param {Object} object Pass as |this| when calling the |callback|. - * @param {function(...)} callback Called by {@code chrome.send}. - * @see overrideGlobal - */ -function registerMockGlobal(name, object, callback) { - assertEquals(undefined, globalOverrides[name]); - globalOverrides[name] = { - object: object, - callback: callback, - }; - - if (!deferGlobalOverrides) { - overrideGlobal(name); - } -} - -/** - * Registers the mock API call and its function. - * @param {string} name The '_'-separated name of the API call. - * @param {function(...)} theFunction Mock function for this API call. - */ -function registerMockApi(name, theFunction) { - var path = name.split('_'); - - var namespace = this; - for (var i = 0; i < path.length - 1; i++) { - var fieldName = path[i]; - if (!namespace[fieldName]) { - namespace[fieldName] = {}; - } - - namespace = namespace[fieldName]; - } - - var fieldName = path[path.length - 1]; - namespace[fieldName] = theFunction; -} - -/** * Empty function for use in making mocks. * @const */ @@ -727,37 +628,6 @@ } /** - * Register all methods of {@code mockClass.prototype} as overrides to global - * functions of the same name as the method, using the proxy of the - * |mockObject| to handle the functions. - * @param {Mock4JS.Mock} mockObject The mock to register callbacks against. - * @param {function(new:Object)} mockClass Constructor for the mocked class. - * @see registerMockGlobal - */ -function registerMockGlobals(mockObject, mockClass) { - var mockProxy = mockObject.proxy(); - for (var func in mockClass.prototype) { - if (typeof mockClass.prototype[func] === 'function') { - registerMockGlobal(func, mockProxy, mockProxy[func]); - } - } -} - -/** - * Register all functions in |mockObject.functions()| as global API calls. - * @param {Mock4JS.Mock} mockObject The mock to register callbacks against. - * @see registerMockApi - */ -function registerMockApis(mockObject) { - var functions = mockObject.functions(); - for (var func in functions) { - if (typeof functions[func] === 'function') { - registerMockApi(func, functions[func]); - } - } -} - -/** * Overrides {@code chrome.send} for routing messages to javascript * functions. Also falls back to sending with the original chrome object. * @param {string} messageName The message to route. @@ -1217,9 +1087,6 @@ // Override globals at load time so they will be defined. assertTrue(deferGlobalOverrides); deferGlobalOverrides = false; - for (var funcName in globalOverrides) { - overrideGlobal(funcName); - } }, true); currentTestCase = createTestCase(testFixture, testName); currentTestCase.preLoad(); @@ -1512,54 +1379,6 @@ } /** - * CallGlobalAction as a subclass of CallFunctionAction looks up the original - * global object in |globalOverrides| using |funcName| as the key. This allows - * tests, which need to wait until a global function to be called in order to - * start the test to run the original function. When used with runAllActions - * or runAllActionsAsync, Mock4JS expectations may call start or continue the - * test after calling the original function. - * @param {?SaveMockArguments} savedArgs when non-null, saved arguments are - * passed to the global function |funcName|. - * @param {string} funcName The name of the global function to call. - * @param {Array} args Any arguments to pass to func. - * @constructor - * @extends {CallFunctionAction} - * @see globalOverrides - */ -function CallGlobalAction(savedArgs, funcName, args) { - CallFunctionAction.call(this, null, savedArgs, funcName, args); -} - -CallGlobalAction.prototype = { - __proto__: CallFunctionAction.prototype, - - /** - * Fetch and return the original global function to call. - * @return {Function} The global function to invoke. - * @override - */ - get func() { - var func = globalOverrides[this.func_].original; - assertNotEquals(undefined, func); - return func; - }, -}; - -/** - * Syntactic sugar for use with will() on a Mock4JS.Mock. - * @param {SaveMockArguments} savedArgs Arguments saved with this object - * are passed to the global function |funcName|. - * @param {string} funcName The name of a registered mock global function to - * call when the method is invoked. - * @param {...*} var_args Arguments to pass when calling func. - * @return {CallGlobalAction} Action for use in Mock4JS will(). - */ -function callGlobalWithSavedArgs(savedArgs, funcName) { - return new CallGlobalAction( - savedArgs, funcName, Array.prototype.slice.call(arguments, 2)); -} - -/** * When to call testDone(). * @enum {number} */ @@ -1838,7 +1657,6 @@ function exportMock4JsHelpers() { exports.callFunction = callFunction; exports.callFunctionWithSavedArgs = callFunctionWithSavedArgs; - exports.callGlobalWithSavedArgs = callGlobalWithSavedArgs; exports.eqJSON = eqJSON; exports.eqToString = eqToString; exports.invokeCallback = invokeCallback; @@ -1859,8 +1677,6 @@ exports.setWaitUser = setWaitUser; exports.go = go; exports.registerMessageCallback = registerMessageCallback; -exports.registerMockGlobals = registerMockGlobals; -exports.registerMockMessageCallbacks = registerMockMessageCallbacks; exports.resetTestState = resetTestState; exports.runAccessibilityAudit = runAccessibilityAudit; exports.runAllActions = runAllActions;
diff --git a/chrome/test/data/webui/welcome/onboarding_welcome_browsertest.js b/chrome/test/data/webui/welcome/onboarding_welcome_browsertest.js index 6cd5934..8b37047 100644 --- a/chrome/test/data/webui/welcome/onboarding_welcome_browsertest.js +++ b/chrome/test/data/webui/welcome/onboarding_welcome_browsertest.js
@@ -30,7 +30,9 @@ } }; -OnboardingWelcomeAppChooserTest = class extends OnboardingWelcomeBrowserTest { +// eslint-disable-next-line no-var +var OnboardingWelcomeAppChooserTest = + class extends OnboardingWelcomeBrowserTest { /** @override */ get browsePreload() { return 'chrome://welcome/google_apps/nux_google_apps.html'; @@ -51,7 +53,9 @@ mocha.run(); }); -OnboardingWelcomeWelcomeAppTest = class extends OnboardingWelcomeBrowserTest { +// eslint-disable-next-line no-var +var OnboardingWelcomeWelcomeAppTest = + class extends OnboardingWelcomeBrowserTest { /** @override */ get browsePreload() { return 'chrome://welcome/welcome_app.html'; @@ -73,7 +77,9 @@ mocha.run(); }); -OnboardingWelcomeSigninViewTest = class extends OnboardingWelcomeBrowserTest { +// eslint-disable-next-line no-var +var OnboardingWelcomeSigninViewTest = + class extends OnboardingWelcomeBrowserTest { /** @override */ get browsePreload() { return 'chrome://welcome/signin_view.html'; @@ -92,7 +98,8 @@ mocha.run(); }); -OnboardingWelcomeNavigationBehaviorTest = +// eslint-disable-next-line no-var +var OnboardingWelcomeNavigationBehaviorTest = class extends OnboardingWelcomeBrowserTest { /** @override */ get browsePreload() { @@ -112,7 +119,8 @@ mocha.run(); }); -OnboardingWelcomeModuleMetricsTest = +// eslint-disable-next-line no-var +var OnboardingWelcomeModuleMetricsTest = class extends OnboardingWelcomeBrowserTest { /** @override */ get browsePreload() { @@ -132,7 +140,9 @@ mocha.run(); }); -OnboardingWelcomeSetAsDefaultTest = class extends OnboardingWelcomeBrowserTest { +// eslint-disable-next-line no-var +var OnboardingWelcomeSetAsDefaultTest = + class extends OnboardingWelcomeBrowserTest { /** @override */ get browsePreload() { return 'chrome://welcome/set_as_default/nux_set_as_default.html'; @@ -152,7 +162,8 @@ mocha.run(); }); -OnboardingWelcomeNtpBackgroundTest = +// eslint-disable-next-line no-var +var OnboardingWelcomeNtpBackgroundTest = class extends OnboardingWelcomeBrowserTest { /** @override */ get browsePreload() {
diff --git a/chromecast/app/cast_main_delegate.cc b/chromecast/app/cast_main_delegate.cc index a36392b0..7c8554d 100644 --- a/chromecast/app/cast_main_delegate.cc +++ b/chromecast/app/cast_main_delegate.cc
@@ -180,7 +180,13 @@ // Note: Android must handle running its own browser process. // See ChromeMainDelegateAndroid::RunProcess. browser_runner_ = content::BrowserMainRunner::Create(); - return browser_runner_->Initialize(main_function_params); + int exit_code = browser_runner_->Initialize(main_function_params); + // On Android we do not run BrowserMain(), so the above initialization of a + // BrowserMainRunner is all we want to occur. Return >= 0 to avoid running + // BrowserMain, while preserving any error codes > 0. + if (exit_code > 0) + return exit_code; + return 0; #else return -1; #endif // defined(OS_ANDROID)
diff --git a/chromeos/services/assistant/assistant_manager_service_impl.cc b/chromeos/services/assistant/assistant_manager_service_impl.cc index ef80048..8bbc4dc 100644 --- a/chromeos/services/assistant/assistant_manager_service_impl.cc +++ b/chromeos/services/assistant/assistant_manager_service_impl.cc
@@ -96,21 +96,6 @@ assistant_state->context_enabled().value_or(false); } -action::AppStatus GetActionAppStatus(mojom::AppStatus status) { - switch (status) { - case mojom::AppStatus::UNKNOWN: - return action::UNKNOWN; - case mojom::AppStatus::AVAILABLE: - return action::AVAILABLE; - case mojom::AppStatus::UNAVAILABLE: - return action::UNAVAILABLE; - case mojom::AppStatus::VERSION_MISMATCH: - return action::VERSION_MISMATCH; - case mojom::AppStatus::DISABLED: - return action::DISABLED; - } -} - ash::mojom::AssistantTimerState GetTimerState( assistant_client::Timer::State state) { switch (state) { @@ -639,24 +624,6 @@ weak_factory_.GetWeakPtr(), interaction)); } -void AssistantManagerServiceImpl::OnVerifyAndroidApp( - const std::vector<action::AndroidAppInfo>& apps_info, - const action::InteractionInfo& interaction) { - ENSURE_MAIN_THREAD(&AssistantManagerServiceImpl::OnVerifyAndroidApp, - apps_info, interaction); - std::vector<mojom::AndroidAppInfoPtr> apps_info_list; - for (auto& app_info : apps_info) { - mojom::AndroidAppInfoPtr app_info_ptr = mojom::AndroidAppInfo::New(); - app_info_ptr->package_name = app_info.package_name; - apps_info_list.push_back(std::move(app_info_ptr)); - } - service_->device_actions()->VerifyAndroidApp( - std::move(apps_info_list), - base::BindOnce( - &AssistantManagerServiceImpl::HandleVerifyAndroidAppResponse, - weak_factory_.GetWeakPtr(), interaction)); -} - void AssistantManagerServiceImpl::OnOpenMediaAndroidIntentOnMainThread( const std::string play_media_args_proto, action::AndroidAppInfo* android_app_info) { @@ -1059,28 +1026,6 @@ interaction_proto, "open_provider_response", options, [](auto) {}); } -void AssistantManagerServiceImpl::HandleVerifyAndroidAppResponse( - const action::InteractionInfo& interaction, - std::vector<mojom::AndroidAppInfoPtr> apps_info) { - std::vector<action::AndroidAppInfo> action_apps_info; - for (const auto& app_info : apps_info) { - action_apps_info.push_back({app_info->package_name, app_info->version, - app_info->localized_app_name, app_info->intent, - GetActionAppStatus(app_info->status)}); - } - std::string interaction_proto = CreateVerifyProviderResponseInteraction( - interaction.interaction_id, action_apps_info); - - assistant_client::VoicelessOptions options; - options.obfuscated_gaia_id = interaction.user_id; - // Set the request to be user initiated so that a new conversation will be - // created to handle the client OPs in the response of this request. - options.is_user_initiated = true; - - assistant_manager_internal_->SendVoicelessInteraction( - interaction_proto, "verify_provider_response", options, [](auto) {}); -} - // assistant_client::DeviceStateListener overrides // Run on LibAssistant threads // This method currently only triggered as the callback of libassistant bootup
diff --git a/chromeos/services/assistant/assistant_manager_service_impl.h b/chromeos/services/assistant/assistant_manager_service_impl.h index c883966..e6cbe28 100644 --- a/chromeos/services/assistant/assistant_manager_service_impl.h +++ b/chromeos/services/assistant/assistant_manager_service_impl.h
@@ -153,8 +153,6 @@ void OnShowNotification(const action::Notification& notification) override; void OnOpenAndroidApp(const action::AndroidAppInfo& app_info, const action::InteractionInfo& interaction) override; - void OnVerifyAndroidApp(const std::vector<action::AndroidAppInfo>& apps_info, - const action::InteractionInfo& interaction) override; // AssistantEventObserver overrides: void OnSpeechLevelUpdated(float speech_level) override; @@ -225,9 +223,6 @@ void HandleOpenAndroidAppResponse(const action::InteractionInfo& interaction, bool app_opened); - void HandleVerifyAndroidAppResponse( - const action::InteractionInfo& interaction, - std::vector<mojom::AndroidAppInfoPtr> apps_info); void HandleLaunchMediaIntentResponse(bool app_opened);
diff --git a/chromeos/services/assistant/public/mojom/assistant.mojom b/chromeos/services/assistant/public/mojom/assistant.mojom index d63927d..5e31f49 100644 --- a/chromeos/services/assistant/public/mojom/assistant.mojom +++ b/chromeos/services/assistant/public/mojom/assistant.mojom
@@ -180,10 +180,6 @@ // Open the Android app if the app is available. OpenAndroidApp(AndroidAppInfo app_info) => (bool app_opened); - // Verify the status of the Android apps. - VerifyAndroidApp(array<AndroidAppInfo> apps_info) => (array<AndroidAppInfo> - apps_info); - // Launch Android intent. The intent is encoded as a URI string. // See Intent.toUri(). LaunchAndroidIntent(string intent);
diff --git a/chromeos/services/assistant/service_unittest.cc b/chromeos/services/assistant/service_unittest.cc index abdf27a..9d1f2337a 100644 --- a/chromeos/services/assistant/service_unittest.cc +++ b/chromeos/services/assistant/service_unittest.cc
@@ -139,9 +139,6 @@ void SetNightLightEnabled(bool enabled) override {} void OpenAndroidApp(chromeos::assistant::mojom::AndroidAppInfoPtr app_info, OpenAndroidAppCallback callback) override {} - void VerifyAndroidApp( - std::vector<chromeos::assistant::mojom::AndroidAppInfoPtr> apps_info, - VerifyAndroidAppCallback callback) override {} void LaunchAndroidIntent(const std::string& intent) override {} void AddAppListEventSubscriber( chromeos::assistant::mojom::AppListEventSubscriberPtr subscriber)
diff --git a/components/cronet/native/engine.cc b/components/cronet/native/engine.cc index dcda7e059..32ae47f 100644 --- a/components/cronet/native/engine.cc +++ b/components/cronet/native/engine.cc
@@ -289,10 +289,23 @@ } } -using RequestInfo = base::RefCountedData<Cronet_RequestFinishedInfo>; +namespace { + +using RequestFinishedInfo = base::RefCountedData<Cronet_RequestFinishedInfo>; +using UrlResponseInfo = base::RefCountedData<Cronet_UrlResponseInfo>; +using CronetError = base::RefCountedData<Cronet_Error>; + +template <typename T> +T* GetData(scoped_refptr<base::RefCountedData<T>> ptr) { + return ptr == nullptr ? nullptr : &ptr->data; +} + +} // namespace void Cronet_EngineImpl::ReportRequestFinished( - scoped_refptr<RequestInfo> request_info) { + scoped_refptr<RequestFinishedInfo> request_info, + scoped_refptr<UrlResponseInfo> url_response_info, + scoped_refptr<CronetError> error) { base::flat_map<Cronet_RequestFinishedInfoListenerPtr, Cronet_ExecutorPtr> registrations; { @@ -309,15 +322,16 @@ request_finished_executor->Execute( new cronet::OnceClosureRunnable(base::BindOnce( - [](scoped_refptr<RequestInfo> request_info, - Cronet_RequestFinishedInfoListenerPtr - request_finished_listener) { - // TODO(crbug.com/879208): Pass-though UrlResponseInfo and Error - // too. - request_finished_listener->OnRequestFinished(&request_info->data, - nullptr, nullptr); + [](Cronet_RequestFinishedInfoListenerPtr request_finished_listener, + scoped_refptr<RequestFinishedInfo> request_info, + scoped_refptr<UrlResponseInfo> url_response_info, + scoped_refptr<CronetError> error) { + request_finished_listener->OnRequestFinished( + GetData(request_info), GetData(url_response_info), + GetData(error)); }, - request_info, request_finished_listener))); + request_finished_listener, request_info, url_response_info, + error))); } }
diff --git a/components/cronet/native/engine.h b/components/cronet/native/engine.h index 2075d9c1..4eeed32 100644 --- a/components/cronet/native/engine.h +++ b/components/cronet/native/engine.h
@@ -70,7 +70,10 @@ // Provide |request_info| to all registered RequestFinishedListeners. void ReportRequestFinished( scoped_refptr<base::RefCountedData<Cronet_RequestFinishedInfo>> - request_info); + request_info, + scoped_refptr<base::RefCountedData<Cronet_UrlResponseInfo>> + url_response_info, + scoped_refptr<base::RefCountedData<Cronet_Error>> error); private: class StreamEngineImpl;
diff --git a/components/cronet/native/engine_unittest.cc b/components/cronet/native/engine_unittest.cc index b3ad17bc..ac544e4 100644 --- a/components/cronet/native/engine_unittest.cc +++ b/components/cronet/native/engine_unittest.cc
@@ -33,8 +33,8 @@ void TestRequestInfoListener_OnRequestFinished( Cronet_RequestFinishedInfoListenerPtr self, Cronet_RequestFinishedInfoPtr request_info, - Cronet_UrlResponseInfoPtr, - Cronet_ErrorPtr) { + Cronet_UrlResponseInfoPtr url_response_info, + Cronet_ErrorPtr error) { CHECK(self); Cronet_ClientContext context = Cronet_RequestFinishedInfoListener_GetClientContext(self); @@ -43,6 +43,8 @@ ++(*listener_run_count); auto* metrics = Cronet_RequestFinishedInfo_metrics_get(request_info); EXPECT_EQ(kSentByteCount, Cronet_Metrics_sent_byte_count_get(metrics)); + EXPECT_NE(nullptr, url_response_info); + EXPECT_NE(nullptr, error); } TEST(EngineUnitTest, HasNoRequestFinishedInfoListener) { @@ -76,6 +78,8 @@ TEST(EngineUnitTest, RequestFinishedInfoListeners) { using RequestInfo = base::RefCountedData<Cronet_RequestFinishedInfo>; + using UrlResponseInfo = base::RefCountedData<Cronet_UrlResponseInfo>; + using CronetError = base::RefCountedData<Cronet_Error>; constexpr int kNumListeners = 5; TestOnRequestFinishedClientContext listener_run_count = 0; @@ -96,10 +100,12 @@ // Simulate the UrlRequest reporting metrics to the engine. auto* engine_impl = static_cast<Cronet_EngineImpl*>(engine); auto request_info = base::MakeRefCounted<RequestInfo>(); + auto url_response_info = base::MakeRefCounted<UrlResponseInfo>(); + auto error = base::MakeRefCounted<CronetError>(); auto metrics = std::make_unique<Cronet_Metrics>(); metrics->sent_byte_count = kSentByteCount; request_info->data.metrics.emplace(*metrics); - engine_impl->ReportRequestFinished(request_info); + engine_impl->ReportRequestFinished(request_info, url_response_info, error); EXPECT_EQ(kNumListeners, listener_run_count); for (auto* listener : listeners) {
diff --git a/components/cronet/native/test/BUILD.gn b/components/cronet/native/test/BUILD.gn index 023157d..58acf49 100644 --- a/components/cronet/native/test/BUILD.gn +++ b/components/cronet/native/test/BUILD.gn
@@ -47,6 +47,8 @@ "buffer_test.cc", "engine_test.cc", "executors_test.cc", + "test_request_finished_info_listener.cc", + "test_request_finished_info_listener.h", "test_stream_engine.cc", "test_upload_data_provider.cc", "test_upload_data_provider.h",
diff --git a/components/cronet/native/test/test_request_finished_info_listener.cc b/components/cronet/native/test/test_request_finished_info_listener.cc new file mode 100644 index 0000000..f75d094a --- /dev/null +++ b/components/cronet/native/test/test_request_finished_info_listener.cc
@@ -0,0 +1,54 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/cronet/native/test/test_request_finished_info_listener.h" + +#include "base/logging.h" + +namespace cronet { +namespace test { + +Cronet_RequestFinishedInfoListenerPtr +TestRequestFinishedInfoListener::CreateRequestFinishedListener() { + auto* listener = Cronet_RequestFinishedInfoListener_CreateWith( + TestRequestFinishedInfoListener::OnRequestFinished); + Cronet_RequestFinishedInfoListener_SetClientContext(listener, this); + return listener; +} + +void TestRequestFinishedInfoListener::WaitForDone() { + done_.Wait(); +} + +/* static */ +TestRequestFinishedInfoListener* TestRequestFinishedInfoListener::GetThis( + Cronet_RequestFinishedInfoListenerPtr self) { + CHECK(self); + return static_cast<TestRequestFinishedInfoListener*>( + Cronet_RequestFinishedInfoListener_GetClientContext(self)); +} + +/* static */ +void TestRequestFinishedInfoListener::OnRequestFinished( + Cronet_RequestFinishedInfoListenerPtr self, + Cronet_RequestFinishedInfoPtr request_finished_info, + Cronet_UrlResponseInfoPtr url_response_info, + Cronet_ErrorPtr error) { + GetThis(self)->OnRequestFinished(request_finished_info, url_response_info, + error); + Cronet_RequestFinishedInfoListener_Destroy(self); +} + +void TestRequestFinishedInfoListener::OnRequestFinished( + Cronet_RequestFinishedInfoPtr request_finished_info, + Cronet_UrlResponseInfoPtr url_response_info, + Cronet_ErrorPtr error) { + request_finished_info_ = request_finished_info; + url_response_info_ = url_response_info; + error_ = error; + done_.Signal(); +} + +} // namespace test +} // namespace cronet
diff --git a/components/cronet/native/test/test_request_finished_info_listener.h b/components/cronet/native/test/test_request_finished_info_listener.h new file mode 100644 index 0000000..9f8a6474 --- /dev/null +++ b/components/cronet/native/test/test_request_finished_info_listener.h
@@ -0,0 +1,85 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/logging.h" +#include "base/synchronization/waitable_event.h" +#include "cronet_c.h" + +#ifndef COMPONENTS_CRONET_NATIVE_TEST_TEST_REQUEST_FINISHED_INFO_LISTENER_H_ +#define COMPONENTS_CRONET_NATIVE_TEST_TEST_REQUEST_FINISHED_INFO_LISTENER_H_ + +namespace cronet { +namespace test { + +// A RequestFinishedInfoListener implementation that allows waiting for and +// accessing callback results from tests. +// +// Note that the RequestFinishedInfo for a request is shared-owned by its +// UrlRequest and the code calling the listeners. +class TestRequestFinishedInfoListener { + public: + // Create a listener that can be registered with Cronet. + // + // The listener deletes itself when OnRequestFinished() is run. + Cronet_RequestFinishedInfoListenerPtr CreateRequestFinishedListener(); + + // Wait until a listener created with CreateRequestFinishedListener() runs + // OnRequestFinished(). + void WaitForDone(); + + Cronet_RequestFinishedInfoPtr request_finished_info() { + CHECK(done_.IsSignaled()); + return request_finished_info_; + } + + Cronet_UrlResponseInfoPtr url_response_info() { + CHECK(done_.IsSignaled()); + return url_response_info_; + } + + Cronet_ErrorPtr error() { + CHECK(done_.IsSignaled()); + return error_; + } + + private: + static TestRequestFinishedInfoListener* GetThis( + Cronet_RequestFinishedInfoListenerPtr self); + + // Implementation of Cronet_RequestFinishedInfoListener methods. + static void OnRequestFinished( + Cronet_RequestFinishedInfoListenerPtr self, + Cronet_RequestFinishedInfoPtr request_finished_info, + Cronet_UrlResponseInfoPtr url_response_info, + Cronet_ErrorPtr error); + + virtual void OnRequestFinished( + Cronet_RequestFinishedInfoPtr request_finished_info, + Cronet_UrlResponseInfoPtr url_response_info, + Cronet_ErrorPtr error); + + // RequestFinishedInfo from the request -- will be set when the listener is + // called, which only happens if there are metrics to report. Won't be + // destroyed if the UrlRequest object hasn't been destroyed. + Cronet_RequestFinishedInfoPtr request_finished_info_ = nullptr; + + // UrlResponseInfo from the request -- will be set when the listener is + // called, which only happens if there are metrics to report. Won't be + // destroyed if the UrlRequest object hasn't been destroyed. + Cronet_UrlResponseInfoPtr url_response_info_ = nullptr; + + // Error from the request -- will be will be set when the listener is called, + // which only happens if there are metrics to report. Won't be destroyed if + // the UrlRequest object hasn't been destroyed. + Cronet_ErrorPtr error_ = nullptr; + + // Signaled by OnRequestFinished() on a listener created by + // CreateRequestFinishedListener(). + base::WaitableEvent done_; +}; + +} // namespace test +} // namespace cronet + +#endif // COMPONENTS_CRONET_NATIVE_TEST_TEST_REQUEST_FINISHED_INFO_LISTENER_H_
diff --git a/components/cronet/native/test/test_url_request_callback.cc b/components/cronet/native/test/test_url_request_callback.cc index b90f3607..b3ef62a 100644 --- a/components/cronet/native/test/test_url_request_callback.cc +++ b/components/cronet/native/test/test_url_request_callback.cc
@@ -125,6 +125,7 @@ CHECK(response_step_ == NOTHING || response_step_ == ON_RECEIVED_REDIRECT); CHECK(!last_error_); response_step_ = ON_RESPONSE_STARTED; + original_response_info_ = info; response_info_ = std::make_unique<UrlResponseInfo>(info); if (MaybeCancelOrPause(request)) { return; @@ -142,6 +143,7 @@ response_step_ == ON_READ_COMPLETED); CHECK(!last_error_); response_step_ = ON_READ_COMPLETED; + original_response_info_ = info; response_info_ = std::make_unique<UrlResponseInfo>(info); response_data_length_ += bytes_read; @@ -168,6 +170,7 @@ CHECK(!on_canceled_called_); CHECK(!last_error_); response_step_ = ON_SUCCEEDED; + original_response_info_ = info; response_info_ = std::make_unique<UrlResponseInfo>(info); MaybeCancelOrPause(request); @@ -189,8 +192,10 @@ response_step_ = ON_FAILED; on_error_called_ = true; // It is possible that |info| is nullptr if response has not started. - if (info) + if (info) { + original_response_info_ = info; response_info_ = std::make_unique<UrlResponseInfo>(info); + } last_error_ = error; last_error_code_ = Cronet_Error_error_code_get(error); last_error_message_ = Cronet_Error_message_get(error); @@ -210,8 +215,10 @@ response_step_ = ON_CANCELED; on_canceled_called_ = true; // It is possible |info| is nullptr if the response has not started. - if (info) + if (info) { + original_response_info_ = info; response_info_ = std::make_unique<UrlResponseInfo>(info); + } MaybeCancelOrPause(request); SignalDone(); }
diff --git a/components/cronet/native/test/test_url_request_callback.h b/components/cronet/native/test/test_url_request_callback.h index 3dadf4f..f5e232f 100644 --- a/components/cronet/native/test/test_url_request_callback.h +++ b/components/cronet/native/test/test_url_request_callback.h
@@ -67,8 +67,13 @@ int64_t received_byte_count = 0; }; + // TODO(crbug.com/969048): Make these private with public accessors. std::vector<std::unique_ptr<UrlResponseInfo>> redirect_response_info_list_; std::vector<std::string> redirect_url_list_; + // Owned by UrlRequest, only valid until UrlRequest is destroyed. + Cronet_UrlResponseInfoPtr original_response_info_ = nullptr; + // |response_info_| is copied from |original_response_info_|, valid after + // UrlRequest is destroyed. std::unique_ptr<UrlResponseInfo> response_info_; // Owned by UrlRequest, only valid until UrlRequest is destroyed. Cronet_ErrorPtr last_error_ = nullptr;
diff --git a/components/cronet/native/test/url_request_test.cc b/components/cronet/native/test/url_request_test.cc index b0175cd..1824146 100644 --- a/components/cronet/native/test/url_request_test.cc +++ b/components/cronet/native/test/url_request_test.cc
@@ -13,6 +13,7 @@ #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/synchronization/waitable_event.h" +#include "components/cronet/native/test/test_request_finished_info_listener.h" #include "components/cronet/native/test/test_upload_data_provider.h" #include "components/cronet/native/test/test_url_request_callback.h" #include "components/cronet/native/test/test_util.h" @@ -24,6 +25,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" +using cronet::test::TestRequestFinishedInfoListener; using cronet::test::TestUploadDataProvider; using cronet::test::TestUrlRequestCallback; using ::testing::HasSubstr; @@ -105,13 +107,174 @@ kEngineListener, // Add a request finished listener to the Engine. }; -// App implementation of Cronet_RequestFinishedInfoListener methods. -static void TestRequestInfoListener_OnRequestFinished( - Cronet_RequestFinishedInfoListenerPtr self, - Cronet_RequestFinishedInfoPtr request_info, - Cronet_UrlResponseInfoPtr, - Cronet_ErrorPtr) { - CHECK(self); +// Converts a Cronet_DateTimePtr into the int64 number of milliseconds since +// the UNIX epoch. +// +// Returns -1 if |date_time| is nullptr. +int64_t DateToMillis(Cronet_DateTimePtr date_time) { + if (date_time == nullptr) { + return -1; + } + int64_t value = Cronet_DateTime_value_get(date_time); + // Cronet_DateTime fields shouldn't be before the UNIX epoch. + // + // While DateToMillis() callers can easily check this themselves (and + // produce more descriptive errors showing which field is violating), they + // can't easily distinguish a nullptr vs -1 value, so we check for -1 here. + EXPECT_NE(-1, value); + return value; +} + +// Sanity check that the date isn't wildly off, somehow (perhaps due to read of +// used memory, wild pointer, etc.). +// +// Interpreted as milliseconds after the UNIX timestamp, this timestamp occurs +// at 37,648 C.E. +constexpr int64_t kDateOverrunThreshold = 1LL << 50; + +// Basic sanity checking of all Cronet_Metrics fields. For optional fields, we +// allow the field to be non-present. Start/end pairs should be monotonic (end +// not less than start). +// +// Ordering of events is also checked. +void VerifyRequestMetrics(Cronet_MetricsPtr metrics) { + EXPECT_GE(DateToMillis(Cronet_Metrics_request_start_get(metrics)), 0); + EXPECT_LT(DateToMillis(Cronet_Metrics_request_start_get(metrics)), + kDateOverrunThreshold); + EXPECT_GE(DateToMillis(Cronet_Metrics_request_end_get(metrics)), + DateToMillis(Cronet_Metrics_request_start_get(metrics))); + EXPECT_LT(DateToMillis(Cronet_Metrics_request_end_get(metrics)), + kDateOverrunThreshold); + + EXPECT_GE(DateToMillis(Cronet_Metrics_dns_start_get(metrics)), -1); + EXPECT_LT(DateToMillis(Cronet_Metrics_dns_start_get(metrics)), + kDateOverrunThreshold); + EXPECT_GE(DateToMillis(Cronet_Metrics_dns_end_get(metrics)), + DateToMillis(Cronet_Metrics_dns_start_get(metrics))); + EXPECT_LT(DateToMillis(Cronet_Metrics_dns_end_get(metrics)), + kDateOverrunThreshold); + + EXPECT_GE(DateToMillis(Cronet_Metrics_connect_start_get(metrics)), -1); + EXPECT_LT(DateToMillis(Cronet_Metrics_connect_start_get(metrics)), + kDateOverrunThreshold); + EXPECT_GE(DateToMillis(Cronet_Metrics_connect_end_get(metrics)), + DateToMillis(Cronet_Metrics_connect_start_get(metrics))); + EXPECT_LT(DateToMillis(Cronet_Metrics_connect_end_get(metrics)), + kDateOverrunThreshold); + + EXPECT_GE(DateToMillis(Cronet_Metrics_ssl_start_get(metrics)), -1); + EXPECT_LT(DateToMillis(Cronet_Metrics_ssl_start_get(metrics)), + kDateOverrunThreshold); + EXPECT_GE(DateToMillis(Cronet_Metrics_ssl_end_get(metrics)), + DateToMillis(Cronet_Metrics_ssl_start_get(metrics))); + EXPECT_LT(DateToMillis(Cronet_Metrics_ssl_end_get(metrics)), + kDateOverrunThreshold); + + EXPECT_GE(DateToMillis(Cronet_Metrics_sending_start_get(metrics)), -1); + EXPECT_LT(DateToMillis(Cronet_Metrics_sending_start_get(metrics)), + kDateOverrunThreshold); + EXPECT_GE(DateToMillis(Cronet_Metrics_sending_end_get(metrics)), + DateToMillis(Cronet_Metrics_sending_start_get(metrics))); + EXPECT_LT(DateToMillis(Cronet_Metrics_sending_end_get(metrics)), + kDateOverrunThreshold); + + EXPECT_GE(DateToMillis(Cronet_Metrics_push_start_get(metrics)), -1); + EXPECT_LT(DateToMillis(Cronet_Metrics_push_start_get(metrics)), + kDateOverrunThreshold); + EXPECT_GE(DateToMillis(Cronet_Metrics_push_end_get(metrics)), + DateToMillis(Cronet_Metrics_push_start_get(metrics))); + EXPECT_LT(DateToMillis(Cronet_Metrics_push_end_get(metrics)), + kDateOverrunThreshold); + + EXPECT_GE(DateToMillis(Cronet_Metrics_response_start_get(metrics)), -1); + EXPECT_LT(DateToMillis(Cronet_Metrics_response_start_get(metrics)), + kDateOverrunThreshold); + + EXPECT_GE(Cronet_Metrics_sent_byte_count_get(metrics), -1); + EXPECT_GE(Cronet_Metrics_received_byte_count_get(metrics), -1); + + // Verify order of events. + if (Cronet_Metrics_dns_start_get(metrics) != nullptr) { + EXPECT_GE(DateToMillis(Cronet_Metrics_dns_start_get(metrics)), + DateToMillis(Cronet_Metrics_request_start_get(metrics))); + } + + if (Cronet_Metrics_connect_start_get(metrics) != nullptr && + Cronet_Metrics_dns_end_get(metrics) != nullptr) { + EXPECT_GE(DateToMillis(Cronet_Metrics_connect_start_get(metrics)), + DateToMillis(Cronet_Metrics_dns_end_get(metrics))); + } + + if (Cronet_Metrics_ssl_start_get(metrics) != nullptr && + Cronet_Metrics_connect_start_get(metrics) != nullptr) { + EXPECT_GE(DateToMillis(Cronet_Metrics_ssl_start_get(metrics)), + DateToMillis(Cronet_Metrics_connect_start_get(metrics))); + } + + if (Cronet_Metrics_connect_end_get(metrics) != nullptr && + Cronet_Metrics_ssl_end_get(metrics) != nullptr) { + EXPECT_GE(DateToMillis(Cronet_Metrics_connect_end_get(metrics)), + DateToMillis(Cronet_Metrics_ssl_end_get(metrics))); + } + + if (Cronet_Metrics_sending_start_get(metrics) != nullptr && + Cronet_Metrics_connect_end_get(metrics) != nullptr) { + EXPECT_GE(DateToMillis(Cronet_Metrics_sending_start_get(metrics)), + DateToMillis(Cronet_Metrics_connect_end_get(metrics))); + } + + if (Cronet_Metrics_response_start_get(metrics) != nullptr && + Cronet_Metrics_sending_end_get(metrics) != nullptr) { + EXPECT_GE(DateToMillis(Cronet_Metrics_response_start_get(metrics)), + DateToMillis(Cronet_Metrics_sending_end_get(metrics))); + } + + if (Cronet_Metrics_response_start_get(metrics) != nullptr) { + EXPECT_GE(DateToMillis(Cronet_Metrics_request_end_get(metrics)), + DateToMillis(Cronet_Metrics_response_start_get(metrics))); + } +} + +// Convert a TestUrlRequestCallback::ResponseStep into the equivalent +// RequestFinishedInfo.FINISHED_REASON. +Cronet_RequestFinishedInfo_FINISHED_REASON MapFinishedReason( + TestUrlRequestCallback::ResponseStep response_step) { + switch (response_step) { + case TestUrlRequestCallback::ON_SUCCEEDED: + return Cronet_RequestFinishedInfo_FINISHED_REASON_SUCCEEDED; + case TestUrlRequestCallback::ON_FAILED: + return Cronet_RequestFinishedInfo_FINISHED_REASON_FAILED; + case TestUrlRequestCallback::ON_CANCELED: + return Cronet_RequestFinishedInfo_FINISHED_REASON_CANCELED; + default: + CHECK(false) << "Unknown TestUrlRequestCallback::ResponseStep: " + << response_step; + return Cronet_RequestFinishedInfo_FINISHED_REASON_FAILED; + } +} + +// Basic sanity checking of all Cronet_RequestFinishedInfo, +// Cronet_UrlResponseInfoPtr, and Cronet_ErrorPtr fields passed to +// RequestFinishedInfoListener.OnRequestFinished(). +// +// All fields are checked except for |annotations|. +// +// |test_request_finished_info_listener| Test listener -- will verify all fields +// of this listener. +// |callback| Callback associated with the UrlRequest associated with +// |request_info|. +void VerifyRequestFinishedInfoListener( + TestRequestFinishedInfoListener* test_request_finished_info_listener, + const TestUrlRequestCallback& callback) { + Cronet_RequestFinishedInfoPtr request_info = + test_request_finished_info_listener->request_finished_info(); + VerifyRequestMetrics(Cronet_RequestFinishedInfo_metrics_get(request_info)); + auto finished_reason = + Cronet_RequestFinishedInfo_finished_reason_get(request_info); + EXPECT_EQ(MapFinishedReason(callback.response_step_), finished_reason); + EXPECT_EQ(callback.original_response_info_, + test_request_finished_info_listener->url_response_info()); + EXPECT_EQ(callback.last_error_, test_request_finished_info_listener->error()); } // Parameterized off whether to use a direct executor, and whether (if so, how) @@ -120,10 +283,7 @@ std::tuple<bool, RequestFinishedListenerType>> { protected: UrlRequestTest() {} - ~UrlRequestTest() override { - if (request_finished_listener_ != nullptr) - Cronet_RequestFinishedInfoListener_Destroy(request_finished_listener_); - } + ~UrlRequestTest() override {} void SetUp() override { EXPECT_TRUE(cronet::TestServer::Start()); } @@ -171,13 +331,17 @@ Cronet_UrlRequestCallbackPtr callback = test_callback->CreateUrlRequestCallback(); - MaybeAddRequestFinishedListener(request_params, engine, executor); + TestRequestFinishedInfoListener test_request_finished_info_listener; + MaybeAddRequestFinishedListener(request_params, engine, executor, + &test_request_finished_info_listener); Cronet_UrlRequest_InitWithParams(request, engine, url.c_str(), request_params, callback, executor); Cronet_UrlRequest_Start(request); test_callback->WaitForDone(); + MaybeVerifyRequestFinishedInfo(&test_request_finished_info_listener, + *test_callback); CleanupRequestFinishedListener(request_params, engine); // Wait for all posted tasks to be executed to ensure there is no unhandled // exception. @@ -252,15 +416,16 @@ void MaybeAddRequestFinishedListener( Cronet_UrlRequestParamsPtr url_request_params, Cronet_EnginePtr engine, - Cronet_ExecutorPtr executor) { + Cronet_ExecutorPtr executor, + TestRequestFinishedInfoListener* test_request_finished_info_listener) { auto request_finished_listener_type = GetRequestFinishedListenerTypeParam(); if (request_finished_listener_type == RequestFinishedListenerType::kNoListener) return; - request_finished_listener_ = Cronet_RequestFinishedInfoListener_CreateWith( - TestRequestInfoListener_OnRequestFinished); + request_finished_listener_ = + test_request_finished_info_listener->CreateRequestFinishedListener(); switch (request_finished_listener_type) { case RequestFinishedListenerType::kUrlRequestListener: @@ -296,12 +461,21 @@ nullptr); Cronet_UrlRequestParams_request_finished_executor_set(url_request_params, nullptr); - // TODO(crbug.com/879208): When we actually call the listeners, we should - // move listener destruction to the end of the listener body. - if (request_finished_listener_ != nullptr) { - Cronet_RequestFinishedInfoListener_Destroy(request_finished_listener_); - request_finished_listener_ = nullptr; - } + } + + // TestRequestFinishedInfoListener.WaitForDone() is called and checks are + // performed only if a RequestFinishedInfoListener is registered. + // + // This method should be called after TestUrlRequestCallback.WaitForDone(). + void MaybeVerifyRequestFinishedInfo( + TestRequestFinishedInfoListener* test_request_finished_info_listener, + const TestUrlRequestCallback& callback) { + if (GetRequestFinishedListenerTypeParam() == + RequestFinishedListenerType::kNoListener) + return; + test_request_finished_info_listener->WaitForDone(); + VerifyRequestFinishedInfoListener(test_request_finished_info_listener, + callback); } void TestCancel(TestUrlRequestCallback::FailureType failure_type, @@ -313,6 +487,10 @@ // Provide a message loop for use by TestExecutor instances. base::MessageLoop message_loop_; + // Not owned, |request_finished_listener_| destroys itself when run. This + // pointer is only needed to unregister the listener from the Engine in + // CleanupRequestFinishedListener() and to allow tests that never run the + // |request_finished_listener_| to be able to destroy it. Cronet_RequestFinishedInfoListenerPtr request_finished_listener_ = nullptr; private: @@ -358,7 +536,9 @@ // Callback provided by the application. Cronet_UrlRequestCallbackPtr callback = test_callback.CreateUrlRequestCallback(); - MaybeAddRequestFinishedListener(request_params, engine, executor); + TestRequestFinishedInfoListener test_request_finished_info_listener; + MaybeAddRequestFinishedListener(request_params, engine, executor, + &test_request_finished_info_listener); EXPECT_EQ(Cronet_RESULT_NULL_POINTER_URL, Cronet_UrlRequest_InitWithParams( request, engine, /* url = */ nullptr, @@ -462,6 +642,11 @@ Cronet_UrlRequestParams_Destroy(request_params); Cronet_UrlRequestCallback_Destroy(callback); Cronet_Engine_Destroy(engine); + if (request_finished_listener_ != nullptr) { + // This test never actually runs |request_finished_listener_|, so we delete + // it here. + Cronet_RequestFinishedInfoListener_Destroy(request_finished_listener_); + } } TEST_P(UrlRequestTest, SimpleGet) { @@ -985,7 +1170,9 @@ // Callback provided by the application. Cronet_UrlRequestCallbackPtr callback = test_callback.CreateUrlRequestCallback(); - MaybeAddRequestFinishedListener(request_params, engine, executor); + TestRequestFinishedInfoListener test_request_finished_info_listener; + MaybeAddRequestFinishedListener(request_params, engine, executor, + &test_request_finished_info_listener); Cronet_UrlRequest_InitWithParams(request, engine, url.c_str(), request_params, callback, executor); @@ -993,6 +1180,8 @@ Cronet_UrlRequest_Start(request); test_callback.WaitForDone(); + MaybeVerifyRequestFinishedInfo(&test_request_finished_info_listener, + test_callback); EXPECT_TRUE(test_callback.IsDone()); ASSERT_EQ("The quick brown fox jumps over the lazy dog.", test_callback.response_as_string_); @@ -1003,6 +1192,86 @@ Cronet_Engine_Destroy(engine); } +TEST_P(UrlRequestTest, ReceiveBackAnnotations) { + Cronet_EnginePtr engine = cronet::test::CreateTestEngine(0); + Cronet_UrlRequestPtr request = Cronet_UrlRequest_Create(); + Cronet_UrlRequestParamsPtr request_params = Cronet_UrlRequestParams_Create(); + std::string url = cronet::TestServer::GetSimpleURL(); + + TestUrlRequestCallback test_callback(GetDirectExecutorParam()); + // Executor provided by the application is owned by |test_callback|. + Cronet_ExecutorPtr executor = test_callback.GetExecutor(); + // Callback provided by the application. + Cronet_UrlRequestCallbackPtr callback = + test_callback.CreateUrlRequestCallback(); + TestRequestFinishedInfoListener test_request_finished_info_listener; + MaybeAddRequestFinishedListener(request_params, engine, executor, + &test_request_finished_info_listener); + + int object_to_annotate = 0; + Cronet_UrlRequestParams_annotations_add(request_params, &object_to_annotate); + Cronet_UrlRequest_InitWithParams(request, engine, url.c_str(), request_params, + callback, executor); + + Cronet_UrlRequest_Start(request); + + test_callback.WaitForDone(); + MaybeVerifyRequestFinishedInfo(&test_request_finished_info_listener, + test_callback); + EXPECT_TRUE(test_callback.IsDone()); + if (GetRequestFinishedListenerTypeParam() != + RequestFinishedListenerType::kNoListener) { + ASSERT_EQ(1u, + Cronet_RequestFinishedInfo_annotations_size( + test_request_finished_info_listener.request_finished_info())); + EXPECT_EQ( + &object_to_annotate, + Cronet_RequestFinishedInfo_annotations_at( + test_request_finished_info_listener.request_finished_info(), 0)); + } + + Cronet_UrlRequestParams_Destroy(request_params); + Cronet_UrlRequest_Destroy(request); + Cronet_UrlRequestCallback_Destroy(callback); + Cronet_Engine_Destroy(engine); +} + +TEST_P(UrlRequestTest, UrlParamsAnnotationsUnchanged) { + Cronet_EnginePtr engine = cronet::test::CreateTestEngine(0); + Cronet_UrlRequestPtr request = Cronet_UrlRequest_Create(); + Cronet_UrlRequestParamsPtr request_params = Cronet_UrlRequestParams_Create(); + std::string url = cronet::TestServer::GetSimpleURL(); + + TestUrlRequestCallback test_callback(GetDirectExecutorParam()); + // Executor provided by the application is owned by |test_callback|. + Cronet_ExecutorPtr executor = test_callback.GetExecutor(); + // Callback provided by the application. + Cronet_UrlRequestCallbackPtr callback = + test_callback.CreateUrlRequestCallback(); + TestRequestFinishedInfoListener test_request_finished_info_listener; + MaybeAddRequestFinishedListener(request_params, engine, executor, + &test_request_finished_info_listener); + + int object_to_annotate = 0; + Cronet_UrlRequestParams_annotations_add(request_params, &object_to_annotate); + Cronet_UrlRequest_InitWithParams(request, engine, url.c_str(), request_params, + callback, executor); + ASSERT_EQ(1u, Cronet_UrlRequestParams_annotations_size(request_params)); + EXPECT_EQ(&object_to_annotate, + Cronet_UrlRequestParams_annotations_at(request_params, 0)); + EXPECT_EQ(0, object_to_annotate); + + if (request_finished_listener_ != nullptr) { + // This test never actually runs |request_finished_listener_|, so we delete + // it here. + Cronet_RequestFinishedInfoListener_Destroy(request_finished_listener_); + } + Cronet_UrlRequestParams_Destroy(request_params); + Cronet_UrlRequest_Destroy(request); + Cronet_UrlRequestCallback_Destroy(callback); + Cronet_Engine_Destroy(engine); +} + TEST_P(UrlRequestTest, MultiRedirect) { const std::string url = cronet::TestServer::GetMultiRedirectURL(); auto callback = StartAndWaitForComplete(url); @@ -1065,7 +1334,9 @@ // Callback provided by the application. Cronet_UrlRequestCallbackPtr callback = test_callback.CreateUrlRequestCallback(); - MaybeAddRequestFinishedListener(request_params, engine, executor); + TestRequestFinishedInfoListener test_request_finished_info_listener; + MaybeAddRequestFinishedListener(request_params, engine, executor, + &test_request_finished_info_listener); Cronet_UrlRequest_InitWithParams(request, engine, url.c_str(), request_params, callback, executor); @@ -1073,6 +1344,8 @@ Cronet_UrlRequest_Start(request); test_callback.WaitForDone(); + MaybeVerifyRequestFinishedInfo(&test_request_finished_info_listener, + test_callback); EXPECT_TRUE(test_callback.IsDone()); EXPECT_TRUE(test_callback.on_canceled_called_); ASSERT_FALSE(test_callback.on_error_called_); @@ -1096,7 +1369,9 @@ // Callback provided by the application. Cronet_UrlRequestCallbackPtr callback = test_callback.CreateUrlRequestCallback(); - MaybeAddRequestFinishedListener(request_params, engine, executor); + TestRequestFinishedInfoListener test_request_finished_info_listener; + MaybeAddRequestFinishedListener(request_params, engine, executor, + &test_request_finished_info_listener); Cronet_UrlRequest_InitWithParams(request, engine, url.c_str(), request_params, callback, executor); @@ -1104,6 +1379,8 @@ Cronet_UrlRequest_Start(request); test_callback.WaitForDone(); + MaybeVerifyRequestFinishedInfo(&test_request_finished_info_listener, + test_callback); EXPECT_TRUE(test_callback.IsDone()); EXPECT_TRUE(test_callback.on_error_called_); EXPECT_FALSE(test_callback.on_canceled_called_); @@ -1209,13 +1486,17 @@ // Callback provided by the application. Cronet_UrlRequestCallbackPtr callback = test_callback.CreateUrlRequestCallback(); - MaybeAddRequestFinishedListener(request_params, engine, executor); + TestRequestFinishedInfoListener test_request_finished_info_listener; + MaybeAddRequestFinishedListener(request_params, engine, executor, + &test_request_finished_info_listener); Cronet_UrlRequest_InitWithParams(request, engine, url.c_str(), request_params, callback, executor); Cronet_UrlRequest_Start(request); test_callback.WaitForDone(); + MaybeVerifyRequestFinishedInfo(&test_request_finished_info_listener, + test_callback); EXPECT_TRUE(test_callback.IsDone()); ASSERT_EQ(kDownloadSize, test_callback.response_data_length_); @@ -1256,7 +1537,9 @@ // Callback provided by the application. Cronet_UrlRequestCallbackPtr callback = test_callback.CreateUrlRequestCallback(); - MaybeAddRequestFinishedListener(request_params, engine, executor); + TestRequestFinishedInfoListener test_request_finished_info_listener; + MaybeAddRequestFinishedListener(request_params, engine, executor, + &test_request_finished_info_listener); Cronet_UrlRequest_InitWithParams(request, engine, url.c_str(), request_params, callback, executor); @@ -1296,6 +1579,8 @@ GetRequestStatus(request, &test_callback); test_callback.WaitForNextStep(); } while (!Cronet_UrlRequest_IsDone(request)); + MaybeVerifyRequestFinishedInfo(&test_request_finished_info_listener, + test_callback); EXPECT_EQ(Cronet_UrlRequestStatusListener_Status_INVALID, GetRequestStatus(request, &test_callback)); @@ -1308,8 +1593,14 @@ Cronet_Engine_Destroy(engine); } -TEST(UrlRequestTestNoParam, - RequestFinishedListenerWithoutExecutorReturnsError) { +class UrlRequestTestNoParam : public ::testing::Test { + void SetUp() override { cronet::TestServer::Start(); } + + void TearDown() override { cronet::TestServer::Shutdown(); } +}; + +TEST_F(UrlRequestTestNoParam, + RequestFinishedListenerWithoutExecutorReturnsError) { Cronet_EngineParamsPtr engine_params = Cronet_EngineParams_Create(); Cronet_EnginePtr engine = Cronet_Engine_Create(); // Disable runtime CHECK of the result, so it could be verified. @@ -1319,9 +1610,9 @@ Cronet_EngineParams_Destroy(engine_params); Cronet_UrlRequestPtr request = Cronet_UrlRequest_Create(); Cronet_UrlRequestParamsPtr request_params = Cronet_UrlRequestParams_Create(); + TestRequestFinishedInfoListener test_request_finished_info_listener; Cronet_RequestFinishedInfoListenerPtr request_finished_listener = - Cronet_RequestFinishedInfoListener_CreateWith( - TestRequestInfoListener_OnRequestFinished); + test_request_finished_info_listener.CreateRequestFinishedListener(); // Executor type doesn't matter for this test. TestUrlRequestCallback test_callback(/*direct_executor=*/true); // Executor provided by the application is owned by |test_callback|. @@ -1338,12 +1629,206 @@ request, engine, "http://fakeurl.example.com", request_params, callback, executor)); - // TODO(crbug.com/879208): When we actually call the listeners, we should move - // listener destruction to the end of the listener body. + // This test never actually runs |request_finished_listener|, so we delete + // it here. Cronet_RequestFinishedInfoListener_Destroy(request_finished_listener); Cronet_UrlRequestParams_Destroy(request_params); Cronet_UrlRequest_Destroy(request); Cronet_UrlRequestCallback_Destroy(callback); Cronet_Engine_Destroy(engine); } + +TEST_F(UrlRequestTestNoParam, + UseRequestFinishedInfoAfterUrlRequestDestructionSuccess) { + Cronet_EnginePtr engine = cronet::test::CreateTestEngine(0); + Cronet_UrlRequestPtr request = Cronet_UrlRequest_Create(); + Cronet_UrlRequestParamsPtr request_params = Cronet_UrlRequestParams_Create(); + std::string url = cronet::TestServer::GetSimpleURL(); + + // The UrlRequest executor type doesn't matter, but the + // RequestFinishedInfoListener executor type can't be direct. + TestUrlRequestCallback test_callback(/* direct_executor= */ false); + // Executor provided by the application is owned by |test_callback|. + Cronet_ExecutorPtr executor = test_callback.GetExecutor(); + // Callback provided by the application. + Cronet_UrlRequestCallbackPtr callback = + test_callback.CreateUrlRequestCallback(); + + base::WaitableEvent done_event; + struct ListenerContext { + TestUrlRequestCallback* test_callback; + Cronet_UrlRequestPtr url_request; + base::WaitableEvent* done_event; + }; + ListenerContext listener_context = {&test_callback, request, &done_event}; + + auto* request_finished_listener = + Cronet_RequestFinishedInfoListener_CreateWith( + +[](Cronet_RequestFinishedInfoListenerPtr self, + Cronet_RequestFinishedInfoPtr request_finished_info, + Cronet_UrlResponseInfoPtr response_info, Cronet_ErrorPtr error) { + auto* listener_context = static_cast<ListenerContext*>( + Cronet_RequestFinishedInfoListener_GetClientContext(self)); + listener_context->test_callback->WaitForDone(); + Cronet_UrlRequest_Destroy(listener_context->url_request); + // The next few get methods shouldn't use-after-free on + // |request_finished_info| or |response_info|. + EXPECT_NE(nullptr, Cronet_RequestFinishedInfo_metrics_get( + request_finished_info)); + EXPECT_NE(nullptr, Cronet_UrlResponseInfo_url_get(response_info)); + Cronet_RequestFinishedInfoListener_Destroy(self); + listener_context->done_event->Signal(); + }); + Cronet_RequestFinishedInfoListener_SetClientContext(request_finished_listener, + &listener_context); + + Cronet_UrlRequestParams_request_finished_listener_set( + request_params, request_finished_listener); + Cronet_UrlRequestParams_request_finished_executor_set(request_params, + executor); + Cronet_UrlRequest_InitWithParams(request, engine, url.c_str(), request_params, + callback, executor); + Cronet_UrlRequest_Start(request); + + done_event.Wait(); + EXPECT_TRUE(test_callback.IsDone()); + ASSERT_EQ("The quick brown fox jumps over the lazy dog.", + test_callback.response_as_string_); + + Cronet_UrlRequestParams_Destroy(request_params); + Cronet_UrlRequestCallback_Destroy(callback); + Cronet_Engine_Destroy(engine); +} + +TEST_F(UrlRequestTestNoParam, + UseRequestFinishedInfoAfterUrlRequestDestructionFailure) { + Cronet_EnginePtr engine = cronet::test::CreateTestEngine(0); + Cronet_UrlRequestPtr request = Cronet_UrlRequest_Create(); + Cronet_UrlRequestParamsPtr request_params = Cronet_UrlRequestParams_Create(); + std::string url = "https://notfound.example.com"; + + // The UrlRequest executor type doesn't matter, but the + // RequestFinishedInfoListener executor type can't be direct. + TestUrlRequestCallback test_callback(/* direct_executor= */ false); + // Executor provided by the application is owned by |test_callback|. + Cronet_ExecutorPtr executor = test_callback.GetExecutor(); + // Callback provided by the application. + Cronet_UrlRequestCallbackPtr callback = + test_callback.CreateUrlRequestCallback(); + + base::WaitableEvent done_event; + struct ListenerContext { + TestUrlRequestCallback* test_callback; + Cronet_UrlRequestPtr url_request; + base::WaitableEvent* done_event; + }; + ListenerContext listener_context = {&test_callback, request, &done_event}; + + auto* request_finished_listener = + Cronet_RequestFinishedInfoListener_CreateWith( + +[](Cronet_RequestFinishedInfoListenerPtr self, + Cronet_RequestFinishedInfoPtr request_finished_info, + Cronet_UrlResponseInfoPtr response_info, Cronet_ErrorPtr error) { + auto* listener_context = static_cast<ListenerContext*>( + Cronet_RequestFinishedInfoListener_GetClientContext(self)); + listener_context->test_callback->WaitForDone(); + Cronet_UrlRequest_Destroy(listener_context->url_request); + // The next few get methods shouldn't use-after-free on + // |request_finished_info| or |error|. + EXPECT_NE(nullptr, Cronet_RequestFinishedInfo_metrics_get( + request_finished_info)); + EXPECT_NE(nullptr, Cronet_Error_message_get(error)); + Cronet_RequestFinishedInfoListener_Destroy(self); + listener_context->done_event->Signal(); + }); + Cronet_RequestFinishedInfoListener_SetClientContext(request_finished_listener, + &listener_context); + + Cronet_UrlRequestParams_request_finished_listener_set( + request_params, request_finished_listener); + Cronet_UrlRequestParams_request_finished_executor_set(request_params, + executor); + Cronet_UrlRequest_InitWithParams(request, engine, url.c_str(), request_params, + callback, executor); + Cronet_UrlRequest_Start(request); + + done_event.Wait(); + EXPECT_TRUE(test_callback.IsDone()); + + Cronet_UrlRequestParams_Destroy(request_params); + Cronet_UrlRequestCallback_Destroy(callback); + Cronet_Engine_Destroy(engine); +} + +TEST_F(UrlRequestTestNoParam, + CorrelateCallbackAndRequestInfoWithoutSynchronization) { + class TestUrlRequestCallbackWithCorrelation : public TestUrlRequestCallback { + public: + using TestUrlRequestCallback::TestUrlRequestCallback; + + void OnSucceeded(Cronet_UrlRequestPtr request, + Cronet_UrlResponseInfoPtr info) override { + // This method is guaranteed to run after + // RequestFinishedInfoListener.OnRequestFinished(), **on the same + // thread** (due to the use of a direct executor with the + // RequestFinishedInfoListener). + // + // The following read should therefore not need synchronization -- we rely + // on running this test under sanitizers to verify this. + EXPECT_NE(nullptr, + Cronet_RequestFinishedInfo_metrics_get(request_finished_info_)); + TestUrlRequestCallback::OnSucceeded(request, info); + } + + Cronet_RequestFinishedInfoPtr request_finished_info_; + }; + + Cronet_EnginePtr engine = cronet::test::CreateTestEngine(0); + Cronet_UrlRequestPtr request = Cronet_UrlRequest_Create(); + Cronet_UrlRequestParamsPtr request_params = Cronet_UrlRequestParams_Create(); + std::string url = cronet::TestServer::GetSimpleURL(); + + // The UrlRequest executor type doesn't matter, but the + // RequestFinishedInfoListener executor type *must* be direct. + TestUrlRequestCallbackWithCorrelation test_callback( + /* direct_executor= */ true); + // Executor provided by the application is owned by |test_callback|. + Cronet_ExecutorPtr executor = test_callback.GetExecutor(); + // Callback provided by the application. + Cronet_UrlRequestCallbackPtr callback = + test_callback.CreateUrlRequestCallback(); + + auto* request_finished_listener = + Cronet_RequestFinishedInfoListener_CreateWith( + +[](Cronet_RequestFinishedInfoListenerPtr self, + Cronet_RequestFinishedInfoPtr request_finished_info, + Cronet_UrlResponseInfoPtr, Cronet_ErrorPtr) { + auto* test_callback = + static_cast<TestUrlRequestCallbackWithCorrelation*>( + Cronet_RequestFinishedInfoListener_GetClientContext(self)); + test_callback->request_finished_info_ = request_finished_info; + Cronet_RequestFinishedInfoListener_Destroy(self); + }); + Cronet_RequestFinishedInfoListener_SetClientContext(request_finished_listener, + &test_callback); + + Cronet_UrlRequestParams_request_finished_listener_set( + request_params, request_finished_listener); + Cronet_UrlRequestParams_request_finished_executor_set(request_params, + executor); + Cronet_UrlRequest_InitWithParams(request, engine, url.c_str(), request_params, + callback, executor); + Cronet_UrlRequest_Start(request); + + test_callback.WaitForDone(); + EXPECT_TRUE(test_callback.IsDone()); + ASSERT_EQ("The quick brown fox jumps over the lazy dog.", + test_callback.response_as_string_); + + Cronet_UrlRequest_Destroy(request); + Cronet_UrlRequestParams_Destroy(request_params); + Cronet_UrlRequestCallback_Destroy(callback); + Cronet_Engine_Destroy(engine); +} + } // namespace
diff --git a/components/cronet/native/url_request.cc b/components/cronet/native/url_request.cc index a993f40..95e6270 100644 --- a/components/cronet/native/url_request.cc +++ b/components/cronet/native/url_request.cc
@@ -10,6 +10,9 @@ #include "base/bind.h" #include "base/logging.h" #include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_refptr.h" +#include "base/optional.h" #include "components/cronet/cronet_upload_data_stream.h" #include "components/cronet/native/engine.h" #include "components/cronet/native/generated/cronet.idl_impl_struct.h" @@ -23,6 +26,15 @@ namespace { +using RequestFinishedInfo = base::RefCountedData<Cronet_RequestFinishedInfo>; +using UrlResponseInfo = base::RefCountedData<Cronet_UrlResponseInfo>; +using CronetError = base::RefCountedData<Cronet_Error>; + +template <typename T> +T* GetData(scoped_refptr<base::RefCountedData<T>> ptr) { + return ptr == nullptr ? nullptr : &ptr->data; +} + net::RequestPriority ConvertRequestPriority( Cronet_UrlRequestParams_REQUEST_PRIORITY priority) { switch (priority) { @@ -40,7 +52,7 @@ return net::DEFAULT_PRIORITY; } -std::unique_ptr<Cronet_UrlResponseInfo> CreateCronet_UrlResponseInfo( +scoped_refptr<UrlResponseInfo> CreateCronet_UrlResponseInfo( const std::vector<std::string>& url_chain, int http_status_code, const std::string& http_status_text, @@ -49,11 +61,11 @@ const std::string& negotiated_protocol, const std::string& proxy_server, int64_t received_byte_count) { - auto response_info = std::make_unique<Cronet_UrlResponseInfo>(); - response_info->url = url_chain.back(); - response_info->url_chain = url_chain; - response_info->http_status_code = http_status_code; - response_info->http_status_text = http_status_text; + auto response_info = base::MakeRefCounted<UrlResponseInfo>(); + response_info->data.url = url_chain.back(); + response_info->data.url_chain = url_chain; + response_info->data.http_status_code = http_status_code; + response_info->data.http_status_text = http_status_text; // |headers| could be nullptr. if (headers != nullptr) { size_t iter = 0; @@ -63,13 +75,13 @@ Cronet_HttpHeader header; header.name = header_name; header.value = header_value; - response_info->all_headers_list.push_back(std::move(header)); + response_info->data.all_headers_list.push_back(std::move(header)); } } - response_info->was_cached = was_cached; - response_info->negotiated_protocol = negotiated_protocol; - response_info->proxy_server = proxy_server; - response_info->received_byte_count = received_byte_count; + response_info->data.was_cached = was_cached; + response_info->data.negotiated_protocol = negotiated_protocol; + response_info->data.proxy_server = proxy_server; + response_info->data.received_byte_count = received_byte_count; return response_info; } @@ -118,17 +130,16 @@ } } -std::unique_ptr<Cronet_Error> CreateCronet_Error( - int net_error, - int quic_error, - const std::string& error_string) { - auto error = std::make_unique<Cronet_Error>(); - error->error_code = NetErrorToCronetErrorCode(net_error); - error->message = error_string; - error->internal_error_code = net_error; - error->quic_detailed_error_code = quic_error; - error->immediately_retryable = - IsCronetErrorImmediatelyRetryable(error->error_code); +scoped_refptr<CronetError> CreateCronet_Error(int net_error, + int quic_error, + const std::string& error_string) { + auto error = base::MakeRefCounted<CronetError>(); + error->data.error_code = NetErrorToCronetErrorCode(net_error); + error->data.message = error_string; + error->data.internal_error_code = net_error; + error->data.quic_detailed_error_code = quic_error; + error->data.immediately_retryable = + IsCronetErrorImmediatelyRetryable(error->data.error_code); return error; } @@ -338,6 +349,8 @@ request_finished_listener_ = params->request_finished_listener; request_finished_executor_ = params->request_finished_executor; + // Copy, don't move -- this function isn't allowed to change |params|. + annotations_ = params->annotations; auto network_tasks = std::make_unique<NetworkTasks>(url, this); network_tasks_ = network_tasks.get(); @@ -504,7 +517,7 @@ return; error_ = CreateCronet_Error( 0, 0, "Failure from UploadDataProvider: " + error_message); - error_->error_code = Cronet_Error_ERROR_CODE_ERROR_CALLBACK; + error_->data.error_code = Cronet_Error_ERROR_CODE_ERROR_CALLBACK; request_->MaybeReportMetricsAndRunCallback( base::BindOnce(&Cronet_UrlRequestImpl::PostCallbackOnFailedToExecutor, @@ -523,7 +536,7 @@ if (IsDone()) return; Cronet_UrlRequestCallback_OnRedirectReceived( - callback_, this, response_info_.get(), new_location.c_str()); + callback_, this, GetData(response_info_), new_location.c_str()); } void Cronet_UrlRequestImpl::InvokeCallbackOnResponseStarted() { @@ -538,7 +551,7 @@ } #endif // DCHECK_IS_ON() Cronet_UrlRequestCallback_OnResponseStarted(callback_, this, - response_info_.get()); + GetData(response_info_)); } void Cronet_UrlRequestImpl::InvokeCallbackOnReadCompleted( @@ -547,7 +560,7 @@ if (IsDone()) return; Cronet_UrlRequestCallback_OnReadCompleted( - callback_, this, response_info_.get(), cronet_buffer.release(), + callback_, this, GetData(response_info_), cronet_buffer.release(), bytes_read); } @@ -557,7 +570,9 @@ return; } InvokeAllStatusListeners(); - Cronet_UrlRequestCallback_OnSucceeded(callback_, this, response_info_.get()); + MaybeReportMetrics(Cronet_RequestFinishedInfo_FINISHED_REASON_SUCCEEDED); + Cronet_UrlRequestCallback_OnSucceeded(callback_, this, + GetData(response_info_)); // |this| may have been deleted here. } @@ -567,14 +582,17 @@ return; } InvokeAllStatusListeners(); - Cronet_UrlRequestCallback_OnFailed(callback_, this, response_info_.get(), - error_.get()); + MaybeReportMetrics(Cronet_RequestFinishedInfo_FINISHED_REASON_FAILED); + Cronet_UrlRequestCallback_OnFailed(callback_, this, GetData(response_info_), + GetData(error_)); // |this| may have been deleted here. } void Cronet_UrlRequestImpl::InvokeCallbackOnCanceled() { InvokeAllStatusListeners(); - Cronet_UrlRequestCallback_OnCanceled(callback_, this, response_info_.get()); + MaybeReportMetrics(Cronet_RequestFinishedInfo_FINISHED_REASON_CANCELED); + Cronet_UrlRequestCallback_OnCanceled(callback_, this, + GetData(response_info_)); // |this| may have been deleted here. } @@ -598,6 +616,33 @@ #endif // DCHECK_IS_ON() } +void Cronet_UrlRequestImpl::MaybeReportMetrics( + Cronet_RequestFinishedInfo_FINISHED_REASON finished_reason) { + if (request_finished_info_ == nullptr) + return; + request_finished_info_->data.annotations = std::move(annotations_); + request_finished_info_->data.finished_reason = finished_reason; + + engine_->ReportRequestFinished(request_finished_info_, response_info_, + error_); + if (request_finished_listener_ != nullptr) { + DCHECK(request_finished_executor_ != nullptr); + // Execute() owns and deletes the runnable. + request_finished_executor_->Execute( + new cronet::OnceClosureRunnable(base::BindOnce( + [](Cronet_RequestFinishedInfoListenerPtr request_finished_listener, + scoped_refptr<RequestFinishedInfo> request_finished_info, + scoped_refptr<UrlResponseInfo> response_info, + scoped_refptr<CronetError> error) { + request_finished_listener->OnRequestFinished( + GetData(request_finished_info), GetData(response_info), + GetData(error)); + }, + request_finished_listener_, request_finished_info_, response_info_, + error_))); + } +} + Cronet_UrlRequestImpl::NetworkTasks::NetworkTasks( const std::string& url, Cronet_UrlRequestImpl* url_request) @@ -670,7 +715,8 @@ { base::AutoLock lock(url_request_->lock_); url_request_->waiting_on_read_ = true; - url_request_->response_info_->received_byte_count = received_byte_count; + url_request_->response_info_->data.received_byte_count = + received_byte_count; } // Invoke Cronet_UrlRequestCallback_OnReadCompleted on client executor. @@ -684,7 +730,8 @@ DCHECK_CALLED_ON_VALID_THREAD(network_thread_checker_); { base::AutoLock lock(url_request_->lock_); - url_request_->response_info_->received_byte_count = received_byte_count; + url_request_->response_info_->data.received_byte_count = + received_byte_count; } // Invoke Cronet_UrlRequestCallback_OnSucceeded on client executor. @@ -703,7 +750,8 @@ { base::AutoLock lock(url_request_->lock_); if (url_request_->response_info_) - url_request_->response_info_->received_byte_count = received_byte_count; + url_request_->response_info_->data.received_byte_count = + received_byte_count; url_request_->error_ = CreateCronet_Error(net_error, quic_error, error_string); } @@ -755,9 +803,12 @@ int64_t received_bytes_count) { DCHECK_CALLED_ON_VALID_THREAD(network_thread_checker_); base::AutoLock lock(url_request_->lock_); - DCHECK_EQ(url_request_->metrics_.get(), nullptr) + DCHECK_EQ(url_request_->request_finished_info_, nullptr) << "Metrics collection should only happen once."; - auto metrics = std::make_unique<Cronet_Metrics>(); + url_request_->request_finished_info_ = + base::MakeRefCounted<RequestFinishedInfo>(); + auto& metrics = url_request_->request_finished_info_->data.metrics; + metrics.emplace(); using native_metrics_util::ConvertTime; ConvertTime(request_start, request_start, request_start_time, &metrics->request_start); @@ -785,7 +836,6 @@ metrics->socket_reused = socket_reused; metrics->sent_byte_count = sent_bytes_count; metrics->received_byte_count = received_bytes_count; - url_request_->metrics_ = std::move(metrics); } void Cronet_UrlRequestImpl::NetworkTasks::OnStatus(
diff --git a/components/cronet/native/url_request.h b/components/cronet/native/url_request.h index dc77482..02992ef4 100644 --- a/components/cronet/native/url_request.h +++ b/components/cronet/native/url_request.h
@@ -90,6 +90,19 @@ // and |executor_| may be deleted and so the callbacks cannot be issued. void InvokeAllStatusListeners(); + // Reports metrics if metrics were collected, otherwise does nothing. This + // method should only be called once on Callback's executor thread and before + // Callback's OnSucceeded, OnFailed and OnCanceled. + // + // Adds |finished_reason| to the reported RequestFinishedInfo. Also passes + // pointers to |response_info_| and |error_|. + // + // Also, the field |annotations_| is moved into the RequestFinishedInfo. + // + // |finished_reason|: Success / fail / cancel status of request. + void MaybeReportMetrics( + Cronet_RequestFinishedInfo_FINISHED_REASON finished_reason); + // Synchronize access to |request_| and other objects below from different // threads. base::Lock lock_; @@ -105,10 +118,26 @@ std::unordered_multiset<Cronet_UrlRequestStatusListenerPtr> status_listeners_ GUARDED_BY(lock_); - // Metrics to include in RequestFinishedInfo report sent to attached - // RequestFinishedListener(s). A nullptr value indicates that the metrics - // haven't been collected. - std::unique_ptr<Cronet_Metrics> metrics_ GUARDED_BY(lock_); + // Report containing metrics and other information to send to attached + // RequestFinishedListener(s). A nullptr value indicates that metrics haven't + // been collected. + // + // Ownership is shared since we guarantee that the RequestFinishedInfo will + // be valid if its UrlRequest isn't destroyed. We also guarantee that it's + // valid in RequestFinishedListener.OnRequestFinished() even if the + // UrlRequest is destroyed (and furthermore, each listener finishes at + // different times). + // + // NOTE: this field isn't protected by |lock_| since we pass this field as a + // unowned pointer to OnRequestFinished(). The pointee of this field cannot + // be updated after that call is made. + scoped_refptr<base::RefCountedData<Cronet_RequestFinishedInfo>> + request_finished_info_; + + // Annotations passed via UrlRequestParams.annotations. These annotations + // aren't used by Cronet itself -- they're just moved into the + // RequestFinishedInfo passed to RequestFinishedInfoListener instances. + std::vector<Cronet_RawDataPtr> annotations_; // Optional; allows a listener to receive request info and stats. // @@ -128,18 +157,30 @@ // Response info updated by callback with number of bytes received. May be // nullptr, if no response has been received. // - // NOTE: the synchronization of this field is complex -- it can't be - // completely protected by |lock_| since we pass this field as a unowned - // pointer to OnSucceed(), OnFailed(), and OnCanceled(). The pointee of this - // field cannot be updated after one of those callback calls is made. - std::unique_ptr<Cronet_UrlResponseInfo> response_info_; - // The error reported by request. May be nullptr if no error has occurred. + // Ownership is shared since we guarantee that the UrlResponseInfo will + // be valid if its UrlRequest isn't destroyed. We also guarantee that it's + // valid in RequestFinishedListener.OnRequestFinished() even if the + // UrlRequest is destroyed (and furthermore, each listener finishes at + // different times). // // NOTE: the synchronization of this field is complex -- it can't be // completely protected by |lock_| since we pass this field as a unowned // pointer to OnSucceed(), OnFailed(), and OnCanceled(). The pointee of this // field cannot be updated after one of those callback calls is made. - std::unique_ptr<Cronet_Error> error_; + scoped_refptr<base::RefCountedData<Cronet_UrlResponseInfo>> response_info_; + + // The error reported by request. May be nullptr if no error has occurred. + // + // Ownership is shared since we guarantee that the Error will be valid if its + // UrlRequest isn't destroyed. We also guarantee that it's valid in + // RequestFinishedListener.OnRequestFinished() even if the UrlRequest is + // destroyed (and furthermore, each listener finishes at different times). + // + // NOTE: the synchronization of this field is complex -- it can't be + // completely protected by |lock_| since we pass this field as an unowned + // pointer to OnSucceed(), OnFailed(), and OnCanceled(). The pointee of this + // field cannot be updated after one of those callback calls is made. + scoped_refptr<base::RefCountedData<Cronet_Error>> error_; // The upload data stream if specified. std::unique_ptr<Cronet_UploadDataSinkImpl> upload_data_sink_;
diff --git a/components/module_installer/android/java/src-impl/org/chromium/components/module_installer/PlayCoreModuleInstallerBackend.java b/components/module_installer/android/java/src-impl/org/chromium/components/module_installer/PlayCoreModuleInstallerBackend.java index 447be85..13ba7c7 100644 --- a/components/module_installer/android/java/src-impl/org/chromium/components/module_installer/PlayCoreModuleInstallerBackend.java +++ b/components/module_installer/android/java/src-impl/org/chromium/components/module_installer/PlayCoreModuleInstallerBackend.java
@@ -174,6 +174,7 @@ @Override public void onStateUpdate(SplitInstallSessionState state) { assert !mIsClosed; + Log.i(TAG, "Status for modules '%s' updated to %d", state.moduleNames(), state.status()); switch (state.status()) { case SplitInstallSessionStatus.DOWNLOADING: case SplitInstallSessionStatus.DOWNLOADED:
diff --git a/components/new_or_sad_tab_strings.grdp b/components/new_or_sad_tab_strings.grdp index 47f5ccc..4771a59 100644 --- a/components/new_or_sad_tab_strings.grdp +++ b/components/new_or_sad_tab_strings.grdp
@@ -60,9 +60,6 @@ <message name="IDS_SAD_TAB_RELOAD_INCOGNITO" desc="One of the bullet points displayed on the web page if a reload failed to fix the issue, advising the user to open the web page in Chrome's Incognito mode." formatter_data="android_java"> Open page in a new Incognito tab </message> - <message name="IDS_SAD_TAB_RELOAD_PRIVATE" desc="One of the bullet points displayed on the web page if a reload failed to fix the issue, advising the user to open the web page in Chrome's private mode. Note that 'Private' is used as a different name for 'Incognito'." formatter_data="android_java"> - Open page in a new Private tab - </message> </if> <if expr="is_macosx or chromeos"> <message name="IDS_SAD_TAB_RELOAD_CLOSE_TABS" desc="One of the bullet points displayed on the web page if a reload failed to fix the issue, advising the user to close other Chrome tabs or apps running on their computer (Mac, Chrome OS)."> @@ -144,9 +141,6 @@ <message name="IDS_NEW_TAB_OTR_TITLE" desc="Title of the Incognito new tab page. The Incognito mode provides private browsing experience by hiding browsing activity from other people using the same device. However, it does not make the user completely invisible or anonymous; please don't translate it as such." formatter_data="android_java"> You’ve gone incognito </message> - <message name="IDS_NEW_TAB_PRIVATE_TITLE" desc="Title of the Private new tab page. The Private mode provides private browsing experience by hiding browsing activity from other people using the same device. However, it does not make the user completely invisible or anonymous; please don't translate it as such. Note that 'Private' is used as a different name for 'Incognito'." formatter_data="android_java"> - You’ve gone private - </message> <message name="IDS_NEW_TAB_OTR_SUBTITLE" desc="Subtitle of the Incognito new tab page, explaining to the user that the Incognito mode hides their browsing activity from other people using the same device. The second sentence clarifies that there are two important exceptions from this rule - downloaded files and added bookmarks will be persisted even after the Incognito session is closed." formatter_data="android_java"> Now you can browse privately, and other people who use this device won’t see your activity. However, downloads and bookmarks will be saved. </message>
diff --git a/components/omnibox/browser/autocomplete_match_classification.cc b/components/omnibox/browser/autocomplete_match_classification.cc index d5a79e5f..8203cbf 100644 --- a/components/omnibox/browser/autocomplete_match_classification.cc +++ b/components/omnibox/browser/autocomplete_match_classification.cc
@@ -11,7 +11,7 @@ namespace { base::string16 clean(base::string16 text) { - const size_t kMaxTextLength = 200; + const size_t kMaxTextLength = 2000; return base::i18n::ToLower(text.substr(0, kMaxTextLength)); }
diff --git a/components/payments/OWNERS b/components/payments/OWNERS index 766c6ea..5751c73 100644 --- a/components/payments/OWNERS +++ b/components/payments/OWNERS
@@ -1,4 +1,5 @@ gogerald@chromium.org rouslan@chromium.org +danyao@chromium.org # COMPONENT: UI>Browser>Payments
diff --git a/components/payments_strings.grdp b/components/payments_strings.grdp index d545b2d..b17b26c 100644 --- a/components/payments_strings.grdp +++ b/components/payments_strings.grdp
@@ -582,9 +582,6 @@ <message name="IDS_EXTERNAL_PAYMENT_APP_LEAVE_INCOGNITO_WARNING" desc="Alert dialog text warning the user that incognito mode does not continue into external payment apps." formatter_data="android_java"> Leaving incognito mode to pay via an external application. Continue? </message> - <message name="IDS_EXTERNAL_PAYMENT_APP_LEAVE_PRIVATE_WARNING" desc="Alert dialog text warning the user that private mode does not continue into external payment apps." formatter_data="android_java"> - Leaving private mode to pay via an external application. Continue? - </message> </if> <!-- Payment Request section preview strings. They are slightly different on desktop and android because the pluralization and formatting code behaves differently. -->
diff --git a/components/viz/service/display/skia_renderer.cc b/components/viz/service/display/skia_renderer.cc index ea01418..ef8cd43 100644 --- a/components/viz/service/display/skia_renderer.cc +++ b/components/viz/service/display/skia_renderer.cc
@@ -1632,8 +1632,19 @@ // Convert CC image filters for the backdrop into a SkImageFilter root node if (backdrop_filters) { DCHECK(!backdrop_filters->IsEmpty()); + + // Must account for clipping that occurs for backdrop filters, since their + // input content has already been clipped to the output rect. + gfx::Rect deviceRect = gfx::ToEnclosingRect(cc::MathUtil::MapClippedRect( + params->content_device_transform, gfx::RectF(quad->rect))); + gfx::Rect outRect = MoveFromDrawToWindowSpace( + current_frame()->current_render_pass->output_rect); + outRect.Intersect(deviceRect); + gfx::Vector2dF offset = (deviceRect.top_right() - outRect.top_right()) + + (deviceRect.bottom_left() - outRect.bottom_left()); + auto bg_paint_filter = cc::RenderSurfaceFilters::BuildImageFilter( - *backdrop_filters, filter_size); + *backdrop_filters, gfx::SizeF(outRect.size()), offset); auto sk_bg_filter = bg_paint_filter ? bg_paint_filter->cached_sk_filter_ : nullptr; @@ -1795,13 +1806,20 @@ } // Save the layer with the restoration paint (which holds the final image - // filters and blending parameters), the backdrop filters, and mask image. + // filters, the backdrop filters, and mask image. If we have a backdrop filter + // the layer will blended with src-over, and the rpdq's blend mode will apply + // when drawing the content into the layer itself. When there's no backdrop + // (so the layer starts empty), use the rp's blend mode when flattening layer. SkCanvas::SaveLayerFlags layer_flags = 0; + SkBlendMode content_blend = SkBlendMode::kSrcOver; if (rpdq_params.backdrop_filter) { layer_flags |= SkCanvas::kInitWithPrevious_SaveLayerFlag; + content_blend = paint.getBlendMode(); + paint.setBlendMode(SkBlendMode::kSrcOver); } + SkRect bounds = gfx::RectFToSkRect(params->visible_rect); current_canvas_->saveLayer( - SkCanvas::SaveLayerRec(nullptr, &paint, rpdq_params.backdrop_filter.get(), + SkCanvas::SaveLayerRec(&bounds, &paint, rpdq_params.backdrop_filter.get(), rpdq_params.mask_image.get(), &rpdq_params.mask_to_quad_matrix, layer_flags)); @@ -1819,9 +1837,11 @@ } // Now draw the main content using the same per-edge AA API to be consistent - // with DrawSingleImage. Use a new paint that defaults to opaque+src-over, - // and just preserve the filter quality from the original paint. + // with DrawSingleImage. Use a new paint that uses either srcOver or the rpdq + // blend mode, depending how filters were applied, and just preserve the + // filter quality from the original paint. SkPaint content_paint; + content_paint.setBlendMode(content_blend); content_paint.setFilterQuality(paint.getFilterQuality()); SkCanvas::SrcRectConstraint constraint =
diff --git a/components/viz/service/display_embedder/direct_context_provider.cc b/components/viz/service/display_embedder/direct_context_provider.cc index abfc342..8d0a716 100644 --- a/components/viz/service/display_embedder/direct_context_provider.cc +++ b/components/viz/service/display_embedder/direct_context_provider.cc
@@ -134,10 +134,11 @@ gl_context_.reset(); transfer_buffer_.reset(); gles2_cmd_helper_.reset(); - command_buffer_.reset(); decoder_->Destroy(have_context); decoder_.reset(); + + command_buffer_.reset(); } void DirectContextProvider::SetGLRendererCopierRequiredState(
diff --git a/components/viz/test/data/blur_filter_with_clip_skia.png b/components/viz/test/data/blur_filter_with_clip_skia.png new file mode 100644 index 0000000..c4c6b83 --- /dev/null +++ b/components/viz/test/data/blur_filter_with_clip_skia.png Binary files differ
diff --git a/components/viz/test/data/rotated_drop_shadow_filter_skia.png b/components/viz/test/data/rotated_drop_shadow_filter_skia.png index b67789ab..96b36769 100644 --- a/components/viz/test/data/rotated_drop_shadow_filter_skia.png +++ b/components/viz/test/data/rotated_drop_shadow_filter_skia.png Binary files differ
diff --git a/components/viz/test/data/zoom_filter_skia.png b/components/viz/test/data/zoom_filter_skia.png new file mode 100644 index 0000000..4eaa23c --- /dev/null +++ b/components/viz/test/data/zoom_filter_skia.png Binary files differ
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index f131f341..5665846 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -199,7 +199,6 @@ "//third_party/blink/public:scaled_resources", "//third_party/blink/public/common", "//third_party/blink/public/mojom:mojom_broadcastchannel_bindings", - "//third_party/blink/public/mojom:web_bluetooth_mojo_bindings", "//third_party/boringssl", "//third_party/brotli:dec", "//third_party/icu", @@ -805,8 +804,6 @@ "dom_storage/dom_storage_database_adapter.h", "dom_storage/dom_storage_host.cc", "dom_storage/dom_storage_host.h", - "dom_storage/dom_storage_message_filter.cc", - "dom_storage/dom_storage_message_filter.h", "dom_storage/dom_storage_namespace.cc", "dom_storage/dom_storage_namespace.h", "dom_storage/dom_storage_task_runner.cc",
diff --git a/content/browser/accessibility/ax_platform_node_textrangeprovider_win_browsertest.cc b/content/browser/accessibility/ax_platform_node_textrangeprovider_win_browsertest.cc index c44e9ad..e63f56b 100644 --- a/content/browser/accessibility/ax_platform_node_textrangeprovider_win_browsertest.cc +++ b/content/browser/accessibility/ax_platform_node_textrangeprovider_win_browsertest.cc
@@ -11,9 +11,12 @@ #include "content/browser/accessibility/browser_accessibility.h" #include "content/browser/accessibility/browser_accessibility_com_win.h" #include "content/browser/accessibility/browser_accessibility_manager.h" +#include "content/browser/web_contents/web_contents_impl.h" #include "content/public/test/browser_test_utils.h" +#include "content/public/test/hit_test_region_observer.h" #include "content/shell/browser/shell.h" #include "content/test/accessibility_browser_test_utils.h" +#include "content/test/content_browser_test_utils_internal.h" #include "net/dns/mock_host_resolver.h" using Microsoft::WRL::ComPtr; @@ -79,6 +82,16 @@ ASSERT_TRUE(embedded_test_server()->Start()); } + RenderWidgetHostImpl* GetWidgetHost() { + return RenderWidgetHostImpl::From( + shell()->web_contents()->GetRenderViewHost()->GetWidget()); + } + + void SynchronizeThreads() { + MainThreadFrameObserver observer(GetWidgetHost()); + observer.Wait(); + } + void GetTextRangeProviderFromTextNode( ComPtr<ITextRangeProvider>& text_range_provider, BrowserAccessibility* target_browser_accessibility) { @@ -837,6 +850,100 @@ } IN_PROC_BROWSER_TEST_F(AXPlatformNodeTextRangeProviderWinBrowserTest, + OutOfProcessIFrameTraversal) { + GURL main_url(embedded_test_server()->GetURL( + "a.com", "/accessibility/html/iframe-cross-process.html")); + LoadInitialAccessibilityTreeFromUrl(main_url); + + WaitForAccessibilityTreeToContainNodeWithName(shell()->web_contents(), + "Text in iframe"); + + FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) + ->GetFrameTree() + ->root(); + ASSERT_EQ(1U, root->child_count()); + + // Navigate oopif to URL. + FrameTreeNode* iframe_node = root->child_at(0); + GURL iframe_url(embedded_test_server()->GetURL( + "b.com", "/accessibility/html/frame/static_text.html")); + WebContentsImpl* iframe_web_contents = + WebContentsImpl::FromFrameTreeNode(iframe_node); + DCHECK(iframe_web_contents); + { + AccessibilityNotificationWaiter waiter(iframe_web_contents, + ui::kAXModeComplete, + ax::mojom::Event::kLoadComplete); + NavigateFrameToURL(iframe_node, iframe_url); + waiter.WaitForNotification(); + } + + SynchronizeThreads(); + WaitForAccessibilityTreeToContainNodeWithName(shell()->web_contents(), + "Text in iframe"); + + WaitForHitTestDataOrChildSurfaceReady(iframe_node->current_frame_host()); + FrameTreeVisualizer visualizer; + ASSERT_EQ( + " Site A ------------ proxies for B\n" + " +--Site B ------- proxies for A\n" + "Where A = http://a.com/\n" + " B = http://b.com/", + visualizer.DepictFrameTree(root)); + + auto* node = FindNode(ax::mojom::Role::kStaticText, "After frame"); + ASSERT_NE(nullptr, node); + EXPECT_TRUE(node->PlatformIsLeaf()); + EXPECT_EQ(0u, node->PlatformChildCount()); + + ComPtr<ITextRangeProvider> text_range_provider; + GetTextRangeProviderFromTextNode(text_range_provider, node); + ASSERT_NE(nullptr, text_range_provider.Get()); + EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"After frame"); + + EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT( + text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Word, + /*count*/ -1, + /*expected_text*/ L"iframeAfter frame", + /*expected_count*/ -1); + EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT( + text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Word, + /*count*/ -2, + /*expected_text*/ L"Text in iframeAfter frame", + /*expected_count*/ -2); + EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider, + TextPatternRangeEndpoint_End, TextUnit_Word, + /*count*/ -3, + /*expected_text*/ L"Text in", + /*expected_count*/ -3); + EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider, + TextPatternRangeEndpoint_End, TextUnit_Word, + /*count*/ 2, + /*expected_text*/ L"Text in iframeAfter", + /*expected_count*/ 2); + EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT( + text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Line, + /*count*/ 1, + /*expected_text*/ L"Text in iframeAfter frame", + /*expected_count*/ 1); + EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT( + text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Document, + /*count*/ 1, + /*expected_text*/ L"", + /*expected_count*/ 1); + EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT( + text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Character, + /*count*/ -17, + /*expected_text*/ L"iframeAfter frame", + /*expected_count*/ -17); + EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider, + TextPatternRangeEndpoint_End, TextUnit_Line, + /*count*/ -1, + /*expected_text*/ L"iframe", + /*expected_count*/ -1); +} + +IN_PROC_BROWSER_TEST_F(AXPlatformNodeTextRangeProviderWinBrowserTest, ExpandToEnclosingFormat) { LoadInitialAccessibilityTreeFromHtml( R"HTML(<!DOCTYPE html>
diff --git a/content/browser/accessibility/browser_accessibility_manager.cc b/content/browser/accessibility/browser_accessibility_manager.cc index cff0477..773fc1cb 100644 --- a/content/browser/accessibility/browser_accessibility_manager.cc +++ b/content/browser/accessibility/browser_accessibility_manager.cc
@@ -1324,7 +1324,8 @@ } bool BrowserAccessibilityManager::IsRootTree() { - return delegate()->AccessibilityIsMainFrame(); + return delegate()->AccessibilityIsMainFrame() && + GetTreeData().parent_tree_id == ui::AXTreeIDUnknown(); } // static
diff --git a/content/browser/accessibility/browser_accessibility_manager_win_unittest.cc b/content/browser/accessibility/browser_accessibility_manager_win_unittest.cc index 4d67502d..62e499bc 100644 --- a/content/browser/accessibility/browser_accessibility_manager_win_unittest.cc +++ b/content/browser/accessibility/browser_accessibility_manager_win_unittest.cc
@@ -82,4 +82,61 @@ root_document_root_node->GetNativeViewAccessible()); } +TEST_F(BrowserAccessibilityManagerWinTest, ChildTree) { + base::CommandLine::ForCurrentProcess()->AppendSwitch( + ::switches::kEnableExperimentalUIAutomation); + + ui::AXNodeData child_tree_root; + child_tree_root.id = 1; + child_tree_root.role = ax::mojom::Role::kRootWebArea; + ui::AXTreeUpdate child_tree_update = MakeAXTreeUpdate(child_tree_root); + + ui::AXNodeData parent_tree_root; + parent_tree_root.id = 1; + parent_tree_root.role = ax::mojom::Role::kRootWebArea; + parent_tree_root.AddStringAttribute( + ax::mojom::StringAttribute::kChildTreeId, + child_tree_update.tree_data.tree_id.ToString()); + ui::AXTreeUpdate parent_tree_update = MakeAXTreeUpdate(parent_tree_root); + + child_tree_update.tree_data.parent_tree_id = + parent_tree_update.tree_data.tree_id; + + test_browser_accessibility_delegate_->accelerated_widget_ = + gfx::kMockAcceleratedWidget; + + std::unique_ptr<BrowserAccessibilityManager> parent_manager( + BrowserAccessibilityManager::Create( + parent_tree_update, test_browser_accessibility_delegate_.get(), + new BrowserAccessibilityFactory())); + + ui::AXPlatformNode* root_document_root_node = + ui::AXPlatformNode::FromNativeViewAccessible( + parent_manager->GetRoot()->GetNativeViewAccessible()); + + std::unique_ptr<ui::AXPlatformNodeDelegate> fragment_root = + std::make_unique<ui::AXFragmentRootWin>( + gfx::kMockAcceleratedWidget, + static_cast<ui::AXPlatformNodeWin*>(root_document_root_node)); + + EXPECT_EQ(fragment_root->GetChildCount(), 1); + EXPECT_EQ(fragment_root->ChildAtIndex(0), + root_document_root_node->GetNativeViewAccessible()); + + // Add the child tree. + std::unique_ptr<TestBrowserAccessibilityDelegate> child_tree_delegate = + std::make_unique<TestBrowserAccessibilityDelegate>(); + child_tree_delegate->is_root_frame_ = true; + child_tree_delegate->accelerated_widget_ = gfx::kMockAcceleratedWidget; + std::unique_ptr<BrowserAccessibilityManager> child_manager( + BrowserAccessibilityManager::Create(child_tree_update, + child_tree_delegate.get(), + new BrowserAccessibilityFactory())); + + // The fragment root's lone child should still be the same as before. + EXPECT_EQ(fragment_root->GetChildCount(), 1); + EXPECT_EQ(fragment_root->ChildAtIndex(0), + root_document_root_node->GetNativeViewAccessible()); +} + } // namespace content
diff --git a/content/browser/appcache/appcache_browsertest.cc b/content/browser/appcache/appcache_browsertest.cc index 2c35177..9e45b07 100644 --- a/content/browser/appcache/appcache_browsertest.cc +++ b/content/browser/appcache/appcache_browsertest.cc
@@ -4,13 +4,19 @@ #include <stdint.h> #include "base/bind.h" +#include "base/run_loop.h" +#include "base/strings/strcat.h" #include "base/strings/utf_string_conversions.h" #include "base/test/bind_test_util.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" #include "content/browser/appcache/appcache_subresource_url_factory.h" #include "content/public/browser/navigation_entry.h" +#include "content/public/browser/render_frame_host.h" +#include "content/public/browser/render_process_host.h" #include "content/public/browser/ssl_status.h" +#include "content/public/browser/storage_partition.h" +#include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" @@ -23,6 +29,7 @@ #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" #include "services/network/public/cpp/features.h" +#include "services/network/public/mojom/network_context.mojom.h" namespace content { @@ -122,4 +129,71 @@ EXPECT_TRUE(entry->GetSSL().certificate); } +// Regression test for crbug.com/968179. +IN_PROC_BROWSER_TEST_F(AppCacheNetworkServiceBrowserTest, + CacheableResourcesReuse) { + net::EmbeddedTestServer embedded_test_server; + + std::string manifest_nonce = "# Version 1"; + int resource_request_count = 0; + embedded_test_server.RegisterRequestHandler(base::BindLambdaForTesting( + [&](const net::test_server::HttpRequest& request) + -> std::unique_ptr<net::test_server::HttpResponse> { + if (request.GetURL().path() != "/appcache/cache_reuse.manifest") { + ++resource_request_count; + return nullptr; + } + + // Return a dynamically generated manifest, to trigger AppCache updates. + auto http_response = + std::make_unique<net::test_server::BasicHttpResponse>(); + http_response->set_content_type("text/cache-manifest"); + http_response->set_content(base::StrCat({ + "CACHE MANIFEST\n", + manifest_nonce, + "\n/appcache/cache_reuse.html\n", + })); + return http_response; + })); + + embedded_test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, + net::SSLServerConfig()); + embedded_test_server.ServeFilesFromSourceDirectory(GetTestDataFilePath()); + ASSERT_TRUE(embedded_test_server.Start()); + + GURL main_url = embedded_test_server.GetURL("/appcache/cache_reuse.html"); + + // First navigation populates AppCache. + { + EXPECT_TRUE(NavigateToURL(shell(), main_url)); + base::string16 expected_title = base::ASCIIToUTF16("AppCache primed"); + TitleWatcher title_watcher(shell()->web_contents(), expected_title); + EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); + } + + // Flush the HTTP cache so cache_reuse.html won't be served from there. + base::RunLoop run_loop; + content::StoragePartition* storage_partition = shell() + ->web_contents() + ->GetMainFrame() + ->GetProcess() + ->GetStoragePartition(); + storage_partition->GetNetworkContext()->ClearHttpCache( + base::Time(), base::Time::Max(), nullptr, run_loop.QuitClosure()); + run_loop.Run(); + + // Second navigation triggers an AppCache update. + resource_request_count = 0; + manifest_nonce = "# Version 2"; + { + EXPECT_TRUE(NavigateToURL(shell(), main_url)); + base::string16 expected_title = base::ASCIIToUTF16("AppCache updated"); + TitleWatcher title_watcher(shell()->web_contents(), expected_title); + EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); + } + + // The AppCache update should only reload the manifest. + EXPECT_EQ(0, resource_request_count); +} + } // namespace content
diff --git a/content/browser/appcache/appcache_update_url_loader_request.cc b/content/browser/appcache/appcache_update_url_loader_request.cc index 155e623..f232fbc 100644 --- a/content/browser/appcache/appcache_update_url_loader_request.cc +++ b/content/browser/appcache/appcache_update_url_loader_request.cc
@@ -137,7 +137,7 @@ // Populate other fields in the HttpResponseInfo class. It would be good to // have a helper function which populates the HttpResponseInfo structure from // the ResourceResponseHead structure. - http_response_info_.reset(new net::HttpResponseInfo()); + http_response_info_ = std::make_unique<net::HttpResponseInfo>(); if (response_head.ssl_info.has_value()) http_response_info_->ssl_info = *response_head.ssl_info; http_response_info_->headers = response_head.headers; @@ -148,6 +148,8 @@ response_head.alpn_negotiated_protocol; http_response_info_->connection_info = response_head.connection_info; http_response_info_->remote_endpoint = response_head.remote_endpoint; + http_response_info_->request_time = response_head.request_time; + http_response_info_->response_time = response_head.response_time; fetcher_->OnResponseStarted(net::OK); }
diff --git a/content/browser/bluetooth/DEPS b/content/browser/bluetooth/DEPS index 78c99702..8dec055 100644 --- a/content/browser/bluetooth/DEPS +++ b/content/browser/bluetooth/DEPS
@@ -1,3 +1,4 @@ include_rules = [ "+device/bluetooth", + "+third_party/blink/common/bluetooth", ]
diff --git a/content/browser/bluetooth/bluetooth_allowed_devices.cc b/content/browser/bluetooth/bluetooth_allowed_devices.cc index dda74a0..862e1b0 100644 --- a/content/browser/bluetooth/bluetooth_allowed_devices.cc +++ b/content/browser/bluetooth/bluetooth_allowed_devices.cc
@@ -12,7 +12,6 @@ #include "base/stl_util.h" #include "base/strings/string_util.h" #include "content/browser/bluetooth/bluetooth_blocklist.h" -#include "content/common/bluetooth/web_bluetooth_device_id.h" using device::BluetoothUUID; @@ -23,7 +22,7 @@ const BluetoothAllowedDevices& other) = default; BluetoothAllowedDevices::~BluetoothAllowedDevices() {} -const WebBluetoothDeviceId& BluetoothAllowedDevices::AddDevice( +const blink::WebBluetoothDeviceId& BluetoothAllowedDevices::AddDevice( const std::string& device_address, const blink::mojom::WebBluetoothRequestDeviceOptionsPtr& options) { auto& device_id = AddDevice(device_address); @@ -37,7 +36,7 @@ return device_id; } -const WebBluetoothDeviceId& BluetoothAllowedDevices::AddDevice( +const blink::WebBluetoothDeviceId& BluetoothAllowedDevices::AddDevice( const std::string& device_address) { DVLOG(1) << "Adding a device to Map of Allowed Devices."; @@ -46,7 +45,7 @@ DVLOG(1) << "Device already in map of allowed devices."; return device_address_to_id_map_[device_address]; } - const WebBluetoothDeviceId device_id = GenerateUniqueDeviceId(); + const blink::WebBluetoothDeviceId device_id = GenerateUniqueDeviceId(); DVLOG(1) << "Id generated for device: " << device_id; device_address_to_id_map_[device_address] = device_id; @@ -58,12 +57,13 @@ } void BluetoothAllowedDevices::RemoveDevice(const std::string& device_address) { - const WebBluetoothDeviceId* device_id_ptr = GetDeviceId(device_address); + const blink::WebBluetoothDeviceId* device_id_ptr = + GetDeviceId(device_address); DCHECK(device_id_ptr != nullptr); // We make a copy because we are going to remove the original value from its // map. - WebBluetoothDeviceId device_id = *device_id_ptr; + blink::WebBluetoothDeviceId device_id = *device_id_ptr; // 1. Remove from all three maps. CHECK(device_address_to_id_map_.erase(device_address)); @@ -77,7 +77,7 @@ CHECK(device_id_set_.erase(device_id)); } -const WebBluetoothDeviceId* BluetoothAllowedDevices::GetDeviceId( +const blink::WebBluetoothDeviceId* BluetoothAllowedDevices::GetDeviceId( const std::string& device_address) { auto id_iter = device_address_to_id_map_.find(device_address); if (id_iter == device_address_to_id_map_.end()) { @@ -87,7 +87,7 @@ } const std::string& BluetoothAllowedDevices::GetDeviceAddress( - const WebBluetoothDeviceId& device_id) { + const blink::WebBluetoothDeviceId& device_id) { auto id_iter = device_id_to_address_map_.find(device_id); return id_iter == device_id_to_address_map_.end() ? base::EmptyString() @@ -95,7 +95,7 @@ } bool BluetoothAllowedDevices::IsAllowedToAccessAtLeastOneService( - const WebBluetoothDeviceId& device_id) const { + const blink::WebBluetoothDeviceId& device_id) const { auto id_iter = device_id_to_services_map_.find(device_id); return id_iter == device_id_to_services_map_.end() ? false @@ -103,7 +103,7 @@ } bool BluetoothAllowedDevices::IsAllowedToAccessService( - const WebBluetoothDeviceId& device_id, + const blink::WebBluetoothDeviceId& device_id, const BluetoothUUID& service_uuid) const { if (BluetoothBlocklist::Get().IsExcluded(service_uuid)) { return false; @@ -117,18 +117,18 @@ } bool BluetoothAllowedDevices::IsAllowedToGATTConnect( - const WebBluetoothDeviceId& device_id) const { + const blink::WebBluetoothDeviceId& device_id) const { auto id_iter = device_id_to_connectable_map_.find(device_id); if (id_iter == device_id_to_connectable_map_.end()) return false; return id_iter->second; } -WebBluetoothDeviceId BluetoothAllowedDevices::GenerateUniqueDeviceId() { - WebBluetoothDeviceId device_id = WebBluetoothDeviceId::Create(); +blink::WebBluetoothDeviceId BluetoothAllowedDevices::GenerateUniqueDeviceId() { + blink::WebBluetoothDeviceId device_id = blink::WebBluetoothDeviceId::Create(); while (base::ContainsKey(device_id_set_, device_id)) { LOG(WARNING) << "Generated repeated id."; - device_id = WebBluetoothDeviceId::Create(); + device_id = blink::WebBluetoothDeviceId::Create(); } return device_id; }
diff --git a/content/browser/bluetooth/bluetooth_allowed_devices.h b/content/browser/bluetooth/bluetooth_allowed_devices.h index d59608a5..ba53d188 100644 --- a/content/browser/bluetooth/bluetooth_allowed_devices.h +++ b/content/browser/bluetooth/bluetooth_allowed_devices.h
@@ -12,8 +12,8 @@ #include <vector> #include "base/optional.h" -#include "content/common/bluetooth/web_bluetooth_device_id.h" #include "content/common/content_export.h" +#include "third_party/blink/public/common/bluetooth/web_bluetooth_device_id.h" #include "third_party/blink/public/mojom/bluetooth/web_bluetooth.mojom.h" namespace device { @@ -36,13 +36,14 @@ // Adds the Bluetooth Device with |device_address| to the map of allowed // devices. Generates and returns a new random device ID so that devices // IDs can not be compared between sites. - const WebBluetoothDeviceId& AddDevice( + const blink::WebBluetoothDeviceId& AddDevice( const std::string& device_address, const blink::mojom::WebBluetoothRequestDeviceOptionsPtr& options); // Same as the above version of |AddDevice| but does not add any services to // the device id -> services map. - const WebBluetoothDeviceId& AddDevice(const std::string& device_address); + const blink::WebBluetoothDeviceId& AddDevice( + const std::string& device_address); // Removes the Bluetooth Device with |device_address| from the map of allowed // devices. @@ -50,42 +51,47 @@ // Returns the Bluetooth Device's id if it has been added previously with // |AddDevice|. - const WebBluetoothDeviceId* GetDeviceId(const std::string& device_address); + const blink::WebBluetoothDeviceId* GetDeviceId( + const std::string& device_address); // For |device_id|, returns the Bluetooth device's address. If there is no // such |device_id|, returns an empty string. - const std::string& GetDeviceAddress(const WebBluetoothDeviceId& device_id); + const std::string& GetDeviceAddress( + const blink::WebBluetoothDeviceId& device_id); // Returns true if access has previously been granted to at least one // service. bool IsAllowedToAccessAtLeastOneService( - const WebBluetoothDeviceId& device_id) const; + const blink::WebBluetoothDeviceId& device_id) const; // Returns true if access has previously been granted to the service. bool IsAllowedToAccessService( - const WebBluetoothDeviceId& device_id, + const blink::WebBluetoothDeviceId& device_id, const device::BluetoothUUID& service_uuid) const; - bool IsAllowedToGATTConnect(const WebBluetoothDeviceId& device_id) const; + bool IsAllowedToGATTConnect( + const blink::WebBluetoothDeviceId& device_id) const; private: - typedef std::unordered_map<std::string, WebBluetoothDeviceId> + typedef std::unordered_map<std::string, blink::WebBluetoothDeviceId> DeviceAddressToIdMap; - typedef std:: - unordered_map<WebBluetoothDeviceId, std::string, WebBluetoothDeviceIdHash> - DeviceIdToAddressMap; + typedef std::unordered_map<blink::WebBluetoothDeviceId, + std::string, + blink::WebBluetoothDeviceIdHash> + DeviceIdToAddressMap; typedef std::unordered_map< - WebBluetoothDeviceId, + blink::WebBluetoothDeviceId, std::unordered_set<device::BluetoothUUID, device::BluetoothUUIDHash>, - WebBluetoothDeviceIdHash> + blink::WebBluetoothDeviceIdHash> DeviceIdToServicesMap; - typedef std:: - unordered_map<WebBluetoothDeviceId, bool, WebBluetoothDeviceIdHash> - DeviceIdToConnectableMap; + typedef std::unordered_map<blink::WebBluetoothDeviceId, + bool, + blink::WebBluetoothDeviceIdHash> + DeviceIdToConnectableMap; // Returns an id guaranteed to be unique for the map. The id is randomly // generated so that an origin can't guess the id used in another origin. - WebBluetoothDeviceId GenerateUniqueDeviceId(); + blink::WebBluetoothDeviceId GenerateUniqueDeviceId(); void AddUnionOfServicesTo( const blink::mojom::WebBluetoothRequestDeviceOptionsPtr& options, std::unordered_set<device::BluetoothUUID, device::BluetoothUUIDHash>* @@ -97,7 +103,8 @@ DeviceIdToConnectableMap device_id_to_connectable_map_; // Keep track of all device_ids in the map. - std::unordered_set<WebBluetoothDeviceId, WebBluetoothDeviceIdHash> + std::unordered_set<blink::WebBluetoothDeviceId, + blink::WebBluetoothDeviceIdHash> device_id_set_; };
diff --git a/content/browser/bluetooth/bluetooth_allowed_devices_unittest.cc b/content/browser/bluetooth/bluetooth_allowed_devices_unittest.cc index ef4f7de..525356c 100644 --- a/content/browser/bluetooth/bluetooth_allowed_devices_unittest.cc +++ b/content/browser/bluetooth/bluetooth_allowed_devices_unittest.cc
@@ -6,8 +6,8 @@ #include "base/strings/string_util.h" #include "content/browser/bluetooth/bluetooth_allowed_devices_map.h" -#include "content/common/bluetooth/web_bluetooth_device_id.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/bluetooth/web_bluetooth_device_id.h" #include "url/gurl.h" using device::BluetoothUUID; @@ -58,7 +58,7 @@ TEST_F(BluetoothAllowedDevicesTest, AddDevice) { BluetoothAllowedDevices allowed_devices; - const WebBluetoothDeviceId& device_id = + const blink::WebBluetoothDeviceId& device_id = allowed_devices.AddDevice(kDeviceAddress1, empty_options_); // Test that we can retrieve the device address/id. @@ -68,9 +68,9 @@ TEST_F(BluetoothAllowedDevicesTest, AddDeviceTwice) { BluetoothAllowedDevices allowed_devices; - const WebBluetoothDeviceId& device_id1 = + const blink::WebBluetoothDeviceId& device_id1 = allowed_devices.AddDevice(kDeviceAddress1, empty_options_); - const WebBluetoothDeviceId& device_id2 = + const blink::WebBluetoothDeviceId& device_id2 = allowed_devices.AddDevice(kDeviceAddress1, empty_options_); EXPECT_EQ(device_id1, device_id2); @@ -82,9 +82,9 @@ TEST_F(BluetoothAllowedDevicesTest, AddTwoDevices) { BluetoothAllowedDevices allowed_devices; - const WebBluetoothDeviceId& device_id1 = + const blink::WebBluetoothDeviceId& device_id1 = allowed_devices.AddDevice(kDeviceAddress1, empty_options_); - const WebBluetoothDeviceId& device_id2 = + const blink::WebBluetoothDeviceId& device_id2 = allowed_devices.AddDevice(kDeviceAddress2, empty_options_); EXPECT_NE(device_id1, device_id2); @@ -105,9 +105,9 @@ content::BluetoothAllowedDevices& allowed_devices2 = allowed_devices_map->GetOrCreateAllowedDevices(kTestOrigin2); - const WebBluetoothDeviceId& device_id1 = + const blink::WebBluetoothDeviceId& device_id1 = allowed_devices1.AddDevice(kDeviceAddress1, empty_options_); - const WebBluetoothDeviceId& device_id2 = + const blink::WebBluetoothDeviceId& device_id2 = allowed_devices2.AddDevice(kDeviceAddress2, empty_options_); EXPECT_NE(device_id1, device_id2); @@ -135,9 +135,9 @@ content::BluetoothAllowedDevices& allowed_devices2 = allowed_devices_map->GetOrCreateAllowedDevices(kTestOrigin2); - const WebBluetoothDeviceId& device_id1 = + const blink::WebBluetoothDeviceId& device_id1 = allowed_devices1.AddDevice(kDeviceAddress1, empty_options_); - const WebBluetoothDeviceId& device_id2 = + const blink::WebBluetoothDeviceId& device_id2 = allowed_devices2.AddDevice(kDeviceAddress1, empty_options_); EXPECT_NE(device_id1, device_id2); @@ -149,12 +149,12 @@ TEST_F(BluetoothAllowedDevicesTest, AddRemoveAddDevice) { BluetoothAllowedDevices allowed_devices; - const WebBluetoothDeviceId device_id_first_time = + const blink::WebBluetoothDeviceId device_id_first_time = allowed_devices.AddDevice(kDeviceAddress1, empty_options_); allowed_devices.RemoveDevice(kDeviceAddress1); - const WebBluetoothDeviceId device_id_second_time = + const blink::WebBluetoothDeviceId device_id_second_time = allowed_devices.AddDevice(kDeviceAddress1, empty_options_); EXPECT_NE(device_id_first_time, device_id_second_time); @@ -163,7 +163,7 @@ TEST_F(BluetoothAllowedDevicesTest, RemoveDevice) { BluetoothAllowedDevices allowed_devices; - const WebBluetoothDeviceId device_id = + const blink::WebBluetoothDeviceId device_id = allowed_devices.AddDevice(kDeviceAddress1, empty_options_); allowed_devices.RemoveDevice(kDeviceAddress1); @@ -186,7 +186,7 @@ options->filters->push_back({scan_filter.Clone()}); // Add to map. - const WebBluetoothDeviceId device_id = + const blink::WebBluetoothDeviceId device_id = allowed_devices.AddDevice(kDeviceAddress1, options); // Try to access at least one service. @@ -219,7 +219,7 @@ options->optional_services.push_back(kHeartRateUUID); // Add to map. - const WebBluetoothDeviceId device_id1 = + const blink::WebBluetoothDeviceId device_id1 = allowed_devices.AddDevice(kDeviceAddress1, options); // Access allowed services. @@ -254,7 +254,7 @@ options2->filters->push_back(scan_filter1.Clone()); options2->filters->push_back(scan_filter2.Clone()); - const WebBluetoothDeviceId device_id2 = + const blink::WebBluetoothDeviceId device_id2 = allowed_devices.AddDevice(kDeviceAddress1, options2); // Access allowed services. @@ -307,9 +307,9 @@ options2->optional_services.push_back(kBloodPressureUUID); // Add devices to map. - const WebBluetoothDeviceId& device_id1 = + const blink::WebBluetoothDeviceId& device_id1 = allowed_devices.AddDevice(kDeviceAddress1, options1); - const WebBluetoothDeviceId& device_id2 = + const blink::WebBluetoothDeviceId& device_id2 = allowed_devices.AddDevice(kDeviceAddress2, options2); // Access allowed services. @@ -375,9 +375,9 @@ options2->optional_services.push_back(kBloodPressureUUID); // Add devices to map. - const WebBluetoothDeviceId& device_id1 = + const blink::WebBluetoothDeviceId& device_id1 = allowed_devices1.AddDevice(kDeviceAddress1, options1); - const WebBluetoothDeviceId& device_id2 = + const blink::WebBluetoothDeviceId& device_id2 = allowed_devices2.AddDevice(kDeviceAddress1, options2); // Access allowed services. @@ -442,7 +442,7 @@ options1->optional_services.push_back(kBatteryServiceUUID); // Add to map. - const WebBluetoothDeviceId device_id1 = + const blink::WebBluetoothDeviceId device_id1 = allowed_devices.AddDevice(kDeviceAddress1, options1); // Setup second request. @@ -459,7 +459,7 @@ options2->optional_services.push_back(kBloodPressureUUID); // Add to map again. - const WebBluetoothDeviceId device_id2 = + const blink::WebBluetoothDeviceId device_id2 = allowed_devices.AddDevice(kDeviceAddress1, options2); EXPECT_EQ(device_id1, device_id2); @@ -478,10 +478,10 @@ TEST_F(BluetoothAllowedDevicesTest, CorrectIdFormat) { BluetoothAllowedDevices allowed_devices; - const WebBluetoothDeviceId& device_id = + const blink::WebBluetoothDeviceId& device_id = allowed_devices.AddDevice(kDeviceAddress1, empty_options_); - EXPECT_TRUE(WebBluetoothDeviceId::IsValid(device_id.str())); + EXPECT_TRUE(blink::WebBluetoothDeviceId::IsValid(device_id.str())); } TEST_F(BluetoothAllowedDevicesTest, NoFilterServices) { @@ -497,7 +497,7 @@ options->filters->push_back(std::move(scan_filter)); // Add to map. - const WebBluetoothDeviceId device_id = + const blink::WebBluetoothDeviceId device_id = allowed_devices.AddDevice(kDeviceAddress1, options); EXPECT_FALSE(allowed_devices.IsAllowedToAccessAtLeastOneService(device_id));
diff --git a/content/browser/bluetooth/bluetooth_metrics.h b/content/browser/bluetooth/bluetooth_metrics.h index 68ec45c4..d9435fc6 100644 --- a/content/browser/bluetooth/bluetooth_metrics.h +++ b/content/browser/bluetooth/bluetooth_metrics.h
@@ -8,6 +8,7 @@ #include <string> #include <vector> +#include "content/common/content_export.h" #include "third_party/blink/public/mojom/bluetooth/web_bluetooth.mojom.h" namespace base {
diff --git a/content/browser/bluetooth/bluetooth_util.h b/content/browser/bluetooth/bluetooth_util.h index 131d50c..50154ebf 100644 --- a/content/browser/bluetooth/bluetooth_util.h +++ b/content/browser/bluetooth/bluetooth_util.h
@@ -5,6 +5,7 @@ #ifndef CONTENT_BROWSER_BLUETOOTH_BLUETOOTH_UTIL_H_ #define CONTENT_BROWSER_BLUETOOTH_BLUETOOTH_UTIL_H_ +#include "content/common/content_export.h" #include "third_party/blink/public/mojom/bluetooth/web_bluetooth.mojom.h" namespace content {
diff --git a/content/browser/bluetooth/frame_connected_bluetooth_devices.cc b/content/browser/bluetooth/frame_connected_bluetooth_devices.cc index 1b4b070..b53f58e9 100644 --- a/content/browser/bluetooth/frame_connected_bluetooth_devices.cc +++ b/content/browser/bluetooth/frame_connected_bluetooth_devices.cc
@@ -35,7 +35,7 @@ } bool FrameConnectedBluetoothDevices::IsConnectedToDeviceWithId( - const WebBluetoothDeviceId& device_id) { + const blink::WebBluetoothDeviceId& device_id) { auto connection_iter = device_id_to_connection_map_.find(device_id); if (connection_iter == device_id_to_connection_map_.end()) { return false; @@ -45,7 +45,7 @@ } void FrameConnectedBluetoothDevices::Insert( - const WebBluetoothDeviceId& device_id, + const blink::WebBluetoothDeviceId& device_id, std::unique_ptr<device::BluetoothGattConnection> connection, blink::mojom::WebBluetoothServerClientAssociatedPtr client) { if (device_id_to_connection_map_.find(device_id) != @@ -71,7 +71,7 @@ } void FrameConnectedBluetoothDevices::CloseConnectionToDeviceWithId( - const WebBluetoothDeviceId& device_id) { + const blink::WebBluetoothDeviceId& device_id) { auto connection_iter = device_id_to_connection_map_.find(device_id); if (connection_iter == device_id_to_connection_map_.end()) { return; @@ -82,14 +82,14 @@ DecrementDevicesConnectedCount(); } -base::Optional<WebBluetoothDeviceId> +base::Optional<blink::WebBluetoothDeviceId> FrameConnectedBluetoothDevices::CloseConnectionToDeviceWithAddress( const std::string& device_address) { auto device_address_iter = device_address_to_id_map_.find(device_address); if (device_address_iter == device_address_to_id_map_.end()) { return base::nullopt; } - WebBluetoothDeviceId device_id = device_address_iter->second; + blink::WebBluetoothDeviceId device_id = device_address_iter->second; auto device_id_iter = device_id_to_connection_map_.find(device_id); CHECK(device_id_iter != device_id_to_connection_map_.end()); device_id_iter->second->server_client->GATTServerDisconnected();
diff --git a/content/browser/bluetooth/frame_connected_bluetooth_devices.h b/content/browser/bluetooth/frame_connected_bluetooth_devices.h index 8020682..2da3e3ca 100644 --- a/content/browser/bluetooth/frame_connected_bluetooth_devices.h +++ b/content/browser/bluetooth/frame_connected_bluetooth_devices.h
@@ -10,8 +10,8 @@ #include <unordered_map> #include "base/optional.h" -#include "content/common/bluetooth/web_bluetooth_device_id.h" #include "content/common/content_export.h" +#include "third_party/blink/public/common/bluetooth/web_bluetooth_device_id.h" #include "third_party/blink/public/mojom/bluetooth/web_bluetooth.mojom.h" #include "url/origin.h" @@ -39,24 +39,25 @@ ~FrameConnectedBluetoothDevices(); // Returns true if the map holds a connection to |device_id|. - bool IsConnectedToDeviceWithId(const WebBluetoothDeviceId& device_id); + bool IsConnectedToDeviceWithId(const blink::WebBluetoothDeviceId& device_id); // If a connection doesn't exist already for |device_id|, adds a connection to // the map and increases the WebContents count of connected devices. - void Insert(const WebBluetoothDeviceId& device_id, + void Insert(const blink::WebBluetoothDeviceId& device_id, std::unique_ptr<device::BluetoothGattConnection> connection, blink::mojom::WebBluetoothServerClientAssociatedPtr client); // Deletes the BluetoothGattConnection for |device_id| and decrements the // WebContents count of connected devices if |device_id| had a connection. - void CloseConnectionToDeviceWithId(const WebBluetoothDeviceId& device_id); + void CloseConnectionToDeviceWithId( + const blink::WebBluetoothDeviceId& device_id); // Deletes the BluetoothGattConnection for |device_address| and decrements the // WebContents count of connected devices if |device_address| had a // connection. Returns the device_id of the device associated with the // connection. - base::Optional<WebBluetoothDeviceId> CloseConnectionToDeviceWithAddress( - const std::string& device_address); + base::Optional<blink::WebBluetoothDeviceId> + CloseConnectionToDeviceWithAddress(const std::string& device_address); private: // Increments the Connected Devices count of the frame's WebContents. @@ -69,13 +70,13 @@ // Keeps the BluetoothGattConnection objects alive so that connections don't // get closed. - std::unordered_map<WebBluetoothDeviceId, + std::unordered_map<blink::WebBluetoothDeviceId, std::unique_ptr<GATTConnectionAndServerClient>, - WebBluetoothDeviceIdHash> + blink::WebBluetoothDeviceIdHash> device_id_to_connection_map_; // Keeps track of which device addresses correspond to which ids. - std::unordered_map<std::string, WebBluetoothDeviceId> + std::unordered_map<std::string, blink::WebBluetoothDeviceId> device_address_to_id_map_; DISALLOW_COPY_AND_ASSIGN(FrameConnectedBluetoothDevices);
diff --git a/content/browser/bluetooth/frame_connected_bluetooth_devices_unittest.cc b/content/browser/bluetooth/frame_connected_bluetooth_devices_unittest.cc index 22f2e06d..6d89ce4b 100644 --- a/content/browser/bluetooth/frame_connected_bluetooth_devices_unittest.cc +++ b/content/browser/bluetooth/frame_connected_bluetooth_devices_unittest.cc
@@ -30,11 +30,11 @@ namespace { -const WebBluetoothDeviceId kDeviceId0("000000000000000000000A=="); +const blink::WebBluetoothDeviceId kDeviceId0("000000000000000000000A=="); constexpr char kDeviceAddress0[] = "0"; constexpr char kDeviceName0[] = "Device0"; -const WebBluetoothDeviceId kDeviceId1("111111111111111111111A=="); +const blink::WebBluetoothDeviceId kDeviceId1("111111111111111111111A=="); constexpr char kDeviceAddress1[] = "1"; constexpr char kDeviceName1[] = "Device1";
diff --git a/content/browser/bluetooth/web_bluetooth_service_impl.cc b/content/browser/bluetooth/web_bluetooth_service_impl.cc index 3546035..41d2063 100644 --- a/content/browser/bluetooth/web_bluetooth_service_impl.cc +++ b/content/browser/bluetooth/web_bluetooth_service_impl.cc
@@ -26,7 +26,6 @@ #include "content/browser/permissions/permission_controller_impl.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/storage_partition_impl.h" -#include "content/common/bluetooth/web_bluetooth_device_id.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h" @@ -37,6 +36,7 @@ #include "device/bluetooth/bluetooth_adapter_factory_wrapper.h" #include "device/bluetooth/bluetooth_remote_gatt_characteristic.h" #include "device/bluetooth/bluetooth_remote_gatt_descriptor.h" +#include "third_party/blink/public/common/bluetooth/web_bluetooth_device_id.h" using device::BluetoothAdapterFactoryWrapper; using device::BluetoothUUID; @@ -437,7 +437,7 @@ } if (!device->IsGattConnected()) { - base::Optional<WebBluetoothDeviceId> device_id = + base::Optional<blink::WebBluetoothDeviceId> device_id = connected_devices_->CloseConnectionToDeviceWithAddress( device->GetAddress()); @@ -590,7 +590,7 @@ } void WebBluetoothServiceImpl::RemoteServerConnect( - const WebBluetoothDeviceId& device_id, + const blink::WebBluetoothDeviceId& device_id, blink::mojom::WebBluetoothServerClientAssociatedPtrInfo client, RemoteServerConnectCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -642,7 +642,7 @@ } void WebBluetoothServiceImpl::RemoteServerDisconnect( - const WebBluetoothDeviceId& device_id) { + const blink::WebBluetoothDeviceId& device_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (connected_devices_->IsConnectedToDeviceWithId(device_id)) { @@ -652,7 +652,7 @@ } void WebBluetoothServiceImpl::RemoteServerGetPrimaryServices( - const WebBluetoothDeviceId& device_id, + const blink::WebBluetoothDeviceId& device_id, blink::mojom::WebBluetoothGATTQueryQuantity quantity, const base::Optional<BluetoothUUID>& services_uuid, RemoteServerGetPrimaryServicesCallback callback) { @@ -1291,7 +1291,7 @@ } void WebBluetoothServiceImpl::RemoteServerGetPrimaryServicesImpl( - const WebBluetoothDeviceId& device_id, + const blink::WebBluetoothDeviceId& device_id, blink::mojom::WebBluetoothGATTQueryQuantity quantity, const base::Optional<BluetoothUUID>& services_uuid, RemoteServerGetPrimaryServicesCallback callback, @@ -1376,7 +1376,7 @@ return; } - const WebBluetoothDeviceId device_id = + const blink::WebBluetoothDeviceId device_id = allowed_devices().AddDevice(device_address, options); DVLOG(1) << "Device: " << device->GetNameForDisplay(); @@ -1399,7 +1399,7 @@ } void WebBluetoothServiceImpl::OnCreateGATTConnectionSuccess( - const WebBluetoothDeviceId& device_id, + const blink::WebBluetoothDeviceId& device_id, base::TimeTicks start_time, blink::mojom::WebBluetoothServerClientAssociatedPtr client, RemoteServerConnectCallback callback, @@ -1529,7 +1529,7 @@ } CacheQueryResult WebBluetoothServiceImpl::QueryCacheForDevice( - const WebBluetoothDeviceId& device_id) { + const blink::WebBluetoothDeviceId& device_id) { const std::string& device_address = allowed_devices().GetDeviceAddress(device_id); if (device_address.empty()) { @@ -1559,7 +1559,7 @@ return CacheQueryResult(CacheQueryOutcome::BAD_RENDERER); } - const WebBluetoothDeviceId* device_id = + const blink::WebBluetoothDeviceId* device_id = allowed_devices().GetDeviceId(device_iter->second); // Kill the renderer if origin is not allowed to access the device. if (device_id == nullptr) {
diff --git a/content/browser/bluetooth/web_bluetooth_service_impl.h b/content/browser/bluetooth/web_bluetooth_service_impl.h index 70033cee..890b0cc 100644 --- a/content/browser/bluetooth/web_bluetooth_service_impl.h +++ b/content/browser/bluetooth/web_bluetooth_service_impl.h
@@ -170,12 +170,13 @@ void RequestDevice(blink::mojom::WebBluetoothRequestDeviceOptionsPtr options, RequestDeviceCallback callback) override; void RemoteServerConnect( - const WebBluetoothDeviceId& device_id, + const blink::WebBluetoothDeviceId& device_id, blink::mojom::WebBluetoothServerClientAssociatedPtrInfo client, RemoteServerConnectCallback callback) override; - void RemoteServerDisconnect(const WebBluetoothDeviceId& device_id) override; + void RemoteServerDisconnect( + const blink::WebBluetoothDeviceId& device_id) override; void RemoteServerGetPrimaryServices( - const WebBluetoothDeviceId& device_id, + const blink::WebBluetoothDeviceId& device_id, blink::mojom::WebBluetoothGATTQueryQuantity quantity, const base::Optional<device::BluetoothUUID>& services_uuid, RemoteServerGetPrimaryServicesCallback callback) override; @@ -236,7 +237,7 @@ // Should only be run after the services have been discovered for // |device_address|. void RemoteServerGetPrimaryServicesImpl( - const WebBluetoothDeviceId& device_id, + const blink::WebBluetoothDeviceId& device_id, blink::mojom::WebBluetoothGATTQueryQuantity quantity, const base::Optional<device::BluetoothUUID>& services_uuid, RemoteServerGetPrimaryServicesCallback callback, @@ -252,7 +253,7 @@ // Callbacks for BluetoothDevice::CreateGattConnection. void OnCreateGATTConnectionSuccess( - const WebBluetoothDeviceId& device_id, + const blink::WebBluetoothDeviceId& device_id, base::TimeTicks start_time, blink::mojom::WebBluetoothServerClientAssociatedPtr client, RemoteServerConnectCallback callback, @@ -315,7 +316,8 @@ // Queries the platform cache for a Device with |device_id| for |origin|. // Fills in the |outcome| field and the |device| field if successful. - CacheQueryResult QueryCacheForDevice(const WebBluetoothDeviceId& device_id); + CacheQueryResult QueryCacheForDevice( + const blink::WebBluetoothDeviceId& device_id); // Queries the platform cache for a Service with |service_instance_id|. Fills // in the |outcome| field, and |device| and |service| fields if successful.
diff --git a/content/browser/devtools/devtools_instrumentation.cc b/content/browser/devtools/devtools_instrumentation.cc index fd4f77b..11de8de 100644 --- a/content/browser/devtools/devtools_instrumentation.cc +++ b/content/browser/devtools/devtools_instrumentation.cc
@@ -253,7 +253,7 @@ // Within the target, the agents added earlier are closer to network. DevToolsAgentHostImpl* frame_agent_host = - RenderFrameDevToolsAgentHost::GetFor(rfh->frame_tree_node()); + RenderFrameDevToolsAgentHost::GetFor(rfh); RenderProcessHost* rph = rfh->GetProcess(); const base::UnguessableToken& frame_token = rfh->GetDevToolsFrameToken();
diff --git a/content/browser/devtools/render_frame_devtools_agent_host.cc b/content/browser/devtools/render_frame_devtools_agent_host.cc index 2166aad..1a385b5d 100644 --- a/content/browser/devtools/render_frame_devtools_agent_host.cc +++ b/content/browser/devtools/render_frame_devtools_agent_host.cc
@@ -120,6 +120,14 @@ return FindAgentHost(frame_tree_node); } +// static +DevToolsAgentHostImpl* RenderFrameDevToolsAgentHost::GetFor( + RenderFrameHostImpl* rfh) { + return ShouldCreateDevToolsForHost(rfh) + ? FindAgentHost(rfh->frame_tree_node()) + : GetFor(rfh->frame_tree_node()); +} + scoped_refptr<DevToolsAgentHost> RenderFrameDevToolsAgentHost::GetOrCreateFor( FrameTreeNode* frame_tree_node) { frame_tree_node = GetFrameTreeNodeAncestor(frame_tree_node);
diff --git a/content/browser/devtools/render_frame_devtools_agent_host.h b/content/browser/devtools/render_frame_devtools_agent_host.h index 3f78049..000892d 100644 --- a/content/browser/devtools/render_frame_devtools_agent_host.h +++ b/content/browser/devtools/render_frame_devtools_agent_host.h
@@ -45,6 +45,12 @@ // Returns appropriate agent host for given frame tree node, traversing // up to local root as needed. static DevToolsAgentHostImpl* GetFor(FrameTreeNode* frame_tree_node); + // Returns appropriate agent host for given render frame host, traversing + // up to local root as needed. This will have an effect different from + // calling the above overload as GetFor(rfh->frame_tree_node()) when + // given RFH is a pending local root. + static DevToolsAgentHostImpl* GetFor(RenderFrameHostImpl* rfh); + // Similar to GetFor(), but creates a host if it doesn't exist yet. static scoped_refptr<DevToolsAgentHost> GetOrCreateFor( FrameTreeNode* frame_tree_node);
diff --git a/content/browser/dom_storage/dom_storage_browsertest.cc b/content/browser/dom_storage/dom_storage_browsertest.cc index a7b066a1c..6d1d861b 100644 --- a/content/browser/dom_storage/dom_storage_browsertest.cc +++ b/content/browser/dom_storage/dom_storage_browsertest.cc
@@ -38,9 +38,6 @@ namespace content { -constexpr const char kTestSessionStorageId[] = - "574d2d70-24ca-4d8c-ae23-c7e1e39d07be"; - // This browser test is aimed towards exercising the DOMStorage system // from end-to-end. class DOMStorageBrowserTest : public ContentBrowserTest { @@ -221,79 +218,4 @@ } } -class DOMStorageMigrationBrowserTest : public DOMStorageBrowserTest { - public: - DOMStorageMigrationBrowserTest() : DOMStorageBrowserTest() { - if (IsPreTest()) - feature_list_.InitAndDisableFeature( - blink::features::kOnionSoupDOMStorage); - else - feature_list_.InitAndEnableFeature(blink::features::kOnionSoupDOMStorage); - } - - void SessionStorageTest(const GURL& test_url) { - // The test page will perform tests then navigate to either - // a #pass or #fail ref. - context_wrapper()->SetSaveSessionStorageOnDisk(); - scoped_refptr<SessionStorageNamespaceImpl> ss_namespace = - SessionStorageNamespaceImpl::Create(context_wrapper(), - kTestSessionStorageId); - ss_namespace->SetShouldPersist(true); - Shell* the_browser = Shell::CreateNewWindowWithSessionStorageNamespace( - ShellContentBrowserClient::Get()->browser_context(), - GURL(url::kAboutBlankURL), nullptr, gfx::Size(), - std::move(ss_namespace)); - NavigateToURLBlockUntilNavigationsComplete(the_browser, test_url, 2); - context_wrapper()->Flush(); - std::string result = - the_browser->web_contents()->GetLastCommittedURL().ref(); - if (result != "pass") { - std::string js_result; - ASSERT_TRUE(ExecuteScriptAndExtractString( - the_browser, "window.domAutomationController.send(getLog())", - &js_result)); - FAIL() << "Failed: " << js_result; - } - } - - private: - base::test::ScopedFeatureList feature_list_; -}; - -IN_PROC_BROWSER_TEST_F(DOMStorageMigrationBrowserTest, PRE_DataMigrates) { - SessionStorageTest( - GetTestUrl("dom_storage", "store_session_storage_data.html")); -} - -// http://crbug.com/654704 PRE_ tests aren't supported on Android. -#if defined(OS_ANDROID) -#define MAYBE_DataMigrates DISABLED_DataMigrates -#else -#define MAYBE_DataMigrates DataMigrates -#endif -IN_PROC_BROWSER_TEST_F(DOMStorageMigrationBrowserTest, MAYBE_DataMigrates) { - EXPECT_TRUE(session_storage_context()); - EnsureSessionStorageConnected(); - SessionStorageTest( - GetTestUrl("dom_storage", "verify_session_storage_data.html")); - - // Check that we migrated from v0 (no version) to v1. - base::RunLoop loop; - leveldb::mojom::LevelDBDatabase* database = - session_storage_context()->DatabaseForTesting(); - mojo_task_runner()->PostTask( - FROM_HERE, base::BindLambdaForTesting([&]() { - database->Get( - leveldb::StringPieceToUint8Vector("version"), - base::BindLambdaForTesting([&](leveldb::mojom::DatabaseError error, - const std::vector<uint8_t>& value) { - EXPECT_EQ(leveldb::mojom::DatabaseError::OK, error); - EXPECT_EQ(base::StringPiece("1"), - leveldb::Uint8VectorToStringPiece(value)); - loop.Quit(); - })); - })); - loop.Run(); -} - } // namespace content
diff --git a/content/browser/dom_storage/dom_storage_message_filter.cc b/content/browser/dom_storage/dom_storage_message_filter.cc deleted file mode 100644 index 33c9163..0000000 --- a/content/browser/dom_storage/dom_storage_message_filter.cc +++ /dev/null
@@ -1,209 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/dom_storage/dom_storage_message_filter.h" - -#include "base/auto_reset.h" -#include "base/bind.h" -#include "base/strings/nullable_string16.h" -#include "base/strings/utf_string_conversions.h" -#include "content/browser/bad_message.h" -#include "content/browser/dom_storage/dom_storage_area.h" -#include "content/browser/dom_storage/dom_storage_context_wrapper.h" -#include "content/browser/dom_storage/dom_storage_host.h" -#include "content/browser/dom_storage/dom_storage_namespace.h" -#include "content/browser/dom_storage/dom_storage_task_runner.h" -#include "content/common/dom_storage/dom_storage_messages.h" -#include "content/public/browser/browser_thread.h" -#include "url/gurl.h" - -namespace content { - -DOMStorageMessageFilter::DOMStorageMessageFilter( - DOMStorageContextWrapper* context) - : BrowserMessageFilter(DOMStorageMsgStart), - context_(context->context()), - connection_dispatching_message_for_(0) { -} - -DOMStorageMessageFilter::~DOMStorageMessageFilter() { - DCHECK(!host_.get()); -} - -void DOMStorageMessageFilter::InitializeInSequence() { - DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO)); - host_.reset(new DOMStorageHost(context_.get())); - context_->AddEventObserver(this); -} - -void DOMStorageMessageFilter::UninitializeInSequence() { - // TODO(michaeln): Restore this DCHECK once crbug/166470 and crbug/164403 - // are resolved. - // DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO)); - context_->RemoveEventObserver(this); - host_.reset(); -} - -void DOMStorageMessageFilter::OnFilterAdded(IPC::Channel* channel) { - context_->task_runner()->PostShutdownBlockingTask( - FROM_HERE, DOMStorageTaskRunner::PRIMARY_SEQUENCE, - base::BindOnce(&DOMStorageMessageFilter::InitializeInSequence, this)); -} - -void DOMStorageMessageFilter::OnFilterRemoved() { - context_->task_runner()->PostShutdownBlockingTask( - FROM_HERE, DOMStorageTaskRunner::PRIMARY_SEQUENCE, - base::BindOnce(&DOMStorageMessageFilter::UninitializeInSequence, this)); -} - -base::TaskRunner* DOMStorageMessageFilter::OverrideTaskRunnerForMessage( - const IPC::Message& message) { - if (IPC_MESSAGE_CLASS(message) == DOMStorageMsgStart) - return context_->task_runner(); - return nullptr; -} - -bool DOMStorageMessageFilter::OnMessageReceived(const IPC::Message& message) { - if (IPC_MESSAGE_CLASS(message) != DOMStorageMsgStart) - return false; - DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO)); - DCHECK(host_.get()); - - bool handled = true; - IPC_BEGIN_MESSAGE_MAP(DOMStorageMessageFilter, message) - IPC_MESSAGE_HANDLER(DOMStorageHostMsg_OpenStorageArea, OnOpenStorageArea) - IPC_MESSAGE_HANDLER(DOMStorageHostMsg_CloseStorageArea, OnCloseStorageArea) - IPC_MESSAGE_HANDLER(DOMStorageHostMsg_LoadStorageArea, OnLoadStorageArea) - IPC_MESSAGE_HANDLER(DOMStorageHostMsg_SetItem, OnSetItem) - IPC_MESSAGE_HANDLER(DOMStorageHostMsg_RemoveItem, OnRemoveItem) - IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Clear, OnClear) - IPC_MESSAGE_HANDLER(DOMStorageHostMsg_FlushMessages, OnFlushMessages) - IPC_MESSAGE_UNHANDLED(handled = false) - IPC_END_MESSAGE_MAP() - return handled; -} - -void DOMStorageMessageFilter::OnOpenStorageArea(int connection_id, - const std::string& namespace_id, - const GURL& origin) { - DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO)); - base::Optional<bad_message::BadMessageReason> error = host_->OpenStorageArea( - connection_id, namespace_id, url::Origin::Create(origin)); - if (error) - bad_message::ReceivedBadMessage(this, error.value()); -} - -void DOMStorageMessageFilter::OnCloseStorageArea(int connection_id) { - DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO)); - host_->CloseStorageArea(connection_id); -} - -void DOMStorageMessageFilter::OnLoadStorageArea(int connection_id, - DOMStorageValuesMap* map) { - DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO)); - if (!host_->ExtractAreaValues(connection_id, map)) { - bad_message::ReceivedBadMessage(this, bad_message::DSMF_LOAD_STORAGE); - return; - } - Send(new DOMStorageMsg_AsyncOperationComplete(true)); -} - -void DOMStorageMessageFilter::OnSetItem( - int connection_id, - const base::string16& key, - const base::string16& value, - const base::NullableString16& client_old_value, - const GURL& page_url) { - DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO)); - DCHECK_EQ(0, connection_dispatching_message_for_); - base::AutoReset<int> auto_reset(&connection_dispatching_message_for_, - connection_id); - bool success = - host_->SetAreaItem(connection_id, key, value, client_old_value, page_url); - Send(new DOMStorageMsg_AsyncOperationComplete(success)); -} - -void DOMStorageMessageFilter::OnRemoveItem( - int connection_id, - const base::string16& key, - const base::NullableString16& client_old_value, - const GURL& page_url) { - DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO)); - DCHECK_EQ(0, connection_dispatching_message_for_); - base::AutoReset<int> auto_reset(&connection_dispatching_message_for_, - connection_id); - host_->RemoveAreaItem(connection_id, key, client_old_value, page_url); - Send(new DOMStorageMsg_AsyncOperationComplete(true)); -} - -void DOMStorageMessageFilter::OnClear( - int connection_id, const GURL& page_url) { - DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO)); - DCHECK_EQ(0, connection_dispatching_message_for_); - base::AutoReset<int> auto_reset(&connection_dispatching_message_for_, - connection_id); - host_->ClearArea(connection_id, page_url); - Send(new DOMStorageMsg_AsyncOperationComplete(true)); -} - -void DOMStorageMessageFilter::OnFlushMessages() { - // Intentionally empty method body. -} - -void DOMStorageMessageFilter::OnDOMStorageItemSet( - const DOMStorageArea* area, - const base::string16& key, - const base::string16& new_value, - const base::NullableString16& old_value, - const GURL& page_url) { - SendDOMStorageEvent(area, page_url, - base::NullableString16(key, false), - base::NullableString16(new_value, false), - old_value); -} - -void DOMStorageMessageFilter::OnDOMStorageItemRemoved( - const DOMStorageArea* area, - const base::string16& key, - const base::string16& old_value, - const GURL& page_url) { - SendDOMStorageEvent(area, page_url, - base::NullableString16(key, false), - base::NullableString16(), - base::NullableString16(old_value, false)); -} - -void DOMStorageMessageFilter::OnDOMStorageAreaCleared( - const DOMStorageArea* area, - const GURL& page_url) { - SendDOMStorageEvent(area, page_url, - base::NullableString16(), - base::NullableString16(), - base::NullableString16()); -} - -void DOMStorageMessageFilter::SendDOMStorageEvent( - const DOMStorageArea* area, - const GURL& page_url, - const base::NullableString16& key, - const base::NullableString16& new_value, - const base::NullableString16& old_value) { - DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO)); - // Only send mutation events to processes which have the area open. - bool originated_in_process = connection_dispatching_message_for_ != 0; - if (originated_in_process || - host_->HasAreaOpen(area->namespace_id(), area->origin())) { - DOMStorageMsg_Event_Params params; - params.origin = area->origin().GetURL(); - params.page_url = page_url; - params.connection_id = connection_dispatching_message_for_; - params.key = key; - params.new_value = new_value; - params.old_value = old_value; - params.namespace_id = area->namespace_id(); - Send(new DOMStorageMsg_Event(params)); - } -} - -} // namespace content
diff --git a/content/browser/dom_storage/dom_storage_message_filter.h b/content/browser/dom_storage/dom_storage_message_filter.h deleted file mode 100644 index 1c1aba32..0000000 --- a/content/browser/dom_storage/dom_storage_message_filter.h +++ /dev/null
@@ -1,100 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_BROWSER_DOM_STORAGE_DOM_STORAGE_MESSAGE_FILTER_H_ -#define CONTENT_BROWSER_DOM_STORAGE_DOM_STORAGE_MESSAGE_FILTER_H_ - -#include <stdint.h> - -#include <memory> - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "content/browser/dom_storage/dom_storage_context_impl.h" -#include "content/common/dom_storage/dom_storage_types.h" -#include "content/public/browser/browser_message_filter.h" - -class GURL; - -namespace base { -class NullableString16; -} - -namespace content { - -class DOMStorageArea; -class DOMStorageContextImpl; -class DOMStorageContextWrapper; -class DOMStorageHost; - -// This class handles the logistics of DOM Storage within the browser process. -// It mostly ferries information between IPCs and the dom_storage classes. -class DOMStorageMessageFilter - : public BrowserMessageFilter, - public DOMStorageContextImpl::EventObserver { - public: - explicit DOMStorageMessageFilter(DOMStorageContextWrapper* context); - - private: - ~DOMStorageMessageFilter() override; - - void InitializeInSequence(); - void UninitializeInSequence(); - - // BrowserMessageFilter implementation - void OnFilterAdded(IPC::Channel* channel) override; - void OnFilterRemoved() override; - base::TaskRunner* OverrideTaskRunnerForMessage( - const IPC::Message& message) override; - bool OnMessageReceived(const IPC::Message& message) override; - - // Message Handlers. - void OnOpenStorageArea(int connection_id, - const std::string& namespace_id, - const GURL& origin); - void OnCloseStorageArea(int connection_id); - void OnLoadStorageArea(int connection_id, DOMStorageValuesMap* map); - void OnSetItem(int connection_id, - const base::string16& key, - const base::string16& value, - const base::NullableString16& client_old_value, - const GURL& page_url); - void OnRemoveItem(int connection_id, - const base::string16& key, - const base::NullableString16& client_old_value, - const GURL& page_url); - void OnClear(int connection_id, const GURL& page_url); - void OnFlushMessages(); - - // DOMStorageContextImpl::EventObserver implementation which - // sends events back to our renderer process. - void OnDOMStorageItemSet(const DOMStorageArea* area, - const base::string16& key, - const base::string16& new_value, - const base::NullableString16& old_value, - const GURL& page_url) override; - void OnDOMStorageItemRemoved(const DOMStorageArea* area, - const base::string16& key, - const base::string16& old_value, - const GURL& page_url) override; - void OnDOMStorageAreaCleared(const DOMStorageArea* area, - const GURL& page_url) override; - - void SendDOMStorageEvent( - const DOMStorageArea* area, - const GURL& page_url, - const base::NullableString16& key, - const base::NullableString16& new_value, - const base::NullableString16& old_value); - - scoped_refptr<DOMStorageContextImpl> context_; - std::unique_ptr<DOMStorageHost> host_; - int connection_dispatching_message_for_; - - DISALLOW_IMPLICIT_CONSTRUCTORS(DOMStorageMessageFilter); -}; - -} // namespace content - -#endif // CONTENT_BROWSER_DOM_STORAGE_DOM_STORAGE_MESSAGE_FILTER_H_
diff --git a/content/browser/portal/portal.cc b/content/browser/portal/portal.cc index b45333f..85d8b67a 100644 --- a/content/browser/portal/portal.cc +++ b/content/browser/portal/portal.cc
@@ -18,6 +18,7 @@ #include "content/public/browser/navigation_controller.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/common/content_switches.h" +#include "content/public/common/referrer_type_converters.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "services/service_manager/public/mojom/interface_provider.mojom.h" #include "third_party/blink/public/common/features.h" @@ -162,7 +163,7 @@ return proxy_host; } -void Portal::Navigate(const GURL& url) { +void Portal::Navigate(const GURL& url, blink::mojom::ReferrerPtr referrer) { if (!url.SchemeIsHTTPOrHTTPS()) { mojo::ReportBadMessage("Portal::Navigate tried to use non-HTTP protocol."); binding_->Close(); // Also deletes |this|. @@ -173,6 +174,7 @@ // navigating portals. See http://crbug.com/964395. NavigationController::LoadURLParams load_url_params(url); + load_url_params.referrer = mojo::ConvertTo<Referrer>(referrer); portal_contents_impl_->GetController().LoadURLWithParams(load_url_params); }
diff --git a/content/browser/portal/portal.h b/content/browser/portal/portal.h index 07e4b43..ed47e4ac 100644 --- a/content/browser/portal/portal.h +++ b/content/browser/portal/portal.h
@@ -60,7 +60,7 @@ RenderFrameProxyHost* CreateProxyAndAttachPortal(); // blink::mojom::Portal implementation. - void Navigate(const GURL& url) override; + void Navigate(const GURL& url, blink::mojom::ReferrerPtr referrer) override; void Activate(blink::TransferableMessage data, ActivateCallback callback) override; void PostMessageToGuest(
diff --git a/content/browser/portal/portal_browsertest.cc b/content/browser/portal/portal_browsertest.cc index 11ae0aa..12abd88 100644 --- a/content/browser/portal/portal_browsertest.cc +++ b/content/browser/portal/portal_browsertest.cc
@@ -60,13 +60,13 @@ portal_->Activate(std::move(data), std::move(callback)); } - void Navigate(const GURL& url) override { + void Navigate(const GURL& url, blink::mojom::ReferrerPtr referrer) override { if (navigate_callback_) { - navigate_callback_.Run(url); + navigate_callback_.Run(url, std::move(referrer)); return; } - portal_->Navigate(url); + portal_->Navigate(url, std::move(referrer)); } void WaitForActivate() { @@ -83,7 +83,8 @@ WebContents* GetPortalContents() { return portal_->GetPortalContents(); } // IPC callbacks - base::RepeatingCallback<void(const GURL&)> navigate_callback_; + base::RepeatingCallback<void(const GURL&, blink::mojom::ReferrerPtr)> + navigate_callback_; private: PortalInterceptorForTesting(RenderFrameHostImpl* render_frame_host_impl) @@ -520,9 +521,9 @@ // Try to navigate to chrome://settings and wait for the process to die. portal_interceptor->navigate_callback_ = base::BindRepeating( - [](Portal* portal, const GURL& url) { + [](Portal* portal, const GURL& url, blink::mojom::ReferrerPtr referrer) { GURL chrome_url("chrome://settings"); - portal->Navigate(chrome_url); + portal->Navigate(chrome_url, std::move(referrer)); }, portal); RenderProcessHostKillWaiter kill_waiter(
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index 1aa874a..7940d99 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -90,7 +90,6 @@ #include "content/browser/code_cache/generated_code_cache_context.h" #include "content/browser/compositor/surface_utils.h" #include "content/browser/dom_storage/dom_storage_context_wrapper.h" -#include "content/browser/dom_storage/dom_storage_message_filter.h" #include "content/browser/field_trial_recorder.h" #include "content/browser/fileapi/file_system_manager_impl.h" #include "content/browser/font_unique_name_lookup/font_unique_name_lookup_service.h" @@ -1899,9 +1898,6 @@ AddFilter(resource_message_filter_.get()); } - AddFilter(new DOMStorageMessageFilter( - storage_partition_impl_->GetDOMStorageContext())); - peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID()); AddFilter(peer_connection_tracker_host_.get()); #if BUILDFLAG(ENABLE_PLUGINS)
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 aeec980..8113209 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.h +++ b/content/browser/renderer_host/render_widget_host_view_mac.h
@@ -25,9 +25,9 @@ #include "ipc/ipc_sender.h" #include "mojo/public/cpp/bindings/associated_binding.h" #include "ui/accelerated_widget_mac/accelerated_widget_mac.h" -#include "ui/accelerated_widget_mac/display_link_mac.h" #include "ui/base/cocoa/accessibility_focus_overrider.h" #include "ui/base/cocoa/remote_layer_api.h" +#include "ui/display/mac/display_link_mac.h" #include "ui/events/gesture_detection/filtered_gesture_provider.h" namespace remote_cocoa {
diff --git a/content/common/BUILD.gn b/content/common/BUILD.gn index 5389629..a46d4f4 100644 --- a/content/common/BUILD.gn +++ b/content/common/BUILD.gn
@@ -53,8 +53,6 @@ "ax_content_node_data.h", "background_fetch/background_fetch_types.cc", "background_fetch/background_fetch_types.h", - "bluetooth/web_bluetooth_device_id.cc", - "bluetooth/web_bluetooth_device_id.h", "browser_plugin/browser_plugin_constants.cc", "browser_plugin/browser_plugin_constants.h", "browser_plugin/browser_plugin_messages.h", @@ -96,7 +94,6 @@ "cursors/webcursor_ozone.cc", "dom_storage/dom_storage_map.cc", "dom_storage/dom_storage_map.h", - "dom_storage/dom_storage_messages.h", "dom_storage/dom_storage_types.h", "drag_event_source_info.h", "drag_messages.h", @@ -522,7 +519,6 @@ "//services/ws/public/mojom", "//skia/public/interfaces", "//third_party/blink/public/mojom:mojom_core", - "//third_party/blink/public/mojom:web_bluetooth_mojo_bindings", "//third_party/blink/public/mojom:web_feature_mojo_bindings", "//ui/base/ime/mojo", "//ui/base/mojo",
diff --git a/content/common/bluetooth/typemaps.gni b/content/common/bluetooth/typemaps.gni deleted file mode 100644 index 552e6cfe..0000000 --- a/content/common/bluetooth/typemaps.gni +++ /dev/null
@@ -1,5 +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. - -typemaps = [ "//content/common/bluetooth/web_bluetooth_device_id.typemap" ]
diff --git a/content/common/bluetooth/web_bluetooth_device_id.typemap b/content/common/bluetooth/web_bluetooth_device_id.typemap deleted file mode 100644 index 015117249..0000000 --- a/content/common/bluetooth/web_bluetooth_device_id.typemap +++ /dev/null
@@ -1,10 +0,0 @@ -# Copyright 2016 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -mojom = "//third_party/blink/public/mojom/bluetooth/web_bluetooth.mojom" -public_headers = [ "//content/common/bluetooth/web_bluetooth_device_id.h" ] -traits_headers = - [ "//content/common/bluetooth/web_bluetooth_device_id_struct_traits.h" ] -type_mappings = - [ "blink.mojom.WebBluetoothDeviceId=content::WebBluetoothDeviceId" ]
diff --git a/content/common/bluetooth/web_bluetooth_device_id_struct_traits.h b/content/common/bluetooth/web_bluetooth_device_id_struct_traits.h deleted file mode 100644 index 71bf2f9..0000000 --- a/content/common/bluetooth/web_bluetooth_device_id_struct_traits.h +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_BROWSER_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_STRUCT_TRAITS_H_ -#define CONTENT_BROWSER_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_STRUCT_TRAITS_H_ - -#include <string> - -#include "content/common/bluetooth/web_bluetooth_device_id.h" -#include "third_party/blink/public/mojom/bluetooth/web_bluetooth.mojom.h" - -namespace mojo { - -template <> -struct StructTraits<blink::mojom::WebBluetoothDeviceIdDataView, - content::WebBluetoothDeviceId> { - static const std::string& device_id( - const content::WebBluetoothDeviceId& device_id) { - return device_id.str(); - } - - static bool Read(blink::mojom::WebBluetoothDeviceIdDataView input, - content::WebBluetoothDeviceId* output) { - std::string result; - - if (!input.ReadDeviceId(&result)) - return false; - if (!content::WebBluetoothDeviceId::IsValid(result)) - return false; - - *output = content::WebBluetoothDeviceId(std::move(result)); - return true; - } -}; - -} // namespace mojo - -#endif // CONTENT_BROWSER_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_STRUCT_TRAITS_H_
diff --git a/content/common/content_message_generator.h b/content/common/content_message_generator.h index 3fb646b..3bfbf7f 100644 --- a/content/common/content_message_generator.h +++ b/content/common/content_message_generator.h
@@ -16,11 +16,6 @@ #error \ "Failed to include content/common/browser_plugin/browser_plugin_messages.h" #endif -#undef CONTENT_COMMON_DOM_STORAGE_DOM_STORAGE_MESSAGES_H_ -#include "content/common/dom_storage/dom_storage_messages.h" -#ifndef CONTENT_COMMON_DOM_STORAGE_DOM_STORAGE_MESSAGES_H_ -#error "Failed to include content/common/dom_storage/dom_storage_messages.h" -#endif #undef CONTENT_COMMON_DRAG_MESSAGES_H_ #include "content/common/drag_messages.h" #ifndef CONTENT_COMMON_DRAG_MESSAGES_H_
diff --git a/content/common/dom_storage/dom_storage_messages.h b/content/common/dom_storage/dom_storage_messages.h deleted file mode 100644 index ca95369..0000000 --- a/content/common/dom_storage/dom_storage_messages.h +++ /dev/null
@@ -1,104 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_COMMON_DOM_STORAGE_DOM_STORAGE_MESSAGES_H_ -#define CONTENT_COMMON_DOM_STORAGE_DOM_STORAGE_MESSAGES_H_ - -#include <stdint.h> - -#include "content/common/dom_storage/dom_storage_types.h" -#include "ipc/ipc_message_macros.h" -#include "ipc/ipc_param_traits.h" -#include "third_party/blink/public/platform/web_storage_area.h" -#include "url/gurl.h" -#include "url/ipc/url_param_traits.h" - -#define IPC_MESSAGE_START DOMStorageMsgStart - -IPC_ENUM_TRAITS_MAX_VALUE(blink::WebStorageArea::Result, - blink::WebStorageArea::kResultLast) - -// Signals a local storage event. -IPC_STRUCT_BEGIN(DOMStorageMsg_Event_Params) - // The key that generated the storage event. Null if clear() was called. - IPC_STRUCT_MEMBER(base::NullableString16, key) - - // The old value of this key. Null on clear() or if it didn't have a value. - IPC_STRUCT_MEMBER(base::NullableString16, old_value) - - // The new value of this key. Null on removeItem() or clear(). - IPC_STRUCT_MEMBER(base::NullableString16, new_value) - - // The origin this is associated with. - IPC_STRUCT_MEMBER(GURL, origin) - - // The URL of the page that caused the storage event. - IPC_STRUCT_MEMBER(GURL, page_url) - - // The non-zero connection_id which caused the event or 0 if the event - // was not caused by the target renderer process. - IPC_STRUCT_MEMBER(int, connection_id) - - // The non-zero session namespace_id associated with the event or 0 if - // this is a local storage event. - IPC_STRUCT_MEMBER(std::string, namespace_id) -IPC_STRUCT_END() - -// DOM Storage messages sent from the browser to the renderer. - -// Storage events are broadcast to all renderer processes. -IPC_MESSAGE_CONTROL1(DOMStorageMsg_Event, - DOMStorageMsg_Event_Params) - -// Completion notification sent in response to each async -// load, set, remove, and clear operation. -// Used to maintain the integrity of the renderer-side cache. -IPC_MESSAGE_CONTROL1(DOMStorageMsg_AsyncOperationComplete, - bool /* success */) - -// DOM Storage messages sent from the renderer to the browser. -// Note: The 'connection_id' must be the first parameter in these message. - -// Open the storage area for a particular origin within a namespace. -IPC_MESSAGE_CONTROL3(DOMStorageHostMsg_OpenStorageArea, - int /* connection_id */, - std::string /* namespace_id */, - GURL /* origin */) - -// Close a previously opened storage area. -IPC_MESSAGE_CONTROL1(DOMStorageHostMsg_CloseStorageArea, - int /* connection_id */) - -// Retrieves the set of key/value pairs for the area. Used to prime -// the renderer-side cache. A completion notification is sent in response. -IPC_SYNC_MESSAGE_CONTROL1_1(DOMStorageHostMsg_LoadStorageArea, - int /* connection_id */, - content::DOMStorageValuesMap) - -// Set a value that's associated with a key in a storage area. -// A completion notification is sent in response. -IPC_MESSAGE_CONTROL5(DOMStorageHostMsg_SetItem, - int /* connection_id */, - base::string16 /* key */, - base::string16 /* value */, - base::NullableString16 /* client_old_value */, - GURL /* page_url */) - -// Remove the value associated with a key in a storage area. -// A completion notification is sent in response. -IPC_MESSAGE_CONTROL4(DOMStorageHostMsg_RemoveItem, - int /* connection_id */, - base::string16 /* key */, - base::NullableString16 /* client_old_value */, - GURL /* page_url */) - -// Clear the storage area. A completion notification is sent in response. -IPC_MESSAGE_CONTROL2(DOMStorageHostMsg_Clear, - int /* connection_id */, - GURL /* page_url */) - -// Used to flush the ipc message queue. -IPC_SYNC_MESSAGE_CONTROL0_0(DOMStorageHostMsg_FlushMessages) - -#endif // CONTENT_COMMON_DOM_STORAGE_DOM_STORAGE_MESSAGES_H_
diff --git a/content/ppapi_plugin/ppapi_blink_platform_impl.cc b/content/ppapi_plugin/ppapi_blink_platform_impl.cc index 5350660..921d326f 100644 --- a/content/ppapi_plugin/ppapi_blink_platform_impl.cc +++ b/content/ppapi_plugin/ppapi_blink_platform_impl.cc
@@ -15,7 +15,6 @@ #include "content/child/child_thread_impl.h" #include "ppapi/proxy/plugin_globals.h" #include "ppapi/shared_impl/proxy_lock.h" -#include "third_party/blink/public/platform/web_storage_namespace.h" #include "third_party/blink/public/platform/web_string.h" #if defined(OS_MACOSX) @@ -91,12 +90,6 @@ return blink::WebData(); } -std::unique_ptr<blink::WebStorageNamespace> -PpapiBlinkPlatformImpl::CreateLocalStorageNamespace() { - NOTREACHED(); - return nullptr; -} - int PpapiBlinkPlatformImpl::DatabaseDeleteFile( const blink::WebString& vfs_file_name, bool sync_dir) {
diff --git a/content/ppapi_plugin/ppapi_blink_platform_impl.h b/content/ppapi_plugin/ppapi_blink_platform_impl.h index 41a4f9b..2227892 100644 --- a/content/ppapi_plugin/ppapi_blink_platform_impl.h +++ b/content/ppapi_plugin/ppapi_blink_platform_impl.h
@@ -35,8 +35,6 @@ blink::WebString DefaultLocale() override; blink::WebThemeEngine* ThemeEngine() override; blink::WebData GetDataResource(const char* name) override; - std::unique_ptr<blink::WebStorageNamespace> CreateLocalStorageNamespace() - override; int DatabaseDeleteFile(const blink::WebString& vfs_file_name, bool sync_dir) override;
diff --git a/content/renderer/BUILD.gn b/content/renderer/BUILD.gn index 80b72daa6..8250aee0 100644 --- a/content/renderer/BUILD.gn +++ b/content/renderer/BUILD.gn
@@ -70,25 +70,6 @@ "crash_helpers.h", "dom_automation_controller.cc", "dom_automation_controller.h", - "dom_storage/dom_storage_cached_area.cc", - "dom_storage/dom_storage_cached_area.h", - "dom_storage/dom_storage_dispatcher.cc", - "dom_storage/dom_storage_dispatcher.h", - "dom_storage/dom_storage_proxy.h", - "dom_storage/local_storage_area.cc", - "dom_storage/local_storage_area.h", - "dom_storage/local_storage_cached_area.cc", - "dom_storage/local_storage_cached_area.h", - "dom_storage/local_storage_cached_areas.cc", - "dom_storage/local_storage_cached_areas.h", - "dom_storage/local_storage_namespace.cc", - "dom_storage/local_storage_namespace.h", - "dom_storage/session_web_storage_namespace_impl.cc", - "dom_storage/session_web_storage_namespace_impl.h", - "dom_storage/webstoragearea_impl.cc", - "dom_storage/webstoragearea_impl.h", - "dom_storage/webstoragenamespace_impl.cc", - "dom_storage/webstoragenamespace_impl.h", "drop_data_builder.cc", "drop_data_builder.h", "effective_connection_type_helper.cc",
diff --git a/content/renderer/dom_storage/DEPS b/content/renderer/dom_storage/DEPS deleted file mode 100644 index 32e0c4f..0000000 --- a/content/renderer/dom_storage/DEPS +++ /dev/null
@@ -1,15 +0,0 @@ -specific_include_rules = { - 'local_storage\.*': [ - "-content/renderer", - "+components/services/leveldb/public/cpp/util.h", - "+components/services/leveldb/public/interfaces", - "+content/common/dom_storage/dom_storage_map.h", - "+content/renderer/dom_storage/local_storage_cached_area.h", - "+content/renderer/dom_storage/local_storage_cached_areas.h", - "+content/renderer/dom_storage/local_storage_area.h", - "+content/renderer/dom_storage/local_storage_namespace.h", - "+content/renderer/dom_storage/mock_leveldb_wrapper.h", - "+content/renderer/dom_storage/session_web_storage_namespace_impl.h", - "+content/renderer/render_thread_impl.h", - ], -}
diff --git a/content/renderer/dom_storage/OWNERS b/content/renderer/dom_storage/OWNERS deleted file mode 100644 index aeb1ffd..0000000 --- a/content/renderer/dom_storage/OWNERS +++ /dev/null
@@ -1,4 +0,0 @@ -file://content/browser/dom_storage/OWNERS - -# TEAM: storage-dev@chromium.org -# COMPONENT: Blink>Storage>DOMStorage
diff --git a/content/renderer/dom_storage/dom_storage_cached_area.cc b/content/renderer/dom_storage/dom_storage_cached_area.cc deleted file mode 100644 index 13bcf8e..0000000 --- a/content/renderer/dom_storage/dom_storage_cached_area.cc +++ /dev/null
@@ -1,267 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/dom_storage/dom_storage_cached_area.h" - -#include <limits> - -#include "base/bind.h" -#include "base/metrics/histogram_macros.h" -#include "base/time/time.h" -#include "build/build_config.h" -#include "content/common/dom_storage/dom_storage_map.h" -#include "content/renderer/dom_storage/dom_storage_proxy.h" -#include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h" - -namespace content { - -DOMStorageCachedArea::DOMStorageCachedArea( - const std::string& namespace_id, - const GURL& origin, - DOMStorageProxy* proxy, - blink::scheduler::WebThreadScheduler* main_thread_scheduler) - : ignore_all_mutations_(false), - namespace_id_(namespace_id), - origin_(origin), - proxy_(proxy), - main_thread_scheduler_(main_thread_scheduler), - weak_factory_(this) {} - -DOMStorageCachedArea::~DOMStorageCachedArea() {} - -unsigned DOMStorageCachedArea::GetLength(int connection_id) { - PrimeIfNeeded(connection_id); - return map_->Length(); -} - -base::NullableString16 DOMStorageCachedArea::GetKey( - int connection_id, - unsigned index, - bool* did_decrease_iterator) { - PrimeIfNeeded(connection_id); - return map_->Key(index, did_decrease_iterator); -} - -base::NullableString16 DOMStorageCachedArea::GetItem( - int connection_id, - const base::string16& key) { - PrimeIfNeeded(connection_id); - return map_->GetItem(key); -} - -bool DOMStorageCachedArea::SetItem(int connection_id, - const base::string16& key, - const base::string16& value, - const GURL& page_url) { - // A quick check to reject obviously overbudget items to avoid - // the priming the cache. - if ((key.length() + value.length()) * sizeof(base::char16) > - kPerStorageAreaQuota) - return false; - - PrimeIfNeeded(connection_id); - base::NullableString16 old_value; -#if !defined(OS_ANDROID) - if (!map_->SetItem(key, value, nullptr)) - return false; -#else - // The old value is only used on Android when the cache stores only the keys. - // Do not send old value on other platforms. - // TODO(ssid): Clear this value when values are stored in the browser cache on - // Android, crbug.com/743187. - if (!map_->SetItem(key, value, &old_value)) - return false; -#endif // !defined(OS_ANDROID) - - // Ignore mutations to 'key' until OnSetItemComplete. - blink::WebScopedVirtualTimePauser virtual_time_pauser = - main_thread_scheduler_->CreateWebScopedVirtualTimePauser( - "DOMStorageCachedArea"); - virtual_time_pauser.PauseVirtualTime(); - ignore_key_mutations_[key]++; - proxy_->SetItem(connection_id, key, value, old_value, page_url, - base::BindOnce(&DOMStorageCachedArea::OnSetItemComplete, - weak_factory_.GetWeakPtr(), key, - std::move(virtual_time_pauser))); - return true; -} - -void DOMStorageCachedArea::RemoveItem(int connection_id, - const base::string16& key, - const GURL& page_url) { - PrimeIfNeeded(connection_id); - base::string16 old_value; -#if !defined(OS_ANDROID) - if (!map_->RemoveItem(key, nullptr)) - return; -#else - // The old value is only used on Android when the cache stores only the keys. - // Do not send old value on other platforms. - if (!map_->RemoveItem(key, &old_value)) - return; -#endif - - // Ignore mutations to 'key' until OnRemoveItemComplete. - blink::WebScopedVirtualTimePauser virtual_time_pauser = - main_thread_scheduler_->CreateWebScopedVirtualTimePauser( - "DOMStorageCachedArea"); - virtual_time_pauser.PauseVirtualTime(); - ignore_key_mutations_[key]++; - proxy_->RemoveItem(connection_id, key, - base::NullableString16(old_value, false), page_url, - base::BindOnce(&DOMStorageCachedArea::OnRemoveItemComplete, - weak_factory_.GetWeakPtr(), key, - std::move(virtual_time_pauser))); -} - -void DOMStorageCachedArea::Clear(int connection_id, const GURL& page_url) { - // No need to prime the cache in this case. - Reset(); - map_ = new DOMStorageMap(kPerStorageAreaQuota); - - // Ignore all mutations until OnClearComplete time. - blink::WebScopedVirtualTimePauser virtual_time_pauser = - main_thread_scheduler_->CreateWebScopedVirtualTimePauser( - "DOMStorageCachedArea"); - virtual_time_pauser.PauseVirtualTime(); - ignore_all_mutations_ = true; - proxy_->ClearArea(connection_id, page_url, - base::BindOnce(&DOMStorageCachedArea::OnClearComplete, - weak_factory_.GetWeakPtr(), - std::move(virtual_time_pauser))); -} - -void DOMStorageCachedArea::ApplyMutation( - const base::NullableString16& key, - const base::NullableString16& new_value) { - if (!map_.get() || ignore_all_mutations_) - return; - - if (key.is_null()) { - // It's a clear event. - scoped_refptr<DOMStorageMap> old = map_; - map_ = new DOMStorageMap(kPerStorageAreaQuota); - - // We have to retain local additions which happened after this - // clear operation from another process. - auto iter = ignore_key_mutations_.begin(); - while (iter != ignore_key_mutations_.end()) { - base::NullableString16 value = old->GetItem(iter->first); - if (!value.is_null()) { - map_->SetItem(iter->first, value.string(), nullptr); - } - ++iter; - } - return; - } - - // We have to retain local changes. - if (should_ignore_key_mutation(key.string())) - return; - - if (new_value.is_null()) { - // It's a remove item event. - map_->RemoveItem(key.string(), nullptr); - return; - } - - // It's a set item event. - // We turn off quota checking here to accomodate the over budget - // allowance that's provided in the browser process. - map_->set_quota(std::numeric_limits<int32_t>::max()); - map_->SetItem(key.string(), new_value.string(), nullptr); - map_->set_quota(kPerStorageAreaQuota); -} - -void DOMStorageCachedArea::Prime(int connection_id) { - DCHECK(!map_.get()); - - // The LoadArea method is actually synchronous, but we have to - // wait for an asyncly delivered message to know when incoming - // mutation events should be applied. Our valuemap is plucked - // from ipc stream out of order, mutations in front if it need - // to be ignored. - - // Ignore all mutations until OnLoadComplete time. - ignore_all_mutations_ = true; - DOMStorageValuesMap values; - base::TimeTicks before = base::TimeTicks::Now(); - proxy_->LoadArea(connection_id, &values, - base::BindOnce(&DOMStorageCachedArea::OnLoadComplete, - weak_factory_.GetWeakPtr())); - base::TimeDelta time_to_prime = base::TimeTicks::Now() - before; - // Keeping this histogram named the same (without the ForRenderer suffix) - // to maintain histogram continuity. - UMA_HISTOGRAM_TIMES("LocalStorage.TimeToPrimeLocalStorage", - time_to_prime); - map_ = new DOMStorageMap(kPerStorageAreaQuota); - map_->SwapValues(&values); - - size_t local_storage_size_kb = map_->storage_used() / 1024; - // Track localStorage size, from 0-6MB. Note that the maximum size should be - // 5MB, but we add some slop since we want to make sure the max size is always - // above what we see in practice, since histograms can't change. - UMA_HISTOGRAM_CUSTOM_COUNTS("LocalStorage.RendererLocalStorageSizeInKB", - local_storage_size_kb, - 1, 6 * 1024, 50); - if (local_storage_size_kb < 100) { - UMA_HISTOGRAM_TIMES( - "LocalStorage.RendererTimeToPrimeLocalStorageUnder100KB", - time_to_prime); - } else if (local_storage_size_kb < 1000) { - UMA_HISTOGRAM_TIMES( - "LocalStorage.RendererTimeToPrimeLocalStorage100KBTo1MB", - time_to_prime); - } else { - UMA_HISTOGRAM_TIMES( - "LocalStorage.RendererTimeToPrimeLocalStorage1MBTo5MB", - time_to_prime); - } -} - -void DOMStorageCachedArea::Reset() { - map_ = nullptr; - weak_factory_.InvalidateWeakPtrs(); - ignore_key_mutations_.clear(); - ignore_all_mutations_ = false; -} - -void DOMStorageCachedArea::OnLoadComplete(bool success) { - DCHECK(success); - DCHECK(ignore_all_mutations_); - ignore_all_mutations_ = false; -} - -void DOMStorageCachedArea::OnSetItemComplete(const base::string16& key, - blink::WebScopedVirtualTimePauser, - bool success) { - if (!success) { - Reset(); - return; - } - auto found = ignore_key_mutations_.find(key); - DCHECK(found != ignore_key_mutations_.end()); - if (--found->second == 0) - ignore_key_mutations_.erase(found); -} - -void DOMStorageCachedArea::OnRemoveItemComplete( - const base::string16& key, - blink::WebScopedVirtualTimePauser, - bool success) { - DCHECK(success); - auto found = ignore_key_mutations_.find(key); - DCHECK(found != ignore_key_mutations_.end()); - if (--found->second == 0) - ignore_key_mutations_.erase(found); -} - -void DOMStorageCachedArea::OnClearComplete(blink::WebScopedVirtualTimePauser, - bool success) { - DCHECK(success); - DCHECK(ignore_all_mutations_); - ignore_all_mutations_ = false; -} - -} // namespace content
diff --git a/content/renderer/dom_storage/dom_storage_cached_area.h b/content/renderer/dom_storage/dom_storage_cached_area.h deleted file mode 100644 index ae1a945..0000000 --- a/content/renderer/dom_storage/dom_storage_cached_area.h +++ /dev/null
@@ -1,117 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_DOM_STORAGE_DOM_STORAGE_CACHED_AREA_H_ -#define CONTENT_RENDERER_DOM_STORAGE_DOM_STORAGE_CACHED_AREA_H_ - -#include <stddef.h> -#include <stdint.h> - -#include <map> - -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/strings/nullable_string16.h" -#include "content/common/content_export.h" -#include "third_party/blink/public/platform/scheduler/web_scoped_virtual_time_pauser.h" -#include "url/gurl.h" - -namespace blink { -namespace scheduler { -class WebThreadScheduler; -} -} // namespace blink - -namespace content { - -class DOMStorageMap; -class DOMStorageProxy; - -// Unlike the other classes in the dom_storage library, this one is intended -// for use in renderer processes. It maintains a complete cache of the -// origin's Map of key/value pairs for fast access. The cache is primed on -// first access and changes are written to the backend thru the |proxy|. -// Mutations originating in other processes are applied to the cache via -// the ApplyMutation method. -class CONTENT_EXPORT DOMStorageCachedArea - : public base::RefCounted<DOMStorageCachedArea> { - public: - DOMStorageCachedArea( - const std::string& namespace_id, - const GURL& origin, - DOMStorageProxy* proxy, - blink::scheduler::WebThreadScheduler* main_thread_scheduler); - - const std::string& namespace_id() const { return namespace_id_; } - const GURL& origin() const { return origin_; } - - unsigned GetLength(int connection_id); - // See DOMStorageMap for the meaning of |did_decrease_iterator|. - base::NullableString16 GetKey(int connection_id, - unsigned index, - bool* did_decrease_iterator = nullptr); - base::NullableString16 GetItem(int connection_id, const base::string16& key); - bool SetItem(int connection_id, - const base::string16& key, - const base::string16& value, - const GURL& page_url); - void RemoveItem(int connection_id, - const base::string16& key, - const GURL& page_url); - void Clear(int connection_id, const GURL& page_url); - - void ApplyMutation(const base::NullableString16& key, - const base::NullableString16& new_value); - - private: - friend class DOMStorageCachedAreaTest; - friend class base::RefCounted<DOMStorageCachedArea>; - ~DOMStorageCachedArea(); - - // Primes the cache, loading all values for the area. - void Prime(int connection_id); - void PrimeIfNeeded(int connection_id) { - if (!map_.get()) - Prime(connection_id); - } - - // Resets the object back to its newly constructed state. - void Reset(); - - // Async completion callbacks for proxied operations. - // These are used to maintain cache consistency by preventing - // mutation events from other processes from overwriting local - // changes made after the mutation. - void OnLoadComplete(bool success); - void OnSetItemComplete(const base::string16& key, - blink::WebScopedVirtualTimePauser virtual_time_pauser, - bool success); - void OnClearComplete(blink::WebScopedVirtualTimePauser virtual_time_pauser, - bool success); - void OnRemoveItemComplete( - const base::string16& key, - blink::WebScopedVirtualTimePauser virtual_time_pauser, - bool success); - - bool should_ignore_key_mutation(const base::string16& key) const { - return ignore_key_mutations_.find(key) != ignore_key_mutations_.end(); - } - - bool ignore_all_mutations_; - std::map<base::string16, int> ignore_key_mutations_; - - std::string namespace_id_; - GURL origin_; - scoped_refptr<DOMStorageMap> map_; - scoped_refptr<DOMStorageProxy> proxy_; - - // Not owned. - blink::scheduler::WebThreadScheduler* main_thread_scheduler_; - - base::WeakPtrFactory<DOMStorageCachedArea> weak_factory_; -}; - -} // namespace content - -#endif // CONTENT_RENDERER_DOM_STORAGE_DOM_STORAGE_CACHED_AREA_H_
diff --git a/content/renderer/dom_storage/dom_storage_cached_area_unittest.cc b/content/renderer/dom_storage/dom_storage_cached_area_unittest.cc deleted file mode 100644 index 9f65f8ad..0000000 --- a/content/renderer/dom_storage/dom_storage_cached_area_unittest.cc +++ /dev/null
@@ -1,366 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/dom_storage/dom_storage_cached_area.h" - -#include <stdint.h> -#include <list> -#include <memory> - -#include "base/bind.h" -#include "base/strings/utf_string_conversions.h" -#include "base/test/scoped_task_environment.h" -#include "content/renderer/dom_storage/dom_storage_proxy.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/blink/public/platform/scheduler/test/web_fake_thread_scheduler.h" - -namespace content { - -namespace { -// A mock implementation of the DOMStorageProxy interface. -class MockProxy : public DOMStorageProxy { - public: - MockProxy() { - ResetObservations(); - } - - // DOMStorageProxy interface for use by DOMStorageCachedArea. - - void LoadArea(int connection_id, - DOMStorageValuesMap* values, - CompletionCallback callback) override { - pending_callbacks_.push_back(std::move(callback)); - observed_load_area_ = true; - observed_connection_id_ = connection_id; - *values = load_area_return_values_; - } - - void SetItem(int connection_id, - const base::string16& key, - const base::string16& value, - const base::NullableString16& old_value, - const GURL& page_url, - CompletionCallback callback) override { - pending_callbacks_.push_back(std::move(callback)); - observed_set_item_ = true; - observed_connection_id_ = connection_id; - observed_key_ = key; - observed_value_ = value; - observed_page_url_ = page_url; - } - - void RemoveItem(int connection_id, - const base::string16& key, - const base::NullableString16& old_value, - const GURL& page_url, - CompletionCallback callback) override { - pending_callbacks_.push_back(std::move(callback)); - observed_remove_item_ = true; - observed_connection_id_ = connection_id; - observed_key_ = key; - observed_page_url_ = page_url; - } - - void ClearArea(int connection_id, - const GURL& page_url, - CompletionCallback callback) override { - pending_callbacks_.push_back(std::move(callback)); - observed_clear_area_ = true; - observed_connection_id_ = connection_id; - observed_page_url_ = page_url; - } - - // Methods and members for use by test fixtures. - - void ResetObservations() { - observed_load_area_ = false; - observed_set_item_ = false; - observed_remove_item_ = false; - observed_clear_area_ = false; - observed_connection_id_ = 0; - observed_key_.clear(); - observed_value_.clear(); - observed_page_url_ = GURL(); - } - - void CompleteAllPendingCallbacks() { - while (!pending_callbacks_.empty()) - CompleteOnePendingCallback(true); - } - - void CompleteOnePendingCallback(bool success) { - ASSERT_TRUE(!pending_callbacks_.empty()); - std::move(pending_callbacks_.front()).Run(success); - pending_callbacks_.pop_front(); - } - - typedef std::list<CompletionCallback> CallbackList; - - DOMStorageValuesMap load_area_return_values_; - CallbackList pending_callbacks_; - bool observed_load_area_; - bool observed_set_item_; - bool observed_remove_item_; - bool observed_clear_area_; - int observed_connection_id_; - base::string16 observed_key_; - base::string16 observed_value_; - GURL observed_page_url_; - - private: - ~MockProxy() override {} -}; - -} // namespace - -class DOMStorageCachedAreaTest : public testing::Test { - public: - DOMStorageCachedAreaTest() - : kNamespaceId("id"), - kOrigin("http://dom_storage/"), - kKey(base::ASCIIToUTF16("key")), - kValue(base::ASCIIToUTF16("value")), - kPageUrl("http://dom_storage/page") {} - - const std::string kNamespaceId; - const GURL kOrigin; - const base::string16 kKey; - const base::string16 kValue; - const GURL kPageUrl; - - void SetUp() override { - main_thread_scheduler_ = - std::make_unique<blink::scheduler::WebFakeThreadScheduler>(); - mock_proxy_ = new MockProxy(); - } - - bool IsPrimed(DOMStorageCachedArea* cached_area) { - return cached_area->map_.get(); - } - - bool IsIgnoringAllMutations(DOMStorageCachedArea* cached_area) { - return cached_area->ignore_all_mutations_; - } - - bool IsIgnoringKeyMutations(DOMStorageCachedArea* cached_area, - const base::string16& key) { - return cached_area->should_ignore_key_mutation(key); - } - - void ResetAll(DOMStorageCachedArea* cached_area) { - cached_area->Reset(); - mock_proxy_->ResetObservations(); - mock_proxy_->pending_callbacks_.clear(); - } - - void ResetCacheOnly(DOMStorageCachedArea* cached_area) { - cached_area->Reset(); - } - - protected: - base::test::ScopedTaskEnvironment - task_environment_; // Needed to construct a RendererScheduler. - std::unique_ptr<blink::scheduler::WebThreadScheduler> main_thread_scheduler_; - scoped_refptr<MockProxy> mock_proxy_; -}; - -TEST_F(DOMStorageCachedAreaTest, Basics) { - EXPECT_TRUE(mock_proxy_->HasOneRef()); - scoped_refptr<DOMStorageCachedArea> cached_area = new DOMStorageCachedArea( - kNamespaceId, kOrigin, mock_proxy_.get(), main_thread_scheduler_.get()); - EXPECT_EQ(kNamespaceId, cached_area->namespace_id()); - EXPECT_EQ(kOrigin, cached_area->origin()); - EXPECT_FALSE(mock_proxy_->HasOneRef()); - cached_area->ApplyMutation(base::NullableString16(kKey, false), - base::NullableString16(kValue, false)); - EXPECT_FALSE(IsPrimed(cached_area.get())); - - ResetAll(cached_area.get()); - EXPECT_EQ(kNamespaceId, cached_area->namespace_id()); - EXPECT_EQ(kOrigin, cached_area->origin()); - - const int kConnectionId = 1; - EXPECT_EQ(0u, cached_area->GetLength(kConnectionId)); - EXPECT_TRUE(cached_area->SetItem(kConnectionId, kKey, kValue, kPageUrl)); - EXPECT_EQ(1u, cached_area->GetLength(kConnectionId)); - EXPECT_EQ(kKey, cached_area->GetKey(kConnectionId, 0).string()); - EXPECT_EQ(kValue, cached_area->GetItem(kConnectionId, kKey).string()); - cached_area->RemoveItem(kConnectionId, kKey, kPageUrl); - EXPECT_EQ(0u, cached_area->GetLength(kConnectionId)); -} - -TEST_F(DOMStorageCachedAreaTest, Getters) { - const int kConnectionId = 7; - scoped_refptr<DOMStorageCachedArea> cached_area = new DOMStorageCachedArea( - kNamespaceId, kOrigin, mock_proxy_.get(), main_thread_scheduler_.get()); - - // GetLength, we expect to see one call to load in the proxy. - EXPECT_FALSE(IsPrimed(cached_area.get())); - EXPECT_EQ(0u, cached_area->GetLength(kConnectionId)); - EXPECT_TRUE(IsPrimed(cached_area.get())); - EXPECT_TRUE(mock_proxy_->observed_load_area_); - EXPECT_EQ(kConnectionId, mock_proxy_->observed_connection_id_); - EXPECT_EQ(1u, mock_proxy_->pending_callbacks_.size()); - EXPECT_TRUE(IsIgnoringAllMutations(cached_area.get())); - mock_proxy_->CompleteAllPendingCallbacks(); - EXPECT_FALSE(IsIgnoringAllMutations(cached_area.get())); - - // GetKey, expect the one call to load. - ResetAll(cached_area.get()); - EXPECT_FALSE(IsPrimed(cached_area.get())); - EXPECT_TRUE(cached_area->GetKey(kConnectionId, 2).is_null()); - EXPECT_TRUE(IsPrimed(cached_area.get())); - EXPECT_TRUE(mock_proxy_->observed_load_area_); - EXPECT_EQ(kConnectionId, mock_proxy_->observed_connection_id_); - EXPECT_EQ(1u, mock_proxy_->pending_callbacks_.size()); - - // GetItem, ditto. - ResetAll(cached_area.get()); - EXPECT_FALSE(IsPrimed(cached_area.get())); - EXPECT_TRUE(cached_area->GetItem(kConnectionId, kKey).is_null()); - EXPECT_TRUE(IsPrimed(cached_area.get())); - EXPECT_TRUE(mock_proxy_->observed_load_area_); - EXPECT_EQ(kConnectionId, mock_proxy_->observed_connection_id_); - EXPECT_EQ(1u, mock_proxy_->pending_callbacks_.size()); -} - -TEST_F(DOMStorageCachedAreaTest, Setters) { - const int kConnectionId = 7; - scoped_refptr<DOMStorageCachedArea> cached_area = new DOMStorageCachedArea( - kNamespaceId, kOrigin, mock_proxy_.get(), main_thread_scheduler_.get()); - - // SetItem, we expect a call to load followed by a call to set item - // in the proxy. - EXPECT_FALSE(IsPrimed(cached_area.get())); - EXPECT_TRUE(cached_area->SetItem(kConnectionId, kKey, kValue, kPageUrl)); - EXPECT_TRUE(IsPrimed(cached_area.get())); - EXPECT_TRUE(mock_proxy_->observed_load_area_); - EXPECT_TRUE(mock_proxy_->observed_set_item_); - EXPECT_EQ(kConnectionId, mock_proxy_->observed_connection_id_); - EXPECT_EQ(kPageUrl, mock_proxy_->observed_page_url_); - EXPECT_EQ(kKey, mock_proxy_->observed_key_); - EXPECT_EQ(kValue, mock_proxy_->observed_value_); - EXPECT_EQ(2u, mock_proxy_->pending_callbacks_.size()); - - // Clear, we expect a just the one call to clear in the proxy since - // there's no need to load the data prior to deleting it. - ResetAll(cached_area.get()); - EXPECT_FALSE(IsPrimed(cached_area.get())); - cached_area->Clear(kConnectionId, kPageUrl); - EXPECT_TRUE(IsPrimed(cached_area.get())); - EXPECT_TRUE(mock_proxy_->observed_clear_area_); - EXPECT_EQ(kConnectionId, mock_proxy_->observed_connection_id_); - EXPECT_EQ(kPageUrl, mock_proxy_->observed_page_url_); - EXPECT_EQ(1u, mock_proxy_->pending_callbacks_.size()); - - // RemoveItem with nothing to remove, expect just one call to load. - ResetAll(cached_area.get()); - EXPECT_FALSE(IsPrimed(cached_area.get())); - cached_area->RemoveItem(kConnectionId, kKey, kPageUrl); - EXPECT_TRUE(IsPrimed(cached_area.get())); - EXPECT_TRUE(mock_proxy_->observed_load_area_); - EXPECT_FALSE(mock_proxy_->observed_remove_item_); - EXPECT_EQ(kConnectionId, mock_proxy_->observed_connection_id_); - EXPECT_EQ(1u, mock_proxy_->pending_callbacks_.size()); - - // RemoveItem with something to remove, expect a call to load followed - // by a call to remove. - ResetAll(cached_area.get()); - mock_proxy_->load_area_return_values_[kKey] = - base::NullableString16(kValue, false); - EXPECT_FALSE(IsPrimed(cached_area.get())); - cached_area->RemoveItem(kConnectionId, kKey, kPageUrl); - EXPECT_TRUE(IsPrimed(cached_area.get())); - EXPECT_TRUE(mock_proxy_->observed_load_area_); - EXPECT_TRUE(mock_proxy_->observed_remove_item_); - EXPECT_EQ(kConnectionId, mock_proxy_->observed_connection_id_); - EXPECT_EQ(kPageUrl, mock_proxy_->observed_page_url_); - EXPECT_EQ(kKey, mock_proxy_->observed_key_); - EXPECT_EQ(2u, mock_proxy_->pending_callbacks_.size()); -} - -TEST_F(DOMStorageCachedAreaTest, MutationsAreIgnoredUntilLoadCompletion) { - const int kConnectionId = 7; - scoped_refptr<DOMStorageCachedArea> cached_area = new DOMStorageCachedArea( - kNamespaceId, kOrigin, mock_proxy_.get(), main_thread_scheduler_.get()); - EXPECT_TRUE(cached_area->GetItem(kConnectionId, kKey).is_null()); - EXPECT_TRUE(IsPrimed(cached_area.get())); - EXPECT_TRUE(IsIgnoringAllMutations(cached_area.get())); - - // Before load completion, the mutation should be ignored. - cached_area->ApplyMutation(base::NullableString16(kKey, false), - base::NullableString16(kValue, false)); - EXPECT_TRUE(cached_area->GetItem(kConnectionId, kKey).is_null()); - - // Call the load completion callback. - mock_proxy_->CompleteOnePendingCallback(true); - EXPECT_FALSE(IsIgnoringAllMutations(cached_area.get())); - - // Verify that mutations are now applied. - cached_area->ApplyMutation(base::NullableString16(kKey, false), - base::NullableString16(kValue, false)); - EXPECT_EQ(kValue, cached_area->GetItem(kConnectionId, kKey).string()); -} - -TEST_F(DOMStorageCachedAreaTest, MutationsAreIgnoredUntilClearCompletion) { - const int kConnectionId = 4; - scoped_refptr<DOMStorageCachedArea> cached_area = new DOMStorageCachedArea( - kNamespaceId, kOrigin, mock_proxy_.get(), main_thread_scheduler_.get()); - cached_area->Clear(kConnectionId, kPageUrl); - EXPECT_TRUE(IsIgnoringAllMutations(cached_area.get())); - mock_proxy_->CompleteOnePendingCallback(true); - EXPECT_FALSE(IsIgnoringAllMutations(cached_area.get())); - - // Verify that calling Clear twice works as expected, the first - // completion callback should have been cancelled. - ResetCacheOnly(cached_area.get()); - cached_area->Clear(kConnectionId, kPageUrl); - EXPECT_TRUE(IsIgnoringAllMutations(cached_area.get())); - cached_area->Clear(kConnectionId, kPageUrl); - EXPECT_TRUE(IsIgnoringAllMutations(cached_area.get())); - mock_proxy_->CompleteOnePendingCallback(true); - EXPECT_TRUE(IsIgnoringAllMutations(cached_area.get())); - mock_proxy_->CompleteOnePendingCallback(true); - EXPECT_FALSE(IsIgnoringAllMutations(cached_area.get())); -} - -TEST_F(DOMStorageCachedAreaTest, KeyMutationsAreIgnoredUntilCompletion) { - const int kConnectionId = 8; - scoped_refptr<DOMStorageCachedArea> cached_area = new DOMStorageCachedArea( - kNamespaceId, kOrigin, mock_proxy_.get(), main_thread_scheduler_.get()); - - // SetItem - EXPECT_TRUE(cached_area->SetItem(kConnectionId, kKey, kValue, kPageUrl)); - mock_proxy_->CompleteOnePendingCallback(true); // load completion - EXPECT_FALSE(IsIgnoringAllMutations(cached_area.get())); - EXPECT_TRUE(IsIgnoringKeyMutations(cached_area.get(), kKey)); - cached_area->ApplyMutation(base::NullableString16(kKey, false), - base::NullableString16()); - EXPECT_EQ(kValue, cached_area->GetItem(kConnectionId, kKey).string()); - mock_proxy_->CompleteOnePendingCallback(true); // set completion - EXPECT_FALSE(IsIgnoringKeyMutations(cached_area.get(), kKey)); - - // RemoveItem - cached_area->RemoveItem(kConnectionId, kKey, kPageUrl); - EXPECT_TRUE(IsIgnoringKeyMutations(cached_area.get(), kKey)); - mock_proxy_->CompleteOnePendingCallback(true); // remove completion - EXPECT_FALSE(IsIgnoringKeyMutations(cached_area.get(), kKey)); - - // Multiple mutations to the same key. - EXPECT_TRUE(cached_area->SetItem(kConnectionId, kKey, kValue, kPageUrl)); - cached_area->RemoveItem(kConnectionId, kKey, kPageUrl); - EXPECT_TRUE(IsIgnoringKeyMutations(cached_area.get(), kKey)); - mock_proxy_->CompleteOnePendingCallback(true); // set completion - EXPECT_TRUE(IsIgnoringKeyMutations(cached_area.get(), kKey)); - mock_proxy_->CompleteOnePendingCallback(true); // remove completion - EXPECT_FALSE(IsIgnoringKeyMutations(cached_area.get(), kKey)); - - // A failed set item operation should Reset the cache. - EXPECT_TRUE(cached_area->SetItem(kConnectionId, kKey, kValue, kPageUrl)); - EXPECT_TRUE(IsIgnoringKeyMutations(cached_area.get(), kKey)); - mock_proxy_->CompleteOnePendingCallback(false); - EXPECT_FALSE(IsPrimed(cached_area.get())); -} - -} // namespace content
diff --git a/content/renderer/dom_storage/dom_storage_dispatcher.cc b/content/renderer/dom_storage/dom_storage_dispatcher.cc deleted file mode 100644 index f7fcb66..0000000 --- a/content/renderer/dom_storage/dom_storage_dispatcher.cc +++ /dev/null
@@ -1,345 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/dom_storage/dom_storage_dispatcher.h" - -#include <list> -#include <map> - -#include "base/strings/string_number_conversions.h" -#include "base/synchronization/lock.h" -#include "content/common/dom_storage/dom_storage_messages.h" -#include "content/common/dom_storage/dom_storage_types.h" -#include "content/renderer/dom_storage/dom_storage_cached_area.h" -#include "content/renderer/dom_storage/dom_storage_proxy.h" -#include "content/renderer/dom_storage/webstoragearea_impl.h" -#include "content/renderer/dom_storage/webstoragenamespace_impl.h" -#include "content/renderer/render_thread_impl.h" -#include "ipc/message_filter.h" -#include "third_party/blink/public/platform/platform.h" -#include "third_party/blink/public/web/blink.h" -#include "third_party/blink/public/web/web_storage_event_dispatcher.h" - -namespace content { - -namespace { -// MessageThrottlingFilter ------------------------------------------- -// Used to limit the number of ipc messages pending completion so we -// don't overwhelm the main browser process. When the limit is reached, -// a synchronous message is sent to flush all pending messages thru. -// We expect to receive an 'ack' for each message sent. This object -// observes receipt of the acks on the IPC thread to decrement a counter. -class MessageThrottlingFilter : public IPC::MessageFilter { - public: - explicit MessageThrottlingFilter(RenderThreadImpl* sender) - : pending_count_(0), sender_(sender) {} - - void SendThrottled(IPC::Message* message); - void Shutdown() { sender_ = nullptr; } - - private: - ~MessageThrottlingFilter() override {} - - bool OnMessageReceived(const IPC::Message& message) override; - - int GetPendingCount() { return IncrementPendingCountN(0); } - int IncrementPendingCount() { return IncrementPendingCountN(1); } - int DecrementPendingCount() { return IncrementPendingCountN(-1); } - int IncrementPendingCountN(int increment) { - base::AutoLock locker(lock_); - pending_count_ += increment; - return pending_count_; - } - - base::Lock lock_; - int pending_count_; - RenderThreadImpl* sender_; -}; - -void MessageThrottlingFilter::SendThrottled(IPC::Message* message) { - // Should only be used for sending of messages which will be acknowledged - // with a separate DOMStorageMsg_AsyncOperationComplete message. - DCHECK(message->type() == DOMStorageHostMsg_LoadStorageArea::ID || - message->type() == DOMStorageHostMsg_SetItem::ID || - message->type() == DOMStorageHostMsg_RemoveItem::ID || - message->type() == DOMStorageHostMsg_Clear::ID); - DCHECK(sender_); - if (!sender_) { - delete message; - return; - } - const int kMaxPendingMessages = 1000; - bool need_to_flush = (IncrementPendingCount() > kMaxPendingMessages) && - !message->is_sync(); - sender_->Send(message); - if (need_to_flush) { - sender_->Send(new DOMStorageHostMsg_FlushMessages); - DCHECK_EQ(0, GetPendingCount()); - } else { - DCHECK_LE(0, GetPendingCount()); - } -} - -bool MessageThrottlingFilter::OnMessageReceived(const IPC::Message& message) { - if (message.type() == DOMStorageMsg_AsyncOperationComplete::ID) { - DecrementPendingCount(); - DCHECK_LE(0, GetPendingCount()); - } - return false; -} -} // namespace - -// ProxyImpl ----------------------------------------------------- -// An implementation of the DOMStorageProxy interface in terms of IPC. -// This class also manages the collection of cached areas and pending -// operations awaiting completion callbacks. -class DomStorageDispatcher::ProxyImpl : public DOMStorageProxy { - public: - explicit ProxyImpl(RenderThreadImpl* sender); - - // Methods for use by DomStorageDispatcher directly. - DOMStorageCachedArea* OpenCachedArea(const std::string& namespace_id, - const GURL& origin); - void CloseCachedArea(DOMStorageCachedArea* area); - DOMStorageCachedArea* LookupCachedArea(const std::string& namespace_id, - const GURL& origin); - void CompleteOnePendingCallback(bool success); - void Shutdown(); - - // DOMStorageProxy interface for use by DOMStorageCachedArea. - void LoadArea(int connection_id, - DOMStorageValuesMap* values, - CompletionCallback callback) override; - void SetItem(int connection_id, - const base::string16& key, - const base::string16& value, - const base::NullableString16& old_value, - const GURL& page_url, - CompletionCallback callback) override; - void RemoveItem(int connection_id, - const base::string16& key, - const base::NullableString16& old_value, - const GURL& page_url, - CompletionCallback callback) override; - void ClearArea(int connection_id, - const GURL& page_url, - CompletionCallback callback) override; - - private: - // Struct to hold references to our contained areas and - // to keep track of how many tabs have a given area open. - struct CachedAreaHolder { - scoped_refptr<DOMStorageCachedArea> area_; - int open_count_; - CachedAreaHolder() : open_count_(0) {} - CachedAreaHolder(DOMStorageCachedArea* area, int count) - : area_(area), open_count_(count) {} - }; - typedef std::map<std::string, CachedAreaHolder> CachedAreaMap; - typedef std::list<CompletionCallback> CallbackList; - - ~ProxyImpl() override {} - - void PushPendingCallback(CompletionCallback callback) { - // Terminate the renderer if an excessive number of calls are made, - // This is indicative of script in an infinite loop or being malicious. - // It's better to crash intentionally than by running the system OOM - // and interfering with everything else running in the system. - const int kMaxPendingCompletionCallbacks = 1000000; - if (pending_callbacks_.size() > kMaxPendingCompletionCallbacks) - CHECK(false) << "Too many pending DOMStorage calls."; - - // Sudden termination is disabled when there are callbacks pending - // to more reliably commit changes during shutdown. - if (pending_callbacks_.empty()) - blink::Platform::Current()->SuddenTerminationChanged(false); - pending_callbacks_.push_back(std::move(callback)); - } - - CompletionCallback PopPendingCallback() { - CompletionCallback callback = std::move(pending_callbacks_.front()); - pending_callbacks_.pop_front(); - if (pending_callbacks_.empty()) - blink::Platform::Current()->SuddenTerminationChanged(true); - return callback; - } - - std::string GetCachedAreaKey(const std::string& namespace_id, - const GURL& origin) { - return namespace_id + origin.spec(); - } - - CachedAreaHolder* GetAreaHolder(const std::string& key) { - auto found = cached_areas_.find(key); - if (found == cached_areas_.end()) - return nullptr; - return &(found->second); - } - - RenderThreadImpl* sender_; - CachedAreaMap cached_areas_; - CallbackList pending_callbacks_; - scoped_refptr<MessageThrottlingFilter> throttling_filter_; -}; - -DomStorageDispatcher::ProxyImpl::ProxyImpl(RenderThreadImpl* sender) - : sender_(sender), - throttling_filter_(new MessageThrottlingFilter(sender)) { - sender_->AddFilter(throttling_filter_.get()); -} - -DOMStorageCachedArea* DomStorageDispatcher::ProxyImpl::OpenCachedArea( - const std::string& namespace_id, - const GURL& origin) { - std::string key = GetCachedAreaKey(namespace_id, origin); - if (CachedAreaHolder* holder = GetAreaHolder(key)) { - ++(holder->open_count_); - return holder->area_.get(); - } - scoped_refptr<DOMStorageCachedArea> area = new DOMStorageCachedArea( - namespace_id, origin, this, - content::RenderThreadImpl::current()->GetWebMainThreadScheduler()); - cached_areas_[key] = CachedAreaHolder(area.get(), 1); - return area.get(); -} - -void DomStorageDispatcher::ProxyImpl::CloseCachedArea( - DOMStorageCachedArea* area) { - std::string key = GetCachedAreaKey(area->namespace_id(), area->origin()); - CachedAreaHolder* holder = GetAreaHolder(key); - DCHECK(holder); - DCHECK_EQ(holder->area_.get(), area); - DCHECK_GT(holder->open_count_, 0); - if (--(holder->open_count_) == 0) { - cached_areas_.erase(key); - } -} - -DOMStorageCachedArea* DomStorageDispatcher::ProxyImpl::LookupCachedArea( - const std::string& namespace_id, - const GURL& origin) { - std::string key = GetCachedAreaKey(namespace_id, origin); - CachedAreaHolder* holder = GetAreaHolder(key); - if (!holder) - return nullptr; - return holder->area_.get(); -} - -void DomStorageDispatcher::ProxyImpl::CompleteOnePendingCallback(bool success) { - PopPendingCallback().Run(success); -} - -void DomStorageDispatcher::ProxyImpl::Shutdown() { - throttling_filter_->Shutdown(); - sender_->RemoveFilter(throttling_filter_.get()); - sender_ = nullptr; - cached_areas_.clear(); - pending_callbacks_.clear(); -} - -void DomStorageDispatcher::ProxyImpl::LoadArea(int connection_id, - DOMStorageValuesMap* values, - CompletionCallback callback) { - PushPendingCallback(std::move(callback)); - throttling_filter_->SendThrottled(new DOMStorageHostMsg_LoadStorageArea( - connection_id, values)); -} - -void DomStorageDispatcher::ProxyImpl::SetItem( - int connection_id, - const base::string16& key, - const base::string16& value, - const base::NullableString16& old_value, - const GURL& page_url, - CompletionCallback callback) { - PushPendingCallback(std::move(callback)); - throttling_filter_->SendThrottled(new DOMStorageHostMsg_SetItem( - connection_id, key, value, old_value, page_url)); -} - -void DomStorageDispatcher::ProxyImpl::RemoveItem( - int connection_id, - const base::string16& key, - const base::NullableString16& old_value, - const GURL& page_url, - CompletionCallback callback) { - PushPendingCallback(std::move(callback)); - throttling_filter_->SendThrottled(new DOMStorageHostMsg_RemoveItem( - connection_id, key, old_value, page_url)); -} - -void DomStorageDispatcher::ProxyImpl::ClearArea(int connection_id, - const GURL& page_url, - CompletionCallback callback) { - PushPendingCallback(std::move(callback)); - throttling_filter_->SendThrottled(new DOMStorageHostMsg_Clear( - connection_id, page_url)); -} - -// DomStorageDispatcher ------------------------------------------------ - -DomStorageDispatcher::DomStorageDispatcher() - : proxy_(new ProxyImpl(RenderThreadImpl::current())) { -} - -DomStorageDispatcher::~DomStorageDispatcher() { - proxy_->Shutdown(); -} - -scoped_refptr<DOMStorageCachedArea> DomStorageDispatcher::OpenCachedArea( - int connection_id, - const std::string& namespace_id, - const GURL& origin) { - RenderThreadImpl::current()->Send( - new DOMStorageHostMsg_OpenStorageArea( - connection_id, namespace_id, origin)); - return proxy_->OpenCachedArea(namespace_id, origin); -} - -void DomStorageDispatcher::CloseCachedArea( - int connection_id, DOMStorageCachedArea* area) { - RenderThreadImpl::current()->Send( - new DOMStorageHostMsg_CloseStorageArea(connection_id)); - proxy_->CloseCachedArea(area); -} - -bool DomStorageDispatcher::OnMessageReceived(const IPC::Message& msg) { - bool handled = true; - IPC_BEGIN_MESSAGE_MAP(DomStorageDispatcher, msg) - IPC_MESSAGE_HANDLER(DOMStorageMsg_Event, OnStorageEvent) - IPC_MESSAGE_HANDLER(DOMStorageMsg_AsyncOperationComplete, - OnAsyncOperationComplete) - IPC_MESSAGE_UNHANDLED(handled = false) - IPC_END_MESSAGE_MAP() - return handled; -} - -void DomStorageDispatcher::OnStorageEvent( - const DOMStorageMsg_Event_Params& params) { - WebStorageAreaImpl* originating_area = nullptr; - if (params.connection_id) { - originating_area = WebStorageAreaImpl::FromConnectionId( - params.connection_id); - } else { - DOMStorageCachedArea* cached_area = proxy_->LookupCachedArea( - params.namespace_id, params.origin); - if (cached_area) - cached_area->ApplyMutation(params.key, params.new_value); - } - - DCHECK(!params.namespace_id.empty()); - WebStorageNamespaceImpl session_namespace_for_event_dispatch( - params.namespace_id); - blink::WebStorageEventDispatcher::DispatchSessionStorageEvent( - blink::WebString::FromUTF16(params.key), - blink::WebString::FromUTF16(params.old_value), - blink::WebString::FromUTF16(params.new_value), params.origin, - params.page_url, session_namespace_for_event_dispatch, originating_area); -} - -void DomStorageDispatcher::OnAsyncOperationComplete(bool success) { - proxy_->CompleteOnePendingCallback(success); -} - -} // namespace content
diff --git a/content/renderer/dom_storage/dom_storage_dispatcher.h b/content/renderer/dom_storage/dom_storage_dispatcher.h deleted file mode 100644 index 9946b07..0000000 --- a/content/renderer/dom_storage/dom_storage_dispatcher.h +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_DOM_STORAGE_DOM_STORAGE_DISPATCHER_H_ -#define CONTENT_RENDERER_DOM_STORAGE_DOM_STORAGE_DISPATCHER_H_ - -#include <stdint.h> - -#include "base/memory/ref_counted.h" - -class GURL; -struct DOMStorageMsg_Event_Params; - -namespace IPC { -class Message; -} - -namespace content { - -class DOMStorageCachedArea; - -// Dispatches DomStorage related messages sent to a renderer process from the -// main browser process. There is one instance per child process. Messages -// are dispatched on the main renderer thread. The RenderThreadImpl -// creates an instance and delegates calls to it. This classes also manages -// the collection of DOMStorageCachedAreas that are active in the process. -class DomStorageDispatcher { - public: - DomStorageDispatcher(); - ~DomStorageDispatcher(); - - // Each call to open should be balanced with a call to close. - scoped_refptr<DOMStorageCachedArea> OpenCachedArea( - int connection_id, - const std::string& namespace_id, - const GURL& origin); - void CloseCachedArea(int connection_id, DOMStorageCachedArea* area); - - bool OnMessageReceived(const IPC::Message& msg); - - private: - class ProxyImpl; - - // IPC message handlers - void OnStorageEvent(const DOMStorageMsg_Event_Params& params); - void OnAsyncOperationComplete(bool success); - - scoped_refptr<ProxyImpl> proxy_; -}; - -} // namespace content - -#endif // CONTENT_RENDERER_DOM_STORAGE_DOM_STORAGE_DISPATCHER_H_
diff --git a/content/renderer/dom_storage/dom_storage_proxy.h b/content/renderer/dom_storage/dom_storage_proxy.h deleted file mode 100644 index 9434567..0000000 --- a/content/renderer/dom_storage/dom_storage_proxy.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_DOM_STORAGE_DOM_STORAGE_PROXY_H_ -#define CONTENT_RENDERER_DOM_STORAGE_DOM_STORAGE_PROXY_H_ - -#include "base/bind.h" -#include "base/memory/ref_counted.h" -#include "base/strings/nullable_string16.h" -#include "base/strings/string16.h" -#include "content/common/dom_storage/dom_storage_types.h" -#include "url/gurl.h" - -namespace content { - -// Abstract interface for cached area, renderer to browser communications. -class DOMStorageProxy : public base::RefCounted<DOMStorageProxy> { - public: - typedef base::OnceCallback<void(bool)> CompletionCallback; - - virtual void LoadArea(int connection_id, - DOMStorageValuesMap* values, - CompletionCallback callback) = 0; - - virtual void SetItem(int connection_id, - const base::string16& key, - const base::string16& value, - const base::NullableString16& old_value, - const GURL& page_url, - CompletionCallback callback) = 0; - - virtual void RemoveItem(int connection_id, - const base::string16& key, - const base::NullableString16& old_value, - const GURL& page_url, - CompletionCallback callback) = 0; - - virtual void ClearArea(int connection_id, - const GURL& page_url, - CompletionCallback callback) = 0; - - protected: - friend class base::RefCounted<DOMStorageProxy>; - virtual ~DOMStorageProxy() {} -}; - -} // namespace content - -#endif // CONTENT_RENDERER_DOM_STORAGE_DOM_STORAGE_PROXY_H_
diff --git a/content/renderer/dom_storage/local_storage_area.cc b/content/renderer/dom_storage/local_storage_area.cc deleted file mode 100644 index 9aae885..0000000 --- a/content/renderer/dom_storage/local_storage_area.cc +++ /dev/null
@@ -1,59 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/dom_storage/local_storage_area.h" - -#include "base/rand_util.h" -#include "base/strings/string_number_conversions.h" -#include "third_party/blink/public/platform/web_url.h" - -using blink::WebString; -using blink::WebURL; - -namespace content { - -LocalStorageArea::LocalStorageArea( - scoped_refptr<LocalStorageCachedArea> cached_area) - : cached_area_(std::move(cached_area)), - id_(base::NumberToString(base::RandUint64())) { - cached_area_->AreaCreated(this); -} - -LocalStorageArea::~LocalStorageArea() { - cached_area_->AreaDestroyed(this); -} - -unsigned LocalStorageArea::length() { - return cached_area_->GetLength(); -} - -WebString LocalStorageArea::Key(unsigned index, bool* did_decrease_iterator) { - return WebString::FromUTF16( - cached_area_->GetKey(index, did_decrease_iterator)); -} - -WebString LocalStorageArea::GetItem(const WebString& key) { - return WebString::FromUTF16(cached_area_->GetItem(key.Utf16())); -} - -void LocalStorageArea::SetItem(const WebString& key, - const WebString& value, - const WebURL& page_url, - WebStorageArea::Result& result) { - if (!cached_area_->SetItem(key.Utf16(), value.Utf16(), page_url, id_)) - result = kResultBlockedByQuota; - else - result = kResultOK; -} - -void LocalStorageArea::RemoveItem(const WebString& key, - const WebURL& page_url) { - cached_area_->RemoveItem(key.Utf16(), page_url, id_); -} - -void LocalStorageArea::Clear(const WebURL& page_url) { - cached_area_->Clear(page_url, id_); -} - -} // namespace content
diff --git a/content/renderer/dom_storage/local_storage_area.h b/content/renderer/dom_storage/local_storage_area.h deleted file mode 100644 index 01ed6f22..0000000 --- a/content/renderer/dom_storage/local_storage_area.h +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_DOM_STORAGE_LOCAL_STORAGE_AREA_H_ -#define CONTENT_RENDERER_DOM_STORAGE_LOCAL_STORAGE_AREA_H_ - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "content/renderer/dom_storage/local_storage_cached_area.h" -#include "third_party/blink/public/platform/web_storage_area.h" - -namespace content { - -// There could be n instances of this class for the same origin in a renderer -// process. It delegates to the one LocalStorageCachedArea instance in a process -// for a given origin. -class LocalStorageArea : public blink::WebStorageArea { - public: - explicit LocalStorageArea(scoped_refptr<LocalStorageCachedArea> cached_area); - ~LocalStorageArea() override; - - // blink::WebStorageArea: - unsigned length() override; - blink::WebString Key(unsigned index, bool* did_decrease_iterator) override; - blink::WebString GetItem(const blink::WebString& key) override; - void SetItem(const blink::WebString& key, - const blink::WebString& value, - const blink::WebURL& page_url, - WebStorageArea::Result& result) override; - void RemoveItem(const blink::WebString& key, - const blink::WebURL& page_url) override; - void Clear(const blink::WebURL& url) override; - - const std::string& id() const { return id_; } - - private: - scoped_refptr<LocalStorageCachedArea> cached_area_; - // A globally unique identifier for this storage area. It's used to pass the - // source storage area, if any, in mutation events. - std::string id_; - - DISALLOW_COPY_AND_ASSIGN(LocalStorageArea); -}; - -} // namespace content - -#endif // CONTENT_RENDERER_DOM_STORAGE_LOCAL_STORAGE_AREA_H_
diff --git a/content/renderer/dom_storage/local_storage_cached_area.cc b/content/renderer/dom_storage/local_storage_cached_area.cc deleted file mode 100644 index c04e0e8..0000000 --- a/content/renderer/dom_storage/local_storage_cached_area.cc +++ /dev/null
@@ -1,623 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/dom_storage/local_storage_cached_area.h" - -#include "base/bind.h" -#include "base/memory/ptr_util.h" -#include "base/metrics/histogram_macros.h" -#include "base/rand_util.h" -#include "base/strings/string16.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_split.h" -#include "base/strings/utf_string_conversions.h" -#include "base/time/time.h" -#include "components/services/leveldb/public/cpp/util.h" -#include "content/common/dom_storage/dom_storage_map.h" -#include "content/renderer/dom_storage/local_storage_area.h" -#include "content/renderer/dom_storage/local_storage_cached_areas.h" -#include "content/renderer/dom_storage/session_web_storage_namespace_impl.h" -#include "content/renderer/render_thread_impl.h" -#include "mojo/public/cpp/bindings/strong_associated_binding.h" -#include "third_party/blink/public/mojom/dom_storage/session_storage_namespace.mojom.h" -#include "third_party/blink/public/mojom/dom_storage/storage_partition_service.mojom.h" -#include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h" -#include "third_party/blink/public/platform/web_url.h" -#include "third_party/blink/public/web/web_storage_event_dispatcher.h" - -namespace content { - -namespace { - -// Don't change or reorder any of the values in this enum, as these values -// are serialized on disk. -enum class StorageFormat : uint8_t { UTF16 = 0, Latin1 = 1 }; - -class GetAllCallback : public blink::mojom::StorageAreaGetAllCallback { - public: - static blink::mojom::StorageAreaGetAllCallbackAssociatedPtrInfo CreateAndBind( - base::OnceCallback<void(bool)> callback) { - blink::mojom::StorageAreaGetAllCallbackAssociatedPtrInfo ptr_info; - auto request = mojo::MakeRequest(&ptr_info); - mojo::MakeStrongAssociatedBinding( - base::WrapUnique(new GetAllCallback(std::move(callback))), - std::move(request)); - return ptr_info; - } - - private: - explicit GetAllCallback(base::OnceCallback<void(bool)> callback) - : m_callback(std::move(callback)) {} - void Complete(bool success) override { std::move(m_callback).Run(success); } - - base::OnceCallback<void(bool)> m_callback; -}; - -} // namespace - -// These methods are used to pack and unpack the page_url/storage_area_id into -// source strings to/from the browser. -std::string PackSource(const GURL& page_url, - const std::string& storage_area_id) { - return page_url.spec() + "\n" + storage_area_id; -} - -void UnpackSource(const std::string& source, - GURL* page_url, - std::string* storage_area_id) { - std::vector<std::string> result = base::SplitString( - source, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); - DCHECK_EQ(result.size(), 2u); - *page_url = GURL(result[0]); - *storage_area_id = result[1]; -} - -LocalStorageCachedArea::LocalStorageCachedArea( - const std::string& namespace_id, - const url::Origin& origin, - blink::mojom::SessionStorageNamespace* session_namespace, - LocalStorageCachedAreas* cached_areas, - blink::scheduler::WebThreadScheduler* main_thread_scheduler) - : namespace_id_(namespace_id), - origin_(origin), - binding_(this), - cached_areas_(cached_areas), - main_thread_scheduler_(main_thread_scheduler), - weak_factory_(this) { - DCHECK(!namespace_id_.empty()); - blink::mojom::StorageAreaAssociatedPtrInfo wrapper_ptr_info; - session_namespace->OpenArea(origin_, mojo::MakeRequest(&wrapper_ptr_info)); - leveldb_.Bind(std::move(wrapper_ptr_info), - main_thread_scheduler->IPCTaskRunner()); - blink::mojom::StorageAreaObserverAssociatedPtrInfo ptr_info; - binding_.Bind(mojo::MakeRequest(&ptr_info), - main_thread_scheduler->IPCTaskRunner()); - leveldb_->AddObserver(std::move(ptr_info)); -} - -LocalStorageCachedArea::LocalStorageCachedArea( - const url::Origin& origin, - blink::mojom::StoragePartitionService* storage_partition_service, - LocalStorageCachedAreas* cached_areas, - blink::scheduler::WebThreadScheduler* main_thread_scheduler) - : origin_(origin), - binding_(this), - cached_areas_(cached_areas), - main_thread_scheduler_(main_thread_scheduler), - weak_factory_(this) { - DCHECK(namespace_id_.empty()); - blink::mojom::StorageAreaPtrInfo wrapper_ptr_info; - storage_partition_service->OpenLocalStorage( - origin_, mojo::MakeRequest(&wrapper_ptr_info)); - leveldb_.Bind(std::move(wrapper_ptr_info), - main_thread_scheduler->IPCTaskRunner()); - blink::mojom::StorageAreaObserverAssociatedPtrInfo ptr_info; - binding_.Bind(mojo::MakeRequest(&ptr_info), - main_thread_scheduler->IPCTaskRunner()); - leveldb_->AddObserver(std::move(ptr_info)); -} - -LocalStorageCachedArea::~LocalStorageCachedArea() {} - -unsigned LocalStorageCachedArea::GetLength() { - EnsureLoaded(); - return map_->Length(); -} - -base::NullableString16 LocalStorageCachedArea::GetKey( - unsigned index, - bool* did_decrease_iterator) { - EnsureLoaded(); - return map_->Key(index, did_decrease_iterator); -} - -base::NullableString16 LocalStorageCachedArea::GetItem( - const base::string16& key) { - EnsureLoaded(); - return map_->GetItem(key); -} - -bool LocalStorageCachedArea::SetItem(const base::string16& key, - const base::string16& value, - const GURL& page_url, - const std::string& storage_area_id) { - // A quick check to reject obviously overbudget items to avoid priming the - // cache. - if ((key.length() + value.length()) * sizeof(base::char16) > - kPerStorageAreaQuota) - return false; - - EnsureLoaded(); - bool result = false; - base::NullableString16 old_nullable_value; - if (should_send_old_value_on_mutations_) - result = map_->SetItem(key, value, &old_nullable_value); - else - result = map_->SetItem(key, value, nullptr); - if (!result) - return false; - - // Determine data formats. - bool is_session_storage = IsSessionStorage(); - FormatOption key_format = is_session_storage - ? FormatOption::kSessionStorageForceUTF8 - : FormatOption::kLocalStorageDetectFormat; - FormatOption value_format = is_session_storage - ? FormatOption::kSessionStorageForceUTF16 - : FormatOption::kLocalStorageDetectFormat; - - // Ignore mutations to |key| until OnSetItemComplete. - ignore_key_mutations_[key]++; - base::Optional<std::vector<uint8_t>> optional_old_value; - if (!old_nullable_value.is_null()) - optional_old_value = - String16ToUint8Vector(old_nullable_value.string(), value_format); - - blink::WebScopedVirtualTimePauser virtual_time_pauser = - main_thread_scheduler_->CreateWebScopedVirtualTimePauser( - "LocalStorageCachedArea"); - virtual_time_pauser.PauseVirtualTime(); - leveldb_->Put(String16ToUint8Vector(key, key_format), - String16ToUint8Vector(value, value_format), optional_old_value, - PackSource(page_url, storage_area_id), - base::BindOnce(&LocalStorageCachedArea::OnSetItemComplete, - weak_factory_.GetWeakPtr(), key, - std::move(virtual_time_pauser))); - if (IsSessionStorage() && - (old_nullable_value.is_null() || old_nullable_value.string() != value)) { - blink::WebStorageArea* originating_area = areas_[storage_area_id]; - DCHECK_NE(nullptr, originating_area); - SessionWebStorageNamespaceImpl session_namespace_for_event_dispatch( - namespace_id_, nullptr); - blink::WebStorageEventDispatcher::DispatchSessionStorageEvent( - blink::WebString::FromUTF16(key), - blink::WebString::FromUTF16(old_nullable_value), - blink::WebString::FromUTF16(value), origin_.GetURL(), page_url, - session_namespace_for_event_dispatch, originating_area); - } - return true; -} - -void LocalStorageCachedArea::RemoveItem(const base::string16& key, - const GURL& page_url, - const std::string& storage_area_id) { - EnsureLoaded(); - bool result = false; - base::string16 old_value; - if (should_send_old_value_on_mutations_) - result = map_->RemoveItem(key, &old_value); - else - result = map_->RemoveItem(key, nullptr); - if (!result) - return; - - // Determine data formats. - bool is_session_storage = IsSessionStorage(); - FormatOption key_format = is_session_storage - ? FormatOption::kSessionStorageForceUTF8 - : FormatOption::kLocalStorageDetectFormat; - FormatOption value_format = is_session_storage - ? FormatOption::kSessionStorageForceUTF16 - : FormatOption::kLocalStorageDetectFormat; - - // Ignore mutations to |key| until OnRemoveItemComplete. - ignore_key_mutations_[key]++; - base::Optional<std::vector<uint8_t>> optional_old_value; - if (should_send_old_value_on_mutations_) - optional_old_value = String16ToUint8Vector(old_value, value_format); - - blink::WebScopedVirtualTimePauser virtual_time_pauser = - main_thread_scheduler_->CreateWebScopedVirtualTimePauser( - "LocalStorageCachedArea"); - virtual_time_pauser.PauseVirtualTime(); - leveldb_->Delete(String16ToUint8Vector(key, key_format), optional_old_value, - PackSource(page_url, storage_area_id), - base::BindOnce(&LocalStorageCachedArea::OnRemoveItemComplete, - weak_factory_.GetWeakPtr(), key, - std::move(virtual_time_pauser))); - if (IsSessionStorage() && old_value != base::string16()) { - blink::WebStorageArea* originating_area = areas_[storage_area_id]; - DCHECK_NE(nullptr, originating_area); - SessionWebStorageNamespaceImpl session_namespace_for_event_dispatch( - namespace_id_, nullptr); - blink::WebStorageEventDispatcher::DispatchSessionStorageEvent( - blink::WebString::FromUTF16(key), - blink::WebString::FromUTF16(old_value), blink::WebString(), - origin_.GetURL(), page_url, session_namespace_for_event_dispatch, - originating_area); - } -} - -void LocalStorageCachedArea::Clear(const GURL& page_url, - const std::string& storage_area_id) { - bool already_empty = false; - if (IsSessionStorage()) { - EnsureLoaded(); - already_empty = map_->Length() == 0u; - } - // No need to prime the cache in this case. - Reset(); - map_ = new DOMStorageMap(kPerStorageAreaQuota); - ignore_all_mutations_ = true; - - blink::WebScopedVirtualTimePauser virtual_time_pauser = - main_thread_scheduler_->CreateWebScopedVirtualTimePauser( - "LocalStorageCachedArea"); - virtual_time_pauser.PauseVirtualTime(); - leveldb_->DeleteAll(PackSource(page_url, storage_area_id), - base::BindOnce(&LocalStorageCachedArea::OnClearComplete, - weak_factory_.GetWeakPtr(), - std::move(virtual_time_pauser))); - if (IsSessionStorage() && !already_empty) { - blink::WebStorageArea* originating_area = areas_[storage_area_id]; - DCHECK_NE(nullptr, originating_area); - SessionWebStorageNamespaceImpl session_namespace_for_event_dispatch( - namespace_id_, nullptr); - blink::WebStorageEventDispatcher::DispatchSessionStorageEvent( - blink::WebString(), blink::WebString(), blink::WebString(), - origin_.GetURL(), page_url, session_namespace_for_event_dispatch, - originating_area); - } -} - -void LocalStorageCachedArea::AreaCreated(LocalStorageArea* area) { - areas_[area->id()] = area; -} - -void LocalStorageCachedArea::AreaDestroyed(LocalStorageArea* area) { - areas_.erase(area->id()); -} - -// static -base::string16 LocalStorageCachedArea::Uint8VectorToString16( - const std::vector<uint8_t>& input, - FormatOption format_option) { - if (input.empty()) - return base::string16(); - size_t input_size = input.size(); - base::string16 result; - switch (format_option) { - case FormatOption::kSessionStorageForceUTF16: - if (input_size % sizeof(base::char16) != 0) { - // TODO(mek): Better error recovery when corrupt (or otherwise invalid) - // data is detected. - LOCAL_HISTOGRAM_BOOLEAN("LocalStorageCachedArea.CorruptData", true); - LOG(ERROR) << "Corrupt data in domstorage"; - return base::string16(); - } - result.resize(input_size / sizeof(base::char16)); - std::memcpy(&result[0], input.data(), input_size); - return result; - case FormatOption::kSessionStorageForceUTF8: - // Encoding / codepoint errors are ignored on purpose. - return base::UTF8ToUTF16(leveldb::Uint8VectorToStringPiece(input)); - case FormatOption::kLocalStorageDetectFormat: - break; - } - StorageFormat format = static_cast<StorageFormat>(input[0]); - const size_t payload_size = input_size - 1; - bool corrupt = false; - switch (format) { - case StorageFormat::UTF16: - if (payload_size % sizeof(base::char16) != 0) { - corrupt = true; - break; - } - result.resize(payload_size / sizeof(base::char16)); - std::memcpy(&result[0], input.data() + 1, payload_size); - break; - case StorageFormat::Latin1: - result.resize(payload_size); - std::copy(input.begin() + 1, input.end(), result.begin()); - break; - default: - corrupt = true; - } - if (corrupt) { - // TODO(mek): Better error recovery when corrupt (or otherwise invalid) data - // is detected. - LOCAL_HISTOGRAM_BOOLEAN("LocalStorageCachedArea.CorruptData", true); - LOG(ERROR) << "Corrupt data in localstorage"; - return base::string16(); - } - return result; -} - -// static -std::vector<uint8_t> LocalStorageCachedArea::String16ToUint8Vector( - const base::string16& input, - FormatOption format_option) { - switch (format_option) { - case FormatOption::kSessionStorageForceUTF16: { - std::vector<uint8_t> result; - result.reserve(input.size() * sizeof(base::char16)); - const uint8_t* data = reinterpret_cast<const uint8_t*>(input.data()); - result.insert(result.begin(), data, - data + input.size() * sizeof(base::char16)); - return result; - } - case FormatOption::kSessionStorageForceUTF8: { - // Encoding / codepoint errors are ignored on purpose. - std::string utf8 = base::UTF16ToUTF8(base::StringPiece16(input)); - return leveldb::StdStringToUint8Vector(utf8); - } - case FormatOption::kLocalStorageDetectFormat: - break; - } - bool is_8bit = true; - for (const auto& c : input) { - if (c & 0xff00) { - is_8bit = false; - break; - } - } - if (is_8bit) { - std::vector<uint8_t> result(input.size() + 1); - result[0] = static_cast<uint8_t>(StorageFormat::Latin1); - std::copy(input.begin(), input.end(), result.begin() + 1); - return result; - } - const uint8_t* data = reinterpret_cast<const uint8_t*>(input.data()); - std::vector<uint8_t> result; - result.reserve(input.size() * sizeof(base::char16) + 1); - result.push_back(static_cast<uint8_t>(StorageFormat::UTF16)); - result.insert(result.end(), data, data + input.size() * sizeof(base::char16)); - return result; -} - -void LocalStorageCachedArea::KeyAdded(const std::vector<uint8_t>& key, - const std::vector<uint8_t>& value, - const std::string& source) { - DCHECK(!IsSessionStorage()); - base::NullableString16 null_value; - KeyAddedOrChanged(key, value, null_value, source); -} - -void LocalStorageCachedArea::KeyChanged(const std::vector<uint8_t>& key, - const std::vector<uint8_t>& new_value, - const std::vector<uint8_t>& old_value, - const std::string& source) { - DCHECK(!IsSessionStorage()); - base::NullableString16 old_value_str( - Uint8VectorToString16(old_value, FormatOption::kLocalStorageDetectFormat), - false); - KeyAddedOrChanged(key, new_value, old_value_str, source); -} - -void LocalStorageCachedArea::KeyDeleted(const std::vector<uint8_t>& key, - const std::vector<uint8_t>& old_value, - const std::string& source) { - DCHECK(!IsSessionStorage()); - GURL page_url; - std::string storage_area_id; - UnpackSource(source, &page_url, &storage_area_id); - - base::string16 key_string = - Uint8VectorToString16(key, FormatOption::kLocalStorageDetectFormat); - - blink::WebStorageArea* originating_area = nullptr; - if (areas_.find(storage_area_id) != areas_.end()) { - // The source storage area is in this process. - originating_area = areas_[storage_area_id]; - } else if (map_ && !ignore_all_mutations_) { - // This was from another process or the storage area is gone. If the former, - // remove it from our cache if we haven't already changed it and are waiting - // for the confirmation callback. In the latter case, we won't do anything - // because ignore_key_mutations_ won't be updated until the callback runs. - if (ignore_key_mutations_.find(key_string) == ignore_key_mutations_.end()) - map_->RemoveItem(key_string, nullptr); - } - - blink::WebStorageEventDispatcher::DispatchLocalStorageEvent( - blink::WebString::FromUTF16(key_string), - blink::WebString::FromUTF16(Uint8VectorToString16( - old_value, FormatOption::kLocalStorageDetectFormat)), - blink::WebString(), origin_.GetURL(), page_url, originating_area); -} - -void LocalStorageCachedArea::AllDeleted(const std::string& source) { - GURL page_url; - std::string storage_area_id; - UnpackSource(source, &page_url, &storage_area_id); - - blink::WebStorageArea* originating_area = nullptr; - if (areas_.find(storage_area_id) != areas_.end()) { - // The source storage area is in this process. - originating_area = areas_[storage_area_id]; - } else if (map_ && !ignore_all_mutations_) { - scoped_refptr<DOMStorageMap> old = map_; - map_ = new DOMStorageMap(kPerStorageAreaQuota); - - // We have to retain local additions which happened after this clear - // operation from another process. - auto iter = ignore_key_mutations_.begin(); - while (iter != ignore_key_mutations_.end()) { - base::NullableString16 value = old->GetItem(iter->first); - if (!value.is_null()) - map_->SetItem(iter->first, value.string(), nullptr); - ++iter; - } - } - - if (IsSessionStorage()) { - SessionWebStorageNamespaceImpl session_namespace_for_event_dispatch( - namespace_id_, nullptr); - blink::WebStorageEventDispatcher::DispatchSessionStorageEvent( - blink::WebString(), blink::WebString(), blink::WebString(), - origin_.GetURL(), page_url, session_namespace_for_event_dispatch, - originating_area); - } else { - blink::WebStorageEventDispatcher::DispatchLocalStorageEvent( - blink::WebString(), blink::WebString(), blink::WebString(), - origin_.GetURL(), page_url, originating_area); - } -} - -void LocalStorageCachedArea::ShouldSendOldValueOnMutations(bool value) { - DCHECK(!IsSessionStorage()); - should_send_old_value_on_mutations_ = value; -} - -void LocalStorageCachedArea::KeyAddedOrChanged( - const std::vector<uint8_t>& key, - const std::vector<uint8_t>& new_value, - const base::NullableString16& old_value, - const std::string& source) { - DCHECK(!IsSessionStorage()); - GURL page_url; - std::string storage_area_id; - UnpackSource(source, &page_url, &storage_area_id); - - base::string16 key_string = - Uint8VectorToString16(key, FormatOption::kLocalStorageDetectFormat); - base::string16 new_value_string = - Uint8VectorToString16(new_value, FormatOption::kLocalStorageDetectFormat); - - blink::WebStorageArea* originating_area = nullptr; - if (areas_.find(storage_area_id) != areas_.end()) { - // The source storage area is in this process. - originating_area = areas_[storage_area_id]; - } else if (map_ && !ignore_all_mutations_) { - // This was from another process or the storage area is gone. If the former, - // apply it to our cache if we haven't already changed it and are waiting - // for the confirmation callback. In the latter case, we won't do anything - // because ignore_key_mutations_ won't be updated until the callback runs. - if (ignore_key_mutations_.find(key_string) == ignore_key_mutations_.end()) { - // We turn off quota checking here to accomodate the over budget allowance - // that's provided in the browser process. - map_->set_quota(std::numeric_limits<int32_t>::max()); - map_->SetItem(key_string, new_value_string, nullptr); - map_->set_quota(kPerStorageAreaQuota); - } - } - - blink::WebStorageEventDispatcher::DispatchLocalStorageEvent( - blink::WebString::FromUTF16(key_string), - blink::WebString::FromUTF16(old_value), - blink::WebString::FromUTF16(new_value_string), origin_.GetURL(), page_url, - originating_area); -} - -void LocalStorageCachedArea::EnsureLoaded() { - if (map_) - return; - - base::TimeTicks before = base::TimeTicks::Now(); - ignore_all_mutations_ = true; - bool success = false; - std::vector<blink::mojom::KeyValuePtr> data; - leveldb_->GetAll(GetAllCallback::CreateAndBind( - base::BindOnce(&LocalStorageCachedArea::OnGetAllComplete, - weak_factory_.GetWeakPtr())), - &success, &data); - - DOMStorageValuesMap values; - bool is_session_storage = IsSessionStorage(); - FormatOption key_format = is_session_storage - ? FormatOption::kSessionStorageForceUTF8 - : FormatOption::kLocalStorageDetectFormat; - FormatOption value_format = is_session_storage - ? FormatOption::kSessionStorageForceUTF16 - : FormatOption::kLocalStorageDetectFormat; - for (size_t i = 0; i < data.size(); ++i) { - values[Uint8VectorToString16(data[i]->key, key_format)] = - base::NullableString16( - Uint8VectorToString16(data[i]->value, value_format), false); - } - - map_ = new DOMStorageMap(kPerStorageAreaQuota); - map_->SwapValues(&values); - - base::TimeDelta time_to_prime = base::TimeTicks::Now() - before; - UMA_HISTOGRAM_TIMES("LocalStorage.MojoTimeToPrime", time_to_prime); - - size_t local_storage_size_kb = map_->storage_used() / 1024; - // Track localStorage size, from 0-6MB. Note that the maximum size should be - // 5MB, but we add some slop since we want to make sure the max size is always - // above what we see in practice, since histograms can't change. - UMA_HISTOGRAM_CUSTOM_COUNTS("LocalStorage.MojoSizeInKB", - local_storage_size_kb, - 1, 6 * 1024, 50); - if (local_storage_size_kb < 100) { - UMA_HISTOGRAM_TIMES("LocalStorage.MojoTimeToPrimeForUnder100KB", - time_to_prime); - } else if (local_storage_size_kb < 1000) { - UMA_HISTOGRAM_TIMES("LocalStorage.MojoTimeToPrimeFor100KBTo1MB", - time_to_prime); - } else { - UMA_HISTOGRAM_TIMES("LocalStorage.MojoTimeToPrimeFor1MBTo5MB", - time_to_prime); - } -} - -void LocalStorageCachedArea::OnSetItemComplete( - const base::string16& key, - blink::WebScopedVirtualTimePauser, - bool success) { - if (!success) { - Reset(); - return; - } - - auto found = ignore_key_mutations_.find(key); - DCHECK(found != ignore_key_mutations_.end()); - if (--found->second == 0) - ignore_key_mutations_.erase(found); -} - -void LocalStorageCachedArea::OnRemoveItemComplete( - const base::string16& key, - blink::WebScopedVirtualTimePauser, - bool success) { - DCHECK(success); - auto found = ignore_key_mutations_.find(key); - DCHECK(found != ignore_key_mutations_.end()); - if (--found->second == 0) - ignore_key_mutations_.erase(found); -} - -void LocalStorageCachedArea::OnClearComplete(blink::WebScopedVirtualTimePauser, - bool success) { - DCHECK(success); - DCHECK(ignore_all_mutations_); - ignore_all_mutations_ = false; -} - -void LocalStorageCachedArea::OnGetAllComplete(bool success) { - // Since the GetAll method is synchronous, we need this asynchronously - // delivered notification to avoid applying changes to the returned array - // that we already have. - DCHECK(success); - DCHECK(ignore_all_mutations_); - ignore_all_mutations_ = false; -} - -void LocalStorageCachedArea::Reset() { - map_ = nullptr; - ignore_key_mutations_.clear(); - ignore_all_mutations_ = false; - weak_factory_.InvalidateWeakPtrs(); -} - -} // namespace content
diff --git a/content/renderer/dom_storage/local_storage_cached_area.h b/content/renderer/dom_storage/local_storage_cached_area.h deleted file mode 100644 index 62b7e83..0000000 --- a/content/renderer/dom_storage/local_storage_cached_area.h +++ /dev/null
@@ -1,166 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_DOM_STORAGE_LOCAL_STORAGE_CACHED_AREA_H_ -#define CONTENT_RENDERER_DOM_STORAGE_LOCAL_STORAGE_CACHED_AREA_H_ - -#include <map> - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/strings/nullable_string16.h" -#include "content/common/content_export.h" -#include "content/common/dom_storage/dom_storage_map.h" -#include "content/common/possibly_associated_interface_ptr.h" -#include "mojo/public/cpp/bindings/associated_binding.h" -#include "third_party/blink/public/mojom/dom_storage/storage_area.mojom.h" -#include "third_party/blink/public/platform/scheduler/web_scoped_virtual_time_pauser.h" -#include "url/gurl.h" -#include "url/origin.h" - -namespace blink { -namespace mojom { -class SessionStorageNamespace; -class StoragePartitionService; -} // namespace mojom - -namespace scheduler { -class WebThreadScheduler; -} -} // namespace blink - -namespace content { -class LocalStorageArea; -class LocalStorageCachedAreas; - -// An in-process implementation of LocalStorage using a LevelDB Mojo service. -// Maintains a complete cache of the origin's Map of key/value pairs for fast -// access. The cache is primed on first access and changes are written to the -// backend through the level db interface pointer. Mutations originating in -// other processes are applied to the cache via mojom::LevelDBObserver -// callbacks. -// There is one LocalStorageCachedArea for potentially many LocalStorageArea -// objects. -// TODO(dmurph): Rename to remove LocalStorage. -class CONTENT_EXPORT LocalStorageCachedArea - : public blink::mojom::StorageAreaObserver, - public base::RefCounted<LocalStorageCachedArea> { - public: - LocalStorageCachedArea( - const std::string& namespace_id, - const url::Origin& origin, - blink::mojom::SessionStorageNamespace* session_namespace, - LocalStorageCachedAreas* cached_areas, - blink::scheduler::WebThreadScheduler* main_thread_scheduler); - LocalStorageCachedArea( - const url::Origin& origin, - blink::mojom::StoragePartitionService* storage_partition_service, - LocalStorageCachedAreas* cached_areas, - blink::scheduler::WebThreadScheduler* main_thread_scheduler); - - // These correspond to blink::WebStorageArea. - unsigned GetLength(); - // See DOMStorageMap for the meaning of |did_decrease_iterator|. - base::NullableString16 GetKey(unsigned index, - bool* did_decrease_iterator = nullptr); - base::NullableString16 GetItem(const base::string16& key); - bool SetItem(const base::string16& key, - const base::string16& value, - const GURL& page_url, - const std::string& storage_area_id); - void RemoveItem(const base::string16& key, - const GURL& page_url, - const std::string& storage_area_id); - void Clear(const GURL& page_url, const std::string& storage_area_id); - - // Allow this object to keep track of the LocalStorageAreas corresponding to - // it, which is needed for mutation event notifications. - void AreaCreated(LocalStorageArea* area); - void AreaDestroyed(LocalStorageArea* area); - - const std::string& namespace_id() { return namespace_id_; } - const url::Origin& origin() { return origin_; } - - size_t memory_used() const { return map_ ? map_->memory_used() : 0; } - - bool IsSessionStorage() const { return !namespace_id_.empty(); } - - private: - friend class base::RefCounted<LocalStorageCachedArea>; - ~LocalStorageCachedArea() override; - - friend class LocalStorageCachedAreaTest; - - enum class FormatOption { - kLocalStorageDetectFormat, - kSessionStorageForceUTF16, - kSessionStorageForceUTF8 - }; - - static base::string16 Uint8VectorToString16(const std::vector<uint8_t>& input, - FormatOption format_option); - static std::vector<uint8_t> String16ToUint8Vector(const base::string16& input, - FormatOption format_option); - - // LevelDBObserver: - void KeyAdded(const std::vector<uint8_t>& key, - const std::vector<uint8_t>& value, - const std::string& source) override; - void KeyChanged(const std::vector<uint8_t>& key, - const std::vector<uint8_t>& new_value, - const std::vector<uint8_t>& old_value, - const std::string& source) override; - void KeyDeleted(const std::vector<uint8_t>& key, - const std::vector<uint8_t>& old_value, - const std::string& source) override; - void AllDeleted(const std::string& source) override; - void ShouldSendOldValueOnMutations(bool value) override; - - // Common helper for KeyAdded() and KeyChanged() - void KeyAddedOrChanged(const std::vector<uint8_t>& key, - const std::vector<uint8_t>& new_value, - const base::NullableString16& old_value, - const std::string& source); - - // Synchronously fetches the origin's local storage data if it hasn't been - // fetched already. - void EnsureLoaded(); - - void OnSetItemComplete(const base::string16& key, - blink::WebScopedVirtualTimePauser virtual_time_pauser, - bool success); - void OnRemoveItemComplete( - const base::string16& key, - blink::WebScopedVirtualTimePauser virtual_time_pauser, - bool success); - void OnClearComplete(blink::WebScopedVirtualTimePauser virtual_time_pauser, - bool success); - void OnGetAllComplete(bool success); - - // Resets the object back to its newly constructed state. - void Reset(); - - std::string namespace_id_; - url::Origin origin_; - scoped_refptr<DOMStorageMap> map_; - std::map<base::string16, int> ignore_key_mutations_; - bool ignore_all_mutations_ = false; - // See ShouldSendOldValueOnMutations(). - bool should_send_old_value_on_mutations_ = true; - content::PossiblyAssociatedInterfacePtr<blink::mojom::StorageArea> leveldb_; - mojo::AssociatedBinding<blink::mojom::StorageAreaObserver> binding_; - LocalStorageCachedAreas* cached_areas_; - std::map<std::string, LocalStorageArea*> areas_; - - // Not owned. - blink::scheduler::WebThreadScheduler* main_thread_scheduler_; - - base::WeakPtrFactory<LocalStorageCachedArea> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(LocalStorageCachedArea); -}; - -} // namespace content - -#endif // CONTENT_RENDERER_DOM_STORAGE_LOCAL_STORAGE_CACHED_AREA_H_
diff --git a/content/renderer/dom_storage/local_storage_cached_area_unittest.cc b/content/renderer/dom_storage/local_storage_cached_area_unittest.cc deleted file mode 100644 index cfd3169..0000000 --- a/content/renderer/dom_storage/local_storage_cached_area_unittest.cc +++ /dev/null
@@ -1,336 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/dom_storage/local_storage_cached_area.h" - -#include <stdint.h> - -#include <list> - -#include "base/bind.h" -#include "base/strings/utf_string_conversions.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "content/renderer/dom_storage/local_storage_cached_areas.h" -#include "content/renderer/dom_storage/mock_leveldb_wrapper.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/blink/public/platform/scheduler/test/web_fake_thread_scheduler.h" - -namespace content { - -class LocalStorageCachedAreaTest : public testing::Test { - public: - LocalStorageCachedAreaTest() - : kOrigin(url::Origin::Create(GURL("http://dom_storage/"))), - kKey(base::ASCIIToUTF16("key")), - kValue(base::ASCIIToUTF16("value")), - kPageUrl("http://dom_storage/page"), - kStorageAreaId("7"), - kSource(kPageUrl.spec() + "\n" + kStorageAreaId), - main_thread_scheduler_(new blink::scheduler::WebFakeThreadScheduler()), - cached_areas_(&mock_leveldb_wrapper_, main_thread_scheduler_.get()) {} - - const url::Origin kOrigin; - const base::string16 kKey; - const base::string16 kValue; - const GURL kPageUrl; - const std::string kStorageAreaId; - const std::string kSource; - - bool IsCacheLoaded(LocalStorageCachedArea* cached_area) { - return cached_area->map_.get(); - } - - bool IsIgnoringAllMutations(LocalStorageCachedArea* cached_area) { - return cached_area->ignore_all_mutations_; - } - - bool IsIgnoringKeyMutations(LocalStorageCachedArea* cached_area, - const base::string16& key) { - return cached_area->ignore_key_mutations_.find(key) != - cached_area->ignore_key_mutations_.end(); - } - - void ResetAll(LocalStorageCachedArea* cached_area) { - mock_leveldb_wrapper_.CompleteAllPendingCallbacks(); - mock_leveldb_wrapper_.ResetObservations(); - cached_area->Reset(); - } - - void ResetCacheOnly(LocalStorageCachedArea* cached_area) { - cached_area->Reset(); - } - - static std::vector<uint8_t> String16ToUint8Vector( - const base::string16& input) { - return LocalStorageCachedArea::String16ToUint8Vector( - input, LocalStorageCachedArea::FormatOption::kLocalStorageDetectFormat); - } - - static base::string16 Uint8VectorToString16( - const std::vector<uint8_t>& input) { - return LocalStorageCachedArea::Uint8VectorToString16( - input, LocalStorageCachedArea::FormatOption::kLocalStorageDetectFormat); - } - - protected: - TestBrowserThreadBundle test_browser_thread_bundle_; - MockLevelDBWrapper mock_leveldb_wrapper_; - std::unique_ptr<blink::scheduler::WebThreadScheduler> main_thread_scheduler_; - LocalStorageCachedAreas cached_areas_; -}; - -TEST_F(LocalStorageCachedAreaTest, Basics) { - EXPECT_FALSE(mock_leveldb_wrapper_.HasBindings()); - scoped_refptr<LocalStorageCachedArea> cached_area = - cached_areas_.GetCachedArea(kOrigin); - EXPECT_EQ(kOrigin, cached_area->origin()); - EXPECT_TRUE(mock_leveldb_wrapper_.HasBindings()); - - EXPECT_FALSE(IsCacheLoaded(cached_area.get())); - - const std::string kStorageAreaId = "123"; - EXPECT_EQ(0u, cached_area->GetLength()); - EXPECT_TRUE(cached_area->SetItem(kKey, kValue, kPageUrl, kStorageAreaId)); - EXPECT_EQ(1u, cached_area->GetLength()); - EXPECT_EQ(kKey, cached_area->GetKey(0).string()); - EXPECT_EQ(kValue, cached_area->GetItem(kKey).string()); - cached_area->RemoveItem(kKey, kPageUrl, kStorageAreaId); - EXPECT_EQ(0u, cached_area->GetLength()); -} - -TEST_F(LocalStorageCachedAreaTest, Getters) { - scoped_refptr<LocalStorageCachedArea> cached_area = - cached_areas_.GetCachedArea(kOrigin); - - // GetLength, we expect to see one call to load in the db. - EXPECT_FALSE(IsCacheLoaded(cached_area.get())); - EXPECT_EQ(0u, cached_area->GetLength()); - EXPECT_TRUE(IsCacheLoaded(cached_area.get())); - EXPECT_TRUE(mock_leveldb_wrapper_.observed_get_all()); - EXPECT_EQ(1u, mock_leveldb_wrapper_.pending_callbacks().size()); - EXPECT_TRUE(IsIgnoringAllMutations(cached_area.get())); - mock_leveldb_wrapper_.CompleteAllPendingCallbacks(); - mock_leveldb_wrapper_.Flush(); - EXPECT_FALSE(IsIgnoringAllMutations(cached_area.get())); - - // GetKey, expect the one call to load. - ResetAll(cached_area.get()); - EXPECT_FALSE(IsCacheLoaded(cached_area.get())); - EXPECT_TRUE(cached_area->GetKey(2).is_null()); - EXPECT_TRUE(IsCacheLoaded(cached_area.get())); - EXPECT_TRUE(mock_leveldb_wrapper_.observed_get_all()); - EXPECT_EQ(1u, mock_leveldb_wrapper_.pending_callbacks().size()); - - // GetItem, ditto. - ResetAll(cached_area.get()); - EXPECT_FALSE(IsCacheLoaded(cached_area.get())); - EXPECT_TRUE(cached_area->GetItem(kKey).is_null()); - EXPECT_TRUE(IsCacheLoaded(cached_area.get())); - EXPECT_TRUE(mock_leveldb_wrapper_.observed_get_all()); - EXPECT_EQ(1u, mock_leveldb_wrapper_.pending_callbacks().size()); -} - -TEST_F(LocalStorageCachedAreaTest, Setters) { - scoped_refptr<LocalStorageCachedArea> cached_area = - cached_areas_.GetCachedArea(kOrigin); - - // SetItem, we expect a call to load followed by a call to put in the db. - EXPECT_FALSE(IsCacheLoaded(cached_area.get())); - EXPECT_TRUE(cached_area->SetItem(kKey, kValue, kPageUrl, kStorageAreaId)); - mock_leveldb_wrapper_.Flush(); - EXPECT_TRUE(IsCacheLoaded(cached_area.get())); - EXPECT_TRUE(mock_leveldb_wrapper_.observed_get_all()); - EXPECT_TRUE(mock_leveldb_wrapper_.observed_put()); - EXPECT_EQ(kSource, mock_leveldb_wrapper_.observed_source()); - EXPECT_EQ(String16ToUint8Vector(kKey), mock_leveldb_wrapper_.observed_key()); - EXPECT_EQ(String16ToUint8Vector(kValue), - mock_leveldb_wrapper_.observed_value()); - EXPECT_EQ(2u, mock_leveldb_wrapper_.pending_callbacks().size()); - - // Clear, we expect a just the one call to clear in the db since - // there's no need to load the data prior to deleting it. - ResetAll(cached_area.get()); - EXPECT_FALSE(IsCacheLoaded(cached_area.get())); - cached_area->Clear(kPageUrl, kStorageAreaId); - mock_leveldb_wrapper_.Flush(); - EXPECT_TRUE(IsCacheLoaded(cached_area.get())); - EXPECT_TRUE(mock_leveldb_wrapper_.observed_delete_all()); - EXPECT_EQ(kSource, mock_leveldb_wrapper_.observed_source()); - EXPECT_EQ(1u, mock_leveldb_wrapper_.pending_callbacks().size()); - - // RemoveItem with nothing to remove, expect just one call to load. - ResetAll(cached_area.get()); - EXPECT_FALSE(IsCacheLoaded(cached_area.get())); - cached_area->RemoveItem(kKey, kPageUrl, kStorageAreaId); - mock_leveldb_wrapper_.Flush(); - EXPECT_TRUE(IsCacheLoaded(cached_area.get())); - EXPECT_TRUE(mock_leveldb_wrapper_.observed_get_all()); - EXPECT_FALSE(mock_leveldb_wrapper_.observed_delete()); - EXPECT_EQ(1u, mock_leveldb_wrapper_.pending_callbacks().size()); - - // RemoveItem with something to remove, expect a call to load followed - // by a call to remove. - ResetAll(cached_area.get()); - mock_leveldb_wrapper_ - .mutable_get_all_return_values()[String16ToUint8Vector(kKey)] = - String16ToUint8Vector(kValue); - EXPECT_FALSE(IsCacheLoaded(cached_area.get())); - cached_area->RemoveItem(kKey, kPageUrl, kStorageAreaId); - mock_leveldb_wrapper_.Flush(); - EXPECT_TRUE(IsCacheLoaded(cached_area.get())); - EXPECT_TRUE(mock_leveldb_wrapper_.observed_get_all()); - EXPECT_TRUE(mock_leveldb_wrapper_.observed_delete()); - EXPECT_EQ(kSource, mock_leveldb_wrapper_.observed_source()); - EXPECT_EQ(String16ToUint8Vector(kKey), mock_leveldb_wrapper_.observed_key()); - EXPECT_EQ(2u, mock_leveldb_wrapper_.pending_callbacks().size()); -} - -TEST_F(LocalStorageCachedAreaTest, MutationsAreIgnoredUntilLoadCompletion) { - scoped_refptr<LocalStorageCachedArea> cached_area = - cached_areas_.GetCachedArea(kOrigin); - blink::mojom::StorageAreaObserver* observer = cached_area.get(); - - EXPECT_TRUE(cached_area->GetItem(kKey).is_null()); - EXPECT_TRUE(IsCacheLoaded(cached_area.get())); - EXPECT_TRUE(IsIgnoringAllMutations(cached_area.get())); - - // Before load completion, the mutation should be ignored. - observer->KeyAdded(String16ToUint8Vector(kKey), String16ToUint8Vector(kValue), - kSource); - EXPECT_TRUE(cached_area->GetItem(kKey).is_null()); - - // Call the load completion callback. - mock_leveldb_wrapper_.CompleteOnePendingCallback(true); - mock_leveldb_wrapper_.Flush(); - EXPECT_FALSE(IsIgnoringAllMutations(cached_area.get())); - - // Verify that mutations are now applied. - observer->KeyAdded(String16ToUint8Vector(kKey), String16ToUint8Vector(kValue), - kSource); - EXPECT_EQ(kValue, cached_area->GetItem(kKey).string()); -} - -TEST_F(LocalStorageCachedAreaTest, MutationsAreIgnoredUntilClearCompletion) { - scoped_refptr<LocalStorageCachedArea> cached_area = - cached_areas_.GetCachedArea(kOrigin); - - cached_area->Clear(kPageUrl, kStorageAreaId); - mock_leveldb_wrapper_.Flush(); - EXPECT_TRUE(IsIgnoringAllMutations(cached_area.get())); - mock_leveldb_wrapper_.CompleteOnePendingCallback(true); - mock_leveldb_wrapper_.Flush(); - EXPECT_FALSE(IsIgnoringAllMutations(cached_area.get())); - - // Verify that calling Clear twice works as expected, the first - // completion callback should have been cancelled. - ResetCacheOnly(cached_area.get()); - cached_area->Clear(kPageUrl, kStorageAreaId); - mock_leveldb_wrapper_.Flush(); - EXPECT_TRUE(IsIgnoringAllMutations(cached_area.get())); - cached_area->Clear(kPageUrl, kStorageAreaId); - mock_leveldb_wrapper_.Flush(); - EXPECT_TRUE(IsIgnoringAllMutations(cached_area.get())); - mock_leveldb_wrapper_.CompleteOnePendingCallback(true); - mock_leveldb_wrapper_.Flush(); - EXPECT_TRUE(IsIgnoringAllMutations(cached_area.get())); - mock_leveldb_wrapper_.CompleteOnePendingCallback(true); - mock_leveldb_wrapper_.Flush(); - EXPECT_FALSE(IsIgnoringAllMutations(cached_area.get())); -} - -TEST_F(LocalStorageCachedAreaTest, KeyMutationsAreIgnoredUntilCompletion) { - scoped_refptr<LocalStorageCachedArea> cached_area = - cached_areas_.GetCachedArea(kOrigin); - blink::mojom::StorageAreaObserver* observer = cached_area.get(); - - // SetItem - EXPECT_TRUE(cached_area->SetItem(kKey, kValue, kPageUrl, kStorageAreaId)); - mock_leveldb_wrapper_.CompleteOnePendingCallback(true); // load completion - mock_leveldb_wrapper_.Flush(); - EXPECT_FALSE(IsIgnoringAllMutations(cached_area.get())); - EXPECT_TRUE(IsIgnoringKeyMutations(cached_area.get(), kKey)); - observer->KeyDeleted(String16ToUint8Vector(kKey), {0}, kSource); - mock_leveldb_wrapper_.Flush(); - EXPECT_EQ(kValue, cached_area->GetItem(kKey).string()); - mock_leveldb_wrapper_.CompleteOnePendingCallback(true); // set completion - mock_leveldb_wrapper_.Flush(); - EXPECT_FALSE(IsIgnoringKeyMutations(cached_area.get(), kKey)); - - // RemoveItem - cached_area->RemoveItem(kKey, kPageUrl, kStorageAreaId); - mock_leveldb_wrapper_.Flush(); - EXPECT_TRUE(IsIgnoringKeyMutations(cached_area.get(), kKey)); - mock_leveldb_wrapper_.CompleteOnePendingCallback(true); // remove completion - mock_leveldb_wrapper_.Flush(); - EXPECT_FALSE(IsIgnoringKeyMutations(cached_area.get(), kKey)); - - // Multiple mutations to the same key. - EXPECT_TRUE(cached_area->SetItem(kKey, kValue, kPageUrl, kStorageAreaId)); - cached_area->RemoveItem(kKey, kPageUrl, kStorageAreaId); - mock_leveldb_wrapper_.Flush(); - EXPECT_TRUE(IsIgnoringKeyMutations(cached_area.get(), kKey)); - mock_leveldb_wrapper_.CompleteOnePendingCallback(true); // set completion - mock_leveldb_wrapper_.Flush(); - EXPECT_TRUE(IsIgnoringKeyMutations(cached_area.get(), kKey)); - mock_leveldb_wrapper_.CompleteOnePendingCallback(true); // remove completion - mock_leveldb_wrapper_.Flush(); - EXPECT_FALSE(IsIgnoringKeyMutations(cached_area.get(), kKey)); - - // A failed set item operation should Reset the cache. - EXPECT_TRUE(cached_area->SetItem(kKey, kValue, kPageUrl, kStorageAreaId)); - mock_leveldb_wrapper_.Flush(); - EXPECT_TRUE(IsIgnoringKeyMutations(cached_area.get(), kKey)); - mock_leveldb_wrapper_.CompleteOnePendingCallback(false); - mock_leveldb_wrapper_.Flush(); - EXPECT_FALSE(IsCacheLoaded(cached_area.get())); -} - -TEST_F(LocalStorageCachedAreaTest, StringEncoding) { - base::string16 ascii_key = base::ASCIIToUTF16("simplekey"); - base::string16 non_ascii_key = base::ASCIIToUTF16("key"); - non_ascii_key.push_back(0xd83d); - non_ascii_key.push_back(0xde00); - EXPECT_EQ(Uint8VectorToString16(String16ToUint8Vector(ascii_key)), ascii_key); - EXPECT_EQ(Uint8VectorToString16(String16ToUint8Vector(non_ascii_key)), - non_ascii_key); - EXPECT_LT(String16ToUint8Vector(ascii_key).size(), ascii_key.size() * 2); - EXPECT_GT(String16ToUint8Vector(non_ascii_key).size(), - non_ascii_key.size() * 2); -} - -TEST_F(LocalStorageCachedAreaTest, BrowserDisconnect) { - scoped_refptr<LocalStorageCachedArea> cached_area = - cached_areas_.GetCachedArea(kOrigin); - - // GetLength to prime the cache. - mock_leveldb_wrapper_ - .mutable_get_all_return_values()[String16ToUint8Vector(kKey)] = - String16ToUint8Vector(kValue); - EXPECT_EQ(1u, cached_area->GetLength()); - EXPECT_TRUE(IsCacheLoaded(cached_area.get())); - mock_leveldb_wrapper_.CompleteAllPendingCallbacks(); - mock_leveldb_wrapper_.ResetObservations(); - - // Now disconnect the pipe from the browser, simulating situations where the - // browser might be forced to destroy the LevelDBWrapperImpl. - mock_leveldb_wrapper_.CloseAllBindings(); - - // Getters should still function. - EXPECT_EQ(1u, cached_area->GetLength()); - EXPECT_EQ(kValue, cached_area->GetItem(kKey).string()); - - // And setters should also still function. - cached_area->RemoveItem(kKey, kPageUrl, kStorageAreaId); - EXPECT_EQ(0u, cached_area->GetLength()); - EXPECT_TRUE(cached_area->GetItem(kKey).is_null()); - - // Even resetting the cache should still allow class to function properly. - ResetCacheOnly(cached_area.get()); - EXPECT_TRUE(cached_area->GetItem(kKey).is_null()); - EXPECT_TRUE(cached_area->SetItem(kKey, kValue, kPageUrl, kStorageAreaId)); - EXPECT_EQ(1u, cached_area->GetLength()); - EXPECT_EQ(kValue, cached_area->GetItem(kKey).string()); -} - -} // namespace content
diff --git a/content/renderer/dom_storage/local_storage_cached_areas.cc b/content/renderer/dom_storage/local_storage_cached_areas.cc deleted file mode 100644 index 32dc5d9..0000000 --- a/content/renderer/dom_storage/local_storage_cached_areas.cc +++ /dev/null
@@ -1,190 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/dom_storage/local_storage_cached_areas.h" - -#include "base/metrics/histogram_macros.h" -#include "base/system/sys_info.h" -#include "content/common/dom_storage/dom_storage_types.h" -#include "content/renderer/dom_storage/local_storage_cached_area.h" -#include "content/renderer/render_thread_impl.h" -#include "third_party/blink/public/common/dom_storage/session_storage_namespace_id.h" -#include "third_party/blink/public/common/features.h" -#include "third_party/blink/public/mojom/dom_storage/storage_partition_service.mojom.h" - -namespace content { -namespace { -const size_t kTotalCacheLimitInBytesLowEnd = 1 * 1024 * 1024; -const size_t kTotalCacheLimitInBytes = 5 * 1024 * 1024; - -const constexpr int64_t kDOMStorageObjectPrefix = 0x0001020304050607; -const constexpr int64_t kDOMStorageObjectPostfix = 0x08090a0b0c0d0e0f; - -// An empty namespace is the local storage namespace. -constexpr const char kLocalStorageNamespaceId[] = ""; -} // namespace - -LocalStorageCachedAreas::LocalStorageCachedAreas( - blink::mojom::StoragePartitionService* storage_partition_service, - blink::scheduler::WebThreadScheduler* main_thread_scheduler) - : storage_partition_service_(storage_partition_service), - total_cache_limit_(base::SysInfo::IsLowEndDevice() - ? kTotalCacheLimitInBytesLowEnd - : kTotalCacheLimitInBytes), - main_thread_scheduler_(main_thread_scheduler) {} - -LocalStorageCachedAreas::~LocalStorageCachedAreas() { - CHECK(sequence_checker_.CalledOnValidSequence()); -} - -scoped_refptr<LocalStorageCachedArea> LocalStorageCachedAreas::GetCachedArea( - const url::Origin& origin) { - CHECK(sequence_checker_.CalledOnValidSequence()); - return GetCachedArea(kLocalStorageNamespaceId, origin, - main_thread_scheduler_); -} - -scoped_refptr<LocalStorageCachedArea> -LocalStorageCachedAreas::GetSessionStorageArea(const std::string& namespace_id, - const url::Origin& origin) { - DCHECK_NE(kLocalStorageNamespaceId, namespace_id); - CHECK(sequence_checker_.CalledOnValidSequence()); - return GetCachedArea(namespace_id, origin, main_thread_scheduler_); -} - -void LocalStorageCachedAreas::CloneNamespace( - const std::string& source_namespace, - const std::string& destination_namespace) { - DCHECK(base::FeatureList::IsEnabled(blink::features::kOnionSoupDOMStorage)); - DCHECK_EQ(blink::kSessionStorageNamespaceIdLength, source_namespace.size()); - DCHECK_EQ(blink::kSessionStorageNamespaceIdLength, - destination_namespace.size()); - CHECK(sequence_checker_.CalledOnValidSequence()); - - auto namespace_it = cached_namespaces_.find(source_namespace); - if (namespace_it == cached_namespaces_.end()) { - namespace_it = - cached_namespaces_ - .emplace(std::make_pair(source_namespace, DOMStorageNamespace())) - .first; - storage_partition_service_->OpenSessionStorage( - source_namespace, - mojo::MakeRequest(&namespace_it->second.session_storage_namespace)); - } - DCHECK(namespace_it->second.session_storage_namespace); - namespace_it->second.session_storage_namespace->Clone(destination_namespace); -} - -size_t LocalStorageCachedAreas::TotalCacheSize() const { - CHECK(sequence_checker_.CalledOnValidSequence()); - size_t total = 0; - for (const auto& it : cached_namespaces_) - total += it.second.TotalCacheSize(); - return total; -} - -void LocalStorageCachedAreas::ClearAreasIfNeeded() { - CHECK(sequence_checker_.CalledOnValidSequence()); - if (TotalCacheSize() < total_cache_limit_) - return; - - base::EraseIf(cached_namespaces_, - [](auto& pair) { return pair.second.CleanUpUnusedAreas(); }); -} - -scoped_refptr<LocalStorageCachedArea> LocalStorageCachedAreas::GetCachedArea( - const std::string& namespace_id, - const url::Origin& origin, - blink::scheduler::WebThreadScheduler* scheduler) { - CHECK(sequence_checker_.CalledOnValidSequence()); - // These values are persisted to logs. Entries should not be renumbered and - // numeric values should never be reused. - enum class CacheMetrics { - kMiss = 0, // Area not in cache. - kHit = 1, // Area with refcount = 0 loaded from cache. - kUnused = 2, // Cache was not used. Area had refcount > 0. - kMaxValue = kUnused, - }; - - auto namespace_it = cached_namespaces_.find(namespace_id); - CacheMetrics metric; - scoped_refptr<LocalStorageCachedArea> result; - DOMStorageNamespace* dom_namespace = nullptr; - if (namespace_it == cached_namespaces_.end()) { - metric = CacheMetrics::kMiss; - } else { - dom_namespace = &namespace_it->second; - dom_namespace->CheckPrefixes(); - auto cache_it = dom_namespace->cached_areas.find(origin); - if (cache_it == dom_namespace->cached_areas.end()) { - metric = CacheMetrics::kMiss; - } else { - if (cache_it->second->HasOneRef()) { - metric = CacheMetrics::kHit; - } else { - metric = CacheMetrics::kUnused; - } - result = cache_it->second; - } - } - if (namespace_id == kLocalStorageNamespaceId) - UMA_HISTOGRAM_ENUMERATION("LocalStorage.RendererAreaCacheHit", metric); - else - LOCAL_HISTOGRAM_ENUMERATION("SessionStorage.RendererAreaCacheHit", metric); - - if (!result) { - if (!dom_namespace) { - dom_namespace = &cached_namespaces_[namespace_id]; - } - dom_namespace->CheckPrefixes(); - if (namespace_id == kLocalStorageNamespaceId) { - result = base::MakeRefCounted<LocalStorageCachedArea>( - origin, storage_partition_service_, this, scheduler); - } else { - DCHECK( - base::FeatureList::IsEnabled(blink::features::kOnionSoupDOMStorage)); - if (!dom_namespace->session_storage_namespace) { - storage_partition_service_->OpenSessionStorage( - namespace_id, - mojo::MakeRequest(&dom_namespace->session_storage_namespace)); - } - result = base::MakeRefCounted<LocalStorageCachedArea>( - namespace_id, origin, dom_namespace->session_storage_namespace.get(), - this, scheduler); - } - dom_namespace->cached_areas.emplace(origin, result); - ClearAreasIfNeeded(); - } - return result; -} - -LocalStorageCachedAreas::DOMStorageNamespace::DOMStorageNamespace() - : prefix(kDOMStorageObjectPrefix), postfix(kDOMStorageObjectPostfix) {} -LocalStorageCachedAreas::DOMStorageNamespace::~DOMStorageNamespace() { - CheckPrefixes(); -} -LocalStorageCachedAreas::DOMStorageNamespace::DOMStorageNamespace( - LocalStorageCachedAreas::DOMStorageNamespace&& other) = default; - -void LocalStorageCachedAreas::DOMStorageNamespace::CheckPrefixes() const { - CHECK_EQ(kDOMStorageObjectPrefix, prefix) << "Memory corruption?"; - CHECK_EQ(kDOMStorageObjectPostfix, postfix) << "Memory corruption?"; -} - -size_t LocalStorageCachedAreas::DOMStorageNamespace::TotalCacheSize() const { - CheckPrefixes(); - size_t total = 0; - for (const auto& it : cached_areas) - total += it.second.get()->memory_used(); - return total; -} - -bool LocalStorageCachedAreas::DOMStorageNamespace::CleanUpUnusedAreas() { - CheckPrefixes(); - base::EraseIf(cached_areas, - [](const auto& pair) { return pair.second->HasOneRef(); }); - return cached_areas.empty(); -} - -} // namespace content
diff --git a/content/renderer/dom_storage/local_storage_cached_areas.h b/content/renderer/dom_storage/local_storage_cached_areas.h deleted file mode 100644 index 390b7ed..0000000 --- a/content/renderer/dom_storage/local_storage_cached_areas.h +++ /dev/null
@@ -1,112 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_DOM_STORAGE_LOCAL_STORAGE_CACHED_AREAS_H_ -#define CONTENT_RENDERER_DOM_STORAGE_LOCAL_STORAGE_CACHED_AREAS_H_ - -#include <array> -#include <map> -#include <string> - -#include "base/containers/flat_map.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/sequence_checker.h" -#include "content/common/content_export.h" -#include "third_party/blink/public/mojom/dom_storage/session_storage_namespace.mojom.h" -#include "url/origin.h" - -namespace blink { -namespace mojom { -class StoragePartitionService; -} - -namespace scheduler { -class WebThreadScheduler; -} -} // namespace blink - -namespace content { -class LocalStorageCachedArea; - -// Keeps a map of all the LocalStorageCachedArea objects in a renderer. This is -// needed because we can have n LocalStorageArea objects for the same origin but -// we want just one LocalStorageCachedArea to service them (no point in having -// multiple caches of the same data in the same process). -// TODO(dmurph): Rename to remove LocalStorage. -class CONTENT_EXPORT LocalStorageCachedAreas { - public: - LocalStorageCachedAreas( - blink::mojom::StoragePartitionService* storage_partition_service, - blink::scheduler::WebThreadScheduler* main_thread_scheduler); - ~LocalStorageCachedAreas(); - - // Returns, creating if necessary, a cached storage area for the given origin. - scoped_refptr<LocalStorageCachedArea> - GetCachedArea(const url::Origin& origin); - - scoped_refptr<LocalStorageCachedArea> GetSessionStorageArea( - const std::string& namespace_id, - const url::Origin& origin); - - void CloneNamespace(const std::string& source_namespace, - const std::string& destination_namespace); - - size_t TotalCacheSize() const; - - void set_cache_limit_for_testing(size_t limit) { - CHECK(sequence_checker_.CalledOnValidSequence()); - total_cache_limit_ = limit; - } - - private: - void ClearAreasIfNeeded(); - - scoped_refptr<LocalStorageCachedArea> GetCachedArea( - const std::string& namespace_id, - const url::Origin& origin, - blink::scheduler::WebThreadScheduler* scheduler); - - // TODO(dmurph): Remove release check when crashing has stopped. - // http://crbug.com/857464 - base::SequenceCheckerImpl sequence_checker_; - - blink::mojom::StoragePartitionService* const storage_partition_service_; - - struct DOMStorageNamespace { - public: - DOMStorageNamespace(); - ~DOMStorageNamespace(); - DOMStorageNamespace(DOMStorageNamespace&& other); - DOMStorageNamespace& operator=(DOMStorageNamespace&&) = default; - - void CheckPrefixes() const; - - size_t TotalCacheSize() const; - // Returns true if this namespace is totally unused and can be deleted. - bool CleanUpUnusedAreas(); - - // TODO(dmurph): Remove the prefix & postfix after memory corruption is - // solved. - int64_t prefix; - blink::mojom::SessionStorageNamespacePtr session_storage_namespace; - base::flat_map<url::Origin, scoped_refptr<LocalStorageCachedArea>> - cached_areas; - int64_t postfix; - - DISALLOW_COPY_AND_ASSIGN(DOMStorageNamespace); - }; - - base::flat_map<std::string, DOMStorageNamespace> cached_namespaces_; - size_t total_cache_limit_; - - // Not owned. - blink::scheduler::WebThreadScheduler* main_thread_scheduler_; - - DISALLOW_COPY_AND_ASSIGN(LocalStorageCachedAreas); -}; - -} // namespace content - -#endif // CONTENT_RENDERER_DOM_STORAGE_LOCAL_STORAGE_CACHED_AREAS_H_
diff --git a/content/renderer/dom_storage/local_storage_cached_areas_unittest.cc b/content/renderer/dom_storage/local_storage_cached_areas_unittest.cc deleted file mode 100644 index 83959eb..0000000 --- a/content/renderer/dom_storage/local_storage_cached_areas_unittest.cc +++ /dev/null
@@ -1,96 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/dom_storage/local_storage_cached_areas.h" - -#include "base/guid.h" -#include "base/strings/utf_string_conversions.h" -#include "base/test/scoped_feature_list.h" -#include "base/test/scoped_task_environment.h" -#include "content/renderer/dom_storage/local_storage_cached_area.h" -#include "content/renderer/dom_storage/mock_leveldb_wrapper.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/blink/public/common/features.h" -#include "third_party/blink/public/platform/scheduler/test/web_fake_thread_scheduler.h" - -namespace content { - -class LocalStorageCachedAreasTest : public testing::Test { - // testing::Test: - void TearDown() override { - // Some of these tests close message pipes which serve as master interfaces - // to other associated interfaces; this in turn schedules tasks to invoke - // the associated interfaces' error handlers, and local storage code relies - // on those handlers running in order to avoid memory leaks at shutdown. - scoped_task_environment_.RunUntilIdle(); - } - - base::test::ScopedTaskEnvironment scoped_task_environment_; -}; - -TEST_F(LocalStorageCachedAreasTest, CacheLimit) { - const url::Origin kOrigin = url::Origin::Create(GURL("http://dom_storage1/")); - const url::Origin kOrigin2 = - url::Origin::Create(GURL("http://dom_storage2/")); - const url::Origin kOrigin3 = - url::Origin::Create(GURL("http://dom_storage3/")); - const base::string16 kKey = base::ASCIIToUTF16("key"); - const base::string16 kValue = base::ASCIIToUTF16("value"); - const GURL kPageUrl("http://dom_storage/page"); - const std::string kStorageAreaId("7"); - const size_t kCacheLimit = 100; - - blink::scheduler::WebFakeThreadScheduler thread_scheduler; - - MockLevelDBWrapper mock_leveldb_wrapper; - LocalStorageCachedAreas cached_areas(&mock_leveldb_wrapper, - &thread_scheduler); - cached_areas.set_cache_limit_for_testing(kCacheLimit); - - scoped_refptr<LocalStorageCachedArea> cached_area1 = - cached_areas.GetCachedArea(kOrigin); - cached_area1->SetItem(kKey, kValue, kPageUrl, kStorageAreaId); - const LocalStorageCachedArea* area1_ptr = cached_area1.get(); - size_t expected_total = (kKey.size() + kValue.size()) * sizeof(base::char16); - EXPECT_EQ(expected_total, cached_area1->memory_used()); - EXPECT_EQ(expected_total, cached_areas.TotalCacheSize()); - cached_area1 = nullptr; - - scoped_refptr<LocalStorageCachedArea> cached_area2 = - cached_areas.GetCachedArea(kOrigin2); - cached_area2->SetItem(kKey, kValue, kPageUrl, kStorageAreaId); - // Area for kOrigin should still be alive. - EXPECT_EQ(2 * cached_area2->memory_used(), cached_areas.TotalCacheSize()); - EXPECT_EQ(area1_ptr, cached_areas.GetCachedArea(kOrigin)); - - base::string16 long_value(kCacheLimit, 'a'); - cached_area2->SetItem(kKey, long_value, kPageUrl, kStorageAreaId); - // Cache is cleared when a new area is opened. - scoped_refptr<LocalStorageCachedArea> cached_area3 = - cached_areas.GetCachedArea(kOrigin3); - EXPECT_EQ(cached_area2->memory_used(), cached_areas.TotalCacheSize()); -} - -TEST_F(LocalStorageCachedAreasTest, CloneBeforeGetArea) { - base::test::ScopedFeatureList feature_list; - feature_list.InitAndEnableFeature(blink::features::kOnionSoupDOMStorage); - const std::string kNamespace1 = base::GenerateGUID(); - const std::string kNamespace2 = base::GenerateGUID(); - const url::Origin kOrigin = url::Origin::Create(GURL("http://dom_storage1/")); - - blink::scheduler::WebFakeThreadScheduler thread_scheduler; - - MockLevelDBWrapper mock_leveldb_wrapper; - LocalStorageCachedAreas cached_areas(&mock_leveldb_wrapper, - &thread_scheduler); - - cached_areas.CloneNamespace(kNamespace1, kNamespace2); - - scoped_refptr<LocalStorageCachedArea> cached_area1 = - cached_areas.GetSessionStorageArea(kNamespace1, kOrigin); - EXPECT_TRUE(cached_area1); - EXPECT_EQ(1ul, mock_leveldb_wrapper.NumNamespaceBindings()); -} - -} // namespace content
diff --git a/content/renderer/dom_storage/local_storage_namespace.cc b/content/renderer/dom_storage/local_storage_namespace.cc deleted file mode 100644 index 8ec1992b..0000000 --- a/content/renderer/dom_storage/local_storage_namespace.cc +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/dom_storage/local_storage_namespace.h" - -#include "content/renderer/dom_storage/local_storage_area.h" -#include "content/renderer/dom_storage/local_storage_cached_areas.h" -#include "third_party/blink/public/platform/url_conversion.h" -#include "third_party/blink/public/platform/web_url.h" -#include "url/gurl.h" -#include "url/origin.h" - -using blink::WebStorageArea; -using blink::WebStorageNamespace; - -namespace content { - -LocalStorageNamespace::LocalStorageNamespace( - LocalStorageCachedAreas* local_storage_cached_areas) - : local_storage_cached_areas_(local_storage_cached_areas) { -} - -LocalStorageNamespace::~LocalStorageNamespace() { -} - -blink::WebString LocalStorageNamespace::GetNamespaceId() const { - return blink::WebString(); -} - -WebStorageArea* LocalStorageNamespace::CreateStorageArea( - const blink::WebSecurityOrigin& origin) { - return new LocalStorageArea( - local_storage_cached_areas_->GetCachedArea(origin)); -} - -bool LocalStorageNamespace::IsSameNamespace( - const WebStorageNamespace& other) const { - NOTREACHED() << "This method should only be called for session storage."; - return false; -} - -} // namespace content
diff --git a/content/renderer/dom_storage/local_storage_namespace.h b/content/renderer/dom_storage/local_storage_namespace.h deleted file mode 100644 index b0ce3845..0000000 --- a/content/renderer/dom_storage/local_storage_namespace.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_DOM_STORAGE_LOCAL_STORAGE_NAMESPACE_H_ -#define CONTENT_RENDERER_DOM_STORAGE_LOCAL_STORAGE_NAMESPACE_H_ - -#include "base/macros.h" -#include "third_party/blink/public/platform/web_security_origin.h" -#include "third_party/blink/public/platform/web_storage_namespace.h" - -namespace content { -class LocalStorageCachedAreas; - -class LocalStorageNamespace : public blink::WebStorageNamespace { - public: - // |local_storage_cached_areas| is guaranteed to outlive this object. - explicit LocalStorageNamespace( - LocalStorageCachedAreas* local_storage_cached_areas); - ~LocalStorageNamespace() override; - - // blink::WebStorageNamespace: - blink::WebStorageArea* CreateStorageArea( - const blink::WebSecurityOrigin& origin) override; - - blink::WebString GetNamespaceId() const override; - - bool IsSameNamespace(const WebStorageNamespace&) const override; - - private: - LocalStorageCachedAreas* const local_storage_cached_areas_; - - DISALLOW_COPY_AND_ASSIGN(LocalStorageNamespace); -}; - -} // namespace content - -#endif // CONTENT_RENDERER_DOM_STORAGE_LOCAL_STORAGE_NAMESPACE_H_
diff --git a/content/renderer/dom_storage/mock_leveldb_wrapper.cc b/content/renderer/dom_storage/mock_leveldb_wrapper.cc deleted file mode 100644 index 4f7dead..0000000 --- a/content/renderer/dom_storage/mock_leveldb_wrapper.cc +++ /dev/null
@@ -1,113 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <memory> - -#include "content/renderer/dom_storage/mock_leveldb_wrapper.h" - -#include "base/bind.h" -#include "mojo/public/cpp/bindings/associated_binding_set.h" -#include "third_party/blink/public/mojom/dom_storage/session_storage_namespace.mojom.h" - -namespace content { - -class MockLevelDBWrapper::MockSessionStorageNamespace - : public blink::mojom::SessionStorageNamespace { - public: - MockSessionStorageNamespace(std::string namespace_id, - MockLevelDBWrapper* wrapper) - : namespace_id_(std::move(namespace_id)), wrapper_(wrapper) {} - - void OpenArea(const url::Origin& origin, - blink::mojom::StorageAreaAssociatedRequest database) override { - bindings_.AddBinding(wrapper_, std::move(database)); - } - - void Clone(const std::string& clone_to_namespace) override { - wrapper_->observed_clone_ = true; - wrapper_->observed_clone_from_namespace_ = namespace_id_; - wrapper_->observed_clone_to_namespace_ = clone_to_namespace; - } - - private: - std::string namespace_id_; - MockLevelDBWrapper* wrapper_; - mojo::AssociatedBindingSet<blink::mojom::StorageArea> bindings_; -}; - -MockLevelDBWrapper::MockLevelDBWrapper() {} -MockLevelDBWrapper::~MockLevelDBWrapper() {} - -void MockLevelDBWrapper::OpenLocalStorage( - const url::Origin& origin, - blink::mojom::StorageAreaRequest database) { - bindings_.AddBinding(this, std::move(database)); -} - -void MockLevelDBWrapper::OpenSessionStorage( - const std::string& namespace_id, - blink::mojom::SessionStorageNamespaceRequest request) { - namespace_bindings_.AddBinding( - std::make_unique<MockSessionStorageNamespace>(namespace_id, this), - std::move(request)); -} - -void MockLevelDBWrapper::AddObserver( - blink::mojom::StorageAreaObserverAssociatedPtrInfo observer) {} - -void MockLevelDBWrapper::Put( - const std::vector<uint8_t>& key, - const std::vector<uint8_t>& value, - const base::Optional<std::vector<uint8_t>>& client_old_value, - const std::string& source, - PutCallback callback) { - observed_put_ = true; - observed_key_ = key; - observed_value_ = value; - observed_source_ = source; - pending_callbacks_.push_back(std::move(callback)); -} - -void MockLevelDBWrapper::Delete( - const std::vector<uint8_t>& key, - const base::Optional<std::vector<uint8_t>>& client_old_value, - const std::string& source, - DeleteCallback callback) { - observed_delete_ = true; - observed_key_ = key; - observed_source_ = source; - pending_callbacks_.push_back(std::move(callback)); -} - -void MockLevelDBWrapper::DeleteAll(const std::string& source, - DeleteAllCallback callback) { - observed_delete_all_ = true; - observed_source_ = source; - pending_callbacks_.push_back(std::move(callback)); -} - -void MockLevelDBWrapper::Get(const std::vector<uint8_t>& key, - GetCallback callback) {} - -void MockLevelDBWrapper::GetAll( - blink::mojom::StorageAreaGetAllCallbackAssociatedPtrInfo complete_callback, - GetAllCallback callback) { - blink::mojom::StorageAreaGetAllCallbackAssociatedPtr complete_ptr; - complete_ptr.Bind(std::move(complete_callback)); - pending_callbacks_.push_back( - base::BindOnce(&blink::mojom::StorageAreaGetAllCallback::Complete, - std::move(complete_ptr))); - - observed_get_all_ = true; - std::vector<blink::mojom::KeyValuePtr> all; - for (const auto& it : get_all_return_values_) { - auto kv = blink::mojom::KeyValue::New(); - kv->key = it.first; - kv->value = it.second; - all.push_back(std::move(kv)); - } - std::move(callback).Run(true, std::move(all)); -} - -} // namespace content
diff --git a/content/renderer/dom_storage/mock_leveldb_wrapper.h b/content/renderer/dom_storage/mock_leveldb_wrapper.h deleted file mode 100644 index 2a2d4103..0000000 --- a/content/renderer/dom_storage/mock_leveldb_wrapper.h +++ /dev/null
@@ -1,129 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_DOM_STORAGE_MOCK_LEVELDB_WRAPPER_H -#define CONTENT_RENDERER_DOM_STORAGE_MOCK_LEVELDB_WRAPPER_H - -#include "mojo/public/cpp/bindings/binding_set.h" -#include "mojo/public/cpp/bindings/strong_binding_set.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/blink/public/mojom/dom_storage/session_storage_namespace.mojom.h" -#include "third_party/blink/public/mojom/dom_storage/storage_area.mojom.h" -#include "third_party/blink/public/mojom/dom_storage/storage_partition_service.mojom.h" - -namespace content { - -// Mock LevelDBWrapper that records all read and write events. It also -// implements a mock StoragePartitionService. -class MockLevelDBWrapper : public blink::mojom::StoragePartitionService, - public blink::mojom::StorageArea { - public: - using ResultCallback = base::OnceCallback<void(bool)>; - - MockLevelDBWrapper(); - ~MockLevelDBWrapper() override; - - // StoragePartitionService implementation: - void OpenLocalStorage(const url::Origin& origin, - blink::mojom::StorageAreaRequest database) override; - void OpenSessionStorage( - const std::string& namespace_id, - blink::mojom::SessionStorageNamespaceRequest request) override; - - // StorageArea implementation: - void AddObserver( - blink::mojom::StorageAreaObserverAssociatedPtrInfo observer) override; - - void Put(const std::vector<uint8_t>& key, - const std::vector<uint8_t>& value, - const base::Optional<std::vector<uint8_t>>& client_old_value, - const std::string& source, - PutCallback callback) override; - - void Delete(const std::vector<uint8_t>& key, - const base::Optional<std::vector<uint8_t>>& client_old_value, - const std::string& source, - DeleteCallback callback) override; - - void DeleteAll(const std::string& source, - DeleteAllCallback callback) override; - - void Get(const std::vector<uint8_t>& key, GetCallback callback) override; - - void GetAll(blink::mojom::StorageAreaGetAllCallbackAssociatedPtrInfo - complete_callback, - GetAllCallback callback) override; - - // Methods and members for use by test fixtures. - bool HasBindings() { return !bindings_.empty(); } - - size_t NumNamespaceBindings() { return namespace_bindings_.size(); } - - void ResetObservations() { - observed_get_all_ = false; - observed_put_ = false; - observed_delete_ = false; - observed_delete_all_ = false; - observed_key_.clear(); - observed_value_.clear(); - observed_source_.clear(); - } - - void CompleteAllPendingCallbacks() { - while (!pending_callbacks_.empty()) - CompleteOnePendingCallback(true); - } - - void CompleteOnePendingCallback(bool success) { - ASSERT_TRUE(!pending_callbacks_.empty()); - std::move(pending_callbacks_.front()).Run(success); - pending_callbacks_.pop_front(); - } - - void Flush() { bindings_.FlushForTesting(); } - - void CloseAllBindings() { bindings_.CloseAllBindings(); } - - const std::list<ResultCallback>& pending_callbacks() const { - return pending_callbacks_; - } - - bool observed_get_all() const { return observed_get_all_; } - bool observed_put() const { return observed_put_; } - bool observed_delete() const { return observed_delete_; } - bool observed_delete_all() const { return observed_delete_all_; } - const std::vector<uint8_t>& observed_key() const { return observed_key_; } - const std::vector<uint8_t>& observed_value() const { return observed_value_; } - const std::string& observed_source() const { return observed_source_; } - - std::map<std::vector<uint8_t>, std::vector<uint8_t>>& - mutable_get_all_return_values() { - return get_all_return_values_; - } - - private: - class MockSessionStorageNamespace; - - std::list<ResultCallback> pending_callbacks_; - bool observed_get_all_ = false; - bool observed_put_ = false; - bool observed_delete_ = false; - bool observed_delete_all_ = false; - bool observed_clone_ = false; - std::vector<uint8_t> observed_key_; - std::vector<uint8_t> observed_value_; - std::string observed_source_; - std::string observed_clone_from_namespace_; - std::string observed_clone_to_namespace_; - - std::map<std::vector<uint8_t>, std::vector<uint8_t>> get_all_return_values_; - - mojo::BindingSet<blink::mojom::StorageArea> bindings_; - mojo::StrongBindingSet<blink::mojom::SessionStorageNamespace> - namespace_bindings_; -}; - -} // namespace content - -#endif // CONTENT_RENDERER_DOM_STORAGE_MOCK_LEVELDB_WRAPPER_H
diff --git a/content/renderer/dom_storage/session_web_storage_namespace_impl.cc b/content/renderer/dom_storage/session_web_storage_namespace_impl.cc deleted file mode 100644 index b2d9c70b..0000000 --- a/content/renderer/dom_storage/session_web_storage_namespace_impl.cc +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/dom_storage/session_web_storage_namespace_impl.h" - -#include "content/renderer/dom_storage/local_storage_area.h" -#include "content/renderer/dom_storage/local_storage_cached_areas.h" -#include "third_party/blink/public/platform/url_conversion.h" -#include "third_party/blink/public/platform/web_url.h" -#include "url/gurl.h" -#include "url/origin.h" - -using blink::WebStorageArea; -using blink::WebStorageNamespace; - -namespace content { - -SessionWebStorageNamespaceImpl::SessionWebStorageNamespaceImpl( - const std::string& namespace_id, - LocalStorageCachedAreas* local_storage_cached_areas) - : namespace_id_(namespace_id), - local_storage_cached_areas_(local_storage_cached_areas) {} - -SessionWebStorageNamespaceImpl::~SessionWebStorageNamespaceImpl() {} - -WebStorageArea* SessionWebStorageNamespaceImpl::CreateStorageArea( - const blink::WebSecurityOrigin& origin) { - return new LocalStorageArea( - local_storage_cached_areas_->GetSessionStorageArea(namespace_id_, - origin)); -} - -blink::WebString SessionWebStorageNamespaceImpl::GetNamespaceId() const { - return blink::WebString::FromASCII(namespace_id_); -} - -bool SessionWebStorageNamespaceImpl::IsSameNamespace( - const WebStorageNamespace& other) const { - return GetNamespaceId() == other.GetNamespaceId(); -} - -} // namespace content
diff --git a/content/renderer/dom_storage/session_web_storage_namespace_impl.h b/content/renderer/dom_storage/session_web_storage_namespace_impl.h deleted file mode 100644 index 52830aa2..0000000 --- a/content/renderer/dom_storage/session_web_storage_namespace_impl.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_DOM_STORAGE_SESSION_WEB_STORAGE_NAMESPACE_IMPL_H_ -#define CONTENT_RENDERER_DOM_STORAGE_SESSION_WEB_STORAGE_NAMESPACE_IMPL_H_ - -#include "base/macros.h" -#include "third_party/blink/public/platform/web_security_origin.h" -#include "third_party/blink/public/platform/web_storage_namespace.h" - -namespace content { -class LocalStorageCachedAreas; - -class SessionWebStorageNamespaceImpl : public blink::WebStorageNamespace { - public: - // |local_storage_cached_areas| is guaranteed to outlive this object. - SessionWebStorageNamespaceImpl( - const std::string& namespace_id, - LocalStorageCachedAreas* local_storage_cached_areas); - ~SessionWebStorageNamespaceImpl() override; - - // blink::WebStorageNamespace: - blink::WebStorageArea* CreateStorageArea( - const blink::WebSecurityOrigin& origin) override; - blink::WebString GetNamespaceId() const override; - bool IsSameNamespace(const WebStorageNamespace&) const override; - - private: - std::string namespace_id_; - LocalStorageCachedAreas* const local_storage_cached_areas_; - - DISALLOW_COPY_AND_ASSIGN(SessionWebStorageNamespaceImpl); -}; - -} // namespace content - -#endif // CONTENT_RENDERER_DOM_STORAGE_SESSION_WEB_STORAGE_NAMESPACE_IMPL_H_
diff --git a/content/renderer/dom_storage/webstoragearea_impl.cc b/content/renderer/dom_storage/webstoragearea_impl.cc deleted file mode 100644 index f304121..0000000 --- a/content/renderer/dom_storage/webstoragearea_impl.cc +++ /dev/null
@@ -1,83 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/dom_storage/webstoragearea_impl.h" - -#include "base/lazy_instance.h" -#include "base/metrics/histogram_macros.h" -#include "base/strings/utf_string_conversions.h" -#include "base/time/time.h" -#include "content/common/dom_storage/dom_storage_messages.h" -#include "content/renderer/dom_storage/dom_storage_cached_area.h" -#include "content/renderer/dom_storage/dom_storage_dispatcher.h" -#include "content/renderer/render_thread_impl.h" -#include "third_party/blink/public/platform/web_url.h" - -using blink::WebString; -using blink::WebURL; - -namespace content { - -namespace { -using AreaImplMap = base::IDMap<WebStorageAreaImpl*>; -base::LazyInstance<AreaImplMap>::Leaky - g_all_areas_map = LAZY_INSTANCE_INITIALIZER; - -DomStorageDispatcher* dispatcher() { - return RenderThreadImpl::current()->dom_storage_dispatcher(); -} -} // namespace - -// static -WebStorageAreaImpl* WebStorageAreaImpl::FromConnectionId(int id) { - return g_all_areas_map.Pointer()->Lookup(id); -} - -WebStorageAreaImpl::WebStorageAreaImpl(const std::string& namespace_id, - const GURL& origin) - : connection_id_(g_all_areas_map.Pointer()->Add(this)), - cached_area_( - dispatcher()->OpenCachedArea(connection_id_, namespace_id, origin)) {} - -WebStorageAreaImpl::~WebStorageAreaImpl() { - g_all_areas_map.Pointer()->Remove(connection_id_); - if (dispatcher()) - dispatcher()->CloseCachedArea(connection_id_, cached_area_.get()); -} - -unsigned WebStorageAreaImpl::length() { - return cached_area_->GetLength(connection_id_); -} - -WebString WebStorageAreaImpl::Key(unsigned index, bool* did_decrease_iterator) { - return WebString::FromUTF16( - cached_area_->GetKey(connection_id_, index, did_decrease_iterator)); -} - -WebString WebStorageAreaImpl::GetItem(const WebString& key) { - return WebString::FromUTF16( - cached_area_->GetItem(connection_id_, key.Utf16())); -} - -void WebStorageAreaImpl::SetItem(const WebString& key, - const WebString& value, - const WebURL& page_url, - WebStorageArea::Result& result) { - if (!cached_area_->SetItem(connection_id_, key.Utf16(), value.Utf16(), - page_url)) - result = kResultBlockedByQuota; - else - result = kResultOK; -} - -void WebStorageAreaImpl::RemoveItem(const WebString& key, - const WebURL& page_url) { - cached_area_->RemoveItem(connection_id_, key.Utf16(), page_url); -} - -void WebStorageAreaImpl::Clear(const WebURL& page_url) { - cached_area_->Clear(connection_id_, page_url); -} - -} // namespace content
diff --git a/content/renderer/dom_storage/webstoragearea_impl.h b/content/renderer/dom_storage/webstoragearea_impl.h deleted file mode 100644 index e7c6bcd..0000000 --- a/content/renderer/dom_storage/webstoragearea_impl.h +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_DOM_STORAGE_WEBSTORAGEAREA_IMPL_H_ -#define CONTENT_RENDERER_DOM_STORAGE_WEBSTORAGEAREA_IMPL_H_ - -#include <stddef.h> -#include <stdint.h> - -#include "base/memory/ref_counted.h" -#include "third_party/blink/public/platform/web_storage_area.h" -#include "third_party/blink/public/platform/web_string.h" - -class GURL; - -namespace content { - -class DOMStorageCachedArea; - -class WebStorageAreaImpl : public blink::WebStorageArea { - public: - static WebStorageAreaImpl* FromConnectionId(int id); - - WebStorageAreaImpl(const std::string& namespace_id, const GURL& origin); - ~WebStorageAreaImpl() override; - - // See WebStorageArea.h for documentation on these functions. - unsigned length() override; - blink::WebString Key(unsigned index, bool* did_decrease_iterator) override; - blink::WebString GetItem(const blink::WebString& key) override; - void SetItem(const blink::WebString& key, - const blink::WebString& value, - const blink::WebURL& page_url, - WebStorageArea::Result& result) override; - void RemoveItem(const blink::WebString& key, - const blink::WebURL& page_url) override; - void Clear(const blink::WebURL& url) override; - - private: - int connection_id_; - scoped_refptr<DOMStorageCachedArea> cached_area_; -}; - -} // namespace content - -#endif // CONTENT_RENDERER_DOM_STORAGE_WEBSTORAGEAREA_IMPL_H_
diff --git a/content/renderer/dom_storage/webstoragenamespace_impl.cc b/content/renderer/dom_storage/webstoragenamespace_impl.cc deleted file mode 100644 index cc8d7998..0000000 --- a/content/renderer/dom_storage/webstoragenamespace_impl.cc +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/renderer/dom_storage/webstoragenamespace_impl.h" - -#include "base/logging.h" -#include "content/common/dom_storage/dom_storage_types.h" -#include "content/renderer/dom_storage/webstoragearea_impl.h" -#include "third_party/blink/public/platform/url_conversion.h" -#include "third_party/blink/public/platform/web_security_origin.h" -#include "url/gurl.h" -#include "url/origin.h" - -using blink::WebStorageArea; -using blink::WebStorageNamespace; - -namespace content { - -WebStorageNamespaceImpl::WebStorageNamespaceImpl( - const std::string& namespace_id) - : namespace_id_(namespace_id) { - DCHECK(!namespace_id.empty()); -} - -WebStorageNamespaceImpl::~WebStorageNamespaceImpl() { -} - -WebStorageArea* WebStorageNamespaceImpl::CreateStorageArea( - const blink::WebSecurityOrigin& origin) { - return new WebStorageAreaImpl(namespace_id_, url::Origin(origin).GetURL()); -} - -WebStorageNamespace* WebStorageNamespaceImpl::copy() { - // By returning NULL, we're telling WebKit to lazily fetch it the next time - // session storage is used. In the WebViewClient::createView, we do the - // book-keeping necessary to make it a true copy-on-write despite not doing - // anything here, now. - return nullptr; -} - -blink::WebString WebStorageNamespaceImpl::GetNamespaceId() const { - return blink::WebString::FromASCII(namespace_id_); -} - -bool WebStorageNamespaceImpl::IsSameNamespace( - const WebStorageNamespace& other) const { - return GetNamespaceId() == other.GetNamespaceId(); -} - -} // namespace content
diff --git a/content/renderer/dom_storage/webstoragenamespace_impl.h b/content/renderer/dom_storage/webstoragenamespace_impl.h deleted file mode 100644 index 15008e3..0000000 --- a/content/renderer/dom_storage/webstoragenamespace_impl.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_DOM_STORAGE_WEBSTORAGENAMESPACE_IMPL_H_ -#define CONTENT_RENDERER_DOM_STORAGE_WEBSTORAGENAMESPACE_IMPL_H_ - -#include <stdint.h> -#include <string> - -#include "third_party/blink/public/platform/web_storage_namespace.h" - -namespace content { - -class WebStorageNamespaceImpl : public blink::WebStorageNamespace { - public: - explicit WebStorageNamespaceImpl(const std::string& namespace_id); - ~WebStorageNamespaceImpl() override; - - // See WebStorageNamespace.h for documentation on these functions. - blink::WebStorageArea* CreateStorageArea( - const blink::WebSecurityOrigin& origin) override; - virtual blink::WebStorageNamespace* copy(); - blink::WebString GetNamespaceId() const override; - bool IsSameNamespace(const WebStorageNamespace&) const override; - - private: - std::string namespace_id_; -}; - -} // namespace content - -#endif // CONTENT_RENDERER_DOM_STORAGE_WEBSTORAGENAMESPACE_IMPL_H_
diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc index a908f83..0fa36e7 100644 --- a/content/renderer/render_thread_impl.cc +++ b/content/renderer/render_thread_impl.cc
@@ -61,7 +61,6 @@ #include "content/child/thread_safe_sender.h" #include "content/common/buildflags.h" #include "content/common/content_constants_internal.h" -#include "content/common/dom_storage/dom_storage_messages.h" #include "content/common/frame_messages.h" #include "content/common/frame_owner_properties.h" #include "content/common/view_messages.h" @@ -82,9 +81,6 @@ #include "content/public/renderer/render_view_visitor.h" #include "content/renderer/browser_plugin/browser_plugin_manager.h" #include "content/renderer/categorized_worker_pool.h" -#include "content/renderer/dom_storage/dom_storage_dispatcher.h" -#include "content/renderer/dom_storage/webstoragearea_impl.h" -#include "content/renderer/dom_storage/webstoragenamespace_impl.h" #include "content/renderer/effective_connection_type_helper.h" #include "content/renderer/frame_swap_message_queue.h" #include "content/renderer/input/widget_input_handler_manager.h" @@ -746,8 +742,6 @@ auto registry = std::make_unique<service_manager::BinderRegistry>(); InitializeWebKit(registry.get()); - dom_storage_dispatcher_.reset(new DomStorageDispatcher()); - vc_manager_.reset(new VideoCaptureImplManager()); browser_plugin_manager_.reset(new BrowserPluginManager()); @@ -936,9 +930,6 @@ base::DiscardableMemoryAllocator::SetInstance( discardable_shared_memory_manager_.get()); - GetConnector()->BindInterface(mojom::kBrowserServiceName, - mojo::MakeRequest(&storage_partition_service_)); - #if defined(OS_LINUX) render_message_filter()->SetThreadPriority( ChildProcess::current()->io_thread_id(), base::ThreadPriority::DISPLAY); @@ -1098,11 +1089,6 @@ CHECK(result.second) << "Inserting a duplicate item."; } -blink::mojom::StoragePartitionService* -RenderThreadImpl::GetStoragePartitionService() { - return storage_partition_service_.get(); -} - mojom::RendererHost* RenderThreadImpl::GetRendererHost() { if (!renderer_host_) { GetChannel()->GetRemoteAssociatedInterface(&renderer_host_); @@ -1613,10 +1599,6 @@ return true; } - // Some messages are handled by delegates. - if (dom_storage_dispatcher_->OnMessageReceived(msg)) { - return true; - } return false; }
diff --git a/content/renderer/render_thread_impl.h b/content/renderer/render_thread_impl.h index 87b4767..e9e0b11 100644 --- a/content/renderer/render_thread_impl.h +++ b/content/renderer/render_thread_impl.h
@@ -56,8 +56,8 @@ #include "services/viz/public/interfaces/compositing/compositing_mode_watcher.mojom.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" #include "third_party/blink/public/common/user_agent/user_agent_metadata.h" -#include "third_party/blink/public/mojom/dom_storage/storage_partition_service.mojom.h" #include "third_party/blink/public/platform/scheduler/web_rail_mode_observer.h" +#include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h" #include "third_party/blink/public/platform/web_connection_type.h" #include "third_party/blink/public/web/web_memory_statistics.h" #include "ui/gfx/native_widget_types.h" @@ -119,7 +119,6 @@ class AudioRendererMixerManager; class BrowserPluginManager; class CategorizedWorkerPool; -class DomStorageDispatcher; class GpuVideoAcceleratorFactoriesImpl; class LowMemoryModeController; class P2PSocketDispatcher; @@ -291,10 +290,6 @@ return compositor_task_runner_; } - DomStorageDispatcher* dom_storage_dispatcher() const { - return dom_storage_dispatcher_.get(); - } - ResourceDispatcher* resource_dispatcher() const { return resource_dispatcher_.get(); } @@ -438,7 +433,6 @@ int routing_id, mojom::FrameRequest frame); - blink::mojom::StoragePartitionService* GetStoragePartitionService(); mojom::RendererHost* GetRendererHost(); struct RendererMemoryMetrics { @@ -561,7 +555,6 @@ discardable_shared_memory_manager_; // These objects live solely on the render thread. - std::unique_ptr<DomStorageDispatcher> dom_storage_dispatcher_; std::unique_ptr<blink::scheduler::WebThreadScheduler> main_thread_scheduler_; std::unique_ptr<RendererBlinkPlatformImpl> blink_platform_impl_; std::unique_ptr<ResourceDispatcher> resource_dispatcher_; @@ -701,7 +694,6 @@ std::map<int, scoped_refptr<PendingFrameCreate>>; PendingFrameCreateMap pending_frame_creates_; - blink::mojom::StoragePartitionServicePtr storage_partition_service_; mojom::RendererHostAssociatedPtr renderer_host_; blink::AssociatedInterfaceRegistry associated_interfaces_;
diff --git a/content/renderer/renderer_blink_platform_impl.cc b/content/renderer/renderer_blink_platform_impl.cc index 39f6968..8bdf34b 100644 --- a/content/renderer/renderer_blink_platform_impl.cc +++ b/content/renderer/renderer_blink_platform_impl.cc
@@ -41,10 +41,6 @@ #include "content/public/renderer/content_renderer_client.h" #include "content/public/renderer/render_frame.h" #include "content/renderer/blob_storage/webblobregistry_impl.h" -#include "content/renderer/dom_storage/local_storage_cached_areas.h" -#include "content/renderer/dom_storage/local_storage_namespace.h" -#include "content/renderer/dom_storage/session_web_storage_namespace_impl.h" -#include "content/renderer/dom_storage/webstoragenamespace_impl.h" #include "content/renderer/loader/child_url_loader_factory_bundle.h" #include "content/renderer/loader/code_cache_loader_impl.h" #include "content/renderer/loader/resource_dispatcher.h" @@ -130,7 +126,6 @@ using blink::WebRTCPeerConnectionHandler; using blink::WebRTCPeerConnectionHandlerClient; using blink::WebSize; -using blink::WebStorageNamespace; using blink::WebString; using blink::WebURL; using blink::WebVector; @@ -457,48 +452,6 @@ thread->GetRendererHost()->SuddenTerminationChanged(enabled); } -std::unique_ptr<WebStorageNamespace> -RendererBlinkPlatformImpl::CreateLocalStorageNamespace() { - if (!local_storage_cached_areas_) { - local_storage_cached_areas_.reset(new LocalStorageCachedAreas( - RenderThreadImpl::current()->GetStoragePartitionService(), - main_thread_scheduler_)); - } - return std::make_unique<LocalStorageNamespace>( - local_storage_cached_areas_.get()); -} - -std::unique_ptr<blink::WebStorageNamespace> -RendererBlinkPlatformImpl::CreateSessionStorageNamespace( - base::StringPiece namespace_id) { - if (base::FeatureList::IsEnabled(blink::features::kOnionSoupDOMStorage)) { - if (!local_storage_cached_areas_) { - local_storage_cached_areas_.reset(new LocalStorageCachedAreas( - RenderThreadImpl::current()->GetStoragePartitionService(), - main_thread_scheduler_)); - } - return std::make_unique<SessionWebStorageNamespaceImpl>( - namespace_id.as_string(), local_storage_cached_areas_.get()); - } - - return std::make_unique<WebStorageNamespaceImpl>(namespace_id.as_string()); -} - -void RendererBlinkPlatformImpl::CloneSessionStorageNamespace( - const std::string& source_namespace, - const std::string& destination_namespace) { - if (!local_storage_cached_areas_) { - // Some browser tests don't have a RenderThreadImpl. - RenderThreadImpl* render_thread = RenderThreadImpl::current(); - if (!render_thread) - return; - local_storage_cached_areas_.reset(new LocalStorageCachedAreas( - render_thread->GetStoragePartitionService(), main_thread_scheduler_)); - } - local_storage_cached_areas_->CloneNamespace(source_namespace, - destination_namespace); -} - //------------------------------------------------------------------------------ WebString RendererBlinkPlatformImpl::FileSystemCreateOriginIdentifier(
diff --git a/content/renderer/renderer_blink_platform_impl.h b/content/renderer/renderer_blink_platform_impl.h index 88e609e..a7cc63d 100644 --- a/content/renderer/renderer_blink_platform_impl.h +++ b/content/renderer/renderer_blink_platform_impl.h
@@ -51,7 +51,6 @@ namespace content { class BlinkInterfaceProviderImpl; class ChildURLLoaderFactoryBundle; -class LocalStorageCachedAreas; class ThreadSafeSender; class WebDatabaseObserverImpl; @@ -98,10 +97,6 @@ const blink::WebString& cacheStorageCacheName) override; blink::WebString DefaultLocale() override; void SuddenTerminationChanged(bool enabled) override; - std::unique_ptr<blink::WebStorageNamespace> CreateLocalStorageNamespace() - override; - std::unique_ptr<blink::WebStorageNamespace> CreateSessionStorageNamespace( - base::StringPiece namespace_id) override; base::File DatabaseOpenFile(const blink::WebString& vfs_file_name, int desired_flags) override; int DatabaseDeleteFile(const blink::WebString& vfs_file_name, @@ -229,10 +224,6 @@ PossiblyAssociatedInterfacePtr<network::mojom::URLLoaderFactory> CreateNetworkURLLoaderFactory(); - // Clones the source namespace to the destination namespace. - void CloneSessionStorageNamespace(const std::string& source_namespace, - const std::string& destination_namespace); - // Tells this platform that the renderer is locked to a site (i.e., a scheme // plus eTLD+1, such as https://google.com), or to a more specific origin. void SetIsLockedToSite(); @@ -277,8 +268,6 @@ TopLevelBlameContext top_level_blame_context_; - std::unique_ptr<LocalStorageCachedAreas> local_storage_cached_areas_; - std::unique_ptr<BlinkInterfaceProviderImpl> blink_interface_provider_; blink::mojom::WebDatabaseHostPtrInfo web_database_host_info_;
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index d4c7af9..a0afb5c 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -1759,7 +1759,6 @@ "../child/font_warmup_win_unittest.cc", "../common/android/gin_java_bridge_value_unittest.cc", "../common/background_fetch/background_fetch_struct_traits_unittest.cc", - "../common/bluetooth/web_bluetooth_device_id_unittest.cc", "../common/common_param_traits_unittest.cc", "../common/content_security_policy/content_security_policy_unittest.cc", "../common/content_security_policy/csp_context_unittest.cc", @@ -1797,11 +1796,6 @@ "../renderer/categorized_worker_pool_unittest.cc", "../renderer/child_frame_compositing_helper_unittest.cc", "../renderer/compositor/layer_tree_view_unittest.cc", - "../renderer/dom_storage/dom_storage_cached_area_unittest.cc", - "../renderer/dom_storage/local_storage_cached_area_unittest.cc", - "../renderer/dom_storage/local_storage_cached_areas_unittest.cc", - "../renderer/dom_storage/mock_leveldb_wrapper.cc", - "../renderer/dom_storage/mock_leveldb_wrapper.h", "../renderer/frame_swap_message_queue_unittest.cc", "../renderer/input/input_event_prediction_unittest.cc", "../renderer/input/main_thread_event_queue_unittest.cc",
diff --git a/content/test/data/appcache/cache_reuse.html b/content/test/data/appcache/cache_reuse.html new file mode 100644 index 0000000..c43bab3 --- /dev/null +++ b/content/test/data/appcache/cache_reuse.html
@@ -0,0 +1,15 @@ +<!doctype html> +<html manifest="cache_reuse.manifest"> +<meta charset="utf-8"> +<title>OK</title> +<script> +'use strict'; + +applicationCache.addEventListener('cached', () => { + document.title = 'AppCache primed'; +}); +applicationCache.addEventListener('updateready', () => { + document.title = 'AppCache updated'; +}); +</script> +</html> \ No newline at end of file
diff --git a/content/test/data/appcache/cache_reuse.html.mock-http-headers b/content/test/data/appcache/cache_reuse.html.mock-http-headers new file mode 100644 index 0000000..0e97a23 --- /dev/null +++ b/content/test/data/appcache/cache_reuse.html.mock-http-headers
@@ -0,0 +1,3 @@ +HTTP/1.1 200 OK +Content-Type: text/html +Cache-Control: max-age=31536000 \ No newline at end of file
diff --git a/content/test/data/appcache/simple_page_with_manifest.html b/content/test/data/appcache/simple_page_with_manifest.html index f2e03e81..bb120eb 100644 --- a/content/test/data/appcache/simple_page_with_manifest.html +++ b/content/test/data/appcache/simple_page_with_manifest.html
@@ -1,22 +1,18 @@ -<!DOCTYPE html> +<!doctype html> <html manifest="simple_page.manifest"> -<head> - <title>OK</title> - <script type="text/javascript"> - function onCachedEvent() { - window.document.title = "AppCache updated"; - } +<meta charset="utf-8"> +<title>OK</title> +<script> +'use strict'; - function onLoad() { - window.applicationCache.addEventListener('cached', onCachedEvent, false); - } - </script> -</head> +applicationCache.addEventListener('cached', () => { + document.title = 'AppCache updated'; +}); +</script> -<body onload="onLoad()"> - <p><img src="logo.png" width="336" height="69" /></p> - Basic AppCache test. The manifest for this page is specified in the - simple_page.manifest file. The title of the page is set to AppCache updated - if the cache is successfully updated. -</body> + +<p><img src="logo.png" width="336" height="69" /></p> +Basic AppCache test. The manifest for this page is specified in the +simple_page.manifest file. The title of the page is set to AppCache updated +if the cache is successfully updated. </html>
diff --git a/device/fido/mac/credential_metadata.cc b/device/fido/mac/credential_metadata.cc index 8087b3c..118055ab 100644 --- a/device/fido/mac/credential_metadata.cc +++ b/device/fido/mac/credential_metadata.cc
@@ -24,16 +24,19 @@ using cbor::Writer; // The version tag encoded into encrypted credential metadata. -static constexpr uint8_t kVersion = 0x00; +static constexpr uint8_t kVersionLegacy0 = 0x00; + +// The version tag encoded into encrypted credential metadata. +static constexpr uint8_t kVersion = 0x01; static constexpr size_t kNonceLength = 12; namespace { -// MakeAad returns the concatenation of |kVersion| and |rp_id|, +// MakeAad returns the concatenation of |version| and |rp_id|, // which is used as the additional authenticated data (AAD) input to the AEAD. -std::string MakeAad(const std::string& rp_id) { - return std::string(1, kVersion) + rp_id; +std::string MakeAad(const uint8_t version, const std::string& rp_id) { + return std::string(1, version) + rp_id; } // Cryptor provides methods for encrypting and authenticating credential @@ -173,33 +176,38 @@ } // namespace // static -UserEntity UserEntity::FromPublicKeyCredentialUserEntity( - const PublicKeyCredentialUserEntity& user) { - return UserEntity(user.id, user.name.value_or(""), - user.display_name.value_or("")); +CredentialMetadata CredentialMetadata::FromPublicKeyCredentialUserEntity( + const PublicKeyCredentialUserEntity& user, + bool is_resident) { + return CredentialMetadata(user.id, user.name.value_or(""), + user.display_name.value_or(""), is_resident); } -PublicKeyCredentialUserEntity UserEntity::ToPublicKeyCredentialUserEntity() { - auto user_entity = PublicKeyCredentialUserEntity(id); - if (!name.empty()) { - user_entity.name = name; +PublicKeyCredentialUserEntity +CredentialMetadata::ToPublicKeyCredentialUserEntity() { + PublicKeyCredentialUserEntity user_entity(user_id); + if (!user_name.empty()) { + user_entity.name = user_name; } - if (!display_name.empty()) { - user_entity.display_name = display_name; + if (!user_display_name.empty()) { + user_entity.display_name = user_display_name; } return user_entity; } -UserEntity::UserEntity(std::vector<uint8_t> id_, - std::string name_, - std::string display_name_) - : id(std::move(id_)), - name(std::move(name_)), - display_name(std::move(display_name_)) {} -UserEntity::UserEntity(const UserEntity&) = default; -UserEntity::UserEntity(UserEntity&&) = default; -UserEntity& UserEntity::operator=(UserEntity&&) = default; -UserEntity::~UserEntity() = default; +CredentialMetadata::CredentialMetadata(std::vector<uint8_t> user_id_, + std::string user_name_, + std::string user_display_name_, + bool is_resident_) + : user_id(std::move(user_id_)), + user_name(std::move(user_name_)), + user_display_name(std::move(user_display_name_)), + is_resident(is_resident_) {} +CredentialMetadata::CredentialMetadata(const CredentialMetadata&) = default; +CredentialMetadata::CredentialMetadata(CredentialMetadata&&) = default; +CredentialMetadata& CredentialMetadata::operator=(CredentialMetadata&&) = + default; +CredentialMetadata::~CredentialMetadata() = default; std::string GenerateCredentialMetadataSecret() { static constexpr size_t kSecretSize = 32u; @@ -210,9 +218,10 @@ return secret; } -base::Optional<std::vector<uint8_t>> SealCredentialId(const std::string& secret, - const std::string& rp_id, - const UserEntity& user) { +base::Optional<std::vector<uint8_t>> SealCredentialId( + const std::string& secret, + const std::string& rp_id, + const CredentialMetadata& metadata) { // The first 13 bytes are the version and nonce. std::vector<uint8_t> result(1 + kNonceLength); result[0] = kVersion; @@ -223,19 +232,22 @@ base::span<uint8_t> nonce(result.data() + 1, kNonceLength); RAND_bytes(nonce.data(), nonce.size()); // RAND_bytes always returns 1. - // The remaining bytes are the CBOR-encoded UserEntity, encrypted with + // The remaining bytes are the CBOR-encoded CredentialMetadata, encrypted with // AES-256-GCM and authenticated with the version and RP ID. Value::ArrayValue cbor_user; - cbor_user.emplace_back(Value(user.id)); - cbor_user.emplace_back(Value(user.name, Value::Type::BYTE_STRING)); - cbor_user.emplace_back(Value(user.display_name, Value::Type::BYTE_STRING)); + cbor_user.emplace_back(Value(metadata.user_id)); + cbor_user.emplace_back(Value(metadata.user_name, Value::Type::BYTE_STRING)); + cbor_user.emplace_back( + Value(metadata.user_display_name, Value::Type::BYTE_STRING)); + // TODO(martinkr): Allow creation of resident keys. + cbor_user.emplace_back(Value(false)); base::Optional<std::vector<uint8_t>> pt = Writer::Write(Value(std::move(cbor_user))); if (!pt) { return base::nullopt; } base::Optional<std::string> ciphertext = Cryptor(secret).Seal( - Cryptor::Algorithm::kAes256Gcm, nonce, *pt, MakeAad(rp_id)); + Cryptor::Algorithm::kAes256Gcm, nonce, *pt, MakeAad(kVersion, rp_id)); if (!ciphertext) { return base::nullopt; } @@ -245,25 +257,31 @@ return result; } -base::Optional<UserEntity> UnsealCredentialId( +// UnsealLegacyCredentialId attempts to decrypt a credential ID that has been +// encrypted under the scheme for version 0x00, which is: +// | version | nonce | AEAD(pt=CBOR(user_entity), | +// | (1 byte) | (12 bytes) | nonce=nonce, | +// | | | ad=(version, rpID)) | +// Note the absence of the rk bit, which is always false. +static base::Optional<CredentialMetadata> UnsealLegacyCredentialId( const std::string& secret, const std::string& rp_id, base::span<const uint8_t> credential_id) { // Recover the nonce and check for the correct version byte. Then try to // decrypt the remaining bytes. if (credential_id.size() <= 1 + kNonceLength || - credential_id[0] != kVersion) { + credential_id[0] != kVersionLegacy0) { return base::nullopt; } base::Optional<std::string> plaintext = Cryptor(secret).Unseal( Cryptor::Algorithm::kAes256Gcm, credential_id.subspan(1, kNonceLength), - credential_id.subspan(1 + kNonceLength), MakeAad(rp_id)); + credential_id.subspan(1 + kNonceLength), MakeAad(kVersionLegacy0, rp_id)); if (!plaintext) { return base::nullopt; } - // The recovered plaintext should decode into the UserEntity struct. + // The recovered plaintext should decode into the CredentialMetadata struct. base::Optional<Value> maybe_array = Reader::Read(base::make_span( reinterpret_cast<const uint8_t*>(plaintext->data()), plaintext->size())); if (!maybe_array || !maybe_array->is_array()) { @@ -274,9 +292,47 @@ !array[1].is_bytestring() || !array[2].is_bytestring()) { return base::nullopt; } - return UserEntity(array[0].GetBytestring(), - array[1].GetBytestringAsString().as_string(), - array[2].GetBytestringAsString().as_string()); + return CredentialMetadata(array[0].GetBytestring(), + array[1].GetBytestringAsString().as_string(), + array[2].GetBytestringAsString().as_string(), + /*is_resident=*/false); +} + +base::Optional<CredentialMetadata> UnsealCredentialId( + const std::string& secret, + const std::string& rp_id, + base::span<const uint8_t> credential_id) { + if (!credential_id.empty() && credential_id[0] == kVersionLegacy0) { + return UnsealLegacyCredentialId(secret, rp_id, credential_id); + } + + if (credential_id.size() <= 1 + kNonceLength || + credential_id[0] != kVersion) { + return base::nullopt; + } + + base::Optional<std::string> plaintext = Cryptor(secret).Unseal( + Cryptor::Algorithm::kAes256Gcm, credential_id.subspan(1, kNonceLength), + credential_id.subspan(1 + kNonceLength), MakeAad(kVersion, rp_id)); + if (!plaintext) { + return base::nullopt; + } + + // The recovered plaintext should decode into the CredentialMetadata struct. + base::Optional<Value> maybe_array = Reader::Read(base::make_span( + reinterpret_cast<const uint8_t*>(plaintext->data()), plaintext->size())); + if (!maybe_array || !maybe_array->is_array()) { + return base::nullopt; + } + const Value::ArrayValue& array = maybe_array->GetArray(); + if (array.size() != 4 || !array[0].is_bytestring() || + !array[1].is_bytestring() || !array[2].is_bytestring() || + !array[3].is_bool()) { + return base::nullopt; + } + return CredentialMetadata( + array[0].GetBytestring(), array[1].GetBytestringAsString().as_string(), + array[2].GetBytestringAsString().as_string(), array[3].GetBool()); } base::Optional<std::string> EncodeRpIdAndUserId( @@ -322,6 +378,42 @@ fixed_zero_nonce, ct, empty_ad); } +base::Optional<std::vector<uint8_t>> SealLegacyV0CredentialIdForTestingOnly( + const std::string& secret, + const std::string& rp_id, + const std::vector<uint8_t>& user_id, + const std::string& user_name, + const std::string& user_display_name) { + constexpr uint8_t version = 0x00; + // | version | nonce | AEAD(pt=CBOR(user_entity), | + // | (1 byte) | (12 bytes) | nonce=nonce, | + // | | | ad=(version, rpID)) | + std::vector<uint8_t> result(13); + result[0] = version; + base::span<uint8_t> nonce(result.data() + 1, 12); + RAND_bytes(nonce.data(), nonce.size()); // RAND_bytes always returns 1. + + Value::ArrayValue cbor_user; + cbor_user.emplace_back(Value(user_id)); + cbor_user.emplace_back(Value(user_name, Value::Type::BYTE_STRING)); + cbor_user.emplace_back(Value(user_display_name, Value::Type::BYTE_STRING)); + base::Optional<std::vector<uint8_t>> pt = + Writer::Write(Value(std::move(cbor_user))); + if (!pt) { + return base::nullopt; + } + std::string aad = std::string(1, version) + rp_id; + base::Optional<std::string> ciphertext = + Cryptor(secret).Seal(Cryptor::Algorithm::kAes256Gcm, nonce, *pt, aad); + if (!ciphertext) { + return base::nullopt; + } + base::span<const char> cts(reinterpret_cast<const char*>(ciphertext->data()), + ciphertext->size()); + result.insert(result.end(), cts.begin(), cts.end()); + return result; +} + } // namespace mac } // namespace fido } // namespace device
diff --git a/device/fido/mac/credential_metadata.h b/device/fido/mac/credential_metadata.h index 80bd6386..17e5dc4 100644 --- a/device/fido/mac/credential_metadata.h +++ b/device/fido/mac/credential_metadata.h
@@ -28,25 +28,36 @@ namespace fido { namespace mac { -// UserEntity loosely corresponds to a PublicKeyCredentialUserEntity -// (https://www.w3.org/TR/webauthn/#sctn-user-credential-params). Values of -// this type should be moved whenever possible. -struct COMPONENT_EXPORT(DEVICE_FIDO) UserEntity { +// CredentialMetadata is the metadata for a Touch ID credential stored, in an +// encrypted/authenticated format, in the macOS keychain. Values of this type +// should be moved whenever possible. +struct COMPONENT_EXPORT(DEVICE_FIDO) CredentialMetadata { public: - static UserEntity FromPublicKeyCredentialUserEntity( - const PublicKeyCredentialUserEntity&); + static CredentialMetadata FromPublicKeyCredentialUserEntity( + const PublicKeyCredentialUserEntity&, + bool is_resident); - UserEntity(std::vector<uint8_t> id_, std::string name_, std::string display_); - UserEntity(const UserEntity&); - UserEntity(UserEntity&&); - UserEntity& operator=(UserEntity&&); - ~UserEntity(); + CredentialMetadata(std::vector<uint8_t> user_id_, + std::string user_name_, + std::string user_display_name_, + bool is_resident_); + CredentialMetadata(const CredentialMetadata&); + CredentialMetadata(CredentialMetadata&&); + CredentialMetadata& operator=(CredentialMetadata&&); + ~CredentialMetadata(); PublicKeyCredentialUserEntity ToPublicKeyCredentialUserEntity(); - std::vector<uint8_t> id; - std::string name; - std::string display_name; + // The following correspond to the fields of the same name in + // PublicKeyCredentialUserEntity + // (https://www.w3.org/TR/webauthn/#sctn-user-credential-params). + std::vector<uint8_t> user_id; + std::string user_name; + std::string user_display_name; + + // Whether this credential has the resident key (rk) bit and may be returned + // in response to GetAssertion requests with an empty allowList. + bool is_resident; }; // Generates a random secret for encrypting and authenticating credential @@ -61,7 +72,7 @@ COMPONENT_EXPORT(DEVICE_FIDO) std::string GenerateCredentialMetadataSecret(); -// SealCredentialId encrypts the given UserEntity into a credential id. +// SealCredentialId encrypts the given CredentialMetadata into a credential id. // // Credential IDs have following format: // @@ -72,13 +83,15 @@ // with version as 0x00, a random 12-byte nonce, and using AES-256-GCM as the // AEAD. COMPONENT_EXPORT(DEVICE_FIDO) -base::Optional<std::vector<uint8_t>> SealCredentialId(const std::string& secret, - const std::string& rp_id, - const UserEntity& user); +base::Optional<std::vector<uint8_t>> SealCredentialId( + const std::string& secret, + const std::string& rp_id, + const CredentialMetadata& user); -// UnsealCredentialId attempts to decrypt a UserEntity from a credential id. +// UnsealCredentialId attempts to decrypt a CredentialMetadata from a credential +// id. COMPONENT_EXPORT(DEVICE_FIDO) -base::Optional<UserEntity> UnsealCredentialId( +base::Optional<CredentialMetadata> UnsealCredentialId( const std::string& secret, const std::string& rp_id, base::span<const uint8_t> credential_id); @@ -108,6 +121,15 @@ base::Optional<std::string> DecodeRpId(const std::string& secret, const std::string& ciphertext); +// Seals a legacy V0 credential ID. +COMPONENT_EXPORT(DEVICE_FIDO) +base::Optional<std::vector<uint8_t>> SealLegacyV0CredentialIdForTestingOnly( + const std::string& secret, + const std::string& rp_id, + const std::vector<uint8_t>& user_id, + const std::string& user_name, + const std::string& user_display_name); + } // namespace mac } // namespace fido } // namespace device
diff --git a/device/fido/mac/credential_metadata_unittest.cc b/device/fido/mac/credential_metadata_unittest.cc index 79fd748..11f0104f 100644 --- a/device/fido/mac/credential_metadata_unittest.cc +++ b/device/fido/mac/credential_metadata_unittest.cc
@@ -4,6 +4,9 @@ #include "device/fido/mac/credential_metadata.h" +#include "base/logging.h" +#include "components/cbor/values.h" +#include "components/cbor/writer.h" #include "device/fido/public_key_credential_user_entity.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -13,9 +16,10 @@ namespace mac { namespace { -bool UserEqual(const UserEntity& lhs, const UserEntity& rhs) { - return lhs.id == rhs.id && lhs.name == rhs.name && - lhs.display_name == rhs.display_name; +bool MetadataEq(const CredentialMetadata& lhs, const CredentialMetadata& rhs) { + return lhs.user_id == rhs.user_id && lhs.user_name == rhs.user_name && + lhs.user_display_name == rhs.user_display_name && + lhs.is_resident == rhs.is_resident; } base::span<const uint8_t> to_bytes(base::StringPiece in) { @@ -25,15 +29,17 @@ class CredentialMetadataTest : public ::testing::Test { protected: - UserEntity DefaultUser() { - return UserEntity(default_id_, "user", "user@acme.com"); + CredentialMetadata DefaultUser() { + return CredentialMetadata(default_id_, "user", "user@acme.com", + /*is_resident=*/false); } - std::vector<uint8_t> SealCredentialId(UserEntity user) { + std::vector<uint8_t> SealCredentialId(CredentialMetadata user) { return *device::fido::mac::SealCredentialId(key_, rp_id_, std::move(user)); } - UserEntity UnsealCredentialId(base::span<const uint8_t> credential_id) { + CredentialMetadata UnsealCredentialId( + base::span<const uint8_t> credential_id) { return *device::fido::mac::UnsealCredentialId(key_, rp_id_, credential_id); } @@ -57,9 +63,18 @@ TEST_F(CredentialMetadataTest, CredentialId) { std::vector<uint8_t> id = SealCredentialId(DefaultUser()); - EXPECT_EQ(0, (id)[0]); - EXPECT_EQ(54u, id.size()); - EXPECT_TRUE(UserEqual(UnsealCredentialId(id), DefaultUser())); + EXPECT_EQ(1, (id)[0]); + EXPECT_EQ(55u, id.size()); + EXPECT_TRUE(MetadataEq(UnsealCredentialId(id), DefaultUser())); +} + +TEST_F(CredentialMetadataTest, LegacyCredentialId) { + auto user = DefaultUser(); + auto id = SealLegacyV0CredentialIdForTestingOnly( + key_, rp_id_, user.user_id, user.user_name, user.user_display_name); + EXPECT_EQ(0, (*id)[0]); + EXPECT_EQ(54u, id->size()); + EXPECT_TRUE(MetadataEq(UnsealCredentialId(*id), DefaultUser())); } TEST_F(CredentialMetadataTest, CredentialId_IsRandom) { @@ -128,15 +143,19 @@ in.name = "username"; in.display_name = "display name"; in.icon_url = GURL("http://rp.foo/user.png"); - UserEntity out = UserEntity::FromPublicKeyCredentialUserEntity(std::move(in)); - EXPECT_EQ(user_id, out.id); - EXPECT_EQ("username", out.name); - EXPECT_EQ("display name", out.display_name); + CredentialMetadata out = + CredentialMetadata::FromPublicKeyCredentialUserEntity( + std::move(in), /*is_resident=*/false); + EXPECT_EQ(user_id, out.user_id); + EXPECT_EQ("username", out.user_name); + EXPECT_EQ("display name", out.user_display_name); + EXPECT_FALSE(out.is_resident); } TEST(CredentialMetadata, ToPublicKeyCredentialUserEntity) { std::vector<uint8_t> user_id = {{1, 2, 3}}; - UserEntity in(user_id, "username", "display name"); + CredentialMetadata in(user_id, "username", "display name", + /*is_resident=*/false); PublicKeyCredentialUserEntity out = in.ToPublicKeyCredentialUserEntity(); EXPECT_EQ(user_id, out.id); EXPECT_EQ("username", out.name.value());
diff --git a/device/fido/mac/get_assertion_operation.mm b/device/fido/mac/get_assertion_operation.mm index b77af9d..80d5450 100644 --- a/device/fido/mac/get_assertion_operation.mm +++ b/device/fido/mac/get_assertion_operation.mm
@@ -93,9 +93,9 @@ } // Decrypt the user entity from the credential ID. - base::Optional<UserEntity> credential_user = + base::Optional<CredentialMetadata> metadata = UnsealCredentialId(metadata_secret(), RpId(), credential->credential_id); - if (!credential_user) { + if (!metadata) { // The keychain query already filtered for the RP ID encoded under this // operation's metadata secret, so the credential id really should have // been decryptable. @@ -115,11 +115,11 @@ .Run(CtapDeviceResponseCode::kCtap2ErrOther, base::nullopt); return; } - auto response = AuthenticatorGetAssertionResponse( - std::move(authenticator_data), std::move(*signature)); + AuthenticatorGetAssertionResponse response(std::move(authenticator_data), + std::move(*signature)); response.SetCredential(PublicKeyCredentialDescriptor( CredentialType::kPublicKey, std::move(credential->credential_id))); - response.SetUserEntity(credential_user->ToPublicKeyCredentialUserEntity()); + response.SetUserEntity(metadata->ToPublicKeyCredentialUserEntity()); std::move(callback()) .Run(CtapDeviceResponseCode::kSuccess, std::move(response));
diff --git a/device/fido/mac/make_credential_operation.mm b/device/fido/mac/make_credential_operation.mm index 9100a831..8873dc4 100644 --- a/device/fido/mac/make_credential_operation.mm +++ b/device/fido/mac/make_credential_operation.mm
@@ -229,9 +229,11 @@ base::Optional<std::vector<uint8_t>> MakeCredentialOperation::GenerateCredentialIdForRequest() const { - return SealCredentialId( - metadata_secret(), RpId(), - UserEntity::FromPublicKeyCredentialUserEntity(request().user)); + // TODO(martinkr): Handle resident key creation. + return SealCredentialId(metadata_secret(), RpId(), + CredentialMetadata::FromPublicKeyCredentialUserEntity( + request().user, + /*is_resident=*/false)); } } // namespace mac
diff --git a/docs/gpu/pixel_wrangling.md b/docs/gpu/pixel_wrangling.md index 4dba15e..78f891a9 100644 --- a/docs/gpu/pixel_wrangling.md +++ b/docs/gpu/pixel_wrangling.md
@@ -204,6 +204,8 @@ the "pixel" step. 1. The output will contain a link of the form <http://chromium-browser-gpu-tests.commondatastorage.googleapis.com/view_test_results.html?242523_Linux_Release_Intel__telemetry> + * For pixel_skia_gold_tests the output link will be of the form + <https://chrome-gpu-gold.skia.org/detail?test=Pixel_BackgroundImage&digest=13c038c8d426720ae575f4cb9f0bf8da> 1. Visit the link to see whether the generated or reference images look incorrect. 1. All of the reference images for all of the bots are stored in cloud
diff --git a/docs/login/user_types.md b/docs/login/user_types.md index b35de79..dfafa20 100644 --- a/docs/login/user_types.md +++ b/docs/login/user_types.md
@@ -18,8 +18,8 @@ Users that logged in using * a child account - an account designated for children under the age of 13. -* a Geller account - an account with parental supervision designated for - children between ages 13 and 18. +* a Geller account - an account with parental supervision that has no age + restrictions. In order to add a child user to the device, the user has to go through an adapted GAIA flow, which also requires their parent to authenticate.
diff --git a/docs/webui_explainer.md b/docs/webui_explainer.md index ecb4ccf..3b9bd04c 100644 --- a/docs/webui_explainer.md +++ b/docs/webui_explainer.md
@@ -219,8 +219,11 @@ } void OverHandler::HandleBakeDonuts(const base::ListValue* args) { - double num_donuts; - CHECK(args->GetDouble(0, &num_donuts)); // JavaScript numbers are doubles. + AllowJavascript(); + + CHECK_EQ(1u, args->GetSize()); + // JavaScript numbers are doubles. + double num_donuts = args->GetList()[0].GetDouble(); GetOven()->BakeDonuts(static_cast<int>(num_donuts)); } ``` @@ -429,7 +432,7 @@ * renderer doesn't exist yet * renderer exists but isn't ready -* renderer is ready but application-specifici JS isn't ready yet +* renderer is ready but application-specific JS isn't ready yet * tab refresh * renderer crash @@ -467,12 +470,11 @@ ```c++ void OvenHandler::HandleBakeDonuts(const base::ListValue* args) { -base::Value* callback_id; -args->Get(0, &callback_id); -if (!GetOven()->HasGas()) { - RejectJavascriptCallback(callback_id, - base::StringValue("need gas to cook the donuts!")); -} + AllowJavascript(); + if (!GetOven()->HasGas()) { + RejectJavascriptCallback(args->GetList()[0], + base::StringValue("need gas to cook the donuts!")); + } ``` This method is basically just a @@ -509,10 +511,9 @@ ```c++ void OvenHandler::HandleBakeDonuts(const base::ListValue* args) { - base::Value* callback_id; - args->Get(0, &callback_id); + AllowJavascript(); double num_donuts_baked = GetOven()->BakeDonuts(); - ResolveJavascriptCallback(*callback_id, num_donuts_baked); + ResolveJavascriptCallback(args->GetList()[0], num_donuts_baked); } ``` @@ -649,10 +650,11 @@ ```c++ void DonutHandler::HandleGetNumberOfDonuts(const base::ListValue* args) { - base::Value* callback_id; - args->Get(0, &callback_id); + AllowJavascript(); + + const base::Value& callback_id = args->GetList()[0]; size_t num_donuts = GetOven()->GetNumberOfDonuts(); - ResolveJavascriptCallback(*callback_id, base::FundamentalValue(num_donuts)); + ResolveJavascriptCallback(callback_id, base::FundamentalValue(num_donuts)); } ```
diff --git a/gpu/BUILD.gn b/gpu/BUILD.gn index 034cbfc..3053b53b 100644 --- a/gpu/BUILD.gn +++ b/gpu/BUILD.gn
@@ -197,7 +197,7 @@ ] } -if (!is_android && !is_fuchsia) { +if (!is_android && !is_fuchsia && !is_chromeos) { proto_library("gl_lpm_fuzzer_proto") { sources = [ "command_buffer/tests/lpm/gl_lpm_fuzzer.proto",
diff --git a/gpu/command_buffer/tests/decoder_perftest.cc b/gpu/command_buffer/tests/decoder_perftest.cc index 2ee15e4..5b1ff842 100644 --- a/gpu/command_buffer/tests/decoder_perftest.cc +++ b/gpu/command_buffer/tests/decoder_perftest.cc
@@ -231,9 +231,9 @@ gles2_implementation_.reset(); transfer_buffer_.reset(); gles2_helper_.reset(); - command_buffer_.reset(); decoder_->Destroy(true); decoder_.reset(); + command_buffer_.reset(); } void StartRecord() {
diff --git a/gpu/command_buffer/tests/gl_manager.cc b/gpu/command_buffer/tests/gl_manager.cc index 708b1746..6c42364 100644 --- a/gpu/command_buffer/tests/gl_manager.cc +++ b/gpu/command_buffer/tests/gl_manager.cc
@@ -469,13 +469,13 @@ } transfer_buffer_.reset(); gles2_helper_.reset(); - command_buffer_.reset(); if (decoder_.get()) { bool have_context = decoder_->GetGLContext() && decoder_->GetGLContext()->MakeCurrent(surface_.get()); decoder_->Destroy(have_context); decoder_.reset(); } + command_buffer_.reset(); context_ = nullptr; }
diff --git a/gpu/command_buffer/tests/lpm/gl_lpm_fuzzer.cc b/gpu/command_buffer/tests/lpm/gl_lpm_fuzzer.cc index 69894c4..a4fde280 100644 --- a/gpu/command_buffer/tests/lpm/gl_lpm_fuzzer.cc +++ b/gpu/command_buffer/tests/lpm/gl_lpm_fuzzer.cc
@@ -30,6 +30,9 @@ #include "ui/gl/gl_version_info.h" #include "ui/gl/init/gl_factory.h" +// Enable this to log and crash on unexpected errors during shader compilation. +#define CHECK_FOR_UNKNOWN_ERRORS false + struct Env { Env() { CHECK(base::i18n::InitializeICU()); @@ -54,6 +57,7 @@ public: ScopedGLManager() { gpu::GLManager::Options options; + options.context_type = gpu::CONTEXT_TYPE_OPENGLES3; gl_.Initialize(options); } ~ScopedGLManager() { gl_.Destroy(); } @@ -72,25 +76,45 @@ return shader; } +// TODO(nedwill): Once the grammar stabilizes, try to remove as many +// of these as possible by making tweaks to the grammar/code generation. const char* acceptable_errors[] = { "void function cannot return a value", "function already has a body", "undeclared identifier", - "l-value required (can't modify a const)", + "l-value required", "cannot convert from", "main function cannot return a value", "illegal use of type 'void'", "boolean expression expected", "Missing main()", "Divide by zero error during constant folding", - // TODO(nedwill): enable GLSL ES 3.00 - "operator supported in GLSL ES 3.00 and above only", "wrong operand types", "function must have the same return type in all of its declarations", "function return is not matching type", "redefinition", "WARNING:", "can't modify void", + "No precision specified for", + "exists that takes an operand of type", + "Illegal use of reserved word", + "'double' : syntax error", + "Integer overflow", + "dimension mismatch", + "undeclared identifier", + "comparison operator only defined for scalars", + "Local variables can only use the const storage qualifier.", + "must use 'flat' interpolation here", + "invalid qualifier combination", + "No precision specified for", + "'out' : cannot be matrix", + "non-void function must return a value", + "function does not return a value", + // Uniform, const, input can't be modified + "can't modify a", + "global variable initializers must be constant expressions", + "must explicitly specify all locations when using multiple fragment " + "outputs", }; // Filter errors which we don't think interfere with fuzzing everything. @@ -127,15 +151,18 @@ GLint value = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &value); if (value == 0) { - char buffer[1024]; - GLsizei length = 0; - glGetShaderInfoLog(shader, sizeof(buffer), &length, buffer); - base::StringPiece log(buffer, length); - if (value != 1 && !ErrorsOk(log)) { - LOG(WARNING) << "Encountered an unexpected failure when translating:\n" + if (CHECK_FOR_UNKNOWN_ERRORS) { + GLint log_length = 0; + glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_length); + auto buffer = std::make_unique<GLchar[]>(log_length); + glGetShaderInfoLog(shader, log_length, /*length=*/nullptr, buffer.get()); + base::StringPiece log(buffer.get(), log_length); + if (!ErrorsOk(log)) { + LOG(FATAL) << "Encountered an unexpected failure when translating:\n" << log << "\nfailed to compile shader:\n" << shader_proto.DebugString() << "converted:\n" << shader_s; + } } glDeleteShader(shader); shader = 0; @@ -143,6 +170,30 @@ return shader; } +// Same as GLTestHelper::SetupProgram but does not expect shaders +// to link successfully. +GLuint SetupProgram(GLuint vertex_shader, GLuint fragment_shader) { + GLuint program = + gpu::GLTestHelper::LinkProgram(vertex_shader, fragment_shader); + // Check the link status + GLint linked = 0; + glGetProgramiv(program, GL_LINK_STATUS, &linked); + if (linked == 0) { + if (CHECK_FOR_UNKNOWN_ERRORS) { + GLint log_length = 0; + glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length); + auto buffer = std::make_unique<GLchar[]>(log_length); + glGetProgramInfoLog(program, log_length, /*length=*/nullptr, + buffer.get()); + base::StringPiece log(buffer.get(), log_length); + LOG(WARNING) << "Error linking program: " << log; + } + glDeleteProgram(program); + program = 0; + } + return program; +} + DEFINE_PROTO_FUZZER(const fuzzing::Session& session) { static Env* env = new Env(); CHECK(env); @@ -159,8 +210,7 @@ return; } - GLuint program = - gpu::GLTestHelper::SetupProgram(vertex_shader_id, fragment_shader_id); + GLuint program = SetupProgram(vertex_shader_id, fragment_shader_id); if (!program) { return; }
diff --git a/gpu/command_buffer/tests/lpm/gl_lpm_fuzzer.proto b/gpu/command_buffer/tests/lpm/gl_lpm_fuzzer.proto index 4c4860698..e502836 100644 --- a/gpu/command_buffer/tests/lpm/gl_lpm_fuzzer.proto +++ b/gpu/command_buffer/tests/lpm/gl_lpm_fuzzer.proto
@@ -11,8 +11,6 @@ // structs // interface blocks // swizzles -// all binary operators -// all unary operators // all ternary operators // switch/case statements // loops @@ -30,13 +28,207 @@ optional Var var = 1; } +message Vec2 { + optional float first = 1; + optional float second = 2; +} + +message Vec3 { + optional float first = 1; + optional float second = 2; + optional float third = 3; +} + +message Vec4 { + optional float first = 1; + optional float second = 2; + optional float third = 3; + optional float fourth = 4; +} + +// Keep this in sync with `message Const` +enum Type { + // Use suffix to avoid clashing with VOID define on Windows + VOID_TYPE = 0; + INT = 1; + BOOL = 2; + UINT = 3; + FLOAT = 4; + DOUBLE = 5; + VEC2 = 6; + VEC3 = 7; + VEC4 = 8; + BVEC2 = 9; + BVEC3 = 10; + BVEC4 = 11; + IVEC2 = 12; + IVEC3 = 13; + IVEC4 = 14; + UVEC2 = 15; + UVEC3 = 16; + UVEC4 = 17; + MAT2 = 18; + MAT3 = 19; + MAT4 = 20; + MAT2X2 = 21; + MAT2X3 = 22; + MAT2X4 = 23; + MAT3X2 = 24; + MAT3X3 = 25; + MAT3X4 = 26; + MAT4X2 = 27; + MAT4X3 = 28; + MAT4X4 = 29; + // TODO(nedwill): support DVEC*, DMAT* +} + message Const { - optional int32 val = 1; + // Keep this in sync with `enum Type` + oneof value { + // Empty case is void + int32 int32 = 1; + bool boolean = 2; + uint32 uint = 3; + float float_const = 4; + double double_const = 5; + Vec2 vec2 = 6; + Vec3 vec3 = 7; + Vec4 vec4 = 8; + Bvec2 bvec2 = 9; + Bvec3 bvec3 = 10; + Bvec4 bvec4 = 11; + Ivec2 ivec2 = 12; + Ivec3 ivec3 = 13; + Ivec4 ivec4 = 14; + Uvec2 uvec2 = 15; + Uvec3 uvec3 = 16; + Uvec4 uvec4 = 17; + Mat2 mat2 = 18; + Mat3 mat3 = 19; + Mat4 mat4 = 20; + Mat2 mat2x2 = 21; + Mat2x3 mat2x3 = 22; + Mat2x4 mat2x4 = 23; + Mat3x2 mat3x2 = 24; + Mat3 mat3x3 = 25; + Mat3x4 mat3x4 = 26; + Mat4x2 mat4x2 = 27; + Mat4x3 mat4x3 = 28; + Mat4 mat4x4 = 29; + // TODO(nedwill): support DVEC*, DMAT* + } +} + +message Mat2x3 { + optional Vec3 first = 1; + optional Vec3 second = 2; +} + +message Mat2x4 { + optional Vec4 first = 1; + optional Vec4 second = 2; +} + +message Mat3x2 { + optional Vec2 first = 1; + optional Vec2 second = 2; + optional Vec3 third = 3; +} + +message Mat3x4 { + optional Vec4 first = 1; + optional Vec4 second = 2; + optional Vec4 third = 3; +} + +message Mat4x2 { + optional Vec2 first = 1; + optional Vec2 second = 2; + optional Vec2 third = 3; + optional Vec2 fourth = 4; +} + +message Mat4x3 { + optional Vec3 first = 1; + optional Vec3 second = 2; + optional Vec3 third = 3; + optional Vec3 fourth = 4; +} + +message Bvec2 { + optional bool first = 1; + optional bool second = 2; +} + +message Bvec3 { + optional bool first = 1; + optional bool second = 2; + optional bool third = 3; +} + +message Bvec4 { + optional bool first = 1; + optional bool second = 2; + optional bool third = 3; + optional bool fourth = 4; +} + +message Ivec2 { + optional int32 first = 1; + optional int32 second = 2; +} + +message Ivec3 { + optional int32 first = 1; + optional int32 second = 2; + optional int32 third = 3; +} + +message Ivec4 { + optional int32 first = 1; + optional int32 second = 2; + optional int32 third = 3; + optional int32 fourth = 4; +} + +message Uvec2 { + optional uint32 first = 1; + optional uint32 second = 2; +} + +message Uvec3 { + optional uint32 first = 1; + optional uint32 second = 2; + optional uint32 third = 3; +} + +message Uvec4 { + optional uint32 first = 1; + optional uint32 second = 2; + optional uint32 third = 3; + optional uint32 fourth = 4; +} + +message Mat2 { + optional Vec2 first = 1; + optional Vec2 second = 2; +} + +message Mat3 { + optional Vec3 first = 1; + optional Vec3 second = 2; + optional Vec3 third = 3; +} + +message Mat4 { + optional Vec4 first = 1; + optional Vec4 second = 2; + optional Vec4 third = 3; + optional Vec4 fourth = 4; } message BinaryOp { enum Op { - // TODO: actually use ops from GLSL spec, not c++ PLUS = 0; MINUS = 1; MUL = 2; @@ -51,22 +243,56 @@ GE = 11; LT = 12; GT = 13; + SHL = 14; + SHR = 15; + LOGICAL_AND = 16; + LOGICAL_OR = 17; }; optional Op op = 1; optional Rvalue left = 2; optional Rvalue right = 3; } +message UnaryOp { + enum Op { + PLUS = 0; + MINUS = 1; + TILDE = 2; + NOT = 3; + } + optional Op op = 1; + optional Rvalue rvalue = 2; +} + message Declare { optional Type type = 1; optional Var var = 2; + optional Qualifier qualifier = 3; + enum Qualifier { + NO_QUALIFIER = 0; + CONST_QUALIFIER = 1; + IN_QUALIFIER = 2; + OUT_QUALIFIER = 3; + UNIFORM_QUALIFIER = 4; + // TODO(nedwill): ES2 only + // ATTRIBUTE_QUALIFIER = 5; + // VARYING_QUALIFIER = 6; + // TODO(nedwill): ES3.1 only + // BUFFER_QUALIFIER = 7; + // TODO(nedwill): compute shaders only + // SHARED_QUALIFIER = 8; + } + optional Rvalue rvalue = 9; } +// TODO: finish implementing operators +// https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.60.html#operators message Rvalue { oneof rvalue { Var var = 1; Const cons = 2; BinaryOp binary_op = 3; + UnaryOp unary_op = 4; } } @@ -107,21 +333,18 @@ repeated Statement statements = 1; } -enum Type { - // Use suffix to avoid clashing with VOID define on Windows - VOID_TYPE = 0; - INT = 1; -} - message Function { optional FunctionName function_name = 1; optional Block block = 2; optional Rvalue return_stmt = 3; optional Type type = 4; + // TODO(nedwill): add arguments } message Shader { repeated Function functions = 1; + // Global declarations + repeated Declare declarations = 2; } message Session {
diff --git a/gpu/command_buffer/tests/lpm/gl_lpm_shader_to_string.cc b/gpu/command_buffer/tests/lpm/gl_lpm_shader_to_string.cc index 122e04b..05262da 100644 --- a/gpu/command_buffer/tests/lpm/gl_lpm_shader_to_string.cc +++ b/gpu/command_buffer/tests/lpm/gl_lpm_shader_to_string.cc
@@ -18,14 +18,102 @@ return "f" + base::NumberToString(function_name); } -std::string GetType(const fuzzing::Type& type) { +std::string GetType(const fuzzing::Type& type, bool void_ok) { switch (type) { case fuzzing::VOID_TYPE: { + // Avoid void in variable declarations + if (!void_ok) { + return "float"; + } return "void"; } case fuzzing::INT: { return "int"; } + case fuzzing::BOOL: { + return "bool"; + } + case fuzzing::UINT: { + return "uint"; + } + case fuzzing::FLOAT: { + return "float"; + } + case fuzzing::DOUBLE: { + return "double"; + } + case fuzzing::VEC2: { + return "vec2"; + } + case fuzzing::VEC3: { + return "vec3"; + } + case fuzzing::VEC4: { + return "vec4"; + } + case fuzzing::BVEC2: { + return "bvec2"; + } + case fuzzing::BVEC3: { + return "bvec3"; + } + case fuzzing::BVEC4: { + return "bvec4"; + } + case fuzzing::IVEC2: { + return "ivec2"; + } + case fuzzing::IVEC3: { + return "ivec3"; + } + case fuzzing::IVEC4: { + return "ivec4"; + } + case fuzzing::UVEC2: { + return "uvec2"; + } + case fuzzing::UVEC3: { + return "uvec3"; + } + case fuzzing::UVEC4: { + return "uvec4"; + } + case fuzzing::MAT2: { + return "mat2"; + } + case fuzzing::MAT3: { + return "mat3"; + } + case fuzzing::MAT4: { + return "mat4"; + } + case fuzzing::MAT2X2: { + return "mat2x2"; + } + case fuzzing::MAT2X3: { + return "mat2x3"; + } + case fuzzing::MAT2X4: { + return "mat2x4"; + } + case fuzzing::MAT3X2: { + return "mat3x2"; + } + case fuzzing::MAT3X3: { + return "mat3x3"; + } + case fuzzing::MAT3X4: { + return "mat3x4"; + } + case fuzzing::MAT4X2: { + return "mat4x2"; + } + case fuzzing::MAT4X3: { + return "mat4x3"; + } + case fuzzing::MAT4X4: { + return "mat4x4"; + } } CHECK(false); return ""; @@ -47,11 +135,187 @@ << ifelse.else_body() << "}\n"; } -std::ostream& operator<<(std::ostream& os, const fuzzing::Const& cons) { - return os << base::NumberToString(cons.val()); +std::ostream& operator<<(std::ostream& os, const fuzzing::Vec2& vec2) { + return os << "vec2(" << vec2.first() << ", " << vec2.second() << ")"; } -std::string GetOp(const fuzzing::BinaryOp::Op op) { +std::ostream& operator<<(std::ostream& os, const fuzzing::Vec3& vec3) { + return os << "vec3(" << vec3.first() << ", " << vec3.second() << ", " + << vec3.third() << ")"; +} + +std::ostream& operator<<(std::ostream& os, const fuzzing::Vec4& vec4) { + return os << "vec4(" << vec4.first() << ", " << vec4.second() << ", " + << vec4.third() << ", " << vec4.fourth() << ")"; +} + +std::string BoolToString(bool boolean) { + if (!boolean) { + return "false"; + } + return "true"; +} + +std::ostream& operator<<(std::ostream& os, const fuzzing::Const& cons) { + switch (cons.value_case()) { + case fuzzing::Const::VALUE_NOT_SET: { + os << "1"; + break; + } + case fuzzing::Const::kInt32: { + os << base::NumberToString(cons.int32()); + break; + } + case fuzzing::Const::kBoolean: { + os << BoolToString(cons.boolean()); + break; + } + case fuzzing::Const::kUint: { + os << base::NumberToString(cons.uint()) << "u"; + break; + } + case fuzzing::Const::kFloatConst: { + os << base::NumberToString(cons.float_const()); + break; + } + case fuzzing::Const::kDoubleConst: { + os << base::NumberToString(cons.double_const()); + break; + } + case fuzzing::Const::kVec2: { + os << cons.vec2(); + break; + } + case fuzzing::Const::kVec3: { + os << cons.vec3(); + break; + } + case fuzzing::Const::kVec4: { + os << cons.vec4(); + break; + } + case fuzzing::Const::kBvec2: { + os << "bvec2(" << BoolToString(cons.bvec2().first()) << ", " + << BoolToString(cons.bvec2().second()) << ")"; + break; + } + case fuzzing::Const::kBvec3: { + os << "bvec3(" << BoolToString(cons.bvec3().first()) << ", " + << BoolToString(cons.bvec3().second()) << ", " + << BoolToString(cons.bvec3().third()) << ")"; + break; + } + case fuzzing::Const::kBvec4: { + os << "bvec4(" << BoolToString(cons.bvec4().first()) << ", " + << BoolToString(cons.bvec4().second()) << ", " + << BoolToString(cons.bvec4().third()) << ", " + << BoolToString(cons.bvec4().fourth()) << ")"; + break; + } + case fuzzing::Const::kIvec2: { + os << "ivec2(" << base::NumberToString(cons.ivec2().first()) << ", " + << base::NumberToString(cons.ivec2().second()) << ")"; + break; + } + case fuzzing::Const::kIvec3: { + os << "ivec3(" << base::NumberToString(cons.ivec3().first()) << ", " + << base::NumberToString(cons.ivec3().second()) << ", " + << base::NumberToString(cons.ivec3().third()) << ")"; + break; + } + case fuzzing::Const::kIvec4: { + os << "ivec4(" << base::NumberToString(cons.ivec4().first()) << ", " + << base::NumberToString(cons.ivec4().second()) << ", " + << base::NumberToString(cons.ivec4().third()) << ", " + << base::NumberToString(cons.ivec4().fourth()) << ")"; + break; + } + case fuzzing::Const::kUvec2: { + os << "uvec2(" << base::NumberToString(cons.uvec2().first()) << "u, " + << base::NumberToString(cons.uvec2().second()) << "u)"; + break; + } + case fuzzing::Const::kUvec3: { + os << "uvec3(" << base::NumberToString(cons.uvec3().first()) << "u, " + << base::NumberToString(cons.uvec3().second()) << "u, " + << base::NumberToString(cons.uvec3().third()) << "u)"; + break; + } + case fuzzing::Const::kUvec4: { + os << "uvec4(" << base::NumberToString(cons.uvec4().first()) << "u, " + << base::NumberToString(cons.uvec4().second()) << "u, " + << base::NumberToString(cons.uvec4().third()) << "u, " + << base::NumberToString(cons.uvec4().fourth()) << "u)"; + break; + } + case fuzzing::Const::kMat2: { + os << "mat2(" << cons.mat2().first() << ", " << cons.mat2().second() + << ")"; + break; + } + case fuzzing::Const::kMat3: { + os << "mat3(" << cons.mat3().first() << ", " << cons.mat3().second() + << ", " << cons.mat3().third() << ")"; + break; + } + case fuzzing::Const::kMat4: { + os << "mat4(" << cons.mat4().first() << ", " << cons.mat4().second() + << ", " << cons.mat4().third() << ", " << cons.mat4().fourth() << ")"; + break; + } + case fuzzing::Const::kMat2X2: { + os << "mat2x2(" << cons.mat2x2().first() << ", " << cons.mat2().second() + << ")"; + break; + } + case fuzzing::Const::kMat2X3: { + os << "mat2x3(" << cons.mat2x3().first() << ", " << cons.mat2x3().second() + << ")"; + break; + } + case fuzzing::Const::kMat2X4: { + os << "mat2x4(" << cons.mat2x4().first() << ", " << cons.mat2x4().second() + << ")"; + break; + } + case fuzzing::Const::kMat3X2: { + os << "mat3x2(" << cons.mat3x2().first() << ", " << cons.mat3x2().second() + << ", " << cons.mat3x2().third() << ")"; + break; + } + case fuzzing::Const::kMat3X3: { + os << "mat3x3(" << cons.mat3x3().first() << ", " << cons.mat3x3().second() + << ", " << cons.mat3x3().third() << ")"; + break; + } + case fuzzing::Const::kMat3X4: { + os << "mat3x4(" << cons.mat3x4().first() << ", " << cons.mat3x4().second() + << ", " << cons.mat3x4().third() << ")"; + break; + } + case fuzzing::Const::kMat4X2: { + os << "mat4x2(" << cons.mat4x2().first() << ", " << cons.mat4x2().second() + << ", " << cons.mat4x2().third() << ", " << cons.mat4x2().fourth() + << ")"; + break; + } + case fuzzing::Const::kMat4X3: { + os << "mat4x3(" << cons.mat4x3().first() << ", " << cons.mat4x3().second() + << ", " << cons.mat4x3().third() << ", " << cons.mat4x3().fourth() + << ")"; + break; + } + case fuzzing::Const::kMat4X4: { + os << "mat4x4(" << cons.mat4x4().first() << ", " << cons.mat4x4().second() + << ", " << cons.mat4x4().third() << ", " << cons.mat4x4().fourth() + << ")"; + break; + } + } + return os; +} + +std::string GetBinaryOp(const fuzzing::BinaryOp::Op op) { switch (op) { case fuzzing::BinaryOp::PLUS: return "+"; @@ -66,9 +330,9 @@ case fuzzing::BinaryOp::XOR: return "^"; case fuzzing::BinaryOp::AND: - return "&&"; + return "&"; case fuzzing::BinaryOp::OR: - return "||"; + return "|"; case fuzzing::BinaryOp::EQ: return "=="; case fuzzing::BinaryOp::NE: @@ -81,15 +345,40 @@ return "<"; case fuzzing::BinaryOp::GT: return ">"; + case fuzzing::BinaryOp::SHL: + return "<<"; + case fuzzing::BinaryOp::SHR: + return ">>"; + case fuzzing::BinaryOp::LOGICAL_AND: + return "&&"; + case fuzzing::BinaryOp::LOGICAL_OR: + return "||"; default: DCHECK(false); } return ""; } +std::string GetUnaryOp(const fuzzing::UnaryOp::Op op) { + switch (op) { + case fuzzing::UnaryOp::PLUS: + return "+"; + case fuzzing::UnaryOp::MINUS: + return "-"; + case fuzzing::UnaryOp::TILDE: + return "~"; + case fuzzing::UnaryOp::NOT: + return "!"; + } +} + std::ostream& operator<<(std::ostream& os, const fuzzing::BinaryOp& binary_op) { - return os << "(" << binary_op.left() << " " << GetOp(binary_op.op()) << " " - << binary_op.right() << ")"; + return os << "(" << binary_op.left() << " " << GetBinaryOp(binary_op.op()) + << " " << binary_op.right() << ")"; +} + +std::ostream& operator<<(std::ostream& os, const fuzzing::UnaryOp& unary_op) { + return os << GetUnaryOp(unary_op.op()) << unary_op.rvalue(); } std::ostream& operator<<(std::ostream& os, const fuzzing::Rvalue& rvalue) { @@ -106,6 +395,10 @@ os << rvalue.binary_op(); break; } + case fuzzing::Rvalue::kUnaryOp: { + os << rvalue.unary_op(); + break; + } case fuzzing::Rvalue::RVALUE_NOT_SET: { os << "1"; break; @@ -132,8 +425,87 @@ return os << assignment.lvalue() << " = " << assignment.rvalue() << ";\n"; } -std::ostream& operator<<(std::ostream& os, const fuzzing::Declare& declare) { - return os << GetType(declare.type()) << " " << GetVar(declare.var()) << ";\n"; +bool TypeIsBool(const fuzzing::Type& type) { + switch (type) { + case fuzzing::BOOL: + case fuzzing::BVEC2: + case fuzzing::BVEC3: + case fuzzing::BVEC4: + return true; + case fuzzing::VOID_TYPE: + case fuzzing::INT: + case fuzzing::UINT: + case fuzzing::FLOAT: + case fuzzing::DOUBLE: + case fuzzing::VEC2: + case fuzzing::VEC3: + case fuzzing::VEC4: + case fuzzing::IVEC2: + case fuzzing::IVEC3: + case fuzzing::IVEC4: + case fuzzing::UVEC2: + case fuzzing::UVEC3: + case fuzzing::UVEC4: + case fuzzing::MAT2: + case fuzzing::MAT3: + case fuzzing::MAT4: + case fuzzing::MAT2X2: + case fuzzing::MAT2X3: + case fuzzing::MAT2X4: + case fuzzing::MAT3X2: + case fuzzing::MAT3X3: + case fuzzing::MAT3X4: + case fuzzing::MAT4X2: + case fuzzing::MAT4X3: + case fuzzing::MAT4X4: + return false; + } +} + +void GetDeclaration(std::ostream& os, + const fuzzing::Declare& declare, + bool is_global) { + switch (declare.qualifier()) { + case fuzzing::Declare::NO_QUALIFIER: { + break; + } + case fuzzing::Declare::CONST_QUALIFIER: { + os << "const "; + break; + } + case fuzzing::Declare::IN_QUALIFIER: { + // 'in' cannot be bool + if (TypeIsBool(declare.type())) { + break; + } + os << "in "; + break; + } + case fuzzing::Declare::OUT_QUALIFIER: { + // 'out' cannot be bool + if (TypeIsBool(declare.type())) { + break; + } + os << "out "; + break; + } + case fuzzing::Declare::UNIFORM_QUALIFIER: { + if (!is_global) { + break; + } + os << "uniform "; + break; + } + } + os << GetType(declare.type(), /*void_ok=*/false) << " " + << GetVar(declare.var()); + // Const must be initialized, other types cannot be + if (declare.qualifier() == fuzzing::Declare::CONST_QUALIFIER || + (declare.qualifier() == fuzzing::Declare::NO_QUALIFIER && + declare.has_rvalue())) { + os << " = " << declare.rvalue(); + } + os << ";\n"; } std::ostream& operator<<(std::ostream& os, @@ -159,7 +531,7 @@ break; } case fuzzing::Statement::kDeclare: { - os << statement.declare(); + GetDeclaration(os, statement.declare(), /*is_global=*/false); break; } } @@ -167,15 +539,22 @@ } std::ostream& operator<<(std::ostream& os, const fuzzing::Function& function) { - os << GetType(function.type()) << " " + os << GetType(function.type(), /*void_ok=*/true) << " " << GetFunctionName(function.function_name()) << "() {\n"; os << function.block(); - os << "return " << function.return_stmt() << ";\n"; + if (function.has_return_stmt()) { + os << "return " << function.return_stmt() << ";\n"; + } else { + os << "return;\n"; + } os << "}"; return os; } std::ostream& operator<<(std::ostream& os, const fuzzing::Shader& shader) { + for (const fuzzing::Declare& declare : shader.declarations()) { + GetDeclaration(os, declare, /*is_global=*/true); + } int i = 0; for (const fuzzing::Function& function : shader.functions()) { os << function; @@ -188,7 +567,11 @@ } std::string GetShader(const fuzzing::Shader& shader) { + if (shader.functions().empty()) { + return ""; + } std::ostringstream os; + os << "#version 300 es\n"; os << shader; return os.str(); }
diff --git a/gpu/command_buffer/tests/lpm/gl_lpm_shader_to_string_unittest.cc b/gpu/command_buffer/tests/lpm/gl_lpm_shader_to_string_unittest.cc index f93af792..83b30e07 100644 --- a/gpu/command_buffer/tests/lpm/gl_lpm_shader_to_string_unittest.cc +++ b/gpu/command_buffer/tests/lpm/gl_lpm_shader_to_string_unittest.cc
@@ -21,30 +21,28 @@ ASSERT_EQ(gl_lpm_fuzzer::GetShader(shader), param.second); } -INSTANTIATE_TEST_SUITE_P(LpmFuzzer, - LpmShaderTest, - ::testing::Values(std::make_pair(R"(functions { - function_name: MAIN - block { - statements { - assignment { - lvalue { - var: VAR_0 - } - rvalue { - } - } - } - } - return_stmt { - } - type: VOID_TYPE - })", - R"(void main() { +static const char* kProtoAssignment = R"( +functions { + function_name: MAIN + block { + statements { + assignment { + lvalue { var: VAR_0 } + rvalue {} + } + } + } + return_stmt {} + type: VOID_TYPE +})"; + +static const char* kShaderAssignment = R"(#version 300 es +void main() { var0 = 1; return 1; -})"), - std::make_pair(R"(functions { +})"; + +static const char* kProtoLoop = R"(functions { function_name: MAIN block { statements { @@ -54,7 +52,7 @@ op: PLUS left { cons { - val: 0 + int32: 0 } } right { @@ -69,13 +67,16 @@ return_stmt { } type: VOID_TYPE -})", - R"(void main() { +})"; + +static const char* kShaderLoop = R"(#version 300 es +void main() { while ((0 + 1)) { } return 1; -})"), - std::make_pair(R"(functions { +})"; + +static const char* kProtoTwoFunctions = R"(functions { function_name: MAIN block { statements { @@ -101,16 +102,19 @@ return_stmt { } type: VOID_TYPE -})", - R"(void main() { +})"; + +static const char* kShaderTwoFunctions = R"(#version 300 es +void main() { while (0) { } return 1; } void main() { return 1; -})"), - std::make_pair(R"(functions { +})"; + +static const char* kProtoDeclareFloat = R"(functions { function_name: NAME_2 block { } @@ -131,15 +135,18 @@ return_stmt { } type: VOID_TYPE -})", - R"(void f2() { +})"; + +static const char* kShaderDeclareFloat = R"(#version 300 es +void f2() { return 1; } void f1() { -void var2; +float var2; return 1; -})"), - std::make_pair(R"(functions { +})"; + +static const char* kProtoIfElse = R"(functions { function_name: NAME_2 block { } @@ -154,7 +161,7 @@ ifelse { cond { cons { - val: 0 + int32: 0 } } if_body { @@ -166,12 +173,14 @@ } return_stmt { cons { - val: 0 + int32: 0 } } type: VOID_TYPE -})", - R"(void f2() { +})"; + +static const char* kShaderIfElse = R"(#version 300 es +void f2() { return 1; } void main() { @@ -179,4 +188,54 @@ } else { } return 0; -})"))); +})"; + +static const char* kProtoConstInt32 = R"(functions { + return_stmt { + cons { + int32: 117506048 + } + } +})"; + +static const char* kShaderConstInt32 = R"(#version 300 es +void main() { +return 117506048; +})"; + +// Uniform only applies at global scope +static const char* kProtoNoLocalUniform = R"(functions { + block { + statements { + while_stmt { + body { + statements { + declare { + qualifier: UNIFORM_QUALIFIER + } + } + } + } + } + } +})"; + +static const char* kShaderNoLocalUniform = R"(#version 300 es +void main() { +while (1) { +float var0; +} +return; +})"; + +INSTANTIATE_TEST_SUITE_P( + LpmFuzzer, + LpmShaderTest, + ::testing::Values(std::make_pair(kProtoAssignment, kShaderAssignment), + std::make_pair(kProtoLoop, kShaderLoop), + std::make_pair(kProtoTwoFunctions, kShaderTwoFunctions), + std::make_pair(kProtoDeclareFloat, kShaderDeclareFloat), + std::make_pair(kProtoIfElse, kShaderIfElse), + std::make_pair(kProtoConstInt32, kShaderConstInt32), + std::make_pair(kProtoNoLocalUniform, + kShaderNoLocalUniform)));
diff --git a/gpu/gles2_conform_support/egl/context.cc b/gpu/gles2_conform_support/egl/context.cc index 53bb93376..e8e4bf61 100644 --- a/gpu/gles2_conform_support/egl/context.cc +++ b/gpu/gles2_conform_support/egl/context.cc
@@ -355,10 +355,10 @@ transfer_buffer_.reset(); gles2_cmd_helper_.reset(); - command_buffer_.reset(); if (decoder_) decoder_->Destroy(have_context); decoder_.reset(); + command_buffer_.reset(); } bool Context::HasService() const {
diff --git a/ios/chrome/browser/payments/OWNERS b/ios/chrome/browser/payments/OWNERS index adccd5d..0955915 100644 --- a/ios/chrome/browser/payments/OWNERS +++ b/ios/chrome/browser/payments/OWNERS
@@ -1,4 +1,6 @@ mahmadi@chromium.org +rouslan@chromium.org +danyao@chromium.org # TEAM: ios-directory-owners@chromium.org # OS: iOS
diff --git a/ios/chrome/browser/ui/activity_services/BUILD.gn b/ios/chrome/browser/ui/activity_services/BUILD.gn index 305de56..2e60c5b 100644 --- a/ios/chrome/browser/ui/activity_services/BUILD.gn +++ b/ios/chrome/browser/ui/activity_services/BUILD.gn
@@ -125,6 +125,7 @@ source_set("eg_tests") { configs += [ "//build/config/compiler:enable_arc" ] + defines = [ "CHROME_EARL_GREY_1" ] testonly = true sources = [ "activity_service_controller_egtest.mm", @@ -136,6 +137,7 @@ "//ios/chrome/browser/ui/util", "//ios/chrome/test/app:test_support", "//ios/chrome/test/earl_grey:test_support", + "//ios/testing/earl_grey:earl_grey_support", "//ios/third_party/material_components_ios", "//ios/web:earl_grey_test_support", "//ios/web/public/test",
diff --git a/ios/chrome/browser/ui/activity_services/activity_service_controller_egtest.mm b/ios/chrome/browser/ui/activity_services/activity_service_controller_egtest.mm index 19cebf5..a4df7f0d 100644 --- a/ios/chrome/browser/ui/activity_services/activity_service_controller_egtest.mm +++ b/ios/chrome/browser/ui/activity_services/activity_service_controller_egtest.mm
@@ -2,23 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#import <EarlGrey/EarlGrey.h> #import <XCTest/XCTest.h> #include <memory> -#include "base/ios/ios_util.h" #include "components/strings/grit/components_strings.h" -#import "ios/chrome/browser/ui/util/uikit_ui_util.h" #include "ios/chrome/grit/ios_strings.h" -#import "ios/chrome/test/app/chrome_test_util.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey_ui.h" #import "ios/chrome/test/earl_grey/chrome_error_util.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" -#import "ios/third_party/material_components_ios/src/components/Snackbar/src/MaterialSnackbar.h" -#import "ios/web/public/test/earl_grey/web_view_matchers.h" +#import "ios/testing/earl_grey/earl_grey_test.h" #include "ios/web/public/test/http_server/error_page_response_provider.h" #import "ios/web/public/test/http_server/http_server.h" #include "ios/web/public/test/http_server/http_server_util.h"
diff --git a/ios/chrome/test/earl_grey/chrome_earl_grey_app_interface.mm b/ios/chrome/test/earl_grey/chrome_earl_grey_app_interface.mm index 2c4567d8..200e58c 100644 --- a/ios/chrome/test/earl_grey/chrome_earl_grey_app_interface.mm +++ b/ios/chrome/test/earl_grey/chrome_earl_grey_app_interface.mm
@@ -170,12 +170,9 @@ } + (BOOL)tapWebStateElementWithID:(NSString*)elementID error:(NSError*)error { - NSError* __autoreleasing autoreleasingError = nil; - bool success = web::test::TapWebViewElementWithId( + return web::test::TapWebViewElementWithId( chrome_test_util::GetCurrentWebState(), - base::SysNSStringToUTF8(elementID), &autoreleasingError); - error = autoreleasingError; - return success; + base::SysNSStringToUTF8(elementID), &error); } + (NSError*)waitForWebStateContainingElement:(ElementSelector*)selector {
diff --git a/media/base/android/media_player_bridge_unittest.cc b/media/base/android/media_player_bridge_unittest.cc index 54bbd5c..a34bfa8 100644 --- a/media/base/android/media_player_bridge_unittest.cc +++ b/media/base/android/media_player_bridge_unittest.cc
@@ -5,7 +5,7 @@ #include "media/base/android/media_player_bridge.h" #include "base/bind.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" +#include "base/test/scoped_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -46,9 +46,7 @@ void SimulatePlaybackCompleted() { bridge_.OnPlaybackComplete(); } - // A message loop needs to be instantiated in order for the test to run - // properly. - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; StrictMock<MockMediaPlayerBridgeClient> client_; MediaPlayerBridge bridge_;
diff --git a/media/base/android/media_service_throttler_unittest.cc b/media/base/android/media_service_throttler_unittest.cc index e86e7739..5b6f5f9 100644 --- a/media/base/android/media_service_throttler_unittest.cc +++ b/media/base/android/media_service_throttler_unittest.cc
@@ -4,7 +4,7 @@ #include "media/base/android/media_service_throttler.h" -#include "base/message_loop/message_loop.h" +#include "base/test/scoped_task_environment.h" #include "base/test/simple_test_tick_clock.h" #include "media/base/android/media_server_crash_listener.h" #include "media/base/fake_single_thread_task_runner.h" @@ -60,7 +60,7 @@ scoped_refptr<FakeSingleThreadTaskRunner> test_task_runner_; // Necessary, or else base::ThreadTaskRunnerHandle::Get() fails. - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; private: DISALLOW_COPY_AND_ASSIGN(MediaServiceThrottlerTest);
diff --git a/media/base/bind_to_current_loop_unittest.cc b/media/base/bind_to_current_loop_unittest.cc index effa8b6..1a750bb 100644 --- a/media/base/bind_to_current_loop_unittest.cc +++ b/media/base/bind_to_current_loop_unittest.cc
@@ -9,9 +9,9 @@ #include "base/bind.h" #include "base/memory/free_deleter.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/synchronization/waitable_event.h" +#include "base/test/scoped_task_environment.h" #include "base/threading/thread.h" #include "base/threading/thread_checker_impl.h" #include "testing/gtest/include/gtest/gtest.h" @@ -61,7 +61,7 @@ // on the message loop, not during the original Run. class BindToCurrentLoopTest : public ::testing::Test { protected: - base::MessageLoop loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; }; TEST_F(BindToCurrentLoopTest, RepeatingClosure) {
diff --git a/media/base/fake_demuxer_stream_unittest.cc b/media/base/fake_demuxer_stream_unittest.cc index 16c1da0..b9a077a 100644 --- a/media/base/fake_demuxer_stream_unittest.cc +++ b/media/base/fake_demuxer_stream_unittest.cc
@@ -8,8 +8,8 @@ #include "base/bind.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "media/base/decoder_buffer.h" #include "media/base/demuxer_stream.h" #include "testing/gtest/include/gtest/gtest.h" @@ -180,7 +180,7 @@ ReadAllBuffers(num_configs, num_buffers_in_one_config); } - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; std::unique_ptr<FakeDemuxerStream> stream_; DemuxerStream::Status status_;
diff --git a/media/base/null_video_sink_unittest.cc b/media/base/null_video_sink_unittest.cc index 5909ec9b..4b81e14 100644 --- a/media/base/null_video_sink_unittest.cc +++ b/media/base/null_video_sink_unittest.cc
@@ -7,7 +7,7 @@ #include "base/bind.h" #include "base/callback_helpers.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" +#include "base/test/scoped_task_environment.h" #include "base/test/simple_test_tick_clock.h" #include "components/viz/common/frame_sinks/begin_frame_args.h" #include "media/base/gmock_callback_support.h" @@ -36,7 +36,7 @@ std::unique_ptr<NullVideoSink> new_sink(new NullVideoSink( clockless, interval, base::Bind(&NullVideoSinkTest::FrameReceived, base::Unretained(this)), - message_loop_.task_runner())); + scoped_task_environment_.GetMainThreadTaskRunner())); new_sink->set_tick_clock_for_testing(&tick_clock_); return new_sink; } @@ -61,7 +61,7 @@ MOCK_METHOD1(FrameReceived, void(scoped_refptr<VideoFrame>)); protected: - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; base::SimpleTestTickClock tick_clock_; DISALLOW_COPY_AND_ASSIGN(NullVideoSinkTest);
diff --git a/media/base/pipeline_impl_unittest.cc b/media/base/pipeline_impl_unittest.cc index 426bf90..3c48a46 100644 --- a/media/base/pipeline_impl_unittest.cc +++ b/media/base/pipeline_impl_unittest.cc
@@ -12,10 +12,10 @@ #include "base/bind.h" #include "base/location.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" +#include "base/test/scoped_task_environment.h" #include "base/test/simple_test_tick_clock.h" #include "base/threading/simple_thread.h" #include "base/threading/thread_task_runner_handle.h" @@ -101,9 +101,10 @@ }; PipelineImplTest() - : pipeline_(new PipelineImpl(message_loop_.task_runner(), - message_loop_.task_runner(), - &media_log_)), + : pipeline_( + new PipelineImpl(scoped_task_environment_.GetMainThreadTaskRunner(), + scoped_task_environment_.GetMainThreadTaskRunner(), + &media_log_)), demuxer_(new StrictMock<MockDemuxer>()), demuxer_host_(nullptr), scoped_renderer_(new StrictMock<MockRenderer>()), @@ -321,7 +322,7 @@ // Fixture members. StrictMock<CallbackHelper> callbacks_; base::SimpleTestTickClock test_tick_clock_; - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; NullMediaLog media_log_; std::unique_ptr<PipelineImpl> pipeline_; @@ -714,21 +715,22 @@ // Invoked function OnError. This asserts that the pipeline does not enqueue // non-teardown related tasks while tearing down. -static void TestNoCallsAfterError(PipelineImpl* pipeline, - base::MessageLoop* message_loop, - PipelineStatus /* status */) { +static void TestNoCallsAfterError( + PipelineImpl* pipeline, + base::test::ScopedTaskEnvironment* task_environment, + PipelineStatus /* status */) { CHECK(pipeline); - CHECK(message_loop); + CHECK(task_environment); - // When we get to this stage, the message loop should be empty. - EXPECT_TRUE(message_loop->IsIdleForTesting()); + // When we get to this stage, there should be no pending tasks. + EXPECT_EQ(0u, task_environment->GetPendingMainThreadTaskCount()); // Make calls on pipeline after error has occurred. pipeline->SetPlaybackRate(0.5); pipeline->SetVolume(0.5f); // No additional tasks should be queued as a result of these calls. - EXPECT_TRUE(message_loop->IsIdleForTesting()); + EXPECT_EQ(0u, task_environment->GetPendingMainThreadTaskCount()); } TEST_F(PipelineImplTest, NoMessageDuringTearDownFromError) { @@ -741,8 +743,8 @@ StartPipelineAndExpect(PIPELINE_OK); // Trigger additional requests on the pipeline during tear down from error. - base::Callback<void(PipelineStatus)> cb = - base::Bind(&TestNoCallsAfterError, pipeline_.get(), &message_loop_); + base::Callback<void(PipelineStatus)> cb = base::Bind( + &TestNoCallsAfterError, pipeline_.get(), &scoped_task_environment_); ON_CALL(callbacks_, OnError(_)).WillByDefault(Invoke(CreateFunctor(cb))); base::TimeDelta seek_time = base::TimeDelta::FromSeconds(5);
diff --git a/media/base/serial_runner_unittest.cc b/media/base/serial_runner_unittest.cc index 39e439d7..354f8f8 100644 --- a/media/base/serial_runner_unittest.cc +++ b/media/base/serial_runner_unittest.cc
@@ -8,9 +8,9 @@ #include "base/bind.h" #include "base/debug/stack_trace.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/test/scoped_task_environment.h" #include "media/base/pipeline_status.h" #include "media/base/serial_runner.h" #include "testing/gtest/include/gtest/gtest.h" @@ -24,7 +24,7 @@ ~SerialRunnerTest() override = default; void RunSerialRunner() { - message_loop_.task_runner()->PostTask( + scoped_task_environment_.GetMainThreadTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&SerialRunnerTest::StartRunnerInternal, base::Unretained(this), bound_fns_)); base::RunLoop().RunUntilIdle(); @@ -119,7 +119,7 @@ void CancelSerialRunner(const PipelineStatusCB& status_cb) { // Tasks run by |runner_| shouldn't reset it, hence we post a task to do so. - message_loop_.task_runner()->PostTask( + scoped_task_environment_.GetMainThreadTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&SerialRunnerTest::ResetSerialRunner, base::Unretained(this))); status_cb.Run(PIPELINE_OK); @@ -129,7 +129,7 @@ runner_.reset(); } - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; SerialRunner::Queue bound_fns_; std::unique_ptr<SerialRunner> runner_;
diff --git a/media/base/text_renderer_unittest.cc b/media/base/text_renderer_unittest.cc index be327b6..dd0df32 100644 --- a/media/base/text_renderer_unittest.cc +++ b/media/base/text_renderer_unittest.cc
@@ -12,8 +12,8 @@ #include "base/bind.h" #include "base/callback_helpers.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "media/base/audio_decoder_config.h" #include "media/base/decoder_buffer.h" #include "media/base/demuxer_stream.h" @@ -55,7 +55,7 @@ DCHECK(!text_renderer_); text_renderer_.reset(new TextRenderer( - message_loop_.task_runner(), + scoped_task_environment_.GetMainThreadTaskRunner(), base::Bind(&TextRendererTest::OnAddTextTrack, base::Unretained(this)))); text_renderer_->Initialize( base::Bind(&TextRendererTest::OnEnd, base::Unretained(this))); @@ -190,7 +190,7 @@ MOCK_METHOD0(OnPause, void()); MOCK_METHOD0(OnFlush, void()); - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; typedef std::vector<std::unique_ptr<FakeTextTrackStream>> TextTrackStreams; TextTrackStreams text_track_streams_; @@ -206,7 +206,7 @@ TEST_F(TextRendererTest, CreateTextRendererNoInit) { text_renderer_.reset(new TextRenderer( - message_loop_.task_runner(), + scoped_task_environment_.GetMainThreadTaskRunner(), base::Bind(&TextRendererTest::OnAddTextTrack, base::Unretained(this)))); text_renderer_.reset(); }
diff --git a/media/device_monitors/system_message_window_win_unittest.cc b/media/device_monitors/system_message_window_win_unittest.cc index 59863df..a9eee37 100644 --- a/media/device_monitors/system_message_window_win_unittest.cc +++ b/media/device_monitors/system_message_window_win_unittest.cc
@@ -5,14 +5,15 @@ #include "media/device_monitors/system_message_window_win.h" #include <dbt.h> + #include <string> #include <vector> #include "base/files/file_path.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/system/system_monitor.h" #include "base/test/mock_devices_changed_observer.h" +#include "base/test/scoped_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -27,7 +28,9 @@ system_monitor_.AddDevicesChangedObserver(&observer_); } - base::MessageLoop message_loop_; + // Run single threaded to not require explicit COM initialization + base::test::ScopedTaskEnvironment scoped_task_environment_{ + base::test::ScopedTaskEnvironment::ThreadingMode::MAIN_THREAD_ONLY}; base::SystemMonitor system_monitor_; base::MockDevicesChangedObserver observer_; SystemMessageWindowWin window_;
diff --git a/media/filters/aom_video_decoder_unittest.cc b/media/filters/aom_video_decoder_unittest.cc index 596b761..27498ac 100644 --- a/media/filters/aom_video_decoder_unittest.cc +++ b/media/filters/aom_video_decoder_unittest.cc
@@ -7,8 +7,8 @@ #include "base/bind.h" #include "base/bind_helpers.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "build/build_config.h" #include "media/base/decoder_buffer.h" #include "media/base/limits.h" @@ -164,7 +164,7 @@ testing::StrictMock<MockMediaLog> media_log_; - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; std::unique_ptr<AomVideoDecoder> decoder_; scoped_refptr<DecoderBuffer> i_frame_buffer_;
diff --git a/media/filters/audio_decoder_unittest.cc b/media/filters/audio_decoder_unittest.cc index 8ac201a..b5435e7 100644 --- a/media/filters/audio_decoder_unittest.cc +++ b/media/filters/audio_decoder_unittest.cc
@@ -13,10 +13,10 @@ #include "base/format_macros.h" #include "base/hash/md5.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/stringprintf.h" #include "base/sys_byteorder.h" +#include "base/test/scoped_task_environment.h" #include "base/threading/platform_thread.h" #include "build/build_config.h" #include "media/base/audio_buffer.h" @@ -133,12 +133,13 @@ last_decode_status_(DecodeStatus::DECODE_ERROR) { switch (decoder_type_) { case FFMPEG: - decoder_.reset( - new FFmpegAudioDecoder(message_loop_.task_runner(), &media_log_)); + decoder_.reset(new FFmpegAudioDecoder( + scoped_task_environment_.GetMainThreadTaskRunner(), &media_log_)); break; #if defined(OS_ANDROID) case MEDIA_CODEC: - decoder_.reset(new MediaCodecAudioDecoder(message_loop_.task_runner())); + decoder_.reset(new MediaCodecAudioDecoder( + scoped_task_environment_.GetMainThreadTaskRunner())); break; #endif } @@ -392,7 +393,7 @@ // that the decoder can be reinitialized with different parameters. TestParams params_; - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; NullMediaLog media_log_; scoped_refptr<DecoderBuffer> data_;
diff --git a/media/filters/dav1d_video_decoder_unittest.cc b/media/filters/dav1d_video_decoder_unittest.cc index 21f1e91..27eb02a 100644 --- a/media/filters/dav1d_video_decoder_unittest.cc +++ b/media/filters/dav1d_video_decoder_unittest.cc
@@ -9,8 +9,8 @@ #include "base/bind.h" #include "base/bind_helpers.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "build/build_config.h" #include "media/base/decoder_buffer.h" #include "media/base/limits.h" @@ -172,7 +172,7 @@ testing::StrictMock<MockMediaLog> media_log_; - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; std::unique_ptr<Dav1dVideoDecoder> decoder_; scoped_refptr<DecoderBuffer> i_frame_buffer_;
diff --git a/media/filters/decrypting_audio_decoder_unittest.cc b/media/filters/decrypting_audio_decoder_unittest.cc index 3364873d..62a6fd5 100644 --- a/media/filters/decrypting_audio_decoder_unittest.cc +++ b/media/filters/decrypting_audio_decoder_unittest.cc
@@ -9,9 +9,9 @@ #include "base/bind.h" #include "base/callback_helpers.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/stl_util.h" +#include "base/test/scoped_task_environment.h" #include "media/base/audio_buffer.h" #include "media/base/decoder_buffer.h" #include "media/base/decrypt_config.h" @@ -55,8 +55,9 @@ class DecryptingAudioDecoderTest : public testing::Test { public: DecryptingAudioDecoderTest() - : decoder_(new DecryptingAudioDecoder(message_loop_.task_runner(), - &media_log_)), + : decoder_(new DecryptingAudioDecoder( + scoped_task_environment_.GetMainThreadTaskRunner(), + &media_log_)), cdm_context_(new StrictMock<MockCdmContext>()), decryptor_(new StrictMock<MockDecryptor>()), num_decrypt_and_decode_calls_(0), @@ -242,7 +243,7 @@ MOCK_METHOD1(OnWaiting, void(WaitingReason)); - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; NullMediaLog media_log_; std::unique_ptr<DecryptingAudioDecoder> decoder_; std::unique_ptr<StrictMock<MockCdmContext>> cdm_context_;
diff --git a/media/filters/decrypting_demuxer_stream_unittest.cc b/media/filters/decrypting_demuxer_stream_unittest.cc index ab865a4..3b83b5c 100644 --- a/media/filters/decrypting_demuxer_stream_unittest.cc +++ b/media/filters/decrypting_demuxer_stream_unittest.cc
@@ -9,9 +9,9 @@ #include "base/bind.h" #include "base/callback_helpers.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/stl_util.h" +#include "base/test/scoped_task_environment.h" #include "media/base/decoder_buffer.h" #include "media/base/decrypt_config.h" #include "media/base/gmock_callback_support.h" @@ -68,7 +68,7 @@ public: DecryptingDemuxerStreamTest() : demuxer_stream_(new DecryptingDemuxerStream( - message_loop_.task_runner(), + scoped_task_environment_.GetMainThreadTaskRunner(), &media_log_, base::Bind(&DecryptingDemuxerStreamTest::OnWaiting, base::Unretained(this)))), @@ -263,7 +263,7 @@ void(DemuxerStream::Status, scoped_refptr<DecoderBuffer>)); MOCK_METHOD1(OnWaiting, void(WaitingReason)); - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; StrictMock<MockMediaLog> media_log_; std::unique_ptr<DecryptingDemuxerStream> demuxer_stream_; std::unique_ptr<StrictMock<MockCdmContext>> cdm_context_;
diff --git a/media/filters/decrypting_video_decoder_unittest.cc b/media/filters/decrypting_video_decoder_unittest.cc index 700c56e..adc3b931 100644 --- a/media/filters/decrypting_video_decoder_unittest.cc +++ b/media/filters/decrypting_video_decoder_unittest.cc
@@ -9,9 +9,9 @@ #include "base/bind.h" #include "base/callback_helpers.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/stl_util.h" +#include "base/test/scoped_task_environment.h" #include "media/base/decoder_buffer.h" #include "media/base/decrypt_config.h" #include "media/base/gmock_callback_support.h" @@ -49,8 +49,9 @@ class DecryptingVideoDecoderTest : public testing::Test { public: DecryptingVideoDecoderTest() - : decoder_(new DecryptingVideoDecoder(message_loop_.task_runner(), - &media_log_)), + : decoder_(new DecryptingVideoDecoder( + scoped_task_environment_.GetMainThreadTaskRunner(), + &media_log_)), cdm_context_(new StrictMock<MockCdmContext>()), decryptor_(new StrictMock<MockDecryptor>()), num_decrypt_and_decode_calls_(0), @@ -219,7 +220,7 @@ MOCK_METHOD1(OnWaiting, void(WaitingReason)); - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; NullMediaLog media_log_; std::unique_ptr<DecryptingVideoDecoder> decoder_; std::unique_ptr<StrictMock<MockCdmContext>> cdm_context_;
diff --git a/media/filters/fake_video_decoder_unittest.cc b/media/filters/fake_video_decoder_unittest.cc index 5718ace..a1a729d 100644 --- a/media/filters/fake_video_decoder_unittest.cc +++ b/media/filters/fake_video_decoder_unittest.cc
@@ -6,8 +6,8 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "media/base/decoder_buffer.h" #include "media/base/mock_filters.h" #include "media/base/test_helpers.h" @@ -221,7 +221,7 @@ DCHECK(!is_reset_pending_); } - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; VideoDecoderConfig current_config_; std::unique_ptr<FakeVideoDecoder> decoder_;
diff --git a/media/filters/ffmpeg_demuxer.cc b/media/filters/ffmpeg_demuxer.cc index b6ca49f..b8f209af 100644 --- a/media/filters/ffmpeg_demuxer.cc +++ b/media/filters/ffmpeg_demuxer.cc
@@ -601,14 +601,12 @@ buffer->discard_padding() == DecoderBuffer::DiscardPadding()) { buffer->set_discard_padding( std::make_pair(kInfiniteDuration, base::TimeDelta())); - if (buffer->timestamp() < base::TimeDelta()) { - // These timestamps should never be used, but to ensure they are dropped - // correctly give them unique timestamps. - buffer->set_timestamp(last_packet_timestamp_ == kNoTimestamp - ? base::TimeDelta() - : last_packet_timestamp_ + - base::TimeDelta::FromMicroseconds(1)); - } + // These timestamps should never be used, but to ensure they are dropped + // correctly give them unique timestamps. + buffer->set_timestamp(last_packet_timestamp_ == kNoTimestamp + ? base::TimeDelta() + : last_packet_timestamp_ + + base::TimeDelta::FromMicroseconds(1)); } // Only allow negative timestamps past if we know they'll be fixed up by the
diff --git a/media/filters/ffmpeg_video_decoder_unittest.cc b/media/filters/ffmpeg_video_decoder_unittest.cc index 782d4bc..d152322 100644 --- a/media/filters/ffmpeg_video_decoder_unittest.cc +++ b/media/filters/ffmpeg_video_decoder_unittest.cc
@@ -14,9 +14,9 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/singleton.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_util.h" +#include "base/test/scoped_task_environment.h" #include "media/base/decoder_buffer.h" #include "media/base/gmock_callback_support.h" #include "media/base/limits.h" @@ -201,7 +201,7 @@ StrictMock<MockMediaLog> media_log_; - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; std::unique_ptr<FFmpegVideoDecoder> decoder_; // Various buffers for testing.
diff --git a/media/filters/frame_processor_unittest.cc b/media/filters/frame_processor_unittest.cc index ba29731..507f4f8 100644 --- a/media/filters/frame_processor_unittest.cc +++ b/media/filters/frame_processor_unittest.cc
@@ -12,11 +12,11 @@ #include "base/bind.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" +#include "base/test/scoped_task_environment.h" #include "base/time/time.h" #include "media/base/media_log.h" #include "media/base/media_util.h" @@ -298,7 +298,7 @@ stream->StartReturningData(); } - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; StrictMock<MockMediaLog> media_log_; StrictMock<FrameProcessorTestCallbackHelper> callbacks_;
diff --git a/media/filters/pipeline_controller_unittest.cc b/media/filters/pipeline_controller_unittest.cc index 56ba5839..54569dc3 100644 --- a/media/filters/pipeline_controller_unittest.cc +++ b/media/filters/pipeline_controller_unittest.cc
@@ -11,8 +11,8 @@ #include "base/logging.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "base/time/time.h" #include "media/base/gmock_callback_support.h" #include "media/base/mock_filters.h" @@ -157,7 +157,7 @@ void OnVideoDecoderChange(const std::string& name) override {} void OnRemotePlayStateChange(MediaStatus::State state) override {} - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; NiceMock<MockDemuxer> demuxer_; StrictMock<MockPipeline>* pipeline_;
diff --git a/media/filters/video_decoder_stream_unittest.cc b/media/filters/video_decoder_stream_unittest.cc index d68466e..f2e38c7 100644 --- a/media/filters/video_decoder_stream_unittest.cc +++ b/media/filters/video_decoder_stream_unittest.cc
@@ -8,9 +8,9 @@ #include "base/bind.h" #include "base/callback_helpers.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" +#include "base/test/scoped_task_environment.h" #include "build/build_config.h" #include "media/base/fake_demuxer_stream.h" #include "media/base/gmock_callback_support.h" @@ -84,7 +84,7 @@ has_no_key_(false) { video_decoder_stream_.reset(new VideoDecoderStream( std::make_unique<VideoDecoderStream::StreamTraits>(&media_log_), - message_loop_.task_runner(), + scoped_task_environment_.GetMainThreadTaskRunner(), base::BindRepeating(&VideoDecoderStreamTest::CreateVideoDecodersForTest, base::Unretained(this)), &media_log_)); @@ -138,7 +138,7 @@ void PrepareFrame(scoped_refptr<VideoFrame> frame, VideoDecoderStream::OutputReadyCB output_ready_cb) { // Simulate some delay in return of the output. - message_loop_.task_runner()->PostTask( + scoped_task_environment_.GetMainThreadTaskRunner()->PostTask( FROM_HERE, base::BindOnce(std::move(output_ready_cb), std::move(frame))); } @@ -166,7 +166,7 @@ // Note this is _not_ inserted into |decoders_| below, so we don't need to // adjust the indices used below to compensate. decoders.push_back(std::make_unique<DecryptingVideoDecoder>( - message_loop_.task_runner(), &media_log_)); + scoped_task_environment_.GetMainThreadTaskRunner(), &media_log_)); #endif for (int i = 0; i < 3; ++i) { @@ -462,7 +462,7 @@ SatisfyPendingCallback(DECODER_REINIT); } - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; StrictMock<MockMediaLog> media_log_; std::unique_ptr<VideoDecoderStream> video_decoder_stream_;
diff --git a/media/mojo/clients/mojo_android_overlay_unittest.cc b/media/mojo/clients/mojo_android_overlay_unittest.cc index ca214cd..744f401f7 100644 --- a/media/mojo/clients/mojo_android_overlay_unittest.cc +++ b/media/mojo/clients/mojo_android_overlay_unittest.cc
@@ -8,8 +8,8 @@ #include "base/bind.h" #include "base/macros.h" #include "base/memory/ptr_util.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "gpu/ipc/common/gpu_surface_tracker.h" #include "media/base/mock_filters.h" #include "media/mojo/clients/mojo_android_overlay.h" @@ -155,7 +155,7 @@ } // Mojo stuff. - base::MessageLoop loop; + base::test::ScopedTaskEnvironment scoped_task_environment; // The mock provider that |overlay_client_| will talk to. // |interface_provider_| will bind it.
diff --git a/media/mojo/clients/mojo_audio_decoder_unittest.cc b/media/mojo/clients/mojo_audio_decoder_unittest.cc index f952283..51fce89e 100644 --- a/media/mojo/clients/mojo_audio_decoder_unittest.cc +++ b/media/mojo/clients/mojo_audio_decoder_unittest.cc
@@ -7,9 +7,9 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/test/scoped_task_environment.h" #include "base/threading/thread.h" #include "media/base/audio_decoder_config.h" #include "media/base/audio_timestamp_helper.h" @@ -63,8 +63,9 @@ base::BindOnce(&MojoAudioDecoderTest::ConnectToService, base::Unretained(this), base::Passed(mojo::MakeRequest(&remote_audio_decoder)))); - mojo_audio_decoder_.reset(new MojoAudioDecoder( - message_loop_.task_runner(), std::move(remote_audio_decoder))); + mojo_audio_decoder_.reset( + new MojoAudioDecoder(scoped_task_environment_.GetMainThreadTaskRunner(), + std::move(remote_audio_decoder))); } ~MojoAudioDecoderTest() override { @@ -216,7 +217,7 @@ RunLoop(); } - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; std::unique_ptr<base::RunLoop> run_loop_; // The MojoAudioDecoder that we are testing.
diff --git a/media/mojo/clients/mojo_video_encode_accelerator_unittest.cc b/media/mojo/clients/mojo_video_encode_accelerator_unittest.cc index 82e39c2..aaf4d8e5 100644 --- a/media/mojo/clients/mojo_video_encode_accelerator_unittest.cc +++ b/media/mojo/clients/mojo_video_encode_accelerator_unittest.cc
@@ -4,8 +4,8 @@ #include <stddef.h> -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "gpu/config/gpu_info.h" #include "media/mojo/clients/mojo_video_encode_accelerator.h" #include "media/mojo/interfaces/video_encode_accelerator.mojom.h" @@ -172,7 +172,7 @@ } private: - const base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; // This member holds on to the mock implementation of the "service" side. mojo::StrongBindingPtr<mojom::VideoEncodeAccelerator> mojo_vea_binding_;
diff --git a/media/mojo/common/mojo_data_pipe_read_write_unittest.cc b/media/mojo/common/mojo_data_pipe_read_write_unittest.cc index 045a889..d0abf64 100644 --- a/media/mojo/common/mojo_data_pipe_read_write_unittest.cc +++ b/media/mojo/common/mojo_data_pipe_read_write_unittest.cc
@@ -9,9 +9,9 @@ #include <memory> #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/test/mock_callback.h" +#include "base/test/scoped_task_environment.h" #include "media/base/decoder_buffer.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -67,7 +67,7 @@ } // namespace TEST(MojoDataPipeReadWriteTest, Normal) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; std::string kData = "hello, world"; MojoDataPipeReadWrite pipe_read_write_; pipe_read_write_.WriteAndRead(reinterpret_cast<const uint8_t*>(kData.data()), @@ -75,7 +75,7 @@ } TEST(MojoDataPipeReadWriteTest, SequentialReading) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; std::string kData1 = "hello, world"; std::string kData2 = "Bye!"; MojoDataPipeReadWrite pipe_read_write_; @@ -86,7 +86,7 @@ } TEST(MojoDataPipeReadWriteTest, LongerThanCapacity) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; std::string kData = "hello, world, hello, world, hello, world"; MojoDataPipeReadWrite pipe_read_write_(10); pipe_read_write_.WriteAndRead(reinterpret_cast<const uint8_t*>(kData.data()), @@ -94,7 +94,7 @@ } TEST(MojoDataPipeReadWriteTest, DiscardDataInPipe) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; std::string kData1 = "to be discarded"; std::string kData2 = "hello, world, hello, world, hello, world"; MojoDataPipeReadWrite pipe_read_write_(10);
diff --git a/media/mojo/common/mojo_decoder_buffer_converter_unittest.cc b/media/mojo/common/mojo_decoder_buffer_converter_unittest.cc index afd0a87a..db659da 100644 --- a/media/mojo/common/mojo_decoder_buffer_converter_unittest.cc +++ b/media/mojo/common/mojo_decoder_buffer_converter_unittest.cc
@@ -8,10 +8,10 @@ #include <memory> -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/stl_util.h" #include "base/test/mock_callback.h" +#include "base/test/scoped_task_environment.h" #include "media/base/decoder_buffer.h" #include "media/base/decrypt_config.h" #include "testing/gmock/include/gmock/gmock.h" @@ -59,7 +59,7 @@ } // namespace TEST(MojoDecoderBufferConverterTest, ConvertDecoderBuffer_Normal) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; const uint8_t kData[] = "hello, world"; const uint8_t kSideData[] = "sideshow bob"; const size_t kDataSize = base::size(kData); @@ -79,7 +79,7 @@ } TEST(MojoDecoderBufferConverterTest, ConvertDecoderBuffer_EOS) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; scoped_refptr<DecoderBuffer> buffer(DecoderBuffer::CreateEOSBuffer()); MojoDecoderBufferConverter converter; @@ -89,7 +89,7 @@ // TODO(xhwang): Investigate whether we can get rid of zero-byte-buffer. // See http://crbug.com/663438 TEST(MojoDecoderBufferConverterTest, ConvertDecoderBuffer_ZeroByteBuffer) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; scoped_refptr<DecoderBuffer> buffer(new DecoderBuffer(0)); MojoDecoderBufferConverter converter; @@ -97,7 +97,7 @@ } TEST(MojoDecoderBufferConverterTest, ConvertDecoderBuffer_KeyFrame) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; const uint8_t kData[] = "hello, world"; const size_t kDataSize = base::size(kData); @@ -111,7 +111,7 @@ } TEST(MojoDecoderBufferConverterTest, ConvertDecoderBuffer_EncryptedBuffer) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; const uint8_t kData[] = "hello, world"; const size_t kDataSize = base::size(kData); const char kKeyId[] = "00112233445566778899aabbccddeeff"; @@ -150,7 +150,7 @@ // This test verifies that a DecoderBuffer larger than data-pipe capacity // can be transmitted properly. TEST(MojoDecoderBufferConverterTest, Chunked) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; const uint8_t kData[] = "Lorem ipsum dolor sit amet, consectetur cras amet"; const size_t kDataSize = base::size(kData); scoped_refptr<DecoderBuffer> buffer = @@ -163,7 +163,7 @@ // This test verifies that MojoDecoderBufferReader::ReadCB is called with a // NULL DecoderBuffer if data pipe is closed during transmission. TEST(MojoDecoderBufferConverterTest, WriterSidePipeError) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; const uint8_t kData[] = "Lorem ipsum dolor sit amet, consectetur cras amet"; const size_t kDataSize = base::size(kData); scoped_refptr<DecoderBuffer> media_buffer = @@ -191,7 +191,7 @@ // This test verifies that MojoDecoderBuffer supports concurrent writes and // reads. TEST(MojoDecoderBufferConverterTest, ConcurrentDecoderBuffers) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; base::RunLoop run_loop; // Prevent all of the buffers from fitting at once to exercise the chunking @@ -237,7 +237,7 @@ } TEST(MojoDecoderBufferConverterTest, FlushWithoutRead) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; base::RunLoop run_loop; base::MockCallback<base::OnceClosure> mock_flush_cb; @@ -250,7 +250,7 @@ } TEST(MojoDecoderBufferConverterTest, FlushAfterRead) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; base::RunLoop run_loop; const uint8_t kData[] = "Lorem ipsum dolor sit amet, consectetur cras amet"; @@ -271,7 +271,7 @@ } TEST(MojoDecoderBufferConverterTest, FlushBeforeRead) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; base::RunLoop run_loop; const uint8_t kData[] = "Lorem ipsum dolor sit amet, consectetur cras amet"; @@ -299,7 +299,7 @@ } TEST(MojoDecoderBufferConverterTest, FlushBeforeChunkedRead) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; base::RunLoop run_loop; const uint8_t kData[] = "Lorem ipsum dolor sit amet, consectetur cras amet"; @@ -328,7 +328,7 @@ } TEST(MojoDecoderBufferConverterTest, FlushDuringChunkedRead) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; base::RunLoop run_loop; const uint8_t kData[] = "Lorem ipsum dolor sit amet, consectetur cras amet"; @@ -357,7 +357,7 @@ } TEST(MojoDecoderBufferConverterTest, FlushDuringConcurrentReads) { - base::MessageLoop message_loop; + base::test::ScopedTaskEnvironment scoped_task_environment; base::RunLoop run_loop; // Prevent all of the buffers from fitting at once to exercise the chunking
diff --git a/media/mojo/services/mojo_video_encode_accelerator_service_unittest.cc b/media/mojo/services/mojo_video_encode_accelerator_service_unittest.cc index 592feda..1b4f101 100644 --- a/media/mojo/services/mojo_video_encode_accelerator_service_unittest.cc +++ b/media/mojo/services/mojo_video_encode_accelerator_service_unittest.cc
@@ -6,8 +6,8 @@ #include "base/bind.h" #include "base/bind_helpers.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "gpu/config/gpu_preferences.h" #include "media/mojo/interfaces/video_encode_accelerator.mojom.h" #include "media/mojo/services/mojo_video_encode_accelerator_service.h" @@ -120,7 +120,7 @@ } private: - const base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; mojo::StrongBindingPtr<mojom::VideoEncodeAcceleratorClient> mojo_vea_binding_;
diff --git a/media/mojo/services/watch_time_recorder_unittest.cc b/media/mojo/services/watch_time_recorder_unittest.cc index 32fc1c2..404c7c3 100644 --- a/media/mojo/services/watch_time_recorder_unittest.cc +++ b/media/mojo/services/watch_time_recorder_unittest.cc
@@ -9,10 +9,10 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/hash/hash.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/test/metrics/histogram_tester.h" +#include "base/test/scoped_task_environment.h" #include "base/test/test_message_loop.h" #include "base/threading/thread_task_runner_handle.h" #include "components/ukm/test_ukm_recorder.h" @@ -156,7 +156,7 @@ MOCK_METHOD0(GetCurrentMediaTime, base::TimeDelta()); protected: - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; mojom::MediaMetricsProviderPtr provider_; std::unique_ptr<base::HistogramTester> histogram_tester_; std::unique_ptr<ukm::TestAutoSetUkmRecorder> test_recorder_;
diff --git a/media/mojo/test/mojo_video_encode_accelerator_integration_test.cc b/media/mojo/test/mojo_video_encode_accelerator_integration_test.cc index d1ef47ee..98bc3aa 100644 --- a/media/mojo/test/mojo_video_encode_accelerator_integration_test.cc +++ b/media/mojo/test/mojo_video_encode_accelerator_integration_test.cc
@@ -6,9 +6,9 @@ #include <memory> #include "base/bind.h" -#include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/test/gtest_util.h" +#include "base/test/scoped_task_environment.h" #include "gpu/config/gpu_preferences.h" #include "media/base/limits.h" #include "media/mojo/clients/mojo_video_encode_accelerator.h" @@ -107,7 +107,7 @@ } private: - const base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; // This member holds on to the implementation of the "service" side. mojo::StrongBindingPtr<mojom::VideoEncodeAccelerator> mojo_vea_binding_;
diff --git a/media/renderers/paint_canvas_video_renderer.cc b/media/renderers/paint_canvas_video_renderer.cc index 2c3feeb1..46decb6 100644 --- a/media/renderers/paint_canvas_video_renderer.cc +++ b/media/renderers/paint_canvas_video_renderer.cc
@@ -18,8 +18,10 @@ #include "gpu/GLES2/gl2extchromium.h" #include "gpu/command_buffer/client/context_support.h" #include "gpu/command_buffer/client/gles2_interface.h" +#include "gpu/command_buffer/client/shared_image_interface.h" #include "gpu/command_buffer/common/capabilities.h" #include "gpu/command_buffer/common/mailbox_holder.h" +#include "gpu/command_buffer/common/shared_image_usage.h" #include "media/base/data_buffer.h" #include "media/base/video_frame.h" #include "third_party/libyuv/include/libyuv.h" @@ -1327,43 +1329,71 @@ yuv_textures[plane] = yuv_images[plane]->getBackendTexture(false); } - // Decode 3 GPU-side Y,U,V SkImages into a GPU-side RGB SkImage. - sk_sp<SkImage> yuv_image = YUVGrBackendTexturesToSkImage( - gr_context, video_frame.ColorSpace(), video_frame.format(), yuv_textures); - if (!yuv_image) { - return false; + auto* sii = context_provider->SharedImageInterface(); + gpu::gles2::GLES2Interface* source_gl = context_provider->ContextGL(); + + // Create a shared image to receive the intermediate RGB result. + gpu::Mailbox mailbox = sii->CreateSharedImage( + viz::ResourceFormat::RGBA_8888, video_frame.coded_size(), + gfx::ColorSpace(), gpu::SHARED_IMAGE_USAGE_GLES2); + gpu::SyncToken creation_sync_token = sii->GenUnverifiedSyncToken(); + + // On the source GL context, do the YUV->RGB conversion using Skia. + gpu::SyncToken post_conversion_sync_token; + { + source_gl->WaitSyncTokenCHROMIUM(creation_sync_token.GetConstData()); + GLuint intermediate_texture = + source_gl->CreateAndTexStorage2DSharedImageCHROMIUM(mailbox.name); + source_gl->BeginSharedImageAccessDirectCHROMIUM( + intermediate_texture, GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM); + + GrGLTextureInfo backend_texture = {}; + backend_texture.fTarget = GL_TEXTURE_2D; + backend_texture.fID = intermediate_texture; + backend_texture.fFormat = GL_RGBA8; + GrBackendTexture result_texture(video_frame.coded_size().width(), + video_frame.coded_size().height(), + GrMipMapped::kNo, backend_texture); + + sk_sp<SkImage> yuv_image = YUVGrBackendTexturesToSkImage( + gr_context, video_frame.ColorSpace(), video_frame.format(), + yuv_textures, &result_texture); + + gr_context->flush(); + source_gl->EndSharedImageAccessDirectCHROMIUM(intermediate_texture); + source_gl->DeleteTextures(1, &intermediate_texture); + + source_gl->GenUnverifiedSyncTokenCHROMIUM( + post_conversion_sync_token.GetData()); + + if (!yuv_image) { + sii->DestroySharedImage(post_conversion_sync_token, mailbox); + return false; + } } - GrGLTextureInfo src_texture_info{}; - yuv_image->getBackendTexture(true).getGLTextureInfo(&src_texture_info); + // On the destination GL context, do a copy (with cropping) into the + // destination texture. + gpu::SyncToken post_copy_sync_token; + { + destination_gl->WaitSyncTokenCHROMIUM( + post_conversion_sync_token.GetConstData()); + GLuint intermediate_texture = + destination_gl->CreateAndTexStorage2DSharedImageCHROMIUM(mailbox.name); + destination_gl->BeginSharedImageAccessDirectCHROMIUM( + intermediate_texture, GL_SHARED_IMAGE_ACCESS_MODE_READ_CHROMIUM); - gpu::gles2::GLES2Interface* source_gl = context_provider->ContextGL(); - gpu::MailboxHolder mailbox_holder; - mailbox_holder.texture_target = src_texture_info.fTarget; - source_gl->ProduceTextureDirectCHROMIUM(src_texture_info.fID, - mailbox_holder.mailbox.name); + VideoFrameCopyTextureOrSubTexture( + destination_gl, video_frame.coded_size(), video_frame.visible_rect(), + intermediate_texture, target, texture, internal_format, format, type, + level, premultiply_alpha, flip_y); - // Wait for mailbox creation on source context before consuming it and - // copying from it on the consumer context. - source_gl->GenUnverifiedSyncTokenCHROMIUM( - mailbox_holder.sync_token.GetData()); - - destination_gl->WaitSyncTokenCHROMIUM( - mailbox_holder.sync_token.GetConstData()); - uint32_t intermediate_texture = - destination_gl->CreateAndConsumeTextureCHROMIUM( - mailbox_holder.mailbox.name); - VideoFrameCopyTextureOrSubTexture( - destination_gl, video_frame.coded_size(), video_frame.visible_rect(), - intermediate_texture, target, texture, internal_format, format, type, - level, premultiply_alpha, flip_y); - destination_gl->DeleteTextures(1, &intermediate_texture); - - // Wait for destination context to consume mailbox before deleting it in - // source context. - gpu::SyncToken dest_sync_token; - destination_gl->GenUnverifiedSyncTokenCHROMIUM(dest_sync_token.GetData()); - source_gl->WaitSyncTokenCHROMIUM(dest_sync_token.GetConstData()); + destination_gl->EndSharedImageAccessDirectCHROMIUM(intermediate_texture); + destination_gl->DeleteTextures(1, &intermediate_texture); + destination_gl->GenUnverifiedSyncTokenCHROMIUM( + post_copy_sync_token.GetData()); + } + sii->DestroySharedImage(post_copy_sync_token, mailbox); // video_frame->UpdateReleaseSyncToken is not necessary since the video frame // data we used was CPU-side (IsMappable) to begin with. If there were any
diff --git a/media/renderers/paint_canvas_video_renderer_unittest.cc b/media/renderers/paint_canvas_video_renderer_unittest.cc index 991c8647..9dccbedb 100644 --- a/media/renderers/paint_canvas_video_renderer_unittest.cc +++ b/media/renderers/paint_canvas_video_renderer_unittest.cc
@@ -8,7 +8,7 @@ #include "base/bind.h" #include "base/macros.h" #include "base/memory/aligned_memory.h" -#include "base/message_loop/message_loop.h" +#include "base/test/scoped_task_environment.h" #include "cc/paint/paint_flags.h" #include "cc/paint/skia_paint_canvas.h" #include "components/viz/common/gpu/context_provider.h" @@ -111,7 +111,7 @@ SkBitmap bitmap_; cc::SkiaPaintCanvas target_canvas_; - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; DISALLOW_COPY_AND_ASSIGN(PaintCanvasVideoRendererTest); };
diff --git a/media/renderers/renderer_impl_unittest.cc b/media/renderers/renderer_impl_unittest.cc index cadf707..445a37c3 100644 --- a/media/renderers/renderer_impl_unittest.cc +++ b/media/renderers/renderer_impl_unittest.cc
@@ -10,9 +10,9 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/macros.h" -#include "base/message_loop/message_loop.h" #include "base/optional.h" #include "base/run_loop.h" +#include "base/test/scoped_task_environment.h" #include "base/test/simple_test_tick_clock.h" #include "base/threading/thread_task_runner_handle.h" #include "media/base/gmock_callback_support.h" @@ -82,7 +82,7 @@ video_renderer_(new StrictMock<MockVideoRenderer>()), audio_renderer_(new StrictMock<MockAudioRenderer>()), renderer_impl_( - new RendererImpl(message_loop_.task_runner(), + new RendererImpl(scoped_task_environment_.GetMainThreadTaskRunner(), std::unique_ptr<AudioRenderer>(audio_renderer_), std::unique_ptr<VideoRenderer>(video_renderer_))), cdm_context_(new StrictMock<MockCdmContext>()), @@ -336,7 +336,7 @@ } // Fixture members. - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; StrictMock<CallbackHelper> callbacks_; base::SimpleTestTickClock test_tick_clock_;
diff --git a/media/renderers/video_resource_updater_unittest.cc b/media/renderers/video_resource_updater_unittest.cc index af40660..fdeeb77 100644 --- a/media/renderers/video_resource_updater_unittest.cc +++ b/media/renderers/video_resource_updater_unittest.cc
@@ -8,7 +8,7 @@ #include <stdint.h> #include "base/bind.h" -#include "base/message_loop/message_loop.h" +#include "base/test/scoped_task_environment.h" #include "components/viz/client/client_resource_provider.h" #include "components/viz/client/shared_bitmap_reporter.h" #include "components/viz/test/fake_output_surface.h" @@ -244,7 +244,7 @@ // VideoResourceUpdater registers as a MemoryDumpProvider, which requires // a TaskRunner. - base::MessageLoop message_loop_; + base::test::ScopedTaskEnvironment scoped_task_environment_; UploadCounterGLES2Interface* gl_; scoped_refptr<viz::TestContextProvider> context_provider_; FakeSharedBitmapReporter shared_bitmap_reporter_;
diff --git a/mojo/public/tools/bindings/chromium_bindings_configuration.gni b/mojo/public/tools/bindings/chromium_bindings_configuration.gni index d70eb62d..c135fed 100644 --- a/mojo/public/tools/bindings/chromium_bindings_configuration.gni +++ b/mojo/public/tools/bindings/chromium_bindings_configuration.gni
@@ -17,7 +17,6 @@ "//components/chromeos_camera/common/typemaps.gni", "//components/sync/mojo/typemaps.gni", "//components/typemaps.gni", - "//content/common/bluetooth/typemaps.gni", "//content/common/typemaps.gni", "//content/public/common/typemaps.gni", "//device/bluetooth/public/mojom/typemaps.gni",
diff --git a/net/dns/dns_transaction.cc b/net/dns/dns_transaction.cc index c942a2a..f4adac5 100644 --- a/net/dns/dns_transaction.cc +++ b/net/dns/dns_transaction.cc
@@ -949,6 +949,7 @@ // Makes another attempt at the current name, |qnames_.front()|, using the // next nameserver. AttemptResult MakeUDPAttempt() { + DCHECK(!secure_); doh_attempt_ = false; unsigned attempt_number = attempts_.size(); @@ -963,8 +964,7 @@ const DnsConfig& config = session_->config(); unsigned non_doh_server_index = - (first_server_index_ + attempt_number - doh_attempts_) % - config.nameservers.size(); + (first_server_index_ + attempt_number) % config.nameservers.size(); // Skip over known failed servers. non_doh_server_index = session_->NextGoodServerIndex(non_doh_server_index); @@ -999,6 +999,7 @@ AttemptResult MakeHTTPAttempt( const std::vector<DnsConfig::DnsOverHttpsServerConfig>& servers) { + DCHECK(secure_); doh_attempt_ = true; unsigned attempt_number = attempts_.size(); uint16_t id = session_->NextQueryId(); @@ -1036,6 +1037,7 @@ } AttemptResult MakeTCPAttempt(const DnsAttempt* previous_attempt) { + DCHECK(!secure_); DCHECK(previous_attempt); DCHECK(!had_tcp_attempt_);
diff --git a/net/dns/host_resolver_manager.cc b/net/dns/host_resolver_manager.cc index cf6d390..1b17b2c 100644 --- a/net/dns/host_resolver_manager.cc +++ b/net/dns/host_resolver_manager.cc
@@ -1102,7 +1102,7 @@ DCHECK(transaction); if (net_error != OK && !(net_error == ERR_NAME_NOT_RESOLVED && response && response->IsValid())) { - OnFailure(net_error, DnsResponse::DNS_PARSE_OK, base::nullopt, secure_); + OnFailure(net_error, DnsResponse::DNS_PARSE_OK, base::nullopt); return; } @@ -1130,8 +1130,7 @@ DCHECK_LT(parse_result, DnsResponse::DNS_PARSE_RESULT_MAX); if (results.error() != OK && results.error() != ERR_NAME_NOT_RESOLVED) { - OnFailure(results.error(), parse_result, results.GetOptionalTtl(), - secure_); + OnFailure(results.error(), parse_result, results.GetOptionalTtl()); return; } @@ -1181,7 +1180,7 @@ return; } - OnSuccess(results, secure_); + OnSuccess(results); } DnsResponse::Result ParseAddressDnsResponse(const DnsResponse* response, @@ -1392,7 +1391,7 @@ if (!success) { OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK, - results.GetOptionalTtl(), secure); + results.GetOptionalTtl()); return; } @@ -1402,17 +1401,16 @@ results.hostnames().value_or(std::vector<HostPortPair>()).empty()) { LOG(WARNING) << "Address list empty after RFC3484 sort"; OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK, - results.GetOptionalTtl(), secure); + results.GetOptionalTtl()); return; } - OnSuccess(results, secure); + OnSuccess(results); } void OnFailure(int net_error, DnsResponse::Result parse_result, - base::Optional<base::TimeDelta> ttl, - bool secure) { + base::Optional<base::TimeDelta> ttl) { DCHECK_NE(OK, net_error); HostCache::Entry results(net_error, HostCache::Entry::SOURCE_UNKNOWN); @@ -1435,13 +1433,13 @@ results.set_ttl(ttl.value()); } - delegate_->OnDnsTaskComplete(task_start_time_, results, secure); + delegate_->OnDnsTaskComplete(task_start_time_, results, secure_); } - void OnSuccess(const HostCache::Entry& results, bool secure) { + void OnSuccess(const HostCache::Entry& results) { net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK, results.CreateNetLogCallback()); - delegate_->OnDnsTaskComplete(task_start_time_, results, secure); + delegate_->OnDnsTaskComplete(task_start_time_, results, secure_); } DnsClient* client_; @@ -1450,7 +1448,7 @@ URLRequestContext* const request_context_; // Whether lookups in this DnsTask should occur using DoH or plaintext. - bool secure_; + const bool secure_; // The listener to the results of this DnsTask. Delegate* delegate_; @@ -1865,7 +1863,7 @@ void OnProcTaskComplete(base::TimeTicks start_time, int net_error, const AddressList& addr_list) { - DCHECK(!!proc_task_); + DCHECK(proc_task_); if (dns_task_error_ != OK) { // This ProcTask was a fallback resolution after a failed DnsTask. @@ -1974,7 +1972,7 @@ void OnDnsTaskComplete(base::TimeTicks start_time, const HostCache::Entry& results, bool secure) override { - DCHECK(!!dns_task_); + DCHECK(dns_task_); base::TimeDelta duration = tick_clock_->NowTicks() - start_time; if (results.error() != OK) { @@ -2044,7 +2042,7 @@ } void OnMdnsTaskComplete() { - DCHECK(!!mdns_task_); + DCHECK(mdns_task_); // TODO(crbug.com/846423): Consider adding MDNS-specific logging. HostCache::Entry results = mdns_task_->GetResults(); @@ -2059,7 +2057,7 @@ } void OnMdnsImmediateFailure(int rv) { - DCHECK(!!mdns_task_); + DCHECK(mdns_task_); DCHECK_NE(OK, rv); CompleteRequestsWithError(rv);
diff --git a/pdf/pdfium/pdfium_engine.cc b/pdf/pdfium/pdfium_engine.cc index b140b29..bced612 100644 --- a/pdf/pdfium/pdfium_engine.cc +++ b/pdf/pdfium/pdfium_engine.cc
@@ -1838,8 +1838,10 @@ // If StartFind() gets called before we have any page information (i.e. // before the first call to LoadDocument has happened). Handle this case. - if (pages_.empty()) + if (pages_.empty()) { + client_->NotifyNumberOfFindResultsChanged(0, true); return; + } bool first_search = (current_find_text_ != text); int character_to_start_searching_from = 0;
diff --git a/sandbox/linux/seccomp-bpf-helpers/baseline_policy.cc b/sandbox/linux/seccomp-bpf-helpers/baseline_policy.cc index 479d1ed..f4c7eb7 100644 --- a/sandbox/linux/seccomp-bpf-helpers/baseline_policy.cc +++ b/sandbox/linux/seccomp-bpf-helpers/baseline_policy.cc
@@ -11,6 +11,7 @@ #include <sys/types.h> #include <unistd.h> +#include "base/clang_coverage_buildflags.h" #include "base/logging.h" #include "build/build_config.h" #include "sandbox/linux/bpf_dsl/bpf_dsl.h" @@ -127,6 +128,12 @@ #endif // defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) || // defined(MEMORY_SANITIZER) +#if BUILDFLAG(CLANG_COVERAGE) + if (SyscallSets::IsPrctl(sysno)) { + return Allow(); + } +#endif + if (IsBaselinePolicyAllowed(sysno)) { return Allow(); }
diff --git a/services/tracing/perfetto/producer_host.cc b/services/tracing/perfetto/producer_host.cc index 12da7a6..a8150a51 100644 --- a/services/tracing/perfetto/producer_host.cc +++ b/services/tracing/perfetto/producer_host.cc
@@ -132,7 +132,10 @@ } void ProducerHost::ClearIncrementalState(const perfetto::DataSourceInstanceID*, - size_t) {} + size_t) { + DCHECK(producer_client_); + producer_client_->ClearIncrementalState(); +} // This data can come from a malicious child process. We don't do any // sanitization here because ProducerEndpoint::CommitData() (And any other
diff --git a/services/tracing/public/cpp/perfetto/perfetto_config.cc b/services/tracing/public/cpp/perfetto/perfetto_config.cc index 84fbef7..5d31211 100644 --- a/services/tracing/public/cpp/perfetto/perfetto_config.cc +++ b/services/tracing/public/cpp/perfetto/perfetto_config.cc
@@ -51,6 +51,10 @@ builtin_data_sources->set_disable_trace_config(privacy_filtering_enabled); builtin_data_sources->set_disable_system_info(privacy_filtering_enabled); + // Clear incremental state every 5 seconds, so that we lose at most the first + // 5 seconds of the trace (if we wrap around perfetto's central buffer). + perfetto_config.mutable_incremental_state_config()->set_clear_period_ms(5000); + // We strip the process filter from the config string we send to Perfetto, // so perfetto doesn't reject it from a future // TracingService::ChangeTraceConfig call due to being an unsupported
diff --git a/services/tracing/public/cpp/perfetto/perfetto_traced_process.h b/services/tracing/public/cpp/perfetto/perfetto_traced_process.h index abd7b7f..afe220d 100644 --- a/services/tracing/public/cpp/perfetto/perfetto_traced_process.h +++ b/services/tracing/public/cpp/perfetto/perfetto_traced_process.h
@@ -48,6 +48,8 @@ // Flush the data source. virtual void Flush(base::RepeatingClosure flush_complete_callback) = 0; + virtual void ClearIncrementalState() {} + const std::string& name() const { return name_; } uint64_t data_source_id() const { return data_source_id_; }
diff --git a/services/tracing/public/cpp/perfetto/producer_client.cc b/services/tracing/public/cpp/perfetto/producer_client.cc index 245624cf..c6509fb0 100644 --- a/services/tracing/public/cpp/perfetto/producer_client.cc +++ b/services/tracing/public/cpp/perfetto/producer_client.cc
@@ -92,6 +92,7 @@ new_registration.set_name(data_source->name()); new_registration.set_will_notify_on_start(true); new_registration.set_will_notify_on_stop(true); + new_registration.set_handles_incremental_state_clear(true); producer_host_->RegisterDataSource(std::move(new_registration)); } @@ -175,6 +176,12 @@ } } +void ProducerClient::ClearIncrementalState() { + for (auto* data_source : PerfettoTracedProcess::Get()->data_sources()) { + data_source->ClearIncrementalState(); + } +} + void ProducerClient::RegisterDataSource(const perfetto::DataSourceDescriptor&) { NOTREACHED(); }
diff --git a/services/tracing/public/cpp/perfetto/producer_client.h b/services/tracing/public/cpp/perfetto/producer_client.h index 2322307..6b218be 100644 --- a/services/tracing/public/cpp/perfetto/producer_client.h +++ b/services/tracing/public/cpp/perfetto/producer_client.h
@@ -61,6 +61,7 @@ void StopDataSource(uint64_t id, StopDataSourceCallback callback) override; void Flush(uint64_t flush_request_id, const std::vector<uint64_t>& data_source_ids) override; + void ClearIncrementalState() override; // perfetto::TracingService::ProducerEndpoint implementation. // Used by the TraceWriters
diff --git a/services/tracing/public/cpp/perfetto/thread_local_event_sink.cc b/services/tracing/public/cpp/perfetto/thread_local_event_sink.cc index ec5a83a..0aa7890 100644 --- a/services/tracing/public/cpp/perfetto/thread_local_event_sink.cc +++ b/services/tracing/public/cpp/perfetto/thread_local_event_sink.cc
@@ -25,6 +25,4 @@ std::move(trace_writer_)); } -void ThreadLocalEventSink::ResetIncrementalState() {} - } // namespace tracing
diff --git a/services/tracing/public/cpp/perfetto/thread_local_event_sink.h b/services/tracing/public/cpp/perfetto/thread_local_event_sink.h index f45e4a8..db85b12c 100644 --- a/services/tracing/public/cpp/perfetto/thread_local_event_sink.h +++ b/services/tracing/public/cpp/perfetto/thread_local_event_sink.h
@@ -44,8 +44,6 @@ virtual void Flush() = 0; - virtual void ResetIncrementalState(); - uint32_t session_id() const { return session_id_; } protected:
diff --git a/services/tracing/public/cpp/perfetto/trace_event_data_source.cc b/services/tracing/public/cpp/perfetto/trace_event_data_source.cc index 2a8f262..7ea0561 100644 --- a/services/tracing/public/cpp/perfetto/trace_event_data_source.cc +++ b/services/tracing/public/cpp/perfetto/trace_event_data_source.cc
@@ -367,12 +367,8 @@ std::move(flush_complete_callback))); } -void TraceEventDataSource::ResetIncrementalStateForTesting() { - auto* thread_local_event_sink = - static_cast<ThreadLocalEventSink*>(ThreadLocalEventSinkSlot()->Get()); - if (thread_local_event_sink) { - thread_local_event_sink->ResetIncrementalState(); - } +void TraceEventDataSource::ClearIncrementalState() { + TrackEventThreadLocalEventSink::ClearIncrementalState(); } ThreadLocalEventSink* TraceEventDataSource::CreateThreadLocalEventSink(
diff --git a/services/tracing/public/cpp/perfetto/trace_event_data_source.h b/services/tracing/public/cpp/perfetto/trace_event_data_source.h index b350726f9..308364f 100644 --- a/services/tracing/public/cpp/perfetto/trace_event_data_source.h +++ b/services/tracing/public/cpp/perfetto/trace_event_data_source.h
@@ -112,11 +112,7 @@ // Called from the PerfettoProducer. void StopTracing(base::OnceClosure stop_complete_callback) override; void Flush(base::RepeatingClosure flush_complete_callback) override; - - // Resets emitted incremental state on the current thread and causes - // incremental data (e.g. interning index entries and a ThreadDescriptor) to - // be emitted again. - void ResetIncrementalStateForTesting(); + void ClearIncrementalState() override; // Deletes TraceWriter safely on behalf of a ThreadLocalEventSink. void ReturnTraceWriter(
diff --git a/services/tracing/public/cpp/perfetto/trace_event_data_source_unittest.cc b/services/tracing/public/cpp/perfetto/trace_event_data_source_unittest.cc index 02ce6c0..a6e6847 100644 --- a/services/tracing/public/cpp/perfetto/trace_event_data_source_unittest.cc +++ b/services/tracing/public/cpp/perfetto/trace_event_data_source_unittest.cc
@@ -916,7 +916,7 @@ // Resetting the interning state causes ThreadDescriptor and interning // entries to be emitted again, with the same interning IDs. - TraceEventDataSource::GetInstance()->ResetIncrementalStateForTesting(); + TraceEventDataSource::GetInstance()->ClearIncrementalState(); } }
diff --git a/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.cc b/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.cc index d99437e..93b3e14 100644 --- a/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.cc +++ b/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.cc
@@ -34,12 +34,6 @@ constexpr uint32_t kMagicChunkIndex = base::trace_event::TraceBufferChunk::kMaxChunkIndex; -// Force an incremental state reset every 1000 events on each thread. This -// limits the maximum number of events we lose when trace buffers wrap. -// TODO(eseckler): Tune this value experimentally and/or replace it with a -// signal by the service. -constexpr int kMaxEventsBeforeIncrementalStateReset = 1000; - // Replacement string for names of events with TRACE_EVENT_FLAG_COPY. const char* const kPrivacyFiltered = "PRIVACY_FILTERED"; @@ -119,6 +113,10 @@ // static constexpr size_t TrackEventThreadLocalEventSink::kMaxCompleteEventDepth; +// static +std::atomic<uint32_t> + TrackEventThreadLocalEventSink::incremental_state_reset_id_{0}; + TrackEventThreadLocalEventSink::TrackEventThreadLocalEventSink( std::unique_ptr<perfetto::StartupTraceWriter> trace_writer, uint32_t session_id, @@ -138,11 +136,9 @@ TrackEventThreadLocalEventSink::~TrackEventThreadLocalEventSink() {} -// TODO(eseckler): Trigger this upon a signal from the perfetto, once perfetto -// supports this. -void TrackEventThreadLocalEventSink::ResetIncrementalState() { - reset_incremental_state_ = true; - events_since_last_incremental_state_reset_ = 0; +// static +void TrackEventThreadLocalEventSink::ClearIncrementalState() { + incremental_state_reset_id_.fetch_add(1u, std::memory_order_relaxed); } void TrackEventThreadLocalEventSink::AddTraceEvent( @@ -176,6 +172,15 @@ bool copy_strings = flags & TRACE_EVENT_FLAG_COPY; bool explicit_timestamp = flags & TRACE_EVENT_FLAG_EXPLICIT_TIMESTAMP; + // We access |incremental_state_reset_id_| atomically but racily. It's OK if + // we don't notice the reset request immediately, as long as we will notice + // and service it eventually. + auto reset_id = incremental_state_reset_id_.load(std::memory_order_relaxed); + if (reset_id != last_incremental_state_reset_id_) { + reset_incremental_state_ = true; + last_incremental_state_reset_id_ = reset_id; + } + if (reset_incremental_state_) { interned_event_categories_.ResetEmittedState(); interned_event_names_.ResetEmittedState(); @@ -453,12 +458,6 @@ interned_annotation_names_.Clear(); interned_source_locations_.Clear(); } - - events_since_last_incremental_state_reset_++; - if (events_since_last_incremental_state_reset_ >= - kMaxEventsBeforeIncrementalStateReset) { - ResetIncrementalState(); - } } void TrackEventThreadLocalEventSink::UpdateDuration(
diff --git a/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.h b/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.h index 80d1227..7cae3bd7 100644 --- a/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.h +++ b/services/tracing/public/cpp/perfetto/track_event_thread_local_event_sink.h
@@ -34,8 +34,11 @@ bool proto_writer_filtering_enabled); ~TrackEventThreadLocalEventSink() override; + // Resets emitted incremental state on all threads and causes incremental data + // (e.g. interning index entries and a ThreadDescriptor) to be emitted again. + static void ClearIncrementalState(); + // ThreadLocalEventSink implementation: - void ResetIncrementalState() override; void AddTraceEvent(base::trace_event::TraceEvent* trace_event, base::trace_event::TraceEventHandle* handle) override; void UpdateDuration(base::trace_event::TraceEventHandle handle, @@ -54,12 +57,14 @@ InterningIndex<std::pair<const char*, const char*>> interned_source_locations_; + static std::atomic<uint32_t> incremental_state_reset_id_; + bool reset_incremental_state_ = true; + uint32_t last_incremental_state_reset_id_ = 0; base::TimeTicks last_timestamp_; base::ThreadTicks last_thread_time_; int process_id_; int thread_id_; - int events_since_last_incremental_state_reset_ = 0; base::trace_event::TraceEvent complete_event_stack_[kMaxCompleteEventDepth]; uint32_t current_stack_depth_ = 0;
diff --git a/services/tracing/public/mojom/data_source_descriptor_mojom_traits.cc b/services/tracing/public/mojom/data_source_descriptor_mojom_traits.cc index e09645e1..3325748 100644 --- a/services/tracing/public/mojom/data_source_descriptor_mojom_traits.cc +++ b/services/tracing/public/mojom/data_source_descriptor_mojom_traits.cc
@@ -18,6 +18,8 @@ out->set_name(name); out->set_will_notify_on_start(data.will_notify_on_start()); out->set_will_notify_on_stop(data.will_notify_on_stop()); + out->set_handles_incremental_state_clear( + data.handles_incremental_state_clear()); return true; } } // namespace mojo
diff --git a/services/tracing/public/mojom/data_source_descriptor_mojom_traits.h b/services/tracing/public/mojom/data_source_descriptor_mojom_traits.h index aaf6826e..b98db41 100644 --- a/services/tracing/public/mojom/data_source_descriptor_mojom_traits.h +++ b/services/tracing/public/mojom/data_source_descriptor_mojom_traits.h
@@ -28,6 +28,10 @@ static bool will_notify_on_stop(const perfetto::DataSourceDescriptor& src) { return src.will_notify_on_stop(); } + static bool handles_incremental_state_clear( + const perfetto::DataSourceDescriptor& src) { + return src.handles_incremental_state_clear(); + } static bool Read(tracing::mojom::DataSourceRegistrationDataView data, perfetto::DataSourceDescriptor* out);
diff --git a/services/tracing/public/mojom/perfetto_service.mojom b/services/tracing/public/mojom/perfetto_service.mojom index 799b2c4..aad114c 100644 --- a/services/tracing/public/mojom/perfetto_service.mojom +++ b/services/tracing/public/mojom/perfetto_service.mojom
@@ -90,6 +90,7 @@ string name; bool will_notify_on_start; bool will_notify_on_stop; + bool handles_incremental_state_clear; }; // This is implemented by the tracing service and represents the service- @@ -127,6 +128,7 @@ // sent in the StartDataSource call. StopDataSource(uint64 id) => (); Flush(uint64 flush_request_id, array<uint64> data_source_ids); + ClearIncrementalState(); }; // This is implemented by the tracing service, and is essentially a singleton @@ -155,6 +157,12 @@ bool disable_system_info; }; +struct IncrementalStateConfig { + // If set to a value > 0, this enables periodical ClearIncrementalState + // messages to be sent to the producers registered for the session. + uint32 clear_period_ms; +}; + // The configuration provided by a Consumer to the Perfetto service which // primarily configures which named data sources it would like to enable and // receive tracing data from, and how large the destination buffers should be. @@ -162,6 +170,7 @@ array<DataSource> data_sources; PerfettoBuiltinDataSource perfetto_builtin_data_source; array<BufferConfig> buffers; + IncrementalStateConfig incremental_state_config; uint32 duration_ms; };
diff --git a/services/tracing/public/mojom/perfetto_service.typemap b/services/tracing/public/mojom/perfetto_service.typemap index 2671fac..ac29824 100644 --- a/services/tracing/public/mojom/perfetto_service.typemap +++ b/services/tracing/public/mojom/perfetto_service.typemap
@@ -37,5 +37,6 @@ "tracing.mojom.ChromeConfig=perfetto::ChromeConfig", "tracing.mojom.DataSourceRegistration=perfetto::DataSourceDescriptor", "tracing.mojom.PerfettoBuiltinDataSource=perfetto::TraceConfig::BuiltinDataSource", + "tracing.mojom.IncrementalStateConfig=perfetto::TraceConfig::IncrementalStateConfig", "tracing.mojom.TraceConfig=perfetto::TraceConfig", ]
diff --git a/services/tracing/public/mojom/trace_config_mojom_traits.cc b/services/tracing/public/mojom/trace_config_mojom_traits.cc index 9e78d913..9608f2e 100644 --- a/services/tracing/public/mojom/trace_config_mojom_traits.cc +++ b/services/tracing/public/mojom/trace_config_mojom_traits.cc
@@ -56,13 +56,24 @@ } // static +bool StructTraits<tracing::mojom::IncrementalStateConfigDataView, + perfetto::TraceConfig::IncrementalStateConfig>:: + Read(tracing::mojom::IncrementalStateConfigDataView data, + perfetto::TraceConfig::IncrementalStateConfig* out) { + out->set_clear_period_ms(data.clear_period_ms()); + return true; +} + +// static bool StructTraits<tracing::mojom::TraceConfigDataView, perfetto::TraceConfig>:: Read(tracing::mojom::TraceConfigDataView data, perfetto::TraceConfig* out) { std::vector<perfetto::TraceConfig::DataSource> data_sources; std::vector<perfetto::TraceConfig::BufferConfig> buffers; if (!data.ReadDataSources(&data_sources) || !data.ReadBuffers(&buffers) || !data.ReadPerfettoBuiltinDataSource( - out->mutable_builtin_data_sources())) { + out->mutable_builtin_data_sources()) || + !data.ReadIncrementalStateConfig( + out->mutable_incremental_state_config())) { return false; }
diff --git a/services/tracing/public/mojom/trace_config_mojom_traits.h b/services/tracing/public/mojom/trace_config_mojom_traits.h index bb274ef..49fefba 100644 --- a/services/tracing/public/mojom/trace_config_mojom_traits.h +++ b/services/tracing/public/mojom/trace_config_mojom_traits.h
@@ -73,6 +73,20 @@ perfetto::TraceConfig::BuiltinDataSource* out); }; +// perfetto::TraceConfig::IncrementalStateConfig +template <> +class StructTraits<tracing::mojom::IncrementalStateConfigDataView, + perfetto::TraceConfig::IncrementalStateConfig> { + public: + static uint32_t clear_period_ms( + const perfetto::TraceConfig::IncrementalStateConfig& src) { + return src.clear_period_ms(); + } + + static bool Read(tracing::mojom::IncrementalStateConfigDataView data, + perfetto::TraceConfig::IncrementalStateConfig* out); +}; + // perfetto::TraceConfig template <> class StructTraits<tracing::mojom::TraceConfigDataView, perfetto::TraceConfig> { @@ -92,6 +106,11 @@ return src.buffers(); } + static const perfetto::TraceConfig::IncrementalStateConfig& + incremental_state_config(const perfetto::TraceConfig& src) { + return src.incremental_state_config(); + } + static uint32_t duration_ms(const perfetto::TraceConfig& src) { return src.duration_ms(); }
diff --git a/testing/buildbot/chromium.android.json b/testing/buildbot/chromium.android.json index 82c39c56..898bd7e8 100644 --- a/testing/buildbot/chromium.android.json +++ b/testing/buildbot/chromium.android.json
@@ -1676,6 +1676,53 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_browsertests" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "KTU84P", + "device_os_type": "userdebug", + "device_type": "hammerhead", + "os": "Android" + } + ], + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_browsertests" + }, + { + "args": [ "--disable-perfetto", "--gtest_filter=TracingControllerTest.*:BackgroundTracingManagerBrowserTest.*", "--gs-results-bucket=chromium-result-details", @@ -1815,6 +1862,53 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_shell_test_apk" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_shell_test_apk", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "KTU84P", + "device_os_type": "userdebug", + "device_type": "hammerhead", + "os": "Android" + } + ], + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_shell_test_apk" + }, + { + "args": [ "--gs-results-bucket=chromium-result-details", "--recover-devices" ], @@ -4498,6 +4592,54 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_browsertests" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "KTU84Z", + "device_os_type": "userdebug", + "device_type": "flo", + "os": "Android" + } + ], + "expiration": 10800, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_browsertests" + }, + { + "args": [ "--disable-perfetto", "--gtest_filter=TracingControllerTest.*:BackgroundTracingManagerBrowserTest.*", "--gs-results-bucket=chromium-result-details", @@ -4640,6 +4782,54 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_shell_test_apk" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_shell_test_apk", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "KTU84Z", + "device_os_type": "userdebug", + "device_type": "flo", + "os": "Android" + } + ], + "expiration": 10800, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_shell_test_apk" + }, + { + "args": [ "--gs-results-bucket=chromium-result-details", "--recover-devices" ], @@ -7455,6 +7645,54 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_browsertests" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "LMY48I", + "device_os_type": "userdebug", + "device_type": "hammerhead", + "os": "Android" + } + ], + "expiration": 10800, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_browsertests" + }, + { + "args": [ "--disable-perfetto", "--gtest_filter=TracingControllerTest.*:BackgroundTracingManagerBrowserTest.*", "--gs-results-bucket=chromium-result-details", @@ -7597,6 +7835,54 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_shell_test_apk" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_shell_test_apk", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "LMY48I", + "device_os_type": "userdebug", + "device_type": "hammerhead", + "os": "Android" + } + ], + "expiration": 10800, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_shell_test_apk" + }, + { + "args": [ "--gs-results-bucket=chromium-result-details", "--recover-devices" ], @@ -10460,6 +10746,54 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_browsertests" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "LMY49B", + "device_os_type": "userdebug", + "device_type": "flo", + "os": "Android" + } + ], + "expiration": 10800, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_browsertests" + }, + { + "args": [ "--disable-perfetto", "--gtest_filter=TracingControllerTest.*:BackgroundTracingManagerBrowserTest.*", "--gs-results-bucket=chromium-result-details", @@ -10602,6 +10936,54 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_shell_test_apk" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_shell_test_apk", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "LMY49B", + "device_os_type": "userdebug", + "device_type": "flo", + "os": "Android" + } + ], + "expiration": 10800, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_shell_test_apk" + }, + { + "args": [ "--gs-results-bucket=chromium-result-details", "--recover-devices" ], @@ -13442,6 +13824,53 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_browsertests" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "MMB29Q", + "device_os_type": "userdebug", + "device_type": "bullhead", + "os": "Android" + } + ], + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_browsertests" + }, + { + "args": [ "--disable-perfetto", "--gtest_filter=TracingControllerTest.*:BackgroundTracingManagerBrowserTest.*", "--gs-results-bucket=chromium-result-details", @@ -13581,6 +14010,53 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_shell_test_apk" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_shell_test_apk", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "MMB29Q", + "device_os_type": "userdebug", + "device_type": "bullhead", + "os": "Android" + } + ], + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_shell_test_apk" + }, + { + "args": [ "--gs-results-bucket=chromium-result-details", "--recover-devices" ], @@ -16402,6 +16878,54 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_browsertests" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "MRA58Z", + "device_os_type": "userdebug", + "device_type": "flo", + "os": "Android" + } + ], + "expiration": 10800, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_browsertests" + }, + { + "args": [ "--disable-perfetto", "--gtest_filter=TracingControllerTest.*:BackgroundTracingManagerBrowserTest.*", "--gs-results-bucket=chromium-result-details", @@ -16544,6 +17068,54 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_shell_test_apk" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_shell_test_apk", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "MRA58Z", + "device_os_type": "userdebug", + "device_type": "flo", + "os": "Android" + } + ], + "expiration": 10800, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_shell_test_apk" + }, + { + "args": [ "--gs-results-bucket=chromium-result-details", "--recover-devices" ],
diff --git a/testing/buildbot/chromium.chrome.json b/testing/buildbot/chromium.chrome.json index 585b321..931df742 100644 --- a/testing/buildbot/chromium.chrome.json +++ b/testing/buildbot/chromium.chrome.json
@@ -191,6 +191,7 @@ }, { "args": [ + "--stop-ui", "--dbus-stub", "--gtest_filter=SplitViewTest.SplitViewResize" ], @@ -345,7 +346,7 @@ }, { "args": [ - "--ozone-platform=headless" + "--stop-ui" ], "merge": { "args": [], @@ -364,6 +365,9 @@ "test": "ozone_gl_unittests" }, { + "args": [ + "--test-launcher-filter-file=../../testing/buildbot/filters/chromeos.ozone_unittests.filter" + ], "merge": { "args": [], "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -1742,6 +1746,9 @@ "test": "ozone_gl_unittests" }, { + "args": [ + "--test-launcher-filter-file=../../testing/buildbot/filters/chromeos.ozone_unittests.filter" + ], "experiment_percentage": 100, "merge": { "args": [],
diff --git a/testing/buildbot/chromium.chromiumos.json b/testing/buildbot/chromium.chromiumos.json index 0fd8279b..13c3ffa2 100644 --- a/testing/buildbot/chromium.chromiumos.json +++ b/testing/buildbot/chromium.chromiumos.json
@@ -196,6 +196,7 @@ }, { "args": [ + "--stop-ui", "--dbus-stub", "--gtest_filter=SplitViewTest.SplitViewResize" ], @@ -350,7 +351,7 @@ }, { "args": [ - "--ozone-platform=headless" + "--stop-ui" ], "merge": { "args": [],
diff --git a/testing/buildbot/chromium.clang.json b/testing/buildbot/chromium.clang.json index 432d505..e69a5fc 100644 --- a/testing/buildbot/chromium.clang.json +++ b/testing/buildbot/chromium.clang.json
@@ -5450,6 +5450,53 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_browsertests" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "KTU84P", + "device_os_type": "userdebug", + "device_type": "hammerhead", + "os": "Android" + } + ], + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_browsertests" + }, + { + "args": [ "--disable-perfetto", "--gtest_filter=TracingControllerTest.*:BackgroundTracingManagerBrowserTest.*", "--gs-results-bucket=chromium-result-details", @@ -5589,6 +5636,53 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_shell_test_apk" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_shell_test_apk", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "KTU84P", + "device_os_type": "userdebug", + "device_type": "hammerhead", + "os": "Android" + } + ], + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_shell_test_apk" + }, + { + "args": [ "--gs-results-bucket=chromium-result-details", "--recover-devices" ], @@ -8441,6 +8535,53 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_browsertests" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "MMB29Q", + "device_os_type": "userdebug", + "device_type": "bullhead", + "os": "Android" + } + ], + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_browsertests" + }, + { + "args": [ "--disable-perfetto", "--gtest_filter=TracingControllerTest.*:BackgroundTracingManagerBrowserTest.*", "--gs-results-bucket=chromium-result-details", @@ -8580,6 +8721,53 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_shell_test_apk" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_shell_test_apk", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "MMB29Q", + "device_os_type": "userdebug", + "device_type": "bullhead", + "os": "Android" + } + ], + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_shell_test_apk" + }, + { + "args": [ "--gs-results-bucket=chromium-result-details", "--recover-devices" ],
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index 6cebb60..601e006c9 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -1555,6 +1555,54 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_browsertests" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "MMB29Q", + "device_os_type": "userdebug", + "device_type": "bullhead", + "os": "Android" + } + ], + "hard_timeout": 3600, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_browsertests" + }, + { + "args": [ "--disable-features=NetworkServiceInProcess", "--gs-results-bucket=chromium-result-details", "--recover-devices" @@ -1603,6 +1651,54 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_shell_test_apk" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_shell_test_apk", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "MMB29Q", + "device_os_type": "userdebug", + "device_type": "bullhead", + "os": "Android" + } + ], + "hard_timeout": 3600, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_shell_test_apk" + }, + { + "args": [ "--enable-features=NetworkService,NetworkServiceInProcess", "--test-launcher-filter-file=../../testing/buildbot/filters/mojo.fyi.network_webview_instrumentation_test_apk.filter", "--gs-results-bucket=chromium-result-details", @@ -3509,6 +3605,53 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_browsertests" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "MMB29Q", + "device_os_type": "userdebug", + "device_type": "bullhead", + "os": "Android" + } + ], + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_browsertests" + }, + { + "args": [ "--disable-features=NetworkServiceInProcess", "--gs-results-bucket=chromium-result-details", "--recover-devices" @@ -3556,6 +3699,53 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_shell_test_apk" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_shell_test_apk", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "MMB29Q", + "device_os_type": "userdebug", + "device_type": "bullhead", + "os": "Android" + } + ], + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_shell_test_apk" + }, + { + "args": [ "--enable-features=NetworkService,NetworkServiceInProcess", "--test-launcher-filter-file=../../testing/buildbot/filters/mojo.fyi.network_webview_instrumentation_test_apk.filter", "--gs-results-bucket=chromium-result-details", @@ -4117,7 +4307,7 @@ }, { "args": [ - "--ozone-platform=headless" + "--stop-ui" ], "isolate_coverage_data": true, "merge": {
diff --git a/testing/buildbot/chromium.memory.json b/testing/buildbot/chromium.memory.json index 47563544..8f0ee98 100644 --- a/testing/buildbot/chromium.memory.json +++ b/testing/buildbot/chromium.memory.json
@@ -1035,6 +1035,53 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_browsertests" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "MMB29Q", + "device_os_type": "userdebug", + "device_type": "bullhead", + "os": "Android" + } + ], + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_browsertests" + }, + { + "args": [ "--disable-perfetto", "--gtest_filter=TracingControllerTest.*:BackgroundTracingManagerBrowserTest.*", "--gs-results-bucket=chromium-result-details", @@ -1174,6 +1221,53 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_shell_test_apk" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_shell_test_apk", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "MMB29Q", + "device_os_type": "userdebug", + "device_type": "bullhead", + "os": "Android" + } + ], + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_shell_test_apk" + }, + { + "args": [ "--gs-results-bucket=chromium-result-details", "--recover-devices" ], @@ -14919,6 +15013,53 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_browsertests" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "MMB29Q", + "device_os_type": "userdebug", + "device_type": "bullhead", + "os": "Android" + } + ], + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_browsertests" + }, + { + "args": [ "--disable-perfetto", "--gtest_filter=TracingControllerTest.*:BackgroundTracingManagerBrowserTest.*", "--gs-results-bucket=chromium-result-details", @@ -15013,6 +15154,53 @@ }, { "args": [ + "--disable-features=NetworkService", + "--gs-results-bucket=chromium-result-details", + "--recover-devices" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "non_network_service_content_shell_test_apk" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "name": "non_network_service_content_shell_test_apk", + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "dimension_sets": [ + { + "device_os": "MMB29Q", + "device_os_type": "userdebug", + "device_type": "bullhead", + "os": "Android" + } + ], + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "shards": 5 + }, + "test": "content_shell_test_apk" + }, + { + "args": [ "--gs-results-bucket=chromium-result-details", "--recover-devices" ],
diff --git a/testing/buildbot/filters/BUILD.gn b/testing/buildbot/filters/BUILD.gn index a69ea159..73632a7 100644 --- a/testing/buildbot/filters/BUILD.gn +++ b/testing/buildbot/filters/BUILD.gn
@@ -79,6 +79,12 @@ ] } +source_set("ozone_unittests_filters") { + data = [ + "//testing/buildbot/filters/chromeos.ozone_unittests.filter", + ] +} + source_set("webview_cts_tests_filters") { testonly = true
diff --git a/testing/buildbot/filters/chromeos.ozone_unittests.filter b/testing/buildbot/filters/chromeos.ozone_unittests.filter new file mode 100644 index 0000000..b4e90f7d --- /dev/null +++ b/testing/buildbot/filters/chromeos.ozone_unittests.filter
@@ -0,0 +1,4 @@ +# crbug.com/968349 +-DrmWindowTest.CheckDeathOnFailedSwap +-HardwareDisplayControllerTest.CheckStateIfPageFlipFails +-HardwareDisplayControllerTest.FailPageFlipping
diff --git a/testing/buildbot/gn_isolate_map.pyl b/testing/buildbot/gn_isolate_map.pyl index 463cffa..a9aa6ffd 100644 --- a/testing/buildbot/gn_isolate_map.pyl +++ b/testing/buildbot/gn_isolate_map.pyl
@@ -1306,9 +1306,14 @@ "label": "//ios/chrome/test/earl_grey:ios_chrome_web_egtests", "type": "raw", }, - "ios_chrome_smoke_eg2tests": { + "ios_chrome_smoke_eg2tests_module": { "args": [], - "label": "//ios/chrome/test/earl_grey2:ios_chrome_smoke_eg2tests", + "label": "//ios/chrome/test/earl_grey2:ios_chrome_smoke_eg2tests_module", + "type": "raw", + }, + "ios_web_shell_eg2tests_module": { + "args": [], + "label": "//ios/web/shell/test:ios_web_shell_eg2tests_module", "type": "raw", }, "ios_components_unittests": {
diff --git a/testing/buildbot/manage.py b/testing/buildbot/manage.py index 2e59a6ff..8b7d7162 100755 --- a/testing/buildbot/manage.py +++ b/testing/buildbot/manage.py
@@ -101,7 +101,8 @@ 'ios_chrome_unified_consent_egtests', 'ios_chrome_unittests', 'ios_chrome_web_egtests', - 'ios_chrome_smoke_eg2tests', + 'ios_chrome_smoke_eg2tests_module', + 'ios_web_shell_eg2tests_module', 'ios_components_unittests', 'ios_net_unittests', "ios_remoting_unittests",
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index 25915be..14a0007a 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -1071,6 +1071,20 @@ 'ToTAndroidCFI', ], }, + 'non_network_service_content_browsertests': { + # Don't run on trybots; waterfall is enough. + 'remove_from': [ + 'android-kitkat-arm-rel', + 'android-marshmallow-arm64-rel' + ], + }, + 'non_network_service_content_shell_test_apk': { + # Don't run on trybots; waterfall is enough. + 'remove_from': [ + 'android-kitkat-arm-rel', + 'android-marshmallow-arm64-rel' + ], + }, 'non_network_service_webkit_layout_tests' : { 'remove_from': [ 'Linux Tests (dbg)(1)(32)', # 32-bit linux is unsupported @@ -1142,6 +1156,20 @@ 'ToTWinThinLTO64', ], }, + 'ozone_unittests': { + 'modifications': { + 'chromeos-betty-google-rel': { + 'args': [ + '--test-launcher-filter-file=../../testing/buildbot/filters/chromeos.ozone_unittests.filter', + ], + }, + 'linux-chromeos-google-rel': { + 'args': [ + '--test-launcher-filter-file=../../testing/buildbot/filters/chromeos.ozone_unittests.filter', + ], + }, + }, + }, 'perfetto_unittests': { 'remove_from': [ 'android-kitkat-arm-rel',
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index be038f7..84207b4 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -244,6 +244,7 @@ 'google_apis_unittests': {}, 'interactive_ui_tests': { 'args': [ + '--stop-ui', '--dbus-stub', '--gtest_filter=SplitViewTest.SplitViewResize', ], @@ -278,7 +279,7 @@ }, 'ozone_gl_unittests': { 'args': [ - '--ozone-platform=headless', + '--stop-ui', ], }, 'ozone_unittests': {}, @@ -4040,6 +4041,29 @@ 'crashpad_tests': {}, }, + # These tests will be run on the main Android waterfall since Android + # WebView hasn't switched to network service on stable yet. + 'non_network_service_android_gtests': { + 'non_network_service_content_browsertests': { + 'args': [ + '--disable-features=NetworkService', + ], + 'swarming': { + 'shards': 5, + }, + 'test': 'content_browsertests', + }, + 'non_network_service_content_shell_test_apk': { + 'swarming': { + 'shards': 5, + }, + 'args': [ + '--disable-features=NetworkService', + ], + 'test': 'content_shell_test_apk', + }, + }, + 'non_network_service_isolated_scripts': { 'non_network_service_webkit_layout_tests': { 'args': [ @@ -4476,6 +4500,7 @@ 'linux_flavor_specific_chromium_gtests', 'vr_platform_specific_chromium_gtests', 'network_service_android_gtests', + 'non_network_service_android_gtests', ], 'chromium_code_coverage_isolated_scripts_and_fuzzers': [ @@ -5162,6 +5187,7 @@ 'mojo_android_gtests': [ 'network_service_android_gtests', + 'non_network_service_android_gtests', ], 'mojo_chromiumos_fyi_gtests': [
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 06094a7..170856e3 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -2512,21 +2512,6 @@ ] } ], - "IncognitoStrings": [ - { - "platforms": [ - "android" - ], - "experiments": [ - { - "name": "Enabled", - "enable_features": [ - "IncognitoStrings" - ] - } - ] - } - ], "IncognitoWindowInProductHelp": [ { "platforms": [ @@ -5262,6 +5247,27 @@ ] } ], + "TabHoverCards": [ + { + "platforms": [ + "chromeos", + "linux", + "mac", + "windows" + ], + "experiments": [ + { + "name": "Enabled", + "params": { + "setting": "2" + }, + "enable_features": [ + "TabHoverCards" + ] + } + ] + } + ], "TabRanker": [ { "platforms": [
diff --git a/third_party/blink/common/BUILD.gn b/third_party/blink/common/BUILD.gn index 67d795b..0a0fbd0 100644 --- a/third_party/blink/common/BUILD.gn +++ b/third_party/blink/common/BUILD.gn
@@ -22,6 +22,9 @@ "associated_interfaces/associated_interface_provider.cc", "associated_interfaces/associated_interface_registry.cc", "blob/blob_utils.cc", + "bluetooth/web_bluetooth_device_id.cc", + "bluetooth/web_bluetooth_device_id.h", + "bluetooth/web_bluetooth_device_id_struct_traits.h", "cache_storage/cache_storage_utils.cc", "client_hints/client_hints.cc", "device_memory/approximated_device_memory.cc", @@ -121,6 +124,7 @@ testonly = true sources = [ + "bluetooth/web_bluetooth_device_id_unittest.cc", "client_hints/client_hints_unittest.cc", "device_memory/approximated_device_memory_unittest.cc", "feature_policy/feature_policy_unittest.cc",
diff --git a/third_party/blink/common/bluetooth/DEPS b/third_party/blink/common/bluetooth/DEPS new file mode 100644 index 0000000..bb3ee75 --- /dev/null +++ b/third_party/blink/common/bluetooth/DEPS
@@ -0,0 +1,4 @@ +include_rules = [ + "+crypto/random.h", +] +
diff --git a/content/common/bluetooth/OWNERS b/third_party/blink/common/bluetooth/OWNERS similarity index 100% rename from content/common/bluetooth/OWNERS rename to third_party/blink/common/bluetooth/OWNERS
diff --git a/content/common/bluetooth/web_bluetooth_device_id.cc b/third_party/blink/common/bluetooth/web_bluetooth_device_id.cc similarity index 94% rename from content/common/bluetooth/web_bluetooth_device_id.cc rename to third_party/blink/common/bluetooth/web_bluetooth_device_id.cc index 4d6f095..b3d9ba9 100644 --- a/content/common/bluetooth/web_bluetooth_device_id.cc +++ b/third_party/blink/common/bluetooth/web_bluetooth_device_id.cc
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/common/bluetooth/web_bluetooth_device_id.h" +#include "third_party/blink/public/common/bluetooth/web_bluetooth_device_id.h" #include "base/base64.h" #include "base/strings/string_util.h" #include "crypto/random.h" -namespace content { +namespace blink { namespace { @@ -88,4 +88,4 @@ return out << device_id.str(); } -} // namespace content +} // namespace blink
diff --git a/third_party/blink/common/bluetooth/web_bluetooth_device_id.typemap b/third_party/blink/common/bluetooth/web_bluetooth_device_id.typemap new file mode 100644 index 0000000..46559fad --- /dev/null +++ b/third_party/blink/common/bluetooth/web_bluetooth_device_id.typemap
@@ -0,0 +1,10 @@ +# Copyright 2016 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +mojom = "//third_party/blink/public/mojom/bluetooth/web_bluetooth.mojom" +public_headers = + [ "//third_party/blink/public/common/bluetooth/web_bluetooth_device_id.h" ] +traits_headers = [ "//third_party/blink/public/common/bluetooth/web_bluetooth_device_id_struct_traits.h" ] +type_mappings = + [ "blink.mojom.WebBluetoothDeviceId=blink::WebBluetoothDeviceId" ]
diff --git a/content/common/bluetooth/web_bluetooth_device_id_unittest.cc b/third_party/blink/common/bluetooth/web_bluetooth_device_id_unittest.cc similarity index 96% rename from content/common/bluetooth/web_bluetooth_device_id_unittest.cc rename to third_party/blink/common/bluetooth/web_bluetooth_device_id_unittest.cc index 44f7daa..77130911 100644 --- a/content/common/bluetooth/web_bluetooth_device_id_unittest.cc +++ b/third_party/blink/common/bluetooth/web_bluetooth_device_id_unittest.cc
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/common/bluetooth/web_bluetooth_device_id.h" +#include "third_party/blink/public/common/bluetooth/web_bluetooth_device_id.h" #include "base/base64.h" #include "base/strings/string_util.h" #include "testing/gtest/include/gtest/gtest.h" -using content::WebBluetoothDeviceId; +using blink::WebBluetoothDeviceId; namespace {
diff --git a/third_party/blink/common/features.cc b/third_party/blink/common/features.cc index 075b46b1..3ab319e 100644 --- a/third_party/blink/common/features.cc +++ b/third_party/blink/common/features.cc
@@ -272,7 +272,7 @@ // Use scroll gestures for scrollbar scrolls (see https://crbug.com/954007). const base::Feature kScrollbarInjectScrollGestures{ - "ScrollbarInjectScrollGestures", base::FEATURE_DISABLED_BY_DEFAULT}; + "ScrollbarInjectScrollGestures", base::FEATURE_ENABLED_BY_DEFAULT}; bool IsOffMainThreadSharedWorkerScriptFetchEnabled() { // Off-the-main-thread shared worker script fetch depends on PlzSharedWorker
diff --git a/third_party/blink/common/typemaps.gni b/third_party/blink/common/typemaps.gni index b46c007d..f0f89bd 100644 --- a/third_party/blink/common/typemaps.gni +++ b/third_party/blink/common/typemaps.gni
@@ -3,6 +3,7 @@ # found in the LICENSE file. typemaps = [ + "//third_party/blink/common/bluetooth/web_bluetooth_device_id.typemap", "//third_party/blink/common/feature_policy/feature_policy.typemap", "//third_party/blink/common/messaging/cloneable_message.typemap", "//third_party/blink/common/messaging/transferable_message.typemap",
diff --git a/third_party/blink/perf_tests/owp_storage/resources/idb-load-docs-runner.html b/third_party/blink/perf_tests/owp_storage/resources/idb-load-docs-runner.html index b3213e6..48e31d9 100644 --- a/third_party/blink/perf_tests/owp_storage/resources/idb-load-docs-runner.html +++ b/third_party/blink/perf_tests/owp_storage/resources/idb-load-docs-runner.html
@@ -155,14 +155,16 @@ lockGet.onsuccess = incrementBarrier(); let docGetBarrier = incrementBarrier(); + let docGetCallbackPromise; documentGet.onsuccess = () => { - docGetCallback(); + docGetCallbackPromise = docGetCallback(); docGetBarrier(); }; commandsDelete.onsuccess = incrementBarrier(); queuesGet.onsuccess = incrementBarrier(); - return transactionCompletePromise(txn).then(() => { + return transactionCompletePromise(txn).then(async () => { + await docGetCallbackPromise; logToDocumentBody("Txn17 done."); }); };
diff --git a/third_party/blink/public/BUILD.gn b/third_party/blink/public/BUILD.gn index 463d621..6ffbefd 100644 --- a/third_party/blink/public/BUILD.gn +++ b/third_party/blink/public/BUILD.gn
@@ -326,8 +326,6 @@ "platform/web_speech_synthesizer.h", "platform/web_speech_synthesizer_client.h", "platform/web_spell_check_panel_host_client.h", - "platform/web_storage_area.h", - "platform/web_storage_namespace.h", "platform/web_string.h", "platform/web_surface_layer_bridge.h", "platform/web_text_input_info.h", @@ -479,7 +477,6 @@ "web/web_settings.h", "web/web_shared_worker.h", "web/web_shared_worker_client.h", - "web/web_storage_event_dispatcher.h", "web/web_surrounding_text.h", "web/web_testing_support.h", "web/web_text_check_client.h",
diff --git a/third_party/blink/public/common/BUILD.gn b/third_party/blink/public/common/BUILD.gn index d43833a..6073b80 100644 --- a/third_party/blink/public/common/BUILD.gn +++ b/third_party/blink/public/common/BUILD.gn
@@ -16,6 +16,7 @@ public_deps = [ "//third_party/blink/public/common:headers", "//third_party/blink/public/mojom:mojom_modules", + "//third_party/blink/public/mojom:web_bluetooth_mojo_bindings", ] deps = [ "//third_party/blink/common", @@ -37,6 +38,8 @@ "associated_interfaces/associated_interface_provider.h", "associated_interfaces/associated_interface_registry.h", "blob/blob_utils.h", + "bluetooth/web_bluetooth_device_id.h", + "bluetooth/web_bluetooth_device_id_struct_traits.h", "cache_storage/cache_storage_utils.h", "client_hints/client_hints.h", "common_export.h", @@ -111,6 +114,7 @@ "//services/network/public/cpp:cpp", "//skia", "//third_party/blink/public/mojom:mojom_modules_headers", + "//third_party/blink/public/mojom:web_bluetooth_mojo_bindings_headers", ] deps = [
diff --git a/content/common/bluetooth/OWNERS b/third_party/blink/public/common/bluetooth/OWNERS similarity index 100% copy from content/common/bluetooth/OWNERS copy to third_party/blink/public/common/bluetooth/OWNERS
diff --git a/content/common/bluetooth/web_bluetooth_device_id.h b/third_party/blink/public/common/bluetooth/web_bluetooth_device_id.h similarity index 76% rename from content/common/bluetooth/web_bluetooth_device_id.h rename to third_party/blink/public/common/bluetooth/web_bluetooth_device_id.h index 87445e8..5d00935 100644 --- a/content/common/bluetooth/web_bluetooth_device_id.h +++ b/third_party/blink/public/common/bluetooth/web_bluetooth_device_id.h
@@ -2,19 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_H_ -#define CONTENT_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_H_ +#ifndef THIRD_PARTY_BLINK_PUBLIC_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_H_ +#define THIRD_PARTY_BLINK_PUBLIC_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_H_ #include <string> -#include "content/common/content_export.h" +#include "third_party/blink/public/common/common_export.h" -namespace content { +namespace blink { // Used to uniquely identify a Bluetooth Device for an Origin. // A WebBluetoothDeviceId is generated by base64-encoding a 128bit // string. -class CONTENT_EXPORT WebBluetoothDeviceId { +class BLINK_COMMON_EXPORT WebBluetoothDeviceId { public: // Default constructor that creates an invalid id. We implement it so that // instances of this class in a container, e.g. std::unordered_map, can be @@ -47,8 +47,9 @@ }; // This is required by gtest to print a readable output on test failures. -CONTENT_EXPORT std::ostream& operator<<(std::ostream& out, - const WebBluetoothDeviceId& device_id); +BLINK_COMMON_EXPORT std::ostream& operator<<( + std::ostream& out, + const WebBluetoothDeviceId& device_id); struct WebBluetoothDeviceIdHash { size_t operator()(const WebBluetoothDeviceId& device_id) const { @@ -56,6 +57,6 @@ } }; -} // namespace content +} // namespace blink -#endif // CONTENT_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_H_ +#endif // THIRD_PARTY_BLINK_PUBLIC_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_H_
diff --git a/third_party/blink/public/common/bluetooth/web_bluetooth_device_id_struct_traits.h b/third_party/blink/public/common/bluetooth/web_bluetooth_device_id_struct_traits.h new file mode 100644 index 0000000..838e263 --- /dev/null +++ b/third_party/blink/public/common/bluetooth/web_bluetooth_device_id_struct_traits.h
@@ -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. + +#ifndef THIRD_PARTY_BLINK_PUBLIC_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_STRUCT_TRAITS_H_ +#define THIRD_PARTY_BLINK_PUBLIC_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_STRUCT_TRAITS_H_ + +#include <string> + +#include "third_party/blink/public/common/bluetooth/web_bluetooth_device_id.h" +#include "third_party/blink/public/mojom/bluetooth/web_bluetooth.mojom.h" + +namespace mojo { + +template <> +struct StructTraits<blink::mojom::WebBluetoothDeviceIdDataView, + blink::WebBluetoothDeviceId> { + static const std::string& device_id( + const blink::WebBluetoothDeviceId& device_id) { + return device_id.str(); + } + + static bool Read(blink::mojom::WebBluetoothDeviceIdDataView input, + blink::WebBluetoothDeviceId* output) { + std::string result; + + if (!input.ReadDeviceId(&result)) + return false; + if (!blink::WebBluetoothDeviceId::IsValid(result)) + return false; + + *output = blink::WebBluetoothDeviceId(std::move(result)); + return true; + } +}; + +} // namespace mojo + +#endif // THIRD_PARTY_BLINK_PUBLIC_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_STRUCT_TRAITS_H_
diff --git a/third_party/blink/public/common/manifest/manifest.h b/third_party/blink/public/common/manifest/manifest.h index 28657f3..fdac3521 100644 --- a/third_party/blink/public/common/manifest/manifest.h +++ b/third_party/blink/public/common/manifest/manifest.h
@@ -85,8 +85,8 @@ }; enum class Enctype { - kApplication, - kMultipart, + kFormUrlEncoded, + kMultipartFormData, }; ShareTarget();
diff --git a/third_party/blink/public/common/manifest/manifest_mojom_traits.h b/third_party/blink/public/common/manifest/manifest_mojom_traits.h index 27e7153..51d9108 100644 --- a/third_party/blink/public/common/manifest/manifest_mojom_traits.h +++ b/third_party/blink/public/common/manifest/manifest_mojom_traits.h
@@ -330,22 +330,22 @@ static blink::mojom::ManifestShareTarget_Enctype ToMojom( ::blink::Manifest::ShareTarget::Enctype enctype) { switch (enctype) { - case ::blink::Manifest::ShareTarget::Enctype::kApplication: - return blink::mojom::ManifestShareTarget_Enctype::kApplication; - case ::blink::Manifest::ShareTarget::Enctype::kMultipart: - return blink::mojom::ManifestShareTarget_Enctype::kMultipart; + case ::blink::Manifest::ShareTarget::Enctype::kFormUrlEncoded: + return blink::mojom::ManifestShareTarget_Enctype::kFormUrlEncoded; + case ::blink::Manifest::ShareTarget::Enctype::kMultipartFormData: + return blink::mojom::ManifestShareTarget_Enctype::kMultipartFormData; } NOTREACHED(); - return blink::mojom::ManifestShareTarget_Enctype::kApplication; + return blink::mojom::ManifestShareTarget_Enctype::kFormUrlEncoded; } static bool FromMojom(blink::mojom::ManifestShareTarget_Enctype input, ::blink::Manifest::ShareTarget::Enctype* out) { switch (input) { - case blink::mojom::ManifestShareTarget_Enctype::kApplication: - *out = ::blink::Manifest::ShareTarget::Enctype::kApplication; + case blink::mojom::ManifestShareTarget_Enctype::kFormUrlEncoded: + *out = ::blink::Manifest::ShareTarget::Enctype::kFormUrlEncoded; return true; - case blink::mojom::ManifestShareTarget_Enctype::kMultipart: - *out = ::blink::Manifest::ShareTarget::Enctype::kMultipart; + case blink::mojom::ManifestShareTarget_Enctype::kMultipartFormData: + *out = ::blink::Manifest::ShareTarget::Enctype::kMultipartFormData; return true; }
diff --git a/third_party/blink/public/mojom/BUILD.gn b/third_party/blink/public/mojom/BUILD.gn index 1f6d785..88deaa0f 100644 --- a/third_party/blink/public/mojom/BUILD.gn +++ b/third_party/blink/public/mojom/BUILD.gn
@@ -332,12 +332,17 @@ mojom("web_bluetooth_mojo_bindings") { visibility = [ - "//content/browser:browser", - "//content/common:mojo_bindings", + "//third_party/blink/common", + "//third_party/blink/public/common:common", + "//third_party/blink/public/common:headers", ] - visibility_blink = - [ "//third_party/blink/renderer/platform:blink_platform_public_deps" ] + visibility_blink = [ + "//third_party/blink/common", + "//third_party/blink/public/common:common", + "//third_party/blink/public/common:headers", + "//third_party/blink/renderer/platform:blink_platform_public_deps", + ] sources = [ "bluetooth/web_bluetooth.mojom", @@ -350,9 +355,9 @@ # The chromium variant must be linked with content and use the same export # settings in component build because of the WebBluetoothDeviceId typemap # inside content. - export_class_attribute = "CONTENT_EXPORT" - export_define = "CONTENT_IMPLEMENTATION=1" - export_header = "content/common/content_export.h" + export_class_attribute = "BLINK_COMMON_EXPORT" + export_define = "BLINK_COMMON_IMPLEMENTATION=1" + export_header = "third_party/blink/public/common/common_export.h" # Similarly, the blink variant must be linked with the platform component # since it uses types from it in its typemaps.
diff --git a/third_party/blink/public/mojom/manifest/manifest.mojom b/third_party/blink/public/mojom/manifest/manifest.mojom index c1ab363e..5ba1207 100644 --- a/third_party/blink/public/mojom/manifest/manifest.mojom +++ b/third_party/blink/public/mojom/manifest/manifest.mojom
@@ -139,8 +139,8 @@ // to application/x-www-url-encoded and kMultipart corresponds to // multipart/form-data. enum Enctype { - kApplication, - kMultipart, + kFormUrlEncoded, + kMultipartFormData, }; // The URL that will be opened when the share target is invoked.
diff --git a/third_party/blink/public/mojom/portal/portal.mojom b/third_party/blink/public/mojom/portal/portal.mojom index 8cf199f..3949597 100644 --- a/third_party/blink/public/mojom/portal/portal.mojom +++ b/third_party/blink/public/mojom/portal/portal.mojom
@@ -6,6 +6,7 @@ import "mojo/public/mojom/base/unguessable_token.mojom"; import "third_party/blink/public/mojom/messaging/transferable_message.mojom"; +import "third_party/blink/public/mojom/referrer.mojom"; import "url/mojom/origin.mojom"; import "url/mojom/url.mojom"; import "url/mojom/origin.mojom"; @@ -15,7 +16,7 @@ // (content::Portal). It is 1:1 with PortalClient (defined below). interface Portal { // Navigates the portal to |url|. - Navigate(url.mojom.Url url); + Navigate(url.mojom.Url url, Referrer referrer); // When a portal is activated, it'll replace the current tab with the portal. Activate(TransferableMessage data) => (bool was_adopted);
diff --git a/third_party/blink/public/platform/platform.h b/third_party/blink/public/platform/platform.h index 650fc89..19b7846 100644 --- a/third_party/blink/public/platform/platform.h +++ b/third_party/blink/public/platform/platform.h
@@ -121,7 +121,6 @@ class WebSecurityOrigin; class WebSpeechSynthesizer; class WebSpeechSynthesizerClient; -class WebStorageNamespace; class WebThemeEngine; class WebTransmissionEncodingInfoHandler; class WebURLLoaderMockFactory; @@ -254,15 +253,6 @@ return WebString(); } - // DOM Storage -------------------------------------------------- - - // Return a LocalStorage namespace - virtual std::unique_ptr<WebStorageNamespace> CreateLocalStorageNamespace(); - - // Return a SessionStorage namespace - virtual std::unique_ptr<WebStorageNamespace> CreateSessionStorageNamespace( - base::StringPiece namespace_id); - // FileSystem ---------------------------------------------------------- // Return a filename-friendly identifier for an origin.
diff --git a/third_party/blink/renderer/bindings/scripts/utilities.py b/third_party/blink/renderer/bindings/scripts/utilities.py index ddb4ba7..ebca696 100644 --- a/third_party/blink/renderer/bindings/scripts/utilities.py +++ b/third_party/blink/renderer/bindings/scripts/utilities.py
@@ -454,9 +454,9 @@ 'NodeOrLongSequenceOrEventOrXMLHttpRequestOrStringOrStringByteStringOrNodeListRecord': 'NestedUnionType', # modules/canvas/offscreencanvas/offscreen_canvas_module_support_webgl2_compute.idl. # Due to offscreen_canvas_module_support_webgl2_compute.idl and offscreen_canvas_module.idl are exclusive in modules_idl_files.gni, they have same shorten name. - 'OffscreenCanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContextOrWebGL2ComputeRenderingContext': 'OffscreenRenderingContext', + 'OffscreenCanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContextOrWebGL2ComputeRenderingContextOrImageBitmapRenderingContext': 'OffscreenRenderingContext', # modules/canvas/offscreencanvas/offscreen_canvas_module.idl - 'OffscreenCanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContext': 'OffscreenRenderingContext', + 'OffscreenCanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContextOrImageBitmapRenderingContext': 'OffscreenRenderingContext', } idl_type = union_type
diff --git a/third_party/blink/renderer/config.gni b/third_party/blink/renderer/config.gni index 5145101..bfee64c6 100644 --- a/third_party/blink/renderer/config.gni +++ b/third_party/blink/renderer/config.gni
@@ -15,9 +15,8 @@ declare_args() { # If true, use PFFFT for WebAudio FFT support. This can be used for - # any Android architecture and also Linux and Windows. We only use - # it on Android. - use_webaudio_pffft = is_android + # any Android architecture and also Linux and Windows. + use_webaudio_pffft = is_android || target_os == "linux" } declare_args() {
diff --git a/third_party/blink/renderer/core/animation/keyframe_effect_test.cc b/third_party/blink/renderer/core/animation/keyframe_effect_test.cc index 3992703..5e805cb 100644 --- a/third_party/blink/renderer/core/animation/keyframe_effect_test.cc +++ b/third_party/blink/renderer/core/animation/keyframe_effect_test.cc
@@ -451,20 +451,19 @@ MakeGarbageCollected<KeyframeEffect>(element, effect_model, timing); // If the target has a CSS offset we can't composite it. + element->SetInlineStyleProperty(CSSPropertyID::kOffsetPosition, "50px 50px"); UpdateAllLifecyclePhasesForTest(); - element->MutableComputedStyle()->SetOffsetPosition( - LengthPoint(Length::Percent(50.0), Length::Auto())); + ASSERT_TRUE(element->GetComputedStyle()->HasOffset()); EXPECT_TRUE(keyframe_effect->CheckCanStartAnimationOnCompositor( nullptr, animation_playback_rate) & CompositorAnimations::kTargetHasCSSOffset); // If the target has multiple transform properties we can't composite it. + element->SetInlineStyleProperty(CSSPropertyID::kRotate, "90deg"); + element->SetInlineStyleProperty(CSSPropertyID::kScale, "2 1"); UpdateAllLifecyclePhasesForTest(); - element->MutableComputedStyle()->SetRotate( - RotateTransformOperation::Create(100, TransformOperation::kRotateX)); - element->MutableComputedStyle()->SetScale( - ScaleTransformOperation::Create(2, 1, TransformOperation::kScaleX)); + EXPECT_TRUE(keyframe_effect->CheckCanStartAnimationOnCompositor( nullptr, animation_playback_rate) & CompositorAnimations::kTargetHasMultipleTransformProperties);
diff --git a/third_party/blink/renderer/core/dom/layout_tree_builder.cc b/third_party/blink/renderer/core/dom/layout_tree_builder.cc index b19006a..096cb86d 100644 --- a/third_party/blink/renderer/core/dom/layout_tree_builder.cc +++ b/third_party/blink/renderer/core/dom/layout_tree_builder.cc
@@ -47,7 +47,7 @@ LayoutTreeBuilderForElement::LayoutTreeBuilderForElement(Element& element, ComputedStyle* style) - : LayoutTreeBuilder(element, nullptr), style_(style) { + : LayoutTreeBuilder(element, nullptr, style) { DCHECK(element.CanParticipateInFlatTree()); DCHECK(style_); DCHECK(!style_->IsEnsuredInDisplayNone());
diff --git a/third_party/blink/renderer/core/dom/layout_tree_builder.h b/third_party/blink/renderer/core/dom/layout_tree_builder.h index f3f1bf9..2fe0b75 100644 --- a/third_party/blink/renderer/core/dom/layout_tree_builder.h +++ b/third_party/blink/renderer/core/dom/layout_tree_builder.h
@@ -59,8 +59,12 @@ STACK_ALLOCATED(); protected: - LayoutTreeBuilder(NodeType& node, LayoutObject* layout_object_parent) - : node_(node), layout_object_parent_(layout_object_parent) { + LayoutTreeBuilder(NodeType& node, + LayoutObject* layout_object_parent, + ComputedStyle* style) + : node_(node), + layout_object_parent_(layout_object_parent), + style_(style) { DCHECK(!node.GetLayoutObject()); DCHECK(node.GetDocument().InStyleRecalc()); DCHECK(node.InActiveDocument()); @@ -92,6 +96,7 @@ Member<NodeType> node_; LayoutObject* layout_object_parent_; + ComputedStyle* style_; }; class LayoutTreeBuilderForElement : public LayoutTreeBuilder<Element> { @@ -108,8 +113,6 @@ LayoutObject* NextLayoutObject() const; bool ShouldCreateLayoutObject() const; void CreateLayoutObject(LegacyLayout); - - scoped_refptr<ComputedStyle> style_; }; class LayoutTreeBuilderForText : public LayoutTreeBuilder<Text> { @@ -117,14 +120,12 @@ LayoutTreeBuilderForText(Text& text, LayoutObject* layout_parent, ComputedStyle* style_from_parent) - : LayoutTreeBuilder(text, layout_parent), style_(style_from_parent) {} + : LayoutTreeBuilder(text, layout_parent, style_from_parent) {} void CreateLayoutObject(); private: LayoutObject* CreateInlineWrapperForDisplayContentsIfNeeded(); - - scoped_refptr<ComputedStyle> style_; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/exported/web_remote_frame_impl.cc b/third_party/blink/renderer/core/exported/web_remote_frame_impl.cc index e502736b..e98696f 100644 --- a/third_party/blink/renderer/core/exported/web_remote_frame_impl.cc +++ b/third_party/blink/renderer/core/exported/web_remote_frame_impl.cc
@@ -4,6 +4,8 @@ #include "third_party/blink/renderer/core/exported/web_remote_frame_impl.h" +#include <utility> + #include "third_party/blink/public/common/feature_policy/feature_policy.h" #include "third_party/blink/public/platform/web_float_rect.h" #include "third_party/blink/public/platform/web_intrinsic_sizing_info.h" @@ -326,6 +328,14 @@ void WebRemoteFrameImpl::DidStopLoading() { GetFrame()->SetIsLoading(false); + + // When a subframe finishes loading, the parent should check if *all* + // subframes have finished loading (which may mean that the parent can declare + // that the parent itself has finished loading). This remote-subframe-focused + // code has a local-subframe equivalent in FrameLoader::DidFinishNavigation. + Frame* parent = GetFrame()->Tree().Parent(); + if (parent) + parent->CheckCompleted(); } bool WebRemoteFrameImpl::IsIgnoredForHitTest() const {
diff --git a/third_party/blink/renderer/core/frame/location.cc b/third_party/blink/renderer/core/frame/location.cc index 26e45438..2eb0735 100644 --- a/third_party/blink/renderer/core/frame/location.cc +++ b/third_party/blink/renderer/core/frame/location.cc
@@ -292,11 +292,10 @@ // execution, there are concerns about the correctness of that statement, // see http://github.com/whatwg/html/issues/2591. Document* current_document = current_window->document(); - if (current_document && completed_url.ProtocolIsJavaScript() && - !ContentSecurityPolicy::ShouldBypassMainWorld(current_document)) { + if (current_document && completed_url.ProtocolIsJavaScript()) { String script_source = DecodeURLEscapeSequences( completed_url.GetString(), DecodeURLMode::kUTF8OrIsomorphic); - if (!current_document->GetContentSecurityPolicy()->AllowInline( + if (!current_document->GetContentSecurityPolicyForWorld()->AllowInline( ContentSecurityPolicy::InlineType::kNavigation, nullptr /* element */, script_source, String() /* nonce */, current_document->Url(), OrdinalNumber())) {
diff --git a/third_party/blink/renderer/core/frame/location.h b/third_party/blink/renderer/core/frame/location.h index 29a92b3..2b8601a 100644 --- a/third_party/blink/renderer/core/frame/location.h +++ b/third_party/blink/renderer/core/frame/location.h
@@ -100,6 +100,8 @@ // Returns true if the associated Window is the active Window in the frame. bool IsAttached() const; + // Note: SetLocation should be called synchronously from the DOM operation to + // ensure we use the correct Javascript world for CSP checks. enum class SetLocationPolicy { kNormal, kReplaceThisFrame }; void SetLocation(const String&, LocalDOMWindow* current_window,
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc index b12520b..ce93c3b 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc
@@ -2527,6 +2527,7 @@ PictureInPictureController::From(node->GetDocument()) .ExitPictureInPicture(ToHTMLVideoElement(media_element), nullptr); } + break; } }
diff --git a/third_party/blink/renderer/core/html/media/html_media_element_test.cc b/third_party/blink/renderer/core/html/media/html_media_element_test.cc index f38e4f1..040ed5c 100644 --- a/third_party/blink/renderer/core/html/media/html_media_element_test.cc +++ b/third_party/blink/renderer/core/html/media/html_media_element_test.cc
@@ -19,6 +19,7 @@ #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/network/network_state_notifier.h" #include "third_party/blink/renderer/platform/testing/empty_web_media_player.h" +#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" using ::testing::AnyNumber; @@ -315,7 +316,7 @@ // - Policy: DocumentUserActivation (aka. unified autoplay) // - MEI: low; // - Frame received user gesture. - RuntimeEnabledFeatures::SetMediaEngagementBypassAutoplayPoliciesEnabled(true); + ScopedMediaEngagementBypassAutoplayPoliciesForTest scoped_feature(true); Media()->GetDocument().GetSettings()->SetAutoplayPolicy( AutoplayPolicy::Type::kDocumentUserActivationRequired); LocalFrame::NotifyUserActivation(Media()->GetDocument().GetFrame()); @@ -331,7 +332,7 @@ // - Policy: DocumentUserActivation (aka. unified autoplay) // - MEI: high; // - Frame received user gesture. - RuntimeEnabledFeatures::SetMediaEngagementBypassAutoplayPoliciesEnabled(true); + ScopedMediaEngagementBypassAutoplayPoliciesForTest scoped_feature(true); Media()->GetDocument().GetSettings()->SetAutoplayPolicy( AutoplayPolicy::Type::kDocumentUserActivationRequired); SimulateHighMediaEngagement(); @@ -348,7 +349,7 @@ // - Policy: DocumentUserActivation (aka. unified autoplay) // - MEI: high; // - Frame did not receive user gesture. - RuntimeEnabledFeatures::SetMediaEngagementBypassAutoplayPoliciesEnabled(true); + ScopedMediaEngagementBypassAutoplayPoliciesForTest scoped_feature(true); Media()->GetDocument().GetSettings()->SetAutoplayPolicy( AutoplayPolicy::Type::kDocumentUserActivationRequired); SimulateHighMediaEngagement();
diff --git a/third_party/blink/renderer/core/html/media/video_auto_fullscreen_test.cc b/third_party/blink/renderer/core/html/media/video_auto_fullscreen_test.cc index c1a36918..b6ea07b9 100644 --- a/third_party/blink/renderer/core/html/media/video_auto_fullscreen_test.cc +++ b/third_party/blink/renderer/core/html/media/video_auto_fullscreen_test.cc
@@ -14,6 +14,7 @@ #include "third_party/blink/renderer/core/html_names.h" #include "third_party/blink/renderer/core/testing/wait_for_event.h" #include "third_party/blink/renderer/platform/testing/empty_web_media_player.h" +#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" namespace blink { @@ -52,11 +53,11 @@ WebWidget* web_widget_; }; -class VideoAutoFullscreen : public testing::Test { +class VideoAutoFullscreen : public testing::Test, + private ScopedVideoAutoFullscreenForTest { public: + VideoAutoFullscreen() : ScopedVideoAutoFullscreenForTest(true) {} void SetUp() override { - RuntimeEnabledFeatures::SetVideoAutoFullscreenEnabled(true); - web_view_helper_.Initialize(&web_frame_client_); GetWebView()->GetSettings()->SetAutoplayPolicy( WebSettings::AutoplayPolicy::kUserGestureRequired);
diff --git a/third_party/blink/renderer/core/html/portal/html_portal_element.cc b/third_party/blink/renderer/core/html/portal/html_portal_element.cc index bf97a2d..4a7fa7a60 100644 --- a/third_party/blink/renderer/core/html/portal/html_portal_element.cc +++ b/third_party/blink/renderer/core/html/portal/html_portal_element.cc
@@ -6,6 +6,7 @@ #include <utility> #include "services/service_manager/public/cpp/interface_provider.h" +#include "third_party/blink/public/mojom/referrer.mojom-blink.h" #include "third_party/blink/renderer/bindings/core/v8/script_event_listener.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" @@ -36,7 +37,9 @@ #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" +#include "third_party/blink/renderer/platform/weborigin/referrer.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" +#include "third_party/blink/renderer/platform/weborigin/security_policy.h" #include "third_party/blink/renderer/platform/wtf/functional.h" namespace blink { @@ -71,7 +74,15 @@ return; } - portal_ptr_->Navigate(url); + auto referrer_policy_to_use = ReferrerPolicyAttribute(); + if (referrer_policy_to_use == network::mojom::ReferrerPolicy::kDefault) + referrer_policy_to_use = GetDocument().GetReferrerPolicy(); + Referrer referrer = SecurityPolicy::GenerateReferrer( + referrer_policy_to_use, url, GetDocument().OutgoingReferrer()); + auto mojo_referrer = mojom::blink::Referrer::New( + KURL(NullURL(), referrer.referrer), referrer.referrer_policy); + + portal_ptr_->Navigate(url, std::move(mojo_referrer)); } void HTMLPortalElement::ConsumePortal() { @@ -344,6 +355,16 @@ return; } + if (params.name == html_names::kReferrerpolicyAttr) { + referrer_policy_ = network::mojom::ReferrerPolicy::kDefault; + if (!params.new_value.IsNull()) { + SecurityPolicy::ReferrerPolicyFromString( + params.new_value, kDoNotSupportReferrerPolicyLegacyKeywords, + &referrer_policy_); + } + return; + } + struct { const QualifiedName& name; const AtomicString& event_name; @@ -373,4 +394,8 @@ SetEmbeddedContentView(ContentFrame()->View()); } +network::mojom::ReferrerPolicy HTMLPortalElement::ReferrerPolicyAttribute() { + return referrer_policy_; +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/html/portal/html_portal_element.h b/third_party/blink/renderer/core/html/portal/html_portal_element.h index 296f1022..26cbfe5 100644 --- a/third_party/blink/renderer/core/html/portal/html_portal_element.h +++ b/third_party/blink/renderer/core/html/portal/html_portal_element.h
@@ -95,6 +95,7 @@ return ParsedFeaturePolicy(); } void AttachLayoutTree(AttachContext& context) override; + network::mojom::ReferrerPolicy ReferrerPolicyAttribute() override; // Uniquely identifies the portal, this token is used by the browser process // to reference this portal when communicating with the renderer. @@ -106,6 +107,9 @@ // right before the promise returned by activate() is resolved or rejected. bool is_activating_ = false; + network::mojom::ReferrerPolicy referrer_policy_ = + network::mojom::ReferrerPolicy::kDefault; + mojom::blink::PortalAssociatedPtr portal_ptr_; mojo::AssociatedBinding<mojom::blink::PortalClient> portal_client_binding_; };
diff --git a/third_party/blink/renderer/core/html/portal/html_portal_element.idl b/third_party/blink/renderer/core/html/portal/html_portal_element.idl index cb1b02f..b71a0ab 100644 --- a/third_party/blink/renderer/core/html/portal/html_portal_element.idl +++ b/third_party/blink/renderer/core/html/portal/html_portal_element.idl
@@ -7,6 +7,8 @@ [Exposed=Window, HTMLConstructor, RuntimeEnabled=Portals] interface HTMLPortalElement : HTMLElement { [CEReactions, Reflect, URL, RaisesException=Setter] attribute URLString src; + [CEReactions, Reflect, ReflectOnly=("","no-referrer","origin","no-referrer-when-downgrade","origin-when-cross-origin","unsafe-url"), ReflectMissing="", ReflectInvalid=""] attribute DOMString referrerPolicy; + [CallWith=ScriptState] Promise<void> activate(optional PortalActivateOptions options); [CallWith=ScriptState, RaisesException] void postMessage(any message, DOMString targetOrigin, optional sequence<object> transfer = []);
diff --git a/third_party/blink/renderer/core/layout/layout_flexible_box.cc b/third_party/blink/renderer/core/layout/layout_flexible_box.cc index 17fe058..5adaf7b 100644 --- a/third_party/blink/renderer/core/layout/layout_flexible_box.cc +++ b/third_party/blink/renderer/core/layout/layout_flexible_box.cc
@@ -1665,11 +1665,8 @@ } if (child_needs_relayout || !child.HasOverrideLogicalHeight()) child.SetOverrideLogicalHeight(flex_item.cross_axis_size); - if (child_needs_relayout) { - // TODO(cbiesinger): Why is this necessary? - child.SetLogicalHeight(LayoutUnit()); + if (child_needs_relayout) child.ForceLayout(); - } } else if (!flex_item.MainAxisIsInlineAxis() && child.StyleRef().LogicalWidth().IsAuto()) { if (flex_item.cross_axis_size != child.LogicalWidth()) {
diff --git a/third_party/blink/renderer/core/layout/layout_inline.cc b/third_party/blink/renderer/core/layout/layout_inline.cc index 17b2b0e..dbbb508 100644 --- a/third_party/blink/renderer/core/layout/layout_inline.cc +++ b/third_party/blink/renderer/core/layout/layout_inline.cc
@@ -1292,14 +1292,11 @@ if (IsInLayoutNGInlineFormattingContext()) { PhysicalRect result; NGPaintFragment::InlineFragmentsIncludingCulledFor( - *this, - [](NGPaintFragment* fragment, void* context) { - PhysicalRect* result = static_cast<PhysicalRect*>(context); + *this, [&result](const NGPaintFragment* fragment) { PhysicalRect child_rect = fragment->InkOverflow(); child_rect.offset += fragment->InlineOffsetToContainerBox(); - result->Unite(child_rect); - }, - &result); + result.Unite(child_rect); + }); return result; }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc index d2d3a04..e28568c 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc
@@ -9,23 +9,21 @@ #include "third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.h" #include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h" #include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h" +#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" namespace blink { namespace { -class NGColumnLayoutAlgorithmTest : public NGBaseLayoutAlgorithmTest { +class NGColumnLayoutAlgorithmTest + : public NGBaseLayoutAlgorithmTest, + private ScopedLayoutNGBlockFragmentationForTest { protected: + NGColumnLayoutAlgorithmTest() + : ScopedLayoutNGBlockFragmentationForTest(true) {} + void SetUp() override { NGBaseLayoutAlgorithmTest::SetUp(); style_ = ComputedStyle::Create(); - was_block_fragmentation_enabled_ = - RuntimeEnabledFeatures::LayoutNGBlockFragmentationEnabled(); - RuntimeEnabledFeatures::SetLayoutNGBlockFragmentationEnabled(true); - } - - void TearDown() override { - RuntimeEnabledFeatures::SetLayoutNGBlockFragmentationEnabled( - was_block_fragmentation_enabled_); } scoped_refptr<const NGPhysicalBoxFragment> RunBlockLayoutAlgorithm( @@ -52,7 +50,6 @@ } scoped_refptr<ComputedStyle> style_; - bool was_block_fragmentation_enabled_ = false; }; TEST_F(NGColumnLayoutAlgorithmTest, EmptyMulticol) {
diff --git a/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm_test.cc b/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm_test.cc index d1aae7b..1eb6c26b 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm_test.cc
@@ -8,26 +8,22 @@ #include "third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h" #include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h" #include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h" +#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" namespace blink { namespace { -class NGFieldsetLayoutAlgorithmTest : public NGBaseLayoutAlgorithmTest { +class NGFieldsetLayoutAlgorithmTest + : public NGBaseLayoutAlgorithmTest, + private ScopedLayoutNGFieldsetForTest, + private ScopedLayoutNGBlockFragmentationForTest { protected: + NGFieldsetLayoutAlgorithmTest() + : ScopedLayoutNGFieldsetForTest(true), + ScopedLayoutNGBlockFragmentationForTest(true) {} void SetUp() override { NGBaseLayoutAlgorithmTest::SetUp(); style_ = ComputedStyle::Create(); - was_fieldset_enabled_ = RuntimeEnabledFeatures::LayoutNGFieldsetEnabled(); - was_block_fragmentation_enabled_ = - RuntimeEnabledFeatures::LayoutNGBlockFragmentationEnabled(); - RuntimeEnabledFeatures::SetLayoutNGFieldsetEnabled(true); - RuntimeEnabledFeatures::SetLayoutNGBlockFragmentationEnabled(true); - } - - void TearDown() override { - RuntimeEnabledFeatures::SetLayoutNGFieldsetEnabled(was_fieldset_enabled_); - RuntimeEnabledFeatures::SetLayoutNGBlockFragmentationEnabled( - was_block_fragmentation_enabled_); } scoped_refptr<const NGPhysicalBoxFragment> RunBlockLayoutAlgorithm( @@ -75,8 +71,6 @@ } scoped_refptr<ComputedStyle> style_; - bool was_fieldset_enabled_ = false; - bool was_block_fragmentation_enabled_ = false; }; TEST_F(NGFieldsetLayoutAlgorithmTest, Empty) {
diff --git a/third_party/blink/renderer/core/loader/frame_loader.cc b/third_party/blink/renderer/core/loader/frame_loader.cc index 4867a79..eba2983 100644 --- a/third_party/blink/renderer/core/loader/frame_loader.cc +++ b/third_party/blink/renderer/core/loader/frame_loader.cc
@@ -37,6 +37,8 @@ #include "third_party/blink/renderer/core/loader/frame_loader.h" #include <memory> +#include <utility> + #include "base/auto_reset.h" #include "base/unguessable_token.h" #include "third_party/blink/public/common/features.h" @@ -417,6 +419,11 @@ frame_->FinishedLoading(); } + // When a subframe finishes loading, the parent should check if *all* + // subframes have finished loading (which may mean that the parent can declare + // that the parent itself has finished loading). This local-subframe-focused + // code has a remote-subframe equivalent in + // WebRemoteFrameImpl::DidStopLoading. Frame* parent = frame_->Tree().Parent(); if (parent) parent->CheckCompleted();
diff --git a/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.cc b/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.cc index 2c55ff6..eda7b801d 100644 --- a/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.cc +++ b/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.cc
@@ -161,7 +161,7 @@ if (!image) { // Undocumented exception (not in spec) exception_state.ThrowDOMException(DOMExceptionCode::kUnknownError, - "Out of memory"); + "ImageBitmap construction failed"); } return image; @@ -305,7 +305,13 @@ bool can_use_gpu = false; CanvasResourceProvider::PresentationMode presentation_mode = CanvasResourceProvider::kDefaultPresentationMode; - if (Is2d()) { + if (Is3d()) { + if (RuntimeEnabledFeatures::WebGLImageChromiumEnabled()) { + presentation_mode = + CanvasResourceProvider::kAllowImageChromiumPresentationMode; + } + can_use_gpu = SharedGpuContext::IsGpuCompositingEnabled(); + } else { if (RuntimeEnabledFeatures::Canvas2dImageChromiumEnabled()) { presentation_mode = CanvasResourceProvider::kAllowImageChromiumPresentationMode; @@ -314,12 +320,6 @@ RuntimeEnabledFeatures::Accelerated2dCanvasEnabled()) { can_use_gpu = true; } - } else if (Is3d()) { - if (RuntimeEnabledFeatures::WebGLImageChromiumEnabled()) { - presentation_mode = - CanvasResourceProvider::kAllowImageChromiumPresentationMode; - } - can_use_gpu = SharedGpuContext::IsGpuCompositingEnabled(); } IntSize surface_size(width(), height());
diff --git a/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h b/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h index 09a5e503..e03c557 100644 --- a/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h +++ b/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h
@@ -26,13 +26,13 @@ class ImageBitmap; #if defined(SUPPORT_WEBGL2_COMPUTE_CONTEXT) class - OffscreenCanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContextOrWebGL2ComputeRenderingContext; -typedef OffscreenCanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContextOrWebGL2ComputeRenderingContext + OffscreenCanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContextOrWebGL2ComputeRenderingContextOrImageBitmapRenderingContext; +typedef OffscreenCanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContextOrWebGL2ComputeRenderingContextOrImageBitmapRenderingContext OffscreenRenderingContext; #else class - OffscreenCanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContext; -typedef OffscreenCanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContext + OffscreenCanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContextOrImageBitmapRenderingContext; +typedef OffscreenCanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContextOrImageBitmapRenderingContext OffscreenRenderingContext; #endif
diff --git a/third_party/blink/renderer/core/page/create_window.cc b/third_party/blink/renderer/core/page/create_window.cc index d4e5edc3c..8b97b28 100644 --- a/third_party/blink/renderer/core/page/create_window.cc +++ b/third_party/blink/renderer/core/page/create_window.cc
@@ -288,13 +288,11 @@ AllocateSessionStorageNamespaceId(); Page* old_page = opener_frame.GetPage(); - if (base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)) { - // TODO(dmurph): Don't copy session storage when features.noopener is true: - // https://html.spec.whatwg.org/C/#copy-session-storage - // https://crbug.com/771959 - CoreInitializer::GetInstance().CloneSessionStorage(old_page, - new_namespace_id); - } + // TODO(dmurph): Don't copy session storage when features.noopener is true: + // https://html.spec.whatwg.org/C/#copy-session-storage + // https://crbug.com/771959 + CoreInitializer::GetInstance().CloneSessionStorage(old_page, + new_namespace_id); Page* page = old_page->GetChromeClient().CreateWindow( &opener_frame, request, frame_name, features, sandbox_flags,
diff --git a/third_party/blink/renderer/core/paint/compositing/graphics_layer_updater.cc b/third_party/blink/renderer/core/paint/compositing/graphics_layer_updater.cc index 3d97bdf..cc3c6d1 100644 --- a/third_party/blink/renderer/core/paint/compositing/graphics_layer_updater.cc +++ b/third_party/blink/renderer/core/paint/compositing/graphics_layer_updater.cc
@@ -42,11 +42,12 @@ UpdateContext() : compositing_stacking_context_(nullptr), compositing_ancestor_(nullptr), - use_slow_path(false) {} + use_slow_path_(false) {} UpdateContext(const UpdateContext& other, const PaintLayer& layer) : compositing_stacking_context_(other.compositing_stacking_context_), - compositing_ancestor_(other.CompositingContainer(layer)) { + compositing_ancestor_(other.CompositingContainer(layer)), + use_slow_path_(other.use_slow_path_) { CompositingState compositing_state = layer.GetCompositingState(); if (compositing_state != kNotComposited && compositing_state != kPaintsIntoGroupedBacking) { @@ -64,11 +65,11 @@ // for these situations, to simplify the logic. if (layer.GetLayoutObject().IsSVGRoot() || layer.IsReplacedNormalFlowStacking()) - use_slow_path = true; + use_slow_path_ = true; } const PaintLayer* CompositingContainer(const PaintLayer& layer) const { - if (use_slow_path) + if (use_slow_path_) return layer.EnclosingLayerWithCompositedLayerMapping(kExcludeSelf); const PaintLayer* compositing_container; @@ -100,7 +101,7 @@ private: const PaintLayer* compositing_stacking_context_; const PaintLayer* compositing_ancestor_; - bool use_slow_path; + bool use_slow_path_; }; GraphicsLayerUpdater::GraphicsLayerUpdater() : needs_rebuild_tree_(false) {}
diff --git a/third_party/blink/renderer/core/paint/image_element_timing_test.cc b/third_party/blink/renderer/core/paint/image_element_timing_test.cc index 8dbf7e4..148f345 100644 --- a/third_party/blink/renderer/core/paint/image_element_timing_test.cc +++ b/third_party/blink/renderer/core/paint/image_element_timing_test.cc
@@ -128,10 +128,8 @@ <div id="target">/div> )HTML"); LayoutObject* object = GetLayoutObjectByElementId("target"); - ImageResourceContent* content = object->MutableStyle() - ->AccessBackgroundLayers() - .GetImage() - ->CachedImage(); + ImageResourceContent* content = + object->Style()->BackgroundLayers().GetImage()->CachedImage(); UpdateAllLifecyclePhasesForTest(); EXPECT_EQ(GetBackgroundImagesNotified().size(), 1u); EXPECT_TRUE(
diff --git a/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc b/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc index ad6c444..664392f 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc +++ b/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc
@@ -340,12 +340,8 @@ DCHECK(layout_object->IsLayoutBlockFlow()); const auto& layout_block = To<LayoutBlock>(*layout_object); DCHECK(layout_block.ChildrenInline()); - if (ShouldPaintDescendantOutlines(paint_info.phase)) { - ObjectPainter(layout_block).PaintInlineChildrenOutlines(paint_info); - } else { - PaintLineBoxChildren(box_fragment_.Children(), paint_info.ForDescendants(), - paint_offset); - } + PaintLineBoxChildren(box_fragment_.Children(), paint_info.ForDescendants(), + paint_offset); } void NGBoxFragmentPainter::PaintBlockChildren(const PaintInfo& paint_info) {
diff --git a/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.cc b/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.cc index 1360759..450fcde 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.cc +++ b/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.cc
@@ -493,34 +493,6 @@ return FragmentRange(nullptr, false); } -void NGPaintFragment::InlineFragmentsIncludingCulledFor( - const LayoutObject& layout_object, - Callback callback, - void* context) { - DCHECK(layout_object.IsInLayoutNGInlineFormattingContext()); - - auto fragments = InlineFragmentsFor(&layout_object); - if (!fragments.IsEmpty()) { - for (NGPaintFragment* fragment : fragments) - callback(fragment, context); - return; - } - - // This is a culled LayoutInline. Iterate children's fragments. - if (const LayoutInline* layout_inline = - ToLayoutInlineOrNull(&layout_object)) { - for (LayoutObject* child = layout_inline->FirstChild(); child; - child = child->NextSibling()) { - // |layout_inline| may still have non-inline children, e.g., - // 'position:absolute'. Skip them as they don't contribute to the culled - // rects of |layout_inline|. - if (!child->IsInline()) - continue; - InlineFragmentsIncludingCulledFor(*child, callback, context); - } - } -} - const NGPaintFragment* NGPaintFragment::LastForSameLayoutObject() const { return const_cast<NGPaintFragment*>(this)->LastForSameLayoutObject(); }
diff --git a/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h b/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h index 3ad12a0..9ca08b8 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h +++ b/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h
@@ -9,6 +9,7 @@ #include <memory> #include "third_party/blink/renderer/core/core_export.h" +#include "third_party/blink/renderer/core/layout/layout_inline.h" #include "third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h" #include "third_party/blink/renderer/core/scroll/scroll_types.h" #include "third_party/blink/renderer/platform/graphics/paint/display_item_client.h" @@ -258,10 +259,9 @@ // Same as |InlineFragmentsFor()| but this function includes descendants if // the |layout_object| is culled (i.e., did not generate fragments.) - typedef void (*Callback)(NGPaintFragment*, void*); + template <typename Callback> static void InlineFragmentsIncludingCulledFor(const LayoutObject&, - Callback callback, - void* context); + Callback callback); const NGPaintFragment* LastForSameLayoutObject() const; NGPaintFragment* LastForSameLayoutObject(); @@ -375,6 +375,34 @@ unsigned is_dirty_inline_ : 1; }; +template <typename Callback> +void NGPaintFragment::InlineFragmentsIncludingCulledFor( + const LayoutObject& layout_object, + Callback callback) { + DCHECK(layout_object.IsInLayoutNGInlineFormattingContext()); + + auto fragments = InlineFragmentsFor(&layout_object); + if (!fragments.IsEmpty()) { + for (const NGPaintFragment* fragment : fragments) + callback(fragment); + return; + } + + // This is a culled LayoutInline. Iterate children's fragments. + if (const LayoutInline* layout_inline = + ToLayoutInlineOrNull(&layout_object)) { + for (LayoutObject* child = layout_inline->FirstChild(); child; + child = child->NextSibling()) { + // |layout_inline| may still have non-inline children, e.g., + // 'position:absolute'. Skip them as they don't contribute to the culled + // rects of |layout_inline|. + if (!child->IsInline()) + continue; + InlineFragmentsIncludingCulledFor(*child, callback); + } + } +} + extern template class CORE_EXTERN_TEMPLATE_EXPORT NGPaintFragment::List<NGPaintFragment::TraverseNextForSameLayoutObject>; extern template class CORE_EXTERN_TEMPLATE_EXPORT
diff --git a/third_party/blink/renderer/devtools/front_end/console/ConsolePinPane.js b/third_party/blink/renderer/devtools/front_end/console/ConsolePinPane.js index bf930bf..967df6c3 100644 --- a/third_party/blink/renderer/devtools/front_end/console/ConsolePinPane.js +++ b/third_party/blink/renderer/devtools/front_end/console/ConsolePinPane.js
@@ -102,6 +102,13 @@ super(); const deletePinIcon = UI.Icon.create('smallicon-cross', 'console-delete-pin'); deletePinIcon.addEventListener('click', () => pinPane._removePin(this)); + deletePinIcon.addEventListener('keydown', event => { + if (isEnterKey(event) || event.key === ' ') + pinPane._removePin(this); + }); + deletePinIcon.tabIndex = 0; + UI.ARIAUtils.setAccessibleName(deletePinIcon, ls`Remove expression`); + UI.ARIAUtils.markAsButton(deletePinIcon); const fragment = UI.Fragment.build` <div class='console-pin'>
diff --git a/third_party/blink/renderer/devtools/front_end/console/ConsoleView.js b/third_party/blink/renderer/devtools/front_end/console/ConsoleView.js index 7600d808..42ef6f0 100644 --- a/third_party/blink/renderer/devtools/front_end/console/ConsoleView.js +++ b/third_party/blink/renderer/devtools/front_end/console/ConsoleView.js
@@ -132,6 +132,8 @@ settingsPane.show(this._contentsElement); settingsPane.element.classList.add('console-settings-pane'); + UI.ARIAUtils.setAccessibleName(settingsPane.element, ls`Console settings`); + UI.ARIAUtils.markAsGroup(settingsPane.element); const settingsToolbarLeft = new UI.Toolbar('', settingsPane.element); settingsToolbarLeft.makeVertical(); settingsToolbarLeft.appendToolbarItem(this._hideNetworkMessagesCheckbox);
diff --git a/third_party/blink/renderer/devtools/front_end/console/consolePinPane.css b/third_party/blink/renderer/devtools/front_end/console/consolePinPane.css index 5fbf25d..32367f4 100644 --- a/third_party/blink/renderer/devtools/front_end/console/consolePinPane.css +++ b/third_party/blink/renderer/devtools/front_end/console/consolePinPane.css
@@ -71,7 +71,8 @@ cursor: pointer; } -.console-delete-pin:hover { +.console-delete-pin:hover, +.console-delete-pin[data-keyboard-focus="true"]:focus { opacity: 1; }
diff --git a/third_party/blink/renderer/devtools/front_end/har_importer/HARFormat.js b/third_party/blink/renderer/devtools/front_end/har_importer/HARFormat.js index c8178e09..1fa99ec 100644 --- a/third_party/blink/renderer/devtools/front_end/har_importer/HARFormat.js +++ b/third_party/blink/renderer/devtools/front_end/har_importer/HARFormat.js
@@ -169,12 +169,38 @@ // Chrome specific. this._fromCache = HARImporter.HARBase._optionalString(data['_fromCache']); - if (data['_initiator']) - this._initiator = new HARImporter.HARInitiator(data['_initiator']); + this._initiator = this._importInitiator(data['_initiator']); this._priority = HARImporter.HARBase._optionalString(data['_priority']); this._resourceType = HARImporter.HARBase._optionalString(data['_resourceType']); - if (Array.isArray(data['_webSocketMessages'])) - this._webSocketMessages = data['_webSocketMessages'].map(message => new HARImporter.HARWebSocketMessage(message)); + this._webSocketMessages = this._importWebSocketMessages(data['_webSocketMessages']); + } + + /** + * @param {*} initiator + * @return {!HARImporter.HARInitiator|undefined} + */ + _importInitiator(initiator) { + if (typeof initiator !== 'object') + return; + + return new HARImporter.HARInitiator(initiator); + } + + /** + * @param {*} inputMessages + * @return {!Array<!HARImporter.HARInitiator>|undefined} + */ + _importWebSocketMessages(inputMessages) { + if (!Array.isArray(inputMessages)) + return; + + const outputMessages = []; + for (const message of inputMessages) { + if (typeof message !== 'object') + return; + outputMessages.push(new HARImporter.HARWebSocketMessage(message)); + } + return outputMessages; } };
diff --git a/third_party/blink/renderer/modules/canvas/canvas2d/hit_region.h b/third_party/blink/renderer/modules/canvas/canvas2d/hit_region.h index 1816f5b..d581278 100644 --- a/third_party/blink/renderer/modules/canvas/canvas2d/hit_region.h +++ b/third_party/blink/renderer/modules/canvas/canvas2d/hit_region.h
@@ -11,6 +11,7 @@ #include "third_party/blink/renderer/modules/canvas/canvas2d/hit_region_options.h" #include "third_party/blink/renderer/platform/graphics/path.h" #include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/wtf/linked_hash_set.h" namespace blink { @@ -36,9 +37,11 @@ WindRule fill_rule_; }; -class HitRegionManager final : public GarbageCollected<HitRegionManager> { +class HitRegionManager final + : public GarbageCollectedFinalized<HitRegionManager> { public: HitRegionManager() = default; + ~HitRegionManager() {} void AddHitRegion(HitRegion*); @@ -57,7 +60,7 @@ void Trace(blink::Visitor*); private: - typedef HeapListHashSet<Member<HitRegion>> HitRegionList; + typedef HeapLinkedHashSet<Member<HitRegion>> HitRegionList; typedef HitRegionList::const_reverse_iterator HitRegionIterator; typedef HeapHashMap<String, Member<HitRegion>> HitRegionIdMap; typedef HeapHashMap<Member<const Element>, Member<HitRegion>>
diff --git a/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.cc b/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.cc index 48c3962..90bcad5e 100644 --- a/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.cc +++ b/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.cc
@@ -4,8 +4,11 @@ #include "third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.h" +#include <utility> +#include "third_party/blink/renderer/bindings/modules/v8/offscreen_rendering_context.h" #include "third_party/blink/renderer/bindings/modules/v8/rendering_context.h" #include "third_party/blink/renderer/core/imagebitmap/image_bitmap.h" +#include "third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.h" #include "third_party/blink/renderer/platform/graphics/static_bitmap_image.h" namespace blink { @@ -21,6 +24,10 @@ RenderingContext& result) { result.SetImageBitmapRenderingContext(this); } +void ImageBitmapRenderingContext::SetOffscreenCanvasGetContextResult( + OffscreenRenderingContext& result) { + result.SetImageBitmapRenderingContext(this); +} void ImageBitmapRenderingContext::transferFromImageBitmap( ImageBitmap* image_bitmap, @@ -39,6 +46,15 @@ SetImage(image_bitmap); } +ImageBitmap* ImageBitmapRenderingContext::TransferToImageBitmap(ScriptState*) { + scoped_refptr<StaticBitmapImage> image = GetImageAndResetInternal(); + if (!image) + return nullptr; + + image->Transfer(); + return ImageBitmap::Create(std::move(image)); +} + CanvasRenderingContext* ImageBitmapRenderingContext::Factory::Create( CanvasRenderingContextHost* host, const CanvasContextCreationAttributesCore& attrs) {
diff --git a/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.h b/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.h index 7b08362..016be9b 100644 --- a/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.h +++ b/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.h
@@ -7,6 +7,7 @@ #include "base/macros.h" #include "base/memory/scoped_refptr.h" +#include "third_party/blink/renderer/core/html/canvas/canvas_rendering_context.h" #include "third_party/blink/renderer/core/html/canvas/canvas_rendering_context_factory.h" #include "third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context_base.h" #include "third_party/blink/renderer/modules/modules_export.h" @@ -46,8 +47,10 @@ ContextType GetContextType() const override { return CanvasRenderingContext::kContextImageBitmap; } + ImageBitmap* TransferToImageBitmap(ScriptState*) override; void SetCanvasGetContextResult(RenderingContext&) final; + void SetOffscreenCanvasGetContextResult(OffscreenRenderingContext&) final; ~ImageBitmapRenderingContext() override; };
diff --git a/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.idl b/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.idl index f90843824..0e7ad6f 100644 --- a/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.idl +++ b/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context.idl
@@ -4,9 +4,11 @@ // https://html.spec.whatwg.org/C/#the-imagebitmap-rendering-context -interface ImageBitmapRenderingContext { +[ + Exposed=(Window,Worker) +] interface ImageBitmapRenderingContext { // back-reference to the canvas - readonly attribute HTMLCanvasElement canvas; + [ImplementedAs=getHTMLOrOffscreenCanvas] readonly attribute (HTMLCanvasElement or OffscreenCanvas) canvas; [RaisesException] void transferFromImageBitmap(ImageBitmap? bitmap); };
diff --git a/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context_base.cc b/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context_base.cc index 19586d8..801b914 100644 --- a/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context_base.cc +++ b/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context_base.cc
@@ -4,9 +4,11 @@ #include "third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context_base.h" +#include "third_party/blink/renderer/bindings/modules/v8/html_canvas_element_or_offscreen_canvas.h" #include "third_party/blink/renderer/bindings/modules/v8/rendering_context.h" #include "third_party/blink/renderer/core/imagebitmap/image_bitmap.h" #include "third_party/blink/renderer/platform/graphics/gpu/image_layer_bridge.h" +#include "third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.h" #include "third_party/blink/renderer/platform/graphics/graphics_context.h" #include "third_party/blink/renderer/platform/graphics/static_bitmap_image.h" #include "third_party/skia/include/core/SkImage.h" @@ -23,6 +25,15 @@ ImageBitmapRenderingContextBase::~ImageBitmapRenderingContextBase() = default; +void ImageBitmapRenderingContextBase::getHTMLOrOffscreenCanvas( + HTMLCanvasElementOrOffscreenCanvas& result) const { + if (Host()->IsOffscreenCanvas()) { + result.SetOffscreenCanvas(static_cast<OffscreenCanvas*>(Host())); + } else { + result.SetHTMLCanvasElement(static_cast<HTMLCanvasElement*>(Host())); + } +} + void ImageBitmapRenderingContextBase::Stop() { image_layer_bridge_->Dispose(); } @@ -44,6 +55,21 @@ return image_layer_bridge_->GetImage(); } +scoped_refptr<StaticBitmapImage> +ImageBitmapRenderingContextBase::GetImageAndResetInternal() { + if (!image_layer_bridge_->GetImage()) + return nullptr; + scoped_refptr<StaticBitmapImage> copy_image = image_layer_bridge_->GetImage(); + + SkBitmap black_bitmap; + black_bitmap.allocN32Pixels(copy_image->width(), copy_image->height()); + black_bitmap.eraseColor(SkColorSetRGB(0, 0, 0)); + image_layer_bridge_->SetImage( + StaticBitmapImage::Create(SkImage::MakeFromBitmap(black_bitmap))); + + return copy_image; +} + void ImageBitmapRenderingContextBase::SetUV(const FloatPoint& left_top, const FloatPoint& right_bottom) { image_layer_bridge_->SetUV(left_top, right_bottom); @@ -66,4 +92,36 @@ return image_layer_bridge_->IsAccelerated(); } +bool ImageBitmapRenderingContextBase::CanCreateCanvas2dResourceProvider() + const { + DCHECK(Host()); + DCHECK(Host()->IsOffscreenCanvas()); + return !!static_cast<OffscreenCanvas*>(Host())->GetOrCreateResourceProvider(); +} + +void ImageBitmapRenderingContextBase::PushFrame() { + DCHECK(Host()); + DCHECK(Host()->IsOffscreenCanvas()); + if (!CanCreateCanvas2dResourceProvider()) + return; + + scoped_refptr<StaticBitmapImage> image = image_layer_bridge_->GetImage(); + cc::PaintFlags paint_flags; + paint_flags.setBlendMode(SkBlendMode::kSrc); + Host()->ResourceProvider()->Canvas()->drawImage( + image->PaintImageForCurrentFrame(), 0, 0, &paint_flags); + scoped_refptr<CanvasResource> resource = + Host()->ResourceProvider()->ProduceCanvasResource(); + Host()->PushFrame( + std::move(resource), + SkIRect::MakeWH(image_layer_bridge_->GetImage()->Size().Width(), + image_layer_bridge_->GetImage()->Size().Height())); +} + +bool ImageBitmapRenderingContextBase::IsOriginTopLeft() const { + if (Host()->IsOffscreenCanvas()) + return false; + return IsAccelerated(); +} + } // namespace blink
diff --git a/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context_base.h b/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context_base.h index ec97760..7cb61cd 100644 --- a/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context_base.h +++ b/third_party/blink/renderer/modules/canvas/imagebitmap/image_bitmap_rendering_context_base.h
@@ -19,6 +19,7 @@ class ImageBitmap; class ImageLayerBridge; +class HTMLCanvasElementOrOffscreenCanvas; class MODULES_EXPORT ImageBitmapRenderingContextBase : public CanvasRenderingContext { @@ -29,18 +30,32 @@ void Trace(blink::Visitor*) override; - HTMLCanvasElement* canvas() { - DCHECK(!Host() || !Host()->IsOffscreenCanvas()); + // TODO(juanmihd): Remove this method crbug.com/941579 + HTMLCanvasElement* canvas() const { + if (Host()->IsOffscreenCanvas()) + return nullptr; return static_cast<HTMLCanvasElement*>(Host()); } + bool CanCreateCanvas2dResourceProvider() const; + void getHTMLOrOffscreenCanvas(HTMLCanvasElementOrOffscreenCanvas&) const; + void SetIsHidden(bool) override {} bool isContextLost() const override { return false; } void SetImage(ImageBitmap*); + // The acceleration hing here is ignored as GetImage(AccelerationHint) only + // calls to image_layer_bridge->GetImage(), without giving it a hint scoped_refptr<StaticBitmapImage> GetImage(AccelerationHint) const final; + // This function resets the internal image resource to a image of the same + // size than the original, with the same properties, but completely black. + // This is used to follow the standard regarding transferToBitmap + scoped_refptr<StaticBitmapImage> GetImageAndResetInternal(); void SetUV(const FloatPoint& left_top, const FloatPoint& right_bottom); bool IsComposited() const final { return true; } bool IsAccelerated() const final; + void PushFrame() override; + + bool IsOriginTopLeft() const override; cc::Layer* CcLayer() const final; // TODO(junov): handle lost contexts when content is GPU-backed
diff --git a/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module.idl b/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module.idl index 53440b10..7d321be 100644 --- a/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module.idl +++ b/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module.idl
@@ -6,8 +6,9 @@ typedef (OffscreenCanvasRenderingContext2D or WebGLRenderingContext or - WebGL2RenderingContext) OffscreenRenderingContext; -enum OffscreenRenderingContextType { "2d", "webgl", "webgl2", "webgl2-compute" }; + WebGL2RenderingContext or + ImageBitmapRenderingContext) OffscreenRenderingContext; +enum OffscreenRenderingContextType { "2d", "webgl", "webgl2", "webgl2-compute", "bitmaprenderer" }; [ ImplementedAs=OffscreenCanvasModule
diff --git a/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module_support_webgl2_compute.idl b/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module_support_webgl2_compute.idl index 954e9aa..b98939e 100644 --- a/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module_support_webgl2_compute.idl +++ b/third_party/blink/renderer/modules/canvas/offscreencanvas/offscreen_canvas_module_support_webgl2_compute.idl
@@ -7,8 +7,9 @@ typedef (OffscreenCanvasRenderingContext2D or WebGLRenderingContext or WebGL2RenderingContext or - WebGL2ComputeRenderingContext) OffscreenRenderingContext; -enum OffscreenRenderingContextType { "2d", "webgl", "webgl2", "webgl2-compute" }; + WebGL2ComputeRenderingContext or + ImageBitmapRenderingContext) OffscreenRenderingContext; +enum OffscreenRenderingContextType { "2d", "webgl", "webgl2", "webgl2-compute", "bitmaprenderer" }; [ ImplementedAs=OffscreenCanvasModule
diff --git a/third_party/blink/renderer/modules/exported/BUILD.gn b/third_party/blink/renderer/modules/exported/BUILD.gn index c034cde..835a823 100644 --- a/third_party/blink/renderer/modules/exported/BUILD.gn +++ b/third_party/blink/renderer/modules/exported/BUILD.gn
@@ -13,7 +13,6 @@ "web_dom_media_stream_track.cc", "web_embedded_worker_impl.cc", "web_embedded_worker_impl.h", - "web_storage_event_dispatcher_impl.cc", "web_user_media_request.cc", ]
diff --git a/third_party/blink/renderer/modules/manifest/manifest_parser.cc b/third_party/blink/renderer/modules/manifest/manifest_parser.cc index f7438c1a..90ebf5b 100644 --- a/third_party/blink/renderer/modules/manifest/manifest_parser.cc +++ b/third_party/blink/renderer/modules/manifest/manifest_parser.cc
@@ -519,7 +519,7 @@ "Enctype should be set to either application/x-www-form-urlencoded or " "multipart/form-data. It currently defaults to " "application/x-www-form-urlencoded"); - return mojom::blink::ManifestShareTarget::Enctype::kApplication; + return mojom::blink::ManifestShareTarget::Enctype::kFormUrlEncoded; } String value; @@ -528,10 +528,10 @@ String enctype = value.LowerASCII(); if (enctype == "application/x-www-form-urlencoded") - return mojom::blink::ManifestShareTarget::Enctype::kApplication; + return mojom::blink::ManifestShareTarget::Enctype::kFormUrlEncoded; if (enctype == "multipart/form-data") - return mojom::blink::ManifestShareTarget::Enctype::kMultipart; + return mojom::blink::ManifestShareTarget::Enctype::kMultipartFormData; return base::nullopt; } @@ -603,7 +603,7 @@ if (share_target->method == mojom::blink::ManifestShareTarget::Method::kGet) { if (share_target->enctype == - mojom::blink::ManifestShareTarget::Enctype::kMultipart) { + mojom::blink::ManifestShareTarget::Enctype::kMultipartFormData) { AddErrorInfo( "invalid enctype for GET method. Only " "application/x-www-form-urlencoded is allowed."); @@ -615,7 +615,7 @@ if (share_target->method != mojom::blink::ManifestShareTarget::Method::kPost || share_target->enctype != - mojom::blink::ManifestShareTarget::Enctype::kMultipart) { + mojom::blink::ManifestShareTarget::Enctype::kMultipartFormData) { AddErrorInfo("files are only supported with multipart/form-data POST."); return base::nullopt; }
diff --git a/third_party/blink/renderer/modules/manifest/manifest_parser_unittest.cc b/third_party/blink/renderer/modules/manifest/manifest_parser_unittest.cc index 459fff4..b65e0e0 100644 --- a/third_party/blink/renderer/modules/manifest/manifest_parser_unittest.cc +++ b/third_party/blink/renderer/modules/manifest/manifest_parser_unittest.cc
@@ -1662,7 +1662,7 @@ EXPECT_EQ(manifest->share_target->method, mojom::blink::ManifestShareTarget::Method::kGet); EXPECT_EQ(manifest->share_target->enctype, - mojom::blink::ManifestShareTarget::Enctype::kApplication); + mojom::blink::ManifestShareTarget::Enctype::kFormUrlEncoded); } // Auto-fill in "GET" for method and "application/x-www-form-urlencoded" for @@ -1677,7 +1677,7 @@ EXPECT_EQ(manifest->share_target->method, mojom::blink::ManifestShareTarget::Method::kGet); EXPECT_EQ(manifest->share_target->enctype, - mojom::blink::ManifestShareTarget::Enctype::kApplication); + mojom::blink::ManifestShareTarget::Enctype::kFormUrlEncoded); } // Invalid method values, return undefined. @@ -1743,7 +1743,7 @@ EXPECT_EQ(manifest->share_target->method, mojom::blink::ManifestShareTarget::Method::kPost); EXPECT_EQ(manifest->share_target->enctype, - mojom::blink::ManifestShareTarget::Enctype::kApplication); + mojom::blink::ManifestShareTarget::Enctype::kFormUrlEncoded); EXPECT_EQ(0u, GetErrorCount()); } @@ -1759,7 +1759,7 @@ EXPECT_EQ(manifest->share_target->method, mojom::blink::ManifestShareTarget::Method::kPost); EXPECT_EQ(manifest->share_target->enctype, - mojom::blink::ManifestShareTarget::Enctype::kMultipart); + mojom::blink::ManifestShareTarget::Enctype::kMultipartFormData); EXPECT_EQ(0u, GetErrorCount()); } @@ -1775,7 +1775,7 @@ EXPECT_EQ(manifest->share_target->method, mojom::blink::ManifestShareTarget::Method::kPost); EXPECT_EQ(manifest->share_target->enctype, - mojom::blink::ManifestShareTarget::Enctype::kMultipart); + mojom::blink::ManifestShareTarget::Enctype::kMultipartFormData); EXPECT_EQ(0u, GetErrorCount()); } @@ -1791,7 +1791,7 @@ EXPECT_EQ(manifest->share_target->method, mojom::blink::ManifestShareTarget::Method::kPost); EXPECT_EQ(manifest->share_target->enctype, - mojom::blink::ManifestShareTarget::Enctype::kMultipart); + mojom::blink::ManifestShareTarget::Enctype::kMultipartFormData); EXPECT_EQ(0u, GetErrorCount()); }
diff --git a/third_party/blink/renderer/modules/media_controls/elements/media_control_display_cutout_fullscreen_button_element_test.cc b/third_party/blink/renderer/modules/media_controls/elements/media_control_display_cutout_fullscreen_button_element_test.cc index b9fed8f..e7cf746 100644 --- a/third_party/blink/renderer/modules/media_controls/elements/media_control_display_cutout_fullscreen_button_element_test.cc +++ b/third_party/blink/renderer/modules/media_controls/elements/media_control_display_cutout_fullscreen_button_element_test.cc
@@ -15,6 +15,7 @@ #include "third_party/blink/renderer/modules/media_controls/media_controls_impl.h" #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" +#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" #include "third_party/blink/renderer/platform/text/platform_locale.h" @@ -36,12 +37,15 @@ } // namespace class MediaControlDisplayCutoutFullscreenButtonElementTest - : public PageTestBase { + : public PageTestBase, + private ScopedDisplayCutoutAPIForTest { public: static TouchEventInit* GetValidTouchEventInit() { return TouchEventInit::Create(); } + MediaControlDisplayCutoutFullscreenButtonElementTest() + : ScopedDisplayCutoutAPIForTest(true) {} void SetUp() override { chrome_client_ = MakeGarbageCollected<MockDisplayCutoutChromeClient>(); @@ -50,9 +54,6 @@ clients.chrome_client = chrome_client_.Get(); SetupPageWithClients(&clients, MakeGarbageCollected<EmptyLocalFrameClient>()); - - RuntimeEnabledFeatures::SetDisplayCutoutAPIEnabled(true); - video_ = MakeGarbageCollected<HTMLVideoElement>(GetDocument()); GetDocument().body()->AppendChild(video_); controls_ = MakeGarbageCollected<MediaControlsImpl>(*video_);
diff --git a/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate_test.cc b/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate_test.cc index b837ebb..284e9c8 100644 --- a/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate_test.cc +++ b/third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate_test.cc
@@ -17,6 +17,7 @@ #include "third_party/blink/renderer/core/testing/page_test_base.h" #include "third_party/blink/renderer/modules/media_controls/media_controls_impl.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" +#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" namespace blink { @@ -36,8 +37,14 @@ } // namespace -class MediaControlsDisplayCutoutDelegateTest : public PageTestBase { +class MediaControlsDisplayCutoutDelegateTest + : public PageTestBase, + private ScopedDisplayCutoutAPIForTest, + private ScopedMediaControlsExpandGestureForTest { public: + MediaControlsDisplayCutoutDelegateTest() + : ScopedDisplayCutoutAPIForTest(true), + ScopedMediaControlsExpandGestureForTest(true) {} void SetUp() override { chrome_client_ = MakeGarbageCollected<DisplayCutoutMockChromeClient>(); @@ -46,10 +53,6 @@ clients.chrome_client = chrome_client_.Get(); SetupPageWithClients(&clients, MakeGarbageCollected<EmptyLocalFrameClient>()); - - RuntimeEnabledFeatures::SetDisplayCutoutAPIEnabled(true); - RuntimeEnabledFeatures::SetMediaControlsExpandGestureEnabled(true); - GetDocument().write("<body><video id=video></body>"); }
diff --git a/third_party/blink/renderer/modules/modules_initializer.cc b/third_party/blink/renderer/modules/modules_initializer.cc index a52baf3..f8f82c2 100644 --- a/third_party/blink/renderer/modules/modules_initializer.cc +++ b/third_party/blink/renderer/modules/modules_initializer.cc
@@ -9,6 +9,7 @@ #include "base/memory/ptr_util.h" #include "third_party/blink/public/platform/interface_registry.h" #include "third_party/blink/public/platform/web_security_origin.h" +#include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/web/web_view_client.h" #include "third_party/blink/renderer/bindings/modules/v8/module_bindings_initializer.h" #include "third_party/blink/renderer/core/css/css_paint_image_generator.h" @@ -145,6 +146,8 @@ std::make_unique<WebGLRenderingContext::Factory>()); OffscreenCanvas::RegisterRenderingContextFactory( std::make_unique<WebGL2RenderingContext::Factory>()); + OffscreenCanvas::RegisterRenderingContextFactory( + std::make_unique<ImageBitmapRenderingContext::Factory>()); #if defined(SUPPORT_WEBGL2_COMPUTE_CONTEXT) OffscreenCanvas::RegisterRenderingContextFactory( std::make_unique<WebGL2ComputeRenderingContext::Factory>());
diff --git a/third_party/blink/renderer/modules/payments/OWNERS b/third_party/blink/renderer/modules/payments/OWNERS index 7444621..27254a0e 100644 --- a/third_party/blink/renderer/modules/payments/OWNERS +++ b/third_party/blink/renderer/modules/payments/OWNERS
@@ -5,3 +5,4 @@ mathp@chromium.org mek@chromium.org rouslan@chromium.org +danyao@chromium.org
diff --git a/third_party/blink/renderer/modules/storage/dom_window_storage.cc b/third_party/blink/renderer/modules/storage/dom_window_storage.cc index 80046d5..c6a1f42 100644 --- a/third_party/blink/renderer/modules/storage/dom_window_storage.cc +++ b/third_party/blink/renderer/modules/storage/dom_window_storage.cc
@@ -94,19 +94,12 @@ StorageNamespace* storage_namespace = StorageNamespace::From(page); if (!storage_namespace) return nullptr; - if (base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)) { - auto storage_area = - storage_namespace->GetCachedArea(document->GetSecurityOrigin()); - session_storage_ = - StorageArea::Create(document->GetFrame(), std::move(storage_area), - StorageArea::StorageType::kSessionStorage); - } else { - auto storage_area = - storage_namespace->GetWebStorageArea(document->GetSecurityOrigin()); - session_storage_ = - StorageArea::Create(document->GetFrame(), std::move(storage_area), - StorageArea::StorageType::kSessionStorage); - } + auto storage_area = + storage_namespace->GetCachedArea(document->GetSecurityOrigin()); + session_storage_ = + StorageArea::Create(document->GetFrame(), std::move(storage_area), + StorageArea::StorageType::kSessionStorage); + if (!session_storage_->CanAccessStorage()) { exception_state.ThrowSecurityError(access_denied_message); return nullptr; @@ -149,20 +142,12 @@ Page* page = document->GetPage(); if (!page || !page->GetSettings().GetLocalStorageEnabled()) return nullptr; - if (base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)) { - auto storage_area = StorageController::GetInstance()->GetLocalStorageArea( - document->GetSecurityOrigin()); - local_storage_ = - StorageArea::Create(document->GetFrame(), std::move(storage_area), - StorageArea::StorageType::kLocalStorage); - } else { - auto storage_area = - StorageController::GetInstance()->GetWebLocalStorageArea( - document->GetSecurityOrigin()); - local_storage_ = - StorageArea::Create(document->GetFrame(), std::move(storage_area), - StorageArea::StorageType::kLocalStorage); - } + auto storage_area = StorageController::GetInstance()->GetLocalStorageArea( + document->GetSecurityOrigin()); + local_storage_ = + StorageArea::Create(document->GetFrame(), std::move(storage_area), + StorageArea::StorageType::kLocalStorage); + if (!local_storage_->CanAccessStorage()) { exception_state.ThrowSecurityError(access_denied_message); return nullptr;
diff --git a/third_party/blink/renderer/modules/storage/inspector_dom_storage_agent.cc b/third_party/blink/renderer/modules/storage/inspector_dom_storage_agent.cc index 88982b97..30a5150 100644 --- a/third_party/blink/renderer/modules/storage/inspector_dom_storage_agent.cc +++ b/third_party/blink/renderer/modules/storage/inspector_dom_storage_agent.cc
@@ -221,19 +221,11 @@ if (is_local_storage) { if (!frame->GetDocument()->GetSecurityOrigin()->CanAccessLocalStorage()) return Response::Error("Security origin cannot access local storage"); - if (base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)) { - storage_area = StorageArea::CreateForInspectorAgent( - frame, - StorageController::GetInstance()->GetLocalStorageArea( - frame->GetDocument()->GetSecurityOrigin()), - StorageArea::StorageType::kLocalStorage); - } else { - storage_area = StorageArea::Create( - frame, - StorageController::GetInstance()->GetWebLocalStorageArea( - frame->GetDocument()->GetSecurityOrigin()), - StorageArea::StorageType::kLocalStorage); - } + storage_area = StorageArea::CreateForInspectorAgent( + frame, + StorageController::GetInstance()->GetLocalStorageArea( + frame->GetDocument()->GetSecurityOrigin()), + StorageArea::StorageType::kLocalStorage); return Response::OK(); } @@ -245,19 +237,11 @@ return Response::Error("SessionStorage is not supported"); DCHECK(session_namespace->IsSessionStorage()); - if (base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)) { - storage_area = StorageArea::CreateForInspectorAgent( - frame, - session_namespace->GetCachedArea( - frame->GetDocument()->GetSecurityOrigin()), - StorageArea::StorageType::kSessionStorage); - } else { - storage_area = - StorageArea::Create(frame, - session_namespace->GetWebStorageArea( - frame->GetDocument()->GetSecurityOrigin()), - StorageArea::StorageType::kSessionStorage); - } + storage_area = StorageArea::CreateForInspectorAgent( + frame, + session_namespace->GetCachedArea( + frame->GetDocument()->GetSecurityOrigin()), + StorageArea::StorageType::kSessionStorage); return Response::OK(); }
diff --git a/third_party/blink/renderer/modules/storage/storage_area.cc b/third_party/blink/renderer/modules/storage/storage_area.cc index 338c586..2c11881 100644 --- a/third_party/blink/renderer/modules/storage/storage_area.cc +++ b/third_party/blink/renderer/modules/storage/storage_area.cc
@@ -29,8 +29,6 @@ #include "base/memory/scoped_refptr.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/platform/task_type.h" -#include "third_party/blink/public/platform/web_storage_area.h" -#include "third_party/blink/public/platform/web_storage_namespace.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/modules/storage/dom_window_storage.h" @@ -45,13 +43,6 @@ namespace blink { StorageArea* StorageArea::Create(LocalFrame* frame, - std::unique_ptr<WebStorageArea> storage_area, - StorageType storage_type) { - return MakeGarbageCollected<StorageArea>(frame, std::move(storage_area), - storage_type); -} - -StorageArea* StorageArea::Create(LocalFrame* frame, scoped_refptr<CachedStorageArea> storage_area, StorageType storage_type) { return MakeGarbageCollected<StorageArea>(frame, std::move(storage_area), @@ -69,18 +60,6 @@ } StorageArea::StorageArea(LocalFrame* frame, - std::unique_ptr<WebStorageArea> storage_area, - StorageType storage_type) - : ContextClient(frame), - storage_area_(std::move(storage_area)), - storage_type_(storage_type), - should_enqueue_events_(true) { - DCHECK(!base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)); - DCHECK(frame); - DCHECK(storage_area_); -} - -StorageArea::StorageArea(LocalFrame* frame, scoped_refptr<CachedStorageArea> storage_area, StorageType storage_type, bool should_enqueue_events) @@ -88,7 +67,6 @@ cached_area_(std::move(storage_area)), storage_type_(storage_type), should_enqueue_events_(should_enqueue_events) { - CHECK(base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)); DCHECK(frame); DCHECK(cached_area_); cached_area_->RegisterSource(this); @@ -99,9 +77,7 @@ exception_state.ThrowSecurityError("access is denied for this document."); return 0; } - if (cached_area_) - return cached_area_->GetLength(); - return storage_area_->length(); + return cached_area_->GetLength(); } String StorageArea::key(unsigned index, ExceptionState& exception_state) const { @@ -109,15 +85,7 @@ exception_state.ThrowSecurityError("access is denied for this document."); return String(); } - if (cached_area_) - return cached_area_->GetKey(index); - bool did_decrease_iterator = false; - String result = storage_area_->Key(index, &did_decrease_iterator); - if (did_decrease_iterator) { - UseCounter::Count(GetFrame()->GetDocument(), - WebFeature::kReverseIterateDOMStorage); - } - return result; + return cached_area_->GetKey(index); } String StorageArea::getItem(const String& key, @@ -126,9 +94,7 @@ exception_state.ThrowSecurityError("access is denied for this document."); return String(); } - if (cached_area_) - return cached_area_->GetItem(key); - return storage_area_->GetItem(key); + return cached_area_->GetItem(key); } bool StorageArea::setItem(const String& key, @@ -138,14 +104,7 @@ exception_state.ThrowSecurityError("access is denied for this document."); return true; } - WebStorageArea::Result result = WebStorageArea::kResultOK; - if (!cached_area_) { - storage_area_->SetItem(key, value, GetFrame()->GetDocument()->Url(), - result); - } else if (!cached_area_->SetItem(key, value, this)) { - result = WebStorageArea::kResultBlockedByQuota; - } - if (result != WebStorageArea::kResultOK) { + if (!cached_area_->SetItem(key, value, this)) { exception_state.ThrowDOMException( DOMExceptionCode::kQuotaExceededError, "Setting the value of '" + key + "' exceeded the quota."); @@ -159,10 +118,7 @@ exception_state.ThrowSecurityError("access is denied for this document."); return kDeleteSuccess; } - if (cached_area_) - cached_area_->RemoveItem(key, this); - else - storage_area_->RemoveItem(key, GetFrame()->GetDocument()->Url()); + cached_area_->RemoveItem(key, this); return kDeleteSuccess; } @@ -171,10 +127,7 @@ exception_state.ThrowSecurityError("access is denied for this document."); return; } - if (cached_area_) - cached_area_->Clear(this); - else - storage_area_->Clear(GetFrame()->GetDocument()->Url()); + cached_area_->Clear(this); } bool StorageArea::Contains(const String& key, @@ -183,9 +136,7 @@ exception_state.ThrowSecurityError("access is denied for this document."); return false; } - if (cached_area_) - return !cached_area_->GetItem(key).IsNull(); - return !storage_area_->GetItem(key).IsNull(); + return !cached_area_->GetItem(key).IsNull(); } void StorageArea::NamedPropertyEnumerator(Vector<String>& names, @@ -267,96 +218,4 @@ duration); } -namespace { -// TODO(dmurph): Remove this after onion souping. crbug.com/781870 -Page* FindPageWithSessionStorageNamespace( - const WebStorageNamespace& session_namespace) { - // Iterate over all pages that have a StorageNamespace supplement. - String namespace_str = session_namespace.GetNamespaceId(); - for (Page* page : Page::OrdinaryPages()) { - StorageNamespace* storage_namespace = StorageNamespace::From(page); - if (storage_namespace && storage_namespace->namespace_id() == namespace_str) - return page; - } - return nullptr; -} - -bool IsEventSource(StorageArea* storage, WebStorageArea* source_area_instance) { - DCHECK(storage); - WebStorageArea* web_area = storage->Area(); - return web_area == source_area_instance; -} -} // namespace - -void StorageArea::DispatchLocalStorageEvent( - const String& key, - const String& old_value, - const String& new_value, - const SecurityOrigin* security_origin, - const KURL& page_url, - WebStorageArea* source_area_instance) { - // Iterate over all pages that have a LocalStorage area created. - for (Page* page : Page::OrdinaryPages()) { - for (Frame* frame = page->MainFrame(); frame; - frame = frame->Tree().TraverseNext()) { - // Remote frames are cross-origin and do not need to be notified of - // events. - auto* local_frame = DynamicTo<LocalFrame>(frame); - if (!local_frame) - continue; - LocalDOMWindow* local_window = local_frame->DomWindow(); - StorageArea* storage = - DOMWindowStorage::From(*local_window).OptionalLocalStorage(); - if (storage && - local_frame->GetDocument()->GetSecurityOrigin()->IsSameSchemeHostPort( - security_origin) && - !IsEventSource(storage, source_area_instance)) { - // https://www.w3.org/TR/webstorage/#the-storage-event - local_frame->DomWindow()->EnqueueWindowEvent( - *StorageEvent::Create(event_type_names::kStorage, key, old_value, - new_value, page_url, storage), - TaskType::kDOMManipulation); - } - } - StorageController::GetInstance()->DidDispatchLocalStorageEvent( - security_origin, key, old_value, new_value); - } -} - -void StorageArea::DispatchSessionStorageEvent( - const String& key, - const String& old_value, - const String& new_value, - const SecurityOrigin* security_origin, - const KURL& page_url, - const WebStorageNamespace& session_namespace, - WebStorageArea* source_area_instance) { - Page* page = FindPageWithSessionStorageNamespace(session_namespace); - if (!page) - return; - - for (Frame* frame = page->MainFrame(); frame; - frame = frame->Tree().TraverseNext()) { - // Remote frames are cross-origin and do not need to be notified of events. - auto* local_frame = DynamicTo<LocalFrame>(frame); - if (!local_frame) - continue; - LocalDOMWindow* local_window = local_frame->DomWindow(); - StorageArea* storage = - DOMWindowStorage::From(*local_window).OptionalSessionStorage(); - if (storage && - local_frame->GetDocument()->GetSecurityOrigin()->IsSameSchemeHostPort( - security_origin) && - !IsEventSource(storage, source_area_instance)) { - // https://www.w3.org/TR/webstorage/#the-storage-event - local_frame->DomWindow()->EnqueueWindowEvent( - *StorageEvent::Create(event_type_names::kStorage, key, old_value, - new_value, page_url, storage), - TaskType::kDOMManipulation); - } - } - StorageNamespace::From(page)->DidDispatchStorageEvent(security_origin, key, - old_value, new_value); -} - } // namespace blink
diff --git a/third_party/blink/renderer/modules/storage/storage_area.h b/third_party/blink/renderer/modules/storage/storage_area.h index a06ece7..2f73445 100644 --- a/third_party/blink/renderer/modules/storage/storage_area.h +++ b/third_party/blink/renderer/modules/storage/storage_area.h
@@ -38,8 +38,6 @@ class ExceptionState; class LocalFrame; -class WebStorageArea; -class WebStorageNamespace; class StorageArea final : public ScriptWrappable, public ContextClient, @@ -50,12 +48,6 @@ public: enum class StorageType { kLocalStorage, kSessionStorage }; - // TODO(dmurph): Remove this after onion souping. crbug.com/781870 - static StorageArea* Create(LocalFrame*, - std::unique_ptr<WebStorageArea>, - StorageType); - - // Creates the onion-souped version. static StorageArea* Create(LocalFrame*, scoped_refptr<CachedStorageArea>, StorageType); @@ -66,9 +58,6 @@ scoped_refptr<CachedStorageArea>, StorageType); - // TODO(dmurph): Remove this after onion souping. crbug.com/781870 - StorageArea(LocalFrame*, std::unique_ptr<WebStorageArea>, StorageType); - StorageArea(LocalFrame*, scoped_refptr<CachedStorageArea>, StorageType, @@ -82,8 +71,6 @@ void clear(ExceptionState&); bool Contains(const String& key, ExceptionState& ec) const; - WebStorageArea* Area() const { return storage_area_.get(); } - void NamedPropertyEnumerator(Vector<String>&, ExceptionState&); bool NamedPropertyQuery(const AtomicString&, ExceptionState&); @@ -102,27 +89,8 @@ const char* name, WebScopedVirtualTimePauser::VirtualTaskDuration duration) override; - // TODO(dmurph): Remove this after onion souping. crbug.com/781870 - static void DispatchLocalStorageEvent(const String& key, - const String& old_value, - const String& new_value, - const SecurityOrigin*, - const KURL& page_url, - WebStorageArea* source_area_instance); - // TODO(dmurph): Remove this after onion souping. crbug.com/781870 - static void DispatchSessionStorageEvent(const String& key, - const String& old_value, - const String& new_value, - const SecurityOrigin*, - const KURL& page_url, - const WebStorageNamespace&, - WebStorageArea* source_area_instance); - private: - // TODO(dmurph): Remove this after onion souping. crbug.com/781870 - std::unique_ptr<WebStorageArea> storage_area_; - - scoped_refptr<CachedStorageArea> cached_area_; + const scoped_refptr<CachedStorageArea> cached_area_; StorageType storage_type_; const bool should_enqueue_events_;
diff --git a/third_party/blink/renderer/modules/storage/storage_controller.cc b/third_party/blink/renderer/modules/storage/storage_controller.cc index 69a119e5..d5bebf2 100644 --- a/third_party/blink/renderer/modules/storage/storage_controller.cc +++ b/third_party/blink/renderer/modules/storage/storage_controller.cc
@@ -10,8 +10,6 @@ #include "third_party/blink/public/platform/interface_provider.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_content_settings_client.h" -#include "third_party/blink/public/platform/web_storage_area.h" -#include "third_party/blink/public/platform/web_storage_namespace.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/modules/storage/cached_storage_area.h" #include "third_party/blink/renderer/modules/storage/storage_namespace.h" @@ -74,17 +72,8 @@ auto it = namespaces_->find(namespace_id); if (it != namespaces_->end()) return it->value; - StorageNamespace* ns = nullptr; - if (base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)) { - ns = MakeGarbageCollected<StorageNamespace>(this, namespace_id); - } else { - auto namespace_str = StringUTF8Adaptor(namespace_id); - auto web_namespace = Platform::Current()->CreateSessionStorageNamespace( - namespace_str.AsStringPiece()); - if (!web_namespace) - return nullptr; - ns = MakeGarbageCollected<StorageNamespace>(std::move(web_namespace)); - } + StorageNamespace* ns = + MakeGarbageCollected<StorageNamespace>(this, namespace_id); namespaces_->insert(namespace_id, ns); return ns; } @@ -112,19 +101,10 @@ scoped_refptr<CachedStorageArea> StorageController::GetLocalStorageArea( const SecurityOrigin* origin) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - CHECK(base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)); EnsureLocalStorageNamespaceCreated(); return local_storage_namespace_->GetCachedArea(origin); } -std::unique_ptr<WebStorageArea> StorageController::GetWebLocalStorageArea( - const SecurityOrigin* origin) { - DCHECK(IsMainThread()); - CHECK(!base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)); - EnsureLocalStorageNamespaceCreated(); - return local_storage_namespace_->GetWebStorageArea(origin); -} - void StorageController::AddLocalStorageInspectorStorageAgent( InspectorDOMStorageAgent* agent) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -153,12 +133,7 @@ void StorageController::EnsureLocalStorageNamespaceCreated() { if (local_storage_namespace_) return; - if (base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)) { - local_storage_namespace_ = MakeGarbageCollected<StorageNamespace>(this); - } else { - local_storage_namespace_ = MakeGarbageCollected<StorageNamespace>( - Platform::Current()->CreateLocalStorageNamespace()); - } + local_storage_namespace_ = MakeGarbageCollected<StorageNamespace>(this); } } // namespace blink
diff --git a/third_party/blink/renderer/modules/storage/storage_controller.h b/third_party/blink/renderer/modules/storage/storage_controller.h index 20c30705..7c64d1c0 100644 --- a/third_party/blink/renderer/modules/storage/storage_controller.h +++ b/third_party/blink/renderer/modules/storage/storage_controller.h
@@ -27,7 +27,6 @@ class LocalFrame; class SecurityOrigin; class StorageNamespace; -class WebStorageArea; // Singleton that manages the creation & accounting for DOMStorage objects. It // does this by holding weak references to all session storage namespaces, and @@ -76,11 +75,8 @@ // LocalStorage: scoped_refptr<CachedStorageArea> GetLocalStorageArea(const SecurityOrigin*); - // TODO(dmurph): Remove this once DOMStorage is Onion Soupified. - std::unique_ptr<WebStorageArea> GetWebLocalStorageArea(const SecurityOrigin*); void AddLocalStorageInspectorStorageAgent(InspectorDOMStorageAgent* agent); void RemoveLocalStorageInspectorStorageAgent(InspectorDOMStorageAgent* agent); - // TODO(dmurph): Remove this once DOMStorage is Onion Soupified. void DidDispatchLocalStorageEvent(const SecurityOrigin* origin, const String& key, const String& old_value, @@ -102,7 +98,6 @@ Persistent<StorageNamespace> local_storage_namespace_; size_t total_cache_limit_; - // Onion-soup state. mojom::blink::StoragePartitionServicePtr storage_partition_service_; SEQUENCE_CHECKER(sequence_checker_);
diff --git a/third_party/blink/renderer/modules/storage/storage_controller_test.cc b/third_party/blink/renderer/modules/storage/storage_controller_test.cc index 85e9c6f..8555f4b 100644 --- a/third_party/blink/renderer/modules/storage/storage_controller_test.cc +++ b/third_party/blink/renderer/modules/storage/storage_controller_test.cc
@@ -7,7 +7,6 @@ #include "base/bind.h" #include "base/run_loop.h" #include "base/task/post_task.h" -#include "base/test/scoped_feature_list.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/features.h" @@ -18,7 +17,6 @@ #include "third_party/blink/renderer/platform/cross_thread_functional.h" #include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h" #include "third_party/blink/renderer/platform/uuid.h" -#include "third_party/blink/renderer/platform/wtf/functional.h" namespace blink { namespace { @@ -46,8 +44,6 @@ } // namespace TEST(StorageControllerTest, CacheLimit) { - base::test::ScopedFeatureList features; - features.InitAndEnableFeature(features::kOnionSoupDOMStorage); const auto kOrigin = SecurityOrigin::CreateFromString("http://dom_storage1/"); const auto kOrigin2 = SecurityOrigin::CreateFromString("http://dom_storage2/"); @@ -98,8 +94,6 @@ } TEST(StorageControllerTest, CacheLimitSessionStorage) { - base::test::ScopedFeatureList features; - features.InitAndEnableFeature(features::kOnionSoupDOMStorage); const String kNamespace1 = CreateCanonicalUUIDString(); const String kNamespace2 = CreateCanonicalUUIDString(); const auto kOrigin = SecurityOrigin::CreateFromString("http://dom_storage1/");
diff --git a/third_party/blink/renderer/modules/storage/storage_namespace.cc b/third_party/blink/renderer/modules/storage/storage_namespace.cc index 41e02d1..de6c4dc6 100644 --- a/third_party/blink/renderer/modules/storage/storage_namespace.cc +++ b/third_party/blink/renderer/modules/storage/storage_namespace.cc
@@ -33,8 +33,6 @@ #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_security_origin.h" -#include "third_party/blink/public/platform/web_storage_area.h" -#include "third_party/blink/public/platform/web_storage_namespace.h" #include "third_party/blink/public/web/web_view_client.h" #include "third_party/blink/renderer/modules/storage/cached_storage_area.h" #include "third_party/blink/renderer/modules/storage/inspector_dom_storage_agent.h" @@ -47,22 +45,10 @@ const char StorageNamespace::kSupplementName[] = "SessionStorageNamespace"; StorageNamespace::StorageNamespace(StorageController* controller) - : controller_(controller) { - CHECK(base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)); -} + : controller_(controller) {} StorageNamespace::StorageNamespace(StorageController* controller, const String& namespace_id) - : controller_(controller), namespace_id_(namespace_id) { - CHECK(base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)); -} - -StorageNamespace::StorageNamespace( - std::unique_ptr<WebStorageNamespace> web_storage_namespace) - : controller_(nullptr), - namespace_id_(web_storage_namespace->GetNamespaceId()), - web_storage_namespace_(std::move(web_storage_namespace)) { - CHECK(!base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)); -} + : controller_(controller), namespace_id_(namespace_id) {} StorageNamespace::~StorageNamespace() = default; @@ -131,7 +117,6 @@ } void StorageNamespace::CloneTo(const String& target) { - CHECK(base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)); DCHECK(IsSessionStorage()) << "Cannot clone a local storage namespace."; EnsureConnected(); namespace_->Clone(target); @@ -179,12 +164,6 @@ origin); } } -std::unique_ptr<WebStorageArea> StorageNamespace::GetWebStorageArea( - const SecurityOrigin* origin) { - CHECK(!base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)); - return base::WrapUnique( - web_storage_namespace_->CreateStorageArea(WebSecurityOrigin(origin))); -} void StorageNamespace::EnsureConnected() { DCHECK(IsSessionStorage());
diff --git a/third_party/blink/renderer/modules/storage/storage_namespace.h b/third_party/blink/renderer/modules/storage/storage_namespace.h index 4c316e4..cb54d9f 100644 --- a/third_party/blink/renderer/modules/storage/storage_namespace.h +++ b/third_party/blink/renderer/modules/storage/storage_namespace.h
@@ -30,7 +30,6 @@ #include "third_party/blink/public/mojom/dom_storage/session_storage_namespace.mojom-blink.h" #include "third_party/blink/public/mojom/dom_storage/storage_partition_service.mojom-blink.h" -#include "third_party/blink/public/platform/web_storage_area.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/storage/cached_storage_area.h" @@ -46,7 +45,6 @@ class InspectorDOMStorageAgent; class StorageController; class SecurityOrigin; -class WebStorageNamespace; class WebViewClient; // Contains DOMStorage storage areas for origins & handles inspector agents. A @@ -78,20 +76,13 @@ return Supplement<Page>::From<StorageNamespace>(page); } - // Constructor for an onion-souped LocalStorage namespace. + // Creates a namespace for LocalStorage. StorageNamespace(StorageController*); - // Constructor for an onion-souped SessionStorage namespace. + // Creates a namespace for SessionStorage. StorageNamespace(StorageController*, const String& namespace_id); - // Pre-onion-soup constructor. WebStorageNamespace must not be null. - StorageNamespace(std::unique_ptr<WebStorageNamespace>); ~StorageNamespace() override; - // TODO(dmurph): Remove this once Onion Soupified. - const String& namespace_id() { return namespace_id_; } - // TODO(dmurph): Remove this once Onion Soupified. - std::unique_ptr<WebStorageArea> GetWebStorageArea(const SecurityOrigin*); - scoped_refptr<CachedStorageArea> GetCachedArea(const SecurityOrigin* origin); // Only valid to call this if |this| and |target| are session storage @@ -122,7 +113,6 @@ HeapHashSet<WeakMember<InspectorDOMStorageAgent>> inspector_agents_; - // Onion-souped storage wiring, not turned on yet. // Lives globally. StorageController* controller_; String namespace_id_; @@ -131,9 +121,6 @@ scoped_refptr<CachedStorageArea>, SecurityOriginHash> cached_areas_; - - // Pre-onion-soup storage wiring, currently active. - std::unique_ptr<WebStorageNamespace> web_storage_namespace_; }; } // namespace blink
diff --git a/third_party/blink/renderer/modules/storage/storage_namespace_test.cc b/third_party/blink/renderer/modules/storage/storage_namespace_test.cc index f3a40c4..55c3b591 100644 --- a/third_party/blink/renderer/modules/storage/storage_namespace_test.cc +++ b/third_party/blink/renderer/modules/storage/storage_namespace_test.cc
@@ -6,7 +6,6 @@ #include <third_party/blink/renderer/modules/storage/storage_controller.h> #include "base/task/post_task.h" -#include "base/test/scoped_feature_list.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/features.h" @@ -35,12 +34,8 @@ public: const size_t kTestCacheLimit = 100; - StorageNamespaceTest() { - features_.InitAndEnableFeature(features::kOnionSoupDOMStorage); - } + StorageNamespaceTest() {} ~StorageNamespaceTest() override {} - - base::test::ScopedFeatureList features_; }; TEST_F(StorageNamespaceTest, BasicStorageAreas) {
diff --git a/third_party/blink/renderer/platform/audio/fft_frame.h b/third_party/blink/renderer/platform/audio/fft_frame.h index b1d5226..502a4f5 100644 --- a/third_party/blink/renderer/platform/audio/fft_frame.h +++ b/third_party/blink/renderer/platform/audio/fft_frame.h
@@ -145,10 +145,28 @@ AudioFloatArray imag_data_; #if defined(OS_MACOSX) + // Thin wrapper around FFTSetup so we can call the appropriate routines to + // construct or release the FFTSetup objects. + class FFTSetupDatum { + public: + FFTSetupDatum(unsigned fft_size); + ~FFTSetupDatum(); + FFTSetup GetSetup() const { return setup_; } + + private: + FFTSetup setup_; + }; + + // Returns the vector that holds all of the possible FFTSetupData + // objects. This should be set up in the |Initialize()| method that is called + // when the context is created. + static Vector<std::unique_ptr<FFTSetupDatum>>& FFTSetups(); + + static void InitializeFFTSetupForSize(wtf_size_t fft_order); + DSPSplitComplex& DspSplitComplex() { return frame_; } DSPSplitComplex DspSplitComplex() const { return frame_; } static FFTSetup FftSetupForSize(unsigned fft_size); - static FFTSetup* fft_setups_; FFTSetup fft_setup_; DSPSplitComplex frame_; #elif defined(WTF_USE_WEBAUDIO_FFMPEG)
diff --git a/third_party/blink/renderer/platform/audio/mac/fft_frame_mac.cc b/third_party/blink/renderer/platform/audio/mac/fft_frame_mac.cc index 44aed4c4..8b77f6d 100644 --- a/third_party/blink/renderer/platform/audio/mac/fft_frame_mac.cc +++ b/third_party/blink/renderer/platform/audio/mac/fft_frame_mac.cc
@@ -33,26 +33,75 @@ #if defined(OS_MACOSX) #include "third_party/blink/renderer/platform/audio/fft_frame.h" +#include "third_party/blink/renderer/platform/audio/hrtf_panner.h" #include "third_party/blink/renderer/platform/audio/vector_math.h" +#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" namespace blink { const int kMaxFFTPow2Size = 24; const int kMinFFTPow2Size = 2; -FFTSetup* FFTFrame::fft_setups_ = nullptr; +FFTFrame::FFTSetupDatum::FFTSetupDatum(unsigned log2fft_size) { + // We only need power-of-two sized FFTS, so FFT_RADIX2. + setup_ = vDSP_create_fftsetup(log2fft_size, FFT_RADIX2); + DCHECK(setup_); +} + +FFTFrame::FFTSetupDatum::~FFTSetupDatum() { + DCHECK(setup_); + + vDSP_destroy_fftsetup(setup_); +} + +Vector<std::unique_ptr<FFTFrame::FFTSetupDatum>>& FFTFrame::FFTSetups() { + // TODO(rtoy): Let this bake for a bit and then remove the assertions after + // we're confident the first call is from the main thread. + static bool first_call = true; + + if (first_call) { + // Make sure we construct the fft_setups vector below on the main thread. + // Once constructed, we can access it from any thread. + DCHECK(IsMainThread()); + first_call = false; + } + + // A vector to hold all of the possible FFT setups we need. The setups are + // initialized lazily. + DEFINE_STATIC_LOCAL(Vector<std::unique_ptr<FFTSetupDatum>>, fft_setups, + (kMaxFFTPow2Size)); + + return fft_setups; +} + +void FFTFrame::InitializeFFTSetupForSize(wtf_size_t log2fft_size) { + auto& setup = FFTSetups(); + + if (!setup[log2fft_size]) { + // Make sure allocation of a new setup only occurs on the main thread so we + // don't have a race condition with multiple threads trying to write to the + // same element of the vector. + DCHECK(IsMainThread()); + + setup[log2fft_size] = std::make_unique<FFTSetupDatum>(log2fft_size); + } +} // Normal constructor: allocates for a given fftSize FFTFrame::FFTFrame(unsigned fft_size) - : real_data_(fft_size), imag_data_(fft_size) { - fft_size_ = fft_size; - log2fft_size_ = static_cast<unsigned>(log2(fft_size)); - + : fft_size_(fft_size), + log2fft_size_(static_cast<unsigned>(log2(fft_size))), + real_data_(fft_size), + imag_data_(fft_size) { // We only allow power of two DCHECK_EQ(1UL << log2fft_size_, fft_size_); - // Lazily create and share fftSetup with other frames - fft_setup_ = FftSetupForSize(fft_size); + // Initialize the PFFFT_Setup object here so that it will be ready when we + // compute FFTs. + InitializeFFTSetupForSize(log2fft_size_); + + // Get a copy of the setup from the table. + fft_setup_ = FftSetupForSize(log2fft_size_); // Setup frame data frame_.realp = real_data_.Data(); @@ -112,18 +161,9 @@ vector_math::Vsmul(data, 1, &scale, data, 1, fft_size_); } -FFTSetup FFTFrame::FftSetupForSize(unsigned fft_size) { - if (!fft_setups_) { - fft_setups_ = (FFTSetup*)malloc(sizeof(FFTSetup) * kMaxFFTPow2Size); - memset(fft_setups_, 0, sizeof(FFTSetup) * kMaxFFTPow2Size); - } - - int pow2size = static_cast<int>(log2(fft_size)); - DCHECK_LT(pow2size, kMaxFFTPow2Size); - if (!fft_setups_[pow2size]) - fft_setups_[pow2size] = vDSP_create_fftsetup(pow2size, FFT_RADIX2); - - return fft_setups_[pow2size]; +FFTSetup FFTFrame::FftSetupForSize(unsigned log2fft_size) { + auto& setup = FFTSetups(); + return setup[log2fft_size]->GetSetup(); } int FFTFrame::MinFFTSize() { @@ -134,19 +174,29 @@ return 1 << kMaxFFTPow2Size; } -void FFTFrame::Initialize(float sample_rate) {} +void FFTFrame::Initialize(float sample_rate) { + // Initialize the vector now so it's ready for use when we construct + // FFTFrames. + FFTSetups(); + + // Determine the order of the convolvers used by the HRTF kernel. Allocate + // FFT setups for that size and for half that size. The HRTF kernel uses half + // size for analysis FFTs. + // + // TODO(rtoy): Try to come up with some way so that |Initialize()| doesn't + // need to know about how the HRTF panner uses FFTs. + unsigned hrtf_order = static_cast<unsigned>( + log2(HRTFPanner::FftSizeForSampleRate(sample_rate))); + InitializeFFTSetupForSize(hrtf_order); + InitializeFFTSetupForSize(hrtf_order - 1); +} void FFTFrame::Cleanup() { - if (!fft_setups_) - return; + auto& setups = FFTSetups(); - for (int i = 0; i < kMaxFFTPow2Size; ++i) { - if (fft_setups_[i]) - vDSP_destroy_fftsetup(fft_setups_[i]); + for (wtf_size_t k = 0; k < setups.size(); ++k) { + setups[k].reset(); } - - free(fft_setups_); - fft_setups_ = nullptr; } } // namespace blink
diff --git a/third_party/blink/renderer/platform/exported/platform.cc b/third_party/blink/renderer/platform/exported/platform.cc index 60e7d1f..63f3cc0 100644 --- a/third_party/blink/renderer/platform/exported/platform.cc +++ b/third_party/blink/renderer/platform/exported/platform.cc
@@ -46,7 +46,6 @@ #include "third_party/blink/public/platform/web_prerendering_support.h" #include "third_party/blink/public/platform/web_rtc_certificate_generator.h" #include "third_party/blink/public/platform/web_rtc_peer_connection_handler.h" -#include "third_party/blink/public/platform/web_storage_namespace.h" #include "third_party/blink/public/platform/websocket_handshake_throttle.h" #include "third_party/blink/renderer/platform/bindings/parkable_string_manager.h" #include "third_party/blink/renderer/platform/cross_thread_functional.h" @@ -258,15 +257,6 @@ return InterfaceProvider::GetEmptyInterfaceProvider(); } -std::unique_ptr<WebStorageNamespace> Platform::CreateLocalStorageNamespace() { - return nullptr; -} - -std::unique_ptr<WebStorageNamespace> Platform::CreateSessionStorageNamespace( - base::StringPiece namespace_id) { - return nullptr; -} - std::unique_ptr<Thread> Platform::CreateThread( const ThreadCreationParams& params) { return Thread::CreateThread(params);
diff --git a/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.cc b/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.cc index c90fe8b..d867981 100644 --- a/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.cc +++ b/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.cc
@@ -41,11 +41,25 @@ unsigned texture_id, base::WeakPtr<WebGraphicsContext3DProviderWrapper>&& context_provider_wrapper, - IntSize mailbox_size, - std::unique_ptr<viz::SingleReleaseCallback> release_callback) { + IntSize mailbox_size) { return base::AdoptRef(new AcceleratedStaticBitmapImage( mailbox, sync_token, texture_id, std::move(context_provider_wrapper), - mailbox_size, std::move(release_callback))); + mailbox_size)); +} + +scoped_refptr<AcceleratedStaticBitmapImage> +AcceleratedStaticBitmapImage::CreateFromCanvasMailbox( + const gpu::Mailbox& mailbox, + const gpu::SyncToken& sync_token, + const SkImageInfo& sk_image_info, + GLenum texture_target, + base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper, + PlatformThreadId context_thread_id, + std::unique_ptr<viz::SingleReleaseCallback> release_callback) { + return base::AdoptRef(new AcceleratedStaticBitmapImage( + mailbox, sync_token, sk_image_info, texture_target, + std::move(context_provider_wrapper), context_thread_id, + std::move(release_callback))); } AcceleratedStaticBitmapImage::AcceleratedStaticBitmapImage( @@ -64,13 +78,27 @@ unsigned texture_id, base::WeakPtr<WebGraphicsContext3DProviderWrapper>&& context_provider_wrapper, - IntSize mailbox_size, + IntSize mailbox_size) + : paint_image_content_id_(cc::PaintImage::GetNextContentId()) { + texture_holder_ = std::make_unique<MailboxTextureHolder>( + mailbox, sync_token, texture_id, std::move(context_provider_wrapper), + mailbox_size); +} + +AcceleratedStaticBitmapImage::AcceleratedStaticBitmapImage( + const gpu::Mailbox& mailbox, + const gpu::SyncToken& sync_token, + const SkImageInfo& sk_image_info, + GLenum texture_target, + base::WeakPtr<WebGraphicsContext3DProviderWrapper>&& + context_provider_wrapper, + PlatformThreadId context_thread_id, std::unique_ptr<viz::SingleReleaseCallback> release_callback) : paint_image_content_id_(cc::PaintImage::GetNextContentId()), release_callback_(std::move(release_callback)) { texture_holder_ = std::make_unique<MailboxTextureHolder>( - mailbox, sync_token, texture_id, std::move(context_provider_wrapper), - mailbox_size); + mailbox, sync_token, std::move(context_provider_wrapper), + context_thread_id, sk_image_info, texture_target); } namespace { @@ -95,7 +123,7 @@ image.reset(); } -} // unnamed namespace +} // namespace AcceleratedStaticBitmapImage::~AcceleratedStaticBitmapImage() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
diff --git a/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.h b/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.h index 58da304..1a78056e 100644 --- a/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.h +++ b/third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.h
@@ -15,6 +15,7 @@ #include "third_party/blink/renderer/platform/scheduler/public/thread.h" class GrContext; +struct SkImageInfo; namespace viz { class SingleReleaseCallback; @@ -37,18 +38,26 @@ // callers would use this option. // The |mailbox| is a name for the texture backing, allowing other contexts to // use the same backing. - // |mailbox_type| indicates whether |mailbox| is a SharedImage identifier or a - // deprecated mailbox (generated via ProduceTextureDirectCHROMIUM). - // |release_callback| is an optional callback to be invoked when this image - // is destroyed. It can be invoked on any thread. static scoped_refptr<AcceleratedStaticBitmapImage> CreateFromWebGLContextImage( const gpu::Mailbox&, const gpu::SyncToken&, unsigned texture_id, base::WeakPtr<WebGraphicsContext3DProviderWrapper>&&, - IntSize mailbox_size, - std::unique_ptr<viz::SingleReleaseCallback> release_callback = nullptr); + IntSize mailbox_size); + + // |release_callback| is an optional callback to be invoked when this image + // is destroyed. It can be invoked on any thread. + // If the image is created on a different thread than |context_thread_id| then + // the provided sync_token must be verified. + static scoped_refptr<AcceleratedStaticBitmapImage> CreateFromCanvasMailbox( + const gpu::Mailbox&, + const gpu::SyncToken&, + const SkImageInfo& sk_image_info, + GLenum texture_target, + base::WeakPtr<WebGraphicsContext3DProviderWrapper>, + PlatformThreadId context_thread_id, + std::unique_ptr<viz::SingleReleaseCallback> release_callback); bool CurrentFrameKnownToBeOpaque() override; IntSize Size() const override; @@ -111,7 +120,14 @@ const gpu::SyncToken&, unsigned texture_id, base::WeakPtr<WebGraphicsContext3DProviderWrapper>&&, - IntSize mailbox_size, + IntSize mailbox_size); + AcceleratedStaticBitmapImage( + const gpu::Mailbox&, + const gpu::SyncToken&, + const SkImageInfo& sk_image_info, + GLenum texture_target, + base::WeakPtr<WebGraphicsContext3DProviderWrapper>&&, + PlatformThreadId context_thread_id, std::unique_ptr<viz::SingleReleaseCallback> release_callback); void CreateImageFromMailboxIfNeeded();
diff --git a/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc b/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc index 6a757761..f00e019a 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.cc
@@ -584,8 +584,19 @@ return false; // Note frame is kept alive via a reference kept in out_release_callback. - return frame->PrepareTransferableResource(out_resource, out_release_callback, - kUnverifiedSyncToken); + if (!frame->PrepareTransferableResource(out_resource, out_release_callback, + kUnverifiedSyncToken) || + *out_resource == previous_frame_resource_) { + // If the resource did not change, the release will be handled correctly + // when the callback from the previous frame is dispatched. But run the + // |out_release_callback| to release the ref acquired above. + (*out_release_callback)->Run(gpu::SyncToken(), false /* is_lost */); + *out_release_callback = nullptr; + return false; + } + + previous_frame_resource_ = *out_resource; + return true; } cc::Layer* Canvas2DLayerBridge::Layer() {
diff --git a/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.h b/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.h index 0bfdfb2..74d3d31f 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.h +++ b/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge.h
@@ -35,6 +35,7 @@ #include "base/numerics/checked_math.h" #include "build/build_config.h" #include "cc/layers/texture_layer_client.h" +#include "components/viz/common/resources/transferable_resource.h" #include "third_party/blink/renderer/platform/geometry/float_rect.h" #include "third_party/blink/renderer/platform/geometry/int_size.h" #include "third_party/blink/renderer/platform/graphics/canvas_color_params.h" @@ -209,6 +210,7 @@ mutable SnapshotState snapshot_state_; CanvasResourceHost* resource_host_; + viz::TransferableResource previous_frame_resource_; base::WeakPtrFactory<Canvas2DLayerBridge> weak_ptr_factory_;
diff --git a/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge_test.cc b/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge_test.cc index 02023eb5..6cd65a6 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge_test.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_2d_layer_bridge_test.cc
@@ -86,8 +86,11 @@ MOCK_METHOD2(DeleteTextures, void(GLsizei, const GLuint*)); // Fake void ProduceTextureDirectCHROMIUM(GLuint texture, GLbyte* mailbox) override { - mailbox[0] = 1; // Make non-zero mailbox names + mailbox[0] = mailbox_count_++; // Make non-zero mailbox names } + + private: + int mailbox_count_ = 1; }; class ImageTrackingDecodeCache : public cc::StubDecodeCache { @@ -157,17 +160,34 @@ } void SetUp() override { - auto factory = [](FakeGLES2Interface* gl, ImageTrackingDecodeCache* cache, + auto factory = [](gpu::gles2::GLES2Interface* gl, + ImageTrackingDecodeCache* cache, GrContext* context, bool* gpu_compositing_disabled) -> std::unique_ptr<WebGraphicsContext3DProvider> { *gpu_compositing_disabled = false; - return std::make_unique<FakeWebGraphicsContext3DProvider>(gl, cache); + return std::make_unique<FakeWebGraphicsContext3DProvider>(gl, cache, + context); }; + + gpu::gles2::GLES2Interface* gl = &gl_; + GrContext* context = nullptr; + if (!NeedsMockGL()) { + test_context_provider_ = viz::TestContextProvider::Create(); + test_context_provider_->BindToCurrentThread(); + gl = test_context_provider_->ContextGL(); + context = test_context_provider_->GrContext(); + } SharedGpuContext::SetContextProviderFactoryForTesting(WTF::BindRepeating( - factory, WTF::Unretained(&gl_), WTF::Unretained(&image_decode_cache_))); + factory, WTF::Unretained(gl), WTF::Unretained(&image_decode_cache_), + WTF::Unretained(context))); } - void TearDown() override { SharedGpuContext::ResetForTesting(); } + virtual bool NeedsMockGL() { return true; } + + void TearDown() override { + SharedGpuContext::ResetForTesting(); + test_context_provider_.reset(); + } MockCanvasResourceHost* Host() { DCHECK(host_); @@ -175,6 +195,7 @@ } protected: + scoped_refptr<viz::TestContextProvider> test_context_provider_; MockGLES2InterfaceWithImageSupport gl_; ImageTrackingDecodeCache image_decode_cache_; std::unique_ptr<MockCanvasResourceHost> host_; @@ -1035,7 +1056,8 @@ EXPECT_CALL(gl_, DestroyImageCHROMIUM(image_2d_id_for_copy)); } DrawSomething(bridge.get()); - bridge->PrepareTransferableResource(nullptr, &resource1, &release_callback1); + ASSERT_TRUE(bridge->PrepareTransferableResource(nullptr, &resource1, + &release_callback1)); testing::Mock::VerifyAndClearExpectations(&gl_); @@ -1050,7 +1072,8 @@ EXPECT_CALL(gl_, DestroyImageCHROMIUM(image_2d_id_for_copy)); } DrawSomething(bridge.get()); - bridge->PrepareTransferableResource(nullptr, &resource2, &release_callback2); + ASSERT_TRUE(bridge->PrepareTransferableResource(nullptr, &resource2, + &release_callback2)); testing::Mock::VerifyAndClearExpectations(&gl_); @@ -1336,4 +1359,31 @@ bridge->Canvas()->drawImage(images[1].paint_image(), 0u, 0u, &flags); } +class Canvas2DLayerBridgeTestNoMockGL : public Canvas2DLayerBridgeTest { + bool NeedsMockGL() override { return false; } +}; + +TEST_F(Canvas2DLayerBridgeTestNoMockGL, + PrepareTransferableResourceTracksCanvasChanges) { + IntSize size = IntSize(300, 300); + std::unique_ptr<Canvas2DLayerBridge> bridge = MakeBridge( + size, Canvas2DLayerBridge::kEnableAcceleration, CanvasColorParams()); + host_->set_provider_type(CanvasResourceProvider::kSharedImage); + + bridge->Canvas()->clear(SK_ColorRED); + DrawSomething(bridge.get()); + + viz::TransferableResource resource; + std::unique_ptr<viz::SingleReleaseCallback> release_callback; + EXPECT_TRUE(bridge->PrepareTransferableResource(nullptr, &resource, + &release_callback)); + + std::unique_ptr<viz::SingleReleaseCallback> release_callback2; + EXPECT_FALSE(bridge->PrepareTransferableResource(nullptr, &resource, + &release_callback2)); + + release_callback->Run(gpu::SyncToken(), false); + EXPECT_EQ(release_callback2, nullptr); +} + } // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource.cc b/third_party/blink/renderer/platform/graphics/canvas_resource.cc index f199c5b5..b85ef9e 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_resource.cc
@@ -677,7 +677,9 @@ : CanvasResource(std::move(provider), filter_quality, color_params), context_provider_wrapper_(std::move(context_provider_wrapper)), is_overlay_candidate_(is_overlay_candidate), - size_(size) { + size_(size), + owning_thread_id_(Thread::Current()->ThreadId()), + owning_thread_task_runner_(Thread::Current()->GetTaskRunner()) { if (!context_provider_wrapper_) return; @@ -688,8 +690,13 @@ uint32_t flags = gpu::SHARED_IMAGE_USAGE_DISPLAY | gpu::SHARED_IMAGE_USAGE_GLES2 | gpu::SHARED_IMAGE_USAGE_GLES2_FRAMEBUFFER_HINT; - if (is_overlay_candidate_) + if (is_overlay_candidate_) { flags |= gpu::SHARED_IMAGE_USAGE_SCANOUT; + texture_target_ = gpu::GetBufferTextureTarget( + gfx::BufferUsage::SCANOUT, + BufferFormat(ColorParams().TransferableResourceFormat()), + context_provider_wrapper_->ContextProvider()->GetCapabilities()); + } shared_image_mailbox_ = shared_image_interface->CreateSharedImage( ColorParams().TransferableResourceFormat(), gfx::Size(size), @@ -699,8 +706,9 @@ WaitSyncToken(shared_image_interface->GenUnverifiedSyncToken()); } -GLuint CanvasResourceSharedImage::GetTextureIdForBackendTexture() { +GLuint CanvasResourceSharedImage::GetTextureIdForBackendTexture() const { if (!texture_id_) { + DCHECK(!is_cross_thread()); auto* gl = ContextGL(); DCHECK(gl); texture_id_ = @@ -732,17 +740,12 @@ } GLenum CanvasResourceSharedImage::TextureTarget() const { - if (is_overlay_candidate_) { - return gpu::GetBufferTextureTarget( - gfx::BufferUsage::SCANOUT, - BufferFormat(ColorParams().TransferableResourceFormat()), - context_provider_wrapper_->ContextProvider()->GetCapabilities()); - } else { - return GL_TEXTURE_2D; - } + return texture_target_; } void CanvasResourceSharedImage::TearDown() { + DCHECK(!is_cross_thread()); + if (ContextProviderWrapper()) { auto* gl = ContextGL(); auto* shared_image_interface = @@ -759,31 +762,68 @@ texture_id_ = 0u; } +void CanvasResourceSharedImage::Abandon() { + if (auto context_provider = SharedGpuContext::ContextProviderWrapper()) { + auto* sii = context_provider->ContextProvider()->SharedImageInterface(); + if (sii) + sii->DestroySharedImage(gpu::SyncToken(), shared_image_mailbox_); + } +} + void CanvasResourceSharedImage::WillDraw() { + DCHECK(!is_cross_thread()) + << "Write access is only allowed on the owning thread"; mailbox_needs_new_sync_token_ = true; } // static void CanvasResourceSharedImage::OnBitmapImageDestroyed( scoped_refptr<CanvasResourceSharedImage> resource, - scoped_refptr<base::SingleThreadTaskRunner> original_task_runner, const gpu::SyncToken& sync_token, bool is_lost) { - if (!original_task_runner->BelongsToCurrentThread()) { + if (resource->is_cross_thread()) { + auto& task_runner = *resource->owning_thread_task_runner_; PostCrossThreadTask( - *original_task_runner, FROM_HERE, + task_runner, FROM_HERE, CrossThreadBindOnce(&CanvasResourceSharedImage::OnBitmapImageDestroyed, - std::move(resource), - std::move(original_task_runner), sync_token, - is_lost)); + std::move(resource), sync_token, is_lost)); return; } + // The StaticBitmapImage is used for readbacks which may modify the texture + // params. Note that this is racy, since the modification and resetting of the + // param is not atomic so the display may draw with incorrect params, but its + // a good enough fix for now. + resource->needs_gl_filter_reset_ = true; + resource->SetGLFilterIfNeeded(); auto weak_provider = resource->WeakProvider(); ReleaseFrameResources(std::move(weak_provider), std::move(resource), sync_token, is_lost); } +void CanvasResourceSharedImage::Transfer() { + if (is_cross_thread() || !ContextProviderWrapper()) + return; + + // Initialize lazy params before transfer to another thread. + GetTextureIdForBackendTexture(); + // Initialize GLFilter first so that the generated sync token includes this + // update. + SetGLFilterIfNeeded(); + GetSyncToken(); + + // TODO(khushalsagar): This is for consistency with MailboxTextureHolder + // transfer path. Its unclear why the verification can not be deferred until + // the resource needs to be transferred cross-process. + if (!sync_token_.verified_flush()) { + int8_t* token_data = sync_token_.GetData(); + auto* gl = ContextGL(); + gl->ShallowFlushCHROMIUM(); + gl->VerifySyncTokensCHROMIUM(&token_data, 1); + sync_token_.SetVerifyFlush(); + } +} + scoped_refptr<StaticBitmapImage> CanvasResourceSharedImage::Bitmap() { // The |release_callback| keeps a ref on this resource to ensure the backing // shared image is kept alive until the lifetime of the image. @@ -791,33 +831,59 @@ // ref-count on the resource as a proxy for a read lock to allow recycling the // resource once all refs have been released. auto release_callback = viz::SingleReleaseCallback::Create(base::BindOnce( - &OnBitmapImageDestroyed, scoped_refptr<CanvasResourceSharedImage>(this), - Thread::Current()->GetTaskRunner())); + &OnBitmapImageDestroyed, scoped_refptr<CanvasResourceSharedImage>(this))); - scoped_refptr<StaticBitmapImage> image = - AcceleratedStaticBitmapImage::CreateFromWebGLContextImage( - shared_image_mailbox_, GetSyncToken(), 0, ContextProviderWrapper(), - Size(), std::move(release_callback)); + scoped_refptr<StaticBitmapImage> image; + SkImageInfo image_info = SkImageInfo::Make( + Size().Width(), Size().Height(), ColorParams().GetSkColorType(), + ColorParams().GetSkAlphaType(), ColorParams().GetSkColorSpace()); + auto sync_token = is_cross_thread() ? sync_token_ : GetSyncToken(); + image = AcceleratedStaticBitmapImage::CreateFromCanvasMailbox( + shared_image_mailbox_, sync_token, image_info, texture_target_, + context_provider_wrapper_, owning_thread_id_, + std::move(release_callback)); + DCHECK(image); return image; } const gpu::Mailbox& CanvasResourceSharedImage::GetOrCreateGpuMailbox( MailboxSyncMode sync_mode) { - mailbox_sync_mode_ = sync_mode; + if (!is_cross_thread()) { + SetGLFilterIfNeeded(); + mailbox_sync_mode_ = sync_mode; + } return shared_image_mailbox_; } +void CanvasResourceSharedImage::SetGLFilterIfNeeded() { + DCHECK(!is_cross_thread()); + + if (!needs_gl_filter_reset_ || !ContextGL()) + return; + + ContextGL()->BindTexture(TextureTarget(), GetTextureIdForBackendTexture()); + ContextGL()->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GLFilter()); + ContextGL()->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GLFilter()); + ContextGL()->BindTexture(TextureTarget(), 0u); + // TODO(khushalsagar): Inform skia about the param modification. + mailbox_needs_new_sync_token_ = true; + needs_gl_filter_reset_ = false; +} + bool CanvasResourceSharedImage::HasGpuMailbox() const { return !shared_image_mailbox_.IsZero(); } const gpu::SyncToken CanvasResourceSharedImage::GetSyncToken() { if (mailbox_needs_new_sync_token_) { + DCHECK(!is_cross_thread()); + auto* gl = ContextGL(); DCHECK(gl); // caller should already have early exited if !gl. if (mailbox_sync_mode_ == kVerifiedSyncToken) { gl->GenSyncTokenCHROMIUM(sync_token_.GetData()); + DCHECK(sync_token_.verified_flush()); } else { gl->GenUnverifiedSyncTokenCHROMIUM(sync_token_.GetData()); } @@ -828,6 +894,7 @@ base::WeakPtr<WebGraphicsContext3DProviderWrapper> CanvasResourceSharedImage::ContextProviderWrapper() const { + DCHECK(!is_cross_thread()); return context_provider_wrapper_; }
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource.h b/third_party/blink/renderer/platform/graphics/canvas_resource.h index de43b18..5003606 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource.h +++ b/third_party/blink/renderer/platform/graphics/canvas_resource.h
@@ -86,12 +86,6 @@ return 0; } - virtual GLuint GetTextureIdForBackendTexture() { - // Only used for CanvasResourceSharedImage. - NOTREACHED(); - return 0; - } - virtual GLenum TextureTarget() const { NOTREACHED(); return 0; @@ -324,6 +318,7 @@ bool IsValid() const final; IntSize Size() const final { return size_; } scoped_refptr<StaticBitmapImage> Bitmap() final; + void Transfer() final; bool OriginClean() const final { return is_origin_clean_; } void SetOriginClean(bool value) final { is_origin_clean_ = value; } @@ -337,17 +332,17 @@ return nullptr; } void TakeSkImage(sk_sp<SkImage> image) final { NOTREACHED(); } - GLuint GetTextureIdForBackendTexture() override; + GLuint GetTextureIdForBackendTexture() const; void WillDraw(); private: static void OnBitmapImageDestroyed( scoped_refptr<CanvasResourceSharedImage> resource, - scoped_refptr<base::SingleThreadTaskRunner> original_task_runner, const gpu::SyncToken& sync_token, bool is_lost); void TearDown() override; + void Abandon() override; base::WeakPtr<WebGraphicsContext3DProviderWrapper> ContextProviderWrapper() const override; const gpu::Mailbox& GetOrCreateGpuMailbox(MailboxSyncMode) override; @@ -355,6 +350,9 @@ bool HasGpuMailbox() const override; const gpu::SyncToken GetSyncToken() override; bool IsOverlayCandidate() const final { return is_overlay_candidate_; } + bool is_cross_thread() const { + return Thread::Current()->ThreadId() != owning_thread_id_; + } CanvasResourceSharedImage(const IntSize&, base::WeakPtr<WebGraphicsContext3DProviderWrapper>, @@ -362,17 +360,22 @@ SkFilterQuality, const CanvasColorParams&, bool is_overlay_candidate); + void SetGLFilterIfNeeded(); base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper_; gpu::Mailbox shared_image_mailbox_; bool mailbox_needs_new_sync_token_ = true; gpu::SyncToken sync_token_; MailboxSyncMode mailbox_sync_mode_ = kVerifiedSyncToken; - GLuint texture_id_ = 0u; + mutable GLuint texture_id_ = 0u; // mutable for lazy init. bool is_overlay_candidate_ = false; IntSize size_; - + bool needs_gl_filter_reset_ = true; bool is_origin_clean_ = true; + GLenum texture_target_ = GL_TEXTURE_2D; + + const PlatformThreadId owning_thread_id_; + const scoped_refptr<base::SingleThreadTaskRunner> owning_thread_task_runner_; }; // Resource type for a given opaque external resource described on construction
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc index 47082b8..c6604f5 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc
@@ -485,10 +485,14 @@ bool IsValid() const final { return GetSkSurface() && !IsGpuContextLost(); } bool IsAccelerated() const final { return true; } - bool SupportsDirectCompositing() const override { - return is_overlay_candidate_; - } + bool SupportsDirectCompositing() const override { return true; } bool SupportsSingleBuffering() const override { return false; } + GLuint GetBackingTextureHandleForOverwrite() override { + FlushGrContext(); + WillDraw(); + return static_cast<CanvasResourceSharedImage*>(resource_.get()) + ->GetTextureIdForBackendTexture(); + } scoped_refptr<CanvasResource> CreateResource() final { TRACE_EVENT0("blink", "CanvasResourceProviderSharedImage::CreateResource"); @@ -501,7 +505,7 @@ scoped_refptr<CanvasResource> ProduceCanvasResource() override { TRACE_EVENT0("blink", "CanvasResourceProviderSharedImage::ProduceCanvasResource"); - FlushSkia(); + FlushGrContext(); scoped_refptr<CanvasResource> resource = resource_; if (ContextProviderWrapper() @@ -515,12 +519,12 @@ WillDraw(); } - return resource_; + return resource; } scoped_refptr<StaticBitmapImage> Snapshot() override { TRACE_EVENT0("blink", "CanvasResourceProviderSharedImage::Snapshot"); - FlushSkia(); + FlushGrContext(); return resource_->Bitmap(); } @@ -529,12 +533,14 @@ // If |resource_| is still being used by the compositor we need to create // a new resource or reuse a previously recycled one. This class holds one // reference so we check if there is more than one. - // NOTE: The case when calling handling StaticBitmapImage doesn't currently - // grab a reference but it needs to. See https://crbug.com/948133 if (!resource_->HasOneRef()) { - FlushSkia(); + FlushGrContext(); resource_ = NewOrRecycledResource(); - RecreateSkSurface(); + if (surface_) { + surface_->replaceBackendTexture(CreateGrTextureForResource(), + GetGrSurfaceOrigin()); + surface_->flush(); + } } static_cast<CanvasResourceSharedImage*>(resource_.get())->WillDraw(); } @@ -544,34 +550,37 @@ if (IsGpuContextLost()) return nullptr; - GrGLTextureInfo texture_info = {}; - texture_info.fID = resource_->GetTextureIdForBackendTexture(); - texture_info.fTarget = resource_->TextureTarget(); - texture_info.fFormat = ColorParams().GLSizedInternalFormat(); - - const GrBackendTexture backend_texture(Size().Width(), Size().Height(), - GrMipMapped::kNo, texture_info); - - const enum GrSurfaceOrigin surface_origin = - is_origin_top_left_ ? kTopLeft_GrSurfaceOrigin - : kBottomLeft_GrSurfaceOrigin; return SkSurface::MakeFromBackendTexture( - GetGrContext(), backend_texture, surface_origin, msaa_sample_count_, - ColorParams().GetSkColorType(), + GetGrContext(), CreateGrTextureForResource(), GetGrSurfaceOrigin(), + msaa_sample_count_, ColorParams().GetSkColorType(), ColorParams().GetSkColorSpaceForSkSurfaces(), - nullptr /*surface props*/); + ColorParams().GetSkSurfaceProps()); } - void RecreateSkSurface() { - auto old_surface = std::move(surface_); - surface_ = CreateSkSurface(); - InitializePaintCanvas(); - if (old_surface) { - SkPaint paint; - paint.setBlendMode(SkBlendMode::kSrc); - old_surface->draw(surface_->getCanvas(), 0, 0, &paint); - surface_->flush(); - } + GrSurfaceOrigin GetGrSurfaceOrigin() const { + return is_origin_top_left_ ? kTopLeft_GrSurfaceOrigin + : kBottomLeft_GrSurfaceOrigin; + } + + GrBackendTexture CreateGrTextureForResource() const { + GrGLTextureInfo texture_info = {}; + texture_info.fID = + static_cast<const CanvasResourceSharedImage*>(resource_.get()) + ->GetTextureIdForBackendTexture(); + texture_info.fTarget = resource_->TextureTarget(); + texture_info.fFormat = ColorParams().GLSizedInternalFormat(); + return GrBackendTexture(Size().Width(), Size().Height(), GrMipMapped::kNo, + texture_info); + } + + void FlushGrContext() { + // The resource may have been imported and used in skia. Make sure any + // operations using this resource are flushed to the underlying context. + // Note that its not sufficient to flush the SkSurface here since it will + // only perform a GrContext flush if that SkSurface has any pending ops. And + // this resource may be written to or read from skia without using the + // SkSurface here. + GetGrContext()->flush(); } const unsigned msaa_sample_count_; @@ -646,6 +655,7 @@ }); static const std::vector<CanvasResourceType> kAcceleratedFallbackList({ + CanvasResourceType::kSharedImage, CanvasResourceType::kTexture, // Fallback to software CanvasResourceType::kBitmap, @@ -660,8 +670,7 @@ static const std::vector<CanvasResourceType> kAcceleratedCompositedFallbackList({ - // TODO(aaronhk) add CanvasResourceType::kSharedImage once resource - // recycling and copy on write is in place + CanvasResourceType::kSharedImage, CanvasResourceType::kTextureGpuMemoryBuffer, CanvasResourceType::kTexture, // Fallback to software composited @@ -671,15 +680,18 @@ // Fallback to no direct compositing support CanvasResourceType::kBitmap, }); - DCHECK(std::equal(kAcceleratedCompositedFallbackList.begin() + 2, + DCHECK(std::equal(kAcceleratedCompositedFallbackList.begin() + 3, kAcceleratedCompositedFallbackList.end(), kSoftwareCompositedFallbackList.begin(), kSoftwareCompositedFallbackList.end())); static const std::vector<CanvasResourceType> kAcceleratedDirect2DFallbackList( { + // TODO(khushalsagar): This is used for low-latency canvas. We'll need + // support for single buffering to use shared images here. CanvasResourceType::kDirect2DGpuMemoryBuffer, // The rest is equal to |kAcceleratedCompositedFallbackList|. + CanvasResourceType::kSharedImage, CanvasResourceType::kTextureGpuMemoryBuffer, CanvasResourceType::kTexture, // Fallback to software composited @@ -695,9 +707,14 @@ static const std::vector<CanvasResourceType> kAcceleratedDirect3DFallbackList( { + // This is used with single-buffered WebGL where the resource comes + // from an external source. The external site should take care of + // using SharedImages since the resource will be used by the display + // compositor. CanvasResourceType::kDirect3DGpuMemoryBuffer, CanvasResourceType::kDirect2DGpuMemoryBuffer, // The rest is equal to |kAcceleratedCompositedFallbackList|. + CanvasResourceType::kSharedImage, CanvasResourceType::kTextureGpuMemoryBuffer, CanvasResourceType::kTexture, // Fallback to software composited @@ -711,11 +728,6 @@ kAcceleratedDirect2DFallbackList.begin(), kAcceleratedDirect2DFallbackList.end())); - // Temporal Fallback List for testing SharedImage before enabling it. - static const std::vector<CanvasResourceType> kSharedImageForTestFallbackList({ - CanvasResourceType::kSharedImage, - }); - switch (usage) { case CanvasResourceProvider::kSoftwareResourceUsage: return kSoftwareFallbackList; @@ -729,8 +741,6 @@ return kAcceleratedDirect2DFallbackList; case CanvasResourceProvider::kAcceleratedDirect3DResourceUsage: return kAcceleratedDirect3DFallbackList; - case CanvasResourceProvider::kCreateSharedImageForTesting: - return kSharedImageForTestFallbackList; } NOTREACHED(); } @@ -821,11 +831,23 @@ provider = std::make_unique<CanvasResourceProviderBitmap>( size, color_params, context_provider_wrapper, resource_dispatcher); break; - case CanvasResourceType::kSharedImage: + case CanvasResourceType::kSharedImage: { + // TODO(khushalsagar): Enable this once the shared image work is done. +#if 0 + // TODO(khushalsagar): Also kAcceleratedDirect2DResourceUsage when we + // switch it to use shared images. + const bool is_overlay_candidate = + usage == kAcceleratedCompositedResourceUsage && + is_gpu_memory_buffer_image_allowed && + context_provider_wrapper->ContextProvider() + ->GetCapabilities() + .texture_storage_image; provider = std::make_unique<CanvasResourceProviderSharedImage>( size, msaa_sample_count, color_params, context_provider_wrapper, - resource_dispatcher, is_origin_top_left, false); - break; + resource_dispatcher, is_origin_top_left, is_overlay_candidate); +#endif + continue; + } break; } if (!provider->IsValid()) continue; @@ -837,6 +859,46 @@ return nullptr; } +std::unique_ptr<CanvasResourceProvider> +CanvasResourceProvider::CreateForTesting( + const IntSize& size, + ResourceProviderType type, + base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper, + unsigned msaa_sample_count, + const CanvasColorParams& color_params, + PresentationMode mode, + base::WeakPtr<CanvasResourceDispatcher> resource_dispatcher, + bool is_origin_top_left) { + switch (type) { + case CanvasResourceProvider::kSharedBitmap: + DCHECK(resource_dispatcher); + return std::make_unique<CanvasResourceProviderSharedBitmap>( + size, color_params, resource_dispatcher); + case CanvasResourceProvider::kTexture: + DCHECK(context_provider_wrapper); + return std::make_unique<CanvasResourceProviderTexture>( + size, msaa_sample_count, color_params, context_provider_wrapper, + resource_dispatcher, is_origin_top_left); + case CanvasResourceProvider::kBitmap: + return std::make_unique<CanvasResourceProviderBitmap>( + size, color_params, context_provider_wrapper, resource_dispatcher); + case CanvasResourceProvider::kSharedImage: + return std::make_unique<CanvasResourceProviderSharedImage>( + size, msaa_sample_count, color_params, context_provider_wrapper, + resource_dispatcher, is_origin_top_left, false); + case CanvasResourceProvider::kTextureGpuMemoryBuffer: + return std::make_unique<CanvasResourceProviderTextureGpuMemoryBuffer>( + size, msaa_sample_count, color_params, context_provider_wrapper, + resource_dispatcher, is_origin_top_left); + case CanvasResourceProvider::kBitmapGpuMemoryBuffer: + return std::make_unique<CanvasResourceProviderBitmapGpuMemoryBuffer>( + size, color_params, context_provider_wrapper, resource_dispatcher); + } + + NOTREACHED(); + return nullptr; +} + class CanvasResourceProvider::CanvasImageProvider : public cc::ImageProvider { public: CanvasImageProvider(cc::ImageDecodeCache* cache_n32,
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h index 9664d6c..8081b5a 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h
@@ -55,7 +55,6 @@ kAcceleratedCompositedResourceUsage, kAcceleratedDirect2DResourceUsage, kAcceleratedDirect3DResourceUsage, - kCreateSharedImageForTesting, }; enum PresentationMode { @@ -87,6 +86,16 @@ base::WeakPtr<CanvasResourceDispatcher>, bool is_origin_top_left = true); + static std::unique_ptr<CanvasResourceProvider> CreateForTesting( + const IntSize&, + ResourceProviderType, + base::WeakPtr<WebGraphicsContext3DProviderWrapper>, + unsigned msaa_sample_count, + const CanvasColorParams&, + PresentationMode, + base::WeakPtr<CanvasResourceDispatcher>, + bool is_origin_top_left = true); + // Use Snapshot() for capturing a frame that is intended to be displayed via // the compositor. Cases that are destined to be transferred via a // TransferableResource should call ProduceCanvasResource() instead. @@ -105,6 +114,7 @@ const IntSize& Size() const { return size_; } virtual bool IsValid() const = 0; virtual bool IsAccelerated() const = 0; + // Returns true if the resource can be used by the display compositor. virtual bool SupportsDirectCompositing() const = 0; virtual bool SupportsSingleBuffering() const { return false; } uint32_t ContentUniqueID() const;
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_provider_test.cc b/third_party/blink/renderer/platform/graphics/canvas_resource_provider_test.cc index b985965..0ca9fb3 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_provider_test.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_provider_test.cc
@@ -151,8 +151,8 @@ kRGBA8CanvasPixelFormat, kNonOpaque); EnsureBufferFormatIsSupported(kColorParams.GetBufferFormat()); - auto provider = CanvasResourceProvider::Create( - kSize, CanvasResourceProvider::kAcceleratedCompositedResourceUsage, + auto provider = CanvasResourceProvider::CreateForTesting( + kSize, CanvasResourceProvider::kTextureGpuMemoryBuffer, context_provider_wrapper_, 0 /* msaa_sample_count */, kColorParams, CanvasResourceProvider::kAllowImageChromiumPresentationMode, nullptr /* resource_dispatcher */, true /* is_origin_top_left */); @@ -228,9 +228,9 @@ kRGBA8CanvasPixelFormat, kNonOpaque); EnsureBufferFormatIsSupported(kColorParams.GetBufferFormat()); - auto provider = CanvasResourceProvider::Create( - kSize, CanvasResourceProvider::kCreateSharedImageForTesting, - context_provider_wrapper_, 0 /* msaa_sample_count */, kColorParams, + auto provider = CanvasResourceProvider::CreateForTesting( + kSize, CanvasResourceProvider::kSharedImage, context_provider_wrapper_, + 0 /* msaa_sample_count */, kColorParams, CanvasResourceProvider::kAllowImageChromiumPresentationMode, nullptr /* resource_dispatcher */, true /* is_origin_top_left */); @@ -279,9 +279,9 @@ kRGBA8CanvasPixelFormat, kNonOpaque); EnsureBufferFormatIsSupported(kColorParams.GetBufferFormat()); - auto provider = CanvasResourceProvider::Create( - kSize, CanvasResourceProvider::kCreateSharedImageForTesting, - context_provider_wrapper_, 0 /* msaa_sample_count */, kColorParams, + auto provider = CanvasResourceProvider::CreateForTesting( + kSize, CanvasResourceProvider::kSharedImage, context_provider_wrapper_, + 0 /* msaa_sample_count */, kColorParams, CanvasResourceProvider::kAllowImageChromiumPresentationMode, nullptr /* resource_dispatcher */, true /* is_origin_top_left */); ASSERT_TRUE(provider->IsValid()); @@ -320,9 +320,9 @@ kRGBA8CanvasPixelFormat, kNonOpaque); EnsureBufferFormatIsSupported(kColorParams.GetBufferFormat()); - auto provider = CanvasResourceProvider::Create( - kSize, CanvasResourceProvider::kCreateSharedImageForTesting, - context_provider_wrapper_, 0 /* msaa_sample_count */, kColorParams, + auto provider = CanvasResourceProvider::CreateForTesting( + kSize, CanvasResourceProvider::kSharedImage, context_provider_wrapper_, + 0 /* msaa_sample_count */, kColorParams, CanvasResourceProvider::kAllowImageChromiumPresentationMode, nullptr /* resource_dispatcher */, true /* is_origin_top_left */); ASSERT_TRUE(provider->IsValid());
diff --git a/third_party/blink/renderer/platform/graphics/gpu/graphics_context_3d_utils.cc b/third_party/blink/renderer/platform/graphics/gpu/graphics_context_3d_utils.cc index b1b4dcb1..6544ed6 100644 --- a/third_party/blink/renderer/platform/graphics/gpu/graphics_context_3d_utils.cc +++ b/third_party/blink/renderer/platform/graphics/gpu/graphics_context_3d_utils.cc
@@ -37,6 +37,7 @@ namespace blink { void GraphicsContext3DUtils::GetMailboxForSkImage(gpu::Mailbox& out_mailbox, + GLenum& out_texture_target, const sk_sp<SkImage>& image, GLenum filter) { // This object is owned by context_provider_wrapper_, so that weak ref @@ -60,6 +61,8 @@ DCHECK(result); GLuint texture_id = info.fID; + GLenum texture_target = info.fTarget; + out_texture_target = texture_target; auto it = cached_mailboxes_.find(gr_texture); if (it != cached_mailboxes_.end()) { @@ -74,12 +77,12 @@ gr_texture->setRelease(GrTextureMailboxReleaseProc, release_proc_data); cached_mailboxes_.insert(gr_texture, out_mailbox); } - gl->BindTexture(GL_TEXTURE_2D, texture_id); - gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter); - gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter); - gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - gl->BindTexture(GL_TEXTURE_2D, 0); + gl->BindTexture(texture_target, texture_id); + gl->TexParameteri(texture_target, GL_TEXTURE_MIN_FILTER, filter); + gl->TexParameteri(texture_target, GL_TEXTURE_MAG_FILTER, filter); + gl->TexParameteri(texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + gl->TexParameteri(texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + gl->BindTexture(texture_target, 0); gr_texture->textureParamsModified(); }
diff --git a/third_party/blink/renderer/platform/graphics/gpu/graphics_context_3d_utils.h b/third_party/blink/renderer/platform/graphics/gpu/graphics_context_3d_utils.h index 4b96832..cea20e4 100644 --- a/third_party/blink/renderer/platform/graphics/gpu/graphics_context_3d_utils.h +++ b/third_party/blink/renderer/platform/graphics/gpu/graphics_context_3d_utils.h
@@ -35,6 +35,7 @@ // when the texture gets recycled by skia for creating a new SkSurface or // SkImage with a pre-existing GrTexture backing. void GetMailboxForSkImage(gpu::Mailbox&, + GLenum&, const sk_sp<SkImage>&, GLenum filter); void RemoveCachedMailbox(GrTexture*);
diff --git a/third_party/blink/renderer/platform/graphics/gpu/image_layer_bridge.h b/third_party/blink/renderer/platform/graphics/gpu/image_layer_bridge.h index 6f33ac4c6..b6879f94 100644 --- a/third_party/blink/renderer/platform/graphics/gpu/image_layer_bridge.h +++ b/third_party/blink/renderer/platform/graphics/gpu/image_layer_bridge.h
@@ -56,7 +56,7 @@ } void SetUV(const FloatPoint& left_top, const FloatPoint& right_bottom); - bool IsAccelerated() { return image_->IsTextureBacked(); } + bool IsAccelerated() { return image_ && image_->IsTextureBacked(); } void Trace(blink::Visitor* visitor) {}
diff --git a/third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context_test.cc b/third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context_test.cc index 4f05748..592f4801 100644 --- a/third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context_test.cc +++ b/third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context_test.cc
@@ -6,6 +6,7 @@ #include <memory> +#include "base/test/null_task_runner.h" #include "gpu/command_buffer/client/gles2_interface.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -29,6 +30,8 @@ class SharedGpuContextTestBase : public Test { public: void SetUp() override { + task_runner_ = base::MakeRefCounted<base::NullTaskRunner>(); + handle_ = std::make_unique<base::ThreadTaskRunnerHandle>(task_runner_); auto factory = [](GLES2InterfaceType* gl, bool* gpu_compositing_disabled) -> std::unique_ptr<WebGraphicsContext3DProvider> { *gpu_compositing_disabled = false; @@ -39,8 +42,14 @@ WTF::BindRepeating(factory, WTF::Unretained(&gl_))); } - void TearDown() override { SharedGpuContext::ResetForTesting(); } + void TearDown() override { + handle_.reset(); + task_runner_.reset(); + SharedGpuContext::ResetForTesting(); + } + scoped_refptr<base::NullTaskRunner> task_runner_; + std::unique_ptr<base::ThreadTaskRunnerHandle> handle_; GLES2InterfaceType gl_; }; @@ -62,6 +71,8 @@ class BadSharedGpuContextTest : public Test { public: void SetUp() override { + task_runner_ = base::MakeRefCounted<base::NullTaskRunner>(); + handle_ = std::make_unique<base::ThreadTaskRunnerHandle>(task_runner_); auto factory = [](bool* gpu_compositing_disabled) -> std::unique_ptr<WebGraphicsContext3DProvider> { *gpu_compositing_disabled = false; @@ -71,7 +82,14 @@ WTF::BindRepeating(factory)); } - void TearDown() override { SharedGpuContext::ResetForTesting(); } + void TearDown() override { + handle_.reset(); + task_runner_.reset(); + SharedGpuContext::ResetForTesting(); + } + + scoped_refptr<base::NullTaskRunner> task_runner_; + std::unique_ptr<base::ThreadTaskRunnerHandle> handle_; }; // Test fixure that simulate not using gpu compositing. @@ -205,6 +223,7 @@ FakeMailboxGenerator mailboxGenerator; gpu::Mailbox mailbox; + GLenum texture_target; mailbox.name[0] = 0; EXPECT_CALL(gl_, ProduceTextureDirectCHROMIUM(_, mailbox.name)) @@ -213,7 +232,8 @@ &FakeMailboxGenerator::ProduceTexture)); SharedGpuContext::ContextProviderWrapper()->Utils()->GetMailboxForSkImage( - mailbox, image->PaintImageForCurrentFrame().GetSkImage(), GL_NEAREST); + mailbox, texture_target, image->PaintImageForCurrentFrame().GetSkImage(), + GL_NEAREST); EXPECT_EQ(mailbox.name[0], 1); @@ -224,7 +244,8 @@ mailbox.name[0] = 0; SharedGpuContext::ContextProviderWrapper()->Utils()->GetMailboxForSkImage( - mailbox, image->PaintImageForCurrentFrame().GetSkImage(), GL_NEAREST); + mailbox, texture_target, image->PaintImageForCurrentFrame().GetSkImage(), + GL_NEAREST); EXPECT_EQ(mailbox.name[0], 1); testing::Mock::VerifyAndClearExpectations(&gl_); @@ -246,6 +267,7 @@ FakeMailboxGenerator mailboxGenerator; gpu::Mailbox mailbox; + GLenum texture_target; mailbox.name[0] = 0; EXPECT_CALL(gl_, ProduceTextureDirectCHROMIUM(_, mailbox.name)) @@ -254,7 +276,8 @@ &FakeMailboxGenerator::ProduceTexture)); SharedGpuContext::ContextProviderWrapper()->Utils()->GetMailboxForSkImage( - mailbox, image->PaintImageForCurrentFrame().GetSkImage(), GL_NEAREST); + mailbox, texture_target, image->PaintImageForCurrentFrame().GetSkImage(), + GL_NEAREST); EXPECT_EQ(mailbox.name[0], 1); testing::Mock::VerifyAndClearExpectations(&gl_); @@ -284,7 +307,8 @@ mailbox.name[0] = 0; SharedGpuContext::ContextProviderWrapper()->Utils()->GetMailboxForSkImage( - mailbox, image->PaintImageForCurrentFrame().GetSkImage(), GL_NEAREST); + mailbox, texture_target, image->PaintImageForCurrentFrame().GetSkImage(), + GL_NEAREST); EXPECT_EQ(mailbox.name[0], 1); testing::Mock::VerifyAndClearExpectations(&gl_);
diff --git a/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.cc b/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.cc index 6e06b938..b23235b 100644 --- a/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.cc +++ b/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.cc
@@ -43,13 +43,35 @@ mailbox_(mailbox), sync_token_(sync_token), texture_id_(texture_id_to_delete_after_mailbox_consumed), - size_(mailbox_size), is_converted_from_skia_texture_(false), - thread_id_(0) { + thread_id_(0), + sk_image_info_(SkImageInfo::MakeN32Premul(mailbox_size.Width(), + mailbox_size.Height())), + texture_target_(GL_TEXTURE_2D) { InitCommon(); } MailboxTextureHolder::MailboxTextureHolder( + const gpu::Mailbox& mailbox, + const gpu::SyncToken& sync_token, + base::WeakPtr<WebGraphicsContext3DProviderWrapper>&& + context_provider_wrapper, + PlatformThreadId context_thread_id, + const SkImageInfo& sk_image_info, + GLenum texture_target) + : TextureHolder(std::move(context_provider_wrapper)), + mailbox_(mailbox), + sync_token_(sync_token), + texture_id_(0), + is_converted_from_skia_texture_(false), + thread_id_(context_thread_id), + sk_image_info_(sk_image_info), + texture_target_(texture_target) { + DCHECK(thread_id_); + DCHECK(!IsCrossThread() || sync_token_.verified_flush()); +} + +MailboxTextureHolder::MailboxTextureHolder( std::unique_ptr<TextureHolder> texture_holder, GLenum filter) : TextureHolder(texture_holder->ContextProviderWrapper()), @@ -59,13 +81,13 @@ DCHECK(texture_holder->IsSkiaTextureHolder()); sk_sp<SkImage> image = texture_holder->GetSkImage(); DCHECK(image); - size_ = IntSize(image->width(), image->height()); + sk_image_info_ = image->imageInfo(); if (!ContextProviderWrapper()) return; - ContextProviderWrapper()->Utils()->GetMailboxForSkImage(mailbox_, image, - filter); + ContextProviderWrapper()->Utils()->GetMailboxForSkImage( + mailbox_, texture_target_, image, filter); InitCommon(); } @@ -118,6 +140,7 @@ } void MailboxTextureHolder::InitCommon() { + DCHECK(!thread_id_); Thread* thread = Thread::Current(); thread_id_ = thread->ThreadId(); texture_thread_task_runner_ = thread->GetTaskRunner();
diff --git a/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.h b/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.h index 6d4f3a5..f689320 100644 --- a/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.h +++ b/third_party/blink/renderer/platform/graphics/mailbox_texture_holder.h
@@ -13,6 +13,7 @@ #include "third_party/blink/renderer/platform/platform_export.h" #include "third_party/blink/renderer/platform/scheduler/public/thread.h" #include "third_party/khronos/GLES2/gl2.h" +#include "third_party/skia/include/core/SkImageInfo.h" namespace blink { @@ -22,7 +23,9 @@ bool IsSkiaTextureHolder() final { return false; } bool IsMailboxTextureHolder() final { return true; } - IntSize Size() const final { return size_; } + IntSize Size() const final { + return IntSize(sk_image_info_.width(), sk_image_info_.height()); + } bool CurrentFrameKnownToBeOpaque() final { return false; } bool IsValid() const final; bool IsCrossThread() const final; @@ -32,6 +35,8 @@ void UpdateSyncToken(gpu::SyncToken sync_token) final { sync_token_ = sync_token; } + const SkImageInfo& sk_image_info() const { return sk_image_info_; } + GLenum texture_target() const { return texture_target_; } void Sync(MailboxSyncMode) final; // In WebGL's commit or transferToImageBitmap calls, it will call the @@ -45,6 +50,15 @@ // This function turns a texture-backed SkImage into a mailbox and a // syncToken. MailboxTextureHolder(std::unique_ptr<TextureHolder>, GLenum filter); + // This function may be used when the MailboxTextureHolder is created on a + // different thread. The caller must provide a verified sync token if it is + // created cross-thread. + MailboxTextureHolder(const gpu::Mailbox&, + const gpu::SyncToken&, + base::WeakPtr<WebGraphicsContext3DProviderWrapper>&&, + PlatformThreadId context_thread_id, + const SkImageInfo& sk_image_info, + GLenum texture_target); private: void InitCommon(); @@ -52,11 +66,12 @@ gpu::Mailbox mailbox_; gpu::SyncToken sync_token_; unsigned texture_id_; - IntSize size_; bool is_converted_from_skia_texture_; scoped_refptr<base::SingleThreadTaskRunner> texture_thread_task_runner_; PlatformThreadId thread_id_; bool did_issue_ordering_barrier_ = false; + SkImageInfo sk_image_info_; + GLenum texture_target_; }; } // namespace blink
diff --git a/third_party/blink/renderer/platform/graphics/skia_texture_holder.cc b/third_party/blink/renderer/platform/graphics/skia_texture_holder.cc index 50267b7..daeebbc3 100644 --- a/third_party/blink/renderer/platform/graphics/skia_texture_holder.cc +++ b/third_party/blink/renderer/platform/graphics/skia_texture_holder.cc
@@ -7,6 +7,7 @@ #include "gpu/command_buffer/client/gles2_interface.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/platform/cross_thread_functional.h" +#include "third_party/blink/renderer/platform/graphics/canvas_color_params.h" #include "third_party/blink/renderer/platform/graphics/gpu/shared_gpu_context.h" #include "third_party/blink/renderer/platform/graphics/mailbox_texture_holder.h" #include "third_party/khronos/GLES2/gl2ext.h" @@ -28,7 +29,11 @@ DCHECK(texture_holder->IsMailboxTextureHolder()); const gpu::Mailbox mailbox = texture_holder->GetMailbox(); const gpu::SyncToken sync_token = texture_holder->GetSyncToken(); - const IntSize mailbox_size = texture_holder->Size(); + + auto* mailbox_texture_holder = + static_cast<MailboxTextureHolder*>(texture_holder.get()); + const auto& sk_image_info = mailbox_texture_holder->sk_image_info(); + GLenum texture_target = mailbox_texture_holder->texture_target(); if (!ContextProvider()) return; @@ -53,19 +58,17 @@ } GrGLTextureInfo texture_info; - texture_info.fTarget = GL_TEXTURE_2D; + texture_info.fTarget = texture_target; texture_info.fID = shared_context_texture_id; - if (kN32_SkColorType == kRGBA_8888_SkColorType) { - texture_info.fFormat = GL_RGBA8_OES; - } else { - DCHECK(kN32_SkColorType == kBGRA_8888_SkColorType); - texture_info.fFormat = GL_BGRA8_EXT; - } - GrBackendTexture backend_texture(mailbox_size.Width(), mailbox_size.Height(), - GrMipMapped::kNo, texture_info); - image_ = SkImage::MakeFromAdoptedTexture(shared_gr_context, backend_texture, - kBottomLeft_GrSurfaceOrigin, - kN32_SkColorType); + texture_info.fFormat = + CanvasColorParams(sk_image_info).GLSizedInternalFormat(); + GrBackendTexture backend_texture(sk_image_info.width(), + sk_image_info.height(), GrMipMapped::kNo, + texture_info); + image_ = SkImage::MakeFromAdoptedTexture( + shared_gr_context, backend_texture, kBottomLeft_GrSurfaceOrigin, + sk_image_info.colorType(), sk_image_info.alphaType(), + sk_image_info.refColorSpace()); } SkiaTextureHolder::~SkiaTextureHolder() {
diff --git a/third_party/blink/renderer/platform/graphics/test/fake_canvas_resource_host.h b/third_party/blink/renderer/platform/graphics/test/fake_canvas_resource_host.h index 92e969a5..df217533 100644 --- a/third_party/blink/renderer/platform/graphics/test/fake_canvas_resource_host.h +++ b/third_party/blink/renderer/platform/graphics/test/fake_canvas_resource_host.h
@@ -31,6 +31,7 @@ AccelerationHint hint) override { if (ResourceProvider()) return ResourceProvider(); + CanvasResourceProvider::ResourceUsage usage = hint == kPreferAcceleration ? CanvasResourceProvider::kAcceleratedCompositedResourceUsage @@ -41,16 +42,31 @@ ? CanvasResourceProvider::kAllowImageChromiumPresentationMode : CanvasResourceProvider::kDefaultPresentationMode; - ReplaceResourceProvider(CanvasResourceProvider::Create( - size_, usage, SharedGpuContext::ContextProviderWrapper(), 0, - CanvasColorParams(), presentation_mode, nullptr)); + std::unique_ptr<CanvasResourceProvider> provider; + if (provider_type_) { + provider = CanvasResourceProvider::CreateForTesting( + size_, *provider_type_, SharedGpuContext::ContextProviderWrapper(), 0, + CanvasColorParams(), presentation_mode, nullptr); + } else { + provider = CanvasResourceProvider::Create( + size_, usage, SharedGpuContext::ContextProviderWrapper(), 0, + CanvasColorParams(), presentation_mode, nullptr); + } + + ReplaceResourceProvider(std::move(provider)); return ResourceProvider(); } + SkFilterQuality FilterQuality() const override { return kLow_SkFilterQuality; } + void set_provider_type(CanvasResourceProvider::ResourceProviderType type) { + provider_type_ = type; + } + private: + base::Optional<CanvasResourceProvider::ResourceProviderType> provider_type_; IntSize size_; };
diff --git a/third_party/blink/renderer/platform/graphics/test/fake_web_graphics_context_3d_provider.h b/third_party/blink/renderer/platform/graphics/test/fake_web_graphics_context_3d_provider.h index e1ae3a8..f5c0f6b 100644 --- a/third_party/blink/renderer/platform/graphics/test/fake_web_graphics_context_3d_provider.h +++ b/third_party/blink/renderer/platform/graphics/test/fake_web_graphics_context_3d_provider.h
@@ -21,13 +21,18 @@ class FakeWebGraphicsContext3DProvider : public WebGraphicsContext3DProvider { public: FakeWebGraphicsContext3DProvider(gpu::gles2::GLES2Interface* gl, - cc::ImageDecodeCache* cache = nullptr) + cc::ImageDecodeCache* cache = nullptr, + GrContext* gr_context = nullptr) : gl_(gl), image_decode_cache_(cache ? cache : &stub_image_decode_cache_) { - GrMockOptions mockOptions; - mockOptions.fConfigOptions[kBGRA_8888_GrPixelConfig] = - mockOptions.fConfigOptions[kRGBA_8888_GrPixelConfig]; - gr_context_ = GrContext::MakeMock(&mockOptions); + if (gr_context) { + gr_context_ = sk_ref_sp<GrContext>(gr_context); + } else { + GrMockOptions mockOptions; + mockOptions.fConfigOptions[kBGRA_8888_GrPixelConfig] = + mockOptions.fConfigOptions[kRGBA_8888_GrPixelConfig]; + gr_context_ = GrContext::MakeMock(&mockOptions); + } // enable all gpu features. for (unsigned feature = 0; feature < gpu::NUMBER_OF_GPU_FEATURE_TYPES; ++feature) {
diff --git a/third_party/blink/renderer/platform/graphics/texture_holder.h b/third_party/blink/renderer/platform/graphics/texture_holder.h index e57624df..4c934f11 100644 --- a/third_party/blink/renderer/platform/graphics/texture_holder.h +++ b/third_party/blink/renderer/platform/graphics/texture_holder.h
@@ -67,11 +67,6 @@ : context_provider_wrapper_(std::move(context_provider_wrapper)) {} private: - // Keep a clone of the SingleThreadTaskRunner. This is to handle the case - // where the AcceleratedStaticBitmapImage was created on one thread and - // transferred to another thread, and the original thread gone out of scope, - // and that we need to clear the resouces associated with that - // AcceleratedStaticBitmapImage on the original thread. base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper_; };
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 513ef34..45d1ae4 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -117,7 +117,7 @@ }, { name: "AsyncClipboard", - status: "experimental", + status: "stable", }, { name: "AudioOutputDevices",
diff --git a/third_party/blink/web_tests/FlagExpectations/disable-site-isolation-trials b/third_party/blink/web_tests/FlagExpectations/disable-site-isolation-trials index 37be4b57..9753fac 100644 --- a/third_party/blink/web_tests/FlagExpectations/disable-site-isolation-trials +++ b/third_party/blink/web_tests/FlagExpectations/disable-site-isolation-trials
@@ -6,13 +6,16 @@ crbug.com/910979 http/tests/html/validation-bubble-oopif-clip.html [ Failure ] # These started failing when network service was enabled by default. -crbug.com/933880 external/wpt/FileAPI/url/cross-global-revoke.sub.html [ Failure ] -crbug.com/933880 external/wpt/FileAPI/url/url-with-fetch.any.html [ Failure ] -crbug.com/933880 external/wpt/FileAPI/url/url-with-xhr.any.html [ Failure ] -crbug.com/933880 external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ] -crbug.com/933880 http/tests/inspector-protocol/network/interception-take-stream.js [ Failure ] -crbug.com/933880 http/tests/inspector-protocol/network/raw-headers-for-protected-document.js [ Failure ] -crbug.com/933880 http/tests/inspector-protocol/network/raw-headers-for-websocket.js [ Failure ] -crbug.com/933880 http/tests/inspector-protocol/network/security-info-on-response.js [ Failure ] -crbug.com/933880 http/tests/inspector-protocol/network/xhr-interception-auth-fail.js [ Failure ] -crbug.com/933880 http/tests/misc/redirect-to-about-blank.html [ Timeout ] +crbug.com/933880 external/wpt/FileAPI/url/cross-global-revoke.sub.html [ Failure ] +crbug.com/933880 external/wpt/FileAPI/url/url-with-fetch.any.html [ Failure ] +crbug.com/933880 external/wpt/FileAPI/url/url-with-xhr.any.html [ Failure ] +crbug.com/933880 external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ] +crbug.com/933880 http/tests/inspector-protocol/network/interception-take-stream.js [ Failure ] +crbug.com/933880 http/tests/inspector-protocol/network/raw-headers-for-protected-document.js [ Failure ] +crbug.com/933880 http/tests/inspector-protocol/network/raw-headers-for-websocket.js [ Failure ] +crbug.com/933880 http/tests/inspector-protocol/network/security-info-on-response.js [ Failure ] +crbug.com/933880 http/tests/inspector-protocol/network/xhr-interception-auth-fail.js [ Failure ] +crbug.com/933880 http/tests/misc/redirect-to-about-blank.html [ Timeout ] + +# Test is for OOPIF-specific behavior. +Bug(none) http/tests/inspector-protocol/fetch/fetch-oopif.js [ Skip ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 026bf76..b188e6551 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -1666,14 +1666,7 @@ crbug.com/538697 [ Win Win10 ] virtual/threaded/printing/webgl-oversized-printing.html [ Failure Crash ] crbug.com/538697 [ Win ] printing/webgl-oversized-printing.html [ Failure Crash ] -# ====== Backdrop-filter related tests BEGIN ====== -# These are known failures - this feature is still being implemented -crbug.com/497522 css3/filters/backdrop-filter-boundary.html [ Failure ] -crbug.com/497522 css3/filters/backdrop-filter-bleeding.html [ Failure ] -crbug.com/497522 css3/filters/backdrop-filter-svg.html [ Failure ] -crbug.com/964417 external/wpt/css/filter-effects/backdrop-filter-clipped.html [ Failure ] -# ====== Backdrop-filter related tests END ====== - +crbug.com/904592 css3/filters/backdrop-filter-svg.html [ Failure ] crbug.com/492664 [ Linux ] external/wpt/css/css-writing-modes/box-offsets-rel-pos-vlr-005.xht [ Failure ] crbug.com/492664 [ Linux ] external/wpt/css/css-writing-modes/box-offsets-rel-pos-vrl-004.xht [ Failure ] @@ -4657,6 +4650,10 @@ crbug.com/961439 external/wpt/cookies/samesite-none-secure/ [ Failure ] crbug.com/961439 virtual/samesite-by-default-cookies/external/wpt/cookies/samesite-none-secure/ [ Failure ] +# Deprecation messages for SameSite cookie changes cause flakes in cookies tests using document.cookie. +crbug.com/969144 [ Mac ] http/tests/security/cookies/base-tag.html [ Pass Failure ] +crbug.com/969144 [ Mac ] http/tests/security/cookies/base-about-blank.html [ Pass Failure ] + # Client hint tests that fail in content_shell but pass when run manually using # full browser. crbug.com/856700 external/wpt/client-hints/accept_ch_lifetime_same_origin_iframe.tentative.https.html [ Skip ]
diff --git a/third_party/blink/web_tests/css3/filters/backdrop-filter-bleeding-expected.png b/third_party/blink/web_tests/css3/filters/backdrop-filter-bleeding-expected.png deleted file mode 100644 index 1e76a1c..0000000 --- a/third_party/blink/web_tests/css3/filters/backdrop-filter-bleeding-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/css3/filters/backdrop-filter-bleeding.html b/third_party/blink/web_tests/css3/filters/backdrop-filter-bleeding.html deleted file mode 100644 index 3f94bf3b..0000000 --- a/third_party/blink/web_tests/css3/filters/backdrop-filter-bleeding.html +++ /dev/null
@@ -1,23 +0,0 @@ -<!DOCTYPE html> -<style> -.bg { - position: relative; - display: inline-block; - width: 170px; - height: 100px; - background-image: url('resources/red-border.png'); -} -.fg { - position: absolute; - left: 5px; - top: 5px; - width: 160px; - height: 90px; -} -</style> -<div class="bg"><div class="fg"></div></div> -<div class="bg"><div class="fg" style="backdrop-filter: blur(3px);"></div></div> -<div class="bg"><div class="fg" style="backdrop-filter: blur(6px);"></div></div> -<div class="bg"><div class="fg" style="backdrop-filter: blur(12px);"></div></div> -<div class="bg"><div class="fg" style="backdrop-filter: blur(24px);"></div></div> -<div class="bg"><div class="fg" style="backdrop-filter: blur(48px);"></div></div>
diff --git a/third_party/blink/web_tests/css3/filters/backdrop-filter-boundary-expected.png b/third_party/blink/web_tests/css3/filters/backdrop-filter-boundary-expected.png index e3bd346..f5794ba2 100644 --- a/third_party/blink/web_tests/css3/filters/backdrop-filter-boundary-expected.png +++ b/third_party/blink/web_tests/css3/filters/backdrop-filter-boundary-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/css3/filters/backdrop-filter-boundary.html b/third_party/blink/web_tests/css3/filters/backdrop-filter-boundary.html index 0334c3a..325f1976 100644 --- a/third_party/blink/web_tests/css3/filters/backdrop-filter-boundary.html +++ b/third_party/blink/web_tests/css3/filters/backdrop-filter-boundary.html
@@ -14,9 +14,18 @@ width: 150px; height: 80px; } +body { + background-color: lime; +} </style> -<div class="bg"><div class="fg" style="backdrop-filter: blur(3px);"></div></div> -<div class="bg"><div class="fg" style="backdrop-filter: blur(6px);"></div></div> -<div class="bg"><div class="fg" style="backdrop-filter: blur(12px);"></div></div> -<div class="bg"><div class="fg" style="backdrop-filter: blur(24px);"></div></div> -<div class="bg"><div class="fg" style="backdrop-filter: blur(48px);"></div></div> +<div style="width:550px"> + <div class="bg"><div class="fg" style="backdrop-filter: blur(3px);"></div></div> + <div class="bg"><div class="fg" style="backdrop-filter: blur(6px);"></div></div> + <div class="bg"><div class="fg" style="backdrop-filter: blur(12px);"></div></div> + <div class="bg"><div class="fg" style="backdrop-filter: blur(24px);"></div></div> + <div class="bg"><div class="fg" style="backdrop-filter: blur(48px);"></div></div> + <div class="bg"><div class="fg" style="backdrop-filter: blur(96px);"></div></div> +</div> + +<!-- This should show an increasing series of blurred blocks, with the higher + blur values bringing in lime green from the edges. -->
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json index f0ace99..6b82a4a 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json
@@ -6523,12 +6523,6 @@ {} ] ], - "pointerevents/pointerevent_touch-action-button-test_touch-manual.html": [ - [ - "pointerevents/pointerevent_touch-action-button-test_touch-manual.html", - {} - ] - ], "pointerevents/pointerevent_touch-action-mouse-manual.html": [ [ "pointerevents/pointerevent_touch-action-mouse-manual.html", @@ -6541,18 +6535,6 @@ {} ] ], - "pointerevents/pointerevent_touch-action-span-test_touch-manual.html": [ - [ - "pointerevents/pointerevent_touch-action-span-test_touch-manual.html", - {} - ] - ], - "pointerevents/pointerevent_touch-action-svg-test_touch-manual.html": [ - [ - "pointerevents/pointerevent_touch-action-svg-test_touch-manual.html", - {} - ] - ], "pointerevents/pointerevent_touch-action-table-test_touch-manual.html": [ [ "pointerevents/pointerevent_touch-action-table-test_touch-manual.html", @@ -295715,6 +295697,14 @@ } ] ], + "pointerevents/pointerevent_touch-action-button-none-test_touch.html": [ + [ + "pointerevents/pointerevent_touch-action-button-none-test_touch.html", + { + "testdriver": true + } + ] + ], "pointerevents/pointerevent_touch-action-illegal.html": [ [ "pointerevents/pointerevent_touch-action-illegal.html", @@ -295819,6 +295809,24 @@ } ] ], + "pointerevents/pointerevent_touch-action-span-none-test_touch.html": [ + [ + "pointerevents/pointerevent_touch-action-span-none-test_touch.html", + { + "testdriver": true, + "timeout": "long" + } + ] + ], + "pointerevents/pointerevent_touch-action-svg-none-test_touch.html": [ + [ + "pointerevents/pointerevent_touch-action-svg-none-test_touch.html", + { + "testdriver": true, + "timeout": "long" + } + ] + ], "pointerevents/pointerevent_touch-action-verification.html": [ [ "pointerevents/pointerevent_touch-action-verification.html", @@ -420465,7 +420473,7 @@ "support" ], "css/css-values/calc-background-position-003.html": [ - "58e995f01c8b100c9d3a92106c81e07e93570b73", + "61ba0a4998c679e85620075590d0d273cad61f1b", "testharness" ], "css/css-values/calc-ch-ex-lang-ref.html": [ @@ -482348,9 +482356,9 @@ "e995ccd5d6e1d4c23a3df075208d794f2b66edbe", "testharness" ], - "pointerevents/pointerevent_touch-action-button-test_touch-manual.html": [ - "c7c5d9a44080863f69afda3c1a94f268e7d90096", - "manual" + "pointerevents/pointerevent_touch-action-button-none-test_touch.html": [ + "ea4b4f961562576b622c57e750b4ee568314fb26", + "testharness" ], "pointerevents/pointerevent_touch-action-illegal.html": [ "5fe6179840eeda9a025e951f8ff28b211da9fafe", @@ -482412,13 +482420,13 @@ "1c09b15f1f99eead72a0689ab14a4facb1c61e3f", "manual" ], - "pointerevents/pointerevent_touch-action-span-test_touch-manual.html": [ - "2cbc34fe22cb6a2c65c56f1c69973d542f937856", - "manual" + "pointerevents/pointerevent_touch-action-span-none-test_touch.html": [ + "845da068e6279391af9af2ecc54097298a85c554", + "testharness" ], - "pointerevents/pointerevent_touch-action-svg-test_touch-manual.html": [ - "ecc026e419c7c9bb54623e8b71cf0a202b4107f0", - "manual" + "pointerevents/pointerevent_touch-action-svg-none-test_touch.html": [ + "252ed2fed0cfec792dfc2fccacea27234216d8c4", + "testharness" ], "pointerevents/pointerevent_touch-action-table-test_touch-manual.html": [ "07a78f572985658c04b6ce7709e01b936c73f0fd", @@ -482609,7 +482617,7 @@ "testharness" ], "portals/portals-activate-resolution.html": [ - "03dc09f3cf51c17a4b15e01719ff6ef36d15621b", + "44ccea3bc521e14f7c826f14c3e815494df65ae7", "testharness" ], "portals/portals-activate-twice.html": [ @@ -482621,7 +482629,7 @@ "testharness" ], "portals/portals-cross-origin-load.sub.html": [ - "e94c45be6d75b964e59d985c2826d9cb97947e31", + "e19a225de046ba01a1232fb0cb456b6a706f583a", "testharness" ], "portals/portals-host-exposure.sub.html": [ @@ -482637,7 +482645,7 @@ "testharness" ], "portals/portals-host-post-message.sub.html": [ - "a19715eb0af90c38aec08e3d488523a9c3674a1f", + "5331da0d7c3f0887bc161b7c8bc53ffcf3f1ebda", "testharness" ], "portals/portals-nested.html": [ @@ -482649,7 +482657,7 @@ "testharness" ], "portals/portals-post-message.sub.html": [ - "2d16a42a21508e85cb07f3ee22b1e7abbbdd5350", + "b37e8afa6db05218d8e128ce1bc352ed1f892273", "testharness" ], "portals/portals-rendering.html": [ @@ -482669,15 +482677,15 @@ "support" ], "portals/resources/portal-activate-inside-portal.html": [ - "c6dc0bb68b30777b48d7bb69c72c62dc601619dd", + "517c9a47e516124c2602607f5a3b01d3acb0e971", "support" ], "portals/resources/portal-activate-twice-window-1.html": [ - "2fe6755e96102eaa4a66589347ba5cadb6f0a1ed", + "fbc5a6e93d9244178d89a6a0be30660e8b453452", "support" ], "portals/resources/portal-activate-twice-window-2.html": [ - "89fdf15d7891718522f32ea39e87da9245a86f69", + "6ba8dc5839923c0f90f73495f89faeb4c2342782", "support" ], "portals/resources/portal-embed-and-activate.html": [ @@ -482705,7 +482713,7 @@ "support" ], "portals/resources/portal-host-post-message.sub.html": [ - "06d42820a3a9a907de9904fbe8e4b00c3dc55caf", + "3c49d560f4b7f3b41d463dec1dc8ce621f47c0d3", "support" ], "portals/resources/portal-host.html": [ @@ -482717,35 +482725,35 @@ "support" ], "portals/resources/portal-post-message-after-activate-window.html": [ - "007f0f994a90c35ae28f9073ee211308a5216918", + "73d2c115587ceca5b1583ce909ad4184cebfd0c3", "support" ], "portals/resources/portal-post-message-before-activate-portal.html": [ - "9e6c9a38958e35d754af918bb060a8bfe7ad28c5", + "d34875f981f19cc42b9b69b32b0fb23c535a9cc7", "support" ], "portals/resources/portal-post-message-before-activate-window.html": [ - "36c0ccc742f24c09773f162eb8bf532f34333d05", + "6389829c7cc469304c67be8c7aca2609301fd5ed", "support" ], "portals/resources/portal-post-message-during-activate-window.html": [ - "f588bda8ec4ccad6a573d680fbc75e8f77388b8a", + "6e220277d9fe60dd26caa6a199c9eaf46adc6fb1", "support" ], "portals/resources/portal-post-message-portal.html": [ - "ccb87aaac21d5946b9f409d09be7637074ffc6ce", + "26f62839af5ed8ea7a50535f411780bdf7fd6e03", "support" ], "portals/resources/portals-adopt-predecessor-portal.html": [ - "9e1b41193a68c6d75a522eb1d71698096a4da9b4", + "78c6af1268cb91e9f43cf3fb41586b94f0d44889", "support" ], "portals/resources/portals-adopt-predecessor.html": [ - "72bda702f6236be75cc757f94cdaabe9e34fb701", + "4bd01c338ed6fc2a7c85a17e7d869aa31635533b", "support" ], "portals/resources/portals-nested-portal.html": [ - "42281ce993567821f4840bdd0d943eab7abdedf4", + "1ac17c03d4cdc6c9a7c3648c61be3909e965741e", "support" ], "portals/resources/portals-rendering-portal.html": [ @@ -482757,7 +482765,7 @@ "support" ], "portals/resources/simple-portal.html": [ - "d4710c018c0653406cc6e219c7ae677bc0566d62", + "29380099af1a3b9bf0990990ecefd8fa632d30c4", "support" ], "preload/META.yml": [ @@ -483265,7 +483273,7 @@ "testharness" ], "push-api/idlharness.https.any.serviceworker-expected.txt": [ - "4e57b9848f45c399a291595823820882af84503c", + "572742c5657cdaac6eedabf3762985535ace0f68", "support" ], "quirks/META.yml": [
diff --git a/third_party/blink/web_tests/external/wpt/css/css-flexbox/flex-item-and-percentage-abspos.html b/third_party/blink/web_tests/external/wpt/css/css-flexbox/flex-item-and-percentage-abspos.html new file mode 100644 index 0000000..76bdff21 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-flexbox/flex-item-and-percentage-abspos.html
@@ -0,0 +1,15 @@ +<!DOCTYPE html> +<link rel="author" title="Google LLC" href="http://www.google.com" /> +<link rel="help" href="https://drafts.csswg.org/css-flexbox/#cross-sizing" /> +<link rel="help" href="https://crbug.com/967061" /> +<title>css-flexbox: Tests that we correctly size a flex item when we have a percentage-sized abspos element</title> +<link rel="match" href="../reference/ref-filled-green-100px-square.xht" /> + +<p>Test passes if there is a filled green square and <strong>no red</strong>.</p> + +<div style="display: flex;"> + <div style="overflow: hidden; position: relative;"> + <div style="width: 100%; height: 100%; position: absolute; top: 0; left: 0;"></div> + <div style="width: 100px; height: 100px; background: green;"></div> + </div> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-ui/outline-022.html b/third_party/blink/web_tests/external/wpt/css/css-ui/outline-022.html new file mode 100644 index 0000000..84cb516 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-ui/outline-022.html
@@ -0,0 +1,30 @@ +<!DOCTYPE html> +<title>CSS-UI test: outline works on nested spans</title> +<link rel="author" href="mailto:atotic@google.com"> +<link rel="help" href="https://drafts.csswg.org/css-ui/#outline-props"> +<link rel="match" href="../reference/ref-filled-green-100px-square-only.html"> +<meta name="flags" content=""> +<style> +body { + --outline-width: 10px; + --square-width: 80px; +} +#container { + width: var(--square-width); + padding: var(--outline-width); +} +#target { + font-family: Ahem; + font-size: var(--square-width); + outline: solid var(--outline-width) green; + color: green; +} +</style> +<p>Test passes if there is a filled green square.</p> +<div id="container"> + <span> + <span> + <span id="target">x</span> + </span> + </span> +</div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-values/calc-background-position-003.html b/third_party/blink/web_tests/external/wpt/css/css-values/calc-background-position-003.html index 58e995f0..61ba0a4 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-values/calc-background-position-003.html +++ b/third_party/blink/web_tests/external/wpt/css/css-values/calc-background-position-003.html
@@ -5,7 +5,7 @@ <title>CSS Values and Units Test: serialization of 'background-position' when specified with calc() function</title> <link rel="author" title="Gérard Talbot" href="http://www.gtalbot.org/BrowserBugsSection/css21testsuite/"> - <link rel="help" href="https://www.w3.org/TR/css4-values/#calc-serialize"> + <link rel="help" href="https://www.w3.org/TR/css-values-4/#calc-serialize"> <meta name="flags" content=""> <meta content="This test verifies how 6 calc() functions are serialized for 'background-position'." name="assert">
diff --git a/third_party/blink/web_tests/external/wpt/html/dom/interfaces.worker-expected.txt b/third_party/blink/web_tests/external/wpt/html/dom/interfaces.worker-expected.txt index c2e30c2e..74aec36 100644 --- a/third_party/blink/web_tests/external/wpt/html/dom/interfaces.worker-expected.txt +++ b/third_party/blink/web_tests/external/wpt/html/dom/interfaces.worker-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 660 tests; 611 PASS, 49 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 660 tests; 619 PASS, 41 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS idl_test setup PASS Partial interface Document: original interface defined PASS Partial interface mixin NavigatorID: original interface mixin defined @@ -188,14 +188,14 @@ PASS Path2D interface: operation rect(unrestricted double, unrestricted double, unrestricted double, unrestricted double) PASS Path2D interface: operation arc(unrestricted double, unrestricted double, unrestricted double, unrestricted double, unrestricted double, boolean) PASS Path2D interface: operation ellipse(unrestricted double, unrestricted double, unrestricted double, unrestricted double, unrestricted double, unrestricted double, unrestricted double, boolean) -FAIL ImageBitmapRenderingContext interface: existence and properties of interface object assert_own_property: self does not have own property "ImageBitmapRenderingContext" expected property "ImageBitmapRenderingContext" missing -FAIL ImageBitmapRenderingContext interface object length assert_own_property: self does not have own property "ImageBitmapRenderingContext" expected property "ImageBitmapRenderingContext" missing -FAIL ImageBitmapRenderingContext interface object name assert_own_property: self does not have own property "ImageBitmapRenderingContext" expected property "ImageBitmapRenderingContext" missing -FAIL ImageBitmapRenderingContext interface: existence and properties of interface prototype object assert_own_property: self does not have own property "ImageBitmapRenderingContext" expected property "ImageBitmapRenderingContext" missing -FAIL ImageBitmapRenderingContext interface: existence and properties of interface prototype object's "constructor" property assert_own_property: self does not have own property "ImageBitmapRenderingContext" expected property "ImageBitmapRenderingContext" missing -FAIL ImageBitmapRenderingContext interface: existence and properties of interface prototype object's @@unscopables property assert_own_property: self does not have own property "ImageBitmapRenderingContext" expected property "ImageBitmapRenderingContext" missing -FAIL ImageBitmapRenderingContext interface: attribute canvas assert_own_property: self does not have own property "ImageBitmapRenderingContext" expected property "ImageBitmapRenderingContext" missing -FAIL ImageBitmapRenderingContext interface: operation transferFromImageBitmap(ImageBitmap) assert_own_property: self does not have own property "ImageBitmapRenderingContext" expected property "ImageBitmapRenderingContext" missing +PASS ImageBitmapRenderingContext interface: existence and properties of interface object +PASS ImageBitmapRenderingContext interface object length +PASS ImageBitmapRenderingContext interface object name +PASS ImageBitmapRenderingContext interface: existence and properties of interface prototype object +PASS ImageBitmapRenderingContext interface: existence and properties of interface prototype object's "constructor" property +PASS ImageBitmapRenderingContext interface: existence and properties of interface prototype object's @@unscopables property +PASS ImageBitmapRenderingContext interface: attribute canvas +PASS ImageBitmapRenderingContext interface: operation transferFromImageBitmap(ImageBitmap) PASS OffscreenCanvas interface: existence and properties of interface object PASS OffscreenCanvas interface object length PASS OffscreenCanvas interface object name
diff --git a/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/context-creation-offscreen-with-alpha.html b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/context-creation-offscreen-with-alpha.html new file mode 100644 index 0000000..b565def9 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/context-creation-offscreen-with-alpha.html
@@ -0,0 +1,62 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Canvas's ImageBitmapRenderingContext test</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context"> +<script> +var width = 10; +var height = 10; + +function testImageBitmap(image, opts, expectedR, expectedG, expectedB, expectedA) +{ + var dstCanvas = new OffscreenCanvas(width,height); + var dstCtx = dstCanvas.getContext('bitmaprenderer', opts); + dstCtx.transferFromImageBitmap(image); + + var myCanvas = document.createElement('canvas'); + myCanvas.width = width; + myCanvas.height = height; + var myCtx = myCanvas.getContext('2d'); + myCtx.drawImage(dstCanvas, 0, 0); + var color = myCtx.getImageData(5, 5, 1, 1).data; + assert_array_approx_equals(color, [expectedR, expectedG, expectedB, expectedA],1); +} + +promise_test(function() { + var srcCanvas = document.createElement('canvas'); + srcCanvas.width = width; + srcCanvas.height = height; + var ctx = srcCanvas.getContext('2d'); + ctx.fillStyle = 'rgba(0, 255, 0, 0.5)'; + ctx.fillRect(0, 0, width, height); + return createImageBitmap(srcCanvas).then(function(image) { + testImageBitmap(image, {alpha: false}, 0, 255, 0, 128); + }); +}, "Test that an ImageBitmapRenderingContext with alpha disabled makes the canvas opaque"); + +promise_test(function() { + var srcCanvas = document.createElement('canvas'); + srcCanvas.width = width; + srcCanvas.height = height; + var ctx = srcCanvas.getContext('2d'); + ctx.fillStyle = 'rgba(0, 255, 0, 0.5)'; + ctx.fillRect(0, 0, width, height); + return createImageBitmap(srcCanvas).then(function(image) { + testImageBitmap(image, {alpha: true}, 0, 255, 0, 128); + }); +}, "Test that an ImageBitmapRenderingContext with alpha enabled preserves the alpha"); + +promise_test(function() { + var srcCanvas = document.createElement('canvas'); + srcCanvas.width = width; + srcCanvas.height = height; + var ctx = srcCanvas.getContext('2d'); + ctx.fillStyle = 'rgba(0, 255, 0, 0.5)'; + ctx.fillRect(0, 0, width, height); + return createImageBitmap(srcCanvas).then(function(image) { + testImageBitmap(image, {}, 0, 255, 0, 128); + }); +}, "Test that the 'alpha' context creation attribute is true by default"); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/context-creation-offscreen.html b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/context-creation-offscreen.html new file mode 100644 index 0000000..41cc6dc --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/context-creation-offscreen.html
@@ -0,0 +1,17 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Canvas's ImageBitmapRenderingContext test</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context"> +<script> +var width = 10; +var height = 10; + +test(function() { + var canvas = new OffscreenCanvas(60,60); + var ctx = canvas.getContext('bitmaprenderer'); + assert_true(ctx instanceof ImageBitmapRenderingContext); +}, "Test that canvas.getContext('bitmaprenderer') returns an instance of ImageBitmapRenderingContext"); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/context-creation-with-alpha-expected.txt b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/context-creation-with-alpha-expected.txt deleted file mode 100644 index f4a8ae2..0000000 --- a/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/context-creation-with-alpha-expected.txt +++ /dev/null
@@ -1,6 +0,0 @@ -This is a testharness.js-based test. -FAIL Test that an ImageBitmapRenderingContext with alpha disabled makes the canvas opaque assert_array_equals: property 1, expected 127 but got 255 -FAIL Test that an ImageBitmapRenderingContext with alpha enabled preserves the alpha assert_array_equals: property 3, expected 127 but got 128 -FAIL Test that the 'alpha' context creation attribute is true by default assert_array_equals: property 3, expected 127 but got 128 -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/context-creation-with-alpha.html b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/context-creation-with-alpha.html index 4354b9ac..2c8fa08 100644 --- a/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/context-creation-with-alpha.html +++ b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/context-creation-with-alpha.html
@@ -8,24 +8,12 @@ var width = 10; var height = 10; -function testCanvas(ctx, r, g, b, a) -{ - var color = ctx.getImageData(5, 5, 1, 1).data; - assert_array_equals(color, [r, g, b, a]); -} - -function consumeImageBitmap(image, alphaVal, expectedR, expectedG, expectedB, expectedA) +function testImageBitmap(image, opts, expectedR, expectedG, expectedB, expectedA) { var dstCanvas = document.createElement('canvas'); dstCanvas.width = width; dstCanvas.height = height; - var dstCtx; - if (alphaVal == 'true') - dstCtx = dstCanvas.getContext('bitmaprenderer', { alpha: true }); - else if (alphaVal == 'false') - dstCtx = dstCanvas.getContext('bitmaprenderer', { alpha: false }); - else - dstCtx = dstCanvas.getContext('bitmaprenderer'); + var dstCtx = dstCanvas.getContext('bitmaprenderer', opts); dstCtx.transferFromImageBitmap(image); var myCanvas = document.createElement('canvas'); @@ -33,7 +21,8 @@ myCanvas.height = height; var myCtx = myCanvas.getContext('2d'); myCtx.drawImage(dstCanvas, 0, 0); - testCanvas(myCtx, expectedR, expectedG, expectedB, expectedA); + var color = myCtx.getImageData(5, 5, 1, 1).data; + assert_array_approx_equals(color, [expectedR, expectedG, expectedB, expectedA],1); } promise_test(function() { @@ -44,7 +33,7 @@ ctx.fillStyle = 'rgba(0, 255, 0, 0.5)'; ctx.fillRect(0, 0, width, height); return createImageBitmap(srcCanvas).then(function(image) { - consumeImageBitmap(image, 'false', 0, 127, 0, 255); + testImageBitmap(image, {alpha: false}, 0, 255, 0, 128); }); }, "Test that an ImageBitmapRenderingContext with alpha disabled makes the canvas opaque"); @@ -56,7 +45,7 @@ ctx.fillStyle = 'rgba(0, 255, 0, 0.5)'; ctx.fillRect(0, 0, width, height); return createImageBitmap(srcCanvas).then(function(image) { - consumeImageBitmap(image, 'true', 0, 255, 0, 127); + testImageBitmap(image, {alpha: true}, 0, 255, 0, 128); }); }, "Test that an ImageBitmapRenderingContext with alpha enabled preserves the alpha"); @@ -68,7 +57,7 @@ ctx.fillStyle = 'rgba(0, 255, 0, 0.5)'; ctx.fillRect(0, 0, width, height); return createImageBitmap(srcCanvas).then(function(image) { - consumeImageBitmap(image, '', 0, 255, 0, 127); + testImageBitmap(image, {}, 0, 255, 0, 128); }); }, "Test that the 'alpha' context creation attribute is true by default");
diff --git a/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/toBlob-origin-clean-offscreen.sub.html b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/toBlob-origin-clean-offscreen.sub.html new file mode 100644 index 0000000..0a0e203 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/toBlob-origin-clean-offscreen.sub.html
@@ -0,0 +1,30 @@ +<!DOCTYPE html> +<meta charset=utf-8> +<title>convertToBlob, OffscreenCanvas: origin-clean flag</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context"> +<script> +const crossOriginImageUrl = "http://{{domains[www1]}}:{{ports[http][0]}}/images/red.png"; + +async_test(t => { + var img = new Image(); + // Use a cross-origin URL. + img.src = crossOriginImageUrl; + + img.onload = t.step_func(e => { + createImageBitmap(img, 0, 0, img.width, img.height) + .then(t.step_func(bitmap => { + var canvasBitmap = new OffscreenCanvas(img.width,img.height); + var contextBitmap = canvasBitmap.getContext("bitmaprenderer"); + contextBitmap.transferFromImageBitmap(bitmap); + promise_rejects(t, + new DOMException( + 'convertToBlob on a tainted OffscreenCanvas has to throw', + 'SecurityError'), + canvasBitmap.convertToBlob(), + "convertToBlob on a tainted OffscreenCanvas has to throw").then(t.step_func_done()); + })); + }); +}, "Test that call convertToBlob on a tainted OffscreenCanvas throws exception"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/tranferFromImageBitmap-ToBlob-offscreen.html b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/tranferFromImageBitmap-ToBlob-offscreen.html new file mode 100644 index 0000000..6a555fe --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/tranferFromImageBitmap-ToBlob-offscreen.html
@@ -0,0 +1,50 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Canvas's ImageBitmapRenderingContext test</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context"> +<script> +var width = 10; +var height = 10; + +function testCanvas(ctx, r, g, b, a) +{ + var color = ctx.getImageData(5, 5, 1, 1).data; + assert_array_equals(color, [r, g, b, a]); +} + +promise_test(function() { + function testTransferFromImageBitmapNullability(greenImage) { + var bitmapCanvas = new OffscreenCanvas(width,height); + var bitmapCtx = bitmapCanvas.getContext('bitmaprenderer'); + bitmapCtx.transferFromImageBitmap(greenImage); + + // Make sure the bitmap renderer canvas is filled correctly. + var pngImage = document.getElementById("img"); + bitmapCanvas.convertToBlob().then(function(blob){ + pngImage.src = URL.createObjectURL(blob); + var myCanvasToTest = document.createElement('canvas'); + myCanvasToTest.width = width; + myCanvasToTest.height = height; + var myCtxToTest = myCanvasToTest.getContext('2d'); + myCtxToTest.drawImage(pngImage, 0, 0); + testCanvas(myCtxToTest, 0, 255, 0, 255); + }); + } + + var greenCanvas = document.createElement('canvas'); + greenCanvas.width = width; + greenCanvas.height = height; + var greenCtx = greenCanvas.getContext('2d'); + greenCtx.fillStyle = '#0f0'; + greenCtx.fillRect(0, 0, width, height); + + return Promise.all([ + createImageBitmap(greenCanvas), + ]).then(([greenImage]) => { + testTransferFromImageBitmapNullability(greenImage); + }); +},'Test that transferToBlob works and produce the expected image'); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/tranferFromImageBitmap-TransferToImageBitmap-offscreen.html b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/tranferFromImageBitmap-TransferToImageBitmap-offscreen.html new file mode 100644 index 0000000..9f9c339 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/tranferFromImageBitmap-TransferToImageBitmap-offscreen.html
@@ -0,0 +1,56 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Canvas's ImageBitmapRenderingContext test</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context"> +<script> +var width = 10; +var height = 10; + +function testCanvas(bitmapCanvas, r, g, b, a) +{ + var myCanvas = document.createElement('canvas'); + myCanvas.width = width; + myCanvas.height = height; + var myCtx = myCanvas.getContext('2d'); + myCtx.drawImage(bitmapCanvas, 0, 0); + var color = myCtx.getImageData(5, 5, 1, 1).data; + assert_array_equals(color, [r, g, b, a]); +} + +promise_test(function() { + function testTransferFromImageBitmapNullability(greenImage) { + var bitmapCanvas = new OffscreenCanvas(width,height); + var bitmapCtx = bitmapCanvas.getContext('bitmaprenderer'); + bitmapCtx.transferFromImageBitmap(greenImage); + + // Make sure the bitmap renderer canvas is filled correctly. + var myCanvas = document.createElement('canvas'); + var myCtx = myCanvas.getContext('bitmaprenderer'); + myCtx.transferFromImageBitmap(bitmapCanvas.transferToImageBitmap()); + testCanvas(myCanvas, 0, 255, 0, 255); + + // Test that after transfering for second time to ImageBitmap produces + // a black bitmap of the same size + var myCanvas2 = document.createElement('canvas'); + var myCtx2 = myCanvas2.getContext('bitmaprenderer'); + myCtx2.transferFromImageBitmap(bitmapCanvas.transferToImageBitmap()); + testCanvas(myCanvas2, 0, 0, 0, 255); + } + + var greenCanvas = document.createElement('canvas'); + greenCanvas.width = width; + greenCanvas.height = height; + var greenCtx = greenCanvas.getContext('2d'); + greenCtx.fillStyle = '#0f0'; + greenCtx.fillRect(0, 0, width, height); + + return Promise.all([ + createImageBitmap(greenCanvas), + ]).then(([greenImage]) => { + testTransferFromImageBitmapNullability(greenImage); + }); +},'Test that transferToImageBitmap works and that resets the imagebitmap to black'); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/tranferFromImageBitmap-null-offscreen.html b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/tranferFromImageBitmap-null-offscreen.html new file mode 100644 index 0000000..e05a623a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/tranferFromImageBitmap-null-offscreen.html
@@ -0,0 +1,63 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Canvas's ImageBitmapRenderingContext test</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#the-imagebitmap-rendering-context"> +<script> +var width = 10; +var height = 10; + +function testCanvas(bitmapCanvas, r, g, b, a) +{ + var myCanvas = document.createElement('canvas'); + myCanvas.width = width; + myCanvas.height = height; + var myCtx = myCanvas.getContext('2d'); + myCtx.drawImage(bitmapCanvas, 0, 0); + var color = myCtx.getImageData(5, 5, 1, 1).data; + assert_array_equals(color, [r, g, b, a]); +} + +promise_test(function() { + function testTransferFromImageBitmapNullability(greenImage, redImage) { + var bitmapCanvas = new OffscreenCanvas(width,height); + var bitmapCtx = bitmapCanvas.getContext('bitmaprenderer'); + bitmapCtx.transferFromImageBitmap(greenImage); + + // Make sure the bitmap renderer canvas is filled correctly. + testCanvas(bitmapCanvas, 0, 255, 0, 255); + + // Test if passing null resets the bitmap renderer canvas. + // Drawing the resetted canvas cannot change the destination canvas. + bitmapCtx.transferFromImageBitmap(null); + testCanvas(bitmapCanvas, 0, 0, 0, 0); + + // Test if we can redraw the bitmap canvas correctly after reset. + bitmapCtx.transferFromImageBitmap(redImage); + testCanvas(bitmapCanvas, 255, 0, 0, 255); + } + + var greenCanvas = document.createElement('canvas'); + greenCanvas.width = width; + greenCanvas.height = height; + var greenCtx = greenCanvas.getContext('2d'); + greenCtx.fillStyle = '#0f0'; + greenCtx.fillRect(0, 0, width, height); + + var redCanvas = document.createElement('canvas'); + redCanvas.width = width; + redCanvas.height = height; + var redCtx = redCanvas.getContext('2d'); + redCtx.fillStyle = '#f00'; + redCtx.fillRect(0, 0, width, height); + + return Promise.all([ + createImageBitmap(greenCanvas), + createImageBitmap(redCanvas), + ]).then(([greenImage, redImage]) => { + testTransferFromImageBitmapNullability(greenImage, redImage); + }); +},'Test that transferFromImageBitmap(null) discards the previously transferred image'); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/tranferFromImageBitmap-null.html b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/tranferFromImageBitmap-null.html index c12a8c9..19d2f17 100644 --- a/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/tranferFromImageBitmap-null.html +++ b/third_party/blink/web_tests/external/wpt/imagebitmap-renderingcontext/tranferFromImageBitmap-null.html
@@ -8,9 +8,14 @@ var width = 10; var height = 10; -function testCanvas(ctx, r, g, b, a) +function testCanvas(bitmapCanvas, r, g, b, a) { - var color = ctx.getImageData(5, 5, 1, 1).data; + var myCanvas = document.createElement('canvas'); + myCanvas.width = width; + myCanvas.height = height; + var myCtx = myCanvas.getContext('2d'); + myCtx.drawImage(bitmapCanvas, 0, 0); + var color = myCtx.getImageData(5, 5, 1, 1).data; assert_array_equals(color, [r, g, b, a]); } @@ -23,31 +28,16 @@ bitmapCtx.transferFromImageBitmap(greenImage); // Make sure the bitmap renderer canvas is filled correctly. - var myCanvas = document.createElement('canvas'); - myCanvas.width = width; - myCanvas.height = height; - var myCtx = myCanvas.getContext('2d'); - myCtx.drawImage(bitmapCanvas, 0, 0); - testCanvas(myCtx, 0, 255, 0, 255); + testCanvas(bitmapCanvas, 0, 255, 0, 255); // Test if passing null resets the bitmap renderer canvas. // Drawing the resetted canvas cannot change the destination canvas. bitmapCtx.transferFromImageBitmap(null); - var myCanvas2 = document.createElement('canvas'); - myCanvas2.width = width; - myCanvas2.height = height; - var myCtx2 = myCanvas2.getContext('2d'); - myCtx2.drawImage(bitmapCanvas, 0, 0); - testCanvas(myCtx2, 0, 0, 0, 0); + testCanvas(bitmapCanvas, 0, 0, 0, 0); // Test if we can redraw the bitmap canvas correctly after reset. bitmapCtx.transferFromImageBitmap(redImage); - var myCanvas3 = document.createElement('canvas'); - myCanvas3.width = width; - myCanvas3.height = height; - var myCtx3 = myCanvas3.getContext('2d'); - myCtx3.drawImage(bitmapCanvas, 0, 0); - testCanvas(myCtx3, 255, 0, 0, 255); + testCanvas(bitmapCanvas, 255, 0, 0, 255); } var greenCanvas = document.createElement('canvas');
diff --git a/third_party/blink/web_tests/external/wpt/interfaces/html.idl b/third_party/blink/web_tests/external/wpt/interfaces/html.idl index 5ae46f74..b36c3014 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/html.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/html.idl
@@ -1417,8 +1417,9 @@ [Exposed=(Window,Worker)] interface ImageBitmapRenderingContext { - readonly attribute (HTMLCanvasElement or OffscreenCanvas) canvas; - void transferFromImageBitmap(ImageBitmap? bitmap); + [ImplementedAs=getHTMLOrOffscreenCanvas] readonly attribute (HTMLCanvasElement or OffscreenCanvas) canvas; + + [RaisesException] void transferFromImageBitmap(ImageBitmap? bitmap); }; dictionary ImageBitmapRenderingContextSettings {
diff --git a/third_party/blink/web_tests/external/wpt/portals/portals-no-referrer.html b/third_party/blink/web_tests/external/wpt/portals/portals-referrer-inherit-header.html similarity index 91% rename from third_party/blink/web_tests/external/wpt/portals/portals-no-referrer.html rename to third_party/blink/web_tests/external/wpt/portals/portals-referrer-inherit-header.html index 1bd68a1..0207474f 100644 --- a/third_party/blink/web_tests/external/wpt/portals/portals-no-referrer.html +++ b/third_party/blink/web_tests/external/wpt/portals/portals-referrer-inherit-header.html
@@ -18,6 +18,6 @@ } finally { document.body.removeChild(portal); } -}, "portal contents should be loaded with no referrer"); +}, "portal contents should be loaded with no referrer if document requests it"); </script> </body>
diff --git a/third_party/blink/web_tests/external/wpt/portals/portals-referrer-inherit-header.html.headers b/third_party/blink/web_tests/external/wpt/portals/portals-referrer-inherit-header.html.headers new file mode 100644 index 0000000..7ffbf17 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/portals/portals-referrer-inherit-header.html.headers
@@ -0,0 +1 @@ +Referrer-Policy: no-referrer
diff --git a/third_party/blink/web_tests/external/wpt/portals/portals-no-referrer.html b/third_party/blink/web_tests/external/wpt/portals/portals-referrer-inherit-meta.html similarity index 87% copy from third_party/blink/web_tests/external/wpt/portals/portals-no-referrer.html copy to third_party/blink/web_tests/external/wpt/portals/portals-referrer-inherit-meta.html index 1bd68a1..cf0493fb 100644 --- a/third_party/blink/web_tests/external/wpt/portals/portals-no-referrer.html +++ b/third_party/blink/web_tests/external/wpt/portals/portals-referrer-inherit-meta.html
@@ -1,6 +1,7 @@ <!DOCTYPE html> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<meta name="referrer" content="no-referrer"> <body> <script> promise_test(async () => { @@ -18,6 +19,6 @@ } finally { document.body.removeChild(portal); } -}, "portal contents should be loaded with no referrer"); +}, "portal contents should be loaded with no referrer if document requests it"); </script> </body>
diff --git a/third_party/blink/web_tests/external/wpt/portals/portals-referrer.html b/third_party/blink/web_tests/external/wpt/portals/portals-referrer.html new file mode 100644 index 0000000..cb08f56 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/portals/portals-referrer.html
@@ -0,0 +1,61 @@ +<!DOCTYPE html> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<body> +<script> +promise_test(async () => { + assert_true('HTMLPortalElement' in self, 'HTMLPortalElement is required for this test'); + let portal = document.createElement('portal'); + let referrerPromise = new Promise((resolve, reject) => { + portal.addEventListener('message', e => resolve(e.data), {once: true}); + }); + portal.src = 'resources/postmessage-referrer.sub.html'; + document.body.appendChild(portal); + try { + let {httpReferrer, documentReferrer} = await referrerPromise; + assert_equals(httpReferrer, location.href, 'HTTP Referer header should be sent by default'); + assert_equals(documentReferrer, location.href, 'document.referrer should be present by default'); + } finally { + document.body.removeChild(portal); + } +}, "portal contents should be loaded with referrer"); + +promise_test(async () => { + assert_true('HTMLPortalElement' in self, 'HTMLPortalElement is required for this test'); + let portal = document.createElement('portal'); + portal.referrerPolicy = 'no-referrer'; + let referrerPromise = new Promise((resolve, reject) => { + portal.addEventListener('message', e => resolve(e.data), {once: true}); + }); + portal.src = 'resources/postmessage-referrer.sub.html'; + document.body.appendChild(portal); + try { + let {httpReferrer, documentReferrer} = await referrerPromise; + assert_equals(httpReferrer, 'no-http-referrer', 'No HTTP Referer header should be sent'); + assert_equals(documentReferrer, 'no-document-referrer', 'No document.referrer should be present'); + } finally { + document.body.removeChild(portal); + } +}, "portal contents should be loaded with no referrer if referrerpolicy=no-referrer"); + +promise_test(async () => { + assert_true('HTMLPortalElement' in self, 'HTMLPortalElement is required for this test'); + let portal = document.createElement('portal'); + portal.referrerPolicy = 'origin'; + let referrerPromise = new Promise((resolve, reject) => { + portal.addEventListener('message', e => resolve(e.data), {once: true}); + }); + portal.src = 'resources/postmessage-referrer.sub.html'; + document.body.appendChild(portal); + try { + let {httpReferrer, documentReferrer} = await referrerPromise; + assert_equals(httpReferrer, location.origin + '/', 'HTTP Referer header should contain origin'); + assert_equals(documentReferrer, location.origin + '/', 'document.referrer should contain origin'); + } finally { + document.body.removeChild(portal); + } +}, "portal contents should be loaded with origin only if referrerpolicy=origin"); + +// This is not exhaustive coverage of all possible policies, which are tested elsewhere. +</script> +</body>
diff --git a/third_party/blink/web_tests/fast/canvas-api/OffscreenCanvas-getContext.html b/third_party/blink/web_tests/fast/canvas-api/OffscreenCanvas-getContext.html index 25e1665..68f5e1d 100644 --- a/third_party/blink/web_tests/fast/canvas-api/OffscreenCanvas-getContext.html +++ b/third_party/blink/web_tests/fast/canvas-api/OffscreenCanvas-getContext.html
@@ -34,5 +34,9 @@ var bCanvas = new OffscreenCanvas(20, 20); var ctx4 = bCanvas.getContext("webgl"); assert_true(ctx4 instanceof WebGLRenderingContext); + + var cCanvas = new OffscreenCanvas(20,20); + var ctx5 = cCanvas.getContext("bitmaprenderer"); + assert_true(ctx5 instanceof ImageBitmapRenderingContext); }); </script>
diff --git a/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-BitmapRenderer-TransferToWithEmptyBitmap.html b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-BitmapRenderer-TransferToWithEmptyBitmap.html new file mode 100644 index 0000000..3843fe9 --- /dev/null +++ b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-BitmapRenderer-TransferToWithEmptyBitmap.html
@@ -0,0 +1,18 @@ +<!DOCTYPE HTML> +<html> +<head> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +</head> +<body> +<script> +test(function(t) { + var canNewOffscreen = new OffscreenCanvas(60,60); + var ctxNewOffscreen = canNewOffscreen.getContext("bitmaprenderer"); + //We are not loading a bitmap to this context, so it is empty. + + assert_throws("UnknownError", function () {canNewOffscreen.transferToImageBitmap();}); +}, "Test whether transferToImageBitmap does not works with an empty bitmap"); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-DrawImage-expected.html b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-DrawImage-expected.html new file mode 100644 index 0000000..9f0f0f6d --- /dev/null +++ b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-DrawImage-expected.html
@@ -0,0 +1,28 @@ +<html> +<br> <canvas id="can1" width="60" height="60"></canvas> + +<script> + +function DrawCanvas(srcCanvas, outputCanvasId) +{ + var outputCanvas = document.getElementById(outputCanvasId); + var outputContext = outputCanvas.getContext("2d"); + outputContext.drawImage(srcCanvas, 0, 0); +} + +// source content as canvas +var htmlCanvas = document.createElement('canvas'); +htmlCanvas.width = 60; +htmlCanvas.height = 60; +var htmlCanvasCtx = htmlCanvas.getContext("2d"); +htmlCanvasCtx.fillStyle = "blue"; +htmlCanvasCtx.fillRect(0, 0, 15, 60); +htmlCanvasCtx.fillStyle = "red"; +htmlCanvasCtx.fillRect(15, 0, 45, 30); +htmlCanvasCtx.fillStyle = "green"; +htmlCanvasCtx.fillRect(15, 30, 45, 30); + +DrawCanvas(htmlCanvas, "can1"); + +</script> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-DrawImage.html b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-DrawImage.html new file mode 100644 index 0000000..387f53d --- /dev/null +++ b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-DrawImage.html
@@ -0,0 +1,39 @@ +<html> +<br> <canvas id="canvasNewOffscreenDrawImage" width="60" height="60"></canvas> + +<script> + if (window.testRunner) { + testRunner.waitUntilDone(); + } + // source content as canvas + var htmlCanvas = document.createElement('canvas'); + htmlCanvas.width = 60; + htmlCanvas.height = 60; + var htmlCanvasCtx = htmlCanvas.getContext("2d"); + htmlCanvasCtx.fillStyle = "blue"; + htmlCanvasCtx.fillRect(0, 0, 15, 60); + htmlCanvasCtx.fillStyle = "red"; + htmlCanvasCtx.fillRect(15, 0, 45, 30); + htmlCanvasCtx.fillStyle = "green"; + htmlCanvasCtx.fillRect(15, 30, 45, 30); + + createImageBitmap(htmlCanvas).then(function(bmap){ + // This offscreen canvas will be used in several tests + var canNewOffscreen = new OffscreenCanvas(60,60); + var ctxNewOffscreen = canNewOffscreen.getContext("bitmaprenderer"); + ctxNewOffscreen.transferFromImageBitmap(bmap); + + // Fill canvasNewOffscreenDrawImage + var output2dCanvas = document.getElementById("canvasNewOffscreenDrawImage"); + var output2dcontext = output2dCanvas.getContext("2d"); + output2dcontext.drawImage(canNewOffscreen, 0, 0); + + if (window.testRunner) { + requestAnimationFrame(() => { + testRunner.notifyDone(); + }); + } + }); + +</script> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-NewOffscreen-expected.html b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-NewOffscreen-expected.html new file mode 100644 index 0000000..9f0f0f6d --- /dev/null +++ b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-NewOffscreen-expected.html
@@ -0,0 +1,28 @@ +<html> +<br> <canvas id="can1" width="60" height="60"></canvas> + +<script> + +function DrawCanvas(srcCanvas, outputCanvasId) +{ + var outputCanvas = document.getElementById(outputCanvasId); + var outputContext = outputCanvas.getContext("2d"); + outputContext.drawImage(srcCanvas, 0, 0); +} + +// source content as canvas +var htmlCanvas = document.createElement('canvas'); +htmlCanvas.width = 60; +htmlCanvas.height = 60; +var htmlCanvasCtx = htmlCanvas.getContext("2d"); +htmlCanvasCtx.fillStyle = "blue"; +htmlCanvasCtx.fillRect(0, 0, 15, 60); +htmlCanvasCtx.fillStyle = "red"; +htmlCanvasCtx.fillRect(15, 0, 45, 30); +htmlCanvasCtx.fillStyle = "green"; +htmlCanvasCtx.fillRect(15, 30, 45, 30); + +DrawCanvas(htmlCanvas, "can1"); + +</script> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-NewOffscreen.html b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-NewOffscreen.html new file mode 100644 index 0000000..a46c9d9ea --- /dev/null +++ b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-NewOffscreen.html
@@ -0,0 +1,34 @@ +<html> +<br> <canvas id="canvasNewOffscreen" width="60" height="60"></canvas> + +<script> + if (window.testRunner) { + testRunner.waitUntilDone(); + } + // source content as canvas + var htmlCanvas = document.createElement('canvas'); + htmlCanvas.width = 60; + htmlCanvas.height = 60; + var htmlCanvasCtx = htmlCanvas.getContext("2d"); + htmlCanvasCtx.fillStyle = "blue"; + htmlCanvasCtx.fillRect(0, 0, 15, 60); + htmlCanvasCtx.fillStyle = "red"; + htmlCanvasCtx.fillRect(15, 0, 45, 30); + htmlCanvasCtx.fillStyle = "green"; + htmlCanvasCtx.fillRect(15, 30, 45, 30); + + createImageBitmap(htmlCanvas).then(function(bmap){ + // Fill canvasNewOffscreen + var outputCanvas = document.getElementById("canvasNewOffscreen"); + var outputCanvasRenderer = outputCanvas.getContext("bitmaprenderer"); + outputCanvasRenderer.transferFromImageBitmap(bmap); + + if (window.testRunner) { + requestAnimationFrame(() => { + testRunner.notifyDone(); + }); + } + }); + +</script> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-TransferToImageBitmapResetsToBlack-expected.html b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-TransferToImageBitmapResetsToBlack-expected.html new file mode 100644 index 0000000..b5fb912 --- /dev/null +++ b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-TransferToImageBitmapResetsToBlack-expected.html
@@ -0,0 +1,38 @@ +<html> +<br> <canvas id="can1" width="60" height="60"></canvas> +<br> <canvas id="can2" width="60" height="60"></canvas> + +<script> + +function DrawCanvas(srcCanvas, outputCanvasId) +{ + var outputCanvas = document.getElementById(outputCanvasId); + var outputContext = outputCanvas.getContext("2d"); + outputContext.drawImage(srcCanvas, 0, 0); +} + +// source content as canvas +var htmlCanvas = document.createElement('canvas'); +htmlCanvas.width = 60; +htmlCanvas.height = 60; +var htmlCanvasCtx = htmlCanvas.getContext("2d"); +htmlCanvasCtx.fillStyle = "blue"; +htmlCanvasCtx.fillRect(0, 0, 15, 60); +htmlCanvasCtx.fillStyle = "red"; +htmlCanvasCtx.fillRect(15, 0, 45, 30); +htmlCanvasCtx.fillStyle = "green"; +htmlCanvasCtx.fillRect(15, 30, 45, 30); + +DrawCanvas(htmlCanvas, "can1"); + +var htmlCanvas2 = document.createElement('canvas'); +htmlCanvas2.width = 60; +htmlCanvas2.height = 60; +var htmlCanvasCtx2 = htmlCanvas2.getContext("2d"); +htmlCanvasCtx2.fillStyle = "black"; +htmlCanvasCtx2.fillRect(0, 0, 60, 60); + +DrawCanvas(htmlCanvas2, "can2"); + +</script> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-TransferToImageBitmapResetsToBlack.html b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-TransferToImageBitmapResetsToBlack.html new file mode 100644 index 0000000..ded955c5 --- /dev/null +++ b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-TransferToImageBitmapResetsToBlack.html
@@ -0,0 +1,52 @@ +<html> +<br> <canvas id="normalColors" width="60" height="60"></canvas> +<br> <canvas id="blackColors" width="60" height="60"></canvas> + +<script> + function requestAnimationFrameNtimesThen(times, fn) { + if(times>0) { + requestAnimationFrame(() => { + requestAnimationFrameNtimesThen(times-1, fn); + }); + } else + fn(); + }; + + if (window.testRunner) { + testRunner.waitUntilDone(); + } + // source content as canvas + var htmlCanvas = document.createElement('canvas'); + htmlCanvas.width = 60; + htmlCanvas.height = 60; + var htmlCanvasCtx = htmlCanvas.getContext("2d"); + htmlCanvasCtx.fillStyle = "blue"; + htmlCanvasCtx.fillRect(0, 0, 15, 60); + htmlCanvasCtx.fillStyle = "red"; + htmlCanvasCtx.fillRect(15, 0, 45, 30); + htmlCanvasCtx.fillStyle = "green"; + htmlCanvasCtx.fillRect(15, 30, 45, 30); + + createImageBitmap(htmlCanvas).then(function(bmap){ + // This offscreen canvas will be used in several tests + var canNewOffscreen = new OffscreenCanvas(60,60); + var ctxNewOffscreen = canNewOffscreen.getContext("bitmaprenderer"); + ctxNewOffscreen.transferFromImageBitmap(bmap); + + var outputCanvas = document.getElementById("normalColors"); + var outputCanvasRenderer = outputCanvas.getContext("bitmaprenderer"); + outputCanvasRenderer.transferFromImageBitmap(canNewOffscreen.transferToImageBitmap()); + + var outputCanvas = document.getElementById("blackColors"); + var outputCanvasRenderer = outputCanvas.getContext("bitmaprenderer"); + outputCanvasRenderer.transferFromImageBitmap(canNewOffscreen.transferToImageBitmap()); + + if (window.testRunner) { + requestAnimationFrameNtimesThen(1, () => { + testRunner.notifyDone(); + }); + } + }); + +</script> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-toBlob-expected.html b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-toBlob-expected.html new file mode 100644 index 0000000..9f0f0f6d --- /dev/null +++ b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-toBlob-expected.html
@@ -0,0 +1,28 @@ +<html> +<br> <canvas id="can1" width="60" height="60"></canvas> + +<script> + +function DrawCanvas(srcCanvas, outputCanvasId) +{ + var outputCanvas = document.getElementById(outputCanvasId); + var outputContext = outputCanvas.getContext("2d"); + outputContext.drawImage(srcCanvas, 0, 0); +} + +// source content as canvas +var htmlCanvas = document.createElement('canvas'); +htmlCanvas.width = 60; +htmlCanvas.height = 60; +var htmlCanvasCtx = htmlCanvas.getContext("2d"); +htmlCanvasCtx.fillStyle = "blue"; +htmlCanvasCtx.fillRect(0, 0, 15, 60); +htmlCanvasCtx.fillStyle = "red"; +htmlCanvasCtx.fillRect(15, 0, 45, 30); +htmlCanvasCtx.fillStyle = "green"; +htmlCanvasCtx.fillRect(15, 30, 45, 30); + +DrawCanvas(htmlCanvas, "can1"); + +</script> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-toBlob-worker-expected.html b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-toBlob-worker-expected.html new file mode 100644 index 0000000..9f0f0f6d --- /dev/null +++ b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-toBlob-worker-expected.html
@@ -0,0 +1,28 @@ +<html> +<br> <canvas id="can1" width="60" height="60"></canvas> + +<script> + +function DrawCanvas(srcCanvas, outputCanvasId) +{ + var outputCanvas = document.getElementById(outputCanvasId); + var outputContext = outputCanvas.getContext("2d"); + outputContext.drawImage(srcCanvas, 0, 0); +} + +// source content as canvas +var htmlCanvas = document.createElement('canvas'); +htmlCanvas.width = 60; +htmlCanvas.height = 60; +var htmlCanvasCtx = htmlCanvas.getContext("2d"); +htmlCanvasCtx.fillStyle = "blue"; +htmlCanvasCtx.fillRect(0, 0, 15, 60); +htmlCanvasCtx.fillStyle = "red"; +htmlCanvasCtx.fillRect(15, 0, 45, 30); +htmlCanvasCtx.fillStyle = "green"; +htmlCanvasCtx.fillRect(15, 30, 45, 30); + +DrawCanvas(htmlCanvas, "can1"); + +</script> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-toBlob-worker.html b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-toBlob-worker.html new file mode 100644 index 0000000..8dacee0 --- /dev/null +++ b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-toBlob-worker.html
@@ -0,0 +1,53 @@ +<html> +<br> <img id="pngBlobWorker"/> + +<script id="worker" type="text/worker"> + self.onmessage = function(msg) { + var bmap = msg.data[0]; + + var canBlob = new OffscreenCanvas(60,60); + var ctxBlob = canBlob.getContext("bitmaprenderer"); + ctxBlob.transferFromImageBitmap(bmap); + canBlob.convertToBlob().then(function(b) { + self.postMessage(b); + }); + } +</script> + +<script> + if (window.testRunner) { + testRunner.waitUntilDone(); + } + // source content as canvas + var htmlCanvas = document.createElement('canvas'); + htmlCanvas.width = 60; + htmlCanvas.height = 60; + var htmlCanvasCtx = htmlCanvas.getContext("2d"); + htmlCanvasCtx.fillStyle = "blue"; + htmlCanvasCtx.fillRect(0, 0, 15, 60); + htmlCanvasCtx.fillStyle = "red"; + htmlCanvasCtx.fillRect(15, 0, 45, 30); + htmlCanvasCtx.fillStyle = "green"; + htmlCanvasCtx.fillRect(15, 30, 45, 30); + + // Fill canvasToBlobWorker and canvasTrasnferControlWorker + var blob = new Blob([document.getElementById("worker").textContent]); + var worker = new Worker(URL.createObjectURL(blob)); + + var pngImageWorker = document.getElementById("pngBlobWorker"); + + worker.addEventListener('message', ev => { + pngImageWorker.src = URL.createObjectURL(ev.data); + if (window.testRunner) { + requestAnimationFrame(() => { + testRunner.notifyDone(); + }); + } + }); + + createImageBitmap(htmlCanvas).then(function(bmap){ + worker.postMessage([bmap], [bmap]); + }); + +</script> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-toBlob.html b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-toBlob.html new file mode 100644 index 0000000..dbdd1d83 --- /dev/null +++ b/third_party/blink/web_tests/fast/canvas/OffscreenCanvas-Bitmaprenderer-toBlob.html
@@ -0,0 +1,42 @@ +<html> +<br> <img id="pngBlob"/> + +<script> + if (window.testRunner) { + testRunner.waitUntilDone(); + } + // source content as canvas + var htmlCanvas = document.createElement('canvas'); + htmlCanvas.width = 60; + htmlCanvas.height = 60; + var htmlCanvasCtx = htmlCanvas.getContext("2d"); + htmlCanvasCtx.fillStyle = "blue"; + htmlCanvasCtx.fillRect(0, 0, 15, 60); + htmlCanvasCtx.fillStyle = "red"; + htmlCanvasCtx.fillRect(15, 0, 45, 30); + htmlCanvasCtx.fillStyle = "green"; + htmlCanvasCtx.fillRect(15, 30, 45, 30); + + var canNewOffscreen = new OffscreenCanvas(60,60); + var ctxNewOffscreen = canNewOffscreen.getContext("bitmaprenderer"); + var canToBlobOffscreen = new OffscreenCanvas(60,60); + var ctxToBlobOffscreen = canToBlobOffscreen.getContext("bitmaprenderer"); + createImageBitmap(htmlCanvas).then(function(bmap){ + // This offscreen canvas will be used in several tests + ctxNewOffscreen.transferFromImageBitmap(bmap); + + // Fill canvasToBlob + var pngImage = document.getElementById("pngBlob"); + canNewOffscreen.convertToBlob().then(function(blob){ + pngImage.src = URL.createObjectURL(blob); + if (window.testRunner) { + requestAnimationFrame(() => { + testRunner.notifyDone(); + }); + } + }) + + }); + +</script> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/http/tests/devtools/har-importer-expected.txt b/third_party/blink/web_tests/http/tests/devtools/har-importer-expected.txt index f096c3b..6b35dc1 100644 --- a/third_party/blink/web_tests/http/tests/devtools/har-importer-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/har-importer-expected.txt
@@ -129,11 +129,7 @@ { "url": "http://localhost:8000/js_file.js", "documentURL": "http://localhost:8000/", - "initiator": { - "type": "parser", - "url": "http://localhost/", - "lineNumber": 1 - }, + "initiator": null, "requestFormData": null, "connectionId": "2945", "requestMethod": "GET",
diff --git a/third_party/blink/web_tests/http/tests/devtools/har-importer.js b/third_party/blink/web_tests/http/tests/devtools/har-importer.js index 216462a3..dd4980e 100644 --- a/third_party/blink/web_tests/http/tests/devtools/har-importer.js +++ b/third_party/blink/web_tests/http/tests/devtools/har-importer.js
@@ -199,8 +199,7 @@ '_blocked_proxy': 0.4910000000000001 }, 'serverIPAddress': '[::1]', - '_initiator': - {'type': 'parser', 'url': 'http://localhost/', 'lineNumber': 1}, + '_initiator': 'bad_initiator_string', '_priority': 'Low', 'connection': '2945', 'pageref': 'page_1'
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/fetch/fetch-oopif-expected.txt b/third_party/blink/web_tests/http/tests/inspector-protocol/fetch/fetch-oopif-expected.txt new file mode 100644 index 0000000..98a5e67 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/fetch/fetch-oopif-expected.txt
@@ -0,0 +1,13 @@ +Tests fetch interceptor respects cross-frame boundaries of out-of-process iframes. + +Loading in-process iframe (script should be present) +Request to http://127.0.0.1:8000/inspector-protocol/fetch/resources/frame-with-subresource.html, type: Document +Request to http://127.0.0.1:8000/inspector-protocol/resources/dummy.js, type: Script + +Loading out-of-process iframe (script should be absent) +Request to http://devtools.oopif-a.test:8000/inspector-protocol/fetch/resources/frame-with-subresource.html, type: Document + +Loading out-of-process iframe with interception (script should be present) +Request to http://devtools.oopif-a.test:8000/inspector-protocol/fetch/resources/frame-with-subresource.html, type: Document +[subframe] Request to http://devtools.oopif-a.test:8000/inspector-protocol/resources/dummy.js, type: Script +
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/fetch/fetch-oopif.js b/third_party/blink/web_tests/http/tests/inspector-protocol/fetch/fetch-oopif.js new file mode 100644 index 0000000..028be026 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/fetch/fetch-oopif.js
@@ -0,0 +1,41 @@ +(async function(testRunner) { + const {page, session, dp} = await testRunner.startBlank( + `Tests fetch interceptor respects cross-frame boundaries of out-of-process iframes.`); + + const FetchHelper = await testRunner.loadScript('resources/fetch-test.js'); + + const helper = new FetchHelper(testRunner, dp); + await helper.enable(); + helper.onRequest().continueRequest(); + + session.evaluate(` + function addFrame(url) { + const frame = document.createElement('iframe'); + frame.src = url; + const promise = new Promise(fulfill => frame.addEventListener('load', fulfill)); + document.body.appendChild(frame); + return promise; + } + `); + + testRunner.log('\nLoading in-process iframe (script should be present)'); + await session.evaluateAsync(`addFrame('${testRunner.url('resources/frame-with-subresource.html')}')`); + + testRunner.log('\nLoading out-of-process iframe (script should be absent)'); + await session.evaluateAsync(`addFrame('http://devtools.oopif-a.test:8000/inspector-protocol/fetch/resources/frame-with-subresource.html')`); + + testRunner.log('\nLoading out-of-process iframe with interception (script should be present)'); + await dp.Target.setAutoAttach({autoAttach: true, waitForDebuggerOnStart: true, flatten: true}); + dp.Target.onAttachedToTarget(async event => { + const dp1 = session.createChild(event.params.sessionId).protocol; + const subframeFetcher = new FetchHelper(testRunner, dp1); + subframeFetcher.setLogPrefix("[subframe] "); + await subframeFetcher.enable(); + subframeFetcher.onRequest().continueRequest({}); + dp1.Runtime.runIfWaitingForDebugger(); + }); + + await session.evaluateAsync(`addFrame('http://devtools.oopif-a.test:8000/inspector-protocol/fetch/resources/frame-with-subresource.html')`); + + testRunner.completeTest(); +})
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/fetch/resources/frame-with-subresource.html b/third_party/blink/web_tests/http/tests/inspector-protocol/fetch/resources/frame-with-subresource.html new file mode 100644 index 0000000..b0b27d50 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/fetch/resources/frame-with-subresource.html
@@ -0,0 +1,5 @@ +<html> +<body> +<script src="/inspector-protocol/resources/dummy.js"></script> +</body> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/resources/iframe.html b/third_party/blink/web_tests/http/tests/inspector-protocol/resources/iframe.html index b9a87300..cf98432 100644 --- a/third_party/blink/web_tests/http/tests/inspector-protocol/resources/iframe.html +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/resources/iframe.html
@@ -1 +1,3 @@ -<body>Hello World!</body> +<body>Hello World! +<img src="image.png"></img> +</body>
diff --git a/third_party/blink/web_tests/http/tests/security/isolatedWorld/isolated-world-location-csp-expected.txt b/third_party/blink/web_tests/http/tests/security/isolatedWorld/isolated-world-location-csp-expected.txt new file mode 100644 index 0000000..ff773e87 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/security/isolatedWorld/isolated-world-location-csp-expected.txt
@@ -0,0 +1,16 @@ +CONSOLE MESSAGE: line 50: Testing main world. Javascript url should be blocked by mainworld CSP. +CONSOLE ERROR: line 33: Refused to run the JavaScript URL because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. + +CONSOLE MESSAGE: line 17: PASS: Javascript url blocked as expected. +CONSOLE MESSAGE: line 56: Testing isolated world with no csp. Javascript url should be blocked by main world CSP. +CONSOLE ERROR: Refused to run the JavaScript URL because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. + +CONSOLE MESSAGE: PASS: Javascript url blocked as expected. +CONSOLE MESSAGE: line 63: Testing isolated world with permissive csp. +ALERT: iframe javascript: src running +CONSOLE MESSAGE: PASS: Javascript url worked as expected +CONSOLE MESSAGE: line 70: Testing isolated world with strict csp. +CONSOLE MESSAGE: line 71: internals.runtimeFlags.isolatedWorldCSPEnabled is false +ALERT: iframe javascript: src running +CONSOLE MESSAGE: PASS: Javascript url worked as expected +This tests the isolated world CSP and its implications on changing the window location to Javascript urls.
diff --git a/third_party/blink/web_tests/http/tests/security/isolatedWorld/isolated-world-location-csp.html b/third_party/blink/web_tests/http/tests/security/isolatedWorld/isolated-world-location-csp.html new file mode 100644 index 0000000..f549df3 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/security/isolatedWorld/isolated-world-location-csp.html
@@ -0,0 +1,14 @@ +<!DOCTYPE html> +<html> +<head> +<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-eval'"> +<script src="resources/isolated-world-location-csp.js"></script> +</head> +<body id="body"> + <iframe id="test-frame"></iframe> + <p> + This tests the isolated world CSP and its implications on changing the + window location to Javascript urls. + </p> +</body> +</html>
diff --git a/third_party/blink/web_tests/http/tests/security/isolatedWorld/resources/isolated-world-location-csp.js b/third_party/blink/web_tests/http/tests/security/isolatedWorld/resources/isolated-world-location-csp.js new file mode 100644 index 0000000..4e13b16 --- /dev/null +++ b/third_party/blink/web_tests/http/tests/security/isolatedWorld/resources/isolated-world-location-csp.js
@@ -0,0 +1,108 @@ +function testJavascriptUrl(expectBlocked) { + const iframe = document.getElementById('test-frame'); + + const done = function() { + iframe.removeEventListener('load', loadListener); + clearTimeout(timeout); + window.postMessage('next', '*'); + }; + + // We need to use a timeout to detect iframe load failure since onload isn't + // fired for a CSP violation on an iframe. Alternatively, we could have used + // the 'securitypolicyviolation' event, however it is not supported for + // violations in isolated worlds. + const timeout = setTimeout(function() { + // This means the iframe wasn;t loaded. + if (expectBlocked) { + console.log('PASS: Javascript url blocked as expected.'); + } else { + console.log('FAIL: Javascript url blocked unexpectedly.'); + } + done(); + }, 100); + const loadListener = function(e) { + if (expectBlocked) { + console.log('FAIL: Javascript url worked unexpectedly.'); + } else { + console.log('PASS: Javascript url worked as expected'); + } + done(); + }; + + iframe.addEventListener('load', loadListener); + iframe.contentWindow.location.href = + 'javascript:alert(\'iframe javascript: src running\') || \'alerted\''; +} + +const isolatedWorldId = 1; +const isolatedWorldSecurityOrigin = 'chrome-extensions://123'; + +function testJavascriptUrlInIsolatedWorld(expectBlocked) { + const expectBlockedStr = expectBlocked ? 'true' : 'false'; + testRunner.evaluateScriptInIsolatedWorld( + isolatedWorldId, + String(eval('testJavascriptUrl')) + + `\ntestJavascriptUrl(${expectBlockedStr});`); +} + +const tests = [ + function() { + console.log( + 'Testing main world. Javascript url should be blocked by main' + + 'world CSP.'); + testJavascriptUrl(true); + }, + function() { + console.log( + 'Testing isolated world with no csp. Javascript url should be' + + ' blocked by main world CSP.'); + testRunner.setIsolatedWorldInfo(isolatedWorldId, null, null); + testJavascriptUrlInIsolatedWorld(true); + }, + function() { + console.log('Testing isolated world with permissive csp.'); + testRunner.setIsolatedWorldInfo( + isolatedWorldId, isolatedWorldSecurityOrigin, + 'script-src \'unsafe-inline\''); + testJavascriptUrlInIsolatedWorld(false); + }, + function() { + console.log('Testing isolated world with strict csp.'); + console.log( + 'internals.runtimeFlags.isolatedWorldCSPEnabled is ' + + internals.runtimeFlags.isolatedWorldCSPEnabled); + const expectBlocked = internals.runtimeFlags.isolatedWorldCSPEnabled; + testRunner.setIsolatedWorldInfo( + isolatedWorldId, isolatedWorldSecurityOrigin, 'script-src \'none\''); + testJavascriptUrlInIsolatedWorld(expectBlocked); + + // Clear the isolated world data. + testRunner.setIsolatedWorldInfo(1, null, null); + }, +]; + +// This test is meaningless without testRunner. +function setup() { + let currentTest = 0; + window.addEventListener('message', function(e) { + if (e.data == 'next') { + // Move to the next test. + currentTest++; + if (currentTest == tests.length) { + testRunner.notifyDone(); + return; + } + + // Move to the next sub-test. + tests[currentTest](); + } + }, false); + + tests[0](); +} + +if (window.testRunner) { + testRunner.dumpAsText(); + testRunner.waitUntilDone(); + window.addEventListener('load', setup); +}
diff --git a/third_party/blink/web_tests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt b/third_party/blink/web_tests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt index b35fe5c..d5f60da93 100644 --- a/third_party/blink/web_tests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt +++ b/third_party/blink/web_tests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt
@@ -702,6 +702,11 @@ getter width method close method constructor +interface ImageBitmapRenderingContext + attribute @@toStringTag + getter canvas + method constructor + method transferFromImageBitmap interface ImageData attribute @@toStringTag getter data
diff --git a/third_party/blink/web_tests/platform/mac/css3/filters/backdrop-filter-boundary-expected.png b/third_party/blink/web_tests/platform/mac/css3/filters/backdrop-filter-boundary-expected.png new file mode 100644 index 0000000..0bb8a47f --- /dev/null +++ b/third_party/blink/web_tests/platform/mac/css3/filters/backdrop-filter-boundary-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/gpu-threaded-compositing/fast/canvas/gpu-threaded-compositing/README.txt b/third_party/blink/web_tests/virtual/gpu-threaded-compositing/fast/canvas/gpu-threaded-compositing/README.txt new file mode 100644 index 0000000..f7f4518 --- /dev/null +++ b/third_party/blink/web_tests/virtual/gpu-threaded-compositing/fast/canvas/gpu-threaded-compositing/README.txt
@@ -0,0 +1 @@ +Tests that ensure that "--enable-accelerated-2d-canvas", "--enable-threaded-compositing" are enabled. \ No newline at end of file
diff --git a/third_party/blink/web_tests/virtual/isolated_world_csp/http/tests/security/isolatedWorld/isolated-world-location-csp-expected.txt b/third_party/blink/web_tests/virtual/isolated_world_csp/http/tests/security/isolatedWorld/isolated-world-location-csp-expected.txt new file mode 100644 index 0000000..cdf2ceb7 --- /dev/null +++ b/third_party/blink/web_tests/virtual/isolated_world_csp/http/tests/security/isolatedWorld/isolated-world-location-csp-expected.txt
@@ -0,0 +1,17 @@ +CONSOLE MESSAGE: line 50: Testing main world. Javascript url should be blocked by mainworld CSP. +CONSOLE ERROR: line 33: Refused to run the JavaScript URL because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. + +CONSOLE MESSAGE: line 17: PASS: Javascript url blocked as expected. +CONSOLE MESSAGE: line 56: Testing isolated world with no csp. Javascript url should be blocked by main world CSP. +CONSOLE ERROR: Refused to run the JavaScript URL because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. + +CONSOLE MESSAGE: PASS: Javascript url blocked as expected. +CONSOLE MESSAGE: line 63: Testing isolated world with permissive csp. +ALERT: iframe javascript: src running +CONSOLE MESSAGE: PASS: Javascript url worked as expected +CONSOLE MESSAGE: line 70: Testing isolated world with strict csp. +CONSOLE MESSAGE: line 71: internals.runtimeFlags.isolatedWorldCSPEnabled is true +CONSOLE ERROR: Refused to run the JavaScript URL because it violates the following Content Security Policy directive: "script-src 'none'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. + +CONSOLE MESSAGE: PASS: Javascript url blocked as expected. +This tests the isolated world CSP and its implications on changing the window location to Javascript urls.
diff --git a/third_party/blink/web_tests/virtual/stable/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt b/third_party/blink/web_tests/virtual/stable/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt index 8f5d74cc..f111ad4 100644 --- a/third_party/blink/web_tests/virtual/stable/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt +++ b/third_party/blink/web_tests/virtual/stable/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt
@@ -662,6 +662,11 @@ getter width method close method constructor +interface ImageBitmapRenderingContext + attribute @@toStringTag + getter canvas + method constructor + method transferFromImageBitmap interface ImageData attribute @@toStringTag getter data
diff --git a/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-dedicated-worker-expected.txt b/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-dedicated-worker-expected.txt index 5ae2e61..60a2a4d 100644 --- a/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-dedicated-worker-expected.txt +++ b/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-dedicated-worker-expected.txt
@@ -623,6 +623,11 @@ [Worker] getter width [Worker] method close [Worker] method constructor +[Worker] interface ImageBitmapRenderingContext +[Worker] attribute @@toStringTag +[Worker] getter canvas +[Worker] method constructor +[Worker] method transferFromImageBitmap [Worker] interface ImageData [Worker] attribute @@toStringTag [Worker] getter data
diff --git a/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt index b5db119..c0b271c 100644 --- a/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-expected.txt
@@ -845,12 +845,19 @@ interface Clipboard : EventTarget attribute @@toStringTag method constructor + method read method readText + method write method writeText interface ClipboardEvent : Event attribute @@toStringTag getter clipboardData method constructor +interface ClipboardItem + attribute @@toStringTag + getter types + method constructor + method getType interface CloseEvent : Event attribute @@toStringTag getter code
diff --git a/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-shared-worker-expected.txt b/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-shared-worker-expected.txt index 0520ac10..7137cb3 100644 --- a/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-shared-worker-expected.txt +++ b/third_party/blink/web_tests/virtual/stable/webexposed/global-interface-listing-shared-worker-expected.txt
@@ -618,6 +618,11 @@ [Worker] getter width [Worker] method close [Worker] method constructor +[Worker] interface ImageBitmapRenderingContext +[Worker] attribute @@toStringTag +[Worker] getter canvas +[Worker] method constructor +[Worker] method transferFromImageBitmap [Worker] interface ImageData [Worker] attribute @@toStringTag [Worker] getter data
diff --git a/third_party/blink/web_tests/webexposed/element-instance-property-listing-expected.txt b/third_party/blink/web_tests/webexposed/element-instance-property-listing-expected.txt index 493ccf6a..a9f9d79 100644 --- a/third_party/blink/web_tests/webexposed/element-instance-property-listing-expected.txt +++ b/third_party/blink/web_tests/webexposed/element-instance-property-listing-expected.txt
@@ -884,6 +884,7 @@ property onmessage property onmessageerror property postMessage + property referrerPolicy property src html element pre property width
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-dedicated-worker-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-dedicated-worker-expected.txt index 550775a..d9eae374 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-dedicated-worker-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-dedicated-worker-expected.txt
@@ -662,6 +662,11 @@ [Worker] getter width [Worker] method close [Worker] method constructor +[Worker] interface ImageBitmapRenderingContext +[Worker] attribute @@toStringTag +[Worker] getter canvas +[Worker] method constructor +[Worker] method transferFromImageBitmap [Worker] interface ImageData [Worker] attribute @@toStringTag [Worker] getter data
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt index 056af0c6..17f556f 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt
@@ -3634,12 +3634,14 @@ attribute @@toStringTag getter onmessage getter onmessageerror + getter referrerPolicy getter src method activate method constructor method postMessage setter onmessage setter onmessageerror + setter referrerPolicy setter src interface HTMLPreElement : HTMLElement attribute @@toStringTag
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-shared-worker-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-shared-worker-expected.txt index 43d13e5..83b2f13 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-shared-worker-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-shared-worker-expected.txt
@@ -644,6 +644,11 @@ [Worker] getter width [Worker] method close [Worker] method constructor +[Worker] interface ImageBitmapRenderingContext +[Worker] attribute @@toStringTag +[Worker] getter canvas +[Worker] method constructor +[Worker] method transferFromImageBitmap [Worker] interface ImageData [Worker] attribute @@toStringTag [Worker] getter data
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 28744ad..7eb1e62c 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -90172,8 +90172,7 @@ </summary> </histogram> -<histogram base="true" - name="PasswordManager.BubbleSuppression.AccountsInStatisticsTable" +<histogram name="PasswordManager.BubbleSuppression.AccountsInStatisticsTable" units="accounts" expires_after="M78"> <owner>battre@chromium.org</owner> <owner>vasilii@chromium.org</owner> @@ -90185,7 +90184,7 @@ </summary> </histogram> -<histogram base="true" +<histogram name="PasswordManager.BubbleSuppression.AccountsWithSuppressedBubble" units="accounts" expires_after="M86"> <owner>battre@chromium.org</owner> @@ -90198,8 +90197,7 @@ </summary> </histogram> -<histogram base="true" - name="PasswordManager.BubbleSuppression.DomainsWithSuppressedBubble" +<histogram name="PasswordManager.BubbleSuppression.DomainsWithSuppressedBubble" units="accounts" expires_after="M86"> <owner>battre@chromium.org</owner> <owner>vasilii@chromium.org</owner>
diff --git a/ui/accelerated_widget_mac/BUILD.gn b/ui/accelerated_widget_mac/BUILD.gn index 5d4f127..e7526c6 100644 --- a/ui/accelerated_widget_mac/BUILD.gn +++ b/ui/accelerated_widget_mac/BUILD.gn
@@ -20,8 +20,6 @@ "ca_transaction_observer.mm", "display_ca_layer_tree.h", "display_ca_layer_tree.mm", - "display_link_mac.cc", - "display_link_mac.h", "io_surface_context.h", "io_surface_context.mm", "window_resize_helper_mac.cc",
diff --git a/ui/display/BUILD.gn b/ui/display/BUILD.gn index 19320f0..f5ae23c 100644 --- a/ui/display/BUILD.gn +++ b/ui/display/BUILD.gn
@@ -29,6 +29,8 @@ "display_switches.cc", "display_switches.h", "ios/screen_ios.mm", + "mac/display_link_mac.cc", + "mac/display_link_mac.h", "mac/screen_mac.mm", "screen.cc", "screen.h", @@ -54,8 +56,6 @@ "win/uwp_text_scale_factor.h", ] - configs += [ "//build/config/compiler:wexit_time_destructors" ] - defines = [ "DISPLAY_IMPLEMENTATION" ] public_deps = [ @@ -85,6 +85,7 @@ libs = [ "AppKit.framework", "CoreGraphics.framework", + "QuartzCore.framework", ] } }
diff --git a/ui/accelerated_widget_mac/display_link_mac.cc b/ui/display/mac/display_link_mac.cc similarity index 85% rename from ui/accelerated_widget_mac/display_link_mac.cc rename to ui/display/mac/display_link_mac.cc index 8e48f00..29d6b303 100644 --- a/ui/accelerated_widget_mac/display_link_mac.cc +++ b/ui/display/mac/display_link_mac.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ui/accelerated_widget_mac/display_link_mac.h" +#include "ui/display/mac/display_link_mac.h" #include <stdint.h> @@ -17,15 +17,13 @@ namespace base { -template<> +template <> struct ScopedTypeRefTraits<CVDisplayLinkRef> { static CVDisplayLinkRef InvalidValue() { return nullptr; } static CVDisplayLinkRef Retain(CVDisplayLinkRef object) { return CVDisplayLinkRetain(object); } - static void Release(CVDisplayLinkRef object) { - CVDisplayLinkRelease(object); - } + static void Release(CVDisplayLinkRef object) { CVDisplayLinkRelease(object); } }; } // namespace base @@ -40,6 +38,10 @@ // is initialized with the very first DisplayLinkMac instance, and is never // changed (even, e.g, in tests that re-initialize the main thread task runner). // https://885329 +// TODO(ccameron): crbug.com/969157 - Save this ask_runner to DisaplayLinkMac. +// configs += [ "//build/config/compiler:wexit_time_destructors" ] in +// ui/display/BUILD.gn has to be removed because GetMainThreadTaskRunner() +// causes a compiler error. scoped_refptr<base::SingleThreadTaskRunner> GetMainThreadTaskRunner() { static scoped_refptr<base::SingleThreadTaskRunner> task_runner = base::ThreadTaskRunnerHandle::Get(); @@ -80,9 +82,8 @@ CVReturn ret = kCVReturnSuccess; base::ScopedTypeRef<CVDisplayLinkRef> display_link; - ret = CVDisplayLinkCreateWithCGDisplay( - display_id, - display_link.InitializeInto()); + ret = CVDisplayLinkCreateWithCGDisplay(display_id, + display_link.InitializeInto()); if (ret != kCVReturnSuccess) { LOG(ERROR) << "CVDisplayLinkCreateWithActiveCGDisplays failed: " << ret; return nullptr; @@ -111,8 +112,7 @@ CGError register_error = CGDisplayRegisterReconfigurationCallback( DisplayReconfigurationCallBack, nullptr); DPLOG_IF(ERROR, register_error != kCGErrorSuccess) - << "CGDisplayRegisterReconfigurationCallback: " - << register_error; + << "CGDisplayRegisterReconfigurationCallback: " << register_error; } all_display_links.insert(std::make_pair(display_id_, this)); } @@ -129,13 +129,12 @@ CGError remove_error = CGDisplayRemoveReconfigurationCallback( DisplayReconfigurationCallBack, nullptr); DPLOG_IF(ERROR, remove_error != kCGErrorSuccess) - << "CGDisplayRemoveReconfigurationCallback: " - << remove_error; + << "CGDisplayRemoveReconfigurationCallback: " << remove_error; } } -bool DisplayLinkMac::GetVSyncParameters( - base::TimeTicks* timebase, base::TimeDelta* interval) { +bool DisplayLinkMac::GetVSyncParameters(base::TimeTicks* timebase, + base::TimeDelta* interval) { if (!timebase_and_interval_valid_) { StartOrContinueDisplayLink(); return false; @@ -200,8 +199,7 @@ timebase_and_interval_valid_ = true; // Don't restart the display link for 10 seconds. - recalculate_time_ = base::TimeTicks::Now() + - base::TimeDelta::FromSeconds(10); + recalculate_time_ = base::TimeTicks::Now() + base::TimeDelta::FromSeconds(10); StopDisplayLink(); } @@ -224,13 +222,12 @@ } // static -CVReturn DisplayLinkMac::DisplayLinkCallback( - CVDisplayLinkRef display_link, - const CVTimeStamp* now, - const CVTimeStamp* output_time, - CVOptionFlags flags_in, - CVOptionFlags* flags_out, - void* context) { +CVReturn DisplayLinkMac::DisplayLinkCallback(CVDisplayLinkRef display_link, + const CVTimeStamp* now, + const CVTimeStamp* output_time, + CVOptionFlags flags_in, + CVOptionFlags* flags_out, + void* context) { TRACE_EVENT0("ui", "DisplayLinkMac::DisplayLinkCallback"); CGDirectDisplayID display = static_cast<CGDirectDisplayID>(reinterpret_cast<uintptr_t>(context)); @@ -254,4 +251,4 @@ display_link_mac->timebase_and_interval_valid_ = false; } -} // ui +} // namespace ui
diff --git a/ui/accelerated_widget_mac/display_link_mac.h b/ui/display/mac/display_link_mac.h similarity index 64% rename from ui/accelerated_widget_mac/display_link_mac.h rename to ui/display/mac/display_link_mac.h index b552163..c7e23ba 100644 --- a/ui/accelerated_widget_mac/display_link_mac.h +++ b/ui/display/mac/display_link_mac.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_ACCELERATED_WIDGET_MAC_DISPLAY_LINK_MAC_H_ -#define UI_ACCELERATED_WIDGET_MAC_DISPLAY_LINK_MAC_H_ +#ifndef UI_DISPLAY_MAC_DISPLAY_LINK_MAC_H_ +#define UI_DISPLAY_MAC_DISPLAY_LINK_MAC_H_ #include <QuartzCore/CVDisplayLink.h> @@ -12,11 +12,11 @@ #include "base/mac/scoped_typeref.h" #include "base/memory/ref_counted.h" #include "base/time/time.h" -#include "ui/accelerated_widget_mac/accelerated_widget_mac_export.h" +#include "ui/display/display_export.h" namespace ui { -class ACCELERATED_WIDGET_MAC_EXPORT DisplayLinkMac +class DISPLAY_EXPORT DisplayLinkMac : public base::RefCountedThreadSafe<DisplayLinkMac> { public: // This must only be called from the main thread. @@ -25,16 +25,13 @@ // Get vsync scheduling parameters. Returns false if the populated parameters // are invalid. - bool GetVSyncParameters( - base::TimeTicks* timebase, - base::TimeDelta* interval); + bool GetVSyncParameters(base::TimeTicks* timebase, base::TimeDelta* interval); private: friend class base::RefCountedThreadSafe<DisplayLinkMac>; - DisplayLinkMac( - CGDirectDisplayID display_id, - base::ScopedTypeRef<CVDisplayLinkRef> display_link); + DisplayLinkMac(CGDirectDisplayID display_id, + base::ScopedTypeRef<CVDisplayLinkRef> display_link); virtual ~DisplayLinkMac(); void StartOrContinueDisplayLink(); @@ -50,20 +47,18 @@ // Called by the system on the display link thread, and posts a call to // DoUpdateVSyncParameters() to the UI thread. - static CVReturn DisplayLinkCallback( - CVDisplayLinkRef display_link, - const CVTimeStamp* now, - const CVTimeStamp* output_time, - CVOptionFlags flags_in, - CVOptionFlags* flags_out, - void* context); + static CVReturn DisplayLinkCallback(CVDisplayLinkRef display_link, + const CVTimeStamp* now, + const CVTimeStamp* output_time, + CVOptionFlags flags_in, + CVOptionFlags* flags_out, + void* context); // This is called whenever the display is reconfigured, and marks that the // vsync parameters must be recalculated. - static void DisplayReconfigurationCallBack( - CGDirectDisplayID display, - CGDisplayChangeSummaryFlags flags, - void* user_info); + static void DisplayReconfigurationCallBack(CGDirectDisplayID display, + CGDisplayChangeSummaryFlags flags, + void* user_info); // The display that this display link is attached to. CGDirectDisplayID display_id_; @@ -81,6 +76,6 @@ base::TimeTicks recalculate_time_; }; -} // ui +} // namespace ui -#endif // UI_ACCELERATED_WIDGET_MAC_DISPLAY_LINK_MAC_H_ +#endif // UI_DISPLAY_MAC_DISPLAY_LINK_MAC_H_
diff --git a/ui/ozone/BUILD.gn b/ui/ozone/BUILD.gn index ce321ea..24d7a0c 100644 --- a/ui/ozone/BUILD.gn +++ b/ui/ozone/BUILD.gn
@@ -292,6 +292,10 @@ # Platform tests link ozone statically. Make sure we're not getting a # 2nd copy of any code via the component. assert_no_deps = [ "//ui/ozone" ] + + data_deps = [ + "//testing/buildbot/filters:ozone_unittests_filters", + ] } # X11 backend has its own test suite only built when we are using the x11
diff --git a/ui/ozone/common/linux/gbm_wrapper.cc b/ui/ozone/common/linux/gbm_wrapper.cc index eba8647..dc4bc04 100644 --- a/ui/ozone/common/linux/gbm_wrapper.cc +++ b/ui/ozone/common/linux/gbm_wrapper.cc
@@ -175,16 +175,16 @@ buffer->mmap_data_ = nullptr; } - gbm_bo* bo_ = nullptr; + gbm_bo* const bo_; void* mmap_data_ = nullptr; - uint32_t format_ = 0; - uint64_t format_modifier_ = 0; - uint32_t flags_ = 0; + const uint32_t format_; + const uint64_t format_modifier_; + const uint32_t flags_; - gfx::Size size_; + const gfx::Size size_; - gfx::NativePixmapHandle handle_; + const gfx::NativePixmapHandle handle_; DISALLOW_COPY_AND_ASSIGN(Buffer); }; @@ -304,7 +304,7 @@ } private: - gbm_device* device_; + gbm_device* const device_; DISALLOW_COPY_AND_ASSIGN(Device); };
diff --git a/ui/ozone/platform/wayland/host/wayland_keyboard.cc b/ui/ozone/platform/wayland/host/wayland_keyboard.cc index 181e6e56..c082b30 100644 --- a/ui/ozone/platform/wayland/host/wayland_keyboard.cc +++ b/ui/ozone/platform/wayland/host/wayland_keyboard.cc
@@ -4,10 +4,11 @@ #include "ui/ozone/platform/wayland/host/wayland_keyboard.h" -#include <sys/mman.h> #include <utility> #include "base/files/scoped_file.h" +#include "base/memory/unsafe_shared_memory_region.h" +#include "base/unguessable_token.h" #include "ui/base/buildflags.h" #include "ui/events/base_event_utils.h" #include "ui/events/event.h" @@ -58,25 +59,26 @@ void WaylandKeyboard::Keymap(void* data, wl_keyboard* obj, uint32_t format, - int32_t raw_fd, + int32_t keymap_fd, uint32_t size) { WaylandKeyboard* keyboard = static_cast<WaylandKeyboard*>(data); DCHECK(keyboard); - base::ScopedFD fd(raw_fd); - if (!data || format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) + base::ScopedFD fd(keymap_fd); + auto length = size - 1; + auto shmen = base::subtle::PlatformSharedMemoryRegion::Take( + std::move(fd), base::subtle::PlatformSharedMemoryRegion::Mode::kUnsafe, + length, base::UnguessableToken::Create()); + auto mapped_memory = + base::UnsafeSharedMemoryRegion::Deserialize(std::move(shmen)).Map(); + const char* keymap = mapped_memory.GetMemoryAs<char>(); + + if (!keymap || format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) return; - char* keymap_str = reinterpret_cast<char*>( - mmap(nullptr, size, PROT_READ, MAP_SHARED, fd.get(), 0)); - if (keymap_str == MAP_FAILED) - return; - - auto length = strnlen(keymap_str, size); - bool success = - keyboard->layout_engine_->SetCurrentLayoutFromBuffer(keymap_str, length); + bool success = keyboard->layout_engine_->SetCurrentLayoutFromBuffer( + keymap, mapped_memory.size()); DCHECK(success) << "Failed to set the XKB keyboard mapping."; - munmap(keymap_str, size); } void WaylandKeyboard::Enter(void* data,
diff --git a/ui/views/cocoa/bridged_native_widget_host_impl.h b/ui/views/cocoa/bridged_native_widget_host_impl.h index fe933cd..784b7a0 100644 --- a/ui/views/cocoa/bridged_native_widget_host_impl.h +++ b/ui/views/cocoa/bridged_native_widget_host_impl.h
@@ -17,10 +17,10 @@ #include "components/remote_cocoa/common/bridged_native_widget_host.mojom.h" #include "mojo/public/cpp/bindings/associated_binding.h" #include "ui/accelerated_widget_mac/accelerated_widget_mac.h" -#include "ui/accelerated_widget_mac/display_link_mac.h" #include "ui/base/cocoa/accessibility_focus_overrider.h" #include "ui/base/ime/input_method_delegate.h" #include "ui/compositor/layer_owner.h" +#include "ui/display/mac/display_link_mac.h" #include "ui/views/cocoa/drag_drop_client_mac.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/views_export.h"
diff --git a/ui/views/resources/default_100_percent/common/checkbox.png b/ui/views/resources/default_100_percent/common/checkbox.png deleted file mode 100644 index b61b33b6..0000000 --- a/ui/views/resources/default_100_percent/common/checkbox.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_100_percent/common/checkbox_checked.png b/ui/views/resources/default_100_percent/common/checkbox_checked.png deleted file mode 100644 index 332e980..0000000 --- a/ui/views/resources/default_100_percent/common/checkbox_checked.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_100_percent/common/checkbox_checked_hover.png b/ui/views/resources/default_100_percent/common/checkbox_checked_hover.png deleted file mode 100644 index eac00a2d0..0000000 --- a/ui/views/resources/default_100_percent/common/checkbox_checked_hover.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_100_percent/common/checkbox_checked_inactive.png b/ui/views/resources/default_100_percent/common/checkbox_checked_inactive.png deleted file mode 100644 index 1512c30..0000000 --- a/ui/views/resources/default_100_percent/common/checkbox_checked_inactive.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_100_percent/common/checkbox_checked_pressed.png b/ui/views/resources/default_100_percent/common/checkbox_checked_pressed.png deleted file mode 100644 index 36338ba..0000000 --- a/ui/views/resources/default_100_percent/common/checkbox_checked_pressed.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_100_percent/common/checkbox_focused.png b/ui/views/resources/default_100_percent/common/checkbox_focused.png deleted file mode 100644 index 90d8759..0000000 --- a/ui/views/resources/default_100_percent/common/checkbox_focused.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_100_percent/common/checkbox_focused_checked.png b/ui/views/resources/default_100_percent/common/checkbox_focused_checked.png deleted file mode 100644 index 0ba79b5..0000000 --- a/ui/views/resources/default_100_percent/common/checkbox_focused_checked.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_100_percent/common/checkbox_focused_checked_hover.png b/ui/views/resources/default_100_percent/common/checkbox_focused_checked_hover.png deleted file mode 100644 index 97d13b7c..0000000 --- a/ui/views/resources/default_100_percent/common/checkbox_focused_checked_hover.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_100_percent/common/checkbox_focused_checked_pressed.png b/ui/views/resources/default_100_percent/common/checkbox_focused_checked_pressed.png deleted file mode 100644 index a1e335c..0000000 --- a/ui/views/resources/default_100_percent/common/checkbox_focused_checked_pressed.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_100_percent/common/checkbox_focused_hover.png b/ui/views/resources/default_100_percent/common/checkbox_focused_hover.png deleted file mode 100644 index dc935b18..0000000 --- a/ui/views/resources/default_100_percent/common/checkbox_focused_hover.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_100_percent/common/checkbox_focused_pressed.png b/ui/views/resources/default_100_percent/common/checkbox_focused_pressed.png deleted file mode 100644 index 83cd62f..0000000 --- a/ui/views/resources/default_100_percent/common/checkbox_focused_pressed.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_100_percent/common/checkbox_hover.png b/ui/views/resources/default_100_percent/common/checkbox_hover.png deleted file mode 100644 index 9a5db848..0000000 --- a/ui/views/resources/default_100_percent/common/checkbox_hover.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_100_percent/common/checkbox_inactive.png b/ui/views/resources/default_100_percent/common/checkbox_inactive.png deleted file mode 100644 index 4d964ee5..0000000 --- a/ui/views/resources/default_100_percent/common/checkbox_inactive.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_100_percent/common/checkbox_pressed.png b/ui/views/resources/default_100_percent/common/checkbox_pressed.png deleted file mode 100644 index 3a1cba3..0000000 --- a/ui/views/resources/default_100_percent/common/checkbox_pressed.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_200_percent/common/checkbox.png b/ui/views/resources/default_200_percent/common/checkbox.png deleted file mode 100644 index 2192a7f..0000000 --- a/ui/views/resources/default_200_percent/common/checkbox.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_200_percent/common/checkbox_checked.png b/ui/views/resources/default_200_percent/common/checkbox_checked.png deleted file mode 100644 index 1d66001..0000000 --- a/ui/views/resources/default_200_percent/common/checkbox_checked.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_200_percent/common/checkbox_checked_hover.png b/ui/views/resources/default_200_percent/common/checkbox_checked_hover.png deleted file mode 100644 index c88df15..0000000 --- a/ui/views/resources/default_200_percent/common/checkbox_checked_hover.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_200_percent/common/checkbox_checked_inactive.png b/ui/views/resources/default_200_percent/common/checkbox_checked_inactive.png deleted file mode 100644 index 85c314f..0000000 --- a/ui/views/resources/default_200_percent/common/checkbox_checked_inactive.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_200_percent/common/checkbox_checked_pressed.png b/ui/views/resources/default_200_percent/common/checkbox_checked_pressed.png deleted file mode 100644 index 00a7bf4c..0000000 --- a/ui/views/resources/default_200_percent/common/checkbox_checked_pressed.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_200_percent/common/checkbox_focused.png b/ui/views/resources/default_200_percent/common/checkbox_focused.png deleted file mode 100644 index c4d04aa..0000000 --- a/ui/views/resources/default_200_percent/common/checkbox_focused.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_200_percent/common/checkbox_focused_checked.png b/ui/views/resources/default_200_percent/common/checkbox_focused_checked.png deleted file mode 100644 index 91152f2..0000000 --- a/ui/views/resources/default_200_percent/common/checkbox_focused_checked.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_200_percent/common/checkbox_focused_checked_hover.png b/ui/views/resources/default_200_percent/common/checkbox_focused_checked_hover.png deleted file mode 100644 index 0b51305..0000000 --- a/ui/views/resources/default_200_percent/common/checkbox_focused_checked_hover.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_200_percent/common/checkbox_focused_checked_pressed.png b/ui/views/resources/default_200_percent/common/checkbox_focused_checked_pressed.png deleted file mode 100644 index 2a52900..0000000 --- a/ui/views/resources/default_200_percent/common/checkbox_focused_checked_pressed.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_200_percent/common/checkbox_focused_hover.png b/ui/views/resources/default_200_percent/common/checkbox_focused_hover.png deleted file mode 100644 index 91ec9f8..0000000 --- a/ui/views/resources/default_200_percent/common/checkbox_focused_hover.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_200_percent/common/checkbox_focused_pressed.png b/ui/views/resources/default_200_percent/common/checkbox_focused_pressed.png deleted file mode 100644 index f22c98e9..0000000 --- a/ui/views/resources/default_200_percent/common/checkbox_focused_pressed.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_200_percent/common/checkbox_hover.png b/ui/views/resources/default_200_percent/common/checkbox_hover.png deleted file mode 100644 index 610d864a..0000000 --- a/ui/views/resources/default_200_percent/common/checkbox_hover.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_200_percent/common/checkbox_inactive.png b/ui/views/resources/default_200_percent/common/checkbox_inactive.png deleted file mode 100644 index 4b6933c..0000000 --- a/ui/views/resources/default_200_percent/common/checkbox_inactive.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/default_200_percent/common/checkbox_pressed.png b/ui/views/resources/default_200_percent/common/checkbox_pressed.png deleted file mode 100644 index 0e23c5a7..0000000 --- a/ui/views/resources/default_200_percent/common/checkbox_pressed.png +++ /dev/null Binary files differ
diff --git a/ui/views/resources/views_resources.grd b/ui/views/resources/views_resources.grd index dbd023de..3fbd5da7 100644 --- a/ui/views/resources/views_resources.grd +++ b/ui/views/resources/views_resources.grd
@@ -22,20 +22,6 @@ <structure type="chrome_scaled_image" name="IDR_BUTTON_HOVER" file="common/button_hover.png" /> <structure type="chrome_scaled_image" name="IDR_BUTTON_NORMAL" file="common/button.png" /> <structure type="chrome_scaled_image" name="IDR_BUTTON_PRESSED" file="common/button_pressed.png" /> - <structure type="chrome_scaled_image" name="IDR_CHECKBOX" file="common/checkbox.png" /> - <structure type="chrome_scaled_image" name="IDR_CHECKBOX_CHECKED" file="common/checkbox_checked.png" /> - <structure type="chrome_scaled_image" name="IDR_CHECKBOX_CHECKED_DISABLED" file="common/checkbox_checked_inactive.png" /> - <structure type="chrome_scaled_image" name="IDR_CHECKBOX_CHECKED_HOVER" file="common/checkbox_checked_hover.png" /> - <structure type="chrome_scaled_image" name="IDR_CHECKBOX_CHECKED_PRESSED" file="common/checkbox_checked_pressed.png" /> - <structure type="chrome_scaled_image" name="IDR_CHECKBOX_DISABLED" file="common/checkbox_inactive.png" /> - <structure type="chrome_scaled_image" name="IDR_CHECKBOX_FOCUSED" file="common/checkbox_focused.png" /> - <structure type="chrome_scaled_image" name="IDR_CHECKBOX_FOCUSED_CHECKED" file="common/checkbox_focused_checked.png" /> - <structure type="chrome_scaled_image" name="IDR_CHECKBOX_FOCUSED_CHECKED_HOVER" file="common/checkbox_focused_checked_hover.png" /> - <structure type="chrome_scaled_image" name="IDR_CHECKBOX_FOCUSED_CHECKED_PRESSED" file="common/checkbox_focused_checked_pressed.png" /> - <structure type="chrome_scaled_image" name="IDR_CHECKBOX_FOCUSED_HOVER" file="common/checkbox_focused_hover.png" /> - <structure type="chrome_scaled_image" name="IDR_CHECKBOX_FOCUSED_PRESSED" file="common/checkbox_focused_pressed.png" /> - <structure type="chrome_scaled_image" name="IDR_CHECKBOX_HOVER" file="common/checkbox_hover.png" /> - <structure type="chrome_scaled_image" name="IDR_CHECKBOX_PRESSED" file="common/checkbox_pressed.png" /> <structure type="chrome_scaled_image" name="IDR_CLOSE" file="close.png" /> <structure type="chrome_scaled_image" name="IDR_CLOSE_H" file="close_hover.png" /> <structure type="chrome_scaled_image" name="IDR_CLOSE_P" file="close_pressed.png" />
diff --git a/ui/webui/resources/cr_elements/BUILD.gn b/ui/webui/resources/cr_elements/BUILD.gn index f15e02ec..af9dbbf 100644 --- a/ui/webui/resources/cr_elements/BUILD.gn +++ b/ui/webui/resources/cr_elements/BUILD.gn
@@ -10,6 +10,7 @@ "chromeos/cr_picture:closure_compile", "chromeos/network:closure_compile", "cr_action_menu:closure_compile", + "cr_button:closure_compile", "cr_checkbox:closure_compile", "cr_dialog:closure_compile", "cr_drawer:closure_compile",
diff --git a/ui/webui/resources/cr_elements/cr_button/BUILD.gn b/ui/webui/resources/cr_elements/cr_button/BUILD.gn new file mode 100644 index 0000000..b625d826 --- /dev/null +++ b/ui/webui/resources/cr_elements/cr_button/BUILD.gn
@@ -0,0 +1,18 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//third_party/closure_compiler/compile_js.gni") + +js_type_check("closure_compile") { + deps = [ + ":cr_button", + ] +} + +js_library("cr_button") { + deps = [ + "//third_party/polymer/v1_0/components-chromium/paper-behaviors:paper-ripple-behavior-extracted", + "//ui/webui/resources/js/cr/ui:focus_outline_manager", + ] +}
diff --git a/ui/webui/resources/cr_elements/cr_button/cr_button.html b/ui/webui/resources/cr_elements/cr_button/cr_button.html new file mode 100644 index 0000000..ee4fa7b --- /dev/null +++ b/ui/webui/resources/cr_elements/cr_button/cr_button.html
@@ -0,0 +1,149 @@ +<link rel="import" href="../../html/polymer.html"> + +<link rel="import" href="chrome://resources/html/cr/ui/focus_outline_manager.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/paper-behaviors/paper-ripple-behavior.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html"> +<link rel="import" href="../hidden_style_css.html"> +<link rel="import" href="../shared_vars_css.html"> + +<dom-module id="cr-button"> + <template> + <style include="cr-hidden-style"> + :host { + --active-shadow-rgb: var(--google-grey-800-rgb); + --active-shadow-action-rgb: var(--google-blue-500-rgb); + --bg-action: var(--google-blue-600); + --border-color: var(--google-grey-refresh-300); + --disabled-bg-action: var(--google-grey-refresh-100); + --disabled-bg: white; + --disabled-border-color: var(--google-grey-refresh-100); + --focus-shadow-color: rgba(var(--google-blue-600-rgb), .4); + --hover-bg-action: rgba(var(--google-blue-600-rgb), .9); + --hover-bg-color: rgba(var(--google-blue-500-rgb), .04); + --ink-color-action: white; + /* Blue-ish color used either as a background or as a text color, + * depending on the type of button. */ + --ink-color: var(--google-blue-600); + --ripple-opacity-action: .32; + --ripple-opacity: .1; + --text-color-action: white; + --text-color: var(--google-blue-600); + } + + :host-context([dark]) { + /* Only in dark. */ + --active-bg: black linear-gradient(rgba(255, 255, 255, .06), + rgba(255, 255, 255, .06)); + --active-shadow-rgb: 0, 0, 0; + --active-shadow-action-rgb: var(--google-blue-refresh-500-rgb); + --bg-action: var(--google-blue-refresh-300); + --border-color: var(--google-grey-refresh-700); + --disabled-bg-action: var(--google-grey-800); + /* TODO(dbeam): get --disabled-bg from Namrata. */ + --disabled-bg: transparent; + --disabled-border-color: var(--google-grey-800); + --focus-shadow-color: rgba(var(--google-blue-refresh-300-rgb), .5); + --hover-bg-action: var(--bg-action) + linear-gradient(rgba(0, 0, 0, .08), rgba(0, 0, 0, .08)); + --hover-bg-color: rgba(var(--google-blue-refresh-300-rgb), .08); + --ink-color-action: black; + --ink-color: var(--google-blue-refresh-300); + --ripple-opacity-action: .16; + --ripple-opacity: .16; + --text-color-action: var(--google-grey-900); + --text-color: var(--google-blue-refresh-300); + } + + :host { + --paper-ripple-opacity: var(--ripple-opacity); + -webkit-tap-highlight-color: transparent; + align-items: center; + border: 1px solid var(--border-color); + border-radius: 4px; + box-sizing: border-box; + color: var(--text-color); + cursor: pointer; + display: inline-flex; + font-weight: 500; + height: var(--cr-button-height); + min-width: 5.14em; + outline-width: 0; + padding: 8px 16px; + position: relative; + user-select: none; + white-space: nowrap; + } + + :host-context(.focus-outline-visible):host(:focus) { + box-shadow: 0 0 0 2px var(--focus-shadow-color); + } + + :host(:active) { + background: var(--active-bg); + box-shadow: + 0 1px 2px 0 rgba(var(--active-shadow-rgb), .3), + 0 3px 6px 2px rgba(var(--active-shadow-rgb), .15); + } + + :host(:hover) { + background-color: var(--hover-bg-color); + } + + :host-context(html:not([dark])):host(:hover) { + border-color: var(--google-blue-refresh-100); + } + + :host(.action-button) { + --ink-color: var(--ink-color-action); + --paper-ripple-opacity: var(--ripple-opacity-action); + background-color: var(--bg-action); + border: none; + color: var(--text-color-action); + } + + :host(.action-button:active) { + box-shadow: + 0 1px 2px 0 rgba(var(--active-shadow-action-rgb), .3), + 0 3px 6px 2px rgba(var(--active-shadow-action-rgb), .15); + } + + :host(.action-button:hover) { + background: var(--hover-bg-action); + } + + :host-context(html:not([dark])):host(.action-button:hover) { + box-shadow: 0 1px 2px 0 rgba(var(--google-blue-500-rgb), .3), + 0 1px 3px 1px rgba(var(--google-blue-500-rgb), .15); + } + + :host([disabled]) { + background-color: var(--disabled-bg); + border-color: var(--disabled-border-color); + color: var(--google-grey-600); + cursor: auto; + pointer-events: none; + } + + :host(.action-button[disabled]) { + background-color: var(--disabled-bg-action); + border-color: transparent; + } + + /* cancel-button is meant to be used within a cr-dialog */ + :host(.cancel-button) { + margin-inline-end: 8px; + } + + :host(.action-button), + :host(.cancel-button) { + line-height: 154%; + } + + paper-ripple { + color: var(--ink-color); + } + </style> + <slot></slot> + </template> + <script src="cr_button.js"></script> +</dom-module>
diff --git a/ui/webui/resources/cr_elements/cr_button/cr_button.js b/ui/webui/resources/cr_elements/cr_button/cr_button.js new file mode 100644 index 0000000..2dd96d21 --- /dev/null +++ b/ui/webui/resources/cr_elements/cr_button/cr_button.js
@@ -0,0 +1,112 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview 'cr-button' is a button which displays slotted elements. It can + * be interacted with like a normal button using click as well as space and + * enter to effectively click the button and fire a 'click' event. + */ +Polymer({ + is: 'cr-button', + + behaviors: [ + Polymer.PaperRippleBehavior, + ], + + properties: { + disabled: { + type: Boolean, + value: false, + reflectToAttribute: true, + observer: 'disabledChanged_', + }, + }, + + hostAttributes: { + 'aria-disabled': 'false', + role: 'button', + tabindex: 0, + }, + + listeners: { + click: 'onClick_', + keydown: 'onKeyDown_', + keyup: 'onKeyUp_', + pointerdown: 'onPointerDown_', + }, + + /** @override */ + ready: function() { + cr.ui.FocusOutlineManager.forDocument(document); + }, + + /** + * @param {boolean} newValue + * @param {boolean} oldValue + * @private + */ + disabledChanged_: function(newValue, oldValue) { + if (!newValue && oldValue == undefined) { + return; + } + if (this.disabled) { + this.blur(); + } + this.setAttribute('aria-disabled', Boolean(this.disabled)); + this.setAttribute('tabindex', this.disabled ? -1 : 0); + }, + + /** + * @param {!Event} e + * @private + */ + onClick_: function(e) { + if (this.disabled) { + e.stopImmediatePropagation(); + } + }, + + /** + * @param {!KeyboardEvent} e + * @private + */ + onKeyDown_: function(e) { + if (e.key != ' ' && e.key != 'Enter') { + return; + } + + e.preventDefault(); + e.stopPropagation(); + if (e.repeat) { + return; + } + + if (e.key == 'Enter') { + this.click(); + } else { + this.getRipple().uiDownAction(); + } + }, + + /** + * @param {!KeyboardEvent} e + * @private + */ + onKeyUp_: function(e) { + if (e.key == ' ' || e.key == 'Enter') { + e.preventDefault(); + e.stopPropagation(); + } + + if (e.key == ' ') { + this.click(); + this.getRipple().uiUpAction(); + } + }, + + /** @private */ + onPointerDown_: function() { + this.ensureRipple(); + }, +});
diff --git a/ui/webui/resources/cr_elements/hidden_style_css.html b/ui/webui/resources/cr_elements/hidden_style_css.html index 9326a5e8..33bb9159 100644 --- a/ui/webui/resources/cr_elements/hidden_style_css.html +++ b/ui/webui/resources/cr_elements/hidden_style_css.html
@@ -7,7 +7,8 @@ <style> /* Included here so we don't have to include "iron-positioning" in every * stylesheet. See crbug.com/498405. */ - [hidden] { + [hidden], + :host([hidden]) { display: none !important; } </style>
diff --git a/ui/webui/resources/cr_elements_resources.grdp b/ui/webui/resources/cr_elements_resources.grdp index c4427629..2c012619 100644 --- a/ui/webui/resources/cr_elements_resources.grdp +++ b/ui/webui/resources/cr_elements_resources.grdp
@@ -9,6 +9,14 @@ file="cr_elements/cr_action_menu/cr_action_menu.js" type="chrome_html" compress="gzip" /> + <structure name="IDR_CR_ELEMENTS_CR_BUTTON_HTML" + file="cr_elements/cr_button/cr_button.html" + type="chrome_html" + compress="gzip" /> + <structure name="IDR_CR_ELEMENTS_CR_BUTTON_JS" + file="cr_elements/cr_button/cr_button.js" + type="chrome_html" + compress="gzip" /> <structure name="IDR_CR_ELEMENTS_CR_CHECKBOX_HTML" file="cr_elements/cr_checkbox/cr_checkbox.html" type="chrome_html"
diff --git a/ui/webui/resources/css/apps/common.css b/ui/webui/resources/css/apps/common.css index 44b729ab..414a899c 100644 --- a/ui/webui/resources/css/apps/common.css +++ b/ui/webui/resources/css/apps/common.css
@@ -117,54 +117,3 @@ url(chrome://resources/images/2x/apps/blue_button_inactive.png) 2x) 5 fill / 5px / 2px repeat; } - -input[type='checkbox'] { - -webkit-appearance: none; - border: none; - outline: none; -} - -input[type='checkbox']::after { - content: ''; - display: block; - height: 16px; - left: -2px; - top: -2px; - width: 16px; -} - -input[type='checkbox']:not(:checked)::after { - background-image: -webkit-image-set( - url(chrome://resources/images/apps/checkbox.png) 1x, - url(chrome://resources/images/2x/apps/checkbox.png) 2x); -} - -input[type='checkbox']:focus:not(:checked)::after { - background-image: -webkit-image-set( - url(chrome://resources/images/apps/checkbox_focused.png) 1x, - url(chrome://resources/images/2x/apps/checkbox_focused.png) 2x); -} - -input[type='checkbox']:disabled:not(:checked)::after { - background-image: -webkit-image-set( - url(chrome://resources/images/apps/checkbox_inactive.png) 1x, - url(chrome://resources/images/2x/apps/checkbox_inactive.png) 2x); -} - -input[type='checkbox']:checked::after { - background-image: -webkit-image-set( - url(chrome://resources/images/apps/checkbox_checked.png) 1x, - url(chrome://resources/images/2x/apps/checkbox_checked.png) 2x); -} - -input[type='checkbox']:focus:checked::after { - background-image: -webkit-image-set( - url(chrome://resources/images/apps/checkbox_focused_checked.png) 1x, - url(chrome://resources/images/2x/apps/checkbox_focused_checked.png) 2x); -} - -input[type='checkbox']:disabled:checked::after { - background-image: -webkit-image-set( - url(chrome://resources/images/apps/checkbox_checked_inactive.png) 1x, - url(chrome://resources/images/2x/apps/checkbox_checked_inactive.png) 2x); -}
diff --git a/ui/webui/resources/webui_resources.grd b/ui/webui/resources/webui_resources.grd index eb88aa1..4307d81 100644 --- a/ui/webui/resources/webui_resources.grd +++ b/ui/webui/resources/webui_resources.grd
@@ -57,36 +57,6 @@ file="../../views/resources/default_100_percent/common/blue_button_focused_pressed.png" type="BINDATA" /> <include name="IDR_WEBUI_IMAGES_APPS_BLUE_BUTTON_FOCUSED_HOVER" file="../../views/resources/default_100_percent/common/blue_button_focused_hover.png" type="BINDATA" /> - <!-- Checkbox (unchecked) --> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX" - file="../../views/resources/default_100_percent/common/checkbox.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_HOVER" - file="../../views/resources/default_100_percent/common/checkbox_hover.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_PRESSED" - file="../../views/resources/default_100_percent/common/checkbox_pressed.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_FOCUSED" - file="../../views/resources/default_100_percent/common/checkbox_focused.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_FOCUSED_HOVER" - file="../../views/resources/default_100_percent/common/checkbox_focused_hover.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_FOCUSED_PRESSED" - file="../../views/resources/default_100_percent/common/checkbox_focused_pressed.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_INACTIVE" - file="../../views/resources/default_100_percent/common/checkbox_inactive.png" type="BINDATA" /> - <!-- Checkbox (checked) --> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_CHECKED" - file="../../views/resources/default_100_percent/common/checkbox_checked.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_CHECKED_HOVER" - file="../../views/resources/default_100_percent/common/checkbox_checked_hover.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_CHECKED_PRESSED" - file="../../views/resources/default_100_percent/common/checkbox_checked_pressed.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_FOCUSED_CHECKED" - file="../../views/resources/default_100_percent/common/checkbox_focused_checked.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_FOCUSED_CHECKED_HOVER" - file="../../views/resources/default_100_percent/common/checkbox_focused_checked_hover.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_FOCUSED_CHECKED_PRESSED" - file="../../views/resources/default_100_percent/common/checkbox_focused_checked_pressed.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_CHECKED_INACTIVE" - file="../../views/resources/default_100_percent/common/checkbox_checked_inactive.png" type="BINDATA" /> <!-- Misc buttons --> <include name="IDR_WEBUI_IMAGES_APPS_TOPBAR_BUTTON_CLOSE" file="images/apps/topbar_button_close.png" type="BINDATA" /> @@ -132,36 +102,6 @@ file="../../views/resources/default_200_percent/common/blue_button_focused_pressed.png" type="BINDATA" /> <include name="IDR_WEBUI_IMAGES_APPS_BLUE_BUTTON_2X_FOCUSED_HOVER" file="../../views/resources/default_200_percent/common/blue_button_focused_hover.png" type="BINDATA" /> - <!-- Checkbox (unchecked) --> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_2X" - file="../../views/resources/default_200_percent/common/checkbox.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_2X_HOVER" - file="../../views/resources/default_200_percent/common/checkbox_hover.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_2X_PRESSED" - file="../../views/resources/default_200_percent/common/checkbox_pressed.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_2X_FOCUSED" - file="../../views/resources/default_200_percent/common/checkbox_focused.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_2X_FOCUSED_HOVER" - file="../../views/resources/default_200_percent/common/checkbox_focused_hover.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_2X_FOCUSED_PRESSED" - file="../../views/resources/default_200_percent/common/checkbox_focused_pressed.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_INACTIVE_2X" - file="../../views/resources/default_200_percent/common/checkbox_inactive.png" type="BINDATA" /> - <!-- Checkbox (checked) --> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_CHECKED_2X" - file="../../views/resources/default_200_percent/common/checkbox_checked.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_CHECKED_2X_HOVER" - file="../../views/resources/default_200_percent/common/checkbox_checked_hover.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_CHECKED_2X_PRESSED" - file="../../views/resources/default_200_percent/common/checkbox_checked_pressed.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_FOCUSED_CHECKED_2X" - file="../../views/resources/default_200_percent/common/checkbox_focused_checked.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_FOCUSED_CHECKED_2X_HOVER" - file="../../views/resources/default_200_percent/common/checkbox_focused_checked_hover.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_FOCUSED_CHECKED_2X_PRESSED" - file="../../views/resources/default_200_percent/common/checkbox_focused_checked_pressed.png" type="BINDATA" /> - <include name="IDR_WEBUI_IMAGES_APPS_CHECKBOX_CHECKED_INACTIVE_2X" - file="../../views/resources/default_200_percent/common/checkbox_checked_inactive.png" type="BINDATA" /> <!-- Misc buttons --> <include name="IDR_WEBUI_IMAGES_APPS_TOPBAR_BUTTON_2X_CLOSE" file="images/2x/apps/topbar_button_close.png" type="BINDATA" />