diff --git a/DEPS b/DEPS index c62fa590..6aca944 100644 --- a/DEPS +++ b/DEPS
@@ -105,11 +105,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': 'c955a1645148872e9bda432dae8f15954c589cae', + 'skia_revision': '4fb073ac73285d8c96729c335817a4683c5c0033', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': '26fc9ad8a50e1a0d24e2625dd707737795e74329', + 'v8_revision': 'd786acd33ca315f32b69aa4c9e2313d0a701d63a', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -129,7 +129,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': 'e65756725f82456fced473d444961673ad7b3edb', + 'pdfium_revision': '97f4483de007c2ff248696f24d34634e0adbf894', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling openmax_dl # and whatever else without interference from each other. @@ -165,7 +165,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': '45ed33924d94afd1b188cb639fd0c511e5b90603', + 'catapult_revision': 'f19e5d11958805ab942bc0f2485922e80a3ea8a7', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -282,7 +282,7 @@ Var('chromium_git') + '/external/github.com/immersive-web/webxr-samples.git' + '@' + 'cf02f19c4ff6894705a9407722ab52551e010c60', 'src/ios/third_party/earl_grey/src': { - 'url': Var('chromium_git') + '/external/github.com/google/EarlGrey.git' + '@' + '451b6497352d0731e9827a338f32024e564078c6', + 'url': Var('chromium_git') + '/external/github.com/google/EarlGrey.git' + '@' + '3102ef3b137f05a179628b1b9768856e5feea90e', 'condition': 'checkout_ios', }, @@ -853,7 +853,7 @@ }, 'src/third_party/libvpx/source/libvpx': - Var('chromium_git') + '/webm/libvpx.git' + '@' + '282087a14c84a65f10b3a8d0e81c255e13a7a746', + Var('chromium_git') + '/webm/libvpx.git' + '@' + '3448987ab20aa05716ffc4aedf6d02e23f75920b', 'src/third_party/libwebm/source': Var('chromium_git') + '/webm/libwebm.git' + '@' + '01c1d1d76f139345c442bfc8e61b4e1cba809059', @@ -954,7 +954,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'f4a7342c6fc4a1825357e5aea7bbacfe605b9330', + Var('android_git') + '/platform/external/perfetto.git' + '@' + 'e2ea26c8b5212bc44d943397c82b29430be600bf', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + 'ac0d98b5cee6c024b0cffeb4f8f45b6fc5ccdb78',
diff --git a/PRESUBMIT.py b/PRESUBMIT.py index b41bee9..e2bdf373 100644 --- a/PRESUBMIT.py +++ b/PRESUBMIT.py
@@ -858,6 +858,59 @@ return [output_api.PresubmitPromptWarning('UNIT_TEST is only for headers.\n' + '\n'.join(problems))] +def _CheckNoDISABLETypoInTests(input_api, output_api): + """Checks to prevent attempts to disable tests with DISABLE_ prefix. + + This test warns if somebody tries to disable a test with the DISABLE_ prefix + instead of DISABLED_. To filter false positives, reports are only generated + if a corresponding MAYBE_ line exists. + """ + problems = [] + + # The following two patterns are looked for in tandem - is a test labeled + # as MAYBE_ followed by a DISABLE_ (instead of the correct DISABLED) + maybe_pattern = input_api.re.compile(r'MAYBE_([a-zA-Z0-9_]+)') + disable_pattern = input_api.re.compile(r'DISABLE_([a-zA-Z0-9_]+)') + + # This is for the case that a test is disabled on all platforms. + full_disable_pattern = input_api.re.compile( + r'^\s*TEST[^(]*\([a-zA-Z0-9_]+,\s*DISABLE_[a-zA-Z0-9_]+\)', + input_api.re.MULTILINE) + + for f in input_api.AffectedFiles(): + if not 'test' in f.LocalPath() or not f.LocalPath().endswith('.cc'): + continue + + # Search for MABYE_, DISABLE_ pairs. + disable_lines = {} # Maps of test name to line number. + maybe_lines = {} + for line_num, line in f.ChangedContents(): + disable_match = disable_pattern.search(line) + if disable_match: + disable_lines[disable_match.group(1)] = line_num + maybe_match = maybe_pattern.search(line) + if maybe_match: + maybe_lines[maybe_match.group(1)] = line_num + + # Search for DISABLE_ occurrences within a TEST() macro. + disable_tests = set(disable_lines.keys()) + maybe_tests = set(maybe_lines.keys()) + for test in disable_tests.intersection(maybe_tests): + problems.append(' %s:%d' % (f.LocalPath(), disable_lines[test])) + + contents = input_api.ReadFile(f) + full_disable_match = full_disable_pattern.search(contents) + if full_disable_match: + problems.append(' %s' % f.LocalPath()) + + if not problems: + return [] + return [ + output_api.PresubmitPromptWarning( + 'Attempt to disable a test with DISABLE_ instead of DISABLED_?\n' + + '\n'.join(problems)) + ] + def _CheckDCHECK_IS_ONHasBraces(input_api, output_api): """Checks to make sure DCHECK_IS_ON() does not skip the parentheses.""" @@ -2957,6 +3010,7 @@ _CheckNoProductionCodeUsingTestOnlyFunctionsJava(input_api, output_api)) results.extend(_CheckNoIOStreamInHeaders(input_api, output_api)) results.extend(_CheckNoUNIT_TESTInSourceFiles(input_api, output_api)) + results.extend(_CheckNoDISABLETypoInTests(input_api, output_api)) results.extend(_CheckDCHECK_IS_ONHasBraces(input_api, output_api)) results.extend(_CheckNoNewWStrings(input_api, output_api)) results.extend(_CheckNoDEPSGIT(input_api, output_api))
diff --git a/PRESUBMIT_test.py b/PRESUBMIT_test.py index 557b40b9..a6c31b71 100755 --- a/PRESUBMIT_test.py +++ b/PRESUBMIT_test.py
@@ -2019,5 +2019,59 @@ self.assertEqual([], warnings) +class DISABLETypoInTest(unittest.TestCase): + + def testPositive(self): + # Verify the typo "DISABLE_" instead of "DISABLED_" in various contexts + # where the desire is to disable a test. + tests = [ + # Disabled on one platform: + '#if defined(OS_WIN)\n' + '#define MAYBE_FoobarTest DISABLE_FoobarTest\n' + '#else\n' + '#define MAYBE_FoobarTest FoobarTest\n' + '#endif\n', + # Disabled on one platform spread cross lines: + '#if defined(OS_WIN)\n' + '#define MAYBE_FoobarTest \\\n' + ' DISABLE_FoobarTest\n' + '#else\n' + '#define MAYBE_FoobarTest FoobarTest\n' + '#endif\n', + # Disabled on all platforms: + ' TEST_F(FoobarTest, DISABLE_Foo)\n{\n}', + # Disabled on all platforms but multiple lines + ' TEST_F(FoobarTest,\n DISABLE_foo){\n}\n', + ] + + for test in tests: + mock_input_api = MockInputApi() + mock_input_api.files = [ + MockFile('some/path/foo_unittest.cc', test.splitlines()), + ] + + results = PRESUBMIT._CheckNoDISABLETypoInTests(mock_input_api, + MockOutputApi()) + self.assertEqual( + 1, + len(results), + msg=('expected len(results) == 1 but got %d in test: %s' % + (len(results), test))) + self.assertTrue( + 'foo_unittest.cc' in results[0].message, + msg=('expected foo_unittest.cc in message but got %s in test %s' % + (results[0].message, test))) + + def testIngoreNotTestFiles(self): + mock_input_api = MockInputApi() + mock_input_api.files = [ + MockFile('some/path/foo.cc', 'TEST_F(FoobarTest, DISABLE_Foo)'), + ] + + results = PRESUBMIT._CheckNoDISABLETypoInTests(mock_input_api, + MockOutputApi()) + self.assertEqual(0, len(results)) + + if __name__ == '__main__': unittest.main()
diff --git a/WATCHLISTS b/WATCHLISTS index 6fb99d2..fa6f462 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -2135,7 +2135,8 @@ 'explore_sites': ['chili+watch@chromium.org', 'dewittj+watch@chromium.org', 'dimich+watch@chromium.org', - 'freedjm+watch@chromium.org'], + 'freedjm+watch@chromium.org', + 'petewil+watch@chromium.org'], 'extension': ['chromium-apps-reviews@chromium.org', 'extensions-reviews@chromium.org'], 'feature_policy': ['loonybear@chromium.org',
diff --git a/android_webview/java/src/org/chromium/android_webview/AwBrowserProcess.java b/android_webview/java/src/org/chromium/android_webview/AwBrowserProcess.java index be40932..535f898e 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwBrowserProcess.java +++ b/android_webview/java/src/org/chromium/android_webview/AwBrowserProcess.java
@@ -18,7 +18,6 @@ import org.chromium.android_webview.policy.AwPolicyProvider; import org.chromium.android_webview.services.CrashReceiverService; import org.chromium.android_webview.services.ICrashReceiverService; -import org.chromium.base.AsyncTask; import org.chromium.base.BuildInfo; import org.chromium.base.CommandLine; import org.chromium.base.ContextUtils; @@ -30,6 +29,7 @@ import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.library_loader.ProcessInitException; +import org.chromium.base.task.AsyncTask; import org.chromium.components.minidump_uploader.CrashFileManager; import org.chromium.content_public.browser.BrowserStartupController; import org.chromium.content_public.browser.ChildProcessCreationParams;
diff --git a/android_webview/java/src/org/chromium/android_webview/AwContents.java b/android_webview/java/src/org/chromium/android_webview/AwContents.java index 808f8df..4ed0eac 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwContents.java +++ b/android_webview/java/src/org/chromium/android_webview/AwContents.java
@@ -48,7 +48,6 @@ import org.chromium.android_webview.permission.AwGeolocationCallback; import org.chromium.android_webview.permission.AwPermissionRequest; import org.chromium.android_webview.renderer_priority.RendererPriority; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.LocaleUtils; import org.chromium.base.Log; @@ -59,6 +58,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.blink_public.web.WebReferrerPolicy; import org.chromium.components.autofill.AutofillProvider; import org.chromium.components.navigation_interception.InterceptNavigationDelegate;
diff --git a/android_webview/java/src/org/chromium/android_webview/AwWebContentsDelegateAdapter.java b/android_webview/java/src/org/chromium/android_webview/AwWebContentsDelegateAdapter.java index bacce83..ad829f6 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwWebContentsDelegateAdapter.java +++ b/android_webview/java/src/org/chromium/android_webview/AwWebContentsDelegateAdapter.java
@@ -18,10 +18,10 @@ import android.webkit.URLUtil; import android.widget.FrameLayout; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.ContentUriUtils; import org.chromium.base.ThreadUtils; +import org.chromium.base.task.AsyncTask; import org.chromium.content_public.browser.InvalidateTypes; import org.chromium.content_public.common.ContentUrlConstants; import org.chromium.content_public.common.ResourceRequestBody;
diff --git a/android_webview/java/src/org/chromium/android_webview/DefaultVideoPosterRequestHandler.java b/android_webview/java/src/org/chromium/android_webview/DefaultVideoPosterRequestHandler.java index b541494..2400c5de 100644 --- a/android_webview/java/src/org/chromium/android_webview/DefaultVideoPosterRequestHandler.java +++ b/android_webview/java/src/org/chromium/android_webview/DefaultVideoPosterRequestHandler.java
@@ -7,8 +7,8 @@ import android.graphics.Bitmap; import android.util.Log; -import org.chromium.base.AsyncTask; import org.chromium.base.ThreadUtils; +import org.chromium.base.task.AsyncTask; import java.io.IOException; import java.io.InputStream;
diff --git a/android_webview/java/src/org/chromium/android_webview/services/AwVariationsSeedFetcher.java b/android_webview/java/src/org/chromium/android_webview/services/AwVariationsSeedFetcher.java index ecaf3bc..c34f025 100644 --- a/android_webview/java/src/org/chromium/android_webview/services/AwVariationsSeedFetcher.java +++ b/android_webview/java/src/org/chromium/android_webview/services/AwVariationsSeedFetcher.java
@@ -14,10 +14,10 @@ import android.os.Build; import org.chromium.android_webview.VariationsUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.compat.ApiHelperForN; +import org.chromium.base.task.AsyncTask; import org.chromium.components.background_task_scheduler.TaskIds; import org.chromium.components.variations.firstrun.VariationsSeedFetcher; import org.chromium.components.variations.firstrun.VariationsSeedFetcher.SeedInfo;
diff --git a/ash/manifest.json b/ash/manifest.json index defa2de..bb10a14 100644 --- a/ash/manifest.json +++ b/ash/manifest.json
@@ -68,6 +68,7 @@ "*": [ "accessibility", "app" ], "ash_pref_connector": [ "pref_connector" ], "catalog": [ "directory" ], + "device": [ "device:fingerprint"], "local_state": [ "pref_client" ], "multidevice_setup": [ "multidevice_setup" ], "quick_launch_app": [ "mash:launchable" ],
diff --git a/ash/shell.cc b/ash/shell.cc index ae65d99e..b2f923a 100644 --- a/ash/shell.cc +++ b/ash/shell.cc
@@ -1262,8 +1262,9 @@ peripheral_battery_notifier_ = std::make_unique<PeripheralBatteryNotifier>(); power_event_observer_.reset(new PowerEventObserver()); - user_activity_notifier_.reset( - new ui::UserActivityPowerManagerNotifier(user_activity_detector_.get())); + user_activity_notifier_ = + std::make_unique<ui::UserActivityPowerManagerNotifier>( + user_activity_detector_.get(), connector_); video_activity_notifier_.reset( new VideoActivityNotifier(video_detector_.get())); bluetooth_notification_controller_.reset(new BluetoothNotificationController);
diff --git a/ash/wm/overview/scoped_transform_overview_window.cc b/ash/wm/overview/scoped_transform_overview_window.cc index d1b4df70..bfb3083 100644 --- a/ash/wm/overview/scoped_transform_overview_window.cc +++ b/ash/wm/overview/scoped_transform_overview_window.cc
@@ -526,6 +526,10 @@ minimized_widget_->SetBounds(bounds); minimized_widget_->Show(); + // Stack the minimized window at the bottom since it is never transformed in + // and only faded in, so it should always be underneath non minimized windows. + window_->parent()->StackChildAtBottom(minimized_widget_->GetNativeWindow()); + FadeInWidgetAndMaybeSlideOnEnter( minimized_widget_.get(), OVERVIEW_ANIMATION_ENTER_OVERVIEW_MODE_FADE_IN, /*slide=*/false);
diff --git a/ash/wm/overview/window_selector_item.cc b/ash/wm/overview/window_selector_item.cc index 5256a888..0e7101e 100644 --- a/ash/wm/overview/window_selector_item.cc +++ b/ash/wm/overview/window_selector_item.cc
@@ -633,8 +633,14 @@ gfx::Rect inset_bounds(target_bounds); inset_bounds.Inset(kWindowMargin, kWindowMargin); - if (wm::GetWindowState(GetWindow())->IsMinimized()) + + // Do not animate if entering when the window is minimized, as it will be + // faded in. We still want to animate if the position is changed after + // entering. + if (wm::GetWindowState(GetWindow())->IsMinimized() && + mode == HeaderFadeInMode::kFirstUpdate) { new_animation_type = OVERVIEW_ANIMATION_NONE; + } SetItemBounds(inset_bounds, new_animation_type);
diff --git a/ash/wm/overview/window_selector_unittest.cc b/ash/wm/overview/window_selector_unittest.cc index 789dd2c..bcc3bde 100644 --- a/ash/wm/overview/window_selector_unittest.cc +++ b/ash/wm/overview/window_selector_unittest.cc
@@ -2612,13 +2612,14 @@ // The original order of stacking is determined by the order the associated // window was activated (created in this case). All widgets associated with - // minimized windows will be above non minimized windows, because a widget for - // the minimized windows is created upon entering overview, and them the - // window selector item widget is stacked on top of that. - EXPECT_GT(IndexOf(widget2->GetNativeWindow(), parent), - IndexOf(widget3->GetNativeWindow(), parent)); + // minimized windows will be below non minimized windows, because a widget for + // the minimized windows is created upon entering overview, and they are + // explicitly stacked beneath non minimized windows so they do not cover them + // during enter animation. EXPECT_GT(IndexOf(widget3->GetNativeWindow(), parent), IndexOf(widget1->GetNativeWindow(), parent)); + EXPECT_GT(IndexOf(widget1->GetNativeWindow(), parent), + IndexOf(widget2->GetNativeWindow(), parent)); // Verify that only minimized windows have minimized widgets in overview. EXPECT_FALSE(min_widget1); @@ -2660,10 +2661,10 @@ generator->ReleaseLeftButton(); // Verify the stacking order is same as before dragging started. - EXPECT_GT(IndexOf(widget2->GetNativeWindow(), parent), - IndexOf(widget3->GetNativeWindow(), parent)); EXPECT_GT(IndexOf(widget3->GetNativeWindow(), parent), IndexOf(widget1->GetNativeWindow(), parent)); + EXPECT_GT(IndexOf(widget1->GetNativeWindow(), parent), + IndexOf(widget2->GetNativeWindow(), parent)); } // Tests that overview widgets are stacked in the correct order.
diff --git a/base/BUILD.gn b/base/BUILD.gn index dcb45dd..1ed0b8a 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -2974,7 +2974,6 @@ "android/java/src/org/chromium/base/task/AsyncTask.java", "android/java/src/org/chromium/base/task/ChromeThreadPoolExecutor.java", "android/java/src/org/chromium/base/task/SerialExecutor.java", - "//third_party/android_async_task/java/src/org/chromium/base/AsyncTask.java", ] # New versions of BuildConfig.java and NativeLibraries.java @@ -3006,7 +3005,6 @@ # AssertsTest doesn't really belong in //base but it's preferable to # stick it here than create another target for a single test. "android/javatests/src/org/chromium/base/AssertsTest.java", - "android/javatests/src/org/chromium/base/AsyncTaskTest.java", "android/javatests/src/org/chromium/base/AdvancedMockContextTest.java", "android/javatests/src/org/chromium/base/ApiCompatibilityUtilsTest.java", "android/javatests/src/org/chromium/base/CommandLineInitUtilTest.java", @@ -3019,6 +3017,7 @@ "android/javatests/src/org/chromium/base/ObserverListTest.java", "android/javatests/src/org/chromium/base/StrictModeContextTest.java", "android/javatests/src/org/chromium/base/metrics/RecordHistogramTest.java", + "android/javatests/src/org/chromium/base/task/AsyncTaskTest.java", ] } @@ -3112,13 +3111,11 @@ "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/test/BaseRobolectricTestRunner.java", - "test/android/junit/src/org/chromium/base/test/asynctask/BackgroundShadowAsyncTask.java", - "test/android/junit/src/org/chromium/base/test/asynctask/CustomShadowAsyncTask.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/test/util/TestRunnerTestRule.java", "//third_party/robolectric/custom_asynctask/java/src/org/chromium/base/task/test/ShadowAsyncTask.java", "//third_party/robolectric/custom_asynctask/java/src/org/chromium/base/task/test/ShadowAsyncTaskBridge.java", - "//third_party/robolectric/custom_asynctask/java/src/org/chromium/base/test/asynctask/ShadowAsyncTask.java", - "//third_party/robolectric/custom_asynctask/java/src/org/chromium/base/test/asynctask/ShadowAsyncTaskBridge.java", ] deps = [ ":base_java",
diff --git a/base/android/java/src/org/chromium/base/PathUtils.java b/base/android/java/src/org/chromium/base/PathUtils.java index 5ff7a41..d09d6bf 100644 --- a/base/android/java/src/org/chromium/base/PathUtils.java +++ b/base/android/java/src/org/chromium/base/PathUtils.java
@@ -16,6 +16,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.MainDex; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import java.io.File; import java.util.ArrayList;
diff --git a/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java b/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java index 9f3d7db..30f341e6 100644 --- a/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java +++ b/base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java
@@ -16,7 +16,6 @@ import android.support.v4.content.ContextCompat; import android.system.Os; -import org.chromium.base.AsyncTask; import org.chromium.base.BuildConfig; import org.chromium.base.BuildInfo; import org.chromium.base.CommandLine; @@ -31,6 +30,7 @@ import org.chromium.base.annotations.MainDex; import org.chromium.base.compat.ApiHelperForM; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import java.io.File; import java.io.IOException;
diff --git a/base/android/java/src/org/chromium/base/task/ChromeThreadPoolExecutor.java b/base/android/java/src/org/chromium/base/task/ChromeThreadPoolExecutor.java index a348798..7538843 100644 --- a/base/android/java/src/org/chromium/base/task/ChromeThreadPoolExecutor.java +++ b/base/android/java/src/org/chromium/base/task/ChromeThreadPoolExecutor.java
@@ -23,6 +23,10 @@ class ChromeThreadPoolExecutor extends ThreadPoolExecutor { private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); + // Core pool is still used despite allowCoreThreadTimeOut(true) being called - while the core + // pool can still timeout, the thread pool will still start up threads more aggressively while + // under the CORE_POOL_SIZE. + private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4)); private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; private static final int KEEP_ALIVE_SECONDS = 30; @@ -41,7 +45,8 @@ private static final int RUNNABLE_WARNING_COUNT = 32; ChromeThreadPoolExecutor() { - this(0, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, SECONDS, sPoolWorkQueue, sThreadFactory); + this(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, SECONDS, sPoolWorkQueue, + sThreadFactory); } @VisibleForTesting
diff --git a/base/android/javatests/src/org/chromium/base/AsyncTaskTest.java b/base/android/javatests/src/org/chromium/base/task/AsyncTaskTest.java similarity index 86% rename from base/android/javatests/src/org/chromium/base/AsyncTaskTest.java rename to base/android/javatests/src/org/chromium/base/task/AsyncTaskTest.java index 215da3d..61dea5cc 100644 --- a/base/android/javatests/src/org/chromium/base/AsyncTaskTest.java +++ b/base/android/javatests/src/org/chromium/base/task/AsyncTaskTest.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.base; +package org.chromium.base.task; import android.support.annotation.NonNull; import android.support.test.filters.SmallTest; @@ -60,7 +60,7 @@ @Test @SmallTest public void testChromeThreadPoolExecutorRunnables() { - Executor executor = new AsyncTask.ChromeThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, + Executor executor = new ChromeThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(QUEUE_SIZE), new ThreadFactory() { @Override public Thread newThread(@NonNull Runnable r) { @@ -71,8 +71,8 @@ executor.execute(new SpecialRunnable()); } thrown.expect(RejectedExecutionException.class); - thrown.expectMessage( - CoreMatchers.containsString("org.chromium.base.AsyncTaskTest$SpecialRunnable")); + thrown.expectMessage(CoreMatchers.containsString( + "org.chromium.base.task.AsyncTaskTest$SpecialRunnable")); thrown.expectMessage( CoreMatchers.not(CoreMatchers.containsString("SpecialChromeAsyncTask"))); new SpecialChromeAsyncTask().executeOnExecutor(executor); @@ -85,7 +85,7 @@ @Test @SmallTest public void testChromeThreadPoolExecutorChromeAsyncTask() { - Executor executor = new AsyncTask.ChromeThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, + Executor executor = new ChromeThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(QUEUE_SIZE), new ThreadFactory() { @Override public Thread newThread(@NonNull Runnable r) { @@ -97,7 +97,7 @@ } thrown.expect(RejectedExecutionException.class); thrown.expectMessage(CoreMatchers.containsString( - "org.chromium.base.AsyncTaskTest$SpecialChromeAsyncTask")); + "org.chromium.base.task.AsyncTaskTest$SpecialChromeAsyncTask")); thrown.expectMessage(CoreMatchers.not(CoreMatchers.containsString("SpecialOsAsyncTask"))); new SpecialOsAsyncTask().executeOnExecutor(executor); } @@ -109,7 +109,7 @@ @Test @SmallTest public void testChromeThreadPoolExecutorOsAsyncTask() { - Executor executor = new AsyncTask.ChromeThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, + Executor executor = new ChromeThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(QUEUE_SIZE), new ThreadFactory() { @Override public Thread newThread(@NonNull Runnable r) { @@ -120,8 +120,8 @@ new SpecialOsAsyncTask().executeOnExecutor(executor); } thrown.expect(RejectedExecutionException.class); - thrown.expectMessage( - CoreMatchers.containsString("org.chromium.base.AsyncTaskTest$SpecialOsAsyncTask")); + thrown.expectMessage(CoreMatchers.containsString( + "org.chromium.base.task.AsyncTaskTest$SpecialOsAsyncTask")); thrown.expectMessage( CoreMatchers.not(CoreMatchers.containsString("SpecialChromeAsyncTask"))); new SpecialChromeAsyncTask().executeOnExecutor(executor);
diff --git a/base/test/android/junit/src/org/chromium/base/test/asynctask/BackgroundShadowAsyncTask.java b/base/test/android/junit/src/org/chromium/base/test/asynctask/BackgroundShadowAsyncTask.java deleted file mode 100644 index f8ba988e..0000000 --- a/base/test/android/junit/src/org/chromium/base/test/asynctask/BackgroundShadowAsyncTask.java +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.base.test.asynctask; - -import static org.junit.Assert.fail; - -import org.robolectric.annotation.Implementation; -import org.robolectric.annotation.Implements; -import org.robolectric.shadows.ShadowApplication; - -import org.chromium.base.AsyncTask; - -import java.util.concurrent.Callable; -import java.util.concurrent.Executor; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * Executes async tasks on a background thread and waits on the result on the main thread. - * This is useful for users of AsyncTask on Roboelectric who check if the code is actually being - * run on a background thread (i.e. through the use of {@link ThreadUtils#runningOnUiThread()}). - * @param <Result> type for reporting result - */ -@Implements(AsyncTask.class) -public class BackgroundShadowAsyncTask<Result> extends ShadowAsyncTask<Result> { - private static final ExecutorService sExecutorService = Executors.newSingleThreadExecutor(); - - @Override - @Implementation - public final AsyncTask<Result> executeOnExecutor(Executor e) { - try { - return sExecutorService - .submit(new Callable<AsyncTask<Result>>() { - @Override - public AsyncTask<Result> call() throws Exception { - return BackgroundShadowAsyncTask.super.executeInRobolectric(); - } - }) - .get(); - } catch (Exception ex) { - fail(ex.getMessage()); - return null; - } - } - - @Override - @Implementation - public final Result get() { - try { - runBackgroundTasks(); - return BackgroundShadowAsyncTask.super.get(); - } catch (Exception e) { - return null; - } - } - - public static void runBackgroundTasks() throws Exception { - sExecutorService - .submit(new Runnable() { - @Override - public void run() { - ShadowApplication.runBackgroundTasks(); - } - }) - .get(); - } -}
diff --git a/base/test/android/junit/src/org/chromium/base/test/asynctask/CustomShadowAsyncTask.java b/base/test/android/junit/src/org/chromium/base/test/asynctask/CustomShadowAsyncTask.java deleted file mode 100644 index e84c84b..0000000 --- a/base/test/android/junit/src/org/chromium/base/test/asynctask/CustomShadowAsyncTask.java +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.base.test.asynctask; - -import org.robolectric.annotation.Implementation; -import org.robolectric.annotation.Implements; - -import org.chromium.base.AsyncTask; - -import java.util.concurrent.Executor; - -/** - * Forces async tasks to execute with the default executor. - * This works around Robolectric not working out of the box with custom executors. - * - * @param <Result> - */ -@Implements(AsyncTask.class) -public class CustomShadowAsyncTask<Result> extends ShadowAsyncTask<Result> { - @Override - @Implementation - public final AsyncTask<Result> executeOnExecutor(Executor executor) { - return super.executeInRobolectric(); - } -}
diff --git a/chrome/VERSION b/chrome/VERSION index a22ee11f..d914e16 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=71 MINOR=0 -BUILD=3560 +BUILD=3561 PATCH=0
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/BackgroundSyncLauncher.java b/chrome/android/java/src/org/chromium/chrome/browser/BackgroundSyncLauncher.java index 480bd45..847bbbe 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/BackgroundSyncLauncher.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/BackgroundSyncLauncher.java
@@ -12,12 +12,12 @@ import com.google.android.gms.gcm.OneoffTask; import com.google.android.gms.gcm.Task; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.externalauth.ExternalAuthUtils; /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeApplication.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeApplication.java index f7ac12b..5d22916 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeApplication.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeApplication.java
@@ -14,7 +14,6 @@ import org.chromium.base.ActivityState; import org.chromium.base.ApplicationState; import org.chromium.base.ApplicationStatus; -import org.chromium.base.AsyncTask; import org.chromium.base.BuildConfig; import org.chromium.base.CommandLineInitUtil; import org.chromium.base.ContextUtils; @@ -27,6 +26,7 @@ import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.memory.MemoryPressureMonitor; import org.chromium.base.multidex.ChromiumMultiDexInstaller; +import org.chromium.base.task.AsyncTask; import org.chromium.build.BuildHooks; import org.chromium.build.BuildHooksAndroid; import org.chromium.build.BuildHooksConfig;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/DefaultBrowserInfo.java b/chrome/android/java/src/org/chromium/chrome/browser/DefaultBrowserInfo.java index 6e81415..2cb5d69 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/DefaultBrowserInfo.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/DefaultBrowserInfo.java
@@ -13,11 +13,11 @@ import android.support.annotation.IntDef; import android.text.TextUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.BuildInfo; import org.chromium.base.ContextUtils; import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.preferences.ChromePreferenceManager; import org.chromium.content_public.browser.BrowserStartupController;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/SSLClientCertificateRequest.java b/chrome/android/java/src/org/chromium/chrome/browser/SSLClientCertificateRequest.java index ea8f6ab..8290cdf 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/SSLClientCertificateRequest.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/SSLClientCertificateRequest.java
@@ -15,11 +15,11 @@ import android.support.v7.app.AlertDialog; import android.util.Log; -import org.chromium.base.AsyncTask; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.ui.base.WindowAndroid;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ShortcutHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/ShortcutHelper.java index eeb4275..ccd5f1d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ShortcutHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ShortcutHelper.java
@@ -29,7 +29,6 @@ import android.util.Base64; import org.chromium.base.ApiCompatibilityUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.CollectionUtil; import org.chromium.base.ContextUtils; import org.chromium.base.Log; @@ -37,6 +36,7 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.task.AsyncTask; import org.chromium.blink_public.platform.WebDisplayMode; import org.chromium.chrome.R; import org.chromium.chrome.browser.webapps.WebApkInfo;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/TtsPlatformImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/TtsPlatformImpl.java index 79d2da43..7ee0d5e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/TtsPlatformImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/TtsPlatformImpl.java
@@ -8,11 +8,11 @@ import android.speech.tts.TextToSpeech; import android.speech.tts.UtteranceProgressListener; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.ThreadUtils; import org.chromium.base.TraceEvent; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.task.AsyncTask; import java.util.ArrayList; import java.util.HashMap;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/WarmupManager.java b/chrome/android/java/src/org/chromium/chrome/browser/WarmupManager.java index 40de0147..7fe8a16 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/WarmupManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/WarmupManager.java
@@ -17,7 +17,6 @@ import android.view.ViewStub; import android.widget.FrameLayout; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.StrictModeContext; import org.chromium.base.SysUtils; @@ -26,6 +25,7 @@ import org.chromium.base.VisibleForTesting; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.net.spdyproxy.DataReductionProxySettings; import org.chromium.chrome.browser.profiles.Profile;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/CardUnmaskPrompt.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/CardUnmaskPrompt.java index bdfde56..08223bc7f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/CardUnmaskPrompt.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/CardUnmaskPrompt.java
@@ -35,8 +35,8 @@ import android.widget.TextView; import org.chromium.base.ApiCompatibilityUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.VisibleForTesting; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.modaldialog.ModalDialogManager;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browseractions/BrowserActionsCustomContextMenuItem.java b/chrome/android/java/src/org/chromium/chrome/browser/browseractions/BrowserActionsCustomContextMenuItem.java index 612c71b..f99c55f7 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/browseractions/BrowserActionsCustomContextMenuItem.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/browseractions/BrowserActionsCustomContextMenuItem.java
@@ -13,9 +13,9 @@ import android.support.customtabs.browseractions.BrowserActionItem; import android.support.customtabs.browseractions.BrowserServiceImageReadTask; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.VisibleForTesting; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.contextmenu.ContextMenuItem; /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browseractions/BrowserActionsTabModelSelector.java b/chrome/android/java/src/org/chromium/chrome/browser/browseractions/BrowserActionsTabModelSelector.java index 910de51..86eb706 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/browseractions/BrowserActionsTabModelSelector.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/browseractions/BrowserActionsTabModelSelector.java
@@ -4,9 +4,9 @@ package org.chromium.chrome.browser.browseractions; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.ThreadUtils; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.browseractions.BrowserActionsTabCreatorManager.BrowserActionsTabCreator; import org.chromium.chrome.browser.tab.Tab;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/cookies/CookiesFetcher.java b/chrome/android/java/src/org/chromium/chrome/browser/cookies/CookiesFetcher.java index 8f71326e..479ba35 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/cookies/CookiesFetcher.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/cookies/CookiesFetcher.java
@@ -4,12 +4,12 @@ package org.chromium.chrome.browser.cookies; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.ImportantFileWriterAndroid; import org.chromium.base.Log; import org.chromium.base.ThreadUtils; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.crypto.CipherFactory; import org.chromium.chrome.browser.profiles.Profile;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/crypto/CipherFactory.java b/chrome/android/java/src/org/chromium/chrome/browser/crypto/CipherFactory.java index 1a16c29d..6e18787 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/crypto/CipherFactory.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/crypto/CipherFactory.java
@@ -7,11 +7,11 @@ import android.annotation.SuppressLint; import android.os.Bundle; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.ObserverList; import org.chromium.base.SecureRandomInitializer; import org.chromium.base.ThreadUtils; +import org.chromium.base.task.AsyncTask; import java.io.IOException; import java.security.GeneralSecurityException;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabTabPersistencePolicy.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabTabPersistencePolicy.java index 39ddba8..4862c02 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabTabPersistencePolicy.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabTabPersistencePolicy.java
@@ -11,11 +11,11 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.ApplicationStatus; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.Log; import org.chromium.base.StreamUtil; import org.chromium.base.ThreadUtils; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.TabState; import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager; import org.chromium.chrome.browser.tabmodel.TabModel;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/RequestThrottler.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/RequestThrottler.java index 608241b..c770faa 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/RequestThrottler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/RequestThrottler.java
@@ -11,8 +11,8 @@ import android.text.TextUtils; import android.util.SparseArray; -import org.chromium.base.AsyncTask; import org.chromium.base.VisibleForTesting; +import org.chromium.base.task.AsyncTask; import java.util.Map; import java.util.concurrent.TimeUnit;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/dynamicmodule/ModuleLoader.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/dynamicmodule/ModuleLoader.java index 53b32ba..c6a3842c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/dynamicmodule/ModuleLoader.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/dynamicmodule/ModuleLoader.java
@@ -12,10 +12,10 @@ import android.os.Process; import android.support.annotation.Nullable; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.Log; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.crash.CrashKeyIndex; import org.chromium.chrome.browser.crash.CrashKeys;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/dependency_injection/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/dependency_injection/OWNERS new file mode 100644 index 0000000..6979d8a --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/dependency_injection/OWNERS
@@ -0,0 +1,3 @@ +peconn@chromium.org + +# OS: Android
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/ChromeDownloadDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/download/ChromeDownloadDelegate.java index 383c42a..3d82779 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/ChromeDownloadDelegate.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/ChromeDownloadDelegate.java
@@ -15,12 +15,12 @@ import android.webkit.MimeTypeMap; import android.webkit.URLUtil; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.ThreadUtils; import org.chromium.base.UserData; import org.chromium.base.UserDataHost; import org.chromium.base.VisibleForTesting; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.UrlConstants; import org.chromium.chrome.browser.tab.Tab; import org.chromium.ui.base.PermissionCallback;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadDirectoryProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadDirectoryProvider.java index a2ef68e..116de62d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadDirectoryProvider.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadDirectoryProvider.java
@@ -12,11 +12,11 @@ import android.os.Environment; import android.os.Handler; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.PathUtils; import org.chromium.base.ThreadUtils; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.download.DirectoryOption.DownloadLocationDirectoryType; import java.io.File;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerDelegate.java index c5dac20..4cf61b1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerDelegate.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerDelegate.java
@@ -14,10 +14,10 @@ import android.support.v4.app.NotificationManagerCompat; import android.text.TextUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.StrictModeContext; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.UrlConstants; import java.io.File;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerService.java b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerService.java index a9808ba..f02b4e3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerService.java
@@ -20,7 +20,6 @@ import android.util.Pair; import org.chromium.base.ApiCompatibilityUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.Log; @@ -30,6 +29,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.download.DownloadMetrics.DownloadOpenSource;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/OMADownloadHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/download/OMADownloadHandler.java index bf3ff50d..b35fbc1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/OMADownloadHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/OMADownloadHandler.java
@@ -33,9 +33,9 @@ import org.xmlpull.v1.XmlPullParserFactory; import org.chromium.base.ApplicationStatus; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.VisibleForTesting; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.content.ContentUtils; import org.chromium.chrome.download.R;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/home/glue/FileDeletionQueue.java b/chrome/android/java/src/org/chromium/chrome/browser/download/home/glue/FileDeletionQueue.java index b66ab3d..cf02a61 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/home/glue/FileDeletionQueue.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/home/glue/FileDeletionQueue.java
@@ -6,9 +6,9 @@ import android.support.annotation.VisibleForTesting; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.FileUtils; +import org.chromium.base.task.AsyncTask; import java.io.File; import java.util.LinkedList;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/CalendarFactory.java b/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/CalendarFactory.java index 70e62a6a..df15f2b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/CalendarFactory.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/CalendarFactory.java
@@ -4,7 +4,7 @@ package org.chromium.chrome.browser.download.home.list; -import org.chromium.base.AsyncTask; +import org.chromium.base.task.AsyncTask; import java.util.Calendar; import java.util.concurrent.ExecutionException;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/view/AutoAnimatorDrawable.java b/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/view/AutoAnimatorDrawable.java new file mode 100644 index 0000000..8e6a351 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/view/AutoAnimatorDrawable.java
@@ -0,0 +1,37 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.download.home.list.view; + +import android.graphics.drawable.Drawable; +import android.support.v7.graphics.drawable.DrawableWrapper; + +/** + * A helper {@link Drawable} that wraps another {@link Drawable} and starts/stops any + * {@link Animatable} {@link Drawable}s in the {@link Drawable} hierarchy when this {@link Drawable} + * is shown or hidden. + */ +public class AutoAnimatorDrawable extends DrawableWrapper { + // Since Drawables default visible to true by default, we might not get a change and start the + // animation on the first visibility request. + private boolean mGotVisibilityCall; + + public AutoAnimatorDrawable(Drawable drawable) { + super(drawable); + } + + // DrawableWrapper implementation. + @Override + public boolean setVisible(boolean visible, boolean restart) { + boolean changed = super.setVisible(visible, restart); + if (visible) { + if (changed || restart || !mGotVisibilityCall) UiUtils.startAnimatedDrawables(this); + } else { + UiUtils.stopAnimatedDrawables(this); + } + + mGotVisibilityCall = true; + return changed; + } +} \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/view/CircularProgressView.java b/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/view/CircularProgressView.java index f9558c8..498f324 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/view/CircularProgressView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/view/CircularProgressView.java
@@ -6,15 +6,13 @@ import android.content.Context; import android.content.res.TypedArray; -import android.graphics.drawable.Animatable; +import android.graphics.Canvas; import android.graphics.drawable.Drawable; -import android.support.annotation.DrawableRes; import android.support.annotation.IntDef; import android.support.annotation.StringRes; -import android.support.annotation.StyleableRes; -import android.support.v7.content.res.AppCompatResources; import android.support.v7.widget.AppCompatImageButton; import android.util.AttributeSet; +import android.view.View; import org.chromium.chrome.browser.util.MathUtils; import org.chromium.chrome.download.R; @@ -29,8 +27,8 @@ * The determinate {@link Drawable} will have it's level set via {@link Drawable#setLevel(int)} * based on the progress (0 - 10,000). * - * The indeterminate {@link Drawable} supports {@link Animatable} drawables and the animation will - * be started/stopped when shown/hidden respectively. + * The indeterminate and determinate {@link Drawable}s support {@link Animatable} drawables and the + * animation will be started/stopped when shown/hidden respectively. */ public class CircularProgressView extends AppCompatImageButton { /** @@ -61,9 +59,7 @@ private final Drawable mPauseButtonSrc; private final Drawable mRetryButtonSrc; - // Tracking this here as the API {@link View#getForeground()} is not available in all supported - // Android versions. - private Drawable mForegroundDrawable; + private final ForegroundDrawableCompat mForegroundHelper; /** * Creates an instance of a {@link CircularProgressView}. @@ -73,22 +69,24 @@ public CircularProgressView(Context context, AttributeSet attrs) { super(context, attrs); - TypedArray types = - context.obtainStyledAttributes(attrs, R.styleable.CircularProgressView, 0, 0); - try { - mIndeterminateProgress = getDrawable( - context, types, R.styleable.CircularProgressView_indeterminateProgress); - mDeterminateProgress = getDrawable( - context, types, R.styleable.CircularProgressView_determinateProgress); - mResumeButtonSrc = - getDrawable(context, types, R.styleable.CircularProgressView_resumeSrc); - mPauseButtonSrc = - getDrawable(context, types, R.styleable.CircularProgressView_pauseSrc); - mRetryButtonSrc = - getDrawable(context, types, R.styleable.CircularProgressView_retrySrc); - } finally { - types.recycle(); - } + mForegroundHelper = new ForegroundDrawableCompat(this); + + TypedArray types = attrs == null + ? null + : context.obtainStyledAttributes(attrs, R.styleable.CircularProgressView, 0, 0); + + mIndeterminateProgress = UiUtils.autoAnimateDrawable(UiUtils.getDrawable( + context, types, R.styleable.CircularProgressView_indeterminateProgress)); + mDeterminateProgress = UiUtils.autoAnimateDrawable(UiUtils.getDrawable( + context, types, R.styleable.CircularProgressView_determinateProgress)); + mResumeButtonSrc = + UiUtils.getDrawable(context, types, R.styleable.CircularProgressView_resumeSrc); + mPauseButtonSrc = + UiUtils.getDrawable(context, types, R.styleable.CircularProgressView_pauseSrc); + mRetryButtonSrc = + UiUtils.getDrawable(context, types, R.styleable.CircularProgressView_retrySrc); + + types.recycle(); } /** @@ -101,21 +99,13 @@ */ public void setProgress(int progress) { if (progress == INDETERMINATE) { - if (mForegroundDrawable != mIndeterminateProgress) { - setForeground(mIndeterminateProgress); - if (mIndeterminateProgress instanceof Animatable) { - ((Animatable) mIndeterminateProgress).start(); - } + if (mForegroundHelper.getDrawable() != mIndeterminateProgress) { + mForegroundHelper.setDrawable(mIndeterminateProgress); } } else { progress = MathUtils.clamp(progress, 0, 100); mDeterminateProgress.setLevel(progress * MAX_LEVEL / 100); - setForeground(mDeterminateProgress); - } - - // Stop any animation that might have previously been running. - if (mForegroundDrawable != mIndeterminateProgress) { - ((Animatable) mIndeterminateProgress).stop(); + mForegroundHelper.setDrawable(mDeterminateProgress); } } @@ -150,16 +140,25 @@ // View implementation. @Override - public void setForeground(Drawable foreground) { - mForegroundDrawable = foreground; - super.setForeground(foreground); + public void draw(Canvas canvas) { + super.draw(canvas); + mForegroundHelper.draw(canvas); } - private static final Drawable getDrawable( - Context context, TypedArray attrs, @StyleableRes int attrId) { - @DrawableRes - int resId = attrs.getResourceId(attrId, -1); - if (resId == -1) return null; - return AppCompatResources.getDrawable(context, resId); + @Override + protected void onVisibilityChanged(View changedView, int visibility) { + super.onVisibilityChanged(changedView, visibility); + mForegroundHelper.onVisibilityChanged(changedView, visibility); } -} \ No newline at end of file + + @Override + protected void drawableStateChanged() { + super.drawableStateChanged(); + mForegroundHelper.drawableStateChanged(); + } + + @Override + protected boolean verifyDrawable(Drawable dr) { + return super.verifyDrawable(dr) || mForegroundHelper.verifyDrawable(dr); + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/view/ForegroundDrawableCompat.java b/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/view/ForegroundDrawableCompat.java new file mode 100644 index 0000000..d88946f --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/view/ForegroundDrawableCompat.java
@@ -0,0 +1,190 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.download.home.list.view; + +import android.graphics.Canvas; +import android.graphics.drawable.Drawable; +import android.support.v4.graphics.drawable.DrawableCompat; +import android.support.v4.view.ViewCompat; +import android.view.View; +import android.view.View.OnAttachStateChangeListener; +import android.view.View.OnLayoutChangeListener; +import android.view.ViewGroup; +import android.view.ViewParent; + +/** + * A helper class to simulate {@link View#getForeground()} on older versions of Android. This class + * requires specific setup to work properly. The following methods must be overridden and forwarded + * from the underly {@link View}: + * + * 1) {@link View#draw(Canvas)}. + * 2) {@link View#onVisibilityChanged(View,boolean)} + * 3) {@link View#drawableStateChanged()}. + * 4) {@link View#verifyDrawable(Drawable)}. + * + * Here is a rough example of how to use this below to extend an ImageView (replace with any View): + * + * public class ForegroundEnabledView extends ImageView { + * private final ForegroundDrawableCompat mCompat; + * + * public class ForegroundEnabledView(Context context) { + * super(context); + * mCompat = new ForegroundDrawableCompat(this); + * } + * + * public void someHelperMethod(Drawable drawable) { + * mCompat.setDrawable(drawable); + * } + * + * // ImageView implementation. + * @Override + * public void draw(Canvas canvas) { + * super.draw(canvas); + * + * // It is important to make sure the foreground drawable draws *after* other view content. + * mCompat.draw(canvas); + * } + * + * @Override + * protected void onVisibilityChanged(View changedView, int visibility) { + * super.onVisibilityChanged(changedView, visibility); + * mCompat.onVisibilityChanged(changedView, visibility); + * } + * + * @Override + * protected void drawableStateChanged() { + * super.drawableStateChanged(); + * mCompat.drawableStateChanged(); + * } + * + * @Override + * protected boolean verifyDrawable(Drawable dr) { + * return super.verifyDrawable(dr) || mCompat.verifyDrawable(dr); + * } + * } + */ +public class ForegroundDrawableCompat + implements OnAttachStateChangeListener, OnLayoutChangeListener { + private final View mView; + + private boolean mOnBoundsChanged; + private Drawable mDrawable; + + /** + * Builds a {@link ForegroundDrawableCompat} around {@code View}. This will enable setting a + * {@link Drawable} to draw on top of {@link View} at draw time. + * @param view The {@link View} to add foreground {@link Drawable} support to. + */ + public ForegroundDrawableCompat(View view) { + mView = view; + mView.addOnAttachStateChangeListener(this); + mView.addOnLayoutChangeListener(this); + } + + /** + * Sets {@code drawable} to draw on top of the {@link View}. + * @param drawable The {@link Drawable} to set as a foreground {@link Drawable} on the + * {@link View}. + */ + public void setDrawable(Drawable drawable) { + if (mDrawable == drawable) return; + + if (mDrawable != null) { + if (ViewCompat.isAttachedToWindow(mView)) mDrawable.setVisible(false, false); + mDrawable.setCallback(null); + mView.unscheduleDrawable(mDrawable); + mDrawable = null; + } + + mDrawable = drawable; + + if (mDrawable != null) { + mOnBoundsChanged = true; + + DrawableCompat.setLayoutDirection(mDrawable, ViewCompat.getLayoutDirection(mView)); + if (mDrawable.isStateful()) mDrawable.setState(mView.getDrawableState()); + + // TODO(dtrainor): Support tint? + + if (ViewCompat.isAttachedToWindow(mView)) { + mDrawable.setVisible( + mView.getWindowVisibility() == View.VISIBLE && mView.isShown(), false); + } + mDrawable.setCallback(mView); + } + mView.requestLayout(); + mView.invalidate(); + } + + /** @return The currently set foreground {@link Drawable}. */ + public Drawable getDrawable() { + return mDrawable; + } + + /** Meant to be called from {@link View#onDraw(Canvas)}. */ + public void draw(Canvas canvas) { + if (mDrawable == null) return; + + if (mOnBoundsChanged) { + mOnBoundsChanged = false; + mDrawable.setBounds(0, 0, mView.getWidth(), mView.getHeight()); + } + + mDrawable.draw(canvas); + } + + /** Meant to be called from {@link View#onVisibilityChanged(View,visibility)}. */ + public void onVisibilityChanged(View view, int visibility) { + if (mView != view || mDrawable == null) return; + + ViewParent parent = mView.getParent(); + boolean parentVisible = parent != null + && (!(parent instanceof ViewGroup) || ((ViewGroup) parent).isShown()); + + if (parentVisible && mView.getWindowVisibility() == View.VISIBLE) { + mDrawable.setVisible(visibility == View.VISIBLE, false); + } + } + + /** Meant to be called from {@link View#drawableStateChanged()}. */ + public void drawableStateChanged() { + if (mDrawable == null) return; + if (mDrawable.setState(mView.getDrawableState())) mView.invalidate(); + } + + /** Meant to be called from {@link View#verifyDrawable(Drawable)}. */ + public boolean verifyDrawable(Drawable drawable) { + return drawable != null && mDrawable == drawable; + } + + // OnAttachStateChangeListener implementation. + @Override + public void onViewAttachedToWindow(View v) { + if (mView.isShown() && mView.getWindowVisibility() != View.GONE) { + mDrawable.setVisible(mView.getVisibility() == View.VISIBLE, false); + } + } + + @Override + public void onViewDetachedFromWindow(View v) { + if (mView.isShown() && mView.getWindowVisibility() != View.GONE) { + mDrawable.setVisible(false, false); + } + } + + // OnLayoutChangeListener implementation. + @Override + public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, + int oldTop, int oldRight, int oldBottom) { + if (mDrawable == null) return; + + int width = right - left; + int height = bottom - top; + + if (width != mDrawable.getBounds().width() || height != mDrawable.getBounds().height()) { + mOnBoundsChanged = true; + } + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/view/UiUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/view/UiUtils.java new file mode 100644 index 0000000..992c0be2 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/home/list/view/UiUtils.java
@@ -0,0 +1,116 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.download.home.list.view; + +import android.annotation.TargetApi; +import android.content.Context; +import android.content.res.TypedArray; +import android.graphics.drawable.Animatable; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.DrawableWrapper; +import android.graphics.drawable.InsetDrawable; +import android.graphics.drawable.LayerDrawable; +import android.graphics.drawable.RotateDrawable; +import android.graphics.drawable.ScaleDrawable; +import android.os.Build; +import android.support.annotation.DrawableRes; +import android.support.annotation.Nullable; +import android.support.annotation.StyleableRes; +import android.support.v7.content.res.AppCompatResources; + +import org.chromium.base.Callback; + +/** A set of helper methods to make interacting with the Android UI easier. */ +public final class UiUtils { + private UiUtils() {} + + /** + * Loads a {@link Drawable} from an attribute. Uses {@link AppCompatResources} to support all + * modern {@link Drawable} types. + * @return A new {@link Drawable} or {@code null} if the attribute wasn't set. + */ + public static @Nullable Drawable getDrawable( + Context context, @Nullable TypedArray attrs, @StyleableRes int attrId) { + if (attrs == null) return null; + + @DrawableRes + int resId = attrs.getResourceId(attrId, -1); + if (resId == -1) return null; + return UiUtils.getDrawable(context, resId); + } + + /** + * Loads a {@link Drawable} from a resource Id. Uses {@link AppCompatResources} to support all + * modern {@link Drawable} types. + * @return A new {@link Drawable}. + */ + public static Drawable getDrawable(Context context, @DrawableRes int resId) { + return AppCompatResources.getDrawable(context, resId); + } + + /** + * Wraps {@code drawable} in a {@link AutoAnimatorDrawable}. + * @return A wrapped {@code Drawable} or {@code null} if {@code drawable} is null. + */ + public static @Nullable Drawable autoAnimateDrawable(@Nullable Drawable drawable) { + return drawable == null ? null : new AutoAnimatorDrawable(drawable); + } + + /** + * Recursively searches {@code drawable} for all {@link Animatable} instances and starts them. + * @param drawable The {@link Drawable} to start animating. + */ + public static void startAnimatedDrawables(@Nullable Drawable drawable) { + animatedDrawableHelper(drawable, animatable -> animatable.start()); + } + + /** + * Recursively searches {@code drawable} for all {@link Animatable} instances and stops them. + * @param drawable The {@link Drawable} to stop animating. + */ + public static void stopAnimatedDrawables(@Nullable Drawable drawable) { + animatedDrawableHelper(drawable, animatable -> animatable.stop()); + } + + @TargetApi(Build.VERSION_CODES.KITKAT) + private static void animatedDrawableHelper( + @Nullable Drawable drawable, Callback<Animatable> consumer) { + if (drawable == null) return; + + if (drawable instanceof Animatable) { + consumer.onResult((Animatable) drawable); + + // Assume Animatable drawables can handle animating their own internals/sub drawables. + return; + } + + if (drawable != drawable.getCurrent()) { + // Check obvious cases where the current drawable isn't actually being shown. This + // should support all {@link DrawableContainer} instances. + UiUtils.animatedDrawableHelper(drawable.getCurrent(), consumer); + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && drawable instanceof DrawableWrapper) { + // Support all modern versions of drawables that wrap other ones. This won't cover old + // versions of Android (see below for other if/else blocks). + animatedDrawableHelper(((DrawableWrapper) drawable).getDrawable(), consumer); + } else if (drawable instanceof LayerDrawable) { + LayerDrawable layerDrawable = (LayerDrawable) drawable; + for (int i = 0; i < layerDrawable.getNumberOfLayers(); i++) { + animatedDrawableHelper(layerDrawable.getDrawable(i), consumer); + } + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT + && drawable instanceof InsetDrawable) { + // Support legacy versions of InsetDrawable. + animatedDrawableHelper(((InsetDrawable) drawable).getDrawable(), consumer); + } else if (drawable instanceof RotateDrawable) { + // Support legacy versions of RotateDrawable. + animatedDrawableHelper(((RotateDrawable) drawable).getDrawable(), consumer); + } else if (drawable instanceof ScaleDrawable) { + // Support legacy versions of ScaleDrawable. + animatedDrawableHelper(((ScaleDrawable) drawable).getDrawable(), consumer); + } + } +} \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/home/storage/StorageSummaryProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/download/home/storage/StorageSummaryProvider.java index 11eb8dfd..77ce198 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/home/storage/StorageSummaryProvider.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/home/storage/StorageSummaryProvider.java
@@ -8,7 +8,7 @@ import android.os.Environment; import android.support.annotation.Nullable; -import org.chromium.base.AsyncTask; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.download.DirectoryOption; import org.chromium.chrome.browser.download.DownloadUtils;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/ui/DownloadManagerUi.java b/chrome/android/java/src/org/chromium/chrome/browser/download/ui/DownloadManagerUi.java index 33c0514..0fd0768 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/ui/DownloadManagerUi.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/ui/DownloadManagerUi.java
@@ -17,7 +17,6 @@ import android.view.View; import android.view.ViewGroup; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.CollectionUtil; import org.chromium.base.DiscardableReferencePool; @@ -27,6 +26,7 @@ import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.ChromeApplication; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.download.DirectoryOption;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/ui/SpaceDisplay.java b/chrome/android/java/src/org/chromium/chrome/browser/download/ui/SpaceDisplay.java index 7b29159..2e7122d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/ui/SpaceDisplay.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/ui/SpaceDisplay.java
@@ -14,13 +14,13 @@ import android.widget.TextView; import org.chromium.base.ApiCompatibilityUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.ObserverList; import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.download.DownloadUtils; import org.chromium.chrome.browser.widget.MaterialProgressBar; import org.chromium.chrome.download.R;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/externalnav/IntentWithGesturesHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/externalnav/IntentWithGesturesHandler.java index 8de7d09..c5a58e2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/externalnav/IntentWithGesturesHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/externalnav/IntentWithGesturesHandler.java
@@ -7,9 +7,9 @@ import android.annotation.SuppressLint; import android.content.Intent; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.SecureRandomInitializer; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.IntentHandler; import org.chromium.chrome.browser.util.IntentUtils;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/feedback/AsyncFeedbackSourceAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/feedback/AsyncFeedbackSourceAdapter.java index c695374f..a9abfe8d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/feedback/AsyncFeedbackSourceAdapter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/feedback/AsyncFeedbackSourceAdapter.java
@@ -6,9 +6,9 @@ import android.content.Context; -import org.chromium.base.AsyncTask; -import org.chromium.base.AsyncTask.Status; import org.chromium.base.ContextUtils; +import org.chromium.base.task.AsyncTask; +import org.chromium.base.task.AsyncTask.Status; import java.util.concurrent.ExecutionException;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/feedback/ConnectivityChecker.java b/chrome/android/java/src/org/chromium/chrome/browser/feedback/ConnectivityChecker.java index c953584..a76758e1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/feedback/ConnectivityChecker.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/feedback/ConnectivityChecker.java
@@ -4,12 +4,12 @@ package org.chromium.chrome.browser.feedback; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.profiles.Profile; import java.io.IOException;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/incognito/IncognitoDisclosureActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/incognito/IncognitoDisclosureActivity.java index 5135e9eb..4aa8c59a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/incognito/IncognitoDisclosureActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/incognito/IncognitoDisclosureActivity.java
@@ -12,7 +12,7 @@ import android.view.View; import android.widget.CheckBox; -import org.chromium.base.AsyncTask; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.modaldialog.AppModalPresenter; import org.chromium.chrome.browser.modaldialog.ModalDialogManager;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/infobar/DuplicateDownloadInfoBar.java b/chrome/android/java/src/org/chromium/chrome/browser/infobar/DuplicateDownloadInfoBar.java index 6f786f4..96a34ec 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/infobar/DuplicateDownloadInfoBar.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/infobar/DuplicateDownloadInfoBar.java
@@ -16,9 +16,9 @@ import android.view.View; import android.webkit.MimeTypeMap; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.download.DownloadManagerService; import org.chromium.chrome.browser.download.DownloadMetrics;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/init/AsyncInitTaskRunner.java b/chrome/android/java/src/org/chromium/chrome/browser/init/AsyncInitTaskRunner.java index ed1f856..61f8055 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/init/AsyncInitTaskRunner.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/init/AsyncInitTaskRunner.java
@@ -4,7 +4,6 @@ package org.chromium.chrome.browser.init; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.ThreadUtils; @@ -12,6 +11,7 @@ import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.library_loader.ProcessInitException; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.ChromeActivitySessionTracker; import org.chromium.chrome.browser.ChromeVersionInfo; import org.chromium.components.variations.firstrun.VariationsSeedFetcher;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java b/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java index 0a18b45..47e4b45a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java
@@ -15,7 +15,6 @@ import org.chromium.base.ActivityState; import org.chromium.base.ApplicationStatus; import org.chromium.base.ApplicationStatus.ActivityStateListener; -import org.chromium.base.AsyncTask; import org.chromium.base.CommandLine; import org.chromium.base.ContentUriUtils; import org.chromium.base.ContextUtils; @@ -29,6 +28,7 @@ import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.memory.MemoryPressureUma; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.AppHooks; import org.chromium.chrome.browser.ChromeApplication; import org.chromium.chrome.browser.ChromeStrictMode;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/init/ProcessInitializationHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/init/ProcessInitializationHandler.java index 7e0f2d1..03c3333 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/init/ProcessInitializationHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/init/ProcessInitializationHandler.java
@@ -19,7 +19,6 @@ import com.google.ipc.invalidation.external.client.android.service.AndroidLogger; import org.chromium.base.ApiCompatibilityUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.CommandLine; import org.chromium.base.ContextUtils; import org.chromium.base.Log; @@ -28,6 +27,7 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.TraceEvent; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.build.BuildHooksAndroid; import org.chromium.chrome.R; import org.chromium.chrome.browser.AfterStartupTaskUtils;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/installedapp/InstalledAppProviderImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/installedapp/InstalledAppProviderImpl.java index bcbfe08..df09423 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/installedapp/InstalledAppProviderImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/installedapp/InstalledAppProviderImpl.java
@@ -15,10 +15,10 @@ import org.json.JSONException; import org.json.JSONObject; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.instantapps.InstantAppsHandler; import org.chromium.installedapp.mojom.InstalledAppProvider; import org.chromium.installedapp.mojom.RelatedApplication;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/invalidation/DelayedInvalidationsController.java b/chrome/android/java/src/org/chromium/chrome/browser/invalidation/DelayedInvalidationsController.java index 4430f2f..879abd6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/invalidation/DelayedInvalidationsController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/invalidation/DelayedInvalidationsController.java
@@ -11,10 +11,10 @@ import android.support.v4.util.ObjectsCompat; import org.chromium.base.ApplicationStatus; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; +import org.chromium.base.task.AsyncTask; import org.chromium.components.invalidation.PendingInvalidation; import org.chromium.components.signin.AccountManagerFacade; import org.chromium.components.sync.AndroidSyncSettings;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/invalidation/InvalidationController.java b/chrome/android/java/src/org/chromium/chrome/browser/invalidation/InvalidationController.java index 9d237792..513c3bdf 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/invalidation/InvalidationController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/invalidation/InvalidationController.java
@@ -14,10 +14,10 @@ import org.chromium.base.ApplicationState; import org.chromium.base.ApplicationStatus; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.sync.ProfileSyncService; import org.chromium.components.invalidation.InvalidationClientService;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/MediaViewerUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/media/MediaViewerUtils.java index a4bd6118..588d078 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/MediaViewerUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/MediaViewerUtils.java
@@ -21,8 +21,8 @@ import android.text.TextUtils; import org.chromium.base.ApiCompatibilityUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.IntentHandler;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/remote/DefaultMediaRouteController.java b/chrome/android/java/src/org/chromium/chrome/browser/media/remote/DefaultMediaRouteController.java index b026b26..f4c246e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/remote/DefaultMediaRouteController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/remote/DefaultMediaRouteController.java
@@ -24,10 +24,10 @@ import org.chromium.base.ApplicationState; import org.chromium.base.ApplicationStatus; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.annotations.RemovableInRelease; import org.chromium.base.annotations.UsedByReflection; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.UrlConstants; import org.chromium.chrome.browser.media.remote.RemoteVideoInfo.PlayerState;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/remote/MediaUrlResolver.java b/chrome/android/java/src/org/chromium/chrome/browser/media/remote/MediaUrlResolver.java index 13958d5..ff91142 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/remote/MediaUrlResolver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/remote/MediaUrlResolver.java
@@ -8,10 +8,10 @@ import android.support.annotation.IntDef; import android.text.TextUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import java.io.IOException; import java.lang.annotation.Retention;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/metrics/UmaSessionStats.java b/chrome/android/java/src/org/chromium/chrome/browser/metrics/UmaSessionStats.java index bc39e47..170e527 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/metrics/UmaSessionStats.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/metrics/UmaSessionStats.java
@@ -9,8 +9,8 @@ import android.content.res.Configuration; import android.text.TextUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.DefaultBrowserInfo; import org.chromium.chrome.browser.instantapps.InstantAppsHandler; import org.chromium.chrome.browser.preferences.privacy.PrivacyPreferencesManager;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/metrics/WebApkUma.java b/chrome/android/java/src/org/chromium/chrome/browser/metrics/WebApkUma.java index 0176649..163d3fb 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/metrics/WebApkUma.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/metrics/WebApkUma.java
@@ -13,9 +13,9 @@ import android.support.annotation.IntDef; import android.text.TextUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.util.ConversionUtils; import org.chromium.chrome.browser.webapps.WebApkInfo;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtils.java index 9894ca2..323c931 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtils.java
@@ -13,12 +13,12 @@ import org.chromium.base.ActivityState; import org.chromium.base.ApplicationStatus; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ChromeFeatureList;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/evaluation/OfflinePageEvaluationBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/evaluation/OfflinePageEvaluationBridge.java index 8a185d6..59cbb1eb 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/evaluation/OfflinePageEvaluationBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/evaluation/OfflinePageEvaluationBridge.java
@@ -4,13 +4,13 @@ package org.chromium.chrome.browser.offlinepages.evaluation; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.Log; import org.chromium.base.ObserverList; import org.chromium.base.ThreadUtils; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.offlinepages.ClientId; import org.chromium.chrome.browser.offlinepages.OfflinePageItem; import org.chromium.chrome.browser.offlinepages.SavePageRequest;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/indicator/ConnectivityDetector.java b/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/indicator/ConnectivityDetector.java index 5c7e794..e64097ed 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/indicator/ConnectivityDetector.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/indicator/ConnectivityDetector.java
@@ -14,12 +14,12 @@ import android.os.SystemClock; import android.support.annotation.IntDef; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.content.ContentUtils; import org.chromium.net.ConnectionType;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omaha/OmahaService.java b/chrome/android/java/src/org/chromium/chrome/browser/omaha/OmahaService.java index 78d4671..61f8903 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omaha/OmahaService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omaha/OmahaService.java
@@ -11,10 +11,10 @@ import android.os.Build; import android.support.annotation.Nullable; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.ThreadUtils; +import org.chromium.base.task.AsyncTask; import org.chromium.components.background_task_scheduler.BackgroundTask; import org.chromium.components.background_task_scheduler.BackgroundTaskSchedulerFactory; import org.chromium.components.background_task_scheduler.TaskIds;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omaha/UpdateMenuItemHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/omaha/UpdateMenuItemHelper.java index 52997d8..ba10a86 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omaha/UpdateMenuItemHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omaha/UpdateMenuItemHelper.java
@@ -23,11 +23,11 @@ import com.google.android.gms.common.GooglePlayServicesUtil; -import org.chromium.base.AsyncTask; import org.chromium.base.CommandLine; import org.chromium.base.Log; import org.chromium.base.ThreadUtils; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ChromeSwitches;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/geo/VisibleNetworksTracker.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/geo/VisibleNetworksTracker.java index 9933ebc..5e6ee71a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/geo/VisibleNetworksTracker.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/geo/VisibleNetworksTracker.java
@@ -7,10 +7,10 @@ import android.content.Context; import android.os.SystemClock; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; +import org.chromium.base.task.AsyncTask; import javax.annotation.Nullable;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/partnerbookmarks/PartnerBookmarksReader.java b/chrome/android/java/src/org/chromium/chrome/browser/partnerbookmarks/PartnerBookmarksReader.java index cc21bdb..6fc7f5a6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/partnerbookmarks/PartnerBookmarksReader.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/partnerbookmarks/PartnerBookmarksReader.java
@@ -6,10 +6,10 @@ import android.content.Context; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.AppHooks; import org.chromium.chrome.browser.util.ViewUtils;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/partnercustomizations/PartnerBrowserCustomizations.java b/chrome/android/java/src/org/chromium/chrome/browser/partnercustomizations/PartnerBrowserCustomizations.java index 1ebb9a3..f9518e8 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/partnercustomizations/PartnerBrowserCustomizations.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/partnercustomizations/PartnerBrowserCustomizations.java
@@ -12,13 +12,13 @@ import android.support.annotation.Nullable; import android.text.TextUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.CommandLine; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.AppHooks; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.ChromeVersionInfo;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/CardEditor.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/CardEditor.java index eb9c445..a1945c1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/CardEditor.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/CardEditor.java
@@ -12,8 +12,8 @@ import android.util.Pair; import org.chromium.base.ApiCompatibilityUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.autofill.CardType;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/BitmapScalerTask.java b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/BitmapScalerTask.java index b51bb70..4487fa0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/BitmapScalerTask.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/BitmapScalerTask.java
@@ -8,9 +8,9 @@ import android.os.SystemClock; import android.util.LruCache; -import org.chromium.base.AsyncTask; import org.chromium.base.ThreadUtils; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import java.util.concurrent.TimeUnit;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/FileEnumWorkerTask.java b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/FileEnumWorkerTask.java index 957d7f0..9d2a83e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/FileEnumWorkerTask.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/FileEnumWorkerTask.java
@@ -9,8 +9,8 @@ import android.os.Environment; import android.provider.MediaStore; -import org.chromium.base.AsyncTask; import org.chromium.base.ThreadUtils; +import org.chromium.base.task.AsyncTask; import org.chromium.ui.base.WindowAndroid; import java.io.File;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerBitmapViewHolder.java b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerBitmapViewHolder.java index ef22a284..92425a4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerBitmapViewHolder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerBitmapViewHolder.java
@@ -10,8 +10,8 @@ import android.support.v7.widget.RecyclerView.ViewHolder; import android.text.TextUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import java.util.List;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerCategoryView.java b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerCategoryView.java index 9eca081..2bc0c5d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerCategoryView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerCategoryView.java
@@ -18,10 +18,10 @@ import android.widget.Button; import android.widget.RelativeLayout; -import org.chromium.base.AsyncTask; import org.chromium.base.DiscardableReferencePool.DiscardableReference; import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.util.ConversionUtils;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/services/AccountsChangedReceiver.java b/chrome/android/java/src/org/chromium/chrome/browser/services/AccountsChangedReceiver.java index 3cfbbd27..8f12335 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/services/AccountsChangedReceiver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/services/AccountsChangedReceiver.java
@@ -10,10 +10,10 @@ import android.content.Intent; import org.chromium.base.ApplicationStatus; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.ThreadUtils; import org.chromium.base.library_loader.ProcessInitException; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.ChromeApplication; import org.chromium.chrome.browser.init.BrowserParts; import org.chromium.chrome.browser.init.ChromeBrowserInitializer;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/services/gcm/InvalidationGcmUpstreamSender.java b/chrome/android/java/src/org/chromium/chrome/browser/services/gcm/InvalidationGcmUpstreamSender.java index 7c78050..8cd3ad0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/services/gcm/InvalidationGcmUpstreamSender.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/services/gcm/InvalidationGcmUpstreamSender.java
@@ -15,9 +15,9 @@ import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.ipc.invalidation.ticl.android2.channel.GcmUpstreamSenderService; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.ThreadUtils; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.init.ProcessInitializationHandler; import org.chromium.chrome.browser.signin.OAuth2TokenService; import org.chromium.components.signin.AccountManagerFacade;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/share/OptionalShareTargetsManager.java b/chrome/android/java/src/org/chromium/chrome/browser/share/OptionalShareTargetsManager.java index bf58586a..10b59022 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/share/OptionalShareTargetsManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/share/OptionalShareTargetsManager.java
@@ -12,9 +12,9 @@ import org.chromium.base.ActivityState; import org.chromium.base.ApplicationStatus; import org.chromium.base.ApplicationStatus.ActivityStateListener; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.ThreadUtils; +import org.chromium.base.task.AsyncTask; import java.util.ArrayList; import java.util.Collections;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/share/ShareHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/share/ShareHelper.java index e449900..b696f50 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/share/ShareHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/share/ShareHelper.java
@@ -37,7 +37,6 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.ApplicationState; import org.chromium.base.ApplicationStatus; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.Log; @@ -45,6 +44,7 @@ import org.chromium.base.StrictModeContext; import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.CachedMetrics; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.content_public.browser.WebContents; import org.chromium.ui.UiUtils;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java index 53b109b..828d4c2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java
@@ -21,10 +21,10 @@ import android.widget.ImageView; import android.widget.TextView; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.consent_auditor.ConsentAuditorFeature; import org.chromium.chrome.browser.externalauth.UserRecoverableErrorHandler;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountTrackerService.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountTrackerService.java index 175acbe..1345ff7 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountTrackerService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountTrackerService.java
@@ -6,12 +6,12 @@ import android.support.annotation.IntDef; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.ObserverList; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.task.AsyncTask; import org.chromium.components.signin.AccountIdProvider; import org.chromium.components.signin.AccountManagerFacade; import org.chromium.components.signin.AccountsChangeObserver;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/OAuth2TokenService.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/OAuth2TokenService.java index aa55ba98..13f7555 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/OAuth2TokenService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/OAuth2TokenService.java
@@ -304,19 +304,6 @@ return true; } - /** - * Triggers a notification to all observers of the native and Java instance of the - * OAuth2TokenService that a refresh token is now available. This may cause observers to retry - * operations that require authentication. - */ - @VisibleForTesting - public void fireRefreshTokenAvailable(Account account) { - ThreadUtils.assertOnUiThread(); - assert account != null; - nativeFireRefreshTokenAvailableFromJava( - mNativeOAuth2TokenServiceDelegateAndroid, account.name); - } - @CalledByNative private void notifyRefreshTokenAvailable(String accountName) { assert accountName != null; @@ -326,18 +313,6 @@ } } - /** - * Triggers a notification to all observers of the native and Java instance of the - * OAuth2TokenService that a refresh token is now revoked. - */ - @VisibleForTesting - public void fireRefreshTokenRevoked(Account account) { - ThreadUtils.assertOnUiThread(); - assert account != null; - nativeFireRefreshTokenRevokedFromJava( - mNativeOAuth2TokenServiceDelegateAndroid, account.name); - } - @CalledByNative public void notifyRefreshTokenRevoked(String accountName) { assert accountName != null; @@ -347,16 +322,6 @@ } } - /** - * Triggers a notification to all observers of the native and Java instance of the - * OAuth2TokenService that all refresh tokens now have been loaded. - */ - @VisibleForTesting - public void fireRefreshTokensLoaded() { - ThreadUtils.assertOnUiThread(); - nativeFireRefreshTokensLoadedFromJava(mNativeOAuth2TokenServiceDelegateAndroid); - } - @CalledByNative public void notifyRefreshTokensLoaded() { for (OAuth2TokenServiceObserver observer : mObservers) { @@ -382,10 +347,4 @@ String authToken, boolean isTransientError, long nativeCallback); private native void nativeValidateAccounts(long nativeOAuth2TokenServiceDelegateAndroid, String currentlySignedInAccount, boolean forceNotifications); - private native void nativeFireRefreshTokenAvailableFromJava( - long nativeOAuth2TokenServiceDelegateAndroid, String accountName); - private native void nativeFireRefreshTokenRevokedFromJava( - long nativeOAuth2TokenServiceDelegateAndroid, String accountName); - private native void nativeFireRefreshTokensLoadedFromJava( - long nativeOAuth2TokenServiceDelegateAndroid); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninFragmentBase.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninFragmentBase.java index 8010f64d..2df8e7d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninFragmentBase.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninFragmentBase.java
@@ -26,10 +26,10 @@ import android.view.ViewGroup; import android.widget.TextView; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.consent_auditor.ConsentAuditorFeature; import org.chromium.chrome.browser.externalauth.UserRecoverableErrorHandler;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninHelper.java index 201fc14..32efc84 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninHelper.java
@@ -12,10 +12,10 @@ import com.google.android.gms.auth.GoogleAuthException; import com.google.android.gms.auth.GoogleAuthUtil; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.invalidation.InvalidationServiceFactory; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.signin.SigninManager.SignInCallback;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/TileRenderer.java b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/TileRenderer.java index ed513b6e..3251907 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/TileRenderer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/TileRenderer.java
@@ -16,9 +16,9 @@ import android.view.ViewGroup; import org.chromium.base.ApiCompatibilityUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.favicon.IconType; import org.chromium.chrome.browser.favicon.LargeIconBridge;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/survey/ChromeSurveyController.java b/chrome/android/java/src/org/chromium/chrome/browser/survey/ChromeSurveyController.java index b7de6fb..3124e19 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/survey/ChromeSurveyController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/survey/ChromeSurveyController.java
@@ -11,12 +11,12 @@ import android.support.annotation.VisibleForTesting; import android.text.TextUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.CommandLine; import org.chromium.base.ContextUtils; import org.chromium.base.ThreadUtils; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ChromeSwitches;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/DocumentModeAssassin.java b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/DocumentModeAssassin.java index f98a811..c474b9f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/DocumentModeAssassin.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/DocumentModeAssassin.java
@@ -11,7 +11,6 @@ import android.os.StrictMode; import android.util.Pair; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.FileUtils; import org.chromium.base.Log; @@ -19,6 +18,7 @@ import org.chromium.base.StreamUtil; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.TabState; import org.chromium.chrome.browser.document.DocumentActivity; import org.chromium.chrome.browser.document.DocumentUtils;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabPersistentStore.java b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabPersistentStore.java index c8c0f06..5072d65 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabPersistentStore.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabPersistentStore.java
@@ -15,7 +15,6 @@ import android.util.SparseBooleanArray; import android.util.SparseIntArray; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.Log; @@ -26,6 +25,7 @@ import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.RecordUserAction; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.TabState; import org.chromium.chrome.browser.UrlConstants; import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabbedModeTabPersistencePolicy.java b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabbedModeTabPersistencePolicy.java index 59e41d3..c5111e3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabbedModeTabPersistencePolicy.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabbedModeTabPersistencePolicy.java
@@ -10,7 +10,6 @@ import android.util.Pair; import android.util.SparseBooleanArray; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.Log; @@ -20,6 +19,7 @@ import org.chromium.base.VisibleForTesting; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.TabState; import org.chromium.chrome.browser.browseractions.BrowserActionsTabModelSelector; import org.chromium.chrome.browser.browseractions.BrowserActionsTabPersistencePolicy;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/document/StorageDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/document/StorageDelegate.java index 8f07fbd..caf0bd98 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/document/StorageDelegate.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/document/StorageDelegate.java
@@ -7,10 +7,10 @@ import android.content.Context; import android.util.SparseArray; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.StreamUtil; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.TabState; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabmodel.TabPersister;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/upgrade/PackageReplacedBroadcastReceiver.java b/chrome/android/java/src/org/chromium/chrome/browser/upgrade/PackageReplacedBroadcastReceiver.java index c8abad2d..3fc4e4f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/upgrade/PackageReplacedBroadcastReceiver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/upgrade/PackageReplacedBroadcastReceiver.java
@@ -9,7 +9,7 @@ import android.content.Intent; import android.os.Build; -import org.chromium.base.AsyncTask; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.notifications.channels.ChannelsUpdater; /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/vr/VrShellDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/vr/VrShellDelegate.java index 3eb7e96..b280427 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/vr/VrShellDelegate.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/vr/VrShellDelegate.java
@@ -40,7 +40,6 @@ import org.chromium.base.ActivityState; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.ApplicationStatus; -import org.chromium.base.AsyncTask; import org.chromium.base.CollectionUtil; import org.chromium.base.ContextUtils; import org.chromium.base.Log; @@ -51,6 +50,7 @@ import org.chromium.base.annotations.JNINamespace; import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.metrics.RecordUserAction; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.ApplicationLifetime; import org.chromium.chrome.browser.ChromeActivity;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkInstaller.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkInstaller.java index 04b1fee..ec090e1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkInstaller.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkInstaller.java
@@ -7,10 +7,10 @@ import android.content.pm.PackageManager; import android.graphics.Bitmap; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.AppHooks; import org.chromium.chrome.browser.banners.InstallerDelegate; import org.chromium.chrome.browser.metrics.WebApkUma;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappAuthenticator.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappAuthenticator.java index 7b73386..fe8cfcc1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappAuthenticator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappAuthenticator.java
@@ -11,9 +11,9 @@ import android.util.Log; import org.chromium.base.ApiCompatibilityUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.SecureRandomInitializer; import org.chromium.base.metrics.CachedMetrics.TimesHistogramSample; +import org.chromium.base.task.AsyncTask; import java.io.File; import java.io.FileInputStream;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappDataStorage.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappDataStorage.java index b396966..6704ec23 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappDataStorage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappDataStorage.java
@@ -11,10 +11,10 @@ import android.support.annotation.Nullable; import android.text.TextUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; +import org.chromium.base.task.AsyncTask; import org.chromium.blink_public.platform.WebDisplayMode; import org.chromium.chrome.browser.ShortcutHelper; import org.chromium.chrome.browser.ShortcutSource;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappDirectoryManager.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappDirectoryManager.java index b344d53d..26939b6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappDirectoryManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappDirectoryManager.java
@@ -15,12 +15,12 @@ import android.os.SystemClock; import android.text.TextUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.FileUtils; import org.chromium.base.Log; import org.chromium.base.PathUtils; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.document.DocumentUtils; import org.chromium.chrome.browser.metrics.WebApkUma;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappRegistry.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappRegistry.java index 65473c57..5170c19 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappRegistry.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappRegistry.java
@@ -9,10 +9,10 @@ import android.content.pm.PackageManager; import android.text.TextUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.banners.InstallerDelegate; import org.chromium.chrome.browser.browsing_data.UrlFilter; import org.chromium.chrome.browser.browsing_data.UrlFilterBridge;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/DateDividedAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/widget/DateDividedAdapter.java index 7a733c8..3ac4193 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/DateDividedAdapter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/widget/DateDividedAdapter.java
@@ -15,8 +15,8 @@ import android.view.ViewGroup; import android.widget.TextView; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.download.DownloadUtils; import org.chromium.chrome.browser.download.home.list.UiUtils;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/ThumbnailDiskStorage.java b/chrome/android/java/src/org/chromium/chrome/browser/widget/ThumbnailDiskStorage.java index 4036c74..ef4b878 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/ThumbnailDiskStorage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/widget/ThumbnailDiskStorage.java
@@ -15,12 +15,12 @@ import com.google.protobuf.ByteString; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.StreamUtil; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; +import org.chromium.base.task.AsyncTask; import org.chromium.chrome.browser.util.ConversionUtils; import org.chromium.chrome.browser.widget.ThumbnailCacheEntry.ContentId; import org.chromium.chrome.browser.widget.ThumbnailCacheEntry.ThumbnailEntry;
diff --git a/chrome/android/java_sources.gni b/chrome/android/java_sources.gni index 3116d93..362ed3d 100644 --- a/chrome/android/java_sources.gni +++ b/chrome/android/java_sources.gni
@@ -517,7 +517,10 @@ "java/src/org/chromium/chrome/browser/download/home/list/holder/SeparatorViewHolder.java", "java/src/org/chromium/chrome/browser/download/home/list/holder/ThumbnailAwareViewHolder.java", "java/src/org/chromium/chrome/browser/download/home/list/holder/VideoViewHolder.java", + "java/src/org/chromium/chrome/browser/download/home/list/view/AutoAnimatorDrawable.java", "java/src/org/chromium/chrome/browser/download/home/list/view/CircularProgressView.java", + "java/src/org/chromium/chrome/browser/download/home/list/view/ForegroundDrawableCompat.java", + "java/src/org/chromium/chrome/browser/download/home/list/view/UiUtils.java", "java/src/org/chromium/chrome/browser/download/home/list/ListProperties.java", "java/src/org/chromium/chrome/browser/download/home/list/ListPropertyViewBinder.java", "java/src/org/chromium/chrome/browser/download/home/list/ListUtils.java",
diff --git a/chrome/android/javatests/OWNERS b/chrome/android/javatests/OWNERS index 26bbc141..5ad28baa 100644 --- a/chrome/android/javatests/OWNERS +++ b/chrome/android/javatests/OWNERS
@@ -1,8 +1,7 @@ -dtrainor@chromium.org -nyquist@chromium.org +file://chrome/android/OWNERS + +peconn@chromium.org skyostil@chromium.org -tedchoc@chromium.org -yfriedman@chromium.org # COMPONENT: Test>Android # OS: Android
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/ShareIntentTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/ShareIntentTest.java index 76978efc..281eb9d2 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/ShareIntentTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/ShareIntentTest.java
@@ -17,8 +17,8 @@ import org.junit.Test; import org.junit.runner.RunWith; -import org.chromium.base.AsyncTask; import org.chromium.base.ThreadUtils; +import org.chromium.base.task.AsyncTask; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.RetryOnFailure; import org.chromium.chrome.browser.share.ShareHelper;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabTabPersistencePolicyTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabTabPersistencePolicyTest.java index 92b8e79f..4c9520b 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabTabPersistencePolicyTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabTabPersistencePolicyTest.java
@@ -20,11 +20,11 @@ import org.chromium.base.ActivityState; import org.chromium.base.ApplicationStatus; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.StreamUtil; import org.chromium.base.ThreadUtils; +import org.chromium.base.task.AsyncTask; import org.chromium.base.test.util.AdvancedMockContext; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.Feature;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/photo_picker/PhotoPickerDialogTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/photo_picker/PhotoPickerDialogTest.java index fa10c22..20e7241 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/photo_picker/PhotoPickerDialogTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/photo_picker/PhotoPickerDialogTest.java
@@ -20,7 +20,6 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.CommandLineFlags; -import org.chromium.base.test.util.DisabledTest; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ChromeSwitches; @@ -198,12 +197,7 @@ }); } - /** - * Continues to be flaky on bots which doesn't reproduce on local devices, - * continuing to investigate offline. - */ @Test - @DisabledTest(message = "crbug.com/761060") @LargeTest public void testNoSelection() throws Throwable { createDialog(false, Arrays.asList("image/*")); // Multi-select = false. @@ -220,12 +214,7 @@ dismissDialog(); } - /** - * Continues to be flaky on bots which doesn't reproduce on local devices, - * continuing to investigate offline. - */ @Test - @DisabledTest(message = "crbug.com/761060") @LargeTest public void testSingleSelectionPhoto() throws Throwable { createDialog(false, Arrays.asList("image/*")); // Multi-select = false. @@ -245,12 +234,7 @@ dismissDialog(); } - /** - * Continues to be flaky on bots which doesn't reproduce on local devices, - * continuing to investigate offline. - */ @Test - @DisabledTest(message = "crbug.com/761060") @LargeTest public void testMultiSelectionPhoto() throws Throwable { createDialog(true, Arrays.asList("image/*")); // Multi-select = true.
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/OAuth2TokenServiceIntegrationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/OAuth2TokenServiceIntegrationTest.java index 93fe697b..7c5e890a 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/OAuth2TokenServiceIntegrationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/OAuth2TokenServiceIntegrationTest.java
@@ -17,7 +17,6 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.test.BaseJUnit4ClassRunner; -import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.RetryOnFailure; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.test.util.ApplicationData; @@ -126,86 +125,6 @@ @Test @MediumTest - @Feature({"Sync"}) - public void testFireRefreshTokenAvailableNotifiesJavaObservers() { - ThreadUtils.runOnUiThreadBlocking(() -> { - // Adding an observer should not lead to a callback. - Assert.assertEquals(0, mObserver.getAvailableCallCount()); - - // An observer should be called with the correct account. - mOAuth2TokenService.fireRefreshTokenAvailable(TEST_ACCOUNT1); - Assert.assertEquals(1, mObserver.getAvailableCallCount()); - Assert.assertEquals(TEST_ACCOUNT1, mObserver.getLastAccount()); - - // When mOAuth2TokenService, an observer should not be called. - mOAuth2TokenService.removeObserver(mObserver); - mOAuth2TokenService.fireRefreshTokenAvailable(TEST_ACCOUNT1); - Assert.assertEquals(1, mObserver.getAvailableCallCount()); - - // No other observer interface method should ever have been called. - Assert.assertEquals(0, mObserver.getRevokedCallCount()); - Assert.assertEquals(0, mObserver.getLoadedCallCount()); - }); - } - - @Test - @MediumTest - @Feature({"Sync"}) - public void testFireRefreshTokenRevokedNotifiesJavaObservers() { - ThreadUtils.runOnUiThreadBlocking(() -> { - // Adding an observer should not lead to a callback. - Assert.assertEquals(0, mObserver.getRevokedCallCount()); - - // First seed the account state (some native classes make the assumption that - // a notification that a token was revoked for a given account was preceded by a - // notification that that account was available). - mOAuth2TokenService.fireRefreshTokenAvailable(TEST_ACCOUNT1); - mOAuth2TokenService.fireRefreshTokenAvailable(TEST_ACCOUNT2); - - Assert.assertEquals(2, mObserver.getAvailableCallCount()); - - // An observer should be called with the correct account. - mOAuth2TokenService.fireRefreshTokenRevoked(TEST_ACCOUNT1); - Assert.assertEquals(1, mObserver.getRevokedCallCount()); - Assert.assertEquals(TEST_ACCOUNT1, mObserver.getLastAccount()); - - // When removed, an observer should not be called. - mOAuth2TokenService.removeObserver(mObserver); - mOAuth2TokenService.fireRefreshTokenRevoked(TEST_ACCOUNT2); - Assert.assertEquals(1, mObserver.getRevokedCallCount()); - - // No other observer interface method should have been called after the initial seeding - // of the accounts. - Assert.assertEquals(2, mObserver.getAvailableCallCount()); - Assert.assertEquals(0, mObserver.getLoadedCallCount()); - }); - } - - @Test - @MediumTest - @Feature({"Sync"}) - public void testFireRefreshTokensLoadedNotifiesJavaObservers() { - ThreadUtils.runOnUiThreadBlocking(() -> { - // Adding an observer should not lead to a callback. - Assert.assertEquals(0, mObserver.getLoadedCallCount()); - - // An observer should be called with the correct account. - mOAuth2TokenService.fireRefreshTokensLoaded(); - Assert.assertEquals(1, mObserver.getLoadedCallCount()); - - // When removed, an observer should not be called. - mOAuth2TokenService.removeObserver(mObserver); - mOAuth2TokenService.fireRefreshTokensLoaded(); - Assert.assertEquals(1, mObserver.getLoadedCallCount()); - - // No other observer interface method should ever have been called. - Assert.assertEquals(0, mObserver.getAvailableCallCount()); - Assert.assertEquals(0, mObserver.getRevokedCallCount()); - }); - } - - @Test - @MediumTest public void testValidateAccountsNoAccountsRegisteredAndNoSignedInUser() { ThreadUtils.runOnUiThreadBlocking(() -> { // Run test.
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabPersistentStoreTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabPersistentStoreTest.java index d5448efc..ad575bd 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabPersistentStoreTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabPersistentStoreTest.java
@@ -19,9 +19,9 @@ import org.junit.runner.RunWith; import org.chromium.base.ActivityState; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.ThreadUtils; +import org.chromium.base.task.AsyncTask; import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.util.AdvancedMockContext; import org.chromium.base.test.util.CallbackHelper;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/util/ChromeFileProviderTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/util/ChromeFileProviderTest.java index 3ffecca..8f6a1fd0 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/util/ChromeFileProviderTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/util/ChromeFileProviderTest.java
@@ -16,7 +16,7 @@ import org.junit.Test; import org.junit.runner.RunWith; -import org.chromium.base.AsyncTask; +import org.chromium.base.task.AsyncTask; import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.content_public.browser.test.NativeLibraryTestRule;
diff --git a/chrome/android/junit/OWNERS b/chrome/android/junit/OWNERS new file mode 100644 index 0000000..4af0f7a5 --- /dev/null +++ b/chrome/android/junit/OWNERS
@@ -0,0 +1,6 @@ +file://chrome/android/OWNERS + +peconn@chromium.org + +# COMPONENT: Test>Android +# OS: Android
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/AccessorySheetControllerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/AccessorySheetControllerTest.java index 1ad568c..595aa4a8 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/AccessorySheetControllerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/AccessorySheetControllerTest.java
@@ -29,8 +29,8 @@ import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.test.ShadowRecordHistogram; +import org.chromium.base.task.test.CustomShadowAsyncTask; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.base.test.asynctask.CustomShadowAsyncTask; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.Tab; import org.chromium.chrome.browser.modelutil.ListObservable; import org.chromium.chrome.browser.modelutil.PropertyKey; @@ -244,4 +244,4 @@ return RecordHistogram.getHistogramValueCountForTesting( KeyboardAccessoryMetricsRecorder.UMA_KEYBOARD_ACCESSORY_SHEET_TRIGGERED, bucket); } -} \ No newline at end of file +}
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryControllerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryControllerTest.java index 09da1a1d..0e29385c 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryControllerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryControllerTest.java
@@ -30,8 +30,8 @@ import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.test.ShadowRecordHistogram; +import org.chromium.base.task.test.CustomShadowAsyncTask; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.base.test.asynctask.CustomShadowAsyncTask; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.Action; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.PropertyProvider; import org.chromium.chrome.browser.modelutil.ListObservable; @@ -446,4 +446,4 @@ return RecordHistogram.getHistogramValueCountForTesting( KeyboardAccessoryMetricsRecorder.UMA_KEYBOARD_ACCESSORY_BAR_SHOWN, bucket); } -} \ No newline at end of file +}
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetControllerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetControllerTest.java index b3b6593..bb0b7ced 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetControllerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetControllerTest.java
@@ -24,8 +24,8 @@ import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.test.ShadowRecordHistogram; +import org.chromium.base.task.test.CustomShadowAsyncTask; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.base.test.asynctask.CustomShadowAsyncTask; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.Item; import org.chromium.chrome.browser.modelutil.ListModel; import org.chromium.chrome.browser.modelutil.ListObservable; @@ -158,4 +158,4 @@ type), sample); } -} \ No newline at end of file +}
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/init/AsyncInitTaskRunnerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/init/AsyncInitTaskRunnerTest.java index 1e3313ffe..1d460d5e 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/init/AsyncInitTaskRunnerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/init/AsyncInitTaskRunnerTest.java
@@ -25,8 +25,8 @@ import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.library_loader.LoaderErrors; import org.chromium.base.library_loader.ProcessInitException; +import org.chromium.base.task.test.ShadowAsyncTask; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.base.test.asynctask.ShadowAsyncTask; import org.chromium.components.variations.firstrun.VariationsSeedFetcher; import java.util.concurrent.CountDownLatch;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/installedapp/InstalledAppProviderTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/installedapp/InstalledAppProviderTest.java index b15861f..46c8198 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/installedapp/InstalledAppProviderTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/installedapp/InstalledAppProviderTest.java
@@ -23,8 +23,8 @@ import org.robolectric.shadows.ShadowPackageManager; import org.chromium.base.ThreadUtils; +import org.chromium.base.task.test.CustomShadowAsyncTask; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.base.test.asynctask.CustomShadowAsyncTask; import org.chromium.base.test.util.Feature; import org.chromium.chrome.browser.instantapps.InstantAppsHandler; import org.chromium.installedapp.mojom.InstalledAppProvider;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/invalidation/InvalidationControllerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/invalidation/InvalidationControllerTest.java index 1f3e5d6..0faaa968 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/invalidation/InvalidationControllerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/invalidation/InvalidationControllerTest.java
@@ -27,8 +27,8 @@ import org.chromium.base.ApplicationState; import org.chromium.base.ApplicationStatus; import org.chromium.base.CollectionUtil; +import org.chromium.base.task.test.CustomShadowAsyncTask; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.base.test.asynctask.CustomShadowAsyncTask; import org.chromium.base.test.util.Feature; import org.chromium.chrome.browser.sync.ProfileSyncService; import org.chromium.components.signin.AccountManagerFacade;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/media/remote/MediaUrlResolverTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/media/remote/MediaUrlResolverTest.java index 99f188a..f32584d 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/media/remote/MediaUrlResolverTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/media/remote/MediaUrlResolverTest.java
@@ -18,10 +18,10 @@ import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowApplication; -import org.chromium.base.AsyncTask; import org.chromium.base.CommandLine; +import org.chromium.base.task.AsyncTask; +import org.chromium.base.task.test.CustomShadowAsyncTask; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.base.test.asynctask.CustomShadowAsyncTask; import java.io.IOException; import java.net.HttpURLConnection;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/ntp/cards/NewTabPageAdapterTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/ntp/cards/NewTabPageAdapterTest.java index e2544b2..c8da9be 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/ntp/cards/NewTabPageAdapterTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/ntp/cards/NewTabPageAdapterTest.java
@@ -50,8 +50,8 @@ import org.robolectric.shadows.ShadowResources; import org.chromium.base.Callback; +import org.chromium.base.task.test.CustomShadowAsyncTask; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.base.test.asynctask.CustomShadowAsyncTask; import org.chromium.base.test.util.Feature; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/geo/VisibleNetworksTrackerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/geo/VisibleNetworksTrackerTest.java index c5285f0..228fed86 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/geo/VisibleNetworksTrackerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/omnibox/geo/VisibleNetworksTrackerTest.java
@@ -20,8 +20,8 @@ import org.robolectric.shadows.ShadowSystemClock; import org.chromium.base.ThreadUtils; +import org.chromium.base.task.test.CustomShadowAsyncTask; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.base.test.asynctask.CustomShadowAsyncTask; import org.chromium.chrome.browser.omnibox.geo.VisibleNetworks.VisibleCell; import org.chromium.chrome.browser.omnibox.geo.VisibleNetworks.VisibleWifi; import org.chromium.chrome.browser.omnibox.geo.VisibleNetworksTrackerTest.ShadowPlatformNetworksManager;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebApkUpdateManagerUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebApkUpdateManagerUnitTest.java index f1bbc5d..4392f7c 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebApkUpdateManagerUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebApkUpdateManagerUnitTest.java
@@ -30,8 +30,8 @@ import org.chromium.base.Callback; import org.chromium.base.CommandLine; import org.chromium.base.PathUtils; +import org.chromium.base.task.test.CustomShadowAsyncTask; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.base.test.asynctask.CustomShadowAsyncTask; import org.chromium.blink_public.platform.WebDisplayMode; import org.chromium.chrome.browser.ShortcutHelper; import org.chromium.chrome.browser.tab.Tab;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappDataStorageTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappDataStorageTest.java index 9306c80..6eef41563 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappDataStorageTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappDataStorageTest.java
@@ -22,8 +22,8 @@ import org.robolectric.shadows.ShadowLooper; import org.chromium.base.ContextUtils; +import org.chromium.base.task.test.BackgroundShadowAsyncTask; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.base.test.asynctask.BackgroundShadowAsyncTask; import org.chromium.base.test.util.Feature; import org.chromium.blink_public.platform.WebDisplayMode; import org.chromium.chrome.browser.ShortcutHelper;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappDirectoryManagerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappDirectoryManagerTest.java index 0882f66..950c93b 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappDirectoryManagerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappDirectoryManagerTest.java
@@ -25,8 +25,8 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.test.ShadowRecordHistogram; +import org.chromium.base.task.test.CustomShadowAsyncTask; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.base.test.asynctask.CustomShadowAsyncTask; import org.chromium.base.test.util.Feature; import org.chromium.webapk.lib.common.WebApkConstants;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappRegistryTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappRegistryTest.java index 51343e06..6c9fb2a 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappRegistryTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebappRegistryTest.java
@@ -23,8 +23,8 @@ import org.robolectric.shadows.ShadowLooper; import org.chromium.base.ContextUtils; +import org.chromium.base.task.test.BackgroundShadowAsyncTask; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.base.test.asynctask.BackgroundShadowAsyncTask; import org.chromium.base.test.util.Feature; import org.chromium.chrome.browser.ShortcutHelper; import org.chromium.chrome.browser.browsing_data.UrlFilters;
diff --git a/chrome/android/webapk/libs/client/DEPS b/chrome/android/webapk/libs/client/DEPS index 01ebe73e..e8c747b 100644 --- a/chrome/android/webapk/libs/client/DEPS +++ b/chrome/android/webapk/libs/client/DEPS
@@ -1,5 +1,6 @@ include_rules = [ "+base/android/java/src/org/chromium/base/annotations", - "+base/test/android/junit/src/org/chromium/base/test/asynctask", + "+base/test/android/junit/src/org/chromium/base/task/test", + "+base/android/java/src/org/chromium/base/task", "+chrome/android/webapk/libs/common", ]
diff --git a/chrome/android/webapk/libs/client/junit/src/org/chromium/webapk/lib/client/WebApkIdentityServiceClientTest.java b/chrome/android/webapk/libs/client/junit/src/org/chromium/webapk/lib/client/WebApkIdentityServiceClientTest.java index 778c7560..c93ccc6 100644 --- a/chrome/android/webapk/libs/client/junit/src/org/chromium/webapk/lib/client/WebApkIdentityServiceClientTest.java +++ b/chrome/android/webapk/libs/client/junit/src/org/chromium/webapk/lib/client/WebApkIdentityServiceClientTest.java
@@ -19,7 +19,7 @@ import org.robolectric.shadows.ShadowApplication; import org.robolectric.shadows.ShadowLooper; -import org.chromium.base.test.asynctask.CustomShadowAsyncTask; +import org.chromium.base.task.test.CustomShadowAsyncTask; import org.chromium.testing.local.LocalRobolectricTestRunner; import org.chromium.webapk.lib.common.WebApkMetaDataKeys; import org.chromium.webapk.lib.common.identity_service.IIdentityService;
diff --git a/chrome/android/webapk/libs/client/junit/src/org/chromium/webapk/lib/client/WebApkServiceConnectionManagerTest.java b/chrome/android/webapk/libs/client/junit/src/org/chromium/webapk/lib/client/WebApkServiceConnectionManagerTest.java index 4a486bf..5bd69631 100644 --- a/chrome/android/webapk/libs/client/junit/src/org/chromium/webapk/lib/client/WebApkServiceConnectionManagerTest.java +++ b/chrome/android/webapk/libs/client/junit/src/org/chromium/webapk/lib/client/WebApkServiceConnectionManagerTest.java
@@ -21,7 +21,7 @@ import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowApplication; -import org.chromium.base.test.asynctask.CustomShadowAsyncTask; +import org.chromium.base.task.test.CustomShadowAsyncTask; import org.chromium.testing.local.LocalRobolectricTestRunner; /**
diff --git a/chrome/android/webapk/libs/client/src/org/chromium/webapk/lib/client/WebApkServiceConnectionManager.java b/chrome/android/webapk/libs/client/src/org/chromium/webapk/lib/client/WebApkServiceConnectionManager.java index c8a48ad..6bc42ac 100644 --- a/chrome/android/webapk/libs/client/src/org/chromium/webapk/lib/client/WebApkServiceConnectionManager.java +++ b/chrome/android/webapk/libs/client/src/org/chromium/webapk/lib/client/WebApkServiceConnectionManager.java
@@ -12,7 +12,7 @@ import android.os.IBinder; import android.util.Log; -import org.chromium.base.AsyncTask; +import org.chromium.base.task.AsyncTask; import java.util.ArrayList; import java.util.HashMap;
diff --git a/chrome/app/chromeos_strings.grdp b/chrome/app/chromeos_strings.grdp index c8a74c4..d820b42 100644 --- a/chrome/app/chromeos_strings.grdp +++ b/chrome/app/chromeos_strings.grdp
@@ -4240,4 +4240,8 @@ <message name="IDS_POWER_SOURCE_PORT_UNKNOWN" desc="The text referring to the device to charge from, when its port location cannot be determined."> USB-C device </message> + + <message name="IDS_SMB_SHARES_ADD_SERVICE_MENU_OPTION" desc="The text displayed in the files app Add New Services menu for the option that allows users to mount a new SMB file share."> + SMB file share + </message> </grit-part>
diff --git a/chrome/app/theme/default_100_percent/common/webauthn/error.png b/chrome/app/theme/default_100_percent/common/webauthn/error.png index 9e91c940..9dfd404 100644 --- a/chrome/app/theme/default_100_percent/common/webauthn/error.png +++ b/chrome/app/theme/default_100_percent/common/webauthn/error.png Binary files differ
diff --git a/chrome/app/theme/default_100_percent/common/webauthn/welcome.png b/chrome/app/theme/default_100_percent/common/webauthn/welcome.png index 70c8023..3942673 100644 --- a/chrome/app/theme/default_100_percent/common/webauthn/welcome.png +++ b/chrome/app/theme/default_100_percent/common/webauthn/welcome.png Binary files differ
diff --git a/chrome/app/theme/default_200_percent/common/webauthn/error.png b/chrome/app/theme/default_200_percent/common/webauthn/error.png index 28a7c9a..d0fdea1 100644 --- a/chrome/app/theme/default_200_percent/common/webauthn/error.png +++ b/chrome/app/theme/default_200_percent/common/webauthn/error.png Binary files differ
diff --git a/chrome/app/theme/default_200_percent/common/webauthn/welcome.png b/chrome/app/theme/default_200_percent/common/webauthn/welcome.png index 77680d3..0636120 100644 --- a/chrome/app/theme/default_200_percent/common/webauthn/welcome.png +++ b/chrome/app/theme/default_200_percent/common/webauthn/welcome.png Binary files differ
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 66472af..395567e 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -1303,12 +1303,17 @@ const FeatureEntry::FeatureParam kAutofillDropdownLayoutTrailingIcon[] = { {autofill::kAutofillDropdownLayoutParameterName, autofill::kAutofillDropdownLayoutParameterTrailingIcon}}; +const FeatureEntry::FeatureParam kAutofillDropdownLayoutTwoLinesLeadingIcon[] = + {{autofill::kAutofillDropdownLayoutParameterName, + autofill::kAutofillDropdownLayoutParameterTwoLinesLeadingIcon}}; const FeatureEntry::FeatureVariation kAutofillDropdownLayoutVariations[] = { {"(leading icon)", kAutofillDropdownLayoutLeadingIcon, base::size(kAutofillDropdownLayoutLeadingIcon), nullptr}, {"(trailing icon)", kAutofillDropdownLayoutTrailingIcon, - base::size(kAutofillDropdownLayoutTrailingIcon), nullptr}}; + base::size(kAutofillDropdownLayoutLeadingIcon), nullptr}, + {"(two line leading icon)", kAutofillDropdownLayoutTwoLinesLeadingIcon, + base::size(kAutofillDropdownLayoutTwoLinesLeadingIcon), nullptr}}; #endif // !defined(OS_ANDROID) #if defined(OS_ANDROID) @@ -3889,12 +3894,6 @@ FEATURE_VALUE_TYPE(printing::features::kUsePdfCompositorServiceForPrint)}, #endif -#if defined(OS_MACOSX) - {"mac-views-autofill-popup", flag_descriptions::kMacViewsAutofillPopupName, - flag_descriptions::kMacViewsAutofillPopupDescription, kOsMac, - FEATURE_VALUE_TYPE(autofill::features::kMacViewsAutofillPopup)}, -#endif // OS_MACOSX - {"autofill-dynamic-forms", flag_descriptions::kAutofillDynamicFormsName, flag_descriptions::kAutofillDynamicFormsDescription, kOsAll, FEATURE_VALUE_TYPE(autofill::features::kAutofillDynamicForms)},
diff --git a/chrome/browser/android/compositor/layer/tab_layer.cc b/chrome/browser/android/compositor/layer/tab_layer.cc index 09370553..6559adf 100644 --- a/chrome/browser/android/compositor/layer/tab_layer.cc +++ b/chrome/browser/android/compositor/layer/tab_layer.cc
@@ -489,7 +489,7 @@ transform.Translate(toolbar_position.x(), toolbar_position.y()); toolbar_layer_->layer()->SetTransformOrigin(gfx::Point3F(0.f, 0.f, 0.f)); toolbar_layer_->layer()->SetTransform(transform); - toolbar_layer_->layer()->SetOpacity(toolbar_alpha); + toolbar_layer_->SetOpacity(toolbar_alpha); toolbar_layer_->layer()->SetMasksToBounds( toolbar_layer_->layer()->bounds() != toolbar_size);
diff --git a/chrome/browser/android/compositor/layer/toolbar_layer.cc b/chrome/browser/android/compositor/layer/toolbar_layer.cc index 9cefae2..90dbb2a 100644 --- a/chrome/browser/android/compositor/layer/toolbar_layer.cc +++ b/chrome/browser/android/compositor/layer/toolbar_layer.cc
@@ -157,6 +157,14 @@ } } +void ToolbarLayer::SetOpacity(float opacity) { + toolbar_background_layer_->SetOpacity(opacity); + url_bar_background_layer_->SetOpacity(opacity); + bitmap_layer_->SetOpacity(opacity); + progress_bar_layer_->SetOpacity(opacity); + progress_bar_background_layer_->SetOpacity(opacity); +} + ToolbarLayer::ToolbarLayer(ui::ResourceManager* resource_manager) : resource_manager_(resource_manager), layer_(cc::Layer::Create()),
diff --git a/chrome/browser/android/compositor/layer/toolbar_layer.h b/chrome/browser/android/compositor/layer/toolbar_layer.h index 8dfb6d8..7b00464 100644 --- a/chrome/browser/android/compositor/layer/toolbar_layer.h +++ b/chrome/browser/android/compositor/layer/toolbar_layer.h
@@ -51,6 +51,8 @@ int progress_bar_background_height, int progress_bar_background_color); + void SetOpacity(float opacity); + protected: explicit ToolbarLayer(ui::ResourceManager* resource_manager); ~ToolbarLayer() override;
diff --git a/chrome/browser/certificate_manager_model.cc b/chrome/browser/certificate_manager_model.cc index dec4539..d4f1a57f 100644 --- a/chrome/browser/certificate_manager_model.cc +++ b/chrome/browser/certificate_manager_model.cc
@@ -34,9 +34,9 @@ #include "chrome/browser/chromeos/certificate_provider/certificate_provider.h" #include "chrome/browser/chromeos/certificate_provider/certificate_provider_service.h" #include "chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.h" -#include "chrome/browser/chromeos/policy/policy_certificate_provider.h" #include "chrome/browser/chromeos/policy/user_network_configuration_updater.h" #include "chrome/browser/chromeos/policy/user_network_configuration_updater_factory.h" +#include "chromeos/policy_certificate_provider.h" #endif using content::BrowserThread; @@ -270,7 +270,7 @@ #if defined(OS_CHROMEOS) // Provides certificates installed through enterprise policy. class CertsSourcePolicy : public CertificateManagerModel::CertsSource, - policy::PolicyCertificateProvider::Observer { + chromeos::PolicyCertificateProvider::Observer { public: // Defines which policy-provided certificates this CertsSourcePolicy instance // should yield. @@ -284,7 +284,7 @@ }; CertsSourcePolicy(base::RepeatingClosure certs_source_updated_callback, - policy::PolicyCertificateProvider* policy_certs_provider, + chromeos::PolicyCertificateProvider* policy_certs_provider, Mode mode) : CertsSource(certs_source_updated_callback), policy_certs_provider_(policy_certs_provider), @@ -296,7 +296,7 @@ policy_certs_provider_->RemovePolicyProvidedCertsObserver(this); } - // policy::PolicyCertificateProvider::Observer + // chromeos::PolicyCertificateProvider::Observer void OnPolicyProvidedCertsChanged( const net::CertificateList& all_server_and_authority_certs, const net::CertificateList& web_trusted_certs) override { @@ -361,7 +361,7 @@ SetCertInfos(std::move(cert_infos)); } - policy::PolicyCertificateProvider* policy_certs_provider_; + chromeos::PolicyCertificateProvider* policy_certs_provider_; Mode mode_; DISALLOW_COPY_AND_ASSIGN(CertsSourcePolicy);
diff --git a/chrome/browser/certificate_manager_model.h b/chrome/browser/certificate_manager_model.h index 119a46c6..cb296a2 100644 --- a/chrome/browser/certificate_manager_model.h +++ b/chrome/browser/certificate_manager_model.h
@@ -25,9 +25,6 @@ #if defined(OS_CHROMEOS) namespace chromeos { class CertificateProvider; -} - -namespace policy { class PolicyCertificateProvider; } #endif @@ -108,7 +105,7 @@ struct Params { #if defined(OS_CHROMEOS) // May be nullptr. - policy::PolicyCertificateProvider* policy_certs_provider = nullptr; + chromeos::PolicyCertificateProvider* policy_certs_provider = nullptr; // May be nullptr. std::unique_ptr<chromeos::CertificateProvider> extension_certificate_provider;
diff --git a/chrome/browser/certificate_manager_model_unittest.cc b/chrome/browser/certificate_manager_model_unittest.cc index 59ca003..1bf0a86 100644 --- a/chrome/browser/certificate_manager_model_unittest.cc +++ b/chrome/browser/certificate_manager_model_unittest.cc
@@ -18,7 +18,7 @@ #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/certificate_provider/certificate_provider.h" -#include "chrome/browser/chromeos/policy/policy_certificate_provider.h" +#include "chromeos/policy_certificate_provider.h" #endif namespace { @@ -191,7 +191,8 @@ #if defined(OS_CHROMEOS) namespace { -class FakePolicyCertificateProvider : public policy::PolicyCertificateProvider { +class FakePolicyCertificateProvider + : public chromeos::PolicyCertificateProvider { public: void AddPolicyProvidedCertsObserver(Observer* observer) override { observer_list_.AddObserver(observer); @@ -210,6 +211,12 @@ return merged; } + net::CertificateList GetAllAuthorityCertificates() const override { + // This function is not called by CertificateManagerModel. + NOTREACHED(); + return net::CertificateList(); + } + net::CertificateList GetWebTrustedCertificates() const override { return web_trusted_certs_; }
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index ac97de77..6514094b 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -206,6 +206,7 @@ #include "components/safe_browsing/db/database_manager.h" #include "components/safe_browsing/features.h" #include "components/safe_browsing/password_protection/password_protection_navigation_throttle.h" +#include "components/security_interstitials/content/origin_policy_ui.h" #include "components/services/heap_profiling/public/mojom/constants.mojom.h" #include "components/services/unzip/public/interfaces/constants.mojom.h" #include "components/signin/core/browser/profile_management_switches.h" @@ -4862,3 +4863,12 @@ return safe_browsing_url_checker_delegate_.get(); } + +base::Optional<std::string> +ChromeContentBrowserClient::GetOriginPolicyErrorPage( + content::OriginPolicyErrorReason error_reason, + const url::Origin& origin, + const GURL& url) { + return security_interstitials::OriginPolicyUI::GetErrorPage(error_reason, + origin, url); +}
diff --git a/chrome/browser/chrome_content_browser_client.h b/chrome/browser/chrome_content_browser_client.h index ad21627..b3d1b5f 100644 --- a/chrome/browser/chrome_content_browser_client.h +++ b/chrome/browser/chrome_content_browser_client.h
@@ -499,6 +499,11 @@ content::BrowserContext* browser_context, content::mojom::RendererPreferenceWatcherPtr watcher) override; + base::Optional<std::string> GetOriginPolicyErrorPage( + content::OriginPolicyErrorReason error_reason, + const url::Origin& origin, + const GURL& url) override; + protected: static bool HandleWebUI(GURL* url, content::BrowserContext* browser_context); static bool HandleWebUIReverse(GURL* url,
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index e95a4c5..cc4a032 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -1500,7 +1500,6 @@ "policy/policy_cert_service_factory.h", "policy/policy_cert_verifier.cc", "policy/policy_cert_verifier.h", - "policy/policy_certificate_provider.h", "policy/policy_oauth2_token_fetcher.cc", "policy/policy_oauth2_token_fetcher.h", "policy/pre_signin_policy_fetcher.cc",
diff --git a/chrome/browser/chromeos/login/enrollment/enrollment_screen.cc b/chrome/browser/chromeos/login/enrollment/enrollment_screen.cc index 28c2fe72..4344219c 100644 --- a/chrome/browser/chromeos/login/enrollment/enrollment_screen.cc +++ b/chrome/browser/chromeos/login/enrollment/enrollment_screen.cc
@@ -112,7 +112,8 @@ EnrollmentScreen::~EnrollmentScreen() { DCHECK(!enrollment_helper_ || g_browser_process->IsShuttingDown() || - browser_shutdown::IsTryingToQuit()); + browser_shutdown::IsTryingToQuit() || + DBusThreadManager::Get()->IsUsingFakes()); } void EnrollmentScreen::SetParameters(
diff --git a/chrome/browser/chromeos/login/enrollment/hands_off_enrollment_browsertest.cc b/chrome/browser/chromeos/login/enrollment/hands_off_enrollment_browsertest.cc new file mode 100644 index 0000000..4005a5b --- /dev/null +++ b/chrome/browser/chromeos/login/enrollment/hands_off_enrollment_browsertest.cc
@@ -0,0 +1,187 @@ +// 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 "base/command_line.h" +#include "base/run_loop.h" +#include "chrome/browser/chromeos/login/enrollment/enterprise_enrollment_helper_mock.h" +#include "chrome/browser/chromeos/login/existing_user_controller.h" +#include "chrome/browser/chromeos/login/oobe_screen.h" +#include "chrome/browser/chromeos/login/startup_utils.h" +#include "chrome/browser/chromeos/login/test/oobe_screen_waiter.h" +#include "chrome/browser/chromeos/login/test/wizard_in_process_browser_test.h" +#include "chrome/browser/chromeos/login/wizard_controller.h" +#include "chrome/browser/chromeos/policy/enrollment_status_chromeos.h" +#include "chromeos/chromeos_switches.h" +#include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/dbus/shill_service_client.h" +#include "chromeos/network/network_handler.h" +#include "chromeos/network/network_state.h" +#include "chromeos/network/network_state_handler.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/cros_system_api/dbus/shill/dbus-constants.h" + +namespace chromeos { + +namespace { + +constexpr char kDefaultNetworkServicePath[] = "/service/eth1"; + +} // namespace + +// Hands-off enrollment flow test. +class HandsOffEnrollmentTest : public WizardInProcessBrowserTest { + protected: + HandsOffEnrollmentTest() + : WizardInProcessBrowserTest(OobeScreen::SCREEN_TEST_NO_WINDOW) {} + ~HandsOffEnrollmentTest() override = default; + + // WizardInProcessBrowserTest: + void SetUpCommandLine(base::CommandLine* command_line) override { + WizardInProcessBrowserTest::SetUpCommandLine(command_line); + command_line->AppendSwitchASCII( + switches::kEnterpriseEnableZeroTouchEnrollment, "hands-off"); + } + + void SetUpOnMainThread() override { + WizardInProcessBrowserTest::SetUpOnMainThread(); + // Set official build so EULA screen is not skipped by default. + WizardController::default_controller()->is_official_build_ = true; + + // Sets all network services into idle state to simulate disconnected state. + NetworkStateHandler::NetworkStateList networks; + NetworkHandler::Get()->network_state_handler()->GetNetworkListByType( + NetworkTypePattern::Default(), + true, // configured_only + false, // visible_only, + 0, // no limit to number of results + &networks); + ShillServiceClient::TestInterface* service = + DBusThreadManager::Get()->GetShillServiceClient()->GetTestInterface(); + for (const auto* const network : networks) { + service->SetServiceProperty(network->path(), shill::kStateProperty, + base::Value(shill::kStateIdle)); + } + base::RunLoop().RunUntilIdle(); + } + + // Simulates device being connected to the network. + void SimulateNetworkConnected() { + ShillServiceClient::TestInterface* service = + DBusThreadManager::Get()->GetShillServiceClient()->GetTestInterface(); + service->SetServiceProperty(kDefaultNetworkServicePath, + shill::kStateProperty, + base::Value(shill::kStateOnline)); + base::RunLoop().RunUntilIdle(); + } + + // Result of attestation based enrollment used by + // EnterpriseEnrollmentHelperMock. + enum class AttestationEnrollmentResult { SUCCESS, ERROR }; + + // Helper method that mocks EnterpriseEnrollmentHelper for hands-off + // enrollment. It simulates specified attestation based enrollment |result|. + template <AttestationEnrollmentResult result> + static EnterpriseEnrollmentHelper* MockEnrollmentHelperCreator( + EnterpriseEnrollmentHelper::EnrollmentStatusConsumer* status_consumer, + const policy::EnrollmentConfig& enrollment_config, + const std::string& enrolling_user_domain) { + EnterpriseEnrollmentHelperMock* mock = + new EnterpriseEnrollmentHelperMock(status_consumer); + if (result == AttestationEnrollmentResult::SUCCESS) { + // Simulate successful attestation based enrollment. + EXPECT_CALL(*mock, EnrollUsingAttestation()) + .Times(testing::AnyNumber()) + .WillRepeatedly(testing::Invoke( + [mock]() { mock->status_consumer()->OnDeviceEnrolled(""); })); + EXPECT_CALL(*mock, GetDeviceAttributeUpdatePermission()) + .Times(testing::AnyNumber()) + .WillRepeatedly(testing::Invoke([mock]() { + mock->status_consumer()->OnDeviceAttributeUpdatePermission(false); + })); + } else { + // Simulate error during attestation based enrollment. + const policy::EnrollmentStatus enrollment_status = + policy::EnrollmentStatus::ForRegistrationError( + policy::DeviceManagementStatus::DM_STATUS_TEMPORARY_UNAVAILABLE); + EXPECT_CALL(*mock, GetDeviceAttributeUpdatePermission()) + .Times(testing::AnyNumber()) + .WillRepeatedly(testing::Invoke([mock, enrollment_status]() { + mock->status_consumer()->OnEnrollmentError(enrollment_status); + })); + } + // Define behavior of ClearAuth to only run the callback it is given. + EXPECT_CALL(*mock, ClearAuth(testing::_)) + .Times(testing::AnyNumber()) + .WillRepeatedly(testing::Invoke( + [](const base::RepeatingClosure& callback) { callback.Run(); })); + return mock; + } + + private: + DISALLOW_COPY_AND_ASSIGN(HandsOffEnrollmentTest); +}; + +IN_PROC_BROWSER_TEST_F(HandsOffEnrollmentTest, NetworkConnectionReady) { + EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( + &MockEnrollmentHelperCreator<AttestationEnrollmentResult::SUCCESS>); + SimulateNetworkConnected(); + + WizardController::default_controller()->AdvanceToScreen( + OobeScreen::SCREEN_OOBE_WELCOME); + + OobeScreenWaiter(OobeScreen::SCREEN_OOBE_NETWORK).Wait(); + + OobeScreenWaiter(OobeScreen::SCREEN_OOBE_ENROLLMENT).Wait(); + + base::RunLoop().RunUntilIdle(); + + EXPECT_TRUE(StartupUtils::IsOobeCompleted()); + EXPECT_TRUE(StartupUtils::IsDeviceRegistered()); + EXPECT_TRUE(ExistingUserController::current_controller()); +} + +IN_PROC_BROWSER_TEST_F(HandsOffEnrollmentTest, WaitForNetworkConnection) { + EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( + &MockEnrollmentHelperCreator<AttestationEnrollmentResult::SUCCESS>); + + WizardController::default_controller()->AdvanceToScreen( + OobeScreen::SCREEN_OOBE_WELCOME); + + OobeScreenWaiter(OobeScreen::SCREEN_OOBE_NETWORK).Wait(); + + SimulateNetworkConnected(); + + OobeScreenWaiter(OobeScreen::SCREEN_OOBE_ENROLLMENT).Wait(); + + base::RunLoop().RunUntilIdle(); + + EXPECT_TRUE(ExistingUserController::current_controller()); + EXPECT_TRUE(StartupUtils::IsOobeCompleted()); + EXPECT_TRUE(StartupUtils::IsDeviceRegistered()); +} + +IN_PROC_BROWSER_TEST_F(HandsOffEnrollmentTest, EnrollmentError) { + EnterpriseEnrollmentHelper::SetupEnrollmentHelperMock( + &MockEnrollmentHelperCreator<AttestationEnrollmentResult::ERROR>); + SimulateNetworkConnected(); + + WizardController::default_controller()->AdvanceToScreen( + OobeScreen::SCREEN_OOBE_WELCOME); + + OobeScreenWaiter(OobeScreen::SCREEN_OOBE_NETWORK).Wait(); + + OobeScreenWaiter(OobeScreen::SCREEN_OOBE_ENROLLMENT).Wait(); + + base::RunLoop().RunUntilIdle(); + + EXPECT_EQ( + OobeScreen::SCREEN_OOBE_ENROLLMENT, + WizardController::default_controller()->current_screen()->screen_id()); + EXPECT_FALSE(ExistingUserController::current_controller()); + EXPECT_FALSE(StartupUtils::IsOobeCompleted()); + EXPECT_FALSE(StartupUtils::IsDeviceRegistered()); +} + +} // namespace chromeos
diff --git a/chrome/browser/chromeos/login/screens/welcome_screen.cc b/chrome/browser/chromeos/login/screens/welcome_screen.cc index 57e0ee4..2318a05 100644 --- a/chrome/browser/chromeos/login/screens/welcome_screen.cc +++ b/chrome/browser/chromeos/login/screens/welcome_screen.cc
@@ -18,6 +18,7 @@ #include "chrome/browser/chromeos/login/screens/screen_exit_code.h" #include "chrome/browser/chromeos/login/screens/welcome_view.h" #include "chrome/browser/chromeos/login/ui/input_events_blocker.h" +#include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/system/timezone_util.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/webui/chromeos/login/l10n_util.h" @@ -154,8 +155,12 @@ if (!timezone_subscription_) InitializeTimezoneObserver(); - if (view_) + // Automatically continue if we are using hands-off enrollment. + if (WizardController::UsingHandsOffEnrollment()) { + OnUserAction(kUserActionContinueButtonClicked); + } else if (view_) { view_->Show(); + } } void WelcomeScreen::Hide() {
diff --git a/chrome/browser/chromeos/login/wizard_controller.h b/chrome/browser/chromeos/login/wizard_controller.h index 011c2829..834ab41 100644 --- a/chrome/browser/chromeos/login/wizard_controller.h +++ b/chrome/browser/chromeos/login/wizard_controller.h
@@ -464,6 +464,7 @@ friend class DemoSetupTest; friend class EnterpriseEnrollmentConfigurationTest; + friend class HandsOffEnrollmentTest; friend class WizardControllerBrokenLocalStateTest; friend class WizardControllerDemoSetupTest; friend class WizardControllerDeviceStateTest;
diff --git a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc index 6efffe7..50eecc8 100644 --- a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc +++ b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc
@@ -41,6 +41,7 @@ #include "chrome/browser/policy/device_management_service_configuration.h" #include "chrome/common/pref_names.h" #include "chromeos/attestation/attestation_flow.h" +#include "chromeos/cert_loader.h" #include "chromeos/chromeos_switches.h" #include "chromeos/cryptohome/async_method_caller.h" #include "chromeos/cryptohome/system_salt_getter.h" @@ -192,6 +193,11 @@ chromeos::NetworkHandler::Get()->network_device_handler(), chromeos::CrosSettings::Get(), DeviceNetworkConfigurationUpdater::DeviceAssetIDFetcher()); + // CertLoader may be not initialized in tests. + if (chromeos::CertLoader::IsInitialized()) { + chromeos::CertLoader::Get()->AddPolicyCertificateProvider( + device_network_configuration_updater_.get()); + } bluetooth_policy_handler_ = std::make_unique<BluetoothPolicyHandler>(chromeos::CrosSettings::Get()); @@ -214,6 +220,11 @@ } void BrowserPolicyConnectorChromeOS::Shutdown() { + // CertLoader may be not initialized in tests. + if (chromeos::CertLoader::IsInitialized()) { + chromeos::CertLoader::Get()->RemovePolicyCertificateProvider( + device_network_configuration_updater_.get()); + } device_network_configuration_updater_.reset(); if (device_local_account_policy_service_)
diff --git a/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc b/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc index 6e5d2a1..54936e70 100644 --- a/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc +++ b/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc
@@ -57,6 +57,7 @@ #include "components/policy/proto/device_management_backend.pb.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/testing_pref_service.h" +#include "components/session_manager/core/session_manager.h" #include "google_apis/gaia/gaia_oauth_client.h" #include "google_apis/gaia/gaia_urls.h" #include "net/url_request/url_request_test_util.h" @@ -284,6 +285,9 @@ private: scoped_refptr<network::WeakWrapperSharedURLLoaderFactory> test_shared_loader_factory_; + // This property is required to instantiate the session manager, a singleton + // which is used by the device status collector. + session_manager::SessionManager session_manager_; DISALLOW_COPY_AND_ASSIGN(DeviceCloudPolicyManagerChromeOSTest); };
diff --git a/chrome/browser/chromeos/policy/device_network_configuration_updater.cc b/chrome/browser/chromeos/policy/device_network_configuration_updater.cc index 5342df8..c679df2 100644 --- a/chrome/browser/chromeos/policy/device_network_configuration_updater.cc +++ b/chrome/browser/chromeos/policy/device_network_configuration_updater.cc
@@ -66,6 +66,7 @@ device_asset_id_fetcher) : NetworkConfigurationUpdater(onc::ONC_SOURCE_DEVICE_POLICY, key::kDeviceOpenNetworkConfiguration, + false /* allow_trusted_certs_from_policy */, policy_service, network_config_handler), network_device_handler_(network_device_handler), @@ -82,31 +83,6 @@ device_asset_id_fetcher_ = base::BindRepeating(&GetDeviceAssetID); } -net::CertificateList -DeviceNetworkConfigurationUpdater::GetAuthorityCertificates() { - net::CertificateList authority_certs; - - base::ListValue onc_certificates_value; - ParseCurrentPolicy(nullptr /* network_configs */, - nullptr /* global_network_config */, - &onc_certificates_value); - - chromeos::onc::OncParsedCertificates onc_parsed_certificates( - onc_certificates_value); - - for (const chromeos::onc::OncParsedCertificates::ServerOrAuthorityCertificate& - onc_certificate : - onc_parsed_certificates.server_or_authority_certificates()) { - if (onc_certificate.type() == - chromeos::onc::OncParsedCertificates::ServerOrAuthorityCertificate:: - Type::kAuthority) { - authority_certs.push_back(onc_certificate.certificate()); - } - } - - return authority_certs; -} - void DeviceNetworkConfigurationUpdater::Init() { NetworkConfigurationUpdater::Init(); @@ -130,14 +106,8 @@ !connector->IsEnterpriseManaged()); } -void DeviceNetworkConfigurationUpdater::ImportCertificates( - const base::ListValue& certificates_onc) { +void DeviceNetworkConfigurationUpdater::ImportClientCertificates() { // Importing client certificates from device policy is not implemented. - // Permanently importing CA and server certs from device policy or giving such - // certificates trust is not allowed. However, we make authority certificates - // from device policy available (e.g. for use as intermediates in client - // certificate discovery on the sign-in screen), see - // GetAuthorityCertificates(). } void DeviceNetworkConfigurationUpdater::ApplyNetworkPolicy(
diff --git a/chrome/browser/chromeos/policy/device_network_configuration_updater.h b/chrome/browser/chromeos/policy/device_network_configuration_updater.h index 0f032ba89..2ea9c007 100644 --- a/chrome/browser/chromeos/policy/device_network_configuration_updater.h +++ b/chrome/browser/chromeos/policy/device_network_configuration_updater.h
@@ -55,10 +55,6 @@ chromeos::CrosSettings* cros_settings, const DeviceAssetIDFetcher& device_asset_id_fetcher); - // Returns all authority certificates from the currently applied ONC device - // policy. - net::CertificateList GetAuthorityCertificates(); - private: DeviceNetworkConfigurationUpdater( PolicyService* policy_service, @@ -67,8 +63,9 @@ chromeos::CrosSettings* cros_settings, const DeviceAssetIDFetcher& device_asset_id_fetcher); + // NetworkConfigurationUpdater: void Init() override; - void ImportCertificates(const base::ListValue& certificates_onc) override; + void ImportClientCertificates() override; void ApplyNetworkPolicy( base::ListValue* network_configs_onc, base::DictionaryValue* global_network_config) override;
diff --git a/chrome/browser/chromeos/policy/device_status_collector.cc b/chrome/browser/chromeos/policy/device_status_collector.cc index 18fa93a7..3b64733 100644 --- a/chrome/browser/chromeos/policy/device_status_collector.cc +++ b/chrome/browser/chromeos/policy/device_status_collector.cc
@@ -50,6 +50,7 @@ #include "chrome/common/pref_names.h" #include "chromeos/audio/cras_audio_handler.h" #include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/dbus/power_manager/idle.pb.h" #include "chromeos/dbus/update_engine_client.h" #include "chromeos/dbus/util/version_loader.h" #include "chromeos/disks/disk_mount_manager.h" @@ -71,6 +72,7 @@ #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" +#include "components/session_manager/session_manager_types.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "components/user_manager/user_type.h" @@ -712,12 +714,17 @@ max_stored_future_activity_interval_(kMaxStoredFutureActivityInterval), pref_service_(pref_service), last_idle_check_(Time()), + last_active_check_(base::Time()), + last_state_active_(true), volume_info_fetcher_(volume_info_fetcher), cpu_statistics_fetcher_(cpu_statistics_fetcher), cpu_temp_fetcher_(cpu_temp_fetcher), android_status_fetcher_(android_status_fetcher), statistics_provider_(provider), cros_settings_(chromeos::CrosSettings::Get()), + power_manager_( + chromeos::DBusThreadManager::Get()->GetPowerManagerClient()), + session_manager_(session_manager::SessionManager::Get()), is_enterprise_reporting_(is_enterprise_reporting), task_runner_(nullptr), weak_factory_(this) { @@ -768,6 +775,10 @@ running_kiosk_app_subscription_ = cros_settings_->AddSettingsObserver( chromeos::kReportRunningKioskApp, callback); + // Watch for changes on the device state to calculate the child's active time. + power_manager_->AddObserver(this); + session_manager_->AddObserver(this); + // Fetch the current values of the policies. UpdateReportingSettings(); @@ -807,7 +818,10 @@ activity_day_start); } -DeviceStatusCollector::~DeviceStatusCollector() {} +DeviceStatusCollector::~DeviceStatusCollector() { + power_manager_->RemoveObserver(this); + session_manager_->RemoveObserver(this); +} // static void DeviceStatusCollector::RegisterPrefs(PrefRegistrySimple* registry) { @@ -906,18 +920,18 @@ } void DeviceStatusCollector::IdleStateCallback(ui::IdleState state) { - // Do nothing if device activity reporting is disabled. - if (!report_activity_times_) + // Do nothing if device activity reporting is disabled or if it's a child + // account. Usage time for child accounts are calculated differently. + if (!report_activity_times_ || + user_manager::UserManager::Get()->IsLoggedInAsChildUser()) { return; + } Time now = GetCurrentTime(); // For kiosk apps we report total uptime instead of active time. if (state == ui::IDLE_STATE_ACTIVE || IsKioskApp()) { - // Child user is the consumer user registered with DMServer and - // therefore eligible for non-enterprise reporting. - CHECK(is_enterprise_reporting_ || - user_manager::UserManager::Get()->IsLoggedInAsChildUser()); + CHECK(is_enterprise_reporting_); std::string user_email = GetUserForActivityReporting(); // If it's been too long since the last report, or if the activity is // negative (which can happen when the clock changes), assume a single @@ -939,6 +953,63 @@ last_idle_check_ = now; } +void DeviceStatusCollector::OnSessionStateChanged() { + UpdateChildUsageTime(); + last_state_active_ = + session_manager::SessionManager::Get()->session_state() == + session_manager::SessionState::ACTIVE; +} + +void DeviceStatusCollector::ScreenIdleStateChanged( + const power_manager::ScreenIdleState& state) { + UpdateChildUsageTime(); + // It is active if screen is on and if the session is also active. + last_state_active_ = + !state.off() && session_manager_->session_state() == + session_manager::SessionState::ACTIVE; +} + +void DeviceStatusCollector::SuspendImminent( + power_manager::SuspendImminent::Reason reason) { + UpdateChildUsageTime(); + // Device is going to be suspeded, so it won't be active. + last_state_active_ = false; +} + +void DeviceStatusCollector::SuspendDone(const base::TimeDelta& sleep_duration) { + UpdateChildUsageTime(); + // Device is returning from suspension, so it is considered active if the + // session is also active. + last_state_active_ = session_manager_->session_state() == + session_manager::SessionState::ACTIVE; +} + +void DeviceStatusCollector::UpdateChildUsageTime() { + if (!report_activity_times_ || + !user_manager::UserManager::Get()->IsLoggedInAsChildUser()) { + return; + } + + if (last_active_check_.is_null()) { + last_active_check_ = GetCurrentTime(); + return; + } + + // Only child accounts should be using this method. + CHECK(user_manager::UserManager::Get()->IsLoggedInAsChildUser()); + + Time now = GetCurrentTime(); + if (last_state_active_) { + activity_storage_->AddActivityPeriod(last_active_check_, now, + GetUserForActivityReporting()); + + activity_storage_->PruneActivityPeriods( + now, max_stored_past_activity_interval_, + max_stored_future_activity_interval_); + } + last_active_check_ = now; +} + std::unique_ptr<DeviceLocalAccount> DeviceStatusCollector::GetAutoLaunchedKioskSessionInfo() { std::unique_ptr<DeviceLocalAccount> account = @@ -1069,6 +1140,9 @@ bool DeviceStatusCollector::GetActivityTimes( em::DeviceStatusReportRequest* status) { + if (user_manager::UserManager::Get()->IsLoggedInAsChildUser()) + UpdateChildUsageTime(); + // If user reporting is off, data should be aggregated per day. // Signed-in user is reported in non-enterprise reporting. std::vector<ActivityStorage::ActivityPeriod> activity_times =
diff --git a/chrome/browser/chromeos/policy/device_status_collector.h b/chrome/browser/chromeos/policy/device_status_collector.h index 9f49304..2b67f5a 100644 --- a/chrome/browser/chromeos/policy/device_status_collector.h +++ b/chrome/browser/chromeos/policy/device_status_collector.h
@@ -25,8 +25,11 @@ #include "base/timer/timer.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/power_manager_client.h" #include "components/policy/proto/device_management_backend.pb.h" #include "components/prefs/pref_member.h" +#include "components/session_manager/core/session_manager.h" +#include "components/session_manager/core/session_manager_observer.h" #include "ui/base/idle/idle.h" namespace chromeos { @@ -51,7 +54,8 @@ class GetStatusState; // Collects and summarizes the status of an enterprised-managed ChromeOS device. -class DeviceStatusCollector { +class DeviceStatusCollector : public session_manager::SessionManagerObserver, + public chromeos::PowerManagerClient::Observer { public: using VolumeInfoFetcher = base::Callback< std::vector<enterprise_management::VolumeInfo>( @@ -104,7 +108,7 @@ const AndroidStatusFetcher& android_status_fetcher, base::TimeDelta activity_day_start, bool is_enterprise_reporting); - virtual ~DeviceStatusCollector(); + ~DeviceStatusCollector() override; // Gathers device and session status information and calls the passed response // callback. Null pointers passed into the response indicate errors or that @@ -156,6 +160,19 @@ // next device status update. void SampleResourceUsage(); + // session_manager::SessionManagerObserver: + void OnSessionStateChanged() override; + + // power_manager::PowerManagerClient::Observer: + void ScreenIdleStateChanged( + const power_manager::ScreenIdleState& state) override; + + // power_manager::PowerManagerClient::Observer: + void SuspendImminent(power_manager::SuspendImminent::Reason reason) override; + + // power_manager::PowerManagerClient::Observer: + void SuspendDone(const base::TimeDelta& sleep_duration) override; + // The timeout in the past to store device activity. // This is kept in case device status uploads fail for a number of days. base::TimeDelta max_stored_past_activity_interval_; @@ -232,12 +249,22 @@ // reports. bool IncludeEmailsInActivityReports() const; + // Updates the child's active time. + void UpdateChildUsageTime(); + // Pref service that is mainly used to store activity periods for reporting. PrefService* const pref_service_; // The last time an idle state check was performed. base::Time last_idle_check_; + // The last time an active state check was performed. + base::Time last_active_check_; + + // Whether the last state of the device was active. This is used for child + // accounts only. Active is defined as having the screen turned on. + bool last_state_active_; + // The maximum key that went into the last report generated by // GetDeviceStatusAsync(), and the duration for it. This is used to trim // the stored data in OnSubmittedSuccessfully(). Trimming is delayed so @@ -280,6 +307,12 @@ chromeos::CrosSettings* const cros_settings_; + // Power manager client. Used to listen to suspend and idle events. + chromeos::PowerManagerClient* const power_manager_; + + // Session manager. Used to listen to session state changes. + session_manager::SessionManager* const session_manager_; + // Stores and filters activity periods used for reporting. std::unique_ptr<ActivityStorage> activity_storage_;
diff --git a/chrome/browser/chromeos/policy/device_status_collector_browsertest.cc b/chrome/browser/chromeos/policy/device_status_collector_browsertest.cc index 2363c8b..9b43ffb 100644 --- a/chrome/browser/chromeos/policy/device_status_collector_browsertest.cc +++ b/chrome/browser/chromeos/policy/device_status_collector_browsertest.cc
@@ -46,7 +46,9 @@ #include "chromeos/audio/cras_audio_handler.h" #include "chromeos/dbus/cros_disks_client.h" #include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/dbus/fake_power_manager_client.h" #include "chromeos/dbus/fake_update_engine_client.h" +#include "chromeos/dbus/power_manager/idle.pb.h" #include "chromeos/dbus/shill_device_client.h" #include "chromeos/dbus/shill_ipconfig_client.h" #include "chromeos/dbus/shill_profile_client.h" @@ -382,6 +384,10 @@ chromeos::CrasAudioHandler::InitializeForTesting(); chromeos::LoginState::Initialize(); + + fake_power_manager_client_ = new chromeos::FakePowerManagerClient; + chromeos::DBusThreadManager::GetSetterForTesting()->SetPowerManagerClient( + base::WrapUnique(fake_power_manager_client_)); } ~DeviceStatusCollectorTest() override { @@ -410,6 +416,50 @@ void TearDown() override { settings_helper_.RestoreProvider(); } protected: + // States tracked to calculate a child's active time. + enum class DeviceStateTransitions { + kEnterIdleState, + kLeaveIdleState, + kEnterSleep, + kLeaveSleep, + kEnterSessionActive, + kLeaveSessionActive + }; + + void SimulateStateChanges(DeviceStateTransitions* states, int len) { + for (int i = 0; i < len; i++) { + switch (states[i]) { + case DeviceStateTransitions::kEnterIdleState: { + power_manager::ScreenIdleState state; + state.set_off(true); + fake_power_manager_client_->SendScreenIdleStateChanged(state); + } break; + case DeviceStateTransitions::kLeaveIdleState: { + power_manager::ScreenIdleState state; + state.set_off(false); + fake_power_manager_client_->SendScreenIdleStateChanged(state); + } break; + case DeviceStateTransitions::kEnterSleep: + fake_power_manager_client_->SendSuspendImminent( + power_manager::SuspendImminent_Reason_LID_CLOSED); + break; + case DeviceStateTransitions::kLeaveSleep: + fake_power_manager_client_->SendSuspendDone( + base::TimeDelta::FromSeconds( + policy::DeviceStatusCollector::kIdlePollIntervalSeconds)); + break; + case DeviceStateTransitions::kEnterSessionActive: + session_manager::SessionManager::Get()->SetSessionState( + session_manager::SessionState::ACTIVE); + break; + case DeviceStateTransitions::kLeaveSessionActive: + session_manager::SessionManager::Get()->SetSessionState( + session_manager::SessionState::LOCKED); + break; + } + } + } + void AddMountPoint(const std::string& mount_point) { mount_point_map_.insert(DiskMountManager::MountPointMap::value_type( mount_point, DiskMountManager::MountPointInfo( @@ -593,6 +643,13 @@ base::ScopedPathOverride user_data_dir_override_; chromeos::FakeUpdateEngineClient* const update_engine_client_; std::unique_ptr<base::RunLoop> run_loop_; + + // Owned by chromeos::DBusThreadManager. + chromeos::FakePowerManagerClient* fake_power_manager_client_; + + // This property is required to instantiate the session manager, a singleton + // which is used by the device status collector. + session_manager::SessionManager session_manager_; }; TEST_F(DeviceStatusCollectorTest, AllIdle) { @@ -2052,7 +2109,6 @@ void TearDown() override { chromeos::NetworkHandler::Shutdown(); - chromeos::DBusThreadManager::Shutdown(); } void VerifyNetworkReporting() { @@ -2356,16 +2412,56 @@ }; TEST_F(ConsumerDeviceStatusCollectorTimeLimitEnabledTest, - ReportingActivityTimes) { - ui::IdleState test_states[] = {ui::IDLE_STATE_ACTIVE, ui::IDLE_STATE_ACTIVE, - ui::IDLE_STATE_ACTIVE}; - status_collector_->Simulate(test_states, - sizeof(test_states) / sizeof(ui::IdleState)); + ReportingActivityTimesSessionTransistions) { + DeviceStateTransitions test_states[] = { + DeviceStateTransitions::kEnterSessionActive, + DeviceStateTransitions::kLeaveSessionActive, + DeviceStateTransitions::kEnterSessionActive, + DeviceStateTransitions::kLeaveSessionActive}; + SimulateStateChanges(test_states, + sizeof(test_states) / sizeof(DeviceStateTransitions)); GetStatus(); ASSERT_EQ(1, device_status_.active_period_size()); - EXPECT_EQ(3 * ActivePeriodMilliseconds(), + EXPECT_EQ(2 * ActivePeriodMilliseconds(), + GetActiveMilliseconds(device_status_)); + EXPECT_EQ(user_account_id_.GetUserEmail(), + device_status_.active_period(0).user_email()); +} + +TEST_F(ConsumerDeviceStatusCollectorTimeLimitEnabledTest, + ReportingActivityTimesSleepTransistions) { + DeviceStateTransitions test_states[] = { + DeviceStateTransitions::kEnterSessionActive, + DeviceStateTransitions::kEnterSleep, DeviceStateTransitions::kLeaveSleep, + DeviceStateTransitions::kLeaveSessionActive}; + SimulateStateChanges(test_states, + sizeof(test_states) / sizeof(DeviceStateTransitions)); + + GetStatus(); + + ASSERT_EQ(1, device_status_.active_period_size()); + EXPECT_EQ(2 * ActivePeriodMilliseconds(), + GetActiveMilliseconds(device_status_)); + EXPECT_EQ(user_account_id_.GetUserEmail(), + device_status_.active_period(0).user_email()); +} + +TEST_F(ConsumerDeviceStatusCollectorTimeLimitEnabledTest, + ReportingActivityTimesIdleTransitions) { + DeviceStateTransitions test_states[] = { + DeviceStateTransitions::kEnterSessionActive, + DeviceStateTransitions::kEnterIdleState, + DeviceStateTransitions::kLeaveIdleState, + DeviceStateTransitions::kLeaveSessionActive}; + SimulateStateChanges(test_states, + sizeof(test_states) / sizeof(DeviceStateTransitions)); + + GetStatus(); + + ASSERT_EQ(1, device_status_.active_period_size()); + EXPECT_EQ(2 * ActivePeriodMilliseconds(), GetActiveMilliseconds(device_status_)); EXPECT_EQ(user_account_id_.GetUserEmail(), device_status_.active_period(0).user_email()); @@ -2375,11 +2471,15 @@ EXPECT_TRUE( profile_pref_service_.GetDictionary(prefs::kUserActivityTimes)->empty()); - ui::IdleState test_states[] = {ui::IDLE_STATE_ACTIVE, ui::IDLE_STATE_IDLE, - ui::IDLE_STATE_ACTIVE, ui::IDLE_STATE_ACTIVE, - ui::IDLE_STATE_IDLE, ui::IDLE_STATE_IDLE}; - status_collector_->Simulate(test_states, - sizeof(test_states) / sizeof(ui::IdleState)); + DeviceStateTransitions test_states[] = { + DeviceStateTransitions::kEnterSessionActive, + DeviceStateTransitions::kLeaveSessionActive, + DeviceStateTransitions::kEnterSessionActive, + DeviceStateTransitions::kLeaveSessionActive, + DeviceStateTransitions::kEnterSessionActive, + DeviceStateTransitions::kLeaveSessionActive}; + SimulateStateChanges(test_states, + sizeof(test_states) / sizeof(DeviceStateTransitions)); EXPECT_FALSE( profile_pref_service_.GetDictionary(prefs::kUserActivityTimes)->empty()); @@ -2390,8 +2490,8 @@ base::BindRepeating(&GetEmptyCPUStatistics), base::BindRepeating(&GetEmptyCPUTempInfo), base::BindRepeating(&GetEmptyAndroidStatus)); - status_collector_->Simulate(test_states, - sizeof(test_states) / sizeof(ui::IdleState)); + SimulateStateChanges(test_states, + sizeof(test_states) / sizeof(DeviceStateTransitions)); GetStatus(); EXPECT_EQ(6 * ActivePeriodMilliseconds(), @@ -2402,10 +2502,15 @@ ActivityNotWrittenToLocalState) { EXPECT_TRUE(local_state_.GetDictionary(prefs::kDeviceActivityTimes)->empty()); - ui::IdleState test_states[] = {ui::IDLE_STATE_ACTIVE, ui::IDLE_STATE_ACTIVE, - ui::IDLE_STATE_ACTIVE}; - status_collector_->Simulate(test_states, - sizeof(test_states) / sizeof(ui::IdleState)); + DeviceStateTransitions test_states[] = { + DeviceStateTransitions::kEnterSessionActive, + DeviceStateTransitions::kLeaveSessionActive, + DeviceStateTransitions::kEnterSessionActive, + DeviceStateTransitions::kLeaveSessionActive, + DeviceStateTransitions::kEnterSessionActive, + DeviceStateTransitions::kLeaveSessionActive}; + SimulateStateChanges(test_states, + sizeof(test_states) / sizeof(DeviceStateTransitions)); GetStatus(); EXPECT_EQ(1, device_status_.active_period_size()); EXPECT_EQ(3 * ActivePeriodMilliseconds(),
diff --git a/chrome/browser/chromeos/policy/network_configuration_updater.cc b/chrome/browser/chromeos/policy/network_configuration_updater.cc index f163dee1..8644e189 100644 --- a/chrome/browser/chromeos/policy/network_configuration_updater.cc +++ b/chrome/browser/chromeos/policy/network_configuration_updater.cc
@@ -11,9 +11,34 @@ #include "chromeos/network/onc/onc_utils.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/policy_constants.h" +#include "net/cert/x509_certificate.h" +#include "net/cert/x509_util_nss.h" + +using chromeos::onc::OncParsedCertificates; namespace policy { +namespace { + +// A predicate used for filtering server or authority certificates. +using ServerOrAuthorityCertPredicate = base::RepeatingCallback<bool( + const OncParsedCertificates::ServerOrAuthorityCertificate& cert)>; + +net::CertificateList GetFilteredCertificateListFromOnc( + const std::vector<OncParsedCertificates::ServerOrAuthorityCertificate>& + server_or_authority_certificates, + ServerOrAuthorityCertPredicate predicate) { + net::CertificateList certificates; + for (const auto& server_or_authority_cert : + server_or_authority_certificates) { + if (predicate.Run(server_or_authority_cert)) + certificates.push_back(server_or_authority_cert.certificate()); + } + return certificates; +} + +} // namespace + NetworkConfigurationUpdater::~NetworkConfigurationUpdater() { policy_service_->RemoveObserver(POLICY_DOMAIN_CHROME, this); } @@ -36,19 +61,83 @@ } } +void NetworkConfigurationUpdater::AddPolicyProvidedCertsObserver( + chromeos::PolicyCertificateProvider::Observer* observer) { + observer_list_.AddObserver(observer); +} + +void NetworkConfigurationUpdater::RemovePolicyProvidedCertsObserver( + chromeos::PolicyCertificateProvider::Observer* observer) { + observer_list_.RemoveObserver(observer); +} + +net::CertificateList +NetworkConfigurationUpdater::GetAllServerAndAuthorityCertificates() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return GetFilteredCertificateListFromOnc( + certs_->server_or_authority_certificates(), + base::BindRepeating( + [](const OncParsedCertificates::ServerOrAuthorityCertificate& cert) { + return true; + })); +} + +net::CertificateList NetworkConfigurationUpdater::GetAllAuthorityCertificates() + const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return GetFilteredCertificateListFromOnc( + certs_->server_or_authority_certificates(), + base::BindRepeating( + [](const OncParsedCertificates::ServerOrAuthorityCertificate& cert) { + return cert.type() == + OncParsedCertificates::ServerOrAuthorityCertificate::Type:: + kAuthority; + })); +} + +net::CertificateList NetworkConfigurationUpdater::GetWebTrustedCertificates() + const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (!allow_trusted_certificates_from_policy_) + return net::CertificateList(); + + return GetFilteredCertificateListFromOnc( + certs_->server_or_authority_certificates(), + base::BindRepeating( + [](const OncParsedCertificates::ServerOrAuthorityCertificate& cert) { + return cert.web_trust_requested(); + })); +} + +net::CertificateList +NetworkConfigurationUpdater::GetCertificatesWithoutWebTrust() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (!allow_trusted_certificates_from_policy_) + return GetAllServerAndAuthorityCertificates(); + + return GetFilteredCertificateListFromOnc( + certs_->server_or_authority_certificates(), + base::BindRepeating( + [](const OncParsedCertificates::ServerOrAuthorityCertificate& cert) { + return !cert.web_trust_requested(); + })); +} + NetworkConfigurationUpdater::NetworkConfigurationUpdater( onc::ONCSource onc_source, std::string policy_key, + bool allow_trusted_certs_from_policy, PolicyService* policy_service, chromeos::ManagedNetworkConfigurationHandler* network_config_handler) : onc_source_(onc_source), network_config_handler_(network_config_handler), policy_key_(policy_key), - policy_change_registrar_(policy_service, - PolicyNamespace(POLICY_DOMAIN_CHROME, - std::string())), - policy_service_(policy_service) { -} + allow_trusted_certificates_from_policy_(allow_trusted_certs_from_policy), + policy_change_registrar_( + policy_service, + PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())), + policy_service_(policy_service), + certs_(std::make_unique<OncParsedCertificates>()) {} void NetworkConfigurationUpdater::Init() { policy_change_registrar_.Observe( @@ -83,6 +172,11 @@ global_network_config, certificates); } +const std::vector<OncParsedCertificates::ClientCertificate>& +NetworkConfigurationUpdater::GetClientCertificates() const { + return certs_->client_certificates(); +} + void NetworkConfigurationUpdater::OnPolicyChanged(const base::Value* previous, const base::Value* current) { ApplyPolicy(); @@ -102,4 +196,38 @@ return chromeos::onc::GetSourceAsString(onc_source_); } +void NetworkConfigurationUpdater::ImportCertificates( + const base::ListValue& certificates_onc) { + std::unique_ptr<OncParsedCertificates> incoming_certs = + std::make_unique<OncParsedCertificates>(certificates_onc); + + bool server_or_authority_certs_changed = + certs_->server_or_authority_certificates() != + incoming_certs->server_or_authority_certificates(); + bool client_certs_changed = + certs_->client_certificates() != incoming_certs->client_certificates(); + + if (!server_or_authority_certs_changed && !client_certs_changed) + return; + + certs_ = std::move(incoming_certs); + + if (client_certs_changed) + ImportClientCertificates(); + + if (server_or_authority_certs_changed) + NotifyPolicyProvidedCertsChanged(); +} + +void NetworkConfigurationUpdater::NotifyPolicyProvidedCertsChanged() { + net::CertificateList all_server_and_authority_certs = + GetAllServerAndAuthorityCertificates(); + net::CertificateList trust_anchors = GetWebTrustedCertificates(); + + for (auto& observer : observer_list_) { + observer.OnPolicyProvidedCertsChanged(all_server_and_authority_certs, + trust_anchors); + } +} + } // namespace policy
diff --git a/chrome/browser/chromeos/policy/network_configuration_updater.h b/chrome/browser/chromeos/policy/network_configuration_updater.h index e3270be..d9e2762 100644 --- a/chrome/browser/chromeos/policy/network_configuration_updater.h +++ b/chrome/browser/chromeos/policy/network_configuration_updater.h
@@ -7,9 +7,14 @@ #include <memory> #include <string> +#include <vector> #include "base/compiler_specific.h" #include "base/macros.h" +#include "base/observer_list.h" +#include "base/sequence_checker.h" +#include "chromeos/network/onc/onc_parsed_certificates.h" +#include "chromeos/policy_certificate_provider.h" #include "components/onc/onc_constants.h" #include "components/policy/core/common/policy_service.h" @@ -17,11 +22,11 @@ class DictionaryValue; class ListValue; class Value; -} +} // namespace base namespace chromeos { class ManagedNetworkConfigurationHandler; -} +} // namespace chromeos namespace policy { @@ -33,7 +38,8 @@ // Shill. Certificates are imported with the chromeos::onc::CertificateImporter. // For user policies the subclass UserNetworkConfigurationUpdater must be used. // Does not handle proxy settings. -class NetworkConfigurationUpdater : public PolicyService::Observer { +class NetworkConfigurationUpdater : public chromeos::PolicyCertificateProvider, + public PolicyService::Observer { public: ~NetworkConfigurationUpdater() override; @@ -43,17 +49,30 @@ const PolicyMap& current) override; void OnPolicyServiceInitialized(PolicyDomain domain) override; + // chromeos::PolicyCertificateProvider: + void AddPolicyProvidedCertsObserver( + chromeos::PolicyCertificateProvider::Observer* observer) override; + void RemovePolicyProvidedCertsObserver( + chromeos::PolicyCertificateProvider::Observer* observer) override; + net::CertificateList GetAllServerAndAuthorityCertificates() const override; + net::CertificateList GetAllAuthorityCertificates() const override; + net::CertificateList GetWebTrustedCertificates() const override; + net::CertificateList GetCertificatesWithoutWebTrust() const override; + protected: NetworkConfigurationUpdater( onc::ONCSource onc_source, std::string policy_key, + bool allow_trusted_certs_from_policy, PolicyService* policy_service, chromeos::ManagedNetworkConfigurationHandler* network_config_handler); virtual void Init(); - // Imports the certificates part of the policy. - virtual void ImportCertificates(const base::ListValue& certificates_onc) = 0; + // Called in the subclass to import client certificates provided by the ONC + // policy. The client certificates to be imported can be obtained using + // |GetClientcertificates()|. + virtual void ImportClientCertificates() = 0; // Pushes the network part of the policy to the // ManagedNetworkConfigurationHandler. This can be overridden by subclasses to @@ -72,11 +91,16 @@ base::DictionaryValue* global_network_config, base::ListValue* certificates); + const std::vector<chromeos::onc::OncParsedCertificates::ClientCertificate>& + GetClientCertificates() const; + onc::ONCSource onc_source_; // Pointer to the global singleton or a test instance. chromeos::ManagedNetworkConfigurationHandler* network_config_handler_; + SEQUENCE_CHECKER(sequence_checker_); + private: // Called if the ONC policy changed. void OnPolicyChanged(const base::Value* previous, const base::Value* current); @@ -86,14 +110,30 @@ std::string LogHeader() const; + // Imports the certificates part of the policy. + void ImportCertificates(const base::ListValue& certificates_onc); + + void NotifyPolicyProvidedCertsChanged(); + std::string policy_key_; + // Whether Web trust is allowed or not. + bool allow_trusted_certificates_from_policy_; + // Used to register for notifications from the |policy_service_|. PolicyChangeRegistrar policy_change_registrar_; // Used to retrieve the policies. PolicyService* policy_service_; + // Holds certificates from the last parsed ONC policy. + std::unique_ptr<chromeos::onc::OncParsedCertificates> certs_; + + // Observer list for notifying about ONC-provided server and CA certificate + // changes. + base::ObserverList<chromeos::PolicyCertificateProvider::Observer, + true>::Unchecked observer_list_; + DISALLOW_COPY_AND_ASSIGN(NetworkConfigurationUpdater); };
diff --git a/chrome/browser/chromeos/policy/network_configuration_updater_unittest.cc b/chrome/browser/chromeos/policy/network_configuration_updater_unittest.cc index f2c0ddb0..849b912 100644 --- a/chrome/browser/chromeos/policy/network_configuration_updater_unittest.cc +++ b/chrome/browser/chromeos/policy/network_configuration_updater_unittest.cc
@@ -15,7 +15,6 @@ #include "base/run_loop.h" #include "base/values.h" #include "chrome/browser/chromeos/policy/device_network_configuration_updater.h" -#include "chrome/browser/chromeos/policy/policy_certificate_provider.h" #include "chrome/browser/chromeos/policy/user_network_configuration_updater.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/chromeos/settings/scoped_cros_settings_test_helper.h" @@ -26,6 +25,7 @@ #include "chromeos/network/onc/onc_parsed_certificates.h" #include "chromeos/network/onc/onc_test_utils.h" #include "chromeos/network/onc/onc_utils.h" +#include "chromeos/policy_certificate_provider.h" #include "chromeos/system/fake_statistics_provider.h" #include "chromeos/system/statistics_provider.h" #include "components/account_id/account_id.h" @@ -82,7 +82,7 @@ }; class FakePolicyProvidedCertsObserver - : public PolicyCertificateProvider::Observer { + : public chromeos::PolicyCertificateProvider::Observer { public: FakePolicyProvidedCertsObserver() {}
diff --git a/chrome/browser/chromeos/policy/policy_cert_service.h b/chrome/browser/chromeos/policy/policy_cert_service.h index 4ff69a0..c1b6119 100644 --- a/chrome/browser/chromeos/policy/policy_cert_service.h +++ b/chrome/browser/chromeos/policy/policy_cert_service.h
@@ -13,8 +13,8 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" -#include "chrome/browser/chromeos/policy/policy_certificate_provider.h" #include "chrome/browser/chromeos/policy/user_network_configuration_updater.h" +#include "chromeos/policy_certificate_provider.h" #include "components/keyed_service/core/keyed_service.h" namespace user_manager { @@ -36,7 +36,7 @@ // Except for unit tests, PolicyCertVerifier should only be created through this // class. class PolicyCertService : public KeyedService, - public PolicyCertificateProvider::Observer { + public chromeos::PolicyCertificateProvider::Observer { public: PolicyCertService(const std::string& user_id, UserNetworkConfigurationUpdater* net_conf_updater,
diff --git a/chrome/browser/chromeos/policy/status_uploader_unittest.cc b/chrome/browser/chromeos/policy/status_uploader_unittest.cc index 7a03327..fa9a019a 100644 --- a/chrome/browser/chromeos/policy/status_uploader_unittest.cc +++ b/chrome/browser/chromeos/policy/status_uploader_unittest.cc
@@ -21,6 +21,7 @@ #include "components/policy/core/common/cloud/mock_cloud_policy_client.h" #include "components/policy/core/common/cloud/mock_device_management_service.h" #include "components/prefs/testing_pref_service.h" +#include "components/session_manager/core/session_manager.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_utils.h" #include "net/url_request/url_request_context_getter.h" @@ -176,6 +177,9 @@ MockCloudPolicyClient client_; MockDeviceManagementService device_management_service_; TestingPrefServiceSimple prefs_; + // This property is required to instantiate the session manager, a singleton + // which is used by the device status collector. + session_manager::SessionManager session_manager_; }; TEST_F(StatusUploaderTest, BasicTest) {
diff --git a/chrome/browser/chromeos/policy/user_network_configuration_updater.cc b/chrome/browser/chromeos/policy/user_network_configuration_updater.cc index 6105385..8b1d1201 100644 --- a/chrome/browser/chromeos/policy/user_network_configuration_updater.cc +++ b/chrome/browser/chromeos/policy/user_network_configuration_updater.cc
@@ -15,6 +15,7 @@ #include "chrome/browser/chromeos/login/session/user_session_manager.h" #include "chrome/browser/net/nss_context.h" #include "chrome/browser/profiles/profile.h" +#include "chromeos/cert_loader.h" #include "chromeos/network/managed_network_configuration_handler.h" #include "chromeos/network/onc/onc_certificate_importer_impl.h" #include "chromeos/network/onc/onc_parsed_certificates.h" @@ -24,14 +25,14 @@ #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_source.h" -#include "net/cert/x509_certificate.h" -#include "net/cert/x509_util_nss.h" - -using chromeos::onc::OncParsedCertificates; namespace policy { -UserNetworkConfigurationUpdater::~UserNetworkConfigurationUpdater() {} +UserNetworkConfigurationUpdater::~UserNetworkConfigurationUpdater() { + // CertLoader may be not initialized in tests. + if (chromeos::CertLoader::IsInitialized()) + chromeos::CertLoader::Get()->RemovePolicyCertificateProvider(this); +} // static std::unique_ptr<UserNetworkConfigurationUpdater> @@ -55,18 +56,6 @@ SetClientCertificateImporter(std::move(client_certificate_importer)); } -void UserNetworkConfigurationUpdater::AddPolicyProvidedCertsObserver( - PolicyCertificateProvider::Observer* observer) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - observer_list_.AddObserver(observer); -} - -void UserNetworkConfigurationUpdater::RemovePolicyProvidedCertsObserver( - PolicyCertificateProvider::Observer* observer) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - observer_list_.RemoveObserver(observer); -} - UserNetworkConfigurationUpdater::UserNetworkConfigurationUpdater( Profile* profile, bool allow_trusted_certs_from_policy, @@ -75,11 +64,10 @@ chromeos::ManagedNetworkConfigurationHandler* network_config_handler) : NetworkConfigurationUpdater(onc::ONC_SOURCE_USER_POLICY, key::kOpenNetworkConfiguration, + allow_trusted_certs_from_policy, policy_service, network_config_handler), - allow_trusted_certificates_from_policy_(allow_trusted_certs_from_policy), user_(&user), - certs_(std::make_unique<OncParsedCertificates>()), weak_factory_(this) { // The updater is created with |client_certificate_importer_| unset and is // responsible for creating it. This requires |GetNSSCertDatabaseForProfile| @@ -89,64 +77,24 @@ registrar_.Add(this, chrome::NOTIFICATION_PROFILE_ADDED, content::Source<Profile>(profile)); + + // Make sure that the |CertLoader| which makes certificates available to the + // chromeos network code gets policy-pushed certificates from the primary + // profile. This assumes that a |UserNetworkConfigurationUpdater| is only + // created for the primary profile. + // CertLoader may be not initialized in tests. + if (chromeos::CertLoader::IsInitialized()) + chromeos::CertLoader::Get()->AddPolicyCertificateProvider(this); } -net::CertificateList -UserNetworkConfigurationUpdater::GetAllServerAndAuthorityCertificates() const { - return GetServerAndAuthorityCertificates(base::BindRepeating( - [](const OncParsedCertificates::ServerOrAuthorityCertificate& cert) { - return true; - })); -} - -net::CertificateList -UserNetworkConfigurationUpdater::GetWebTrustedCertificates() const { - if (!allow_trusted_certificates_from_policy_) - return net::CertificateList(); - - return GetServerAndAuthorityCertificates(base::BindRepeating( - [](const OncParsedCertificates::ServerOrAuthorityCertificate& cert) { - return cert.web_trust_requested(); - })); -} - -net::CertificateList -UserNetworkConfigurationUpdater::GetCertificatesWithoutWebTrust() const { - if (!allow_trusted_certificates_from_policy_) - return GetAllServerAndAuthorityCertificates(); - - return GetServerAndAuthorityCertificates(base::BindRepeating( - [](const OncParsedCertificates::ServerOrAuthorityCertificate& cert) { - return !cert.web_trust_requested(); - })); -} - -void UserNetworkConfigurationUpdater::ImportCertificates( - const base::ListValue& certificates_onc) { +void UserNetworkConfigurationUpdater::ImportClientCertificates() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - std::unique_ptr<OncParsedCertificates> incoming_certs = - std::make_unique<OncParsedCertificates>(certificates_onc); - - bool server_or_authority_certs_changed = - certs_->server_or_authority_certificates() != - incoming_certs->server_or_authority_certificates(); - bool client_certs_changed = - certs_->client_certificates() != incoming_certs->client_certificates(); - - if (!server_or_authority_certs_changed && !client_certs_changed) - return; - - certs_ = std::move(incoming_certs); - - if (server_or_authority_certs_changed) - NotifyPolicyProvidedCertsChanged(); - // If certificate importer is not yet set, the import of client certificates // will be re-triggered in SetClientCertificateImporter. - if (client_certificate_importer_ && client_certs_changed) { + if (client_certificate_importer_) { client_certificate_importer_->ImportClientCertificates( - certs_->client_certificates(), base::DoNothing()); + GetClientCertificates(), base::DoNothing()); } } @@ -203,38 +151,10 @@ client_certificate_importer_ == nullptr; client_certificate_importer_ = std::move(client_certificate_importer); - if (initial_client_certificate_importer && - !certs_->client_certificates().empty()) { + if (initial_client_certificate_importer && !GetClientCertificates().empty()) { client_certificate_importer_->ImportClientCertificates( - certs_->client_certificates(), base::DoNothing()); + GetClientCertificates(), base::DoNothing()); } } -void UserNetworkConfigurationUpdater::NotifyPolicyProvidedCertsChanged() { - net::CertificateList all_server_and_authority_certs = - GetAllServerAndAuthorityCertificates(); - net::CertificateList trust_anchors = GetWebTrustedCertificates(); - - for (auto& observer : observer_list_) { - observer.OnPolicyProvidedCertsChanged(all_server_and_authority_certs, - trust_anchors); - } -} - -net::CertificateList -UserNetworkConfigurationUpdater::GetServerAndAuthorityCertificates( - ServerOrAuthorityCertPredicate predicate) const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - net::CertificateList certificates; - - for (const OncParsedCertificates::ServerOrAuthorityCertificate& - server_or_authority_cert : - certs_->server_or_authority_certificates()) { - if (predicate.Run(server_or_authority_cert)) - certificates.push_back(server_or_authority_cert.certificate()); - } - - return certificates; -} } // namespace policy
diff --git a/chrome/browser/chromeos/policy/user_network_configuration_updater.h b/chrome/browser/chromeos/policy/user_network_configuration_updater.h index d37e9f7e..07848b86 100644 --- a/chrome/browser/chromeos/policy/user_network_configuration_updater.h +++ b/chrome/browser/chromeos/policy/user_network_configuration_updater.h
@@ -12,11 +12,7 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" -#include "base/observer_list.h" -#include "base/sequence_checker.h" #include "chrome/browser/chromeos/policy/network_configuration_updater.h" -#include "chrome/browser/chromeos/policy/policy_certificate_provider.h" -#include "chromeos/network/onc/onc_parsed_certificates.h" #include "components/keyed_service/core/keyed_service.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" @@ -53,7 +49,6 @@ // expansion with the user's name (or email address, etc.) and handling of "Web" // trust of certificates. class UserNetworkConfigurationUpdater : public NetworkConfigurationUpdater, - public PolicyCertificateProvider, public KeyedService, public content::NotificationObserver { public: @@ -72,15 +67,6 @@ PolicyService* policy_service, chromeos::ManagedNetworkConfigurationHandler* network_config_handler); - // PolicyCertificateProvider: - void AddPolicyProvidedCertsObserver( - PolicyCertificateProvider::Observer* observer) override; - void RemovePolicyProvidedCertsObserver( - PolicyCertificateProvider::Observer* observer) override; - net::CertificateList GetAllServerAndAuthorityCertificates() const override; - net::CertificateList GetWebTrustedCertificates() const override; - net::CertificateList GetCertificatesWithoutWebTrust() const override; - // Helper method to expose |SetClientCertificateImporter| for usage in tests. // Note that the CertificateImporter is only used for importing client // certificates. @@ -90,11 +76,6 @@ private: class CrosTrustAnchorProvider; - // A predicate used for filtering server or authority certificates. - using ServerOrAuthorityCertPredicate = base::RepeatingCallback<bool( - const chromeos::onc::OncParsedCertificates::ServerOrAuthorityCertificate& - cert)>; - UserNetworkConfigurationUpdater( Profile* profile, bool allow_trusted_certs_from_policy, @@ -103,7 +84,8 @@ chromeos::ManagedNetworkConfigurationHandler* network_config_handler); // NetworkConfigurationUpdater: - void ImportCertificates(const base::ListValue& certificates_onc) override; + void ImportClientCertificates() override; + void ApplyNetworkPolicy( base::ListValue* network_configs_onc, base::DictionaryValue* global_network_config) override; @@ -123,25 +105,9 @@ void SetClientCertificateImporter( std::unique_ptr<chromeos::onc::CertificateImporter> certificate_importer); - void NotifyPolicyProvidedCertsChanged(); - - // Returns all server and authority certificates successfully parsed from ONC - // for which |predicate| returns true. - net::CertificateList GetServerAndAuthorityCertificates( - ServerOrAuthorityCertPredicate predicate) const; - - // Whether Web trust is allowed or not. - bool allow_trusted_certificates_from_policy_; - // The user for whom the user policy will be applied. const user_manager::User* user_; - base::ObserverList<PolicyCertificateProvider::Observer, true>::Unchecked - observer_list_; - - // Holds certificates from the last parsed ONC policy. - std::unique_ptr<chromeos::onc::OncParsedCertificates> certs_; - // Certificate importer to be used for importing policy defined client // certificates. Set by |SetClientCertificateImporter|. std::unique_ptr<chromeos::onc::CertificateImporter> @@ -149,8 +115,6 @@ content::NotificationRegistrar registrar_; - SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<UserNetworkConfigurationUpdater> weak_factory_; DISALLOW_COPY_AND_ASSIGN(UserNetworkConfigurationUpdater);
diff --git a/chrome/browser/chromeos/policy/user_network_configuration_updater_factory_browsertest.cc b/chrome/browser/chromeos/policy/user_network_configuration_updater_factory_browsertest.cc index 1eabdf41..3d946d9e 100644 --- a/chrome/browser/chromeos/policy/user_network_configuration_updater_factory_browsertest.cc +++ b/chrome/browser/chromeos/policy/user_network_configuration_updater_factory_browsertest.cc
@@ -14,13 +14,10 @@ #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/login/existing_user_controller.h" #include "chrome/browser/chromeos/login/screens/gaia_view.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/ui/login_display_host.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/policy/device_policy_cros_browser_test.h" #include "chrome/browser/chromeos/policy/login_policy_test_base.h" -#include "chrome/browser/chromeos/policy/policy_certificate_provider.h" #include "chrome/browser/chromeos/policy/user_network_configuration_updater.h" #include "chrome/browser/chromeos/policy/user_network_configuration_updater_factory.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" @@ -31,11 +28,13 @@ #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h" #include "chrome/test/base/in_process_browser_test.h" +#include "chromeos/cert_loader.h" #include "chromeos/chromeos_switches.h" #include "chromeos/chromeos_test_utils.h" #include "chromeos/network/onc/onc_certificate_importer.h" #include "chromeos/network/onc/onc_certificate_importer_impl.h" #include "chromeos/network/onc/onc_test_utils.h" +#include "chromeos/policy_certificate_provider.h" #include "components/policy/core/browser/browser_policy_connector.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" @@ -51,10 +50,12 @@ #include "content/public/browser/notification_service.h" #include "content/public/test/browser_test.h" #include "content/public/test/test_utils.h" +#include "crypto/scoped_test_nss_db.h" #include "net/base/test_completion_callback.h" #include "net/cert/cert_database.h" #include "net/cert/cert_verifier.h" #include "net/cert/nss_cert_database.h" +#include "net/cert/x509_util_nss.h" #include "net/test/cert_test_util.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" @@ -73,42 +74,69 @@ // A PEM-encoded certificate which was signed by the Authority specified in // |kRootCertOnc|. constexpr char kGoodCert[] = "ok_cert.pem"; +// The PEM-encoded Authority certificate specified by |kRootCertOnc|. +constexpr char kRootCert[] = "root_ca_cert.pem"; constexpr char kDeviceLocalAccountId[] = "dla1@example.com"; // Allows waiting until the list of policy-pushed web-trusted certificates // changes. class WebTrustedCertsChangedObserver - : public PolicyCertificateProvider::Observer { + : public chromeos::PolicyCertificateProvider::Observer { public: - WebTrustedCertsChangedObserver() {} + WebTrustedCertsChangedObserver() = default; - // PolicyCertificateProvider::Observer + // chromeos::PolicyCertificateProvider::Observer void OnPolicyProvidedCertsChanged( const net::CertificateList& all_server_and_authority_certs, const net::CertificateList& trust_anchors) override { - run_loop.Quit(); + run_loop_.Quit(); } - void Wait() { run_loop.Run(); } + void Wait() { run_loop_.Run(); } private: - base::RunLoop run_loop; + base::RunLoop run_loop_; DISALLOW_COPY_AND_ASSIGN(WebTrustedCertsChangedObserver); }; +// Allows waiting until |CertLoader| updates its list of certificates. +class CertLoaderTestObserver : public chromeos::CertLoader::Observer { + public: + explicit CertLoaderTestObserver(chromeos::CertLoader* cert_loader) + : cert_loader_(cert_loader) { + cert_loader_->AddObserver(this); + } + + ~CertLoaderTestObserver() override { cert_loader_->RemoveObserver(this); } + + // chromeos::CertLoader::Observer + void OnCertificatesLoaded( + const net::ScopedCERTCertificateList& all_certs) override { + run_loop_.Quit(); + } + + void Wait() { run_loop_.Run(); } + + private: + chromeos::CertLoader* cert_loader_; + base::RunLoop run_loop_; + + DISALLOW_COPY_AND_ASSIGN(CertLoaderTestObserver); +}; + // Allows waiting until the |CertDatabase| notifies its observers that it has // changd. class CertDatabaseChangedObserver : public net::CertDatabase::Observer { public: CertDatabaseChangedObserver() {} - void OnCertDBChanged() override { run_loop.Quit(); } + void OnCertDBChanged() override { run_loop_.Quit(); } - void Wait() { run_loop.Run(); } + void Wait() { run_loop_.Run(); } private: - base::RunLoop run_loop; + base::RunLoop run_loop_; DISALLOW_COPY_AND_ASSIGN(CertDatabaseChangedObserver); }; @@ -224,12 +252,28 @@ return cert_found; } +bool IsCertInCertificateList(const net::X509Certificate* cert, + const net::ScopedCERTCertificateList& cert_list) { + for (const auto& cert_list_element : cert_list) { + if (net::x509_util::IsSameCertificate(cert_list_element.get(), cert)) + return true; + } + return false; +} + } // namespace // Base class for testing if policy-provided trust roots take effect. class PolicyProvidedTrustAnchorsTestBase : public DevicePolicyCrosBrowserTest { protected: - PolicyProvidedTrustAnchorsTestBase() {} + PolicyProvidedTrustAnchorsTestBase() { + // Use the same testing slot as private and public slot for testing. + test_nss_cert_db_ = std::make_unique<net::NSSCertDatabase>( + crypto::ScopedPK11Slot( + PK11_ReferenceSlot(test_nssdb_.slot())) /* public slot */, + crypto::ScopedPK11Slot( + PK11_ReferenceSlot(test_nssdb_.slot())) /* private slot */); + } // InProcessBrowserTest: ~PolicyProvidedTrustAnchorsTestBase() override {} @@ -237,11 +281,19 @@ void SetUpInProcessBrowserTestFixture() override { // Load the certificate which is only OK if the policy-provided authority is // actually trusted. - base::FilePath cert_pem_file_path; + base::FilePath server_cert_pem_file_path; chromeos::test_utils::GetTestDataPath(kNetworkComponentDirectory, kGoodCert, - &cert_pem_file_path); - test_server_cert_ = net::ImportCertFromFile( - cert_pem_file_path.DirName(), cert_pem_file_path.BaseName().value()); + &server_cert_pem_file_path); + test_server_cert_ = + net::ImportCertFromFile(server_cert_pem_file_path.DirName(), + server_cert_pem_file_path.BaseName().value()); + + base::FilePath root_cert_pem_file_path; + chromeos::test_utils::GetTestDataPath(kNetworkComponentDirectory, kRootCert, + &root_cert_pem_file_path); + test_root_cert_ = + net::ImportCertFromFile(root_cert_pem_file_path.DirName(), + root_cert_pem_file_path.BaseName().value()); // Set up the mock policy provider. EXPECT_CALL(provider_, IsInitializationComplete(testing::_)) @@ -285,6 +337,10 @@ protected: // Certificate which is signed by authority specified in |kRootCertOnc|. scoped_refptr<net::X509Certificate> test_server_cert_; + scoped_refptr<net::X509Certificate> test_root_cert_; + + crypto::ScopedTestNSSDB test_nssdb_; + std::unique_ptr<net::NSSCertDatabase> test_nss_cert_db_; }; class PolicyProvidedTrustAnchorsRegularUserTest @@ -297,6 +353,29 @@ VerifyTestServerCert(browser()->profile(), test_server_cert_)); } +IN_PROC_BROWSER_TEST_F(PolicyProvidedTrustAnchorsRegularUserTest, + AuthorityAvailableThroughCertLoader) { + // Set |CertLoader| to use a test NSS database - otherwise, it is not properly + // initialized because |UserSessionManager| only sets the primary user's NSS + // Database in |CertLoader| if running on ChromeOS according to + // |base::SysInfo|. + ASSERT_TRUE(chromeos::CertLoader::IsInitialized()); + chromeos::CertLoader::Get()->SetUserNSSDB(test_nss_cert_db_.get()); + + EXPECT_FALSE(IsCertInCertificateList( + test_root_cert_.get(), chromeos::CertLoader::Get()->all_certs())); + + CertLoaderTestObserver cert_loader_observer(chromeos::CertLoader::Get()); + SetRootCertONCPolicy(browser()->profile()); + cert_loader_observer.Wait(); + + // Check that |CertLoader| is aware of the authority certificate. + // (Web Trust does not matter for the CertLoader, but we currently only set a + // policy with a certificate requesting Web Trust here). + EXPECT_TRUE(IsCertInCertificateList( + test_root_cert_.get(), chromeos::CertLoader::Get()->all_certs())); +} + // Base class for testing policy-provided trust roots with device-local // accounts. Needs device policy. class PolicyProvidedTrustAnchorsDeviceLocalAccountTest
diff --git a/chrome/browser/chromeos/smb_client/smb_provider.cc b/chrome/browser/chromeos/smb_client/smb_provider.cc index 0418ec1..0321c9b9 100644 --- a/chrome/browser/chromeos/smb_client/smb_provider.cc +++ b/chrome/browser/chromeos/smb_client/smb_provider.cc
@@ -12,6 +12,8 @@ #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/settings_window_manager_chromeos.h" #include "chrome/common/webui_url_constants.h" +#include "chrome/grit/generated_resources.h" +#include "ui/base/l10n/l10n_util.h" #include "url/gurl.h" namespace chromeos { @@ -25,7 +27,7 @@ extensions::SOURCE_NETWORK), // TODO(baileyberro): Localize this string, so it shows correctly in all // languages. See l10n_util::GetStringUTF8. - name_("SMB Shares"), + name_(l10n_util::GetStringUTF8(IDS_SMB_SHARES_ADD_SERVICE_MENU_OPTION)), unmount_callback_(std::move(unmount_callback)) { icon_set_.SetIcon(IconSet::IconSize::SIZE_16x16, GURL("chrome://theme/IDR_SMB_ICON"));
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 9780c60..1a30509d 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -1093,11 +1093,6 @@ "Enable navigation suggestions for URLs that are visually similar to " "popular domains or to domains with a site engagement score."; -const char kMacViewsAutofillPopupName[] = - "Uses the Views Autofill Popup on Mac"; -const char kMacViewsAutofillPopupDescription[] = - "Autofill popup will be shown using the Views toolkit rather than Cocoa."; - const char kMarkHttpAsName[] = "Mark non-secure origins as non-secure"; const char kMarkHttpAsDescription[] = "Change the UI treatment for HTTP pages";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 8b821a6..ec9202ad 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -674,9 +674,6 @@ extern const char kLookalikeUrlNavigationSuggestionsName[]; extern const char kLookalikeUrlNavigationSuggestionsDescription[]; -extern const char kMacViewsAutofillPopupName[]; -extern const char kMacViewsAutofillPopupDescription[]; - extern const char kMarkHttpAsName[]; extern const char kMarkHttpAsDescription[]; extern const char kMarkHttpAsDangerous[];
diff --git a/chrome/browser/media_galleries/media_galleries_dialog_controller.h b/chrome/browser/media_galleries/media_galleries_dialog_controller.h index b55570e..0ab5bd2 100644 --- a/chrome/browser/media_galleries/media_galleries_dialog_controller.h +++ b/chrome/browser/media_galleries/media_galleries_dialog_controller.h
@@ -35,12 +35,6 @@ // Constructs a platform-specific dialog owned and controlled by |controller|. static MediaGalleriesDialog* Create( MediaGalleriesDialogController* controller); -#if defined(OS_MACOSX) - // Temporary shim for Polychrome. See bottom of first comment in - // https://crbug.com/80495 for details. - static MediaGalleriesDialog* CreateCocoa( - MediaGalleriesDialogController* controller); -#endif private: friend class TestMediaGalleriesAddScanResultsFunction;
diff --git a/chrome/browser/metrics/chrome_metrics_service_client.cc b/chrome/browser/metrics/chrome_metrics_service_client.cc index 90ab7691..61bba17 100644 --- a/chrome/browser/metrics/chrome_metrics_service_client.cc +++ b/chrome/browser/metrics/chrome_metrics_service_client.cc
@@ -608,8 +608,7 @@ metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::NetworkMetricsProvider>( - std::make_unique<metrics::NetworkQualityEstimatorProviderImpl>( - g_browser_process->io_thread()))); + std::make_unique<metrics::NetworkQualityEstimatorProviderImpl>())); // Currently, we configure OmniboxMetricsProvider to not log events to UMA // if there is a single incognito session visible. In the future, it may @@ -730,8 +729,7 @@ void ChromeMetricsServiceClient::RegisterUKMProviders() { ukm_service_->RegisterMetricsProvider( std::make_unique<metrics::NetworkMetricsProvider>( - std::make_unique<metrics::NetworkQualityEstimatorProviderImpl>( - g_browser_process->io_thread()))); + std::make_unique<metrics::NetworkQualityEstimatorProviderImpl>())); #if defined(OS_CHROMEOS) ukm_service_->RegisterMetricsProvider(
diff --git a/chrome/browser/metrics/network_quality_estimator_provider_impl.cc b/chrome/browser/metrics/network_quality_estimator_provider_impl.cc index 75cf5829..c87b8b5 100644 --- a/chrome/browser/metrics/network_quality_estimator_provider_impl.cc +++ b/chrome/browser/metrics/network_quality_estimator_provider_impl.cc
@@ -5,77 +5,36 @@ #include "chrome/browser/metrics/network_quality_estimator_provider_impl.h" #include "base/sequenced_task_runner.h" -#include "base/task/post_task.h" -#include "chrome/browser/io_thread.h" -#include "content/public/browser/browser_task_traits.h" +#include "chrome/browser/browser_process.h" #include "content/public/browser/browser_thread.h" -#include "net/url_request/url_request_context.h" - -namespace net { -class NetworkQualityEstimator; -} namespace metrics { -namespace { - -void GetNetworkQualityEstimatorOnIOThread( - base::Callback<void(net::NetworkQualityEstimator*)> io_callback, - IOThread* io_thread) { - DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); - - net::NetworkQualityEstimator* network_quality_estimator = - io_thread->globals()->system_request_context->network_quality_estimator(); - // |network_quality_estimator| may be nullptr when running the network service - // out of process. - // TODO(mmenke): Hook this up through a Mojo API. - if (network_quality_estimator) { - // It is safe to run |io_callback| here since it is guaranteed to be - // non-null. - io_callback.Run(network_quality_estimator); - } -} - -} // namespace - -NetworkQualityEstimatorProviderImpl::NetworkQualityEstimatorProviderImpl( - IOThread* io_thread) - : io_thread_(io_thread), weak_ptr_factory_(this) { +NetworkQualityEstimatorProviderImpl::NetworkQualityEstimatorProviderImpl() + : weak_ptr_factory_(this) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); - DCHECK(io_thread_); } NetworkQualityEstimatorProviderImpl::~NetworkQualityEstimatorProviderImpl() { DCHECK(thread_checker_.CalledOnValidThread()); } -scoped_refptr<base::SequencedTaskRunner> -NetworkQualityEstimatorProviderImpl::GetTaskRunner() { - DCHECK(thread_checker_.CalledOnValidThread()); - return base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO}); -} - -void NetworkQualityEstimatorProviderImpl::PostReplyNetworkQualityEstimator( - base::Callback<void(net::NetworkQualityEstimator*)> io_callback) { +void NetworkQualityEstimatorProviderImpl::PostReplyNetworkQualityTracker( + base::OnceCallback<void(network::NetworkQualityTracker*)> callback) { DCHECK(thread_checker_.CalledOnValidThread()); if (!content::BrowserThread::IsThreadInitialized( content::BrowserThread::IO)) { // IO thread is not yet initialized. Try again in the next message pump. bool task_posted = base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&NetworkQualityEstimatorProviderImpl:: - PostReplyNetworkQualityEstimator, - weak_ptr_factory_.GetWeakPtr(), io_callback)); + FROM_HERE, + base::BindOnce(&NetworkQualityEstimatorProviderImpl:: + PostReplyNetworkQualityTracker, + weak_ptr_factory_.GetWeakPtr(), std::move(callback))); DCHECK(task_posted); return; } - bool task_posted = - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO}) - ->PostTask(FROM_HERE, - base::Bind(&GetNetworkQualityEstimatorOnIOThread, - io_callback, io_thread_)); - DCHECK(task_posted); + std::move(callback).Run(g_browser_process->network_quality_tracker()); } } // namespace metrics
diff --git a/chrome/browser/metrics/network_quality_estimator_provider_impl.h b/chrome/browser/metrics/network_quality_estimator_provider_impl.h index c6e21ac..aa805f7 100644 --- a/chrome/browser/metrics/network_quality_estimator_provider_impl.h +++ b/chrome/browser/metrics/network_quality_estimator_provider_impl.h
@@ -9,25 +9,25 @@ #include "base/threading/thread_checker.h" #include "components/metrics/net/network_metrics_provider.h" -class IOThread; +namespace network { +class NetworkQualityTracker; +} namespace metrics { // Implements NetworkMetricsProvider::NetworkQualityEstimatorProvider. Provides -// NetworkQualityEstimator by querying the IOThread. Lives on UI thread. +// NetworkQualityTracker. Lives on UI thread. class NetworkQualityEstimatorProviderImpl : public NetworkMetricsProvider::NetworkQualityEstimatorProvider { public: - explicit NetworkQualityEstimatorProviderImpl(IOThread* io_thread); + NetworkQualityEstimatorProviderImpl(); ~NetworkQualityEstimatorProviderImpl() override; private: // NetworkMetricsProvider::NetworkQualityEstimatorProvider: - scoped_refptr<base::SequencedTaskRunner> GetTaskRunner() override; - void PostReplyNetworkQualityEstimator( - base::Callback<void(net::NetworkQualityEstimator*)> io_callback) override; - - IOThread* io_thread_; + void PostReplyNetworkQualityTracker( + base::OnceCallback<void(network::NetworkQualityTracker*)> callback) + override; base::ThreadChecker thread_checker_;
diff --git a/chrome/browser/metrics/ukm_browsertest.cc b/chrome/browser/metrics/ukm_browsertest.cc index 77b7181..b890eaf 100644 --- a/chrome/browser/metrics/ukm_browsertest.cc +++ b/chrome/browser/metrics/ukm_browsertest.cc
@@ -45,6 +45,7 @@ #include "content/public/test/test_utils.h" #include "services/metrics/public/cpp/ukm_recorder.h" #include "services/metrics/public/cpp/ukm_source.h" +#include "services/network/test/test_network_quality_tracker.h" #include "third_party/metrics_proto/ukm/report.pb.h" #include "third_party/zlib/google/compression_utils.h" @@ -543,6 +544,47 @@ CloseBrowserSynchronously(sync_browser); } +// Verifies that network provider attaches effective connection type correctly +// to the UKM report. +IN_PROC_BROWSER_TEST_P(UkmBrowserTest, NetworkProviderPopulatesSystemProfile) { + // Override network quality to 2G. This should cause the + // |max_effective_connection_type| in the system profile to be set to 2G. + g_browser_process->network_quality_tracker() + ->ReportEffectiveConnectionTypeForTesting( + net::EFFECTIVE_CONNECTION_TYPE_2G); + + MetricsConsentOverride metrics_consent(true); + + Profile* profile = ProfileManager::GetActiveUserProfile(); + std::unique_ptr<ProfileSyncServiceHarness> harness = + EnableSyncForProfile(profile); + + Browser* sync_browser = CreateBrowser(profile); + EXPECT_TRUE(ukm_enabled()); + uint64_t original_client_id = client_id(); + EXPECT_NE(0U, original_client_id); + + // Override network quality to 4G. This should cause the + // |max_effective_connection_type| in the system profile to be set to 4G. + g_browser_process->network_quality_tracker() + ->ReportEffectiveConnectionTypeForTesting( + net::EFFECTIVE_CONNECTION_TYPE_4G); + + // Make sure there is a persistent log. + BuildAndStoreUkmLog(); + EXPECT_TRUE(HasUnsentUkmLogs()); + // Check log contents. + ukm::Report report = GetUkmReport(); + + EXPECT_EQ(SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_2G, + report.system_profile().network().min_effective_connection_type()); + EXPECT_EQ(SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_4G, + report.system_profile().network().max_effective_connection_type()); + + harness->service()->RequestStop(browser_sync::ProfileSyncService::CLEAR_DATA); + CloseBrowserSynchronously(sync_browser); +} + // Make sure that providing consent doesn't enable UKM when sync is disabled. // Keep in sync with UkmTest.consentAddedButNoSyncCheck in // chrome/android/sync_shell/javatests/src/org/chromium/chrome/browser/sync/
diff --git a/chrome/browser/notifications/notification_platform_bridge_win.cc b/chrome/browser/notifications/notification_platform_bridge_win.cc index d2f9077..b642c8a 100644 --- a/chrome/browser/notifications/notification_platform_bridge_win.cc +++ b/chrome/browser/notifications/notification_platform_bridge_win.cc
@@ -132,14 +132,23 @@ content::BrowserThread::UI> { public: explicit NotificationPlatformBridgeWinImpl( - scoped_refptr<base::SequencedTaskRunner> task_runner) - : image_retainer_( - std::make_unique<NotificationImageRetainer>(task_runner)), - task_runner_(std::move(task_runner)) { - DCHECK(task_runner_); - com_functions_initialized_ = - base::win::ResolveCoreWinRTDelayload() && - ScopedHString::ResolveCoreWinRTStringDelayload(); + scoped_refptr<base::SequencedTaskRunner> notification_task_runner) + : com_functions_initialized_( + base::win::ResolveCoreWinRTDelayload() && + ScopedHString::ResolveCoreWinRTStringDelayload()), + notification_task_runner_(std::move(notification_task_runner)), + // file_deletion_task_runner_ runs tasks to delete notification image + // files on the disk. This task will be retried on each Chrome startup, + // so it's okay to specify TaskShutdownBehavior to be + // CONTINUE_ON_SHUTDOWN (i.e., ignore this task for all purposes at + // shutdown). + file_deletion_task_runner_(base::CreateSequencedTaskRunnerWithTraits( + {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})), + image_retainer_(std::make_unique<NotificationImageRetainer>( + file_deletion_task_runner_)) { + DCHECK(notification_task_runner_); + DCHECK(file_deletion_task_runner_); } // Obtain an IToastNotification interface from a given XML (provided by the @@ -304,7 +313,7 @@ std::unique_ptr<NotificationCommon::Metadata> metadata) { // TODO(finnur): Move this to a RoInitialized thread, as per // crbug.com/761039. - DCHECK(task_runner_->RunsTasksInCurrentSequence()); + DCHECK(notification_task_runner_->RunsTasksInCurrentSequence()); if (!notifier_for_testing_ && !notifier_.Get() && FAILED(InitializeToastNotifier())) { @@ -397,7 +406,7 @@ void Close(const std::string& profile_id, bool incognito, const std::string& notification_id) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); + DCHECK(notification_task_runner_->RunsTasksInCurrentSequence()); mswr::ComPtr<winui::Notifications::IToastNotificationHistory> history; if (!GetIToastNotificationHistory(&history)) { @@ -537,7 +546,7 @@ GetDisplayedNotificationsCallback callback) const { // TODO(finnur): Once this function is properly implemented, add DCHECK(UI) // to NotificationPlatformBridgeWin::GetDisplayed. - DCHECK(task_runner_->RunsTasksInCurrentSequence()); + DCHECK(notification_task_runner_->RunsTasksInCurrentSequence()); std::vector<mswr::ComPtr<winui::Notifications::IToastNotification>> notifications = GetNotifications(profile_id, incognito); @@ -579,7 +588,7 @@ void SetReadyCallback( NotificationPlatformBridge::NotificationBridgeReadyCallback callback) { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); + DCHECK(notification_task_runner_->RunsTasksInCurrentSequence()); bool activator_registered = IsToastActivatorRegistered(); bool shortcut_installed = @@ -745,14 +754,17 @@ static winui::Notifications::IToastNotifier* notifier_for_testing_; // Whether the required functions from combase.dll have been loaded. - bool com_functions_initialized_; + const bool com_functions_initialized_; + + // The task runner running notification related tasks. + scoped_refptr<base::SequencedTaskRunner> notification_task_runner_; + + // The task runner running tasks to delete files. + scoped_refptr<base::SequencedTaskRunner> file_deletion_task_runner_; // An object that keeps temp files alive long enough for Windows to pick up. std::unique_ptr<NotificationImageRetainer> image_retainer_; - // The task runner this object runs on. - scoped_refptr<base::SequencedTaskRunner> task_runner_; - // The ToastNotifier to use to communicate with the Action Center. mswr::ComPtr<winui::Notifications::IToastNotifier> notifier_; @@ -766,9 +778,11 @@ NotificationPlatformBridgeWinImpl::notifier_for_testing_ = nullptr; NotificationPlatformBridgeWin::NotificationPlatformBridgeWin() { - task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_BLOCKING}); - impl_ = base::MakeRefCounted<NotificationPlatformBridgeWinImpl>(task_runner_); + notification_task_runner_ = base::CreateSequencedTaskRunnerWithTraits( + {base::MayBlock(), base::TaskPriority::USER_BLOCKING, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); + impl_ = base::MakeRefCounted<NotificationPlatformBridgeWinImpl>( + notification_task_runner_); } NotificationPlatformBridgeWin::~NotificationPlatformBridgeWin() = default; @@ -786,7 +800,7 @@ notification, /*include_body_image=*/true, /*include_small_image=*/true, /*include_icon_images=*/true); - task_runner_->PostTask( + notification_task_runner_->PostTask( FROM_HERE, base::BindOnce(&NotificationPlatformBridgeWinImpl::Display, impl_, notification_type, GetProfileId(profile), @@ -797,7 +811,7 @@ void NotificationPlatformBridgeWin::Close(Profile* profile, const std::string& notification_id) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - task_runner_->PostTask( + notification_task_runner_->PostTask( FROM_HERE, base::BindOnce(&NotificationPlatformBridgeWinImpl::Close, impl_, GetProfileId(profile), profile->IsOffTheRecord(), notification_id)); @@ -806,7 +820,7 @@ void NotificationPlatformBridgeWin::GetDisplayed( Profile* profile, GetDisplayedNotificationsCallback callback) const { - task_runner_->PostTask( + notification_task_runner_->PostTask( FROM_HERE, base::BindOnce(&NotificationPlatformBridgeWinImpl::GetDisplayed, impl_, GetProfileId(profile), profile->IsOffTheRecord(), @@ -816,7 +830,7 @@ void NotificationPlatformBridgeWin::SetReadyCallback( NotificationBridgeReadyCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - task_runner_->PostTask( + notification_task_runner_->PostTask( FROM_HERE, base::BindOnce(&NotificationPlatformBridgeWinImpl::SetReadyCallback, impl_, std::move(callback))); @@ -887,7 +901,7 @@ winui::Notifications::IToastActivatedEventArgs* args, const base::Optional<bool>& by_user) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - task_runner_->PostTask( + notification_task_runner_->PostTask( FROM_HERE, base::BindOnce( &NotificationPlatformBridgeWinImpl::ForwardHandleEventForTesting,
diff --git a/chrome/browser/notifications/notification_platform_bridge_win.h b/chrome/browser/notifications/notification_platform_bridge_win.h index e6a172c..7e4f489e 100644 --- a/chrome/browser/notifications/notification_platform_bridge_win.h +++ b/chrome/browser/notifications/notification_platform_bridge_win.h
@@ -91,7 +91,7 @@ scoped_refptr<NotificationPlatformBridgeWinImpl> impl_; - scoped_refptr<base::SequencedTaskRunner> task_runner_; + scoped_refptr<base::SequencedTaskRunner> notification_task_runner_; DISALLOW_COPY_AND_ASSIGN(NotificationPlatformBridgeWin); };
diff --git a/chrome/browser/notifications/win/mock_itoastnotification.cc b/chrome/browser/notifications/win/mock_itoastnotification.cc index e077555..5eec676 100644 --- a/chrome/browser/notifications/win/mock_itoastnotification.cc +++ b/chrome/browser/notifications/win/mock_itoastnotification.cc
@@ -35,7 +35,7 @@ return hr; } - Microsoft::WRL::ComPtr<winxml::Dom::IXmlDocument> xml_document; + mswr::ComPtr<winxml::Dom::IXmlDocument> xml_document; hr = xml_document_io.CopyTo(xml_document.GetAddressOf()); if (FAILED(hr)) { LOG(ERROR) << "Unable to copy to XMLDoc " << hr;
diff --git a/chrome/browser/page_load_metrics/observers/use_counter/ukm_features.cc b/chrome/browser/page_load_metrics/observers/use_counter/ukm_features.cc index d19b182..3bb007a1 100644 --- a/chrome/browser/page_load_metrics/observers/use_counter/ukm_features.cc +++ b/chrome/browser/page_load_metrics/observers/use_counter/ukm_features.cc
@@ -57,6 +57,7 @@ WebFeature::kDocumentLevelPassiveDefaultEventListenerPreventedWheel, WebFeature::kDocumentDomainBlockedCrossOriginAccess, WebFeature::kDocumentDomainEnabledCrossOriginAccess, + WebFeature::kSuppressHistoryEntryWithoutUserGesture, })); return opt_in_features.count(feature); }
diff --git a/chrome/browser/resource_coordinator/leveldb_site_characteristics_database.cc b/chrome/browser/resource_coordinator/leveldb_site_characteristics_database.cc index 6fb5cd0..388e202e 100644 --- a/chrome/browser/resource_coordinator/leveldb_site_characteristics_database.cc +++ b/chrome/browser/resource_coordinator/leveldb_site_characteristics_database.cc
@@ -15,6 +15,7 @@ #include "base/strings/string_number_conversions.h" #include "base/task_runner_util.h" #include "base/threading/scoped_blocking_call.h" +#include "build/build_config.h" #include "chrome/browser/resource_coordinator/utils.h" #include "third_party/leveldatabase/env_chromium.h" #include "third_party/leveldatabase/leveldb_chrome.h" @@ -84,6 +85,11 @@ return false; } +struct DatabaseSizeResult { + base::Optional<int64_t> num_rows; + base::Optional<int64_t> on_disk_size_kb; +}; + } // namespace // Version history: @@ -135,6 +141,8 @@ void RemoveSiteCharacteristicsFromDB( const std::vector<url::Origin>& site_origin); void ClearDatabase(); + // Returns a struct with unset fields on failure. + DatabaseSizeResult GetDatabaseSize(); bool DBIsInitialized() { return db_ != nullptr; } @@ -295,6 +303,40 @@ } } +DatabaseSizeResult +LevelDBSiteCharacteristicsDatabase::AsyncHelper::GetDatabaseSize() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (!db_) + return DatabaseSizeResult(); + + base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK); + DatabaseSizeResult ret; +#if defined(OS_WIN) + // Windows has an annoying mis-feature that the size of an open file is not + // written to the parent directory until the file is closed. Since this is a + // diagnostic interface that should be rarely called, go to the trouble of + // closing and re-opening the database in order to get an up-to date size to + // report. + db_.reset(); +#endif + ret.on_disk_size_kb = base::ComputeDirectorySize(db_path_) / 1024; +#if defined(OS_WIN) + OpenOrCreateDatabase(); + if (!db_) + return DatabaseSizeResult(); +#endif + + // Default read options will fill the cache as we go. + std::unique_ptr<leveldb::Iterator> iterator( + db_->NewIterator(leveldb::ReadOptions())); + int64_t num_rows = 0; + for (iterator->SeekToFirst(); iterator->Valid(); iterator->Next()) + ++num_rows; + + ret.num_rows = num_rows; + return ret; +} + LevelDBSiteCharacteristicsDatabase::AsyncHelper::OpeningType LevelDBSiteCharacteristicsDatabase::AsyncHelper::OpenOrCreateDatabaseImpl() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -408,6 +450,25 @@ base::Unretained(async_helper_.get()))); } +void LevelDBSiteCharacteristicsDatabase::GetDatabaseSize( + GetDatabaseSizeCallback callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + // Adapt the callback with a lambda to allow using PostTaskAndReplyWithResult. + auto reply_callback = base::BindOnce( + [](GetDatabaseSizeCallback callback, const DatabaseSizeResult& result) { + std::move(callback).Run(result.num_rows, result.on_disk_size_kb); + }, + std::move(callback)); + + base::PostTaskAndReplyWithResult( + blocking_task_runner_.get(), FROM_HERE, + base::BindOnce( + &LevelDBSiteCharacteristicsDatabase::AsyncHelper::GetDatabaseSize, + base::Unretained(async_helper_.get())), + std::move(reply_callback)); +} + bool LevelDBSiteCharacteristicsDatabase::DatabaseIsInitializedForTesting() { return async_helper_->DBIsInitialized(); }
diff --git a/chrome/browser/resource_coordinator/leveldb_site_characteristics_database.h b/chrome/browser/resource_coordinator/leveldb_site_characteristics_database.h index 3e95165..96fe43321 100644 --- a/chrome/browser/resource_coordinator/leveldb_site_characteristics_database.h +++ b/chrome/browser/resource_coordinator/leveldb_site_characteristics_database.h
@@ -42,6 +42,7 @@ void RemoveSiteCharacteristicsFromDB( const std::vector<url::Origin>& site_origins) override; void ClearDatabase() override; + void GetDatabaseSize(GetDatabaseSizeCallback callback) override; bool DatabaseIsInitializedForTesting();
diff --git a/chrome/browser/resource_coordinator/leveldb_site_characteristics_database_unittest.cc b/chrome/browser/resource_coordinator/leveldb_site_characteristics_database_unittest.cc index d968b646..1f8039a 100644 --- a/chrome/browser/resource_coordinator/leveldb_site_characteristics_database_unittest.cc +++ b/chrome/browser/resource_coordinator/leveldb_site_characteristics_database_unittest.cc
@@ -11,6 +11,7 @@ #include "base/files/scoped_temp_dir.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" +#include "base/test/bind_test_util.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_task_environment.h" #include "base/test/test_file_util.h" @@ -122,10 +123,9 @@ } // Add some entries to the database and returns a vector with their origins. - std::vector<url::Origin> AddDummyEntriesToDB() { - const size_t kEntryCount = 10; + std::vector<url::Origin> AddDummyEntriesToDB(size_t num_entries) { std::vector<url::Origin> site_origins; - for (size_t i = 0; i < kEntryCount; ++i) { + for (size_t i = 0; i < num_entries; ++i) { SiteCharacteristicsProto proto_temp; std::string origin_str = base::StringPrintf("http://%zu.com", i); InitSiteCharacteristicProto(&proto_temp, @@ -166,7 +166,7 @@ } TEST_F(LevelDBSiteCharacteristicsDatabaseTest, RemoveEntries) { - std::vector<url::Origin> site_origins = AddDummyEntriesToDB(); + std::vector<url::Origin> site_origins = AddDummyEntriesToDB(10); // Remove half the origins from the database. std::vector<url::Origin> site_origins_to_remove( @@ -195,8 +195,33 @@ EXPECT_FALSE(ReadFromDB(iter, &proto_temp)); } +TEST_F(LevelDBSiteCharacteristicsDatabaseTest, GetDatabaseSize) { + std::vector<url::Origin> site_origins = AddDummyEntriesToDB(200); + + auto size_callback = + base::BindLambdaForTesting([&](base::Optional<int64_t> num_rows, + base::Optional<int64_t> on_disk_size_kb) { + EXPECT_TRUE(num_rows); + // The DB contains an extra row for metadata. + int64_t expected_rows = site_origins.size() + 1; + EXPECT_EQ(expected_rows, num_rows.value()); + + EXPECT_TRUE(on_disk_size_kb); + EXPECT_LT(0, on_disk_size_kb.value()); + }); + + db_->GetDatabaseSize(std::move(size_callback)); + + WaitForAsyncOperationsToComplete(); + + // Verify that the DB is still operational (see implementation detail + // for Windows). + SiteCharacteristicsProto read_proto; + EXPECT_TRUE(ReadFromDB(site_origins[0], &read_proto)); +} + TEST_F(LevelDBSiteCharacteristicsDatabaseTest, DatabaseRecoveryTest) { - std::vector<url::Origin> site_origins = AddDummyEntriesToDB(); + std::vector<url::Origin> site_origins = AddDummyEntriesToDB(10); db_.reset();
diff --git a/chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.cc b/chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.cc index 1b5bd9fd..f9a2c55 100644 --- a/chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.cc +++ b/chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.cc
@@ -82,6 +82,11 @@ void NoopLocalSiteCharacteristicsDatabase::ClearDatabase() {} +void NoopLocalSiteCharacteristicsDatabase::GetDatabaseSize( + GetDatabaseSizeCallback callback) { + std::move(callback).Run(base::nullopt, base::nullopt); +} + ChromeTestHarnessWithLocalDB::ChromeTestHarnessWithLocalDB() { scoped_feature_list_.InitAndEnableFeature( features::kSiteCharacteristicsDatabase);
diff --git a/chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.h b/chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.h index a7056cb..e30d0a7 100644 --- a/chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.h +++ b/chrome/browser/resource_coordinator/local_site_characteristics_data_unittest_utils.h
@@ -72,6 +72,7 @@ void RemoveSiteCharacteristicsFromDB( const std::vector<url::Origin>& site_origins) override; void ClearDatabase() override; + void GetDatabaseSize(GetDatabaseSizeCallback callback) override; private: DISALLOW_COPY_AND_ASSIGN(NoopLocalSiteCharacteristicsDatabase);
diff --git a/chrome/browser/resource_coordinator/local_site_characteristics_database.h b/chrome/browser/resource_coordinator/local_site_characteristics_database.h index cad2775..b013f3547 100644 --- a/chrome/browser/resource_coordinator/local_site_characteristics_database.h +++ b/chrome/browser/resource_coordinator/local_site_characteristics_database.h
@@ -25,6 +25,9 @@ // initialization has failed. using ReadSiteCharacteristicsFromDBCallback = base::OnceCallback<void( base::Optional<SiteCharacteristicsProto> site_characteristic_proto)>; + using GetDatabaseSizeCallback = + base::OnceCallback<void(base::Optional<int64_t> num_rows, + base::Optional<int64_t> on_disk_size_kb)>; LocalSiteCharacteristicsDatabase() = default; virtual ~LocalSiteCharacteristicsDatabase() {} @@ -48,6 +51,9 @@ // Clear the database, removes every entries that it contains. virtual void ClearDatabase() = 0; + + // Retrieve the size of the database. + virtual void GetDatabaseSize(GetDatabaseSizeCallback callback) = 0; }; } // namespace resource_coordinator
diff --git a/chrome/browser/resources/settings/people_page/sync_browser_proxy.js b/chrome/browser/resources/settings/people_page/sync_browser_proxy.js index 323a22b..388dc45 100644 --- a/chrome/browser/resources/settings/people_page/sync_browser_proxy.js +++ b/chrome/browser/resources/settings/people_page/sync_browser_proxy.js
@@ -215,6 +215,13 @@ * Opens the Google Activity Controls url in a new tab. */ openActivityControlsUrl() {} + + /** + * Function to invoke when the unified consent toggle state changes, to + * notify the C++ layer. + * @param {boolean} toggleChecked + */ + unifiedConsentToggleChanged(toggleChecked) {} } /** @@ -302,6 +309,11 @@ chrome.metricsPrivate.recordUserAction( 'Signin_AccountSettings_GoogleActivityControlsClicked'); } + + /** @override */ + unifiedConsentToggleChanged(toggleChecked) { + chrome.send('UnifiedConsentToggleChanged', [toggleChecked]); + } } cr.addSingletonGetter(SyncBrowserProxyImpl);
diff --git a/chrome/browser/resources/settings/people_page/sync_page.js b/chrome/browser/resources/settings/people_page/sync_page.js index 43764f4..7acfee5 100644 --- a/chrome/browser/resources/settings/people_page/sync_page.js +++ b/chrome/browser/resources/settings/people_page/sync_page.js
@@ -321,7 +321,10 @@ * @private */ onUnifiedConsentToggleChange_: function() { - if (!this.$$('#unifiedConsentToggle').checked) { + const checked = this.$$('#unifiedConsentToggle').checked; + this.browserProxy_.unifiedConsentToggleChanged(checked); + + if (!checked) { this.syncSectionOpened_ = !this.syncSectionDisabled_; this.personalizeSectionOpened_ = true; }
diff --git a/chrome/browser/signin/dice_response_handler.cc b/chrome/browser/signin/dice_response_handler.cc index 16cbf92..caa700c 100644 --- a/chrome/browser/signin/dice_response_handler.cc +++ b/chrome/browser/signin/dice_response_handler.cc
@@ -33,6 +33,7 @@ #include "components/signin/core/browser/signin_manager.h" #include "components/signin/core/browser/signin_metrics.h" #include "google_apis/gaia/gaia_auth_fetcher.h" +#include "google_apis/gaia/gaia_auth_util.h" #include "google_apis/gaia/gaia_constants.h" #include "google_apis/gaia/google_service_auth_error.h" @@ -353,7 +354,7 @@ for (auto it = token_fetchers_.begin(); it != token_fetchers_.end(); ++it) { DiceTokenFetcher* fetcher = it->get(); if (fetcher->gaia_id() == gaia_id) { - DCHECK_EQ(fetcher->email(), email); + DCHECK(gaia::AreEmailsSame(fetcher->email(), email)); // If there is a fetch in progress for a resfresh token for the given // account, then simply mark it to enable sync after the refresh token is // available.
diff --git a/chrome/browser/signin/oauth2_token_service_delegate_android.cc b/chrome/browser/signin/oauth2_token_service_delegate_android.cc index dfecaf2..a8cc59c 100644 --- a/chrome/browser/signin/oauth2_token_service_delegate_android.cc +++ b/chrome/browser/signin/oauth2_token_service_delegate_android.cc
@@ -422,16 +422,6 @@ return currently_signed_in; } -void OAuth2TokenServiceDelegateAndroid::FireRefreshTokenAvailableFromJava( - JNIEnv* env, - const JavaParamRef<jobject>& obj, - const JavaParamRef<jstring>& account_name) { - std::string account_id = - MapAccountNameToAccountId(ConvertJavaStringToUTF8(env, account_name)); - // Notify native observers. - FireRefreshTokenAvailable(account_id); -} - void OAuth2TokenServiceDelegateAndroid::FireRefreshTokenAvailable( const std::string& account_id) { DCHECK(!account_id.empty()); @@ -447,16 +437,6 @@ OAuth2TokenServiceDelegate::FireRefreshTokenAvailable(account_id); } -void OAuth2TokenServiceDelegateAndroid::FireRefreshTokenRevokedFromJava( - JNIEnv* env, - const JavaParamRef<jobject>& obj, - const JavaParamRef<jstring>& account_name) { - std::string account_id = - MapAccountNameToAccountId(ConvertJavaStringToUTF8(env, account_name)); - // Notify native observers. - FireRefreshTokenRevoked(account_id); -} - void OAuth2TokenServiceDelegateAndroid::FireRefreshTokenRevoked( const std::string& account_id) { DCHECK(!account_id.empty()); @@ -481,13 +461,6 @@ OAuth2TokenServiceDelegate::FireRefreshTokenRevoked(account_id); } -void OAuth2TokenServiceDelegateAndroid::FireRefreshTokensLoadedFromJava( - JNIEnv* env, - const JavaParamRef<jobject>& obj) { - // Notify native observers. - FireRefreshTokensLoaded(); -} - void OAuth2TokenServiceDelegateAndroid::FireRefreshTokensLoaded() { DVLOG(1) << "OAuth2TokenServiceDelegateAndroid::FireRefreshTokensLoaded"; JNIEnv* env = AttachCurrentThread();
diff --git a/chrome/browser/signin/oauth2_token_service_delegate_android.h b/chrome/browser/signin/oauth2_token_service_delegate_android.h index cb9b817f..02d1baf54 100644 --- a/chrome/browser/signin/oauth2_token_service_delegate_android.h +++ b/chrome/browser/signin/oauth2_token_service_delegate_android.h
@@ -70,25 +70,6 @@ void ValidateAccounts(const std::string& signed_in_account_id, bool force_notifications); - // Triggers a notification to all observers of the OAuth2TokenService that a - // refresh token is now available. This may cause observers to retry - // operations that require authentication. - virtual void FireRefreshTokenAvailableFromJava( - JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj, - const base::android::JavaParamRef<jstring>& account_name); - // Triggers a notification to all observers of the OAuth2TokenService that a - // refresh token is now available. - virtual void FireRefreshTokenRevokedFromJava( - JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj, - const base::android::JavaParamRef<jstring>& account_name); - // Triggers a notification to all observers of the OAuth2TokenService that all - // refresh tokens have now been loaded. - virtual void FireRefreshTokensLoadedFromJava( - JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj); - // Overridden from OAuth2TokenService to complete signout of all // OA2TService aware accounts. void RevokeAllCredentials() override;
diff --git a/chrome/browser/subresource_filter/subresource_filter_browsertest.cc b/chrome/browser/subresource_filter/subresource_filter_browsertest.cc index 64ba82c..2a050b9 100644 --- a/chrome/browser/subresource_filter/subresource_filter_browsertest.cc +++ b/chrome/browser/subresource_filter/subresource_filter_browsertest.cc
@@ -135,6 +135,13 @@ return url.ReplaceComponents(replacements); } +// This string comes from GetErrorStringForDisallowedLoad() in +// blink/renderer/core/loader/subresource_filter.cc +constexpr const char kBlinkDisallowSubframeConsoleMessageFormat[] = + "Chrome blocked resource %s on this site because this site tends to show " + "ads that interrupt, distract, or prevent user control. Learn more at " + "https://www.chromestatus.com/feature/5738264052891648"; + } // namespace // Tests ----------------------------------------------------------------------- @@ -280,10 +287,10 @@ } IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest, SubFrameActivation) { - std::ostringstream message_filter; - message_filter << kDisallowSubframeConsoleMessagePrefix << "*"; + std::string message_filter = + base::StringPrintf(kBlinkDisallowSubframeConsoleMessageFormat, "*"); content::ConsoleObserverDelegate console_observer(web_contents(), - message_filter.str()); + message_filter); web_contents()->SetDelegate(&console_observer); GURL url(GetTestUrl(kTestFrameSetPath)); @@ -302,17 +309,18 @@ SubresourceFilterAction::kUIShown, 1); // Console message for subframe blocking should be displayed. - std::ostringstream result; - result << kDisallowSubframeConsoleMessagePrefix << "*included_script.js*"; - EXPECT_TRUE(base::MatchPattern(console_observer.message(), result.str())); + EXPECT_TRUE(base::MatchPattern( + console_observer.message(), + base::StringPrintf(kBlinkDisallowSubframeConsoleMessageFormat, + "*included_script.js"))); } IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest, ActivationDisabled_NoConsoleMessage) { - std::ostringstream message_filter; - message_filter << kDisallowSubframeConsoleMessageSuffix << "*"; + std::string message_filter = + base::StringPrintf(kBlinkDisallowSubframeConsoleMessageFormat, "*"); content::ConsoleObserverDelegate console_observer(web_contents(), - message_filter.str()); + message_filter); web_contents()->SetDelegate(&console_observer); Configuration config( @@ -334,10 +342,10 @@ IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest, ActivationDryRun_NoConsoleMessage) { - std::ostringstream message_filter; - message_filter << kDisallowSubframeConsoleMessageSuffix << "*"; + std::string message_filter = + base::StringPrintf(kBlinkDisallowSubframeConsoleMessageFormat, "*"); content::ConsoleObserverDelegate console_observer(web_contents(), - message_filter.str()); + message_filter); web_contents()->SetDelegate(&console_observer); Configuration config(
diff --git a/chrome/browser/themes/browser_theme_pack.cc b/chrome/browser/themes/browser_theme_pack.cc index ca821c6e..8c2420ba 100644 --- a/chrome/browser/themes/browser_theme_pack.cc +++ b/chrome/browser/themes/browser_theme_pack.cc
@@ -59,7 +59,7 @@ // theme packs that aren't int-equal to this. Increment this number if you // change default theme assets or if you need themes to recreate their generated // images (which are cached). -const int kThemePackVersion = 59; +const int kThemePackVersion = 60; // IDs that are in the DataPack won't clash with the positive integer // uint16_t. kHeaderID should always have the maximum value because we want the @@ -536,12 +536,13 @@ class ControlButtonBackgroundImageSource : public gfx::CanvasImageSource { public: ControlButtonBackgroundImageSource(SkColor background_color, - const gfx::ImageSkia& bg_image) - : gfx::CanvasImageSource( - bg_image.isNull() ? gfx::Size(1, 1) : bg_image.size(), - false), + const gfx::ImageSkia& bg_image, + const gfx::Size& dest_size) + : gfx::CanvasImageSource(dest_size, false), background_color_(background_color), - bg_image_(bg_image) {} + bg_image_(bg_image) { + DCHECK(!bg_image.isNull()); + } ~ControlButtonBackgroundImageSource() override = default; @@ -549,7 +550,7 @@ canvas->DrawColor(background_color_); if (!bg_image_.isNull()) - canvas->TileImageInt(bg_image_, 0, 0, size().width(), size().height()); + canvas->DrawImageInt(bg_image_, 0, 0); } private: @@ -1397,6 +1398,14 @@ gfx::Size dest_size = WindowFrameUtil::GetWindows10GlassCaptionButtonAreaSize(); + // To get an accurate sampling, all we need to do is get a representative + // image that is at MOST the size of the caption button area. In the case of + // an image that is smaller - we only need to sample an area the size of the + // provided image (trying to take tiling into account would be overkill). + if (!bg_image.isNull()) { + dest_size.SetToMin(bg_image.size()); + } + for (const ControlBGValue& bg_pair : kControlButtonBackgroundMap) { SkColor frame_color; GetColor(bg_pair.frame_color_id, &frame_color); @@ -1409,7 +1418,7 @@ } auto source = std::make_unique<ControlButtonBackgroundImageSource>( - base_color, bg_image); + base_color, bg_image, dest_size); const gfx::Image dest_image(gfx::ImageSkia(std::move(source), dest_size)); ComputeColorFromImage(bg_pair.color_id, dest_size.height(), dest_image); @@ -1495,8 +1504,9 @@ } void BrowserThemePack::GenerateMissingTextColors() { - // Background Tab constexpr int kDefaultSourceTextColorId = TP::COLOR_BACKGROUND_TAB_TEXT; + + // Background Tab GenerateMissingTextColorForID(TP::COLOR_BACKGROUND_TAB_TEXT, TP::COLOR_BACKGROUND_TAB, TP::COLOR_FRAME, kDefaultSourceTextColorId); @@ -1525,20 +1535,36 @@ int frame_color_id, int source_color_id) { SkColor text_color, tab_color, frame_color; + color_utils::HSL tab_tint; + const bool has_text_color = GetColor(text_color_id, &text_color); const bool has_tab_color = GetColor(tab_color_id, &tab_color); const bool has_frame_color = GetColor(frame_color_id, &frame_color); + const bool has_tab_tint = GetTint(TP::TINT_BACKGROUND_TAB, &tab_tint); + const bool has_meaningful_tab_tint = + has_tab_tint && color_utils::IsHSLShiftMeaningful(tab_tint); + // If there is no tab color specified (also meaning there is no image), fall // back to the frame color. SkColor bg_color = (has_tab_color ? tab_color : frame_color); - const bool has_bg_color = has_tab_color || has_frame_color; + const bool has_bg_color = + has_tab_color || has_frame_color || has_meaningful_tab_tint; // If no bg color is set, we have nothing to blend against, so there's no way // to do this calculation. if (!has_bg_color) return; + if (has_meaningful_tab_tint && !has_tab_color) { + // We need to tint the frame color, so if the theme didn't specify it, grab + // the default. + if (!has_frame_color) { + frame_color = TP::GetDefaultColor(TP::GetLookupID(frame_color_id)); + } + bg_color = color_utils::HSLShift(frame_color, tab_tint); + } + // Determine the text color to start with, in order of preference: // 1) The color specified by the theme (if it exists) // 2) The color passed in to use as a source function (if it exists) @@ -1552,7 +1578,7 @@ blend_source_color = source_text_color; } else { // GetDefaultColor() requires incognito-aware lookup, so we first have to - // get the appropriate lookup ID information + // get the appropriate lookup ID information. TP::PropertyLookupPair lookup_pair = TP::GetLookupID(text_color_id); blend_source_color = TP::GetDefaultColor(lookup_pair);
diff --git a/chrome/browser/themes/browser_theme_pack_unittest.cc b/chrome/browser/themes/browser_theme_pack_unittest.cc index b4b3b304..51a21b6 100644 --- a/chrome/browser/themes/browser_theme_pack_unittest.cc +++ b/chrome/browser/themes/browser_theme_pack_unittest.cc
@@ -705,8 +705,7 @@ // TODO(erg): This test should actually test more of the built resources from // the extension data, but for now, exists so valgrind can test some of the // tricky memory stuff that BrowserThemePack does. -// TODO(rameier): This fails on some trybots. crbug.com/883588 -TEST_F(BrowserThemePackTest, DISABLED_CanBuildAndReadPack) { +TEST_F(BrowserThemePackTest, CanBuildAndReadPack) { base::ScopedTempDir dir; ASSERT_TRUE(dir.CreateUniqueTempDir()); base::FilePath file = dir.GetPath().AppendASCII("data.pak"); @@ -873,6 +872,33 @@ TP::COLOR_BACKGROUND_TAB_TEXT); } +// Ensure that, given a theme which specifies a background tab tint, but no +// background tab color, tab text is correctly calculated to ensure contrast +// against the (tinted) background tab color. +TEST_F(BrowserThemePackTest, TestBGTabTextColorContrast_TabTint) { + // This theme specifies a color for frame (white) and background_tab_text + // (black), in addition to a background_tab tint that reduces the color to + // nearly zero. + base::FilePath theme_path = + GetTestExtensionThemePath("theme_test_bgtabtext_tintonly"); + scoped_refptr<BrowserThemePack> pack; + BuildFromUnpackedExtension(theme_path, &pack); + + SkColor frame_color; + SkColor text_color; + color_utils::HSL tab_tint; + + pack->GetColor(TP::COLOR_FRAME, &frame_color); + pack->GetColor(TP::COLOR_BACKGROUND_TAB_TEXT, &text_color); + pack->GetTint(TP::TINT_BACKGROUND_TAB, &tab_tint); + + SkColor tinted_bg_tab_color = color_utils::HSLShift(frame_color, tab_tint); + float contrast_ratio = + color_utils::GetContrastRatio(tinted_bg_tab_color, text_color); + + EXPECT_GE(contrast_ratio, color_utils::kMinimumReadableContrastRatio); +} + // Ensure that, given a theme which only specifies a frame color, the calculated // caption button background colors appropriately match the frame color. TEST_F(BrowserThemePackTest, TestWindowControlButtonBGColor_FrameColor) {
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 8478873..388300a 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -53,27 +53,10 @@ "cocoa/apps/chrome_app_window_client_views_cocoa.mm", "cocoa/apps/native_app_window_cocoa.h", "cocoa/apps/native_app_window_cocoa.mm", - "cocoa/autofill/autofill_bubble_controller.h", - "cocoa/autofill/autofill_bubble_controller.mm", - "cocoa/autofill/autofill_dialog_constants.h", - "cocoa/autofill/autofill_popup_base_view_cocoa.h", - "cocoa/autofill/autofill_popup_base_view_cocoa.mm", - "cocoa/autofill/autofill_popup_view_bridge.h", - "cocoa/autofill/autofill_popup_view_bridge.mm", - "cocoa/autofill/autofill_popup_view_cocoa.h", - "cocoa/autofill/autofill_popup_view_cocoa.mm", - "cocoa/autofill/autofill_tooltip_controller.h", - "cocoa/autofill/autofill_tooltip_controller.mm", - "cocoa/autofill/save_card_bubble_view_views.h", - "cocoa/autofill/save_card_bubble_view_views.mm", "cocoa/background_gradient_view.h", "cocoa/background_gradient_view.mm", - "cocoa/base_bubble_controller.h", - "cocoa/base_bubble_controller.mm", "cocoa/browser/exclusive_access_controller_views.h", "cocoa/browser/exclusive_access_controller_views.mm", - "cocoa/browser/zoom_bubble_controller.h", - "cocoa/browser/zoom_bubble_controller.mm", "cocoa/browser_dialogs_views_mac.cc", "cocoa/browser_dialogs_views_mac.h", "cocoa/browser_window_cocoa.h", @@ -151,10 +134,6 @@ "cocoa/extensions/extension_keybinding_registry_cocoa.mm", "cocoa/extensions/extension_popup_views_mac.h", "cocoa/extensions/extension_popup_views_mac.mm", - "cocoa/extensions/media_galleries_dialog_cocoa.h", - "cocoa/extensions/media_galleries_dialog_cocoa.mm", - "cocoa/extensions/media_gallery_list_entry_view.h", - "cocoa/extensions/media_gallery_list_entry_view.mm", "cocoa/extensions/toolbar_actions_bar_bubble_views_presenter.h", "cocoa/extensions/toolbar_actions_bar_bubble_views_presenter.mm", "cocoa/fast_resize_view.h", @@ -190,10 +169,6 @@ "cocoa/hover_close_button.mm", "cocoa/image_button_cell.h", "cocoa/image_button_cell.mm", - "cocoa/info_bubble_view.h", - "cocoa/info_bubble_view.mm", - "cocoa/info_bubble_window.h", - "cocoa/info_bubble_window.mm", "cocoa/javascript_app_modal_dialog_cocoa.h", "cocoa/javascript_app_modal_dialog_cocoa.mm", "cocoa/location_bar/autocomplete_text_field.h", @@ -204,28 +179,14 @@ "cocoa/location_bar/autocomplete_text_field_editor.mm", "cocoa/location_bar/bubble_decoration.h", "cocoa/location_bar/bubble_decoration.mm", - "cocoa/location_bar/content_setting_decoration.h", - "cocoa/location_bar/content_setting_decoration.mm", "cocoa/location_bar/image_decoration.h", "cocoa/location_bar/image_decoration.mm", - "cocoa/location_bar/keyword_hint_decoration.h", - "cocoa/location_bar/keyword_hint_decoration.mm", "cocoa/location_bar/location_bar_decoration.h", "cocoa/location_bar/location_bar_decoration.mm", "cocoa/location_bar/location_bar_view_mac.h", "cocoa/location_bar/location_bar_view_mac.mm", - "cocoa/location_bar/manage_passwords_decoration.h", - "cocoa/location_bar/manage_passwords_decoration.mm", "cocoa/location_bar/page_info_bubble_decoration.h", "cocoa/location_bar/page_info_bubble_decoration.mm", - "cocoa/location_bar/save_credit_card_decoration.h", - "cocoa/location_bar/save_credit_card_decoration.mm", - "cocoa/location_bar/selected_keyword_decoration.h", - "cocoa/location_bar/selected_keyword_decoration.mm", - "cocoa/location_bar/star_decoration.h", - "cocoa/location_bar/star_decoration.mm", - "cocoa/location_bar/translate_decoration.h", - "cocoa/location_bar/translate_decoration.mm", "cocoa/location_bar/zoom_decoration.h", "cocoa/location_bar/zoom_decoration.mm", "cocoa/main_menu_item.h", @@ -233,8 +194,6 @@ "cocoa/menu_button.mm", "cocoa/multi_key_equivalent_button.h", "cocoa/multi_key_equivalent_button.mm", - "cocoa/new_tab_button.h", - "cocoa/new_tab_button_cocoa.mm", "cocoa/nsview_additions.h", "cocoa/nsview_additions.mm", "cocoa/omnibox/omnibox_popup_cell.h", @@ -247,8 +206,6 @@ "cocoa/omnibox/omnibox_popup_view_mac.mm", "cocoa/omnibox/omnibox_view_mac.h", "cocoa/omnibox/omnibox_view_mac.mm", - "cocoa/omnibox_decoration_bubble_controller.h", - "cocoa/omnibox_decoration_bubble_controller.mm", "cocoa/permission_bubble/chooser_bubble_ui_views_mac.mm", "cocoa/permission_bubble/permission_prompt_impl_views_mac.mm", "cocoa/rect_path_utils.h", @@ -278,8 +235,6 @@ "cocoa/tab_contents/overlayable_contents_controller.mm", "cocoa/tab_contents/tab_contents_controller.h", "cocoa/tab_contents/tab_contents_controller.mm", - "cocoa/tab_modal_confirm_dialog_mac.h", - "cocoa/tab_modal_confirm_dialog_mac.mm", "cocoa/tabbed_browser_window.h", "cocoa/tabbed_browser_window.mm", "cocoa/tabs/alert_indicator_button_cocoa.h", @@ -327,8 +282,6 @@ "cocoa/touchbar/text_suggestions_touch_bar_controller.mm", "cocoa/touchbar/web_textfield_touch_bar_controller.h", "cocoa/touchbar/web_textfield_touch_bar_controller.mm", - "cocoa/translate/translate_bubble_bridge_views.h", - "cocoa/translate/translate_bubble_bridge_views.mm", "cocoa/url_drop_target.h", "cocoa/url_drop_target.mm", "cocoa/view_id_util.h",
diff --git a/chrome/browser/ui/autofill/autofill_popup_view.h b/chrome/browser/ui/autofill/autofill_popup_view.h index 85b30db4..86251e6 100644 --- a/chrome/browser/ui/autofill/autofill_popup_view.h +++ b/chrome/browser/ui/autofill/autofill_popup_view.h
@@ -9,7 +9,6 @@ #include "base/optional.h" #include "base/strings/string16.h" -#include "build/build_config.h" #include "chrome/browser/ui/autofill/autofill_popup_view_delegate.h" namespace autofill { @@ -37,10 +36,6 @@ // Factory function for creating the view. static AutofillPopupView* Create(AutofillPopupController* controller); -#if defined(OS_MACOSX) - static AutofillPopupView* CreateCocoa(AutofillPopupController* controller); -#endif - protected: virtual ~AutofillPopupView() {} };
diff --git a/chrome/browser/ui/cocoa/autofill/OWNERS b/chrome/browser/ui/cocoa/autofill/OWNERS deleted file mode 100644 index 95d9d80..0000000 --- a/chrome/browser/ui/cocoa/autofill/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -groby@chromium.org -
diff --git a/chrome/browser/ui/cocoa/autofill/autofill_bubble_controller.h b/chrome/browser/ui/cocoa/autofill/autofill_bubble_controller.h deleted file mode 100644 index c996412..0000000 --- a/chrome/browser/ui/cocoa/autofill/autofill_bubble_controller.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_BUBBLE_CONTROLLER_H_ -#define CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_BUBBLE_CONTROLLER_H_ - -#import <Cocoa/Cocoa.h> - -#include "base/mac/scoped_nsobject.h" -#import "chrome/browser/ui/cocoa/base_bubble_controller.h" -#import "chrome/browser/ui/cocoa/info_bubble_view.h" - -// Bubble controller for field validation error bubbles. -@interface AutofillBubbleController : BaseBubbleController { - @private - base::scoped_nsobject<NSTextField> label_; - NSSize inset_; // Amount the label is inset from the window. -} - -// Creates an error bubble with the given |message|. You need to call -// -showWindow: to make the bubble visible. It will autorelease itself when the -// user dismisses the bubble. -- (id)initWithParentWindow:(NSWindow*)parentWindow - message:(NSString*)message; - -// Designated initializer. Creates a bubble with given |message| and insets the -// text content by |inset|, with the arrow positioned at |arrowLocation|. -- (id)initWithParentWindow:(NSWindow*)parentWindow - message:(NSString*)message - inset:(NSSize)inset - maxLabelWidth:(CGFloat)maxLabelWidth - arrowLocation:(info_bubble::BubbleArrowLocation)arrowLocation; - -// Update the current text with |message|. -- (void)setMessage:(NSString*)message; - -@end - - -#endif // CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_BUBBLE_CONTROLLER_H_
diff --git a/chrome/browser/ui/cocoa/autofill/autofill_bubble_controller.mm b/chrome/browser/ui/cocoa/autofill/autofill_bubble_controller.mm deleted file mode 100644 index 0fbdb64..0000000 --- a/chrome/browser/ui/cocoa/autofill/autofill_bubble_controller.mm +++ /dev/null
@@ -1,97 +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. - -#import "chrome/browser/ui/cocoa/autofill/autofill_bubble_controller.h" - -#import "chrome/browser/ui/cocoa/autofill/autofill_dialog_constants.h" -#import "chrome/browser/ui/cocoa/info_bubble_window.h" -#include "skia/ext/skia_utils_mac.h" - -namespace { - -// Border inset for error label. -const CGFloat kLabelInset = 3.0; - -} // namespace - -@interface AutofillBubbleController () { - CGFloat maxLabelWidth_; -} - -// Update the current message, keeping arrow location in place. -- (void)updateMessage:(NSString*)message display:(BOOL)display; - -@end - -@implementation AutofillBubbleController - -- (id)initWithParentWindow:(NSWindow*)parentWindow - message:(NSString*)message { - return [self initWithParentWindow:parentWindow - message:message - inset:NSMakeSize(kLabelInset, kLabelInset) - maxLabelWidth:CGFLOAT_MAX - arrowLocation:info_bubble::kTopCenter]; -} - -- (id)initWithParentWindow:(NSWindow*)parentWindow - message:(NSString*)message - inset:(NSSize)inset - maxLabelWidth:(CGFloat)maxLabelWidth - arrowLocation:(info_bubble::BubbleArrowLocation)arrowLocation { - base::scoped_nsobject<InfoBubbleWindow> window( - [[InfoBubbleWindow alloc] initWithContentRect:NSMakeRect(0, 0, 200, 100) - styleMask:NSBorderlessWindowMask - backing:NSBackingStoreBuffered - defer:NO]); - [window setAllowedAnimations:info_bubble::kAnimateNone]; - if ((self = [super initWithWindow:window - parentWindow:parentWindow - anchoredAt:NSZeroPoint])) { - inset_ = inset; - maxLabelWidth_ = maxLabelWidth; - [self setShouldOpenAsKeyWindow:NO]; - [[self bubble] setArrowLocation:arrowLocation]; - [[self bubble] setAlignment:info_bubble::kAlignArrowToAnchor]; - - label_.reset([[NSTextField alloc] init]); - [label_ setEditable:NO]; - [label_ setBordered:NO]; - [label_ setDrawsBackground:NO]; - [[self bubble] addSubview:label_]; - - [self updateMessage:message display:NO]; - } - return self; -} - -- (void)setMessage:(NSString*)message { - if ([[label_ stringValue] isEqualToString:message]) - return; - [self updateMessage:message display:YES]; -} - -- (void)updateMessage:(NSString*)message display:(BOOL)display { - [label_ setStringValue:message]; - - NSRect labelFrame = NSMakeRect(inset_.width, inset_.height, 0, 0); - labelFrame.size = [[label_ cell] - cellSizeForBounds:NSMakeRect(0, 0, maxLabelWidth_, CGFLOAT_MAX)]; - [label_ setFrame:labelFrame]; - - // Update window's size, but ensure the origin is maintained so that the arrow - // still points at the same location. - NSRect windowFrame = [[self window] frame]; - NSPoint origin = windowFrame.origin; - origin.y += NSHeight(windowFrame); - windowFrame.size = - NSMakeSize(NSWidth([label_ frame]), - NSHeight([label_ frame]) + info_bubble::kBubbleArrowHeight); - windowFrame = NSInsetRect(windowFrame, -inset_.width, -inset_.height); - origin.y -= NSHeight(windowFrame); - windowFrame.origin = origin; - [[self window] setFrame:windowFrame display:display]; -} - -@end
diff --git a/chrome/browser/ui/cocoa/autofill/autofill_bubble_controller_unittest.mm b/chrome/browser/ui/cocoa/autofill/autofill_bubble_controller_unittest.mm deleted file mode 100644 index 223d084a..0000000 --- a/chrome/browser/ui/cocoa/autofill/autofill_bubble_controller_unittest.mm +++ /dev/null
@@ -1,26 +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. - -#import "chrome/browser/ui/cocoa/autofill/autofill_bubble_controller.h" - -#import "chrome/browser/ui/cocoa/test/cocoa_test_helper.h" -#include "chrome/browser/ui/cocoa/test/run_loop_testing.h" - -class AutofillBubbleControllerTest : public CocoaTest { -}; - -TEST_F(AutofillBubbleControllerTest, ShowAndClose) { - AutofillBubbleController* controller = - [[AutofillBubbleController alloc] initWithParentWindow:test_window() - message:@"test msg"]; - EXPECT_FALSE([[controller window] isVisible]); - - [controller showWindow:nil]; - EXPECT_TRUE([[controller window] isVisible]); - - // Close will self-delete, but all pending messages must be processed so the - // deallocation happens. - [controller close]; - chrome::testing::NSRunLoopRunAllPending(); -}
diff --git a/chrome/browser/ui/cocoa/autofill/autofill_dialog_constants.h b/chrome/browser/ui/cocoa/autofill/autofill_dialog_constants.h deleted file mode 100644 index bf7ddd1..0000000 --- a/chrome/browser/ui/cocoa/autofill/autofill_dialog_constants.h +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_DIALOG_CONSTANTS_H_ -#define CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_DIALOG_CONSTANTS_H_ - -// Constants governing layout of autofill dialog. -namespace autofill { - -// Horizontal padding between text and other elements (in pixels). -const CGFloat kAroundTextPadding = 4; - -// Spacing between buttons. -const CGFloat kButtonGap = 6; - -// The space between the edges of a notification bar and the text within (in -// pixels). -const int kNotificationPadding = 17; - -// Vertical spacing between legal text and details section. -const int kVerticalSpacing = 8; - -// Padding between top bar and details section, as well as between the bottom of -// the details section and the button strip. -const int kDetailVerticalPadding = 10; - -// Fixed width for a single input field. -const CGFloat kFieldWidth = 104; - -// Horizontal padding between fields -const CGFloat kHorizontalFieldPadding = 8; - -// Size of the information icon in the footer. -const CGFloat kInfoIconSize = 16; - -} // autofill - -#endif // CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_DIALOG_CONSTANTS_H_
diff --git a/chrome/browser/ui/cocoa/autofill/autofill_popup_base_view_cocoa.h b/chrome/browser/ui/cocoa/autofill/autofill_popup_base_view_cocoa.h deleted file mode 100644 index a122a73..0000000 --- a/chrome/browser/ui/cocoa/autofill/autofill_popup_base_view_cocoa.h +++ /dev/null
@@ -1,47 +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_UI_COCOA_AUTOFILL_AUTOFILL_POPUP_BASE_VIEW_COCOA_H_ -#define CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_POPUP_BASE_VIEW_COCOA_H_ - -#import <Cocoa/Cocoa.h> - -#import "ui/base/cocoa/base_view.h" - -namespace autofill { -class AutofillPopupViewDelegate; -} - -@interface AutofillPopupBaseViewCocoa : BaseView { - @private - autofill::AutofillPopupViewDelegate* popup_delegate_; // weak -} - -- (NSColor*)backgroundColor; -- (NSColor*)borderColor; -- (NSColor*)highlightColor; -- (NSColor*)nameColor; -- (NSColor*)separatorColor; -- (NSColor*)subtextColor; - -- (id)initWithDelegate:(autofill::AutofillPopupViewDelegate*)delegate - frame:(NSRect)frame; - -// Informs the view that its delegate has been (or will imminently be) -// destroyed. -- (void)delegateDestroyed; - -// Draw the popup's background and border. -- (void)drawBackgroundAndBorder; - -// Draws a thin separator in the popup UI. -- (void)drawSeparatorWithBounds:(NSRect)bounds; - -// Messages from AutofillPopupViewBridge: -- (void)updateBoundsAndRedrawPopup; -- (void)showPopup; -- (void)hidePopup; -@end - -#endif // CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_POPUP_BASE_VIEW_COCOA_H_
diff --git a/chrome/browser/ui/cocoa/autofill/autofill_popup_base_view_cocoa.mm b/chrome/browser/ui/cocoa/autofill/autofill_popup_base_view_cocoa.mm deleted file mode 100644 index d0d18e8..0000000 --- a/chrome/browser/ui/cocoa/autofill/autofill_popup_base_view_cocoa.mm +++ /dev/null
@@ -1,235 +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. - -#import "chrome/browser/ui/cocoa/autofill/autofill_popup_base_view_cocoa.h" - -#import "base/mac/scoped_nsobject.h" -#include "chrome/browser/ui/autofill/autofill_popup_view_delegate.h" -#include "chrome/browser/ui/autofill/popup_constants.h" -#include "ui/base/cocoa/window_size_constants.h" -#include "ui/gfx/mac/coordinate_conversion.h" - -@implementation AutofillPopupBaseViewCocoa - -#pragma mark - -#pragma mark Colors - -- (NSColor*)backgroundColor { - return [NSColor whiteColor]; -} - -- (NSColor*)borderColor { - return [NSColor colorForControlTint:[NSColor currentControlTint]]; -} - -- (NSColor*)highlightColor { - return [NSColor selectedControlColor]; -} - -- (NSColor*)nameColor { - return [NSColor blackColor]; -} - -- (NSColor*)separatorColor { - return [NSColor colorWithCalibratedWhite:220 / 255.0 alpha:1]; -} - -- (NSColor*)subtextColor { - // Represents #646464. - return [NSColor colorWithCalibratedRed:100.0 / 255.0 - green:100.0 / 255.0 - blue:100.0 / 255.0 - alpha:1.0]; -} - -#pragma mark - -#pragma mark Public methods - -- (id)initWithDelegate:(autofill::AutofillPopupViewDelegate*)delegate - frame:(NSRect)frame { - self = [super initWithFrame:frame]; - if (self) { - popup_delegate_ = delegate; - popup_delegate_->SetTypesetter(gfx::Typesetter::BROWSER); - } - - return self; -} - -- (void)delegateDestroyed { - popup_delegate_ = NULL; -} - -- (void)drawSeparatorWithBounds:(NSRect)bounds { - [[self separatorColor] set]; - [NSBezierPath fillRect:bounds]; -} - -// A slight optimization for drawing: -// https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaViewsGuide/Optimizing/Optimizing.html -- (BOOL)isOpaque { - return YES; -} - -- (BOOL)isFlipped { - // Flipped so that it's easier to share controller logic with other OSes. - return YES; -} - -- (void)drawBackgroundAndBorder { - // The inset is needed since the border is centered on the |path|. - // TODO(isherman): We should consider using asset-based drawing for the - // border, creating simple bitmaps for the view's border and background, and - // drawing them using NSDrawNinePartImage(). - CGFloat inset = autofill::kPopupBorderThickness / 2.0; - NSRect borderRect = NSInsetRect([self bounds], inset, inset); - NSBezierPath* path = [NSBezierPath bezierPathWithRect:borderRect]; - [[self backgroundColor] setFill]; - [path fill]; - [path setLineWidth:autofill::kPopupBorderThickness]; - [[self borderColor] setStroke]; - [path stroke]; -} - -- (void)mouseUp:(NSEvent*)theEvent { - // If the view is in the process of being destroyed, abort. - if (!popup_delegate_) - return; - - // Only accept single-click. - if ([theEvent clickCount] > 1) - return; - - NSPoint location = [self convertPoint:[theEvent locationInWindow] - fromView:nil]; - - if (NSPointInRect(location, [self bounds])) { - popup_delegate_->SetSelectionAtPoint( - gfx::Point(NSPointToCGPoint(location))); - popup_delegate_->AcceptSelectedLine(); - } -} - -- (void)mouseMoved:(NSEvent*)theEvent { - // If the view is in the process of being destroyed, abort. - if (!popup_delegate_) - return; - - NSPoint location = [self convertPoint:[theEvent locationInWindow] - fromView:nil]; - - popup_delegate_->SetSelectionAtPoint(gfx::Point(NSPointToCGPoint(location))); -} - -- (void)mouseDragged:(NSEvent*)theEvent { - [self mouseMoved:theEvent]; -} - -- (void)mouseExited:(NSEvent*)theEvent { - // If the view is in the process of being destroyed, abort. - if (!popup_delegate_) - return; - - popup_delegate_->SelectionCleared(); -} - -#pragma mark - -#pragma mark Private methods: - -// Returns the full frame needed by the content, which may exceed the available -// vertical space (see clippedPopupFrame). -- (NSRect)fullPopupFrame { - // Flip the y-origin back into Cocoa-land. The controller's platform-neutral - // coordinate space places the origin at the top-left of the first screen - // (e.g. 300 from the top), whereas Cocoa's coordinate space expects the - // origin to be at the bottom-left of this same screen (e.g. 1200 from the - // bottom, when including the height of the popup). - return gfx::ScreenRectToNSRect(popup_delegate_->popup_bounds()); -} - -// Returns the frame of the popup that should be displayed, which is basically -// the bounds of the popup, clipped if there is not enough available vertical -// space. -- (NSRect)clippedPopupFrame { - NSRect clippedPopupFrame = [self fullPopupFrame]; - - // The y-origin of the popup may be outside the application window. If this - // happens, it is corrected to be at the application window's bottom edge, and - // the popup height is adjusted. - NSWindow* appWindow = [popup_delegate_->container_view() window]; - CGFloat appWindowBottomEdge = NSMinY([appWindow frame]); - if (clippedPopupFrame.origin.y < appWindowBottomEdge) { - clippedPopupFrame.origin.y = appWindowBottomEdge; - - // Both the popup frame and [appWindow frame] are in screen coordinates. - CGFloat dY = NSMaxY([appWindow frame]) - NSMaxY([self fullPopupFrame]); - clippedPopupFrame.size.height = NSHeight([appWindow frame]) - dY; - } - return clippedPopupFrame; -} - -#pragma mark - -#pragma mark Messages from AutofillPopupViewBridge: - -- (void)updateBoundsAndRedrawPopup { - // Update the full popup view and the scrollview, as the contents of the popup - // may have changed and affected the height. - [self setFrame:[self fullPopupFrame]]; - [(NSScrollView*)[self superview] setDocumentView:self]; - [[[self superview] window] setFrame:[self clippedPopupFrame] display:YES]; - - [self setNeedsDisplay:YES]; -} - -- (void)showPopup { - NSRect clippedPopupFrame = [self clippedPopupFrame]; - // The window contains a scroll view, and both are the same size, which is - // may be clipped at the application window's bottom edge (see - // clippedPopupFrame). - NSWindow* window = - [[NSWindow alloc] initWithContentRect:clippedPopupFrame - styleMask:NSBorderlessWindowMask - backing:NSBackingStoreBuffered - defer:NO]; - base::scoped_nsobject<NSScrollView> scrollView( - [[NSScrollView alloc] initWithFrame:clippedPopupFrame]); - // Configure the scroller to have no visible border. - [scrollView setBorderType:NSNoBorder]; - - // Configure scrolling behavior and appearance of the scrollbar, which will - // not show if scrolling is not possible, and only show during scrolling as an - // overlay scrollbar. - [scrollView setHasVerticalScroller:YES]; - [scrollView setAutohidesScrollers:YES]; - [scrollView setVerticalScrollElasticity:NSScrollElasticityNone]; - [scrollView setHorizontalScrollElasticity:NSScrollElasticityNone]; - - // The |window| contains the |scrollView|, which contains |self|, the full - // popup view (which is not clipped and may be longer than |scrollView|). - [self setFrame:[self fullPopupFrame]]; - [scrollView setDocumentView:self]; - [window setContentView:scrollView]; - - // Telling Cocoa that the window is opaque enables some drawing optimizations. - [window setOpaque:YES]; - - [self updateBoundsAndRedrawPopup]; - [[popup_delegate_->container_view() window] addChildWindow:window - ordered:NSWindowAbove]; - - // This will momentarily show the vertical scrollbar to indicate that it is - // possible to scroll. Will do the right thing and not show if scrolling is - // not possible. - [scrollView flashScrollers]; -} - -- (void)hidePopup { - // Remove the child window before closing, otherwise it can mess up - // display ordering. - NSWindow* window = [self window]; - [[window parentWindow] removeChildWindow:window]; - [window close]; -} - -@end
diff --git a/chrome/browser/ui/cocoa/autofill/autofill_popup_view_bridge.h b/chrome/browser/ui/cocoa/autofill/autofill_popup_view_bridge.h deleted file mode 100644 index 17134c01..0000000 --- a/chrome/browser/ui/cocoa/autofill/autofill_popup_view_bridge.h +++ /dev/null
@@ -1,70 +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_UI_COCOA_AUTOFILL_AUTOFILL_POPUP_VIEW_BRIDGE_H_ -#define CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_POPUP_VIEW_BRIDGE_H_ - -#include <stddef.h> - -#include <vector> - -#include "base/compiler_specific.h" -#include "base/mac/scoped_nsobject.h" -#include "base/macros.h" -#include "base/optional.h" -#include "chrome/browser/ui/autofill/autofill_popup_view.h" -#include "chrome/browser/ui/cocoa/autofill/autofill_popup_view_cocoa.h" - -@class AutofillPopupViewCocoa; -@class NSWindow; - -namespace autofill { - -class AutofillPopupViewCocoaDelegate { - public: - // Returns the bounds of the item at |index| in the popup, relative to - // the top left of the popup. - virtual gfx::Rect GetRowBounds(int index) = 0; - - // Gets the resource value for the given resource, returning -1 if the - // resource isn't recognized. - virtual int GetIconResourceID(const base::string16& resource_name) = 0; -}; - -// Mac implementation of the AutofillPopupView interface. -// Serves as a bridge to an instance of the Objective-C class which actually -// implements the view. -class AutofillPopupViewBridge : public AutofillPopupView, - public AutofillPopupViewCocoaDelegate { - public: - explicit AutofillPopupViewBridge(AutofillPopupController* controller); - - // AutofillPopupViewCocoaDelegate implementation. - gfx::Rect GetRowBounds(int index) override; - int GetIconResourceID(const base::string16& resource_name) override; - - private: - ~AutofillPopupViewBridge() override; - - // AutofillPopupView implementation. - void Hide() override; - void Show() override; - void OnSelectedRowChanged(base::Optional<int> previous_row_selection, - base::Optional<int> current_row_selection) override; - void OnSuggestionsChanged() override; - - // Set the initial bounds of the popup, including its placement. - void SetInitialBounds(); - - // The native Cocoa view. - base::scoped_nsobject<AutofillPopupViewCocoa> view_; - - AutofillPopupController* controller_; // Weak. - - DISALLOW_COPY_AND_ASSIGN(AutofillPopupViewBridge); -}; - -} // namespace autofill - -#endif // CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_POPUP_VIEW_BRIDGE_H_
diff --git a/chrome/browser/ui/cocoa/autofill/autofill_popup_view_bridge.mm b/chrome/browser/ui/cocoa/autofill/autofill_popup_view_bridge.mm deleted file mode 100644 index 05291d7..0000000 --- a/chrome/browser/ui/cocoa/autofill/autofill_popup_view_bridge.mm +++ /dev/null
@@ -1,71 +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. - -#import <Cocoa/Cocoa.h> - -#include "chrome/browser/ui/cocoa/autofill/autofill_popup_view_bridge.h" - -#include "base/logging.h" -#include "build/buildflag.h" -#include "chrome/browser/ui/autofill/autofill_popup_controller.h" -#include "chrome/browser/ui/autofill/autofill_popup_layout_model.h" -#include "chrome/browser/ui/autofill/autofill_popup_view_delegate.h" -#import "chrome/browser/ui/cocoa/autofill/autofill_popup_view_cocoa.h" -#include "ui/base/ui_features.h" -#include "ui/gfx/geometry/rect.h" - -namespace autofill { - -AutofillPopupViewBridge::AutofillPopupViewBridge( - AutofillPopupController* controller) - : controller_(controller) { - view_.reset([[AutofillPopupViewCocoa alloc] initWithController:controller - frame:NSZeroRect - delegate:this]); -} - -AutofillPopupViewBridge::~AutofillPopupViewBridge() { - [view_ controllerDestroyed]; - [view_ hidePopup]; -} - -gfx::Rect AutofillPopupViewBridge::GetRowBounds(int index) { - return controller_->layout_model().GetRowBounds(index); -} - -int AutofillPopupViewBridge::GetIconResourceID( - const base::string16& resource_name) { - return controller_->layout_model().GetIconResourceID(resource_name); -} - -void AutofillPopupViewBridge::Hide() { - delete this; -} - -void AutofillPopupViewBridge::Show() { - [view_ showPopup]; -} - -void AutofillPopupViewBridge::OnSelectedRowChanged( - base::Optional<int> previous_row_selection, - base::Optional<int> current_row_selection) { - if (previous_row_selection) { - [view_ invalidateRow:*previous_row_selection]; - } - - if (current_row_selection) { - [view_ invalidateRow:*current_row_selection]; - } -} - -void AutofillPopupViewBridge::OnSuggestionsChanged() { - [view_ updateBoundsAndRedrawPopup]; -} - -AutofillPopupView* AutofillPopupView::CreateCocoa( - AutofillPopupController* controller) { - return new AutofillPopupViewBridge(controller); -} - -} // namespace autofill
diff --git a/chrome/browser/ui/cocoa/autofill/autofill_popup_view_cocoa.h b/chrome/browser/ui/cocoa/autofill/autofill_popup_view_cocoa.h deleted file mode 100644 index 5af98eb..0000000 --- a/chrome/browser/ui/cocoa/autofill/autofill_popup_view_cocoa.h +++ /dev/null
@@ -1,42 +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_UI_COCOA_AUTOFILL_AUTOFILL_POPUP_VIEW_COCOA_H_ -#define CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_POPUP_VIEW_COCOA_H_ - -#import <Cocoa/Cocoa.h> -#include <stddef.h> - -#include "base/mac/availability.h" -#import "chrome/browser/ui/cocoa/autofill/autofill_popup_base_view_cocoa.h" -#import "ui/base/cocoa/touch_bar_forward_declarations.h" - -namespace autofill { -class AutofillPopupController; -class AutofillPopupViewCocoaDelegate; -} // namespace autofill - -// Draws the native Autofill popup view on Mac. -@interface AutofillPopupViewCocoa : AutofillPopupBaseViewCocoa { - @private - // The cross-platform controller for this view. - autofill::AutofillPopupController* controller_; // weak - // The delegate back to the AutofillPopupViewBridge. - autofill::AutofillPopupViewCocoaDelegate* delegate_; // weak -} - -// Designated initializer. -- (id)initWithController:(autofill::AutofillPopupController*)controller - frame:(NSRect)frame - delegate:(autofill::AutofillPopupViewCocoaDelegate*)delegate; - -// Informs the view that its controller has been (or will imminently be) -// destroyed. -- (void)controllerDestroyed; - -- (void)invalidateRow:(NSInteger)row; - -@end - -#endif // CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_POPUP_VIEW_COCOA_H_
diff --git a/chrome/browser/ui/cocoa/autofill/autofill_popup_view_cocoa.mm b/chrome/browser/ui/cocoa/autofill/autofill_popup_view_cocoa.mm deleted file mode 100644 index 38618f8d..0000000 --- a/chrome/browser/ui/cocoa/autofill/autofill_popup_view_cocoa.mm +++ /dev/null
@@ -1,295 +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. - -#import "chrome/browser/ui/cocoa/autofill/autofill_popup_view_cocoa.h" - -#include "base/logging.h" -#include "base/mac/mac_util.h" -#include "base/strings/sys_string_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "chrome/browser/ui/autofill/autofill_popup_controller.h" -#include "chrome/browser/ui/autofill/autofill_popup_layout_model.h" -#include "chrome/browser/ui/cocoa/autofill/autofill_popup_view_bridge.h" -#import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h" -#include "components/autofill/core/browser/popup_item_ids.h" -#include "components/autofill/core/browser/suggestion.h" -#include "components/toolbar/vector_icons.h" -#include "skia/ext/skia_utils_mac.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/base/cocoa/window_size_constants.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/color_palette.h" -#include "ui/gfx/font_list.h" -#include "ui/gfx/geometry/point.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/image/image_skia_util_mac.h" -#include "ui/gfx/paint_vector_icon.h" -#include "ui/native_theme/native_theme.h" -#include "ui/native_theme/native_theme_mac.h" - -using autofill::AutofillPopupView; -using autofill::AutofillPopupLayoutModel; -using base::SysUTF16ToNSString; - -@interface AutofillPopupViewCocoa () - -#pragma mark - -#pragma mark Private methods - -// Draws an Autofill suggestion in the given |bounds|, labeled with the given -// |name| and |subtext| hint. If the suggestion |isSelected|, then it is drawn -// with a highlight. |index| determines the font to use, as well as the icon, -// if the row requires it -- such as for credit cards. -- (void)drawSuggestionWithName:(NSString*)name - subtext:(NSString*)subtext - index:(NSInteger)index - bounds:(NSRect)bounds - selected:(BOOL)isSelected - textYOffset:(CGFloat)textYOffset; - -// This comment block applies to all three draw* methods that follow. -// If |rightAlign| == YES. -// Draws the widget with right border aligned to |x|. -// Returns the x value of left border of the widget. -// If |rightAlign| == NO. -// Draws the widget with left border aligned to |x|. -// Returns the x value of right border of the widget. -- (CGFloat)drawName:(NSString*)name - atX:(CGFloat)x - index:(NSInteger)index - rightAlign:(BOOL)rightAlign - bounds:(NSRect)bounds - textYOffset:(CGFloat)textYOffset; -- (CGFloat)drawIconAtIndex:(NSInteger)index - atX:(CGFloat)x - rightAlign:(BOOL)rightAlign - bounds:(NSRect)bounds; -- (CGFloat)drawSubtext:(NSString*)subtext - atX:(CGFloat)x - index:(NSInteger)index - rightAlign:(BOOL)rightAlign - bounds:(NSRect)bounds - textYOffset:(CGFloat)textYOffset; - -// Returns the icon for the row with the given |index|, or |nil| if there is -// none. -- (NSImage*)iconAtIndex:(NSInteger)index; - -@end - -@implementation AutofillPopupViewCocoa - -#pragma mark - -#pragma mark Initialisers - -- (id)initWithFrame:(NSRect)frame { - NOTREACHED(); - return [self initWithController:NULL frame:frame delegate:NULL]; -} - -- (id)initWithController:(autofill::AutofillPopupController*)controller - frame:(NSRect)frame - delegate:(autofill::AutofillPopupViewCocoaDelegate*)delegate { - self = [super initWithDelegate:controller frame:frame]; - if (self) { - controller_ = controller; - delegate_ = delegate; - } - - return self; -} - -#pragma mark - -#pragma mark NSView implementation: - -- (void)drawRect:(NSRect)dirtyRect { - // If the view is in the process of being destroyed, don't bother drawing. - if (!controller_) - return; - - [self drawBackgroundAndBorder]; - - for (int i = 0; i < controller_->GetLineCount(); ++i) { - // Skip rows outside of the dirty rect. - NSRect rowBounds = NSRectFromCGRect(delegate_->GetRowBounds(i).ToCGRect()); - if (!NSIntersectsRect(rowBounds, dirtyRect)) - continue; - const autofill::Suggestion& suggestion = controller_->GetSuggestionAt(i); - - if (suggestion.frontend_id == autofill::POPUP_ITEM_ID_SEPARATOR) { - [self drawSeparatorWithBounds:rowBounds]; - continue; - } - - // Additional offset applied to the text in the vertical direction. - CGFloat textYOffset = 0; - - NSString* value = SysUTF16ToNSString(controller_->GetElidedValueAt(i)); - NSString* label = SysUTF16ToNSString(controller_->GetElidedLabelAt(i)); - BOOL isSelected = - controller_->selected_line() && i == *controller_->selected_line(); - [self drawSuggestionWithName:value - subtext:label - index:i - bounds:rowBounds - selected:isSelected - textYOffset:textYOffset]; - } -} - -#pragma mark - -#pragma mark Public API: - -- (void)controllerDestroyed { - // Since the |controller_| either already has been destroyed or is about to - // be, about the only thing we can safely do with it is to null it out. - controller_ = NULL; - [super delegateDestroyed]; -} - -- (void)invalidateRow:(NSInteger)row { - NSRect dirty_rect = NSRectFromCGRect(delegate_->GetRowBounds(row).ToCGRect()); - [self setNeedsDisplayInRect:dirty_rect]; -} - -#pragma mark - -#pragma mark Private API: - -- (void)drawSuggestionWithName:(NSString*)name - subtext:(NSString*)subtext - index:(NSInteger)index - bounds:(NSRect)bounds - selected:(BOOL)isSelected - textYOffset:(CGFloat)textYOffset { - // If this row is selected, highlight it with this mac system color. - // Otherwise the controller may have a specific background color for this - // entry. - if (isSelected) { - [[self highlightColor] set]; - [NSBezierPath fillRect:bounds]; - } else { - SkColor backgroundColor = - ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor( - controller_->GetBackgroundColorIDForRow(index)); - [skia::SkColorToSRGBNSColor(backgroundColor) set]; - [NSBezierPath fillRect:bounds]; - } - - BOOL isRTL = controller_->IsRTL(); - - // The X values of the left and right borders of the autofill widget. - CGFloat leftX = NSMinX(bounds) + AutofillPopupLayoutModel::kEndPadding; - CGFloat rightX = NSMaxX(bounds) - AutofillPopupLayoutModel::kEndPadding; - - // Draw left side if isRTL == NO, right side if isRTL == YES. - CGFloat x = isRTL ? rightX : leftX; - [self drawName:name - atX:x - index:index - rightAlign:isRTL - bounds:bounds - textYOffset:textYOffset]; - - // Draw right side if isRTL == NO, left side if isRTL == YES. - x = isRTL ? leftX : rightX; - x = [self drawIconAtIndex:index atX:x rightAlign:!isRTL bounds:bounds]; - [self drawSubtext:subtext - atX:x - index:index - rightAlign:!isRTL - bounds:bounds - textYOffset:textYOffset]; -} - -- (CGFloat)drawName:(NSString*)name - atX:(CGFloat)x - index:(NSInteger)index - rightAlign:(BOOL)rightAlign - bounds:(NSRect)bounds - textYOffset:(CGFloat)textYOffset { - NSColor* nameColor = skia::SkColorToSRGBNSColor( - ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor( - controller_->layout_model().GetValueFontColorIDForRow(index))); - NSDictionary* nameAttributes = [NSDictionary - dictionaryWithObjectsAndKeys:controller_->layout_model() - .GetValueFontListForRow(index) - .GetPrimaryFont() - .GetNativeFont(), - NSFontAttributeName, nameColor, - NSForegroundColorAttributeName, nil]; - NSSize nameSize = [name sizeWithAttributes:nameAttributes]; - x -= rightAlign ? nameSize.width : 0; - CGFloat y = bounds.origin.y + (bounds.size.height - nameSize.height) / 2; - y += textYOffset; - - [name drawAtPoint:NSMakePoint(x, y) withAttributes:nameAttributes]; - - x += rightAlign ? 0 : nameSize.width; - return x; -} - -- (CGFloat)drawIconAtIndex:(NSInteger)index - atX:(CGFloat)x - rightAlign:(BOOL)rightAlign - bounds:(NSRect)bounds { - NSImage* icon = [self iconAtIndex:index]; - if (!icon) - return x; - NSSize iconSize = [icon size]; - x -= rightAlign ? iconSize.width : 0; - CGFloat y = bounds.origin.y + (bounds.size.height - iconSize.height) / 2; - [icon drawInRect:NSMakeRect(x, y, iconSize.width, iconSize.height) - fromRect:NSZeroRect - operation:NSCompositeSourceOver - fraction:1.0 - respectFlipped:YES - hints:nil]; - - x += rightAlign ? -AutofillPopupLayoutModel::kIconPadding - : iconSize.width + AutofillPopupLayoutModel::kIconPadding; - return x; -} - -- (CGFloat)drawSubtext:(NSString*)subtext - atX:(CGFloat)x - index:(NSInteger)index - rightAlign:(BOOL)rightAlign - bounds:(NSRect)bounds - textYOffset:(CGFloat)textYOffset { - NSDictionary* subtextAttributes = [NSDictionary - dictionaryWithObjectsAndKeys:controller_->layout_model() - .GetLabelFontListForRow(index) - .GetPrimaryFont() - .GetNativeFont(), - NSFontAttributeName, [self subtextColor], - NSForegroundColorAttributeName, nil]; - NSSize subtextSize = [subtext sizeWithAttributes:subtextAttributes]; - x -= rightAlign ? subtextSize.width : 0; - CGFloat y = bounds.origin.y + (bounds.size.height - subtextSize.height) / 2; - y += textYOffset; - - [subtext drawAtPoint:NSMakePoint(x, y) withAttributes:subtextAttributes]; - x += rightAlign ? 0 : subtextSize.width; - return x; -} - -- (NSImage*)iconAtIndex:(NSInteger)index { - const base::string16& icon = controller_->GetSuggestionAt(index).icon; - if (icon.empty()) - return nil; - if (icon == base::ASCIIToUTF16("httpWarning") || - icon == base::ASCIIToUTF16("httpsInvalid")) { - return NSImageFromImageSkiaWithColorSpace( - controller_->layout_model().GetIconImage(index), - base::mac::GetSRGBColorSpace()); - } - int iconId = delegate_->GetIconResourceID(icon); - DCHECK_NE(-1, iconId); - - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - return rb.GetNativeImageNamed(iconId).ToNSImage(); -} - -@end
diff --git a/chrome/browser/ui/cocoa/autofill/autofill_tooltip_controller.h b/chrome/browser/ui/cocoa/autofill/autofill_tooltip_controller.h deleted file mode 100644 index 22a6e29..0000000 --- a/chrome/browser/ui/cocoa/autofill/autofill_tooltip_controller.h +++ /dev/null
@@ -1,44 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_TOOLTIP_CONTROLLER_H_ -#define CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_TOOLTIP_CONTROLLER_H_ - -#import <Cocoa/Cocoa.h> - -#include "base/mac/scoped_nsobject.h" -#import "chrome/browser/ui/cocoa/info_bubble_view.h" - -@class AutofillBubbleController; -@class AutofillTooltip; - -// Controller for the Tooltip view, which handles displaying/hiding the -// tooltip bubble on hover. -@interface AutofillTooltipController : NSViewController { - @private - base::scoped_nsobject<AutofillTooltip> view_; - AutofillBubbleController* bubbleController_; - NSString* message_; - info_bubble::BubbleArrowLocation arrowLocation_; - - // Indicates whether a tooltip bubble should show. YES when hovering on icon - // or tooltip bubble. - BOOL shouldDisplayTooltip_; - - // Tracks whether mouse pointer currently hovers above bubble. - BOOL isHoveringOnBubble_; -} - -// |message| to display in the tooltip. -@property(copy, nonatomic) NSString* message; - -// Maximal width of the text excluding insets. -@property(nonatomic) CGFloat maxTooltipWidth; - -- (id)initWithArrowLocation:(info_bubble::BubbleArrowLocation)arrowLocation; -- (void)setImage:(NSImage*)image; - -@end; - -#endif // CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_TOOLTIP_CONTROLLER_H_
diff --git a/chrome/browser/ui/cocoa/autofill/autofill_tooltip_controller.mm b/chrome/browser/ui/cocoa/autofill/autofill_tooltip_controller.mm deleted file mode 100644 index 4de7e17d..0000000 --- a/chrome/browser/ui/cocoa/autofill/autofill_tooltip_controller.mm +++ /dev/null
@@ -1,204 +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. - -#import "chrome/browser/ui/cocoa/autofill/autofill_tooltip_controller.h" - -#include "base/mac/foundation_util.h" -#import "chrome/browser/ui/cocoa/autofill/autofill_bubble_controller.h" -#import "ui/base/cocoa/base_view.h" -#include "ui/base/cocoa/cocoa_base_utils.h" -#import "ui/base/cocoa/hover_image_button.h" - -// Delay time before tooltip shows/hides. -const NSTimeInterval kTooltipDelay = 0.1; - -// How far to inset tooltip contents. -CGFloat kTooltipInset = 10; - -#pragma mark AutofillTooltipController - private methods - -@interface AutofillTooltipController () - -// Sets hover state for "mouse over InfoBubble". -- (void)setHoveringOnBubble:(BOOL)hoveringOnBubble; - -// Update the combined hover state - if either button or bubble is hovered, -// the combined state is considered "hovered". Notifies delegate if the state -// changed. -- (void)updateTooltipDisplayState; - -@end - -#pragma mark AutofillTooltip - -// The actual tooltip control - based on HoverButtonCocoa, which comes with free -// hover handling. -@interface AutofillTooltip : HoverButtonCocoa { - @private - // Not owned - |tooltipController_| owns this object. - AutofillTooltipController* tooltipController_; -} - -@property(assign, nonatomic) AutofillTooltipController* tooltipController; - -@end - - -@implementation AutofillTooltip - -@synthesize tooltipController = tooltipController_; - -- (void)drawRect:(NSRect)rect { - [[self image] drawInRect:rect - fromRect:NSZeroRect - operation:NSCompositeSourceOver - fraction:1.0 - respectFlipped:YES - hints:nil]; -} - -- (void)setHoverState:(CloseButtonHoverState)state { - [super setHoverState:state]; - [tooltipController_ updateTooltipDisplayState]; -} - -- (BOOL)acceptsFirstResponder { - return NO; -} - -@end - -#pragma mark AutofillTrackingView - -// A very basic view that only tracks mouseEntered:/mouseExited: and forwards -// them to |tooltipController_|. -@interface AutofillTrackingView : BaseView { - @private - // Not owned - tooltip controller owns tracking view and tooltip. - AutofillTooltipController* tooltipController_; -} - -@property(assign, nonatomic) AutofillTooltipController* tooltipController; - -@end - -@implementation AutofillTrackingView - -@synthesize tooltipController = tooltipController_; - -- (void)mouseEntered:(NSEvent*)theEvent { - [tooltipController_ setHoveringOnBubble:YES]; -} - -- (void)mouseExited:(NSEvent*)theEvent { - [tooltipController_ setHoveringOnBubble:NO]; -} - -@end - -#pragma mark AutofillTooltipController - -@implementation AutofillTooltipController - -@synthesize message = message_; -@synthesize maxTooltipWidth = maxTooltipWidth_; - -- (id)initWithArrowLocation:(info_bubble::BubbleArrowLocation)arrowLocation { - if ((self = [super init])) { - arrowLocation_ = arrowLocation; - maxTooltipWidth_ = CGFLOAT_MAX; - view_.reset([[AutofillTooltip alloc] init]); - [self setView:view_]; - [view_ setTooltipController:self]; - } - return self; -} - -- (void)dealloc { - [view_ setTooltipController:nil]; - [NSObject cancelPreviousPerformRequestsWithTarget:self]; - [[NSNotificationCenter defaultCenter] - removeObserver:self - name:NSWindowWillCloseNotification - object:[bubbleController_ window]]; - [super dealloc]; -} - -- (void)setImage:(NSImage*)image { - [view_ setImage:image]; - [view_ setFrameSize:[image size]]; -} - -- (void)tooltipWindowWillClose:(NSNotification*)notification { - bubbleController_ = nil; -} - -- (void)displayHover { - [bubbleController_ close]; - bubbleController_ = [[AutofillBubbleController alloc] - initWithParentWindow:[[self view] window] - message:[self message] - inset:NSMakeSize(kTooltipInset, kTooltipInset) - maxLabelWidth:maxTooltipWidth_ - arrowLocation:arrowLocation_]; - [bubbleController_ setShouldCloseOnResignKey:NO]; - - // Handle bubble self-deleting. - NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; - [center addObserver:self - selector:@selector(tooltipWindowWillClose:) - name:NSWindowWillCloseNotification - object:[bubbleController_ window]]; - - // Inject a tracking view so controller can track hover events for the bubble. - base::scoped_nsobject<NSView> oldContentView( - [[[bubbleController_ window] contentView] retain]); - base::scoped_nsobject<AutofillTrackingView> trackingView( - [[AutofillTrackingView alloc] initWithFrame:[oldContentView frame]]); - [trackingView setTooltipController:self]; - [trackingView setAutoresizesSubviews:YES]; - [oldContentView setFrame:[trackingView bounds]]; - [oldContentView - setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)]; - [[bubbleController_ window] setContentView:trackingView]; - [trackingView setSubviews:@[ oldContentView ]]; - - // Compute anchor point (in window coords - views might be flipped). - NSRect viewRect = [view_ convertRect:[view_ bounds] toView:nil]; - NSPoint anchorPoint = NSMakePoint(NSMidX(viewRect), NSMinY(viewRect)); - [bubbleController_ setAnchorPoint:ui::ConvertPointFromWindowToScreen( - [[self view] window], anchorPoint)]; - [bubbleController_ showWindow:self]; -} - -- (void)hideHover { - [bubbleController_ close]; -} - -- (void)setHoveringOnBubble:(BOOL)hoveringOnBubble { - isHoveringOnBubble_ = hoveringOnBubble; - [self updateTooltipDisplayState]; -} - -- (void)updateTooltipDisplayState { - BOOL newDisplayState = - ([view_ hoverState] != kHoverStateNone || isHoveringOnBubble_); - - if (newDisplayState != shouldDisplayTooltip_) { - shouldDisplayTooltip_ = newDisplayState; - - // Cancel any pending visibility changes. - [NSObject cancelPreviousPerformRequestsWithTarget:self]; - - // If the desired visibility disagrees with current visibility, start a - // timer to change visibility. (Uses '!!' to force bool values) - if (!!bubbleController_ ^ !!shouldDisplayTooltip_) { - SEL sel = shouldDisplayTooltip_ ? @selector(displayHover) - : @selector(hideHover); - [self performSelector:sel withObject:nil afterDelay:kTooltipDelay]; - } - } -} - -@end
diff --git a/chrome/browser/ui/cocoa/autofill/autofill_tooltip_controller_unittest.mm b/chrome/browser/ui/cocoa/autofill/autofill_tooltip_controller_unittest.mm deleted file mode 100644 index f33ed89..0000000 --- a/chrome/browser/ui/cocoa/autofill/autofill_tooltip_controller_unittest.mm +++ /dev/null
@@ -1,28 +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. - -#import "chrome/browser/ui/cocoa/autofill/autofill_tooltip_controller.h" - -#include "base/mac/scoped_nsobject.h" -#include "testing/gtest/include/gtest/gtest.h" -#import "ui/base/test/cocoa_helper.h" - -namespace { - -class AutofillTooltipControllerTest: public ui::CocoaTest { - public: - void SetUp() override { - CocoaTest::SetUp(); - controller_.reset([[AutofillTooltipController alloc] - initWithArrowLocation:info_bubble::kTopCenter]); - [[test_window() contentView] addSubview:[controller_ view]]; - } - - protected: - base::scoped_nsobject<AutofillTooltipController> controller_; -}; - -} // namespace - -TEST_VIEW(AutofillTooltipControllerTest, [controller_ view])
diff --git a/chrome/browser/ui/cocoa/autofill/layout_view_unittest.mm b/chrome/browser/ui/cocoa/autofill/layout_view_unittest.mm deleted file mode 100644 index 59b99ef..0000000 --- a/chrome/browser/ui/cocoa/autofill/layout_view_unittest.mm +++ /dev/null
@@ -1,65 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "chrome/browser/ui/cocoa/autofill/layout_view.h" - -#include "base/mac/scoped_nsobject.h" -#include "chrome/browser/ui/cocoa/autofill/simple_grid_layout.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "testing/platform_test.h" -#import "ui/base/test/cocoa_helper.h" - -namespace { - -class LayoutViewTest : public ui::CocoaTest { - public: - LayoutViewTest() { - CocoaTest::SetUp(); - view_.reset([[LayoutView alloc] initWithFrame:NSZeroRect]); - [view_ setLayoutManager:std::unique_ptr<SimpleGridLayout>( - new SimpleGridLayout(view_))]; - layout_ = [view_ layoutManager]; - [[test_window() contentView] addSubview:view_]; - } - - protected: - base::scoped_nsobject<LayoutView> view_; - SimpleGridLayout* layout_; // weak, owned by view_. -}; - -} // namespace - -TEST_VIEW(LayoutViewTest, view_) - -TEST_F(LayoutViewTest, setFrameInvokesLayout) { - EXPECT_FLOAT_EQ(0, NSWidth([view_ frame])); - EXPECT_FLOAT_EQ(0, NSHeight([view_ frame])); - - ColumnSet* cs = layout_->AddColumnSet(0); - cs->AddColumn(0.4); - cs->AddColumn(0.6); - layout_->StartRow(0, 0); - base::scoped_nsobject<NSView> childView1( - [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 0, 45)]); - base::scoped_nsobject<NSView> childView2( - [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 20, 55)]); - layout_->AddView(childView1); - layout_->AddView(childView2); - - ASSERT_EQ(2U, [[view_ subviews] count]); - EXPECT_FLOAT_EQ(0, NSWidth([view_ frame])); - EXPECT_FLOAT_EQ(0, NSHeight([view_ frame])); - - [view_ setFrame:NSMakeRect(0, 0, 40, 60)]; - EXPECT_FLOAT_EQ(40, NSWidth([view_ frame])); - EXPECT_FLOAT_EQ(60, NSHeight([view_ frame])); - - NSView* subview = [[view_ subviews] objectAtIndex:0]; - EXPECT_FLOAT_EQ(16, NSWidth([subview frame])); - EXPECT_FLOAT_EQ(55, NSHeight([subview frame])); - - subview = [[view_ subviews] objectAtIndex:1]; - EXPECT_FLOAT_EQ(24, NSWidth([subview frame])); - EXPECT_FLOAT_EQ(55, NSHeight([subview frame])); -}
diff --git a/chrome/browser/ui/cocoa/autofill/save_card_bubble_view_unittest.mm b/chrome/browser/ui/cocoa/autofill/save_card_bubble_view_unittest.mm deleted file mode 100644 index 1a470b39..0000000 --- a/chrome/browser/ui/cocoa/autofill/save_card_bubble_view_unittest.mm +++ /dev/null
@@ -1,217 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <Carbon/Carbon.h> // For the kVK_* constants. - -#include <memory> - -#include "base/json/json_reader.h" -#include "base/values.h" -#import "chrome/browser/ui/cocoa/autofill/save_card_bubble_view_bridge.h" -#import "chrome/browser/ui/cocoa/browser_window_controller.h" -#include "chrome/browser/ui/cocoa/test/cocoa_profile_test.h" -#include "components/autofill/core/browser/credit_card.h" -#include "components/autofill/core/browser/ui/save_card_bubble_controller.h" -#include "components/signin/core/browser/account_info.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#import "ui/events/test/cocoa_test_event_utils.h" - -namespace autofill { - -namespace { - -class TestSaveCardBubbleController : public SaveCardBubbleController { - public: - TestSaveCardBubbleController() { - ParseLegalMessageJson(); - - on_save_button_was_called_ = false; - on_cancel_button_was_called_ = false; - on_learn_more_was_called_ = false; - on_legal_message_was_called_ = false; - on_bubble_closed_was_called_ = false; - } - - // SaveCardBubbleController: - MOCK_CONST_METHOD0(GetWindowTitle, base::string16()); - MOCK_CONST_METHOD0(GetExplanatoryMessage, base::string16()); - MOCK_CONST_METHOD0(GetAccountInfo&, AccountInfo()); - MOCK_CONST_METHOD0(GetCard&, const CreditCard()); - MOCK_CONST_METHOD0(ShouldRequestNameFromUser, bool()); - - void OnSaveButton(const base::string16& cardholder_name) override { - on_save_button_was_called_ = true; - } - void OnCancelButton() override { on_cancel_button_was_called_ = true; } - void OnLearnMoreClicked() override { on_learn_more_was_called_ = true; } - void OnLegalMessageLinkClicked(const GURL& url) override { - on_legal_message_was_called_ = true; - legal_message_url_ = url.spec(); - } - void OnBubbleClosed() override { on_bubble_closed_was_called_ = true; } - - const LegalMessageLines& GetLegalMessageLines() const override { - return lines_; - } - - // Testing state. - bool on_save_button_was_called() { return on_save_button_was_called_; } - bool on_cancel_button_was_called() { return on_cancel_button_was_called_; } - bool on_learn_more_was_called() { return on_learn_more_was_called_; } - bool on_legal_message_was_called() { return on_legal_message_was_called_; } - std::string legal_message_url() { return legal_message_url_; } - bool on_bubble_closed_was_called() { return on_bubble_closed_was_called_; } - - private: - void ParseLegalMessageJson() { - std::string message_json = - "{" - " \"line\" : [" - " {" - " \"template\": \"Please check out our {0}.\"," - " \"template_parameter\": [" - " {" - " \"display_text\": \"terms of service\"," - " \"url\": \"http://help.example.com/legal_message\"" - " }" - " ]" - " }," - " {" - " \"template\": \"We also have a {0} and {1}.\"," - " \"template_parameter\": [" - " {" - " \"display_text\": \"mission statement\"," - " \"url\": \"http://www.example.com/our_mission\"" - " }," - " {" - " \"display_text\": \"privacy policy\"," - " \"url\": \"http://help.example.com/privacy_policy\"" - " }" - " ]" - " }" - " ]" - "}"; - std::unique_ptr<base::Value> value(base::JSONReader::Read(message_json)); - ASSERT_TRUE(value); - base::DictionaryValue* dictionary = nullptr; - ASSERT_TRUE(value->GetAsDictionary(&dictionary)); - LegalMessageLine::Parse(*dictionary, &lines_); - } - - LegalMessageLines lines_; - - bool on_save_button_was_called_; - bool on_cancel_button_was_called_; - bool on_learn_more_was_called_; - bool on_legal_message_was_called_; - std::string legal_message_url_; - bool on_bubble_closed_was_called_; -}; - -class SaveCardBubbleViewTest : public CocoaProfileTest { - public: - void SetUp() override { - CocoaProfileTest::SetUp(); - ASSERT_TRUE(browser()); - - browser_window_controller_ = - [[BrowserWindowController alloc] initWithBrowser:browser() - takeOwnership:NO]; - - bubble_controller_.reset(new TestSaveCardBubbleController()); - - // This will show the SaveCardBubbleViewCocoa. - bridge_ = new SaveCardBubbleViewBridge(bubble_controller_.get(), - browser_window_controller_); - } - - void TearDown() override { - [[browser_window_controller_ nsWindowController] close]; - CocoaProfileTest::TearDown(); - } - - protected: - BrowserWindowController* browser_window_controller_; - std::unique_ptr<TestSaveCardBubbleController> bubble_controller_; - SaveCardBubbleViewBridge* bridge_; -}; - -} // namespace - -TEST_F(SaveCardBubbleViewTest, SaveShouldClose) { - [bridge_->view_controller_ onSaveButton:nil]; - - EXPECT_TRUE(bubble_controller_->on_save_button_was_called()); - EXPECT_FALSE(bubble_controller_->on_cancel_button_was_called()); - EXPECT_FALSE(bubble_controller_->on_learn_more_was_called()); - EXPECT_FALSE(bubble_controller_->on_legal_message_was_called()); - - EXPECT_TRUE(bubble_controller_->on_bubble_closed_was_called()); -} - -TEST_F(SaveCardBubbleViewTest, CancelShouldClose) { - [bridge_->view_controller_ onCancelButton:nil]; - - EXPECT_FALSE(bubble_controller_->on_save_button_was_called()); - EXPECT_TRUE(bubble_controller_->on_cancel_button_was_called()); - EXPECT_FALSE(bubble_controller_->on_learn_more_was_called()); - EXPECT_FALSE(bubble_controller_->on_legal_message_was_called()); - - EXPECT_TRUE(bubble_controller_->on_bubble_closed_was_called()); -} - -TEST_F(SaveCardBubbleViewTest, LearnMoreShouldNotClose) { - NSTextView* textView = nil; - NSObject* link = nil; - [bridge_->view_controller_ textView:textView clickedOnLink:link atIndex:0]; - - EXPECT_FALSE(bubble_controller_->on_save_button_was_called()); - EXPECT_FALSE(bubble_controller_->on_cancel_button_was_called()); - EXPECT_TRUE(bubble_controller_->on_learn_more_was_called()); - EXPECT_FALSE(bubble_controller_->on_legal_message_was_called()); - - EXPECT_FALSE(bubble_controller_->on_bubble_closed_was_called()); -} - -TEST_F(SaveCardBubbleViewTest, LegalMessageShouldNotClose) { - NSString* legalText = @"We also have a mission statement and privacy policy."; - base::scoped_nsobject<NSTextView> textView( - [[NSTextView alloc] initWithFrame:NSZeroRect]); - base::scoped_nsobject<NSAttributedString> attributedMessage( - [[NSAttributedString alloc] initWithString:legalText attributes:@{}]); - [[textView textStorage] setAttributedString:attributedMessage]; - - NSObject* link = nil; - [bridge_->view_controller_ textView:textView clickedOnLink:link atIndex:40]; - - EXPECT_FALSE(bubble_controller_->on_save_button_was_called()); - EXPECT_FALSE(bubble_controller_->on_cancel_button_was_called()); - EXPECT_FALSE(bubble_controller_->on_learn_more_was_called()); - EXPECT_TRUE(bubble_controller_->on_legal_message_was_called()); - - std::string url("http://help.example.com/privacy_policy"); - EXPECT_EQ(url, bubble_controller_->legal_message_url()); - - EXPECT_FALSE(bubble_controller_->on_bubble_closed_was_called()); -} - -TEST_F(SaveCardBubbleViewTest, ReturnInvokesDefaultAction) { - [[bridge_->view_controller_ window] - performKeyEquivalent:cocoa_test_event_utils::KeyEventWithKeyCode( - kVK_Return, '\r', NSKeyDown, 0)]; - - EXPECT_TRUE(bubble_controller_->on_save_button_was_called()); - EXPECT_TRUE(bubble_controller_->on_bubble_closed_was_called()); -} - -TEST_F(SaveCardBubbleViewTest, EscapeCloses) { - [[bridge_->view_controller_ window] - performKeyEquivalent:cocoa_test_event_utils::KeyEventWithKeyCode( - kVK_Escape, '\e', NSKeyDown, 0)]; - - EXPECT_TRUE(bubble_controller_->on_bubble_closed_was_called()); -} - -} // namespace autofill
diff --git a/chrome/browser/ui/cocoa/autofill/save_card_bubble_view_views.h b/chrome/browser/ui/cocoa/autofill/save_card_bubble_view_views.h deleted file mode 100644 index cd356a0b..0000000 --- a/chrome/browser/ui/cocoa/autofill/save_card_bubble_view_views.h +++ /dev/null
@@ -1,28 +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_UI_COCOA_AUTOFILL_SAVE_CARD_BUBBLE_VIEW_VIEWS_H_ -#define CHROME_BROWSER_UI_COCOA_AUTOFILL_SAVE_CARD_BUBBLE_VIEW_VIEWS_H_ - -namespace autofill { -class SaveCardBubbleController; -class SaveCardBubbleView; -} // namespace autofill - -namespace content { -class WebContents; -} - -namespace autofill { - -// Creates the SaveCardBubbleView implementation. -SaveCardBubbleView* CreateSaveCardBubbleView( - content::WebContents* web_contents, - autofill::SaveCardBubbleController* controller, - BrowserWindowController* browser_window_controller, - bool user_gesture); - -} // namespace autofill - -#endif // CHROME_BROWSER_UI_COCOA_AUTOFILL_SAVE_CARD_BUBBLE_VIEW_VIEWS_H_
diff --git a/chrome/browser/ui/cocoa/autofill/save_card_bubble_view_views.mm b/chrome/browser/ui/cocoa/autofill/save_card_bubble_view_views.mm deleted file mode 100644 index bf4c4e4..0000000 --- a/chrome/browser/ui/cocoa/autofill/save_card_bubble_view_views.mm +++ /dev/null
@@ -1,68 +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 "chrome/browser/platform_util.h" -#include "chrome/browser/ui/autofill/save_card_ui.h" -#include "chrome/browser/ui/cocoa/browser_dialogs_views_mac.h" -#include "chrome/browser/ui/cocoa/browser_window_cocoa.h" -#include "chrome/browser/ui/cocoa/browser_window_controller.h" -#include "chrome/browser/ui/cocoa/bubble_anchor_helper_views.h" -#include "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" -#include "chrome/browser/ui/cocoa/location_bar/save_credit_card_decoration.h" -#include "chrome/browser/ui/views/autofill/save_card_bubble_views.h" -#include "chrome/browser/ui/views/autofill/save_card_manage_cards_bubble_views.h" -#include "chrome/browser/ui/views/autofill/save_card_offer_bubble_views.h" -#include "chrome/browser/ui/views/autofill/save_card_sign_in_promo_bubble_views.h" -#include "ui/base/cocoa/cocoa_base_utils.h" -#include "ui/gfx/mac/coordinate_conversion.h" - -namespace autofill { - -SaveCardBubbleView* CreateSaveCardBubbleView( - content::WebContents* web_contents, - autofill::SaveCardBubbleController* controller, - BrowserWindowController* browser_window_controller, - bool user_gesture) { - NSWindow* parent_window = [browser_window_controller window]; - LocationBarViewMac* location_bar = - [browser_window_controller locationBarBridge]; - gfx::Point anchor = - gfx::ScreenPointFromNSPoint(ui::ConvertPointFromWindowToScreen( - parent_window, location_bar->GetSaveCreditCardBubblePoint())); - - autofill::BubbleType bubble_type = controller->GetBubbleType(); - autofill::SaveCardBubbleViews* bubble = nullptr; - - switch (bubble_type) { - case autofill::BubbleType::LOCAL_SAVE: - case autofill::BubbleType::UPLOAD_SAVE: - bubble = new autofill::SaveCardOfferBubbleViews(nullptr, anchor, - web_contents, controller); - break; - case autofill::BubbleType::SIGN_IN_PROMO: - bubble = new autofill::SaveCardSignInPromoBubbleViews( - nullptr, anchor, web_contents, controller); - break; - case autofill::BubbleType::MANAGE_CARDS: - bubble = new autofill::SaveCardManageCardsBubbleViews( - nullptr, anchor, web_contents, controller); - break; - case autofill::BubbleType::INACTIVE: - break; - } - - DCHECK(bubble); - - // Usually the anchor view determines the arrow type, but there is none in - // MacViews. So always use TOP_RIGHT, even in fullscreen. - bubble->SetArrow(views::BubbleBorder::TOP_RIGHT); - bubble->set_parent_window(platform_util::GetViewForWindow(parent_window)); - views::BubbleDialogDelegateView::CreateBubble(bubble); - bubble->Show(user_gesture ? autofill::SaveCardBubbleViews::USER_GESTURE - : autofill::SaveCardBubbleViews::AUTOMATIC); - KeepBubbleAnchored(bubble, location_bar->save_credit_card_decoration()); - return bubble; -} - -} // namespace autofill
diff --git a/chrome/browser/ui/cocoa/base_bubble_controller.h b/chrome/browser/ui/cocoa/base_bubble_controller.h deleted file mode 100644 index c19662f..0000000 --- a/chrome/browser/ui/cocoa/base_bubble_controller.h +++ /dev/null
@@ -1,120 +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_UI_COCOA_BASE_BUBBLE_CONTROLLER_H_ -#define CHROME_BROWSER_UI_COCOA_BASE_BUBBLE_CONTROLLER_H_ - -#import <Cocoa/Cocoa.h> - -#include <memory> - -#include "components/bubble/bubble_reference.h" -#include "ui/base/cocoa/bubble_closer.h" - -@class InfoBubbleView; -class TabStripModelObserverBridge; - -// Base class for bubble controllers. Manages a xib that contains an -// InfoBubbleWindow which contains an InfoBubbleView. Contains code to close -// the bubble window on clicks outside of the window, and the like. -// To use this class: -// 1. Create a new xib that contains a window. Change the window's class to -// InfoBubbleWindow. Give it a child view that autosizes to the window's full -// size, give it class InfoBubbleView. Make the controller the window's -// delegate. -// 2. Create a subclass of BaseBubbleController. -// 3. Change the xib's File Owner to your subclass. -// 4. Hook up the File Owner's |bubble_| to the InfoBubbleView in the xib. -@interface BaseBubbleController : NSWindowController<NSWindowDelegate> { - @private - NSWindow* parentWindow_; // weak - NSPoint anchor_; - // Offset of the anchor point relative to the parent window's upper-left-hand - // corner. Used to ensure that if the parent window is resized with the bubble - // remaining visible, the bubble continues to be anchored correctly. - NSPoint anchorOffset_; - - IBOutlet InfoBubbleView* bubble_; // to set arrow position - // Bridge for tab change notifications. - std::unique_ptr<TabStripModelObserverBridge> tabStripObserverBridge_; - - // A local event tap that will dismiss the bubble when a click is delivered - // outside the window. This is needed because the window shares first - // responder with its parent. - std::unique_ptr<ui::BubbleCloser> bubbleCloser_; - - // Weak, owned by AppKit. - // A notification observer that gets triggered when any window resigns key. - id resignationObserver_; - // The controlled window should be the key window when it's opened. True by - // default. - BOOL shouldOpenAsKeyWindow_; - // The bubble window should close if it (or its parent) resigns key status. - BOOL shouldCloseOnResignKey_; - BubbleReference bubbleReference_; -} - -@property(nonatomic, assign) NSWindow* parentWindow; -// The point in base screen coordinates at which the bubble should open and the -// arrow tip points. -@property(nonatomic, assign) NSPoint anchorPoint; -@property(nonatomic, readonly) InfoBubbleView* bubble; -@property(nonatomic, assign) BOOL shouldOpenAsKeyWindow; -// Controls whether, when opening, the bubble should become the active window. -@property(nonatomic, assign) BOOL shouldActivateOnOpen; -// Controls if the bubble auto-closes if the user clicks outside the bubble. -@property(nonatomic, assign) BOOL shouldCloseOnResignKey; -// A reference for bubbles that are managed by the BubbleManager. -@property(nonatomic, assign) BubbleReference bubbleReference; - -// Creates a bubble. |nibPath| is just the basename, e.g. @"FirstRunBubble". -// |anchoredAt| is in screen space. You need to call -showWindow: to make the -// bubble visible. It will autorelease itself when the user dismisses the -// bubble. -// This is the designated initializer. -- (id)initWithWindowNibPath:(NSString*)nibPath - parentWindow:(NSWindow*)parentWindow - anchoredAt:(NSPoint)anchoredAt; - - -// Creates a bubble. |nibPath| is just the basename, e.g. @"FirstRunBubble". -// |view| must be in a window. The bubble will point at |offset| relative to -// |view|'s lower left corner. You need to call -showWindow: to make the -// bubble visible. It will autorelease itself when the user dismisses the -// bubble. -- (id)initWithWindowNibPath:(NSString*)nibPath - relativeToView:(NSView*)view - offset:(NSPoint)offset; - - -// For subclasses that do not load from a XIB, this will simply set the instance -// variables appropriately. This will also replace the |-[self window]|'s -// contentView with an instance of InfoBubbleView. -- (id)initWithWindow:(NSWindow*)theWindow - parentWindow:(NSWindow*)parentWindow - anchoredAt:(NSPoint)anchoredAt; - -// Closes the bubble with BUBBLE_CLOSE_CANCELED. -- (IBAction)cancel:(id)sender; - -// Creates an autoreleased horizontal separator view with a given frame. The -// height of the frame is ignored. -- (NSBox*)horizontalSeparatorWithFrame:(NSRect)frame; - -// Creates an autoreleased vertical separator view with a given frame. The -// width of frame is ignored. -- (NSBox*)verticalSeparatorWithFrame:(NSRect)frame; - - -@end - -// Methods for use by subclasses. -@interface BaseBubbleController (Protected) -// Registers event taps *after* the window is shown so that the bubble is -// dismissed when it resigns key. This only needs to be called if -// |-showWindow:| is overriden and does not call super. Noop on OSes <10.7. -- (void)registerKeyStateEventTap; -@end - -#endif // CHROME_BROWSER_UI_COCOA_BASE_BUBBLE_CONTROLLER_H_
diff --git a/chrome/browser/ui/cocoa/base_bubble_controller.mm b/chrome/browser/ui/cocoa/base_bubble_controller.mm deleted file mode 100644 index e272ddf..0000000 --- a/chrome/browser/ui/cocoa/base_bubble_controller.mm +++ /dev/null
@@ -1,457 +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. - -#import "chrome/browser/ui/cocoa/base_bubble_controller.h" - -#include "base/bind.h" -#include "base/logging.h" -#include "base/mac/bundle_locations.h" -#include "base/mac/foundation_util.h" -#include "base/mac/mac_util.h" -#include "base/mac/scoped_nsobject.h" -#include "base/mac/sdk_forward_declarations.h" -#include "base/strings/string_util.h" -#import "chrome/browser/ui/cocoa/browser_window_controller.h" -#import "chrome/browser/ui/cocoa/info_bubble_view.h" -#import "chrome/browser/ui/cocoa/info_bubble_window.h" -#include "chrome/browser/ui/cocoa/l10n_util.h" -#import "chrome/browser/ui/cocoa/tabs/tab_strip_model_observer_bridge.h" -#include "components/bubble/bubble_controller.h" -#include "ui/base/cocoa/cocoa_base_utils.h" - -@interface BaseBubbleController (Private) -- (void)registerForNotifications; -- (void)updateOriginFromAnchor; -- (void)activateTabWithContents:(content::WebContents*)newContents - previousContents:(content::WebContents*)oldContents - atIndex:(NSInteger)index - reason:(int)reason; -- (void)recordAnchorOffset; -- (void)parentWindowDidResize:(NSNotification*)notification; -- (void)parentWindowWillClose:(NSNotification*)notification; -- (void)parentWindowWillToggleFullScreen:(NSNotification*)notification; -- (void)closeCleanup; - -// Temporary methods to decide how to close the bubble controller. -// TODO(hcarmona): remove these methods when all bubbles use the BubbleManager. -// Notify BubbleManager to close a bubble. -- (void)closeBubbleWithReason:(BubbleCloseReason)reason; -// Will be a no-op in bubble API because this is handled by the BubbleManager. -- (void)closeBubble; -@end - -@implementation BaseBubbleController - -@synthesize anchorPoint = anchor_; -@synthesize bubble = bubble_; -@synthesize shouldOpenAsKeyWindow = shouldOpenAsKeyWindow_; -@synthesize shouldActivateOnOpen = shouldActivateOnOpen_; -@synthesize shouldCloseOnResignKey = shouldCloseOnResignKey_; -@synthesize bubbleReference = bubbleReference_; - -- (id)initWithWindowNibPath:(NSString*)nibPath - parentWindow:(NSWindow*)parentWindow - anchoredAt:(NSPoint)anchoredAt { - nibPath = [base::mac::FrameworkBundle() pathForResource:nibPath - ofType:@"nib"]; - if ((self = [super initWithWindowNibPath:nibPath owner:self])) { - [self setParentWindow:parentWindow]; - anchor_ = anchoredAt; - shouldOpenAsKeyWindow_ = YES; - shouldActivateOnOpen_ = YES; - shouldCloseOnResignKey_ = YES; - } - return self; -} - -- (id)initWithWindowNibPath:(NSString*)nibPath - relativeToView:(NSView*)view - offset:(NSPoint)offset { - DCHECK([view window]); - NSWindow* window = [view window]; - NSRect bounds = [view convertRect:[view bounds] toView:nil]; - NSPoint anchor = NSMakePoint(NSMinX(bounds) + offset.x, - NSMinY(bounds) + offset.y); - anchor = ui::ConvertPointFromWindowToScreen(window, anchor); - return [self initWithWindowNibPath:nibPath - parentWindow:window - anchoredAt:anchor]; -} - -- (id)initWithWindow:(NSWindow*)theWindow - parentWindow:(NSWindow*)parentWindow - anchoredAt:(NSPoint)anchoredAt { - DCHECK(theWindow); - if ((self = [super initWithWindow:theWindow])) { - [self setParentWindow:parentWindow]; - shouldOpenAsKeyWindow_ = YES; - shouldActivateOnOpen_ = YES; - shouldCloseOnResignKey_ = YES; - - DCHECK(![[self window] delegate]); - [theWindow setDelegate:self]; - - base::scoped_nsobject<InfoBubbleView> contentView( - [[InfoBubbleView alloc] initWithFrame:NSZeroRect]); - [theWindow setContentView:contentView.get()]; - bubble_ = contentView.get(); - - [self awakeFromNib]; - [self setAnchorPoint:anchoredAt]; - } - return self; -} - -- (void)awakeFromNib { - // Check all connections have been made in Interface Builder. - DCHECK([self window]); - DCHECK(bubble_); - DCHECK_EQ(self, [[self window] delegate]); - - BrowserWindowController* bwc = - [BrowserWindowController browserWindowControllerForWindow:parentWindow_]; - if (bwc) { - TabStripControllerCocoa* tabStripController = [bwc tabStripController]; - TabStripModel* tabStripModel = [tabStripController tabStripModel]; - tabStripObserverBridge_.reset(new TabStripModelObserverBridge(tabStripModel, - self)); - } - - [bubble_ setArrowLocation:info_bubble::kTopTrailing]; -} - -- (void)dealloc { - [self unregisterFromNotifications]; - [super dealloc]; -} - -- (void)registerForNotifications { - // No window to register notifications for. - if (!parentWindow_) - return; - - NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; - // Watch to see if the parent window closes, and if so, close this one. - [center addObserver:self - selector:@selector(parentWindowWillClose:) - name:NSWindowWillCloseNotification - object:parentWindow_]; - // Watch for the full screen event, if so, close the bubble - [center addObserver:self - selector:@selector(parentWindowWillToggleFullScreen:) - name:NSWindowWillEnterFullScreenNotification - object:parentWindow_]; - // Watch for the full screen exit event, if so, close the bubble - [center addObserver:self - selector:@selector(parentWindowWillToggleFullScreen:) - name:NSWindowWillExitFullScreenNotification - object:parentWindow_]; - // Watch for parent window's resizing, to ensure this one is always - // anchored correctly. - [center addObserver:self - selector:@selector(parentWindowDidResize:) - name:NSWindowDidResizeNotification - object:parentWindow_]; -} - -- (void)unregisterFromNotifications { - // No window to unregister notifications. - if (!parentWindow_) - return; - - NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; - [center removeObserver:self - name:NSWindowWillCloseNotification - object:parentWindow_]; - [center removeObserver:self - name:NSWindowWillEnterFullScreenNotification - object:parentWindow_]; - [center removeObserver:self - name:NSWindowWillExitFullScreenNotification - object:parentWindow_]; - [center removeObserver:self - name:NSWindowDidResizeNotification - object:parentWindow_]; -} - -- (NSWindow*)parentWindow { - return parentWindow_; -} - -- (void)setParentWindow:(NSWindow*)parentWindow { - if (parentWindow_ == parentWindow) { - return; - } - - [self unregisterFromNotifications]; - - if (parentWindow_ && [[self window] isVisible]) { - [parentWindow_ removeChildWindow:[self window]]; - parentWindow_ = parentWindow; - [parentWindow_ addChildWindow:[self window] ordered:NSWindowAbove]; - } else { - parentWindow_ = parentWindow; - } - - [self registerForNotifications]; -} - -- (void)setAnchorPoint:(NSPoint)anchor { - anchor_ = anchor; - [self updateOriginFromAnchor]; -} - -- (void)recordAnchorOffset { - // The offset of the anchor from the parent's upper-left-hand corner is kept - // to ensure the bubble stays anchored correctly if the parent is resized. - anchorOffset_ = NSMakePoint(NSMinX([parentWindow_ frame]), - NSMaxY([parentWindow_ frame])); - anchorOffset_.x -= anchor_.x; - anchorOffset_.y -= anchor_.y; -} - -- (NSBox*)horizontalSeparatorWithFrame:(NSRect)frame { - frame.size.height = 1.0; - base::scoped_nsobject<NSBox> spacer([[NSBox alloc] initWithFrame:frame]); - [spacer setBoxType:NSBoxSeparator]; - [spacer setBorderType:NSLineBorder]; - [spacer setAlphaValue:0.75]; - return [spacer.release() autorelease]; -} - -- (NSBox*)verticalSeparatorWithFrame:(NSRect)frame { - frame.size.width = 1.0; - base::scoped_nsobject<NSBox> spacer([[NSBox alloc] initWithFrame:frame]); - [spacer setBoxType:NSBoxSeparator]; - [spacer setBorderType:NSLineBorder]; - [spacer setAlphaValue:0.75]; - return [spacer.release() autorelease]; -} - -- (void)parentWindowDidResize:(NSNotification*)notification { - if (!parentWindow_) - return; - - DCHECK_EQ(parentWindow_, [notification object]); - NSPoint newOrigin = NSMakePoint(NSMinX([parentWindow_ frame]), - NSMaxY([parentWindow_ frame])); - newOrigin.x -= anchorOffset_.x; - newOrigin.y -= anchorOffset_.y; - [self setAnchorPoint:newOrigin]; -} - -- (void)parentWindowWillClose:(NSNotification*)notification { - [self setParentWindow:nil]; - [self closeBubble]; -} - -- (void)parentWindowWillToggleFullScreen:(NSNotification*)notification { - [self setParentWindow:nil]; - [self closeBubble]; -} - -- (void)closeCleanup { - bubbleCloser_ = nullptr; - if (resignationObserver_) { - [[NSNotificationCenter defaultCenter] - removeObserver:resignationObserver_ - name:NSWindowDidResignKeyNotification - object:nil]; - resignationObserver_ = nil; - } - - tabStripObserverBridge_.reset(); -} - -- (void)closeBubbleWithReason:(BubbleCloseReason)reason { - if ([self bubbleReference]) - [self bubbleReference]->CloseBubble(reason); - else - [self close]; -} - -- (void)closeBubble { - if (![self bubbleReference]) - [self close]; -} - -- (void)windowWillClose:(NSNotification*)notification { - [self closeCleanup]; - [[NSNotificationCenter defaultCenter] removeObserver:self]; - [self autorelease]; -} - -// We want this to be a child of a browser window. addChildWindow: -// (called from this function) will bring the window on-screen; -// unfortunately, [NSWindowController showWindow:] will also bring it -// on-screen (but will cause unexpected changes to the window's -// position). We cannot have an addChildWindow: and a subsequent -// showWindow:. Thus, we have our own version. -- (void)showWindow:(id)sender { - NSWindow* window = [self window]; // Completes nib load. - [self updateOriginFromAnchor]; - [parentWindow_ addChildWindow:window ordered:NSWindowAbove]; - if (parentWindow_ == [NSApp mainWindow] || shouldActivateOnOpen_) { - if (shouldOpenAsKeyWindow_) { - [window makeKeyAndOrderFront:self]; - } else { - [window orderFront:nil]; - } - } else { - [window orderWindow:NSWindowAbove relativeTo:[parentWindow_ windowNumber]]; - } - [self registerKeyStateEventTap]; - [self recordAnchorOffset]; -} - -- (void)close { - [self closeCleanup]; - [super close]; -} - -// The controller is the delegate of the window so it receives did resign key -// notifications. When key is resigned mirror Windows behavior and close the -// window. -- (void)windowDidResignKey:(NSNotification*)notification { - NSWindow* window = [self window]; - DCHECK_EQ([notification object], window); - - // If the window isn't visible, it is already closed, and this notification - // has been sent as part of the closing operation, so no need to close. - if (![window isVisible]) - return; - - // Don't close when explicily disabled, or if there's an attached sheet (e.g. - // Open File dialog). - if ([self shouldCloseOnResignKey] && ![window attachedSheet]) { - [self closeBubbleWithReason:BUBBLE_CLOSE_FOCUS_LOST]; - return; - } - - // The bubble should not receive key events when it is no longer key window, - // so disable sharing parent key state. Share parent key state is only used - // to enable the close/minimize/maximize buttons of the parent window when - // the bubble has key state, so disabling it here is safe. - InfoBubbleWindow* bubbleWindow = - base::mac::ObjCCastStrict<InfoBubbleWindow>([self window]); - [bubbleWindow setAllowShareParentKeyState:NO]; -} - -- (void)windowDidBecomeKey:(NSNotification*)notification { - // Re-enable share parent key state to make sure the close/minimize/maximize - // buttons of the parent window are active. - InfoBubbleWindow* bubbleWindow = - base::mac::ObjCCastStrict<InfoBubbleWindow>([self window]); - [bubbleWindow setAllowShareParentKeyState:YES]; -} - -// Since the bubble shares first responder with its parent window, set event -// handlers to dismiss the bubble when it would normally lose key state. -// Events on sheets are ignored: this assumes the sheet belongs to the bubble -// since, to affect a sheet on a different window, the bubble would also lose -// key status in -[NSWindowDelegate windowDidResignKey:]. This keeps the logic -// simple, since -[NSWindow attachedSheet] returns nil while the sheet is still -// closing. -- (void)registerKeyStateEventTap { - NSWindow* window = self.window; - NSNotification* note = - [NSNotification notificationWithName:NSWindowDidResignKeyNotification - object:window]; - - bubbleCloser_ = std::make_unique<ui::BubbleCloser>( - window, base::BindRepeating(base::RetainBlock(^{ - // Do it right now, because if this event is right mouse event, it may - // pop up a menu. windowDidResignKey: will not run until the menu is - // closed. - if ([self respondsToSelector:@selector(windowDidResignKey:)]) - [self windowDidResignKey:note]; - }))); - - // The resignationObserver_ watches for when a window resigns key state, - // meaning the key window has changed and the bubble should be dismissed. - NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; - resignationObserver_ = - [center addObserverForName:NSWindowDidResignKeyNotification - object:nil - queue:[NSOperationQueue mainQueue] - usingBlock:^(NSNotification* notif) { - if (![[notif object] isSheet] && - [NSApp keyWindow] != [self window]) - [self windowDidResignKey:note]; - }]; -} - -// By implementing this, ESC causes the window to go away. -- (IBAction)cancel:(id)sender { - // This is not a "real" cancel as potential changes to the radio group are not - // undone. That's ok. - [self closeBubbleWithReason:BUBBLE_CLOSE_CANCELED]; -} - -// Takes the |anchor_| point and adjusts the window's origin accordingly. -- (void)updateOriginFromAnchor { - NSWindow* window = [self window]; - NSPoint origin = anchor_; - - BOOL isRTL = cocoa_l10n_util::ShouldDoExperimentalRTLLayout(); - switch ([bubble_ alignment]) { - case info_bubble::kAlignArrowToAnchor: { - NSSize offsets = NSMakeSize(info_bubble::kBubbleArrowXOffset + - info_bubble::kBubbleArrowWidth / 2.0, 0); - offsets = [[parentWindow_ contentView] convertSize:offsets toView:nil]; - switch ([bubble_ arrowLocation]) { - case info_bubble::kTopTrailing: - origin.x -= - isRTL ? offsets.width : NSWidth([window frame]) - offsets.width; - break; - case info_bubble::kTopLeading: - origin.x -= - isRTL ? NSWidth([window frame]) - offsets.width : offsets.width; - break; - case info_bubble::kNoArrow: - // FALLTHROUGH. - case info_bubble::kTopCenter: - origin.x -= NSWidth([window frame]) / 2.0; - break; - } - break; - } - - case info_bubble::kAlignEdgeToAnchorEdge: - // If the arrow is to the right then move the origin so that the right - // edge aligns with the anchor. If the arrow is to the left then there's - // nothing to do because the left edge is already aligned with the left - // edge of the anchor. - if ([bubble_ arrowLocation] == info_bubble::kTopTrailing) { - origin.x -= NSWidth([window frame]); - } - break; - - case info_bubble::kAlignTrailingEdgeToAnchorEdge: - if (!isRTL) - origin.x -= NSWidth([window frame]); - break; - - case info_bubble::kAlignLeadingEdgeToAnchorEdge: - if (isRTL) - origin.x -= NSWidth([window frame]); - break; - - default: - NOTREACHED(); - } - - origin.y -= NSHeight([window frame]); - [window setFrameOrigin:origin]; -} - -- (void)activateTabWithContents:(content::WebContents*)newContents - previousContents:(content::WebContents*)oldContents - atIndex:(NSInteger)index - reason:(int)reason { - // The user switched tabs; close. - [self closeBubble]; -} - -@end // BaseBubbleController
diff --git a/chrome/browser/ui/cocoa/base_bubble_controller_unittest.mm b/chrome/browser/ui/cocoa/base_bubble_controller_unittest.mm deleted file mode 100644 index dfa356ec..0000000 --- a/chrome/browser/ui/cocoa/base_bubble_controller_unittest.mm +++ /dev/null
@@ -1,444 +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. - -#import "chrome/browser/ui/cocoa/base_bubble_controller.h" - -#import "base/mac/scoped_nsobject.h" -#import "base/mac/scoped_objc_class_swizzler.h" -#import "base/mac/sdk_forward_declarations.h" -#include "base/macros.h" -#import "chrome/browser/ui/cocoa/info_bubble_view.h" -#import "chrome/browser/ui/cocoa/info_bubble_window.h" -#import "chrome/browser/ui/cocoa/test/cocoa_test_helper.h" -#import "ui/base/test/menu_test_observer.h" -#import "ui/events/test/cocoa_test_event_utils.h" - -namespace { -const CGFloat kBubbleWindowWidth = 100; -const CGFloat kBubbleWindowHeight = 50; -const CGFloat kAnchorPointX = 400; -const CGFloat kAnchorPointY = 300; - -NSWindow* g_key_window = nil; -} // namespace - -// A helper class to swizzle [NSApplication keyWindow]. -@interface FakeKeyWindow : NSObject -@property(readonly) NSWindow* keyWindow; -@end - -@implementation FakeKeyWindow -- (NSWindow*)keyWindow { - return g_key_window; -} -@end - - -class BaseBubbleControllerTest : public CocoaTest { - public: - BaseBubbleControllerTest() : controller_(nil) {} - - void SetUp() override { - bubble_window_.reset([[InfoBubbleWindow alloc] - initWithContentRect:NSMakeRect(0, 0, kBubbleWindowWidth, - kBubbleWindowHeight) - styleMask:NSBorderlessWindowMask - backing:NSBackingStoreBuffered - defer:NO]); - [bubble_window_ setAllowedAnimations:0]; - - // The bubble controller will release itself when the window closes. - controller_ = [[BaseBubbleController alloc] - initWithWindow:bubble_window_ - parentWindow:test_window() - anchoredAt:NSMakePoint(kAnchorPointX, kAnchorPointY)]; - EXPECT_TRUE([controller_ bubble]); - EXPECT_EQ(bubble_window_.get(), [controller_ window]); - } - - void TearDown() override { - // Close our windows. - [controller_ close]; - bubble_window_.reset(); - CocoaTest::TearDown(); - } - - // Closing the bubble will autorelease the controller. Give callers a keep- - // alive to run checks after closing. - base::scoped_nsobject<BaseBubbleController> ShowBubble() WARN_UNUSED_RESULT { - base::scoped_nsobject<BaseBubbleController> keep_alive( - [controller_ retain]); - EXPECT_FALSE([bubble_window_ isVisible]); - [controller_ showWindow:nil]; - EXPECT_TRUE([bubble_window_ isVisible]); - return keep_alive; - } - - // Fake the key state notification. Because unit_tests is a "daemon" process - // type, its windows can never become key (nor can the app become active). - // Instead of the hacks below, one could make a browser_test or transform the - // process type, but this seems easiest and is best suited to a unit test. - // - // Simply post a notification that will cause the controller to call - // |-windowDidResignKey:|. - void SimulateKeyStatusChange() { - NSNotification* notif = - [NSNotification notificationWithName:NSWindowDidResignKeyNotification - object:[controller_ window]]; - [[NSNotificationCenter defaultCenter] postNotification:notif]; - } - - protected: - base::scoped_nsobject<InfoBubbleWindow> bubble_window_; - BaseBubbleController* controller_; - - private: - DISALLOW_COPY_AND_ASSIGN(BaseBubbleControllerTest); -}; - -// Test that kAlignEdgeToAnchorEdge and a left bubble arrow correctly aligns the -// left edge of the buble to the anchor point. -TEST_F(BaseBubbleControllerTest, LeftAlign) { - [[controller_ bubble] setArrowLocation:info_bubble::kTopLeading]; - [[controller_ bubble] setAlignment:info_bubble::kAlignEdgeToAnchorEdge]; - [controller_ showWindow:nil]; - - NSRect frame = [[controller_ window] frame]; - // Make sure the bubble size hasn't changed. - EXPECT_EQ(frame.size.width, kBubbleWindowWidth); - EXPECT_EQ(frame.size.height, kBubbleWindowHeight); - // Make sure the bubble is left aligned. - EXPECT_EQ(NSMinX(frame), kAnchorPointX); - EXPECT_GE(NSMaxY(frame), kAnchorPointY); -} - -// Test that kAlignEdgeToAnchorEdge and a right bubble arrow correctly aligns -// the right edge of the buble to the anchor point. -TEST_F(BaseBubbleControllerTest, RightAlign) { - [[controller_ bubble] setArrowLocation:info_bubble::kTopTrailing]; - [[controller_ bubble] setAlignment:info_bubble::kAlignEdgeToAnchorEdge]; - [controller_ showWindow:nil]; - - NSRect frame = [[controller_ window] frame]; - // Make sure the bubble size hasn't changed. - EXPECT_EQ(frame.size.width, kBubbleWindowWidth); - EXPECT_EQ(frame.size.height, kBubbleWindowHeight); - // Make sure the bubble is left aligned. - EXPECT_EQ(NSMaxX(frame), kAnchorPointX); - EXPECT_GE(NSMaxY(frame), kAnchorPointY); -} - -// Test that kAlignArrowToAnchor and a left bubble arrow correctly aligns -// the bubble arrow to the anchor point. -TEST_F(BaseBubbleControllerTest, AnchorAlignLeftArrow) { - [[controller_ bubble] setArrowLocation:info_bubble::kTopLeading]; - [[controller_ bubble] setAlignment:info_bubble::kAlignArrowToAnchor]; - [controller_ showWindow:nil]; - - NSRect frame = [[controller_ window] frame]; - // Make sure the bubble size hasn't changed. - EXPECT_EQ(frame.size.width, kBubbleWindowWidth); - EXPECT_EQ(frame.size.height, kBubbleWindowHeight); - // Make sure the bubble arrow points to the anchor. - EXPECT_EQ(NSMinX(frame) + info_bubble::kBubbleArrowXOffset + - roundf(info_bubble::kBubbleArrowWidth / 2.0), kAnchorPointX); - EXPECT_GE(NSMaxY(frame), kAnchorPointY); -} - -// Test that kAlignArrowToAnchor and a right bubble arrow correctly aligns -// the bubble arrow to the anchor point. -TEST_F(BaseBubbleControllerTest, AnchorAlignRightArrow) { - [[controller_ bubble] setArrowLocation:info_bubble::kTopTrailing]; - [[controller_ bubble] setAlignment:info_bubble::kAlignArrowToAnchor]; - [controller_ showWindow:nil]; - - NSRect frame = [[controller_ window] frame]; - // Make sure the bubble size hasn't changed. - EXPECT_EQ(frame.size.width, kBubbleWindowWidth); - EXPECT_EQ(frame.size.height, kBubbleWindowHeight); - // Make sure the bubble arrow points to the anchor. - EXPECT_EQ(NSMaxX(frame) - info_bubble::kBubbleArrowXOffset - - floorf(info_bubble::kBubbleArrowWidth / 2.0), kAnchorPointX); - EXPECT_GE(NSMaxY(frame), kAnchorPointY); -} - -// Test that kAlignArrowToAnchor and a center bubble arrow correctly align -// the bubble towards the anchor point. -TEST_F(BaseBubbleControllerTest, AnchorAlignCenterArrow) { - [[controller_ bubble] setArrowLocation:info_bubble::kTopCenter]; - [[controller_ bubble] setAlignment:info_bubble::kAlignArrowToAnchor]; - [controller_ showWindow:nil]; - - NSRect frame = [[controller_ window] frame]; - // Make sure the bubble size hasn't changed. - EXPECT_EQ(frame.size.width, kBubbleWindowWidth); - EXPECT_EQ(frame.size.height, kBubbleWindowHeight); - // Make sure the bubble arrow points to the anchor. - EXPECT_EQ(NSMidX(frame), kAnchorPointX); - EXPECT_GE(NSMaxY(frame), kAnchorPointY); -} - -// Test that the window is given an initial position before being shown. This -// ensures offscreen initialization is done using correct screen metrics. -TEST_F(BaseBubbleControllerTest, PositionedBeforeShow) { - // Verify default alignment settings, used when initialized in SetUp(). - EXPECT_EQ(info_bubble::kTopTrailing, [[controller_ bubble] arrowLocation]); - EXPECT_EQ(info_bubble::kAlignArrowToAnchor, [[controller_ bubble] alignment]); - - // Verify the default frame (positioned relative to the test_window() origin). - NSRect frame = [[controller_ window] frame]; - EXPECT_EQ(NSMaxX(frame) - info_bubble::kBubbleArrowXOffset - - floorf(info_bubble::kBubbleArrowWidth / 2.0), kAnchorPointX); - EXPECT_EQ(NSMaxY(frame), kAnchorPointY); -} - -// Tests that when a new window gets key state (and the bubble resigns) that -// the key window changes. -TEST_F(BaseBubbleControllerTest, ResignKeyCloses) { - base::scoped_nsobject<NSWindow> other_window( - [[NSWindow alloc] initWithContentRect:NSMakeRect(500, 500, 500, 500) - styleMask:NSTitledWindowMask - backing:NSBackingStoreBuffered - defer:NO]); - - base::scoped_nsobject<BaseBubbleController> keep_alive = ShowBubble(); - EXPECT_FALSE([other_window isVisible]); - - [other_window makeKeyAndOrderFront:nil]; - SimulateKeyStatusChange(); - - EXPECT_FALSE([bubble_window_ isVisible]); - EXPECT_TRUE([other_window isVisible]); -} - -// Test that clicking outside the window causes the bubble to close if -// shouldCloseOnResignKey is YES. -TEST_F(BaseBubbleControllerTest, LionClickOutsideClosesWithoutContextMenu) { - base::scoped_nsobject<BaseBubbleController> keep_alive = ShowBubble(); - NSWindow* window = [controller_ window]; - - EXPECT_TRUE([controller_ shouldCloseOnResignKey]); // Verify default value. - [controller_ setShouldCloseOnResignKey:NO]; - NSEvent* event = cocoa_test_event_utils::LeftMouseDownAtPointInWindow( - NSMakePoint(10, 10), test_window()); - [NSApp sendEvent:event]; - - EXPECT_TRUE([window isVisible]); - - event = cocoa_test_event_utils::RightMouseDownAtPointInWindow( - NSMakePoint(10, 10), test_window()); - [NSApp sendEvent:event]; - - EXPECT_TRUE([window isVisible]); - - [controller_ setShouldCloseOnResignKey:YES]; - event = cocoa_test_event_utils::LeftMouseDownAtPointInWindow( - NSMakePoint(10, 10), test_window()); - [NSApp sendEvent:event]; - - EXPECT_FALSE([window isVisible]); - - [controller_ showWindow:nil]; // Show it again - EXPECT_TRUE([window isVisible]); - EXPECT_TRUE([controller_ shouldCloseOnResignKey]); // Verify. - - event = cocoa_test_event_utils::RightMouseDownAtPointInWindow( - NSMakePoint(10, 10), test_window()); - [NSApp sendEvent:event]; - - EXPECT_FALSE([window isVisible]); -} - -// Test that right-clicking the window with displaying a context menu causes -// the bubble to close. -TEST_F(BaseBubbleControllerTest, LionRightClickOutsideClosesWithContextMenu) { - base::scoped_nsobject<BaseBubbleController> keep_alive = ShowBubble(); - NSWindow* window = [controller_ window]; - - base::scoped_nsobject<NSMenu> context_menu( - [[NSMenu alloc] initWithTitle:@""]); - [context_menu addItemWithTitle:@"ContextMenuTest" - action:nil - keyEquivalent:@""]; - - // Set the menu as the contextual menu of contentView of test_window(). - [[test_window() contentView] setMenu:context_menu]; - - base::scoped_nsobject<MenuTestObserver> menu_observer( - [[MenuTestObserver alloc] initWithMenu:context_menu]); - [menu_observer setCloseAfterOpening:YES]; - [menu_observer setOpenCallback:^(MenuTestObserver* observer) { - // Verify bubble's window is closed when contextual menu is open. - EXPECT_TRUE([observer isOpen]); - EXPECT_FALSE([window isVisible]); - }]; - - // RightMouseDown in test_window() would close the bubble window and then - // dispaly the contextual menu. - NSEvent* event = cocoa_test_event_utils::RightMouseDownAtPointInWindow( - NSMakePoint(10, 10), test_window()); - - EXPECT_FALSE([menu_observer isOpen]); - EXPECT_FALSE([menu_observer didOpen]); - - [NSApp sendEvent:event]; - - // When we got here, menu has already run its RunLoop. - EXPECT_FALSE([window isVisible]); - - EXPECT_FALSE([menu_observer isOpen]); - EXPECT_TRUE([menu_observer didOpen]); -} - -// Test that the bubble is not dismissed when it has an attached sheet, or when -// a sheet loses key status (since the sheet is not attached when that happens). -TEST_F(BaseBubbleControllerTest, BubbleStaysOpenWithSheet) { - base::scoped_nsobject<BaseBubbleController> keep_alive = ShowBubble(); - - // Make a dummy NSPanel for the sheet. Don't use [NSOpenPanel openPanel], - // otherwise a stray FI_TFloatingInputWindow is created which the unit test - // harness doesn't like. - base::scoped_nsobject<NSPanel> panel( - [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0, 100, 50) - styleMask:NSTitledWindowMask - backing:NSBackingStoreBuffered - defer:NO]); - EXPECT_FALSE([panel isReleasedWhenClosed]); // scoped_nsobject releases it. - - // With a NSOpenPanel, we would call -[NSSavePanel beginSheetModalForWindow] - // here. In 10.9, we would call [NSWindow beginSheet:]. For 10.6, this: - [[NSApplication sharedApplication] beginSheet:panel - modalForWindow:bubble_window_ - modalDelegate:nil - didEndSelector:NULL - contextInfo:NULL]; - - EXPECT_TRUE([bubble_window_ isVisible]); - EXPECT_TRUE([panel isVisible]); - // Losing key status while there is an attached window should not close the - // bubble. - SimulateKeyStatusChange(); - EXPECT_TRUE([bubble_window_ isVisible]); - EXPECT_TRUE([panel isVisible]); - - // Closing the attached sheet should not close the bubble. - [[NSApplication sharedApplication] endSheet:panel]; - [panel close]; - - EXPECT_FALSE([bubble_window_ attachedSheet]); - EXPECT_TRUE([bubble_window_ isVisible]); - EXPECT_FALSE([panel isVisible]); - - // Now that the sheet is gone, a key status change should close the bubble. - SimulateKeyStatusChange(); - EXPECT_FALSE([bubble_window_ isVisible]); -} - -// Tests that a bubble will close when a window enters fullscreen. -TEST_F(BaseBubbleControllerTest, EnterFullscreen) { - base::scoped_nsobject<BaseBubbleController> keep_alive = ShowBubble(); - - EXPECT_TRUE([bubble_window_ isVisible]); - - // Post the "enter fullscreen" notification. - NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; - [center postNotificationName:NSWindowWillEnterFullScreenNotification - object:test_window()]; - - EXPECT_FALSE([bubble_window_ isVisible]); -} - -// Tests that a bubble will close when a window exits fullscreen. -TEST_F(BaseBubbleControllerTest, ExitFullscreen) { - base::scoped_nsobject<BaseBubbleController> keep_alive = ShowBubble(); - - EXPECT_TRUE([bubble_window_ isVisible]); - - // Post the "exit fullscreen" notification. - NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; - [center postNotificationName:NSWindowWillExitFullScreenNotification - object:test_window()]; - - EXPECT_FALSE([bubble_window_ isVisible]); -} - -// Tests that a bubble will not close when it's becoming a key window. -TEST_F(BaseBubbleControllerTest, StayOnFocus) { - [controller_ setShouldOpenAsKeyWindow:NO]; - base::scoped_nsobject<BaseBubbleController> keep_alive = ShowBubble(); - - EXPECT_TRUE([bubble_window_ isVisible]); - EXPECT_TRUE([controller_ shouldCloseOnResignKey]); // Verify default value. - - // Make the bubble a key window. - g_key_window = [controller_ window]; - base::mac::ScopedObjCClassSwizzler swizzler( - [NSApplication class], [FakeKeyWindow class], @selector(keyWindow)); - - // Post the "resign key" notification for another window. - NSNotification* notif = - [NSNotification notificationWithName:NSWindowDidResignKeyNotification - object:test_window()]; - [[NSNotificationCenter defaultCenter] postNotification:notif]; - - EXPECT_TRUE([bubble_window_ isVisible]); - g_key_window = nil; -} - -// Test that clicking inside a child window of a bubble, does not dismiss the -// bubble, even if shouldCloseOnResignKey is YES. -TEST_F(BaseBubbleControllerTest, MouseDownInChildWindow) { - [controller_ setShouldCloseOnResignKey:YES]; - - base::scoped_nsobject<NSWindow> child_window([[NSWindow alloc] - initWithContentRect:NSMakeRect(500, 500, 500, 500) - styleMask:NSBorderlessWindowMask - backing:NSBackingStoreBuffered - defer:NO]); - [bubble_window_ addChildWindow:child_window ordered:NSWindowAbove]; - - base::scoped_nsobject<BaseBubbleController> keep_alive = ShowBubble(); - ASSERT_TRUE([bubble_window_ isVisible]); - - NSEvent* event = cocoa_test_event_utils::LeftMouseDownAtPointInWindow( - NSMakePoint(10, 10), child_window); - [NSApp sendEvent:event]; - EXPECT_TRUE([bubble_window_ isVisible]); - - // Clicking outside the bubble on another window should dismiss the bubble. - event = cocoa_test_event_utils::LeftMouseDownAtPointInWindow( - NSMakePoint(10, 10), test_window()); - [NSApp sendEvent:event]; - EXPECT_FALSE([bubble_window_ isVisible]); -} - -// Test that clicking outside the bubble window but on a window with a greater -// level, does not dismiss the bubble, even if shouldCloseOnResignKey is YES. -TEST_F(BaseBubbleControllerTest, MouseDownInPopup) { - [controller_ setShouldCloseOnResignKey:YES]; - - base::scoped_nsobject<NSWindow> other_window([[NSWindow alloc] - initWithContentRect:NSMakeRect(500, 500, 500, 500) - styleMask:NSBorderlessWindowMask - backing:NSBackingStoreBuffered - defer:NO]); - [other_window setLevel:NSPopUpMenuWindowLevel]; - - base::scoped_nsobject<BaseBubbleController> keep_alive = ShowBubble(); - ASSERT_TRUE([bubble_window_ isVisible]); - - NSEvent* event = cocoa_test_event_utils::LeftMouseDownAtPointInWindow( - NSMakePoint(10, 10), other_window); - [NSApp sendEvent:event]; - EXPECT_TRUE([bubble_window_ isVisible]); - - // Clicking outside the bubble on a normal window should dismiss the bubble. - [other_window setLevel:NSNormalWindowLevel]; - ASSERT_GT(NSPopUpMenuWindowLevel, NSNormalWindowLevel); - - event = cocoa_test_event_utils::LeftMouseDownAtPointInWindow( - NSMakePoint(10, 10), other_window); - [NSApp sendEvent:event]; - EXPECT_FALSE([bubble_window_ isVisible]); -}
diff --git a/chrome/browser/ui/cocoa/browser/zoom_bubble_controller.h b/chrome/browser/ui/cocoa/browser/zoom_bubble_controller.h deleted file mode 100644 index 474e0fe..0000000 --- a/chrome/browser/ui/cocoa/browser/zoom_bubble_controller.h +++ /dev/null
@@ -1,86 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_COCOA_BROWSER_ZOOM_BUBBLE_CONTROLLER_H_ -#define CHROME_BROWSER_UI_COCOA_BROWSER_ZOOM_BUBBLE_CONTROLLER_H_ - -#include "base/mac/scoped_block.h" -#include "base/mac/scoped_nsobject.h" -#import "chrome/browser/ui/cocoa/omnibox_decoration_bubble_controller.h" -#import "ui/base/cocoa/tracking_area.h" - -namespace content { -class WebContents; -} - -// TODO(shess): This helper interface exists to let ZoomBubbleController -// reach ZoomDecoration. Since ZoomBubbleController is an implementation -// detail of ZoomDecoration, it would make more sense to just push it -// into location_bar/ and directly access ZoomDecoration. -class ZoomBubbleControllerDelegate { - public: - // Get the web contents associated with this bubble. - virtual content::WebContents* GetWebContents() = 0; - - // Called when the bubble is being closed. - virtual void OnClose() = 0; -}; - -// The ZoomBubbleController is used to display the current page zoom percent -// when not at the user's default. It is opened by the ZoomDecoration in the -// location bar. -@interface ZoomBubbleController : OmniboxDecorationBubbleController { - @private - ZoomBubbleControllerDelegate* delegate_; - - // Whether or not the bubble should automatically close itself after being - // opened. - BOOL autoClose_; - - // The text field that displays the current zoom percentage. - base::scoped_nsobject<NSTextField> zoomPercent_; - - // Whether or not the mouse is over the bubble. - BOOL isMouseInside_; - - // Used to prevent the bubble from auto-closing while the mouse is inside it. - ui::ScopedCrTrackingArea trackingArea_; -} - -@property(nonatomic) ZoomBubbleControllerDelegate* delegate; - -// Creates the bubble for a parent window but does not show it. -- (id)initWithParentWindow:(NSWindow*)parentWindow - delegate:(ZoomBubbleControllerDelegate*)delegate; - -// Shows the bubble at |anchorPoint| in window coordinates. If -// |autoClose| is YES, then the bubble was opened in response to a -// zoom change rather than a direct user action, and it will -// automatically dismiss itself after a few seconds. -- (void)showAnchoredAt:(NSPoint)anchorPoint autoClose:(BOOL)autoClose; - -// Called by the ZoomDecoration when the zoom percentage changes. -- (void)onZoomChanged; - -// Button action from the bubble that resets the zoom level to the default. -- (void)resetToDefault:(id)sender; - -// Button action from the bubble that increases the zoom level. -- (void)zoomIn:(id)sender; - -// Button action from the bubble that decreases the zoom level. -- (void)zoomOut:(id)sender; - -// Closes the bubble synchronously, bypassing any animations. -- (void)closeWithoutAnimation; - -@end - -namespace chrome { - -void SetZoomBubbleAutoCloseDelayForTesting(NSTimeInterval time_interval); - -} // namespace chrome - -#endif // CHROME_BROWSER_UI_COCOA_BROWSER_ZOOM_BUBBLE_CONTROLLER_H_
diff --git a/chrome/browser/ui/cocoa/browser/zoom_bubble_controller.mm b/chrome/browser/ui/cocoa/browser/zoom_bubble_controller.mm deleted file mode 100644 index c2f3efb..0000000 --- a/chrome/browser/ui/cocoa/browser/zoom_bubble_controller.mm +++ /dev/null
@@ -1,373 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/cocoa/browser/zoom_bubble_controller.h" - -#include "base/i18n/number_formatting.h" -#include "base/mac/foundation_util.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/sys_string_conversions.h" -#import "chrome/browser/ui/cocoa/browser_window_controller.h" -#import "chrome/browser/ui/cocoa/info_bubble_view.h" -#import "chrome/browser/ui/cocoa/info_bubble_window.h" -#include "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" -#import "chrome/browser/ui/cocoa/location_bar/zoom_decoration.h" -#include "chrome/grit/generated_resources.h" -#include "components/zoom/page_zoom.h" -#include "components/zoom/zoom_controller.h" -#include "content/public/common/page_zoom.h" -#include "skia/ext/skia_utils_mac.h" -#import "ui/base/cocoa/hover_button.h" -#import "ui/base/cocoa/window_size_constants.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/native_theme/native_theme.h" - -@interface ZoomBubbleController (Private) -- (void)performLayout; -- (void)autoCloseBubble; -- (NSAttributedString*)attributedStringWithString:(NSString*)string - fontSize:(CGFloat)fontSize; -// Adds a new zoom button to the bubble. -- (NSButton*)addButtonWithTitleID:(int)titleID - fontSize:(CGFloat)fontSize - action:(SEL)action; -- (NSTextField*)addZoomPercentTextField; -- (void)updateAutoCloseTimer; - -// Get the WebContents instance and apply the indicated zoom. -- (void)zoomHelper:(content::PageZoom)alterPageZoom; -@end - -// Button that highlights the background on mouse over. -@interface ZoomHoverButton : HoverButtonCocoa -@end - -namespace { - -// The amount of time to wait before the bubble automatically closes. -// Should keep in sync with kBubbleCloseDelay in -// src/chrome/browser/ui/views/location_bar/zoom_bubble_view.cc. -NSTimeInterval gAutoCloseDelay = 1.5; - -// The height of the window. -const CGFloat kZoomBubbleWindowHeight = 29.0; - -// Width of the zoom in and zoom out buttons. -const CGFloat kZoomInOutButtonWidth = 44.0; - -// Width of zoom label. -const CGFloat kZoomLabelWidth = 55.0; - -// Horizontal margin for the reset zoom button. -const CGFloat kResetZoomMargin = 9.0; - -// The font size text shown in the bubble. -const CGFloat kTextFontSize = 12.0; - -// The font size of the zoom in and zoom out buttons. -const CGFloat kZoomInOutButtonFontSize = 16.0; - -} // namespace - -namespace chrome { - -void SetZoomBubbleAutoCloseDelayForTesting(NSTimeInterval time_interval) { - gAutoCloseDelay = time_interval; -} - -} // namespace chrome - -@implementation ZoomBubbleController - -@synthesize delegate = delegate_; - -- (id)initWithParentWindow:(NSWindow*)parentWindow - delegate:(ZoomBubbleControllerDelegate*)delegate { - base::scoped_nsobject<InfoBubbleWindow> window( - [[InfoBubbleWindow alloc] initWithContentRect:NSMakeRect(0, 0, 200, 100) - styleMask:NSBorderlessWindowMask - backing:NSBackingStoreBuffered - defer:NO]); - if ((self = [super initWithWindow:window - parentWindow:parentWindow - anchoredAt:NSZeroPoint])) { - [window setInfoBubbleCanBecomeKeyWindow:NO]; - delegate_ = delegate; - - ui::NativeTheme* nativeTheme = ui::NativeTheme::GetInstanceForNativeUi(); - [[self bubble] setAlignment:info_bubble::kAlignTrailingEdgeToAnchorEdge]; - [[self bubble] setArrowLocation:info_bubble::kNoArrow]; - [[self bubble] setBackgroundColor: - skia::SkColorToCalibratedNSColor(nativeTheme->GetSystemColor( - ui::NativeTheme::kColorId_DialogBackground))]; - - [self performLayout]; - - trackingArea_.reset([[CrTrackingArea alloc] - initWithRect:NSZeroRect - options:NSTrackingMouseEnteredAndExited | - NSTrackingActiveAlways | - NSTrackingInVisibleRect - owner:self - userInfo:nil]); - [trackingArea_.get() clearOwnerWhenWindowWillClose:[self window]]; - [[[self window] contentView] addTrackingArea:trackingArea_.get()]; - } - return self; -} - -- (void)showAnchoredAt:(NSPoint)anchorPoint autoClose:(BOOL)autoClose { - [self onZoomChanged]; - InfoBubbleWindow* window = - base::mac::ObjCCastStrict<InfoBubbleWindow>([self window]); - [window setAllowedAnimations:autoClose - ? info_bubble::kAnimateOrderIn | info_bubble::kAnimateOrderOut - : info_bubble::kAnimateNone]; - - self.anchorPoint = anchorPoint; - [self showWindow:nil]; - - autoClose_ = autoClose; - [self updateAutoCloseTimer]; -} - -- (void)onZoomChanged { - // |delegate_| may be set null by this object's owner. - if (!delegate_) - return; - - // TODO(shess): It may be appropriate to close the window if - // |contents| or |zoomController| are NULL. But they can be NULL in - // tests. - - content::WebContents* contents = delegate_->GetWebContents(); - if (!contents) - return; - - zoom::ZoomController* zoomController = - zoom::ZoomController::FromWebContents(contents); - if (!zoomController) - return; - - int percent = zoomController->GetZoomPercent(); - NSString* string = base::SysUTF16ToNSString(base::FormatPercent(percent)); - [zoomPercent_ setAttributedStringValue: - [self attributedStringWithString:string - fontSize:kTextFontSize]]; - - [self updateAutoCloseTimer]; -} - -- (void)resetToDefault:(id)sender { - [self zoomHelper:content::PAGE_ZOOM_RESET]; -} - -- (void)zoomIn:(id)sender { - [self zoomHelper:content::PAGE_ZOOM_IN]; -} - -- (void)zoomOut:(id)sender { - [self zoomHelper:content::PAGE_ZOOM_OUT]; -} - -- (void)closeWithoutAnimation { - InfoBubbleWindow* window = - base::mac::ObjCCastStrict<InfoBubbleWindow>([self window]); - [window setAllowedAnimations:info_bubble::kAnimateNone]; - [self close]; -} - -// OmniboxDecorationBubbleController implementation. -- (LocationBarDecoration*)decorationForBubble { - BrowserWindowController* controller = [BrowserWindowController - browserWindowControllerForWindow:[self parentWindow]]; - LocationBarViewMac* locationBar = [controller locationBarBridge]; - return locationBar ? locationBar->zoom_decoration() : nullptr; -} - -// NSWindowController implementation. -- (void)windowWillClose:(NSNotification*)notification { - // |delegate_| may be set null by this object's owner. - if (delegate_) { - delegate_->OnClose(); - delegate_ = NULL; - } - [NSObject cancelPreviousPerformRequestsWithTarget:self - selector:@selector(autoCloseBubble) - object:nil]; - [super windowWillClose:notification]; -} - -- (void)mouseEntered:(NSEvent*)theEvent { - isMouseInside_ = YES; - [self updateAutoCloseTimer]; -} - -- (void)mouseExited:(NSEvent*)theEvent { - isMouseInside_ = NO; - [self updateAutoCloseTimer]; -} - -// Private ///////////////////////////////////////////////////////////////////// - -- (void)performLayout { - // Zoom out button. - NSButton* zoomOutButton = [self addButtonWithTitleID:IDS_ZOOM_MINUS2 - fontSize:kZoomInOutButtonFontSize - action:@selector(zoomOut:)]; - NSRect rect = - NSMakeRect(0, 0, kZoomInOutButtonWidth, kZoomBubbleWindowHeight); - [zoomOutButton setFrame:rect]; - - // Zoom label. - zoomPercent_.reset([[self addZoomPercentTextField] retain]); - rect.origin.x += NSWidth(rect); - rect.size.width = kZoomLabelWidth; - [zoomPercent_ sizeToFit]; - NSRect zoomRect = rect; - zoomRect.size.height = NSHeight([zoomPercent_ frame]); - zoomRect.origin.y = roundf((NSHeight(rect) - NSHeight(zoomRect)) / 2.0); - [zoomPercent_ setFrame:zoomRect]; - - // Zoom in button. - NSButton* zoomInButton = [self addButtonWithTitleID:IDS_ZOOM_PLUS2 - fontSize:kZoomInOutButtonFontSize - action:@selector(zoomIn:)]; - rect.origin.x += NSWidth(rect); - rect.size.width = kZoomInOutButtonWidth; - [zoomInButton setFrame:rect]; - - // Separator view. - rect.origin.x += NSWidth(rect); - rect.size.width = 1; - base::scoped_nsobject<NSBox> separatorView( - [[NSBox alloc] initWithFrame:rect]); - [separatorView setBoxType:NSBoxCustom]; - ui::NativeTheme* nativeTheme = ui::NativeTheme::GetInstanceForNativeUi(); - [separatorView setBorderColor: - skia::SkColorToCalibratedNSColor(nativeTheme->GetSystemColor( - ui::NativeTheme::kColorId_MenuSeparatorColor))]; - [[[self window] contentView] addSubview:separatorView]; - - // Reset zoom button. - NSButton* resetButton = - [self addButtonWithTitleID:IDS_ZOOM_SET_DEFAULT - fontSize:kTextFontSize - action:@selector(resetToDefault:)]; - rect.origin.x += NSWidth(rect); - rect.size.width = - [[resetButton attributedTitle] size].width + kResetZoomMargin * 2.0; - [resetButton setFrame:rect]; - - // Update window frame. - NSRect windowFrame = [[self window] frame]; - windowFrame.size.height = NSHeight(rect); - windowFrame.size.width = NSMaxX(rect); - [[self window] setFrame:windowFrame display:YES]; -} - -- (void)autoCloseBubble { - if (!autoClose_) - return; - [self close]; -} - -- (NSAttributedString*)attributedStringWithString:(NSString*)string - fontSize:(CGFloat)fontSize { - base::scoped_nsobject<NSMutableParagraphStyle> paragraphStyle( - [[NSMutableParagraphStyle alloc] init]); - [paragraphStyle setAlignment:NSCenterTextAlignment]; - NSDictionary* attributes = @{ - NSFontAttributeName: - [NSFont systemFontOfSize:fontSize], - NSForegroundColorAttributeName: - [NSColor colorWithCalibratedWhite:0.58 alpha:1.0], - NSParagraphStyleAttributeName: - paragraphStyle.get() - }; - return [[[NSAttributedString alloc] - initWithString:string - attributes:attributes] autorelease]; -} - -- (NSButton*)addButtonWithTitleID:(int)titleID - fontSize:(CGFloat)fontSize - action:(SEL)action { - base::scoped_nsobject<NSButton> button( - [[ZoomHoverButton alloc] initWithFrame:NSZeroRect]); - NSString* title = l10n_util::GetNSStringWithFixup(titleID); - [button setAttributedTitle:[self attributedStringWithString:title - fontSize:fontSize]]; - [[button cell] setBordered:NO]; - [button setTarget:self]; - [button setAction:action]; - [[[self window] contentView] addSubview:button]; - return button.autorelease(); -} - -- (NSTextField*)addZoomPercentTextField { - base::scoped_nsobject<NSTextField> textField( - [[NSTextField alloc] initWithFrame:NSZeroRect]); - [textField setEditable:NO]; - [textField setBordered:NO]; - [textField setDrawsBackground:NO]; - [[[self window] contentView] addSubview:textField]; - return textField.autorelease(); -} - -- (void)updateAutoCloseTimer { - [NSObject cancelPreviousPerformRequestsWithTarget:self - selector:@selector(autoCloseBubble) - object:nil]; - if (autoClose_ && !isMouseInside_) { - [self performSelector:@selector(autoCloseBubble) - withObject:nil - afterDelay:gAutoCloseDelay]; - } -} - -- (void)zoomHelper:(content::PageZoom)alterPageZoom { - // |delegate| can be null after -windowWillClose:. - if (!delegate_) - return; - content::WebContents* webContents = delegate_->GetWebContents(); - - // TODO(shess): Zoom() immediately dereferences |webContents|, and - // there haven't been associated crashes in the wild, so it seems - // fine in practice. It might make sense to close the bubble in - // that case, though. - zoom::PageZoom::Zoom(webContents, alterPageZoom); -} - -@end - -@implementation ZoomHoverButton - -- (void)drawRect:(NSRect)rect { - NSRect bounds = [self bounds]; - NSAttributedString* title = [self attributedTitle]; - if ([self hoverState] != kHoverStateNone) { - ui::NativeTheme* nativeTheme = ui::NativeTheme::GetInstanceForNativeUi(); - [skia::SkColorToCalibratedNSColor(nativeTheme->GetSystemColor( - ui::NativeTheme::kColorId_FocusedMenuItemBackgroundColor)) set]; - NSRectFillUsingOperation(bounds, NSCompositeSourceOver); - - // Change the title color. - base::scoped_nsobject<NSMutableAttributedString> selectedTitle( - [[NSMutableAttributedString alloc] initWithAttributedString:title]); - NSColor* selectedTitleColor = - skia::SkColorToCalibratedNSColor(nativeTheme->GetSystemColor( - ui::NativeTheme::kColorId_SelectedMenuItemForegroundColor)); - [selectedTitle addAttribute:NSForegroundColorAttributeName - value:selectedTitleColor - range:NSMakeRange(0, [title length])]; - title = selectedTitle.autorelease(); - } - - [[self cell] drawTitle:title - withFrame:bounds - inView:self]; -} - -@end
diff --git a/chrome/browser/ui/cocoa/browser/zoom_bubble_controller_unittest.mm b/chrome/browser/ui/cocoa/browser/zoom_bubble_controller_unittest.mm deleted file mode 100644 index 0bd120f8..0000000 --- a/chrome/browser/ui/cocoa/browser/zoom_bubble_controller_unittest.mm +++ /dev/null
@@ -1,90 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/cocoa/browser/zoom_bubble_controller.h" - -#include "base/mac/foundation_util.h" -#include "base/time/time.h" -#import "chrome/browser/ui/cocoa/info_bubble_window.h" -#import "chrome/browser/ui/cocoa/test/cocoa_test_helper.h" -#include "chrome/browser/ui/cocoa/test/run_loop_testing.h" -#import "ui/events/test/cocoa_test_event_utils.h" - -typedef CocoaTest ZoomBubbleControllerTest; - -namespace { - -class TestZoomBubbleControllerDelegate : public ZoomBubbleControllerDelegate { - public: - TestZoomBubbleControllerDelegate() : did_close_(false) {} - - // Get the web contents associated with this bubble. - content::WebContents* GetWebContents() override { return NULL; } - - // Called when the bubble is being closed. - void OnClose() override { did_close_ = true; } - - bool did_close() { return did_close_; } - - private: - bool did_close_; -}; - -} // namespace - -TEST_F(ZoomBubbleControllerTest, CloseObserver) { - TestZoomBubbleControllerDelegate test_delegate; - - ZoomBubbleController* controller = - [[ZoomBubbleController alloc] initWithParentWindow:test_window() - delegate:&test_delegate]; - [controller showAnchoredAt:NSZeroPoint autoClose:NO]; - [base::mac::ObjCCastStrict<InfoBubbleWindow>([controller window]) - setAllowedAnimations:info_bubble::kAnimateNone]; - - EXPECT_FALSE(test_delegate.did_close()); - - [controller close]; - chrome::testing::NSRunLoopRunAllPending(); - - EXPECT_TRUE(test_delegate.did_close()); -} - -TEST_F(ZoomBubbleControllerTest, AutoClose) { - TestZoomBubbleControllerDelegate test_delegate; - - ZoomBubbleController* controller = - [[ZoomBubbleController alloc] initWithParentWindow:test_window() - delegate:&test_delegate]; - chrome::SetZoomBubbleAutoCloseDelayForTesting(0); - [controller showAnchoredAt:NSZeroPoint autoClose:YES]; - [base::mac::ObjCCastStrict<InfoBubbleWindow>([controller window]) - setAllowedAnimations:info_bubble::kAnimateNone]; - - EXPECT_FALSE(test_delegate.did_close()); - chrome::testing::NSRunLoopRunAllPending(); - EXPECT_TRUE(test_delegate.did_close()); -} - -TEST_F(ZoomBubbleControllerTest, MouseEnteredExited) { - TestZoomBubbleControllerDelegate test_delegate; - - ZoomBubbleController* controller = - [[ZoomBubbleController alloc] initWithParentWindow:test_window() - delegate:&test_delegate]; - - chrome::SetZoomBubbleAutoCloseDelayForTesting(0); - [controller showAnchoredAt:NSZeroPoint autoClose:YES]; - [base::mac::ObjCCastStrict<InfoBubbleWindow>([controller window]) - setAllowedAnimations:info_bubble::kAnimateNone]; - - EXPECT_FALSE(test_delegate.did_close()); - [controller mouseEntered:cocoa_test_event_utils::EnterEvent()]; - chrome::testing::NSRunLoopRunAllPending(); - EXPECT_FALSE(test_delegate.did_close()); - - [controller mouseExited:cocoa_test_event_utils::ExitEvent()]; - chrome::testing::NSRunLoopRunAllPending(); - EXPECT_TRUE(test_delegate.did_close()); -}
diff --git a/chrome/browser/ui/cocoa/browser_window_cocoa.mm b/chrome/browser/ui/cocoa/browser_window_cocoa.mm index e4a5e72..7e9789f 100644 --- a/chrome/browser/ui/cocoa/browser_window_cocoa.mm +++ b/chrome/browser/ui/cocoa/browser_window_cocoa.mm
@@ -29,7 +29,6 @@ #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window_state.h" -#include "chrome/browser/ui/cocoa/autofill/save_card_bubble_view_views.h" #import "chrome/browser/ui/cocoa/browser/exclusive_access_controller_views.h" #include "chrome/browser/ui/cocoa/browser_dialogs_views_mac.h" #import "chrome/browser/ui/cocoa/browser_window_controller.h" @@ -37,7 +36,6 @@ #import "chrome/browser/ui/cocoa/chrome_event_processing_window.h" #import "chrome/browser/ui/cocoa/constrained_window/constrained_window_sheet_controller.h" #import "chrome/browser/ui/cocoa/extensions/browser_actions_controller.h" -#import "chrome/browser/ui/cocoa/info_bubble_view.h" #include "chrome/browser/ui/cocoa/key_equivalent_constants.h" #import "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" #import "chrome/browser/ui/cocoa/nsmenuitem_additions.h" @@ -500,8 +498,7 @@ content::WebContents* web_contents, autofill::SaveCardBubbleController* controller, bool user_gesture) { - return autofill::CreateSaveCardBubbleView(web_contents, controller, - controller_, user_gesture); + return nullptr; } autofill::LocalCardMigrationBubble* @@ -519,16 +516,6 @@ translate::TranslateStep step, translate::TranslateErrors::Type error_type, bool is_user_gesture) { - ChromeTranslateClient* chrome_translate_client = - ChromeTranslateClient::FromWebContents(contents); - translate::LanguageState& language_state = - chrome_translate_client->GetLanguageState(); - language_state.SetTranslateEnabled(true); - - [controller_ showTranslateBubbleForWebContents:contents - step:step - errorType:error_type]; - return ShowTranslateBubbleResult::SUCCESS; }
diff --git a/chrome/browser/ui/cocoa/browser_window_controller.h b/chrome/browser/ui/cocoa/browser_window_controller.h index 239f73e..7e0ab8f 100644 --- a/chrome/browser/ui/cocoa/browser_window_controller.h +++ b/chrome/browser/ui/cocoa/browser_window_controller.h
@@ -287,12 +287,6 @@ // Delegate method for the status bubble to query its base frame. - (NSRect)statusBubbleBaseFrame; -// Show the translate bubble. -- (void)showTranslateBubbleForWebContents:(content::WebContents*)contents - step:(translate::TranslateStep)step - errorType: - (translate::TranslateErrors::Type)errorType; - // Dismiss the permission bubble - (void)dismissPermissionBubble;
diff --git a/chrome/browser/ui/cocoa/browser_window_controller.mm b/chrome/browser/ui/cocoa/browser_window_controller.mm index 15869f5..68395bf 100644 --- a/chrome/browser/ui/cocoa/browser_window_controller.mm +++ b/chrome/browser/ui/cocoa/browser_window_controller.mm
@@ -58,7 +58,6 @@ #include "chrome/browser/ui/cocoa/l10n_util.h" #import "chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_editor.h" #import "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" -#import "chrome/browser/ui/cocoa/location_bar/star_decoration.h" #import "chrome/browser/ui/cocoa/status_bubble_mac.h" #import "chrome/browser/ui/cocoa/tab_contents/overlayable_contents_controller.h" #import "chrome/browser/ui/cocoa/tab_contents/tab_contents_controller.h" @@ -69,7 +68,6 @@ #import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h" #import "chrome/browser/ui/cocoa/toolbar/toolbar_view_cocoa.h" #import "chrome/browser/ui/cocoa/touchbar/browser_window_touch_bar_controller.h" -#include "chrome/browser/ui/cocoa/translate/translate_bubble_bridge_views.h" #include "chrome/browser/ui/exclusive_access/fullscreen_controller.h" #include "chrome/browser/ui/location_bar/location_bar.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" @@ -1238,7 +1236,6 @@ } - (void)showNewTabButton:(BOOL)show { - [tabStripController_ showNewTabButton:show]; } - (BOOL)isBookmarkBarVisible { @@ -1376,14 +1373,6 @@ alignment:alignment]; } -- (void)showTranslateBubbleForWebContents:(content::WebContents*)contents - step:(translate::TranslateStep)step - errorType:(translate::TranslateErrors::Type) - errorType { - ShowTranslateBubbleViews([self window], [self locationBarBridge], contents, - step, errorType, true); -} - - (void)dismissPermissionBubble { PermissionPrompt::Delegate* delegate = [self permissionRequestManager]; if (delegate)
diff --git a/chrome/browser/ui/cocoa/bubble_anchor_helper_views.h b/chrome/browser/ui/cocoa/bubble_anchor_helper_views.h index fec4f20a..690d1fa8 100644 --- a/chrome/browser/ui/cocoa/bubble_anchor_helper_views.h +++ b/chrome/browser/ui/cocoa/bubble_anchor_helper_views.h
@@ -13,9 +13,6 @@ class LocationBarDecoration; -// Returns the manage password icon decoration in the omnibox. -LocationBarDecoration* GetManagePasswordDecoration(gfx::NativeWindow window); - // Returns the page info decoration in the omnibox. LocationBarDecoration* GetPageInfoDecoration(gfx::NativeWindow window);
diff --git a/chrome/browser/ui/cocoa/bubble_anchor_helper_views.mm b/chrome/browser/ui/cocoa/bubble_anchor_helper_views.mm index 3d950a2..62eff004 100644 --- a/chrome/browser/ui/cocoa/bubble_anchor_helper_views.mm +++ b/chrome/browser/ui/cocoa/bubble_anchor_helper_views.mm
@@ -12,9 +12,7 @@ #include "chrome/browser/ui/cocoa/l10n_util.h" #import "chrome/browser/ui/cocoa/location_bar/location_bar_decoration.h" #import "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" -#import "chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.h" #import "chrome/browser/ui/cocoa/location_bar/page_info_bubble_decoration.h" -#import "chrome/browser/ui/cocoa/location_bar/save_credit_card_decoration.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" #include "ui/views/widget/widget_observer.h" @@ -77,13 +75,6 @@ } // namespace -LocationBarDecoration* GetManagePasswordDecoration(gfx::NativeWindow window) { - BrowserWindowController* window_controller = - [BrowserWindowController browserWindowControllerForWindow:window]; - LocationBarViewMac* location_bar = [window_controller locationBarBridge]; - return location_bar ? location_bar->manage_passwords_decoration() : nullptr; -} - LocationBarDecoration* GetPageInfoDecoration(gfx::NativeWindow window) { BrowserWindowController* window_controller = [BrowserWindowController browserWindowControllerForWindow:window];
diff --git a/chrome/browser/ui/cocoa/extensions/browser_action_test_util_views_cocoa.mm b/chrome/browser/ui/cocoa/extensions/browser_action_test_util_views_cocoa.mm index 2483610..5e16e985 100644 --- a/chrome/browser/ui/cocoa/extensions/browser_action_test_util_views_cocoa.mm +++ b/chrome/browser/ui/cocoa/extensions/browser_action_test_util_views_cocoa.mm
@@ -21,7 +21,6 @@ #import "chrome/browser/ui/cocoa/extensions/browser_actions_container_view.h" #import "chrome/browser/ui/cocoa/extensions/browser_actions_controller.h" #include "chrome/browser/ui/cocoa/extensions/extension_popup_views_mac.h" -#import "chrome/browser/ui/cocoa/info_bubble_window.h" #import "chrome/browser/ui/cocoa/test/cocoa_test_helper.h" #import "chrome/browser/ui/cocoa/themed_window.h" #import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h"
diff --git a/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.h b/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.h deleted file mode 100644 index 6faeff65..0000000 --- a/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.h +++ /dev/null
@@ -1,92 +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_UI_COCOA_EXTENSIONS_MEDIA_GALLERIES_DIALOG_COCOA_H_ -#define CHROME_BROWSER_UI_COCOA_EXTENSIONS_MEDIA_GALLERIES_DIALOG_COCOA_H_ - -#import <Cocoa/Cocoa.h> - -#include "base/gtest_prod_util.h" -#include "base/macros.h" -#include "chrome/browser/media_galleries/media_galleries_dialog_controller.h" -#import "chrome/browser/ui/cocoa/constrained_window/constrained_window_mac.h" -#import "chrome/browser/ui/cocoa/extensions/media_gallery_list_entry_view.h" - -@class ConstrainedWindowAlert; -@class MediaGalleriesCocoaController; -@class NSString; - -class MediaGalleriesDialogBrowserTest; -class MediaGalleriesDialogTest; - -namespace ui { -class MenuModel; -} - -// This class displays an alert that can be used to manage lists of media -// galleries. -class MediaGalleriesDialogCocoa : public ConstrainedWindowMacDelegate, - public MediaGalleriesDialog, - public MediaGalleryListEntryController { - public: - MediaGalleriesDialogCocoa( - MediaGalleriesDialogController* controller, - MediaGalleriesCocoaController* delegate); - ~MediaGalleriesDialogCocoa() override; - - // Called when the user clicks the accept button. - void OnAcceptClicked(); - // Called when the user clicks the cancel button. - void OnCancelClicked(); - // Called when the user clicks the auxiliary button. - void OnAuxiliaryButtonClicked(); - - // MediaGalleriesDialog implementation: - void UpdateGalleries() override; - - // ConstrainedWindowMacDelegate implementation. - void OnConstrainedWindowClosed(ConstrainedWindowMac* window) override; - - // MediaGalleryListEntryController implementation. - void OnCheckboxToggled(MediaGalleryPrefId pref_id, bool checked) override; - ui::MenuModel* GetContextMenu(MediaGalleryPrefId pref_id) override; - - private: - FRIEND_TEST_ALL_PREFIXES(MediaGalleriesDialogBrowserTest, Close); - FRIEND_TEST_ALL_PREFIXES(MediaGalleriesDialogTest, InitializeCheckboxes); - FRIEND_TEST_ALL_PREFIXES(MediaGalleriesDialogTest, ToggleCheckboxes); - FRIEND_TEST_ALL_PREFIXES(MediaGalleriesDialogTest, UpdateAdds); - FRIEND_TEST_ALL_PREFIXES(MediaGalleriesDialogTest, ForgetDeletes); - - // MediaGalleriesDialog implementation: - void AcceptDialogForTesting() override; - - void InitDialogControls(); - CGFloat CreateCheckboxes( - CGFloat y_pos, - const MediaGalleriesDialogController::Entries& entries); - CGFloat CreateCheckboxSeparator(CGFloat y_pos, NSString* header); - - MediaGalleriesDialogController* controller_; // weak - std::unique_ptr<ConstrainedWindowMac> window_; - - // The alert that the dialog is being displayed as. - base::scoped_nsobject<ConstrainedWindowAlert> alert_; - - // True if the user has pressed accept. - bool accepted_; - - // Container view for checkboxes. - base::scoped_nsobject<NSView> checkbox_container_; - - // Container view for the main dialog contents. - base::scoped_nsobject<NSBox> main_container_; - - // An Objective-C class to route callbacks from Cocoa code. - base::scoped_nsobject<MediaGalleriesCocoaController> cocoa_controller_; - - DISALLOW_COPY_AND_ASSIGN(MediaGalleriesDialogCocoa); -}; - -#endif // CHROME_BROWSER_UI_COCOA_EXTENSIONS_MEDIA_GALLERIES_DIALOG_COCOA_H_
diff --git a/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.mm b/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.mm deleted file mode 100644 index d1f79574..0000000 --- a/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.mm +++ /dev/null
@@ -1,289 +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/ui/cocoa/extensions/media_galleries_dialog_cocoa.h" - -#include <stddef.h> - -#include "base/mac/scoped_nsobject.h" -#include "base/strings/sys_string_conversions.h" -#include "chrome/browser/ui/cocoa/chrome_style.h" -#import "chrome/browser/ui/cocoa/constrained_window/constrained_window_alert.h" -#import "chrome/browser/ui/cocoa/constrained_window/constrained_window_button.h" -#import "chrome/browser/ui/cocoa/constrained_window/constrained_window_control_utils.h" -#import "chrome/browser/ui/cocoa/constrained_window/constrained_window_custom_sheet.h" -#import "chrome/browser/ui/cocoa/key_equivalent_constants.h" -#include "chrome/grit/generated_resources.h" -#include "content/public/browser/web_contents.h" -#import "ui/base/cocoa/flipped_view.h" -#import "ui/base/cocoa/menu_controller.h" -#include "ui/base/l10n/l10n_util.h" -#import "ui/base/models/menu_model.h" -#include "ui/base/ui_features.h" - -// Controller for UI events on items in the media galleries dialog. -@interface MediaGalleriesCocoaController : NSObject { - @private - MediaGalleriesDialogCocoa* dialog_; -} - -@property(assign, nonatomic) MediaGalleriesDialogCocoa* dialog; - -- (void)onAcceptButton:(id)sender; -- (void)onCancelButton:(id)sender; -- (void)onAuxiliaryButton:(id)sender; - -@end - -@implementation MediaGalleriesCocoaController - -@synthesize dialog = dialog_; - -- (void)onAcceptButton:(id)sender { - dialog_->OnAcceptClicked(); -} - -- (void)onCancelButton:(id)sender { - dialog_->OnCancelClicked(); -} - -- (void)onAuxiliaryButton:(id)sender { - DCHECK(dialog_); - dialog_->OnAuxiliaryButtonClicked(); -} - -@end - -namespace { - -const CGFloat kCheckboxMargin = 10; -const CGFloat kCheckboxMaxWidth = 440; -const CGFloat kScrollAreaHeight = 220; - -} // namespace - -MediaGalleriesDialogCocoa::MediaGalleriesDialogCocoa( - MediaGalleriesDialogController* controller, - MediaGalleriesCocoaController* cocoa_controller) - : controller_(controller), - accepted_(false), - cocoa_controller_([cocoa_controller retain]) { - [cocoa_controller_ setDialog:this]; - - alert_.reset([[ConstrainedWindowAlert alloc] init]); - - [alert_ setMessageText:base::SysUTF16ToNSString(controller_->GetHeader())]; - [alert_ setInformativeText: - base::SysUTF16ToNSString(controller_->GetSubtext())]; - [alert_ addButtonWithTitle: - base::SysUTF16ToNSString(controller_->GetAcceptButtonText()) - keyEquivalent:kKeyEquivalentReturn - target:cocoa_controller_ - action:@selector(onAcceptButton:)]; - [alert_ addButtonWithTitle: - l10n_util::GetNSString(IDS_MEDIA_GALLERIES_DIALOG_CANCEL) - keyEquivalent:kKeyEquivalentEscape - target:cocoa_controller_ - action:@selector(onCancelButton:)]; - base::string16 auxiliaryButtonLabel = controller_->GetAuxiliaryButtonText(); - if (!auxiliaryButtonLabel.empty()) { - [alert_ addButtonWithTitle:base::SysUTF16ToNSString(auxiliaryButtonLabel) - keyEquivalent:kKeyEquivalentNone - target:cocoa_controller_ - action:@selector(onAuxiliaryButton:)]; - } - [[alert_ closeButton] setTarget:cocoa_controller_]; - [[alert_ closeButton] setAction:@selector(onCancelButton:)]; - - InitDialogControls(); - - // May be NULL during tests. - if (controller->WebContents()) { - base::scoped_nsobject<CustomConstrainedWindowSheet> sheet( - [[CustomConstrainedWindowSheet alloc] - initWithCustomWindow:[alert_ window]]); - window_ = CreateAndShowWebModalDialogMac( - this, controller->WebContents(), sheet); - } -} - -MediaGalleriesDialogCocoa::~MediaGalleriesDialogCocoa() { -} - -void MediaGalleriesDialogCocoa::AcceptDialogForTesting() { - OnAcceptClicked(); -} - -void MediaGalleriesDialogCocoa::InitDialogControls() { - main_container_.reset([[NSBox alloc] init]); - [main_container_ setBoxType:NSBoxCustom]; - [main_container_ setBorderType:NSLineBorder]; - [main_container_ setBorderWidth:1]; - [main_container_ setCornerRadius:0]; - [main_container_ setContentViewMargins:NSZeroSize]; - [main_container_ setTitlePosition:NSNoTitle]; - [main_container_ setBorderColor:[NSColor disabledControlTextColor]]; - - base::scoped_nsobject<NSScrollView> scroll_view( - [[NSScrollView alloc] initWithFrame: - NSMakeRect(0, 0, kCheckboxMaxWidth, kScrollAreaHeight)]); - [scroll_view setHasVerticalScroller:YES]; - [scroll_view setHasHorizontalScroller:NO]; - [scroll_view setBorderType:NSNoBorder]; - [scroll_view setAutohidesScrollers:YES]; - [[main_container_ contentView] addSubview:scroll_view]; - - // Add gallery checkboxes inside the scrolling view. - checkbox_container_.reset([[FlippedView alloc] initWithFrame:NSZeroRect]); - - std::vector<base::string16> headers = controller_->GetSectionHeaders(); - CGFloat y_pos = 0; - for (size_t i = 0; i < headers.size(); i++) { - MediaGalleriesDialogController::Entries entries = - controller_->GetSectionEntries(i); - if (!entries.empty()) { - if (!headers[i].empty()) { - y_pos = CreateCheckboxSeparator(y_pos, - base::SysUTF16ToNSString(headers[i])); - } - y_pos = CreateCheckboxes(y_pos, entries); - } - } - - // Give the container a reasonable initial size so that the scroll_view can - // figure out the content size. - [checkbox_container_ setFrameSize:NSMakeSize(kCheckboxMaxWidth, y_pos)]; - [scroll_view setDocumentView:checkbox_container_]; - [checkbox_container_ setFrameSize:NSMakeSize([scroll_view contentSize].width, - y_pos)]; - - // Resize to pack the scroll view if possible. - NSRect scroll_frame = [scroll_view frame]; - if (NSHeight(scroll_frame) > NSHeight([checkbox_container_ frame])) { - scroll_frame.size.height = NSHeight([checkbox_container_ frame]); - [scroll_view setFrameSize:scroll_frame.size]; - } - - [main_container_ setFrameFromContentFrame:scroll_frame]; - [main_container_ setFrameOrigin:NSZeroPoint]; - [alert_ setAccessoryView:main_container_]; - - // As a safeguard against the user skipping reading over the dialog and just - // confirming, the button will be unavailable for dialogs without any checks - // until the user toggles something. - [[[alert_ buttons] objectAtIndex:0] setEnabled: - controller_->IsAcceptAllowed()]; - - [alert_ layout]; -} - -CGFloat MediaGalleriesDialogCocoa::CreateCheckboxes( - CGFloat y_pos, - const MediaGalleriesDialogController::Entries& entries) { - for (MediaGalleriesDialogController::Entries::const_iterator iter = - entries.begin(); iter != entries.end(); ++iter) { - const MediaGalleriesDialogController::Entry& entry = *iter; - base::scoped_nsobject<MediaGalleryListEntry> checkbox_entry( - [[MediaGalleryListEntry alloc] - initWithFrame:NSZeroRect - controller:this - prefInfo:entry.pref_info]); - - [checkbox_entry setState:entry.selected]; - - [checkbox_entry setFrameOrigin:NSMakePoint(0, y_pos)]; - y_pos = NSMaxY([checkbox_entry frame]) + kCheckboxMargin; - - [checkbox_container_ addSubview:checkbox_entry]; - } - - return y_pos; -} - -CGFloat MediaGalleriesDialogCocoa::CreateCheckboxSeparator(CGFloat y_pos, - NSString* header) { - base::scoped_nsobject<NSBox> separator( - [[NSBox alloc] initWithFrame:NSMakeRect( - 0, y_pos + kCheckboxMargin * 0.5, kCheckboxMaxWidth, 1.0)]); - [separator setBoxType:NSBoxSeparator]; - [separator setBorderType:NSLineBorder]; - [separator setAlphaValue:0.2]; - [checkbox_container_ addSubview:separator]; - y_pos += kCheckboxMargin * 0.5 + 4; - - base::scoped_nsobject<NSTextField> unattached_label( - [[NSTextField alloc] initWithFrame:NSZeroRect]); - [unattached_label setEditable:NO]; - [unattached_label setSelectable:NO]; - [unattached_label setBezeled:NO]; - [unattached_label setAttributedStringValue: - constrained_window::GetAttributedLabelString( - header, - chrome_style::kTextFontStyle, - NSNaturalTextAlignment, - NSLineBreakByClipping - )]; - [unattached_label sizeToFit]; - NSSize unattached_label_size = [unattached_label frame].size; - [unattached_label setFrame:NSMakeRect( - kCheckboxMargin, y_pos + kCheckboxMargin, - kCheckboxMaxWidth, unattached_label_size.height)]; - [checkbox_container_ addSubview:unattached_label]; - y_pos = NSMaxY([unattached_label frame]) + kCheckboxMargin; - - return y_pos; -} - -void MediaGalleriesDialogCocoa::OnAcceptClicked() { - accepted_ = true; - - if (window_) - window_->CloseWebContentsModalDialog(); -} - -void MediaGalleriesDialogCocoa::OnCancelClicked() { - if (window_) - window_->CloseWebContentsModalDialog(); -} - -void MediaGalleriesDialogCocoa::OnAuxiliaryButtonClicked() { - controller_->DidClickAuxiliaryButton(); -} - -void MediaGalleriesDialogCocoa::UpdateGalleries() { - InitDialogControls(); -} - -void MediaGalleriesDialogCocoa::OnConstrainedWindowClosed( - ConstrainedWindowMac* window) { - controller_->DialogFinished(accepted_); -} - -void MediaGalleriesDialogCocoa::OnCheckboxToggled(MediaGalleryPrefId pref_id, - bool checked) { - controller_->DidToggleEntry(pref_id, checked); - - [[[alert_ buttons] objectAtIndex:0] setEnabled: - controller_->IsAcceptAllowed()]; -} - -ui::MenuModel* MediaGalleriesDialogCocoa::GetContextMenu( - MediaGalleryPrefId pref_id) { - return controller_->GetContextMenu(pref_id); -} - -// static -MediaGalleriesDialog* MediaGalleriesDialog::CreateCocoa( - MediaGalleriesDialogController* controller) { - base::scoped_nsobject<MediaGalleriesCocoaController> cocoa_controller( - [[MediaGalleriesCocoaController alloc] init]); - return new MediaGalleriesDialogCocoa(controller, cocoa_controller); -} - -#if !BUILDFLAG(MAC_VIEWS_BROWSER) -MediaGalleriesDialog* MediaGalleriesDialog::Create( - MediaGalleriesDialogController* controller) { - return CreateCocoa(controller); -} -#endif
diff --git a/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa_browsertest.mm b/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa_browsertest.mm deleted file mode 100644 index 2471f00d..0000000 --- a/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa_browsertest.mm +++ /dev/null
@@ -1,58 +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 "base/strings/utf_string_conversions.h" -#include "chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.h" - -#include "chrome/browser/media_galleries/media_galleries_dialog_controller_mock.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/cocoa/constrained_window/constrained_window_alert.h" -#include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/views/scoped_macviews_browser_mode.h" -#include "components/web_modal/web_contents_modal_dialog_manager.h" -#include "content/public/test/test_utils.h" -#include "testing/gtest/include/gtest/gtest.h" - -using ::testing::_; -using ::testing::AnyNumber; -using ::testing::NiceMock; -using ::testing::Return; -using ::testing::ReturnRef; - -class MediaGalleriesDialogBrowserTest : public InProcessBrowserTest { - private: - test::ScopedMacViewsBrowserMode cocoa_browser_mode_{false}; -}; - -// Verify that programatically closing the constrained window correctly closes -// the sheet. -IN_PROC_BROWSER_TEST_F(MediaGalleriesDialogBrowserTest, Close) { - NiceMock<MediaGalleriesDialogControllerMock> controller; - - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - EXPECT_CALL(controller, WebContents()). - WillRepeatedly(Return(web_contents)); - std::vector<base::string16> headers; - headers.push_back(base::string16()); // The first section has no header. - headers.push_back(base::ASCIIToUTF16("header2")); - ON_CALL(controller, GetSectionHeaders()). - WillByDefault(Return(headers)); - EXPECT_CALL(controller, GetAuxiliaryButtonText()). - WillRepeatedly(Return(base::ASCIIToUTF16("button"))); - EXPECT_CALL(controller, GetSectionEntries(_)). - Times(AnyNumber()); - - std::unique_ptr<MediaGalleriesDialogCocoa> dialog( - static_cast<MediaGalleriesDialogCocoa*>( - MediaGalleriesDialog::Create(&controller))); - base::scoped_nsobject<NSWindow> window([[dialog->alert_ window] retain]); - EXPECT_TRUE([window isVisible]); - - web_modal::WebContentsModalDialogManager* manager = - web_modal::WebContentsModalDialogManager::FromWebContents(web_contents); - web_modal::WebContentsModalDialogManager::TestApi(manager).CloseAllDialogs(); - EXPECT_FALSE([window isVisible]); -}
diff --git a/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa_unittest.mm b/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa_unittest.mm deleted file mode 100644 index f8b99945..0000000 --- a/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa_unittest.mm +++ /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 "base/macros.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "chrome/browser/media_galleries/media_galleries_dialog_controller_mock.h" -#include "chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.h" -#include "components/storage_monitor/storage_info.h" -#include "extensions/common/extension.h" -#include "testing/gtest/include/gtest/gtest.h" - -using ::testing::_; -using ::testing::AnyNumber; -using ::testing::Mock; -using ::testing::NiceMock; -using ::testing::Return; -using ::testing::ReturnPointee; -using ::testing::ReturnRef; - -@interface MediaGalleryListEntry (testing) -- (NSInteger)state; -- (void)performClick:(id)sender; -@end - -@implementation MediaGalleryListEntry (testing) - -- (NSInteger)state { - return [checkbox_ state]; -} - -- (void)performClick:(id)sender { - [checkbox_ performClick:sender]; -} - -@end - - -MediaGalleryPrefInfo MakePrefInfoForTesting(MediaGalleryPrefId pref_id) { - MediaGalleryPrefInfo gallery; - gallery.pref_id = pref_id; - gallery.device_id = storage_monitor::StorageInfo::MakeDeviceId( - storage_monitor::StorageInfo::FIXED_MASS_STORAGE, - base::Int64ToString(pref_id)); - gallery.display_name = base::ASCIIToUTF16("name"); - return gallery; -} - -class MediaGalleriesDialogTest : public testing::Test { - public: - MediaGalleriesDialogTest() {} - ~MediaGalleriesDialogTest() override {} - - void SetUp() override { - std::vector<base::string16> headers; - headers.push_back(base::string16()); - headers.push_back(base::ASCIIToUTF16("header2")); - ON_CALL(controller_, GetSectionHeaders()). - WillByDefault(Return(headers)); - EXPECT_CALL(controller_, GetSectionEntries(_)). - Times(AnyNumber()); - } - - void TearDown() override { - Mock::VerifyAndClearExpectations(&controller_); - dialog_.reset(); - } - - NiceMock<MediaGalleriesDialogControllerMock>* controller() { - return &controller_; - } - - MediaGalleriesDialogCocoa* GetOrCreateDialog() { - if (!dialog_.get()) { - dialog_.reset(static_cast<MediaGalleriesDialogCocoa*>( - MediaGalleriesDialog::Create(&controller_))); - } - return dialog_.get(); - } - - private: - NiceMock<MediaGalleriesDialogControllerMock> controller_; - - std::unique_ptr<MediaGalleriesDialogCocoa> dialog_; - - DISALLOW_COPY_AND_ASSIGN(MediaGalleriesDialogTest); -}; - -// Tests that checkboxes are initialized according to the contents of -// permissions(). -TEST_F(MediaGalleriesDialogTest, InitializeCheckboxes) { - MediaGalleriesDialogController::Entries attached_permissions; - attached_permissions.push_back( - MediaGalleriesDialogController::Entry(MakePrefInfoForTesting(1), true)); - attached_permissions.push_back( - MediaGalleriesDialogController::Entry(MakePrefInfoForTesting(2), false)); - EXPECT_CALL(*controller(), GetSectionEntries(0)). - WillRepeatedly(Return(attached_permissions)); - - // Initializing checkboxes should not cause them to be toggled. - EXPECT_CALL(*controller(), DidToggleEntry(_, _)). - Times(0); - - EXPECT_EQ(2U, [[GetOrCreateDialog()->checkbox_container_ subviews] count]); - - NSButton* checkbox1 = - [[GetOrCreateDialog()->checkbox_container_ subviews] objectAtIndex:0]; - EXPECT_EQ([checkbox1 state], NSOnState); - - NSButton* checkbox2 = - [[GetOrCreateDialog()->checkbox_container_ subviews] objectAtIndex:1]; - EXPECT_EQ([checkbox2 state], NSOffState); -} - -// Tests that toggling checkboxes updates the controller. -TEST_F(MediaGalleriesDialogTest, ToggleCheckboxes) { - MediaGalleriesDialogController::Entries attached_permissions; - attached_permissions.push_back( - MediaGalleriesDialogController::Entry(MakePrefInfoForTesting(1), true)); - EXPECT_CALL(*controller(), GetSectionEntries(0)). - WillRepeatedly(Return(attached_permissions)); - - EXPECT_EQ(1U, [[GetOrCreateDialog()->checkbox_container_ subviews] count]); - - NSButton* checkbox = - [[GetOrCreateDialog()->checkbox_container_ subviews] objectAtIndex:0]; - EXPECT_EQ([checkbox state], NSOnState); - - EXPECT_CALL(*controller(), DidToggleEntry(1, false)); - [checkbox performClick:nil]; - EXPECT_EQ([checkbox state], NSOffState); - - EXPECT_CALL(*controller(), DidToggleEntry(1, true)); - [checkbox performClick:nil]; - EXPECT_EQ([checkbox state], NSOnState); -} - -// Tests that UpdateGalleries will add a new checkbox, but only if it refers to -// a gallery that the dialog hasn't seen before. -TEST_F(MediaGalleriesDialogTest, UpdateAdds) { - MediaGalleriesDialogController::Entries attached_permissions; - EXPECT_CALL(*controller(), GetSectionEntries(0)). - WillRepeatedly(ReturnPointee(&attached_permissions)); - - EXPECT_EQ(0U, [[GetOrCreateDialog()->checkbox_container_ subviews] count]); - CGFloat old_container_height = - NSHeight([GetOrCreateDialog()->checkbox_container_ frame]); - - attached_permissions.push_back( - MediaGalleriesDialogController::Entry(MakePrefInfoForTesting(1), true)); - GetOrCreateDialog()->UpdateGalleries(); - EXPECT_EQ(1U, [[GetOrCreateDialog()->checkbox_container_ subviews] count]); - - // The checkbox container should be taller. - CGFloat new_container_height = - NSHeight([GetOrCreateDialog()->checkbox_container_ frame]); - EXPECT_GT(new_container_height, old_container_height); - old_container_height = new_container_height; - - attached_permissions.push_back( - MediaGalleriesDialogController::Entry(MakePrefInfoForTesting(2), true)); - GetOrCreateDialog()->UpdateGalleries(); - EXPECT_EQ(2U, [[GetOrCreateDialog()->checkbox_container_ subviews] count]); - - // The checkbox container should be taller. - new_container_height = - NSHeight([GetOrCreateDialog()->checkbox_container_ frame]); - EXPECT_GT(new_container_height, old_container_height); - old_container_height = new_container_height; - - attached_permissions[1].selected = false; - GetOrCreateDialog()->UpdateGalleries(); - EXPECT_EQ(2U, [[GetOrCreateDialog()->checkbox_container_ subviews] count]); - - // The checkbox container height should not have changed. - new_container_height = - NSHeight([GetOrCreateDialog()->checkbox_container_ frame]); - EXPECT_EQ(new_container_height, old_container_height); -} - -TEST_F(MediaGalleriesDialogTest, ForgetDeletes) { - MediaGalleriesDialogController::Entries attached_permissions; - EXPECT_CALL(*controller(), GetSectionEntries(0)). - WillRepeatedly(ReturnPointee(&attached_permissions)); - - GetOrCreateDialog(); - - // Add a couple of galleries. - attached_permissions.push_back( - MediaGalleriesDialogController::Entry(MakePrefInfoForTesting(1), true)); - GetOrCreateDialog()->UpdateGalleries(); - attached_permissions.push_back( - MediaGalleriesDialogController::Entry(MakePrefInfoForTesting(2), true)); - GetOrCreateDialog()->UpdateGalleries(); - EXPECT_EQ(2U, [[GetOrCreateDialog()->checkbox_container_ subviews] count]); - CGFloat old_container_height = - NSHeight([GetOrCreateDialog()->checkbox_container_ frame]); - - // Remove a gallery. - attached_permissions.erase(attached_permissions.begin()); - GetOrCreateDialog()->UpdateGalleries(); - EXPECT_EQ(1U, [[GetOrCreateDialog()->checkbox_container_ subviews] count]); - - // The checkbox container should be shorter. - CGFloat new_container_height = - NSHeight([GetOrCreateDialog()->checkbox_container_ frame]); - EXPECT_LT(new_container_height, old_container_height); -}
diff --git a/chrome/browser/ui/cocoa/extensions/media_gallery_list_entry_view.h b/chrome/browser/ui/cocoa/extensions/media_gallery_list_entry_view.h deleted file mode 100644 index 6ab7b77..0000000 --- a/chrome/browser/ui/cocoa/extensions/media_gallery_list_entry_view.h +++ /dev/null
@@ -1,44 +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_UI_COCOA_EXTENSIONS_MEDIA_GALLERY_LIST_ENTRY_VIEW_H_ -#define CHROME_BROWSER_UI_COCOA_EXTENSIONS_MEDIA_GALLERY_LIST_ENTRY_VIEW_H_ - -#import <Cocoa/Cocoa.h> - -#import "base/mac/scoped_nsobject.h" -#include "chrome/browser/media_galleries/media_galleries_preferences.h" -#import "ui/base/models/menu_model.h" - -@class MediaGalleryButton; - -class MediaGalleryListEntryController { - public: - virtual void OnCheckboxToggled(MediaGalleryPrefId pref_id, bool checked) {} - virtual void OnFolderViewerClicked(MediaGalleryPrefId pref_id) {} - virtual ui::MenuModel* GetContextMenu(MediaGalleryPrefId pref_id); - - protected: - virtual ~MediaGalleryListEntryController() {} -}; - -@interface MediaGalleryListEntry : NSView { - @private - MediaGalleryListEntryController* controller_; // |controller_| owns |this|. - MediaGalleryPrefId prefId_; - - base::scoped_nsobject<MediaGalleryButton> checkbox_; - base::scoped_nsobject<NSTextField> details_; -} - -// Does size to fit if frameRect is empty. -- (id)initWithFrame:(NSRect)frameRect - controller:(MediaGalleryListEntryController*)controller_ - prefInfo:(const MediaGalleryPrefInfo&)prefInfo; - -- (void)setState:(bool)selected; - -@end - -#endif // CHROME_BROWSER_UI_COCOA_EXTENSIONS_MEDIA_GALLERY_LIST_ENTRY_VIEW_H_
diff --git a/chrome/browser/ui/cocoa/extensions/media_gallery_list_entry_view.mm b/chrome/browser/ui/cocoa/extensions/media_gallery_list_entry_view.mm deleted file mode 100644 index 4f6edc7..0000000 --- a/chrome/browser/ui/cocoa/extensions/media_gallery_list_entry_view.mm +++ /dev/null
@@ -1,196 +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. - -#import "chrome/browser/ui/cocoa/extensions/media_gallery_list_entry_view.h" - -#include "base/strings/sys_string_conversions.h" -#include "chrome/browser/ui/cocoa/chrome_style.h" -#import "chrome/browser/ui/cocoa/constrained_window/constrained_window_control_utils.h" -#import "ui/base/cocoa/menu_controller.h" -#include "ui/base/resource/resource_bundle.h" - -const CGFloat kGalleryEntryCheckboxMargin = 10; - -ui::MenuModel* MediaGalleryListEntryController::GetContextMenu( - MediaGalleryPrefId pref_id) { - return NULL; -} - -@interface MediaGalleryListEntry () -- (void)onCheckboxToggled:(MediaGalleryButton*)sender; -- (void)onFolderViewerClicked:(id)sender; -- (ui::MenuModel*)getContextMenu; -- (void)layoutSubViews; -@end - - -@interface MediaGalleryButton : NSButton { - @private - MediaGalleryListEntry* controller_; // |controller_| owns |self|. - base::scoped_nsobject<MenuControllerCocoa> menuController_; -} - -- (id)initWithFrame:(NSRect)frameRect - controller:(MediaGalleryListEntry*)controller; -- (NSMenu*)menuForEvent:(NSEvent*)theEvent; - -@end - -@implementation MediaGalleryButton - -- (id)initWithFrame:(NSRect)frameRect - controller:(MediaGalleryListEntry*)controller { - if ((self = [super initWithFrame:frameRect])) { - controller_ = controller; - } - return self; -} - -- (NSMenu*)menuForEvent:(NSEvent*)theEvent { - menuController_.reset([[MenuControllerCocoa alloc] - initWithModel:[controller_ getContextMenu] - useWithPopUpButtonCell:NO]); - return [menuController_ menu]; -} - -@end - - -@implementation MediaGalleryListEntry - -- (id)initWithFrame:(NSRect)frameRect - controller:(MediaGalleryListEntryController*)controller - prefInfo:(const MediaGalleryPrefInfo&)prefInfo { - if ((self = [super initWithFrame:frameRect])) { - controller_ = controller; - prefId_ = prefInfo.pref_id; - - NSString* nsTooltip = - base::SysUTF16ToNSString(prefInfo.GetGalleryTooltip()); - - // Set a auto resize mask so that -resizeWithOldSuperviewSize: is called. - // It is overridden so the particular mask doesn't matter. - [self setAutoresizingMask:NSViewWidthSizable]; - checkbox_.reset( - [[MediaGalleryButton alloc] initWithFrame:NSZeroRect - controller:self]); - [[checkbox_ cell] setLineBreakMode:NSLineBreakByTruncatingMiddle]; - [checkbox_ setButtonType:NSSwitchButton]; - [checkbox_ setTarget:self]; - [checkbox_ setAction:@selector(onCheckboxToggled:)]; - - [checkbox_ setTitle: - base::SysUTF16ToNSString(prefInfo.GetGalleryDisplayName())]; - [checkbox_ setToolTip:nsTooltip]; - [self addSubview:checkbox_]; - - // Additional details text. - base::string16 subscript = prefInfo.GetGalleryAdditionalDetails(); - if (!subscript.empty()) { - details_.reset([[NSTextField alloc] initWithFrame:NSZeroRect]); - [[details_ cell] setLineBreakMode:NSLineBreakByTruncatingHead]; - [details_ setEditable:NO]; - [details_ setSelectable:NO]; - [details_ setBezeled:NO]; - [details_ setAttributedStringValue: - constrained_window::GetAttributedLabelString( - base::SysUTF16ToNSString(subscript), - chrome_style::kTextFontStyle, - NSNaturalTextAlignment, - NSLineBreakByClipping - )]; - [details_ setTextColor:[NSColor disabledControlTextColor]]; - [self addSubview:details_]; - } - - [self layoutSubViews]; - } - return self; -} - -- (void)setFrameSize:(NSSize)frameSize { - [super setFrameSize:frameSize]; - [self layoutSubViews]; -} - -- (void)resizeWithOldSuperviewSize:(NSSize)oldBoundsSize { - NSRect frame = [self frame]; - frame.size.width = NSWidth([[self superview] frame]); - [self setFrameSize:frame.size]; -} - -- (void)setState:(bool)selected { - [checkbox_ setState:selected ? NSOnState : NSOffState]; -} - -- (void)onCheckboxToggled:(MediaGalleryButton*)sender { - controller_->OnCheckboxToggled(prefId_, [sender state] == NSOnState); -} - -- (void)onFolderViewerClicked:(id)sender { - controller_->OnFolderViewerClicked(prefId_); -} - -- (ui::MenuModel*)getContextMenu { - return controller_->GetContextMenu(prefId_); -} - -- (void)layoutSubViews { - NSRect bounds = [self bounds]; - // If we have an empty frame, we should auto size, so start with really big - // bounds and then set it to the real size of the contents later. - if (NSIsEmptyRect([self frame])) - bounds.size = NSMakeSize(10000, 10000); - - [checkbox_ sizeToFit]; - [details_ sizeToFit]; - - // Auto size everything and lay it out horizontally. - CGFloat xPos = kGalleryEntryCheckboxMargin; - for (NSView* view in [self subviews]) { - NSRect viewFrame = [view frame]; - viewFrame.origin.x = xPos; - viewFrame.size.height = std::min(NSHeight(bounds), NSHeight(viewFrame)); - [view setFrame:viewFrame]; - xPos = NSMaxX([view frame]) + kGalleryEntryCheckboxMargin; - } - - // Size the views. If all the elements don't naturally fit, the checkbox - // should get squished and will elide in the middle. However, it shouldn't - // squish too much so it gets at least half of the max width and the details - // text should elide as well in that case. - if (xPos > NSWidth(bounds)) { - CGFloat maxRHSContent = NSWidth(bounds) / 2 - kGalleryEntryCheckboxMargin; - NSRect detailsFrame = [details_ frame]; - NSRect checkboxFrame = [checkbox_ frame]; - - if (NSMaxX(detailsFrame) - NSMaxX(checkboxFrame) > maxRHSContent) { - detailsFrame.size.width = std::max( - maxRHSContent - (NSMinX(detailsFrame) - NSMaxX(checkboxFrame)), - NSWidth(bounds) - kGalleryEntryCheckboxMargin - NSMinX(detailsFrame)); - [details_ setFrameSize:detailsFrame.size]; - xPos = NSMaxX(detailsFrame) + kGalleryEntryCheckboxMargin; - } - CGFloat overflow = xPos - NSWidth(bounds); - if (overflow > 0) { - checkboxFrame.size.width -= overflow; - [checkbox_ setFrameSize:checkboxFrame.size]; - if (details_.get()) { - detailsFrame.origin.x -= overflow; - [details_ setFrameOrigin:detailsFrame.origin]; - } - } - } - - if (NSIsEmptyRect([self frame])) { - NSRect frame = NSMakeRect(0, 0, 1, 1); - for (NSView* view in [self subviews]) { - frame = NSUnionRect(frame, [view frame]); - } - frame.size.width += kGalleryEntryCheckboxMargin; - [super setFrameSize:frame.size]; - } -} - -@end
diff --git a/chrome/browser/ui/cocoa/info_bubble_view.h b/chrome/browser/ui/cocoa/info_bubble_view.h deleted file mode 100644 index 3787f29..0000000 --- a/chrome/browser/ui/cocoa/info_bubble_view.h +++ /dev/null
@@ -1,70 +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_UI_COCOA_INFO_BUBBLE_VIEW_H_ -#define CHROME_BROWSER_UI_COCOA_INFO_BUBBLE_VIEW_H_ - -#import <Cocoa/Cocoa.h> - -#include "base/mac/scoped_nsobject.h" - -namespace info_bubble { - -// These values are in view coordinates. -const CGFloat kBubbleArrowHeight = 8.0; -const CGFloat kBubbleArrowWidth = 15.0; -const CGFloat kBubbleCornerRadius = 2.0; -const CGFloat kBubbleArrowXOffset = kBubbleArrowWidth + kBubbleCornerRadius; - -// Constants that define where the bubble will have rounded corners. -enum CornerFlags { - kRoundedTopCorners = 1, - kRoundedBottomCorners = 1 << 1, - kRoundedAllCorners = kRoundedTopCorners | kRoundedBottomCorners, -}; - -enum BubbleArrowLocation { - kTopLeading, - kTopCenter, - kTopTrailing, - kNoArrow, -}; - -enum BubbleAlignment { - // The tip of the arrow points to the anchor point. - kAlignArrowToAnchor, - // The edge nearest to the arrow is lined up with the anchor point. - kAlignEdgeToAnchorEdge, - // Align the trailing edge (right in LTR, left in RTL) to the anchor point. - kAlignTrailingEdgeToAnchorEdge, - // Align the leading edge (left in LTR, right in RTL) to the anchor point. - kAlignLeadingEdgeToAnchorEdge, -}; - -} // namespace info_bubble - -// Content view for a bubble with an arrow showing arbitrary content. -// This is where nonrectangular drawing happens. -@interface InfoBubbleView : NSView { - @private - info_bubble::BubbleArrowLocation arrowLocation_; - info_bubble::BubbleAlignment alignment_; - info_bubble::CornerFlags cornerFlags_; - base::scoped_nsobject<NSColor> backgroundColor_; -} - -@property(assign, nonatomic) info_bubble::BubbleArrowLocation arrowLocation; -@property(assign, nonatomic) info_bubble::BubbleAlignment alignment; -@property(assign, nonatomic) info_bubble::CornerFlags cornerFlags; - -// Returns the point location in view coordinates of the tip of the arrow. -- (NSPoint)arrowTip; - -// Gets and sets the bubble's background color. -- (NSColor*)backgroundColor; -- (void)setBackgroundColor:(NSColor*)backgroundColor; - -@end - -#endif // CHROME_BROWSER_UI_COCOA_INFO_BUBBLE_VIEW_H_
diff --git a/chrome/browser/ui/cocoa/info_bubble_view.mm b/chrome/browser/ui/cocoa/info_bubble_view.mm deleted file mode 100644 index 0d3f23d2..0000000 --- a/chrome/browser/ui/cocoa/info_bubble_view.mm +++ /dev/null
@@ -1,147 +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. - -#import "chrome/browser/ui/cocoa/info_bubble_view.h" - -#include "base/logging.h" -#include "base/mac/foundation_util.h" -#import "chrome/browser/ui/cocoa/info_bubble_window.h" -#import "chrome/browser/ui/cocoa/l10n_util.h" -#import "third_party/google_toolbox_for_mac/src/AppKit/GTMNSBezierPath+RoundRect.h" - -@implementation InfoBubbleView - -@synthesize arrowLocation = arrowLocation_; -@synthesize alignment = alignment_; -@synthesize cornerFlags = cornerFlags_; - -- (id)initWithFrame:(NSRect)frameRect { - if ((self = [super initWithFrame:frameRect])) { - arrowLocation_ = info_bubble::kTopLeading; - alignment_ = info_bubble::kAlignArrowToAnchor; - cornerFlags_ = info_bubble::kRoundedAllCorners; - backgroundColor_.reset([[NSColor whiteColor] retain]); - } - return self; -} - -- (BOOL)performKeyEquivalent:(NSEvent *)event { - InfoBubbleWindow* info_bubble_window = - base::mac::ObjCCast<InfoBubbleWindow>([self window]); - if (info_bubble_window && [info_bubble_window isClosing]) { - // When a keyboard shortcut is pressed, the method that handles it is - // -[NSApplication _handleKeyEquivalent:], which calls the - // -performKeyEquivalent methods on all windows in the window list, whether - // they are open or closed, shown or hidden, active or dying. If a bubble - // window is closed but lingers in an autorelease pool, it might receive - // unexpected requests for key commands; see <http://crbug.com/574798> for - // an example. In such a case, make sure the key equivalent search stops - // here rather than proceeding down the view hierarchy and tickling stale - // pointers. - return NO; - } - return [super performKeyEquivalent:event]; -} - -- (void)drawRect:(NSRect)rect { - // Make room for the border to be seen. - NSRect bounds = [self bounds]; - if (arrowLocation_ != info_bubble::kNoArrow) { - bounds.size.height -= info_bubble::kBubbleArrowHeight; - } - rect.size.height -= info_bubble::kBubbleArrowHeight; - - float topRadius = cornerFlags_ & info_bubble::kRoundedTopCorners ? - info_bubble::kBubbleCornerRadius : 0; - float bottomRadius = cornerFlags_ & info_bubble::kRoundedBottomCorners ? - info_bubble::kBubbleCornerRadius : 0; - - NSBezierPath* bezier = - [NSBezierPath gtm_bezierPathWithRoundRect:bounds - topLeftCornerRadius:topRadius - topRightCornerRadius:topRadius - bottomLeftCornerRadius:bottomRadius - bottomRightCornerRadius:bottomRadius]; - - // Add the bubble arrow. - BOOL isRTL = cocoa_l10n_util::ShouldDoExperimentalRTLLayout(); - CGFloat dX = 0; - CGFloat leftOffset = info_bubble::kBubbleArrowXOffset; - CGFloat rightOffset = NSWidth(bounds) - info_bubble::kBubbleArrowXOffset - - info_bubble::kBubbleArrowWidth; - switch (arrowLocation_) { - case info_bubble::kTopLeading: - dX = isRTL ? rightOffset : leftOffset; - break; - case info_bubble::kTopTrailing: - dX = isRTL ? leftOffset : rightOffset; - break; - case info_bubble::kTopCenter: - dX = NSMidX(bounds) - info_bubble::kBubbleArrowWidth / 2.0; - break; - case info_bubble::kNoArrow: - break; - default: - NOTREACHED(); - break; - } - NSPoint arrowStart = NSMakePoint(NSMinX(bounds), NSMaxY(bounds)); - arrowStart.x += dX; - [bezier moveToPoint:NSMakePoint(arrowStart.x, arrowStart.y)]; - if (arrowLocation_ != info_bubble::kNoArrow) { - [bezier lineToPoint:NSMakePoint(arrowStart.x + - info_bubble::kBubbleArrowWidth / 2.0, - arrowStart.y + - info_bubble::kBubbleArrowHeight)]; - } - [bezier lineToPoint:NSMakePoint(arrowStart.x + info_bubble::kBubbleArrowWidth, - arrowStart.y)]; - [bezier closePath]; - [backgroundColor_ set]; - [bezier fill]; -} - -- (NSPoint)arrowTip { - NSRect bounds = [self bounds]; - CGFloat tipXOffset = - info_bubble::kBubbleArrowXOffset + info_bubble::kBubbleArrowWidth / 2.0; - CGFloat xOffset = 0.0; - BOOL isRTL = cocoa_l10n_util::ShouldDoExperimentalRTLLayout(); - CGFloat leftOffset = NSMaxX(bounds) - tipXOffset; - CGFloat rightOffset = NSMinX(bounds) + tipXOffset; - switch(arrowLocation_) { - case info_bubble::kTopTrailing: - xOffset = isRTL ? rightOffset : leftOffset; - break; - case info_bubble::kTopLeading: - xOffset = isRTL ? leftOffset : rightOffset; - break; - case info_bubble::kTopCenter: - xOffset = NSMidX(bounds); - break; - default: - NOTREACHED(); - break; - } - NSPoint arrowTip = NSMakePoint(xOffset, NSMaxY(bounds)); - return arrowTip; -} - -- (NSColor*)backgroundColor { - return backgroundColor_; -} - -- (void)setBackgroundColor:(NSColor*)backgroundColor { - backgroundColor_.reset([backgroundColor retain]); -} - -- (void)setArrowLocation:(info_bubble::BubbleArrowLocation)location { - if (arrowLocation_ == location) - return; - - arrowLocation_ = location; - [self setNeedsDisplayInRect:[self bounds]]; -} - -@end
diff --git a/chrome/browser/ui/cocoa/info_bubble_view_unittest.mm b/chrome/browser/ui/cocoa/info_bubble_view_unittest.mm deleted file mode 100644 index b9eb019..0000000 --- a/chrome/browser/ui/cocoa/info_bubble_view_unittest.mm +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright (c) 2011 The Chromium 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/mac/scoped_nsobject.h" -#import "chrome/browser/ui/cocoa/info_bubble_view.h" -#import "chrome/browser/ui/cocoa/test/cocoa_test_helper.h" - -namespace { - -class InfoBubbleViewTest : public CocoaTest { - public: - InfoBubbleViewTest() { - NSRect frame = NSMakeRect(0, 0, 100, 30); - base::scoped_nsobject<InfoBubbleView> view( - [[InfoBubbleView alloc] initWithFrame:frame]); - view_ = view.get(); - [[test_window() contentView] addSubview:view_]; - } - - InfoBubbleView* view_; -}; - -TEST_VIEW(InfoBubbleViewTest, view_); - -} // namespace
diff --git a/chrome/browser/ui/cocoa/info_bubble_window.h b/chrome/browser/ui/cocoa/info_bubble_window.h deleted file mode 100644 index 0b20763..0000000 --- a/chrome/browser/ui/cocoa/info_bubble_window.h +++ /dev/null
@@ -1,65 +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_UI_COCOA_INFO_BUBBLE_WINDOW_H_ -#define CHROME_BROWSER_UI_COCOA_INFO_BUBBLE_WINDOW_H_ - -#import <Cocoa/Cocoa.h> - -#include <memory> - -#import "chrome/browser/ui/cocoa/chrome_event_processing_window.h" - -class AppNotificationBridge; - -namespace info_bubble { - -enum AnimationMask { - kAnimateNone = 0, - kAnimateOrderIn = 1 << 1, - kAnimateOrderOut = 1 << 2, -}; -typedef NSUInteger AllowedAnimations; - -} // namespace info_bubble - -// A rounded window with an arrow used for example when you click on the STAR -// button or that pops up within our first-run UI. -@interface InfoBubbleWindow : ChromeEventProcessingWindow { - @private - // Is self in the process of closing. - BOOL closing_; - - // Specifies if window order in and order out animations are allowed. By - // default both types of animations are allowed. - info_bubble::AllowedAnimations allowedAnimations_; - - // If NO the window will never become key. - // Default YES. - BOOL infoBubbleCanBecomeKeyWindow_; - - // If NO the window will not share key state with its parent. Defaults to YES. - // Can be set both by external callers, but is also changed internally, in - // response to resignKeyWindow and becomeKeyWindow events. - BOOL allowShareParentKeyState_; - - // Bridge to proxy Chrome notifications to the window. - std::unique_ptr<AppNotificationBridge> notificationBridge_; -} - -@property(nonatomic) info_bubble::AllowedAnimations allowedAnimations; -@property(nonatomic) BOOL infoBubbleCanBecomeKeyWindow; -@property(nonatomic) BOOL allowShareParentKeyState; - -// Superclass override. -- (BOOL)canBecomeKeyWindow; - -// Returns YES if the window is in the process of closing. -// Can't use "windowWillClose" notification because that will be sent -// after the closing animation has completed. -- (BOOL)isClosing; - -@end - -#endif // CHROME_BROWSER_UI_COCOA_INFO_BUBBLE_WINDOW_H_
diff --git a/chrome/browser/ui/cocoa/info_bubble_window.mm b/chrome/browser/ui/cocoa/info_bubble_window.mm deleted file mode 100644 index c472054..0000000 --- a/chrome/browser/ui/cocoa/info_bubble_window.mm +++ /dev/null
@@ -1,266 +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. - -#import "chrome/browser/ui/cocoa/info_bubble_window.h" - -#include <Carbon/Carbon.h> - -#include "base/logging.h" -#import "base/mac/foundation_util.h" -#import "base/mac/scoped_nsobject.h" -#import "base/mac/sdk_forward_declarations.h" -#include "base/macros.h" -#include "chrome/browser/chrome_notification_types.h" -#import "chrome/browser/ui/cocoa/base_bubble_controller.h" -#include "chrome/browser/ui/cocoa/cocoa_util.h" -#include "content/public/browser/notification_observer.h" -#include "content/public/browser/notification_registrar.h" -#include "content/public/browser/notification_service.h" -#import "third_party/google_toolbox_for_mac/src/AppKit/GTMNSAnimation+Duration.h" - -namespace { -const CGFloat kOrderInSlideOffset = 10; -const NSTimeInterval kOrderInAnimationDuration = 0.075; -const NSTimeInterval kOrderOutAnimationDuration = 0.15; -} // namespace - -@interface InfoBubbleWindow (Private) -- (void)appIsTerminating; -- (void)finishCloseAfterAnimation; -@end - -// A helper class to proxy app notifications to the window. -class AppNotificationBridge : public content::NotificationObserver { - public: - explicit AppNotificationBridge(InfoBubbleWindow* owner) : owner_(owner) { - registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING, - content::NotificationService::AllSources()); - } - - // Overridden from content::NotificationObserver. - void Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) override { - switch (type) { - case chrome::NOTIFICATION_APP_TERMINATING: - [owner_ appIsTerminating]; - break; - default: - NOTREACHED() << "Unexpected notification"; - } - } - - private: - // The object we need to inform when we get a notification. Weak. Owns us. - InfoBubbleWindow* owner_; - - // Used for registering to receive notifications and automatic clean up. - content::NotificationRegistrar registrar_; - - DISALLOW_COPY_AND_ASSIGN(AppNotificationBridge); -}; - -// A delegate object for watching the alphaValue animation on InfoBubbleWindows. -// An InfoBubbleWindow instance cannot be the delegate for its own animation -// because CAAnimations retain their delegates, and since the InfoBubbleWindow -// retains its animations a retain loop would be formed. -@interface InfoBubbleWindowCloser : NSObject <CAAnimationDelegate> { - @private - InfoBubbleWindow* window_; // Weak. Window to close. -} -- (id)initWithWindow:(InfoBubbleWindow*)window; -@end - -@implementation InfoBubbleWindowCloser - -- (id)initWithWindow:(InfoBubbleWindow*)window { - if ((self = [super init])) { - window_ = window; - } - return self; -} - -- (void)animationDidStart:(CAAnimation*)theAnimation { - // CAAnimationDelegate method added on OSX 10.12. -} - -// Callback for the alpha animation. Closes window_ if appropriate. -- (void)animationDidStop:(CAAnimation*)anim finished:(BOOL)flag { - // When alpha reaches zero, close window_. - if ([window_ alphaValue] == 0.0) { - [window_ finishCloseAfterAnimation]; - } -} - -@end - - -@implementation InfoBubbleWindow - -@synthesize allowedAnimations = allowedAnimations_; -@synthesize infoBubbleCanBecomeKeyWindow = infoBubbleCanBecomeKeyWindow_; -@synthesize allowShareParentKeyState = allowShareParentKeyState_; - -- (id)initWithContentRect:(NSRect)contentRect - styleMask:(NSUInteger)aStyle - backing:(NSBackingStoreType)bufferingType - defer:(BOOL)flag { - if ((self = [super initWithContentRect:contentRect - styleMask:NSBorderlessWindowMask - backing:bufferingType - defer:flag])) { - [self setBackgroundColor:[NSColor clearColor]]; - [self setExcludedFromWindowsMenu:YES]; - [self setAllowShareParentKeyState:YES]; - [self setOpaque:NO]; - [self setHasShadow:YES]; - infoBubbleCanBecomeKeyWindow_ = YES; - allowedAnimations_ = info_bubble::kAnimateOrderIn | - info_bubble::kAnimateOrderOut; - notificationBridge_.reset(new AppNotificationBridge(self)); - - // Start invisible. Will be made visible when ordered front. - [self setAlphaValue:0.0]; - - // Set up alphaValue animation so that self is delegate for the animation. - // Setting up the delegate is required so that the - // animationDidStop:finished: callback can be handled. - // Notice that only the alphaValue Animation is replaced in case - // superclasses set up animations. - CAAnimation* alphaAnimation = [CABasicAnimation animation]; - base::scoped_nsobject<InfoBubbleWindowCloser> delegate( - [[InfoBubbleWindowCloser alloc] initWithWindow:self]); - [alphaAnimation setDelegate:delegate]; - NSMutableDictionary* animations = - [NSMutableDictionary dictionaryWithDictionary:[self animations]]; - [animations setObject:alphaAnimation forKey:@"alphaValue"]; - [self setAnimations:animations]; - } - return self; -} - -- (BOOL)performKeyEquivalent:(NSEvent*)event { - if (([event keyCode] == kVK_Escape) || - (([event keyCode] == kVK_ANSI_Period) && - (([event modifierFlags] & NSCommandKeyMask) != 0))) { - BaseBubbleController* bubbleController = - base::mac::ObjCCastStrict<BaseBubbleController>( - [self windowController]); - [bubbleController cancel:self]; - return YES; - } - return [super performKeyEquivalent:event]; -} - -// According to -// http://www.cocoabuilder.com/archive/message/cocoa/2006/6/19/165953, -// NSBorderlessWindowMask windows cannot become key or main. In this -// case, this is not necessarily a desired behavior. As an example, the -// bubble could have buttons. -- (BOOL)canBecomeKeyWindow { - return infoBubbleCanBecomeKeyWindow_; -} - -// Lets the traffic light buttons on the browser window keep their "active" -// state while an info bubble is open. Only has an effect on 10.7. -- (BOOL)_sharesParentKeyState { - return allowShareParentKeyState_; -} - -- (void)close { - // Block the window from receiving events while it fades out. - closing_ = YES; - - if ((allowedAnimations_ & info_bubble::kAnimateOrderOut) == 0) { - [self finishCloseAfterAnimation]; - } else { - // Apply animations to hide self. - [NSAnimationContext beginGrouping]; - [[NSAnimationContext currentContext] - gtm_setDuration:kOrderOutAnimationDuration - eventMask:NSLeftMouseUpMask]; - [[self animator] setAlphaValue:0.0]; - [NSAnimationContext endGrouping]; - } -} - -// If the app is terminating but the window is still fading out, cancel the -// animation and close the window to prevent it from leaking. -// See http://crbug.com/37717 -- (void)appIsTerminating { - if ((allowedAnimations_ & info_bubble::kAnimateOrderOut) == 0) - return; // The close has already happened with no Core Animation. - - // Cancel the current animation so that it closes immediately, triggering - // |finishCloseAfterAnimation|. - [NSAnimationContext beginGrouping]; - [[NSAnimationContext currentContext] - setDuration:cocoa_util::kMinimumTimeInterval]; - [[self animator] setAlphaValue:0.0]; - [NSAnimationContext endGrouping]; -} - -// Called by InfoBubbleWindowCloser when the window is to be really closed -// after the fading animation is complete. -- (void)finishCloseAfterAnimation { - if (closing_) { - [[self parentWindow] removeChildWindow:self]; - [super close]; - } -} - -// Adds animation for info bubbles being ordered to the front. -- (void)orderWindow:(NSWindowOrderingMode)orderingMode - relativeTo:(NSInteger)otherWindowNumber { - // According to the documentation '0' is the otherWindowNumber when the window - // is ordered front. - if (orderingMode == NSWindowAbove && otherWindowNumber == 0) { - // Order self appropriately assuming that its alpha is zero as set up - // in the designated initializer. - [super orderWindow:orderingMode relativeTo:otherWindowNumber]; - - // Set up frame so it can be adjust down by a few pixels. - NSRect frame = [self frame]; - NSPoint newOrigin = frame.origin; - newOrigin.y += kOrderInSlideOffset; - [self setFrameOrigin:newOrigin]; - - // Apply animations to show and move self. - [NSAnimationContext beginGrouping]; - // The star currently triggers on mouse down, not mouse up. - NSTimeInterval duration = - (allowedAnimations_ & info_bubble::kAnimateOrderIn) - ? kOrderInAnimationDuration - : cocoa_util::kMinimumTimeInterval; - [[NSAnimationContext currentContext] - gtm_setDuration:duration - eventMask:NSLeftMouseUpMask | NSLeftMouseDownMask]; - [[self animator] setAlphaValue:1.0]; - [[self animator] setFrame:frame display:YES]; - [NSAnimationContext endGrouping]; - } else { - [super orderWindow:orderingMode relativeTo:otherWindowNumber]; - } -} - -// If the window is currently animating a close, block all UI events to the -// window. -- (void)sendEvent:(NSEvent*)theEvent { - if (!closing_) - [super sendEvent:theEvent]; -} - -- (BOOL)isClosing { - return closing_; -} - -// Override -[NSWindow addChildWindow] to prevent ShareKit bugs propagating -// to the browser window. See http://crbug.com/475855. -- (void)addChildWindow:(NSWindow*)childWindow - ordered:(NSWindowOrderingMode)orderingMode { - [[self parentWindow] removeChildWindow:self]; - [super addChildWindow:childWindow ordered:orderingMode]; -} - -@end
diff --git a/chrome/browser/ui/cocoa/info_bubble_window_unittest.mm b/chrome/browser/ui/cocoa/info_bubble_window_unittest.mm deleted file mode 100644 index 4f83efd1..0000000 --- a/chrome/browser/ui/cocoa/info_bubble_window_unittest.mm +++ /dev/null
@@ -1,80 +0,0 @@ -// Copyright (c) 2011 The Chromium 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 <Carbon/Carbon.h> - -#include "base/debug/debugger.h" -#include "base/mac/scoped_nsobject.h" -#include "base/run_loop.h" -#import "chrome/browser/ui/cocoa/base_bubble_controller.h" -#include "chrome/browser/ui/cocoa/info_bubble_window.h" -#include "chrome/browser/ui/cocoa/test/cocoa_test_helper.h" -#include "chrome/browser/ui/cocoa/test/run_loop_testing.h" -#include "ui/events/test/cocoa_test_event_utils.h" - -// Mock BaseBubbleController to pick up -cancel:, but don't call the designated -// initializer in order to test just InfoBubbleWindow. -@interface InfoBubbleWindowController : BaseBubbleController -@end - -@implementation InfoBubbleWindowController -- (IBAction)cancel:(id)sender { - [self close]; -} -@end - -class InfoBubbleWindowTest : public CocoaTest { - public: - void SetUp() override { - CocoaTest::SetUp(); - window_.reset( - [[InfoBubbleWindow alloc] initWithContentRect:NSMakeRect(0, 0, 10, 10) - styleMask:NSBorderlessWindowMask - backing:NSBackingStoreBuffered - defer:NO]); - [window_ setAllowedAnimations:info_bubble::kAnimateNone]; - controller_.reset( - [[InfoBubbleWindowController alloc] initWithWindow:window_]); - } - - void TearDown() override { - // Both controller and window need to be closed & released before TearDown, - // or CocoaTest will consider the window still open and spinwait for it to - // close. - [controller_ close]; - chrome::testing::NSRunLoopRunAllPending(); - controller_.reset(); - window_.reset(); - - CocoaTest::TearDown(); - } - - base::scoped_nsobject<InfoBubbleWindow> window_; - base::scoped_nsobject<NSWindowController> controller_; -}; - -TEST_F(InfoBubbleWindowTest, Basics2) { - EXPECT_TRUE([window_ canBecomeKeyWindow]); - EXPECT_FALSE([window_ canBecomeMainWindow]); - - EXPECT_TRUE([window_ isExcludedFromWindowsMenu]); -} - -TEST_F(InfoBubbleWindowTest, EscapeCloses) { - [controller_ showWindow:nil]; - EXPECT_TRUE([window_ isVisible]); - - [window_ performKeyEquivalent:cocoa_test_event_utils::KeyEventWithKeyCode( - kVK_Escape, '\e', NSKeyDown, 0)]; - EXPECT_FALSE([window_ isVisible]); -} - -TEST_F(InfoBubbleWindowTest, CommandPeriodCloses) { - [controller_ showWindow:nil]; - EXPECT_TRUE([window_ isVisible]); - - [window_ performKeyEquivalent:cocoa_test_event_utils::KeyEventWithKeyCode( - kVK_ANSI_Period, '.', NSKeyDown, - NSCommandKeyMask)]; - EXPECT_FALSE([window_ isVisible]); -}
diff --git a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell_unittest.mm b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell_unittest.mm index 9afe74d..d4df5c94 100644 --- a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell_unittest.mm +++ b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell_unittest.mm
@@ -8,11 +8,8 @@ #include "base/strings/utf_string_conversions.h" #import "chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.h" #import "chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.h" -#import "chrome/browser/ui/cocoa/location_bar/keyword_hint_decoration.h" #import "chrome/browser/ui/cocoa/location_bar/location_bar_decoration.h" #import "chrome/browser/ui/cocoa/location_bar/page_info_bubble_decoration.h" -#import "chrome/browser/ui/cocoa/location_bar/selected_keyword_decoration.h" -#import "chrome/browser/ui/cocoa/location_bar/star_decoration.h" #import "chrome/browser/ui/cocoa/test/cocoa_test_helper.h" #import "chrome/browser/ui/cocoa/test/scoped_force_rtl_mac.h" #include "testing/gmock/include/gmock/gmock.h" @@ -97,13 +94,6 @@ // indicate that they should be omitted. const CGFloat kVeryWide = 1000.0; - SelectedKeywordDecoration selected_keyword_decoration; - selected_keyword_decoration.SetVisible(true); - selected_keyword_decoration.SetKeyword(base::ASCIIToUTF16("Google"), false); - [cell addLeadingDecoration:&selected_keyword_decoration]; - EXPECT_NE(selected_keyword_decoration.GetWidthForSpace(kVeryWide), - LocationBarDecoration::kOmittedWidth); - // TODO(shess): This really wants a |LocationBarViewMac|, but only a // few methods reference it, so this works well enough. But // something better would be nice. @@ -116,19 +106,6 @@ EXPECT_NE(page_info_bubble_decoration.GetWidthForSpace(kVeryWide), LocationBarDecoration::kOmittedWidth); - StarDecoration star_decoration(NULL); - star_decoration.SetVisible(true); - [cell addTrailingDecoration:&star_decoration]; - EXPECT_NE(star_decoration.GetWidthForSpace(kVeryWide), - LocationBarDecoration::kOmittedWidth); - - KeywordHintDecoration keyword_hint_decoration; - keyword_hint_decoration.SetVisible(true); - keyword_hint_decoration.SetKeyword(base::ASCIIToUTF16("google"), false); - [cell addTrailingDecoration:&keyword_hint_decoration]; - EXPECT_NE(keyword_hint_decoration.GetWidthForSpace(kVeryWide), - LocationBarDecoration::kOmittedWidth); - // Make sure we're actually calling |DrawInFrame()|. StrictMock<MockDecoration> mock_decoration; mock_decoration.SetVisible(true);
diff --git a/chrome/browser/ui/cocoa/location_bar/bubble_decoration.h b/chrome/browser/ui/cocoa/location_bar/bubble_decoration.h index 66b2aaa..d92d810 100644 --- a/chrome/browser/ui/cocoa/location_bar/bubble_decoration.h +++ b/chrome/browser/ui/cocoa/location_bar/bubble_decoration.h
@@ -61,10 +61,6 @@ base::scoped_nsobject<NSMutableDictionary> attributes_; private: - friend class SelectedKeywordDecorationTest; - FRIEND_TEST_ALL_PREFIXES(SelectedKeywordDecorationTest, - UsesPartialKeywordIfNarrow); - // Contains any Retina-only baseline adjustment for |label_|. CGFloat retina_baseline_offset_;
diff --git a/chrome/browser/ui/cocoa/location_bar/content_setting_decoration.h b/chrome/browser/ui/cocoa/location_bar/content_setting_decoration.h deleted file mode 100644 index 9667da7..0000000 --- a/chrome/browser/ui/cocoa/location_bar/content_setting_decoration.h +++ /dev/null
@@ -1,87 +0,0 @@ -// Copyright (c) 2011 The Chromium 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_UI_COCOA_LOCATION_BAR_CONTENT_SETTING_DECORATION_H_ -#define CHROME_BROWSER_UI_COCOA_LOCATION_BAR_CONTENT_SETTING_DECORATION_H_ - -#include <memory> - -#include "base/macros.h" -#import "chrome/browser/ui/cocoa/location_bar/image_decoration.h" -#include "components/content_settings/core/common/content_settings_types.h" - -// ContentSettingDecoration is used to display the content settings -// images on the current page. For example, the decoration animates into and out -// of view when a page attempts to show a popup and the popup blocker is on. - -@class ContentSettingAnimationState; -@class ContentSettingBubbleController; -class ContentSettingDecorationTest; -class ContentSettingImageModel; -class LocationBarViewMac; -class Profile; - -namespace content { -class WebContents; -} - -class ContentSettingDecoration : public ImageDecoration { - public: - ContentSettingDecoration(std::unique_ptr<ContentSettingImageModel> model, - LocationBarViewMac* owner, - Profile* profile); - ~ContentSettingDecoration() override; - - // Updates the image and visibility state based on the supplied WebContents. - // Returns true if the decoration's visible state changed. - bool UpdateFromWebContents(content::WebContents* web_contents); - - // Returns if the content setting bubble is showing for this decoration. - bool IsShowingBubble() const; - - // Overridden from |LocationBarDecoration| - AcceptsPress AcceptsMousePress() override; - bool OnMousePressed(NSRect frame, NSPoint location) override; - NSString* GetToolTip() override; - CGFloat GetWidthForSpace(CGFloat width) override; - void DrawInFrame(NSRect frame, NSView* control_view) override; - NSPoint GetBubblePointInFrame(NSRect frame) override; - - // Called from internal animator. Only public because ObjC objects can't - // be friends. - virtual void AnimationTimerFired(); - - protected: - CGFloat DividerPadding() const override; - - private: - friend class ContentSettingDecorationTest; - - void SetToolTip(NSString* tooltip); - - // Returns an attributed string with the animated text. - base::scoped_nsobject<NSAttributedString> CreateAnimatedText(); - - // Measure the width of the animated text. - CGFloat MeasureTextWidth(); - - std::unique_ptr<ContentSettingImageModel> content_setting_image_model_; - - LocationBarViewMac* owner_; // weak - Profile* profile_; // weak - - base::scoped_nsobject<NSString> tooltip_; - - // Used when the decoration has animated text. - base::scoped_nsobject<ContentSettingAnimationState> animation_; - CGFloat text_width_; - base::scoped_nsobject<NSAttributedString> animated_text_; - - // The window of the content setting bubble. - base::scoped_nsobject<NSWindow> bubbleWindow_; - - DISALLOW_COPY_AND_ASSIGN(ContentSettingDecoration); -}; - -#endif // CHROME_BROWSER_UI_COCOA_LOCATION_BAR_CONTENT_SETTING_DECORATION_H_
diff --git a/chrome/browser/ui/cocoa/location_bar/content_setting_decoration.mm b/chrome/browser/ui/cocoa/location_bar/content_setting_decoration.mm deleted file mode 100644 index 1b1c140..0000000 --- a/chrome/browser/ui/cocoa/location_bar/content_setting_decoration.mm +++ /dev/null
@@ -1,431 +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. - -#import "chrome/browser/ui/cocoa/location_bar/content_setting_decoration.h" - -#include <algorithm> - -#include "base/strings/sys_string_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "chrome/browser/content_settings/tab_specific_content_settings.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h" -#include "chrome/browser/ui/browser_list.h" -#include "chrome/browser/ui/cocoa/browser_dialogs_views_mac.h" -#import "chrome/browser/ui/cocoa/l10n_util.h" -#include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h" -#import "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" -#import "chrome/browser/ui/cocoa/location_bar/star_decoration.h" -#import "chrome/browser/ui/cocoa/themed_window.h" -#include "chrome/browser/ui/content_settings/content_setting_bubble_model.h" -#include "chrome/browser/ui/content_settings/content_setting_image_model.h" -#include "components/prefs/pref_service.h" -#include "content/public/browser/web_contents.h" -#include "skia/ext/skia_utils_mac.h" -#include "ui/base/cocoa/appkit_utils.h" -#include "ui/base/cocoa/cocoa_base_utils.h" -#import "ui/base/cocoa/nsview_additions.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/gfx/color_palette.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/mac/coordinate_conversion.h" -#include "ui/gfx/scoped_ns_graphics_context_save_gstate_mac.h" - -using content::WebContents; - -namespace { - -// Duration of animation, 3 seconds. The ContentSettingAnimationState breaks -// this up into different states of varying lengths. -const NSTimeInterval kAnimationDuration = 3.0; - -// Interval of the animation timer, 60Hz. -const NSTimeInterval kAnimationInterval = 1.0 / 60.0; - -// The % of time it takes to open or close the animating text, ie at 0.2, the -// opening takes 20% of the whole animation and the closing takes 20%. The -// remainder of the animation is with the text at full width. -const double kInMotionInterval = 0.2; - -// Used to create a % complete of the "in motion" part of the animation, eg -// it should be 1.0 (100%) when the progress is 0.2. -const double kInMotionMultiplier = 1.0 / kInMotionInterval; - -// Padding for the animated text with respect to the image. -const CGFloat kTextMarginPadding = 4; -const CGFloat kIconMarginPadding = 4; -const CGFloat kBorderPadding = 3; - -// Padding between the divider and the decoration on the right. -const CGFloat kDividerPadding = 1; - -// Padding between the divider and the text. -const CGFloat kTextDividerPadding = 2; - -// Color of the vector graphic icons. Used when the location is not dark. -// SkColorSetARGB(0xCC, 0xFF, 0xFF 0xFF); -const SkColor kVectorIconColor = 0xCCFFFFFF; - -// Different states in which the animation can be. In |kOpening|, the text -// is getting larger. In |kOpen|, the text should be displayed at full size. -// In |kClosing|, the text is again getting smaller. The durations in which -// the animation remains in each state are internal to -// |ContentSettingAnimationState|. -enum AnimationState { - kNoAnimation, - kOpening, - kOpen, - kClosing -}; - -} // namespace - - -// An ObjC class that handles the multiple states of the text animation and -// bridges NSTimer calls back to the ContentSettingDecoration that owns it. -// Should be lazily instantiated to only exist when the decoration requires -// animation. -// NOTE: One could make this class more generic, but this class only exists -// because CoreAnimation cannot be used (there are no views to work with). -@interface ContentSettingAnimationState : NSObject { - @private - ContentSettingDecoration* owner_; // Weak, owns this. - double progress_; // Counter, [0..1], with aninmation progress. - NSTimer* timer_; // Animation timer. Owns this, owned by the run loop. -} - -// [0..1], the current progress of the animation. -animationState will return -// |kNoAnimation| when progress is <= 0 or >= 1. Useful when state is -// |kOpening| or |kClosing| as a multiplier for displaying width. Don't use -// to track state transitions, use -animationState instead. -@property (readonly, nonatomic) double progress; - -// Designated initializer. |owner| must not be nil. Animation timer will start -// as soon as the object is created. -- (id)initWithOwner:(ContentSettingDecoration*)owner; - -// Returns the current animation state based on how much time has elapsed. -- (AnimationState)animationState; - -// Call when |owner| is going away or the animation needs to be stopped. -// Ensures that any dangling references are cleared. Can be called multiple -// times. -- (void)stopAnimation; - -@end - -@implementation ContentSettingAnimationState - -@synthesize progress = progress_; - -- (id)initWithOwner:(ContentSettingDecoration*)owner { - self = [super init]; - if (self) { - owner_ = owner; - timer_ = [NSTimer scheduledTimerWithTimeInterval:kAnimationInterval - target:self - selector:@selector(timerFired:) - userInfo:nil - repeats:YES]; - } - return self; -} - -- (void)dealloc { - DCHECK(!timer_); - [super dealloc]; -} - -// Clear weak references and stop the timer. -- (void)stopAnimation { - owner_ = nil; - [timer_ invalidate]; - timer_ = nil; -} - -// Returns the current state based on how much time has elapsed. -- (AnimationState)animationState { - if (progress_ <= 0.0 || progress_ >= 1.0) - return kNoAnimation; - if (progress_ <= kInMotionInterval) - return kOpening; - if (progress_ >= 1.0 - kInMotionInterval) - return kClosing; - return kOpen; -} - -- (void)timerFired:(NSTimer*)timer { - // Increment animation progress, normalized to [0..1]. - progress_ += kAnimationInterval / kAnimationDuration; - progress_ = std::min(progress_, 1.0); - owner_->AnimationTimerFired(); - // Stop timer if it has reached the end of its life. - if (progress_ >= 1.0) - [self stopAnimation]; -} - -@end - -ContentSettingDecoration::ContentSettingDecoration( - std::unique_ptr<ContentSettingImageModel> model, - LocationBarViewMac* owner, - Profile* profile) - : content_setting_image_model_(std::move(model)), - owner_(owner), - profile_(profile), - text_width_(0.0) {} - -ContentSettingDecoration::~ContentSettingDecoration() { - // Just in case the timer is still holding onto the animation object, force - // cleanup so it can't get back to |this|. - [animation_ stopAnimation]; -} - -bool ContentSettingDecoration::UpdateFromWebContents( - WebContents* web_contents) { - bool was_visible = IsVisible(); - bool did_icon_change = - content_setting_image_model_->UpdateFromWebContentsAndCheckIfIconChanged( - web_contents); - SetVisible(content_setting_image_model_->is_visible()); - bool decoration_changed = was_visible != IsVisible() || did_icon_change; - if (IsVisible()) { - SkColor icon_color = - owner_->IsLocationBarDark() ? kVectorIconColor : gfx::kChromeIconGrey; - SetImage(content_setting_image_model_->GetIcon(icon_color).ToNSImage()); - - SetToolTip( - base::SysUTF16ToNSString(content_setting_image_model_->get_tooltip())); - - // Check if there is an animation and start it if it hasn't yet started. - bool has_animated_text = - content_setting_image_model_->explanatory_string_id(); - - // Check if the animation has already run. - if (has_animated_text && - content_setting_image_model_->ShouldRunAnimation(web_contents) && - !animation_) { - // Mark the animation as having been run. - content_setting_image_model_->SetAnimationHasRun(web_contents); - // Start animation, its timer will drive reflow. Note the text is - // cached so it is not allowed to change during the animation. - animation_.reset( - [[ContentSettingAnimationState alloc] initWithOwner:this]); - animated_text_ = CreateAnimatedText(); - text_width_ = MeasureTextWidth(); - } else if (!has_animated_text) { - // Decoration no longer has animation, stop it (ok to always do this). - [animation_ stopAnimation]; - animation_.reset(); - } - } else { - // Decoration no longer visible, stop/clear animation. - [animation_ stopAnimation]; - animation_.reset(nil); - } - return decoration_changed; -} - -bool ContentSettingDecoration::IsShowingBubble() const { - return bubbleWindow_ && [bubbleWindow_ isVisible]; -} - -CGFloat ContentSettingDecoration::MeasureTextWidth() { - return [animated_text_ size].width; -} - -base::scoped_nsobject<NSAttributedString> -ContentSettingDecoration::CreateAnimatedText() { - NSString* text = - l10n_util::GetNSString( - content_setting_image_model_->explanatory_string_id()); - base::scoped_nsobject<NSMutableParagraphStyle> style( - [[NSMutableParagraphStyle alloc] init]); - // Set line break mode to clip the text, otherwise drawInRect: won't draw a - // word if it doesn't fit in the bounding box. - [style setLineBreakMode:NSLineBreakByClipping]; - - SkColor text_color = owner_->IsLocationBarDark() ? kMaterialDarkModeTextColor - : gfx::kChromeIconGrey; - NSDictionary* attributes = @{ - NSFontAttributeName : GetFont(), - NSParagraphStyleAttributeName : style, - NSForegroundColorAttributeName : - skia::SkColorToCalibratedNSColor(text_color) - }; - - return base::scoped_nsobject<NSAttributedString>( - [[NSAttributedString alloc] initWithString:text attributes:attributes]); -} - -NSPoint ContentSettingDecoration::GetBubblePointInFrame(NSRect frame) { - // Compute the frame as if there is no animation pill in the Omnibox. Place - // the bubble where the icon would be without animation, so when the animation - // ends, the bubble is pointing in the right place. - CGFloat final_width = ImageDecoration::GetWidthForSpace(NSWidth(frame)); - NSSize image_size = NSMakeSize(final_width, NSHeight(frame)); - if (!cocoa_l10n_util::ShouldDoExperimentalRTLLayout()) - frame.origin.x += frame.size.width - image_size.width; - frame.size = image_size; - - // Position the same way as the bookmark star. - return StarDecoration::GetStarBubblePointInFrame(GetDrawRectInFrame(frame)); -} - -AcceptsPress ContentSettingDecoration::AcceptsMousePress() { - return AcceptsPress::WHEN_ACTIVATED; -} - -bool ContentSettingDecoration::OnMousePressed(NSRect frame, NSPoint location) { - // Get host. This should be shared on linux/win/osx medium-term. - Browser* browser = owner_->browser(); - WebContents* web_contents = owner_->GetWebContents(); - if (!web_contents) - return true; - - AutocompleteTextField* field = owner_->GetAutocompleteTextField(); - NSPoint anchor = [field bubblePointForDecoration:this]; - anchor = ui::ConvertPointFromWindowToScreen([field window], anchor); - - // Open bubble. - ContentSettingBubbleModel* model = - content_setting_image_model_->CreateBubbleModel( - browser->content_setting_bubble_model_delegate(), - web_contents, - profile_); - - // If the bubble is already opened, close it. Otherwise, open a new bubble. - if (bubbleWindow_ && [bubbleWindow_ isVisible]) { - [bubbleWindow_ close]; - bubbleWindow_.reset(); - return true; - } - - gfx::Point origin = gfx::ScreenPointFromNSPoint(anchor); - NSWindow* bubble = chrome::ContentSettingBubbleViewsBridge::Show( - [web_contents->GetTopLevelNativeWindow() contentView], model, - web_contents, origin, this); - bubbleWindow_.reset([bubble retain]); - - return true; -} - -CGFloat ContentSettingDecoration::DividerPadding() const { - return kDividerPadding; -} - -NSString* ContentSettingDecoration::GetToolTip() { - return tooltip_.get(); -} - -void ContentSettingDecoration::SetToolTip(NSString* tooltip) { - tooltip_.reset([tooltip retain]); -} - -// Override to handle the case where there is text to display during the -// animation. The width is based on the animator's progress. -CGFloat ContentSettingDecoration::GetWidthForSpace(CGFloat width) { - CGFloat preferred_width = ImageDecoration::GetWidthForSpace(width); - if (animation_.get()) { - AnimationState state = [animation_ animationState]; - if (state != kNoAnimation) { - CGFloat progress = [animation_ progress]; - // Add the margins, fixed for all animation states. - preferred_width += kIconMarginPadding + kTextMarginPadding; - - // Add the width of the text based on the state of the animation. - CGFloat text_width = text_width_ + kDividerPadding; - switch (state) { - case kOpening: - preferred_width += text_width * kInMotionMultiplier * progress; - break; - case kOpen: - preferred_width += text_width; - break; - case kClosing: - preferred_width += text_width * kInMotionMultiplier * (1 - progress); - break; - default: - // Do nothing. - break; - } - } - } - return preferred_width; -} - -void ContentSettingDecoration::DrawInFrame(NSRect frame, NSView* control_view) { - const BOOL is_rtl = cocoa_l10n_util::ShouldDoExperimentalRTLLayout(); - if ([animation_ animationState] != kNoAnimation) { - // Align to integral points so that drawing isn't blurry or jittery. - frame = NSIntegralRect(frame); - - NSRect background_rect = NSInsetRect(frame, 0.0, kBorderPadding); - // This code is almost identical to code that appears in BubbleDecoration. - // Unfortunately ContentSettingDecoration does not descend from - // BubbleDecoration. Even if we move the code to LocationBarDecoration (the - // common ancestor) the semantics here are slightly different: there's a - // general DrawBackgroundInFrame() method for LocationBarDecorations that - // draws the background and then calls DrawInFrame(), but for some reason - // this ContentSettingDecoration's DrawInFrame() also draws the background. - // In short, moving this code upstream to a common parent requires a non- - // trivial bit of refactoring. - // Draw the icon. - NSImage* icon = GetImage(); - NSRect icon_rect = background_rect; - if (icon) { - if (is_rtl) { - icon_rect.origin.x = - NSMaxX(background_rect) - kIconMarginPadding - [icon size].width; - } else { - icon_rect.origin.x += kIconMarginPadding; - } - icon_rect.size.width = [icon size].width; - ImageDecoration::DrawInFrame(icon_rect, control_view); - } - - NSRect remainder = frame; - if (is_rtl) { - // drawInRect doesn't take line sweep into account when drawing with - // NSLineBreakByClipping - // This causes the animation to anchor to the left and look like it's - // growing the bounds, as opposed to revealing the text. - // rdar://29576934 - // To compensate, draw the whole string with a negative offset and clip to - // the drawing area. - remainder.size.width = MeasureTextWidth(); - remainder.origin.x = - NSMinX(icon_rect) - kTextMarginPadding - NSWidth(remainder); - NSRect clip_rect = background_rect; - clip_rect.origin.x += kTextDividerPadding; - NSBezierPath* clip_path = [NSBezierPath bezierPathWithRect:clip_rect]; - [control_view lockFocus]; - [clip_path addClip]; - DrawAttributedString(animated_text_, remainder); - [control_view unlockFocus]; - } else { - remainder.origin.x = NSMaxX(icon_rect) + kTextMarginPadding; - remainder.size.width = - NSMaxX(background_rect) - NSMinX(remainder) - kTextDividerPadding; - DrawAttributedString(animated_text_, remainder); - } - - // Draw the divider if available. - if (state() == DecorationMouseState::NONE && !active()) { - DrawDivider(control_view, background_rect, 1.0); - } - } else { - // No animation, draw the image as normal. - ImageDecoration::DrawInFrame(frame, control_view); - } -} - -void ContentSettingDecoration::AnimationTimerFired() { - owner_->Layout(); - // Even after the animation completes, the |animator_| object should be kept - // alive to prevent the animation from re-appearing if the page opens - // additional popups later. The animator will be cleared when the decoration - // hides, indicating something has changed with the WebContents (probably - // navigation). -}
diff --git a/chrome/browser/ui/cocoa/location_bar/content_setting_decoration_browsertest.mm b/chrome/browser/ui/cocoa/location_bar/content_setting_decoration_browsertest.mm deleted file mode 100644 index 99f26ef8..0000000 --- a/chrome/browser/ui/cocoa/location_bar/content_setting_decoration_browsertest.mm +++ /dev/null
@@ -1,66 +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. - -#import "chrome/browser/ui/cocoa/location_bar/content_setting_decoration.h" - -#include "chrome/browser/ui/browser_window.h" -#import "chrome/browser/ui/cocoa/browser_window_controller.h" -#import "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" -#include "chrome/browser/ui/content_settings/content_setting_image_model.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "chrome/test/views/scoped_macviews_browser_mode.h" -#include "content/public/test/test_utils.h" - -class ContentSettingDecorationTest : public InProcessBrowserTest { - protected: - ContentSettingDecorationTest() : InProcessBrowserTest() {} - - void SetUpOnMainThread() override { - std::unique_ptr<ContentSettingImageModel> content_setting_image_model( - ContentSettingImageModel::CreateForContentType( - ContentSettingImageModel::ImageType::GEOLOCATION)); - BrowserWindowController* controller = [BrowserWindowController - browserWindowControllerForWindow:browser() - ->window() - ->GetNativeWindow()]; - - content_setting_decoration_.reset(new ContentSettingDecoration( - std::move(content_setting_image_model), [controller locationBarBridge], - browser()->profile())); - } - - // Returns the content settings bubble window anchored to - // |content_setting_decoration_|. - NSWindow* GetBubbleWindow() const { - return content_setting_decoration_->bubbleWindow_.get(); - } - - // Simulates a mouse press on the decoration. - void PressDecoration() { - content_setting_decoration_->OnMousePressed(NSZeroRect, NSZeroPoint); - } - - private: - std::unique_ptr<ContentSettingDecoration> content_setting_decoration_; - - test::ScopedMacViewsBrowserMode cocoa_browser_mode_{false}; - - DISALLOW_COPY_AND_ASSIGN(ContentSettingDecorationTest); -}; - -// Tests to check if pressing the decoration will open/close the content -// settings bubble. -IN_PROC_BROWSER_TEST_F(ContentSettingDecorationTest, DecorationPress) { - // Bubble should appear. - PressDecoration(); - EXPECT_TRUE(GetBubbleWindow()); - - // Bubble should be closed. - PressDecoration(); - EXPECT_FALSE(GetBubbleWindow()); - - // Bubble should reappear. - PressDecoration(); - EXPECT_TRUE(GetBubbleWindow()); -}
diff --git a/chrome/browser/ui/cocoa/location_bar/keyword_hint_decoration.h b/chrome/browser/ui/cocoa/location_bar/keyword_hint_decoration.h deleted file mode 100644 index a3be8df6..0000000 --- a/chrome/browser/ui/cocoa/location_bar/keyword_hint_decoration.h +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright (c) 2011 The Chromium 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_UI_COCOA_LOCATION_BAR_KEYWORD_HINT_DECORATION_H_ -#define CHROME_BROWSER_UI_COCOA_LOCATION_BAR_KEYWORD_HINT_DECORATION_H_ - -#include <string> - -#import "chrome/browser/ui/cocoa/location_bar/location_bar_decoration.h" - -#import "base/mac/scoped_nsobject.h" -#include "base/macros.h" -#include "base/strings/string16.h" - -// Draws the keyword hint, "Press [tab] to search <site>". - -class KeywordHintDecoration : public LocationBarDecoration { - public: - KeywordHintDecoration(); - ~KeywordHintDecoration() override; - - // Calculates the message to display and where to place the [tab] - // image. - void SetKeyword(const base::string16& keyword, bool is_extension_keyword); - - // Implement |LocationBarDecoration|. - void DrawInFrame(NSRect frame, NSView* control_view) override; - CGFloat GetWidthForSpace(CGFloat width) override; - - NSString* GetAccessibilityLabel() override; - bool IsAccessibilityIgnored() override; - - private: - // Fetch and cache the [tab] image. - NSImage* GetHintImage(); - - // Attributes for drawing the hint string, such as font and color. - base::scoped_nsobject<NSDictionary> attributes_; - - // Cache for the [tab] image. - base::scoped_nsobject<NSImage> hint_image_; - - // The text to display to the left and right of the hint image. - base::scoped_nsobject<NSString> hint_prefix_; - base::scoped_nsobject<NSString> hint_suffix_; - - // The accessibility text used to describe this decoration. - base::string16 accessibility_text_; - - DISALLOW_COPY_AND_ASSIGN(KeywordHintDecoration); -}; - -#endif // CHROME_BROWSER_UI_COCOA_LOCATION_BAR_KEYWORD_HINT_DECORATION_H_
diff --git a/chrome/browser/ui/cocoa/location_bar/keyword_hint_decoration.mm b/chrome/browser/ui/cocoa/location_bar/keyword_hint_decoration.mm deleted file mode 100644 index f2562b9..0000000 --- a/chrome/browser/ui/cocoa/location_bar/keyword_hint_decoration.mm +++ /dev/null
@@ -1,177 +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 <stddef.h> - -#include <cmath> - -#import "chrome/browser/ui/cocoa/location_bar/keyword_hint_decoration.h" - -#include "base/logging.h" -#include "base/strings/string_util.h" -#include "base/strings/sys_string_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "chrome/browser/ui/cocoa/l10n_util.h" -#include "chrome/grit/generated_resources.h" -#include "chrome/grit/theme_resources.h" -#include "skia/ext/skia_utils_mac.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" - -namespace { - -// How far to inset the hint image from sides. Lines baseline of text -// in image with baseline of prefix and suffix. -const CGFloat kHintImageYInset = 4.0; - -// Extra padding right and left of the image. -const CGFloat kHintImagePadding = 1.0; - -// Maxmimum of the available space to allow the hint to take over. -// Should leave enough so that the user has space to edit things. -const CGFloat kHintAvailableRatio = 2.0 / 3.0; - -// Extra padding at the right of the decoration. -const CGFloat kHintTrailingPadding = 5.0; - -// Helper to convert |s| to an |NSString|, trimming whitespace at -// ends. -NSString* TrimAndConvert(const base::string16& s) { - base::string16 output; - base::TrimWhitespace(s, base::TRIM_ALL, &output); - return base::SysUTF16ToNSString(output); -} - -} // namespace - -KeywordHintDecoration::KeywordHintDecoration() { - NSColor* text_color = [NSColor lightGrayColor]; - attributes_.reset([@{ NSFontAttributeName : GetFont(), - NSForegroundColorAttributeName : text_color - } retain]); -} - -KeywordHintDecoration::~KeywordHintDecoration() { -} - -NSImage* KeywordHintDecoration::GetHintImage() { - if (!hint_image_) { - hint_image_.reset(ui::ResourceBundle::GetSharedInstance() - .GetNativeImageNamed(IDR_OMNIBOX_KEYWORD_HINT_TAB) - .CopyNSImage()); - } - return hint_image_; -} - -void KeywordHintDecoration::SetKeyword(const base::string16& short_name, - bool is_extension_keyword) { - // KEYWORD_HINT is a message like "Press [tab] to search <site>". - // [tab] is a parameter to be replaced by an image. "<site>" is - // derived from |short_name|. - std::vector<size_t> content_param_offsets; - int message_id = is_extension_keyword ? - IDS_OMNIBOX_EXTENSION_KEYWORD_HINT : IDS_OMNIBOX_KEYWORD_HINT; - const base::string16 keyword_hint( - l10n_util::GetStringFUTF16(message_id, - base::string16(), short_name, - &content_param_offsets)); - accessibility_text_ = l10n_util::GetStringFUTF16( - message_id, base::UTF8ToUTF16("Tab"), short_name); - - // Should always be 2 offsets, see the comment in - // location_bar_view.cc after IDS_OMNIBOX_KEYWORD_HINT fetch. - DCHECK_EQ(content_param_offsets.size(), 2U); - - // Where to put the [tab] image. - const size_t split = content_param_offsets.front(); - - // Trim the spaces from the edges (there is space in the image) and - // convert to |NSString|. - hint_prefix_.reset([TrimAndConvert(keyword_hint.substr(0, split)) retain]); - hint_suffix_.reset([TrimAndConvert(keyword_hint.substr(split)) retain]); -} - -CGFloat KeywordHintDecoration::GetWidthForSpace(CGFloat width) { - NSImage* image = GetHintImage(); - const CGFloat image_width = image ? [image size].width : 0.0; - - // AFAICT, on Windows the choices are "everything" if it fits, then - // "image only" if it fits. - - // Entirely too small to fit, omit. - if (width < image_width) - return kOmittedWidth; - - // Show the full hint if it won't take up too much space. The image - // needs to be placed at a pixel boundary, round the text widths so - // that any partially-drawn pixels don't look too close (or too - // far). - CGFloat full_width = - std::floor(GetLabelSize(hint_prefix_, attributes_).width + 0.5) + - kHintImagePadding + image_width + kHintImagePadding + - std::floor(GetLabelSize(hint_suffix_, attributes_).width + 0.5) + - kHintTrailingPadding; - if (full_width <= width * kHintAvailableRatio) - return full_width; - - return image_width; -} - -NSString* KeywordHintDecoration::GetAccessibilityLabel() { - return base::SysUTF16ToNSString(accessibility_text_); -} - -bool KeywordHintDecoration::IsAccessibilityIgnored() { - return true; -} - -void KeywordHintDecoration::DrawInFrame(NSRect frame, NSView* control_view) { - NSImage* image = GetHintImage(); - const CGFloat image_width = image ? [image size].width : 0.0; - - const bool draw_full = NSWidth(frame) > image_width; - - BOOL is_rtl = cocoa_l10n_util::ShouldDoExperimentalRTLLayout(); - NSString* left_string = is_rtl ? hint_suffix_ : hint_prefix_; - NSString* right_string = is_rtl ? hint_prefix_ : hint_suffix_; - if (is_rtl) { - frame.origin.x += kHintTrailingPadding; - frame.size.width -= kHintTrailingPadding; - } - - if (draw_full) { - NSRect left_rect = frame; - const CGFloat left_width = GetLabelSize(left_string, attributes_).width; - left_rect.size.width = left_width; - DrawLabel(left_string, attributes_, left_rect); - // The image should be drawn at a pixel boundary, round the prefix - // so that partial pixels aren't oddly close (or distant). - frame.origin.x += std::floor(left_width + 0.5) + kHintImagePadding; - frame.size.width -= std::floor(left_width + 0.5) + kHintImagePadding; - } - - NSRect image_rect = NSInsetRect(frame, 0.0, kHintImageYInset); - image_rect.size = [image size]; - [image drawInRect:image_rect - fromRect:NSZeroRect // Entire image - operation:NSCompositeSourceOver - fraction:1.0 - respectFlipped:YES - hints:nil]; - frame.origin.x += NSWidth(image_rect); - frame.size.width -= NSWidth(image_rect); - - if (draw_full) { - NSRect right_rect = frame; - const CGFloat right_width = GetLabelSize(right_string, attributes_).width; - - // Draw the text kHintImagePadding away from [tab] icon so that - // equal amount of space is maintained on either side of the icon. - // This also ensures that suffix text is at the same distance - // from [tab] icon in different web pages. - right_rect.origin.x += kHintImagePadding; - DCHECK_GE(NSWidth(right_rect), right_width); - DrawLabel(right_string, attributes_, right_rect); - } -}
diff --git a/chrome/browser/ui/cocoa/location_bar/keyword_hint_decoration_unittest.mm b/chrome/browser/ui/cocoa/location_bar/keyword_hint_decoration_unittest.mm deleted file mode 100644 index 155343e..0000000 --- a/chrome/browser/ui/cocoa/location_bar/keyword_hint_decoration_unittest.mm +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright (c) 2010 The Chromium 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 <Cocoa/Cocoa.h> - -#import "chrome/browser/ui/cocoa/location_bar/keyword_hint_decoration.h" - -#include "base/strings/utf_string_conversions.h" -#import "chrome/browser/ui/cocoa/test/cocoa_test_helper.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace { - -class KeywordHintDecorationTest : public CocoaTest { - public: - KeywordHintDecorationTest() { - } - - KeywordHintDecoration decoration_; -}; - -TEST_F(KeywordHintDecorationTest, GetWidthForSpace) { - decoration_.SetVisible(true); - decoration_.SetKeyword(base::ASCIIToUTF16("google"), false); - - const CGFloat kVeryWide = 1000.0; - const CGFloat kFairlyWide = 100.0; // Estimate for full hint space. - const CGFloat kEditingSpace = 50.0; - - // Wider than the [tab] image when we have lots of space. - EXPECT_NE(decoration_.GetWidthForSpace(kVeryWide), - LocationBarDecoration::kOmittedWidth); - EXPECT_GE(decoration_.GetWidthForSpace(kVeryWide), kFairlyWide); - - // When there's not enough space for the text, trims to something - // narrower. - const CGFloat full_width = decoration_.GetWidthForSpace(kVeryWide); - const CGFloat not_wide_enough = full_width - 10.0; - EXPECT_NE(decoration_.GetWidthForSpace(not_wide_enough), - LocationBarDecoration::kOmittedWidth); - EXPECT_LT(decoration_.GetWidthForSpace(not_wide_enough), full_width); - - // Even trims when there's enough space for everything, but it would - // eat "too much". - EXPECT_NE(decoration_.GetWidthForSpace(full_width + kEditingSpace), - LocationBarDecoration::kOmittedWidth); - EXPECT_LT(decoration_.GetWidthForSpace(full_width + kEditingSpace), - full_width); - - // Omitted when not wide enough to fit even the image. - const CGFloat image_width = decoration_.GetWidthForSpace(not_wide_enough); - EXPECT_EQ(decoration_.GetWidthForSpace(image_width - 1.0), - LocationBarDecoration::kOmittedWidth); -} - -} // namespace
diff --git a/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h b/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h index 953483b..1ed33b2 100644 --- a/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h +++ b/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h
@@ -24,15 +24,8 @@ @class AutocompleteTextField; class CommandUpdater; -class ContentSettingDecoration; -class KeywordHintDecoration; class LocationBarDecoration; -class ManagePasswordsDecoration; class Profile; -class SaveCreditCardDecoration; -class SelectedKeywordDecoration; -class StarDecoration; -class TranslateDecoration; class PageInfoBubbleDecoration; class ZoomDecoration; class ZoomDecorationTest; @@ -97,12 +90,6 @@ void SetEditable(bool editable); bool IsEditable(); - // Set the starred state of the bookmark star. - void SetStarred(bool starred); - - // Set whether or not the translate icon is lit. - void SetTranslateIconLit(bool on); - // Happens when the zoom changes for the active tab. |can_show_bubble| is // false when the change in zoom for the active tab wasn't an explicit user // action (e.g. switching tabs, creating a new tab, creating a new browser). @@ -110,17 +97,10 @@ // be obscured by other UI (app menu) or redundant (+/- from app menu). void ZoomChangedForActiveTab(bool can_show_bubble); - // Checks if the bookmark star should be enabled or not. - bool IsStarEnabled() const; - // Get the point in window coordinates in the |decoration| at which the // associate bubble aims. NSPoint GetBubblePointForDecoration(LocationBarDecoration* decoration) const; - // Get the point in window coordinates in the save credit card icon for the - // save credit card bubble to aim at. - NSPoint GetSaveCreditCardBubblePoint() const; - // Get the point in window coordinates for the page info bubble anchor. NSPoint GetPageInfoBubblePoint() const; @@ -187,20 +167,6 @@ return page_info_decoration_.get(); } - ManagePasswordsDecoration* manage_passwords_decoration() { - return manage_passwords_decoration_.get(); - } - - SaveCreditCardDecoration* save_credit_card_decoration() { - return save_credit_card_decoration_.get(); - } - - StarDecoration* star_decoration() const { return star_decoration_.get(); } - - TranslateDecoration* translate_decoration() const { - return translate_decoration_.get(); - } - ZoomDecoration* zoom_decoration() const { return zoom_decoration_.get(); } Browser* browser() const { return browser_; } @@ -229,10 +195,6 @@ // tab contents state. bool RefreshContentSettingsDecorations(); - // Updates the translate decoration in the omnibox with the current translate - // state. - void UpdateTranslateDecoration(); - // Updates the zoom decoration in the omnibox with the current zoom level. // Returns whether any updates were made. bool UpdateZoomDecoration(bool default_zoom_changed); @@ -258,36 +220,14 @@ AutocompleteTextField* field_; // owned by tab controller - // A decoration that shows the keyword-search bubble on the left. - std::unique_ptr<SelectedKeywordDecoration> selected_keyword_decoration_; - // A decoration that shows an icon to the left of the address. If applicable, // it'll also show information about the current page. std::unique_ptr<PageInfoBubbleDecoration> page_info_decoration_; - // Save credit card icon on the right side of the omnibox. - std::unique_ptr<SaveCreditCardDecoration> save_credit_card_decoration_; - - // Bookmark star right of page actions. - std::unique_ptr<StarDecoration> star_decoration_; - - // Translate icon at the end of the ominibox. - std::unique_ptr<TranslateDecoration> translate_decoration_; - // A zoom icon at the end of the omnibox, which shows at non-standard zoom // levels. std::unique_ptr<ZoomDecoration> zoom_decoration_; - // The content blocked decorations. - std::vector<std::unique_ptr<ContentSettingDecoration>> - content_setting_decorations_; - - // Keyword hint decoration displayed on the right-hand side. - std::unique_ptr<KeywordHintDecoration> keyword_hint_decoration_; - - // The right-hand-side button to manage passwords associated with a page. - std::unique_ptr<ManagePasswordsDecoration> manage_passwords_decoration_; - Browser* browser_; // Used to change the visibility of the star decoration.
diff --git a/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm b/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm index 27df49c..3753d3d 100644 --- a/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm +++ b/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.mm
@@ -25,18 +25,10 @@ #include "chrome/browser/ui/autofill/save_card_bubble_controller_impl.h" #include "chrome/browser/ui/browser_list.h" #import "chrome/browser/ui/cocoa/browser_window_controller.h" -#import "chrome/browser/ui/cocoa/info_bubble_view.h" #import "chrome/browser/ui/cocoa/l10n_util.h" #import "chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.h" #import "chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.h" -#import "chrome/browser/ui/cocoa/location_bar/content_setting_decoration.h" -#import "chrome/browser/ui/cocoa/location_bar/keyword_hint_decoration.h" -#import "chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.h" #import "chrome/browser/ui/cocoa/location_bar/page_info_bubble_decoration.h" -#import "chrome/browser/ui/cocoa/location_bar/save_credit_card_decoration.h" -#import "chrome/browser/ui/cocoa/location_bar/selected_keyword_decoration.h" -#import "chrome/browser/ui/cocoa/location_bar/star_decoration.h" -#import "chrome/browser/ui/cocoa/location_bar/translate_decoration.h" #import "chrome/browser/ui/cocoa/location_bar/zoom_decoration.h" #import "chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.h" #import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h" @@ -97,28 +89,12 @@ ChromeOmniboxEditController(command_updater), omnibox_view_(new OmniboxViewMac(this, profile, command_updater, field)), field_(field), - selected_keyword_decoration_(new SelectedKeywordDecoration()), page_info_decoration_(new PageInfoBubbleDecoration(this)), - save_credit_card_decoration_( - new SaveCreditCardDecoration(command_updater)), - star_decoration_(new StarDecoration(command_updater)), - translate_decoration_(new TranslateDecoration(command_updater)), zoom_decoration_(new ZoomDecoration(this)), - keyword_hint_decoration_(new KeywordHintDecoration()), - manage_passwords_decoration_( - new ManagePasswordsDecoration(command_updater, this)), browser_(browser), location_bar_visible_(true), is_width_available_for_security_verbose_(false), security_level_(security_state::NONE) { - std::vector<std::unique_ptr<ContentSettingImageModel>> models = - ContentSettingImageModel::GenerateContentSettingImageModels(); - for (auto& model : models) { - content_setting_decorations_.push_back( - std::make_unique<ContentSettingDecoration>(std::move(model), this, - profile)); - } - edit_bookmarks_enabled_.Init( bookmarks::prefs::kEditBookmarksEnabled, profile->GetPrefs(), base::Bind(&LocationBarViewMac::OnEditBookmarksEnabledChanged, @@ -178,36 +154,12 @@ } void LocationBarViewMac::UpdateContentSettingsIcons() { - if (RefreshContentSettingsDecorations()) - OnDecorationsChanged(); } void LocationBarViewMac::UpdateManagePasswordsIconAndBubble() { - WebContents* web_contents = GetWebContents(); - if (!web_contents) - return; - ManagePasswordsUIController::FromWebContents(web_contents) - ->UpdateIconAndBubbleState(manage_passwords_decoration_->icon()); - OnDecorationsChanged(); } void LocationBarViewMac::UpdateSaveCreditCardIcon() { - WebContents* web_contents = GetWebContents(); - if (!web_contents) - return; - - // |controller| may be nullptr due to lazy initialization. - autofill::SaveCardBubbleControllerImpl* controller = - autofill::SaveCardBubbleControllerImpl::FromWebContents(web_contents); - bool enabled = controller && controller->IsIconVisible(); - if (!command_updater()->UpdateCommandEnabled( - IDC_SAVE_CREDIT_CARD_FOR_PAGE, enabled)) { - enabled = enabled && command_updater()->IsCommandEnabled( - IDC_SAVE_CREDIT_CARD_FOR_PAGE); - } - save_credit_card_decoration_->SetIcon(IsLocationBarDark()); - save_credit_card_decoration_->SetVisible(enabled); - OnDecorationsChanged(); } void LocationBarViewMac::UpdateLocalCardMigrationIcon() { @@ -216,7 +168,6 @@ } void LocationBarViewMac::UpdateBookmarkStarVisibility() { - star_decoration_->SetVisible(IsStarEnabled()); } void LocationBarViewMac::UpdateLocationBarVisibility(bool visible, @@ -253,26 +204,15 @@ } bool LocationBarViewMac::GetBookmarkStarVisibility() { - DCHECK(star_decoration_.get()); - return star_decoration_->IsVisible(); + return false; } bool LocationBarViewMac::TestContentSettingImagePressed(size_t index) { - if (index >= content_setting_decorations_.size()) - return false; - - // TODO(tapted): Use OnAccessibilityViewAction() here. Currently it's broken. - ContentSettingDecoration* decoration = - content_setting_decorations_[index].get(); - AutocompleteTextFieldCell* cell = [field_ cell]; - NSRect frame = [cell frameForDecoration:decoration inFrame:[field_ bounds]]; - decoration->OnMousePressed(frame, NSZeroPoint); - return true; + return false; } bool LocationBarViewMac::IsContentSettingBubbleShowing(size_t index) { - return index < content_setting_decorations_.size() && - content_setting_decorations_[index]->IsShowingBubble(); + return false; } void LocationBarViewMac::SetEditable(bool editable) { @@ -286,20 +226,6 @@ return [field_ isEditable] ? true : false; } -void LocationBarViewMac::SetStarred(bool starred) { - if (star_decoration_->starred() == starred) - return; - - star_decoration_->SetStarred(starred, IsLocationBarDark()); - UpdateBookmarkStarVisibility(); - OnDecorationsChanged(); -} - -void LocationBarViewMac::SetTranslateIconLit(bool on) { - translate_decoration_->SetLit(on, IsLocationBarDark()); - OnDecorationsChanged(); -} - void LocationBarViewMac::ZoomChangedForActiveTab(bool can_show_bubble) { bool changed = UpdateZoomDecoration(/*default_zoom_changed=*/false); if (changed) @@ -309,26 +235,11 @@ zoom_decoration_->ShowBubble(YES); } -bool LocationBarViewMac::IsStarEnabled() const { - return browser_defaults::bookmarks_enabled && - [field_ isEditable] && - !GetToolbarModel()->input_in_progress() && - edit_bookmarks_enabled_.GetValue() && - !IsBookmarkStarHiddenByExtension(); -} - NSPoint LocationBarViewMac::GetBubblePointForDecoration( LocationBarDecoration* decoration) const { - if (decoration == star_decoration_.get()) - DCHECK(IsStarEnabled()); - return [field_ bubblePointForDecoration:decoration]; } -NSPoint LocationBarViewMac::GetSaveCreditCardBubblePoint() const { - return [field_ bubblePointForDecoration:save_credit_card_decoration_.get()]; -} - NSPoint LocationBarViewMac::GetPageInfoBubblePoint() const { return [field_ bubblePointForDecoration:page_info_decoration_.get()]; } @@ -354,23 +265,10 @@ // the constructor. I am still wrestling with how best to deal with // right-hand decorations, which are not a static set. [cell clearDecorations]; - [cell addLeadingDecoration:selected_keyword_decoration_.get()]; [cell addLeadingDecoration:page_info_decoration_.get()]; - [cell addTrailingDecoration:star_decoration_.get()]; - [cell addTrailingDecoration:translate_decoration_.get()]; [cell addTrailingDecoration:zoom_decoration_.get()]; - [cell addTrailingDecoration:save_credit_card_decoration_.get()]; - [cell addTrailingDecoration:manage_passwords_decoration_.get()]; - - for (const auto& decoration : content_setting_decorations_) { - [cell addTrailingDecoration:decoration.get()]; - } - - [cell addTrailingDecoration:keyword_hint_decoration_.get()]; // By default only the location icon is visible. - selected_keyword_decoration_->SetVisible(false); - keyword_hint_decoration_->SetVisible(false); page_info_decoration_->SetVisible(true); // Get the keyword to use for keyword-search and hinting. @@ -392,20 +290,7 @@ NSString* a11y_description = @""; if (!keyword.empty() && !is_keyword_hint) { - // Switch from location icon to keyword mode. - selected_keyword_decoration_->SetVisible(true); - page_info_decoration_->SetVisible(false); - selected_keyword_decoration_->SetKeyword(short_name, is_extension_keyword); - // Note: the first time through this code path the - // |selected_keyword_decoration_| has no image set because under Material - // Design we need to set its color, which we cannot do until we know the - // theme (by being installed in a browser window). - selected_keyword_decoration_->SetImage(GetKeywordImage(keyword)); - a11y_description = selected_keyword_decoration_->GetAccessibilityLabel(); } else if (!keyword.empty() && is_keyword_hint) { - keyword_hint_decoration_->SetKeyword(short_name, is_extension_keyword); - keyword_hint_decoration_->SetVisible(true); - a11y_description = keyword_hint_decoration_->GetAccessibilityLabel(); } else { UpdatePageInfoText(); } @@ -438,7 +323,6 @@ UpdateManagePasswordsIconAndBubble(); UpdateBookmarkStarVisibility(); UpdateSaveCreditCardIcon(); - UpdateTranslateDecoration(); UpdateZoomDecoration(/*default_zoom_changed=*/false); RefreshContentSettingsDecorations(); if (contents) { @@ -480,12 +364,6 @@ // Update the location-bar icon. UpdateLocationIcon(); - // Make sure we're displaying the correct star color for Incognito mode. If - // the window is in Incognito mode, switching between a theme and no theme - // can move the window in and out of dark mode. - star_decoration_->SetStarred(star_decoration_->starred(), - IsLocationBarDark()); - // Update the appearance of the text in the Omnibox. omnibox_view_->Update(); } @@ -634,32 +512,7 @@ } bool LocationBarViewMac::RefreshContentSettingsDecorations() { - const bool input_in_progress = GetToolbarModel()->input_in_progress(); - WebContents* web_contents = input_in_progress ? - NULL : browser_->tab_strip_model()->GetActiveWebContents(); - bool icons_updated = false; - for (const auto& decoration : content_setting_decorations_) - icons_updated |= decoration->UpdateFromWebContents(web_contents); - return icons_updated; -} - -void LocationBarViewMac::UpdateTranslateDecoration() { - if (!TranslateService::IsTranslateBubbleEnabled()) - return; - - WebContents* web_contents = GetWebContents(); - if (!web_contents) - return; - translate::LanguageState& language_state = - ChromeTranslateClient::FromWebContents(web_contents)->GetLanguageState(); - bool enabled = language_state.translate_enabled(); - if (!command_updater()->UpdateCommandEnabled(IDC_TRANSLATE_PAGE, enabled)) { - enabled = enabled && command_updater()->IsCommandEnabled( - IDC_TRANSLATE_PAGE); - } - translate_decoration_->SetVisible(enabled); - translate_decoration_->SetLit(language_state.IsPageTranslated(), - IsLocationBarDark()); + return false; } bool LocationBarViewMac::UpdateZoomDecoration(bool default_zoom_changed) { @@ -764,15 +617,8 @@ // TODO(ellyjones): page actions and keyword hints are not included right // now. Keyword hints have no useful tooltip (issue 752592), and page actions // are likewise. - decorations.push_back(selected_keyword_decoration_.get()); decorations.push_back(page_info_decoration_.get()); - decorations.push_back(save_credit_card_decoration_.get()); - decorations.push_back(star_decoration_.get()); - decorations.push_back(translate_decoration_.get()); decorations.push_back(zoom_decoration_.get()); - decorations.push_back(manage_passwords_decoration_.get()); - for (const auto& decoration : content_setting_decorations_) - decorations.push_back(decoration.get()); return decorations; }
diff --git a/chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.h b/chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.h deleted file mode 100644 index 6797e02..0000000 --- a/chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.h +++ /dev/null
@@ -1,86 +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_UI_COCOA_LOCATION_BAR_MANAGE_PASSWORDS_DECORATION_H_ -#define CHROME_BROWSER_UI_COCOA_LOCATION_BAR_MANAGE_PASSWORDS_DECORATION_H_ - -#import <Cocoa/Cocoa.h> - -#include <memory> - -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "chrome/browser/ui/cocoa/location_bar/image_decoration.h" -#include "chrome/browser/ui/passwords/manage_passwords_icon.h" - -class CommandUpdater; -class LocationBarViewMac; -class ManagePasswordsDecoration; - -// Cocoa implementation of ManagePasswordsIcon that delegates to -// ManagePasswordsDecoration. -class ManagePasswordsIconCocoa : public ManagePasswordsIcon { - public: - ManagePasswordsIconCocoa(ManagePasswordsDecoration* decoration); - virtual ~ManagePasswordsIconCocoa(); - void UpdateVisibleUI() override; - void OnChangingState() override; - - int tooltip_text_id() { return tooltip_text_id_; } - - private: - ManagePasswordsDecoration* decoration_; // weak, owns us -}; - -// Manage passwords icon on the right side of the field. This appears when -// password management is available on the current page. -class ManagePasswordsDecoration : public ImageDecoration { - public: - explicit ManagePasswordsDecoration(CommandUpdater* command_updater, - LocationBarViewMac* location_bar); - ~ManagePasswordsDecoration() override; - - // Implement |LocationBarDecoration| - AcceptsPress AcceptsMousePress() override; - bool OnMousePressed(NSRect frame, NSPoint location) override; - NSString* GetToolTip() override; - NSPoint GetBubblePointInFrame(NSRect frame) override; - - // Updates the decoration according to icon state changes. - void UpdateVisibleUI(); - - // Closes the bubble if it's currently displayed. - void HideBubble(); - - // Accessor for the platform-independent interface. - ManagePasswordsIconCocoa* icon() { return icon_.get(); } - - protected: - // Overridden from LocationBarDecoration: - const gfx::VectorIcon* GetMaterialVectorIcon() const override; - - private: - // Triggers a redraw after a state change. - void OnChange(); - - // Updates child view states. - void UpdateUIState(); - - // Whether a bubble is already showing. Handles both views and Cocoa - // bubbles. - bool IsBubbleShowing(); - - // Shows the manage passwords bubble. - CommandUpdater* command_updater_; // Weak, owned by Browser. - - // Displays all the decorations. - LocationBarViewMac* location_bar_; // Weak, owns us. - - // The platform-independent interface. - std::unique_ptr<ManagePasswordsIconCocoa> icon_; - - DISALLOW_COPY_AND_ASSIGN(ManagePasswordsDecoration); -}; - -#endif // CHROME_BROWSER_UI_COCOA_LOCATION_BAR_MANAGE_PASSWORDS_DECORATION_H_
diff --git a/chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.mm b/chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.mm deleted file mode 100644 index 0ede7323..0000000 --- a/chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.mm +++ /dev/null
@@ -1,114 +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. - -#import "chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.h" - -#include "chrome/app/chrome_command_ids.h" -#include "chrome/app/vector_icons/vector_icons.h" -#include "chrome/browser/command_updater.h" -#include "chrome/browser/ui/cocoa/browser_dialogs_views_mac.h" -#include "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" -#include "chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.h" -#import "chrome/browser/ui/cocoa/themed_window.h" -#include "chrome/browser/ui/views/passwords/password_bubble_view_base.h" -#include "ui/base/l10n/l10n_util_mac.h" -#include "ui/base/material_design/material_design_controller.h" -#include "ui/gfx/color_palette.h" -#include "ui/gfx/image/image_skia_util_mac.h" -#include "ui/gfx/paint_vector_icon.h" - -// ManagePasswordsIconCocoa - -ManagePasswordsIconCocoa::ManagePasswordsIconCocoa( - ManagePasswordsDecoration* decoration) - : decoration_(decoration) { -} - -ManagePasswordsIconCocoa::~ManagePasswordsIconCocoa() { -} - -void ManagePasswordsIconCocoa::UpdateVisibleUI() { - decoration_->UpdateVisibleUI(); -} - -void ManagePasswordsIconCocoa::OnChangingState() { - decoration_->HideBubble(); -} - -// ManagePasswordsDecoration - -ManagePasswordsDecoration::ManagePasswordsDecoration( - CommandUpdater* command_updater, - LocationBarViewMac* location_bar) - : command_updater_(command_updater), - location_bar_(location_bar), - icon_(new ManagePasswordsIconCocoa(this)) { - UpdateUIState(); -} - -ManagePasswordsDecoration::~ManagePasswordsDecoration() = default; - -NSPoint ManagePasswordsDecoration::GetBubblePointInFrame(NSRect frame) { - const NSRect draw_frame = GetDrawRectInFrame(frame); - return NSMakePoint(NSMidX(draw_frame), NSMaxY(draw_frame)); -} - -AcceptsPress ManagePasswordsDecoration::AcceptsMousePress() { - return AcceptsPress::ALWAYS; -} - -bool ManagePasswordsDecoration::OnMousePressed(NSRect frame, NSPoint location) { - if (IsBubbleShowing()) - HideBubble(); - else - command_updater_->ExecuteCommand(IDC_MANAGE_PASSWORDS_FOR_PAGE); - return true; -} - -NSString* ManagePasswordsDecoration::GetToolTip() { - return icon_->tooltip_text_id() - ? l10n_util::GetNSStringWithFixup(icon_->tooltip_text_id()) - : nil; -} - -void ManagePasswordsDecoration::OnChange() { - // |location_bar_| can be NULL in tests. - if (location_bar_) - location_bar_->OnDecorationsChanged(); -} - -void ManagePasswordsDecoration::UpdateUIState() { - if (icon_->state() == password_manager::ui::INACTIVE_STATE) { - SetVisible(false); - SetImage(nil); - return; - } - SetVisible(true); - // |location_bar_| can be NULL in tests. - bool location_bar_is_dark = location_bar_ && - [[location_bar_->GetAutocompleteTextField() window] - inIncognitoModeWithSystemTheme]; - SetImage(GetMaterialIcon(location_bar_is_dark)); -} - -void ManagePasswordsDecoration::UpdateVisibleUI() { - UpdateUIState(); - OnChange(); -} - -void ManagePasswordsDecoration::HideBubble() { - if (IsBubbleShowing()) - PasswordBubbleViewBase::CloseCurrentBubble(); -} - -const gfx::VectorIcon* ManagePasswordsDecoration::GetMaterialVectorIcon() - const { - // Note: update unit tests if this vector icon ever changes (it's hard-coded - // there). - return &kKeyIcon; -} - -bool ManagePasswordsDecoration::IsBubbleShowing() { - return PasswordBubbleViewBase::manage_password_bubble() != nullptr; -}
diff --git a/chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration_unittest.mm b/chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration_unittest.mm deleted file mode 100644 index 414f847..0000000 --- a/chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration_unittest.mm +++ /dev/null
@@ -1,127 +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. - -#import <Cocoa/Cocoa.h> - -#include "base/strings/utf_string_conversions.h" -#include "chrome/app/chrome_command_ids.h" -#include "chrome/app/vector_icons/vector_icons.h" -#include "chrome/browser/command_updater_delegate.h" -#include "chrome/browser/command_updater_impl.h" -#include "chrome/browser/ui/cocoa/location_bar/manage_passwords_decoration.h" -#include "chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.h" -#include "chrome/browser/ui/cocoa/test/cocoa_test_helper.h" -#include "chrome/grit/generated_resources.h" -#include "chrome/grit/theme_resources.h" -#include "components/password_manager/core/common/password_manager_ui.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "testing/gtest_mac.h" -#include "ui/base/l10n/l10n_util_mac.h" -#include "ui/base/material_design/material_design_controller.h" -#include "ui/gfx/color_palette.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/image/image_skia_util_mac.h" -#include "ui/gfx/paint_vector_icon.h" - -namespace { - -// A simple CommandUpdaterDelegate for testing whether the correct command -// was sent. -class TestCommandUpdaterDelegate : public CommandUpdaterDelegate { - public: - TestCommandUpdaterDelegate() : id_(0) {} - - void ExecuteCommandWithDisposition(int id, WindowOpenDisposition disposition) - override { - id_ = id; - } - - int id() { return id_; } - - private: - int id_; -}; - -bool ImagesEqual(NSImage* left, NSImage* right) { - if (!left || !right) - return left == right; - gfx::Image leftImage([left copy]); - gfx::Image rightImage([right copy]); - return leftImage.As1xPNGBytes()->Equals(rightImage.As1xPNGBytes()); -} - -} // namespace - -// Tests isolated functionality of the ManagedPasswordsDecoration. -class ManagePasswordsDecorationTest : public CocoaTest { - public: - ManagePasswordsDecorationTest() - : commandUpdater_(&commandDelegate_), - decoration_(&commandUpdater_, NULL) { - commandUpdater_.UpdateCommandEnabled(IDC_MANAGE_PASSWORDS_FOR_PAGE, true); - } - - protected: - TestCommandUpdaterDelegate* commandDelegate() { return &commandDelegate_; } - ManagePasswordsDecoration* decoration() { return &decoration_; } - - private: - TestCommandUpdaterDelegate commandDelegate_; - CommandUpdaterImpl commandUpdater_; - ManagePasswordsDecoration decoration_; -}; - -TEST_F(ManagePasswordsDecorationTest, ExecutesManagePasswordsCommandOnClick) { - EXPECT_EQ(AcceptsPress::ALWAYS, decoration()->AcceptsMousePress()); - EXPECT_TRUE(decoration()->OnMousePressed(NSRect(), NSPoint())); - EXPECT_EQ(IDC_MANAGE_PASSWORDS_FOR_PAGE, commandDelegate()->id()); -} - -// Parameter object for ManagePasswordsDecorationStateTests. -struct ManagePasswordsTestCase { - // Inputs - password_manager::ui::State state; - - // Outputs - bool visible; - int toolTip; -}; - -// Tests that setting different combinations of password_manager::ui::State -// and the Active property of the decoration result in the correct visibility, -// decoration icon, and tooltip. -class ManagePasswordsDecorationStateTest - : public ManagePasswordsDecorationTest, - public ::testing::WithParamInterface<ManagePasswordsTestCase> {}; - -TEST_P(ManagePasswordsDecorationStateTest, TestState) { - decoration()->icon()->SetState(GetParam().state); - EXPECT_EQ(GetParam().visible, decoration()->IsVisible()); - const int kIconSize = 16; - NSImage* expected_image = - GetParam().state == password_manager::ui::INACTIVE_STATE - ? nil - : NSImageFromImageSkia(gfx::CreateVectorIcon(kKeyIcon, kIconSize, - gfx::kChromeIconGrey)); - EXPECT_TRUE(ImagesEqual(expected_image, decoration()->GetImage())); - EXPECT_NSEQ(GetParam().toolTip - ? l10n_util::GetNSStringWithFixup(GetParam().toolTip) - : nil, - decoration()->GetToolTip()); -} - -ManagePasswordsTestCase testCases[] = { - {.state = password_manager::ui::INACTIVE_STATE, - .visible = false, - .toolTip = 0}, - {.state = password_manager::ui::MANAGE_STATE, - .visible = true, - .toolTip = IDS_PASSWORD_MANAGER_TOOLTIP_MANAGE}, - {.state = password_manager::ui::PENDING_PASSWORD_STATE, - .visible = true, - .toolTip = IDS_PASSWORD_MANAGER_TOOLTIP_SAVE}}; - -INSTANTIATE_TEST_CASE_P(, - ManagePasswordsDecorationStateTest, - ::testing::ValuesIn(testCases));
diff --git a/chrome/browser/ui/cocoa/location_bar/save_credit_card_decoration.h b/chrome/browser/ui/cocoa/location_bar/save_credit_card_decoration.h deleted file mode 100644 index c8a57cb..0000000 --- a/chrome/browser/ui/cocoa/location_bar/save_credit_card_decoration.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_COCOA_LOCATION_BAR_SAVE_CREDIT_CARD_DECORATION_H_ -#define CHROME_BROWSER_UI_COCOA_LOCATION_BAR_SAVE_CREDIT_CARD_DECORATION_H_ - -#import <Cocoa/Cocoa.h> - -#include "base/macros.h" -#include "chrome/browser/ui/cocoa/location_bar/image_decoration.h" - -class CommandUpdater; - -// Save credit card icon on the right side of the field. This appears when -// the save credit card bubble is available on the current page. This icon is -// never lit. -class SaveCreditCardDecoration : public ImageDecoration { - public: - explicit SaveCreditCardDecoration(CommandUpdater* command_updater); - ~SaveCreditCardDecoration() override; - - // Set up the SaveCreditCardDecoration's icon to match the darkness of the - // location bar. This happens once the location bar has been added to the - // window so that we know the theme. - void SetIcon(bool locationBarIsDark); - - // LocationBarDecoration implementation: - AcceptsPress AcceptsMousePress() override; - bool OnMousePressed(NSRect frame, NSPoint location) override; - NSString* GetToolTip() override; - NSPoint GetBubblePointInFrame(NSRect frame) override; - - private: - // For showing the save credit card bubble. - CommandUpdater* command_updater_; // Weak, owned by Browser. - - DISALLOW_COPY_AND_ASSIGN(SaveCreditCardDecoration); -}; - -#endif // CHROME_BROWSER_UI_COCOA_LOCATION_BAR_SAVE_CREDIT_CARD_DECORATION_H_
diff --git a/chrome/browser/ui/cocoa/location_bar/save_credit_card_decoration.mm b/chrome/browser/ui/cocoa/location_bar/save_credit_card_decoration.mm deleted file mode 100644 index 2df8540..0000000 --- a/chrome/browser/ui/cocoa/location_bar/save_credit_card_decoration.mm +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "chrome/browser/ui/cocoa/location_bar/save_credit_card_decoration.h" - -#include "chrome/app/chrome_command_ids.h" -#include "chrome/app/vector_icons/vector_icons.h" -#include "chrome/browser/command_updater.h" -#include "chrome/grit/generated_resources.h" -#include "ui/base/l10n/l10n_util_mac.h" -#include "ui/base/material_design/material_design_controller.h" -#include "ui/gfx/color_palette.h" -#include "ui/gfx/image/image_skia_util_mac.h" -#include "ui/gfx/paint_vector_icon.h" - -SaveCreditCardDecoration::SaveCreditCardDecoration( - CommandUpdater* command_updater) - : command_updater_(command_updater) { -} - -SaveCreditCardDecoration::~SaveCreditCardDecoration() {} - -void SaveCreditCardDecoration::SetIcon(bool locationBarIsDark) { - SkColor theColor = theColor = - locationBarIsDark ? SK_ColorWHITE : gfx::kChromeIconGrey; - - SetImage(NSImageFromImageSkia( - gfx::CreateVectorIcon(kCreditCardIcon, 16, theColor))); -} - -NSPoint SaveCreditCardDecoration::GetBubblePointInFrame(NSRect frame) { - const NSRect draw_frame = GetDrawRectInFrame(frame); - return NSMakePoint(NSMidX(draw_frame), NSMaxY(draw_frame)); -} - -AcceptsPress SaveCreditCardDecoration::AcceptsMousePress() { - return AcceptsPress::ALWAYS; -} - -bool SaveCreditCardDecoration::OnMousePressed(NSRect frame, NSPoint location) { - command_updater_->ExecuteCommand(IDC_SAVE_CREDIT_CARD_FOR_PAGE); - return true; -} - -NSString* SaveCreditCardDecoration::GetToolTip() { - return l10n_util::GetNSStringWithFixup(IDS_TOOLTIP_SAVE_CREDIT_CARD); -}
diff --git a/chrome/browser/ui/cocoa/location_bar/selected_keyword_decoration.h b/chrome/browser/ui/cocoa/location_bar/selected_keyword_decoration.h deleted file mode 100644 index d86b841..0000000 --- a/chrome/browser/ui/cocoa/location_bar/selected_keyword_decoration.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright (c) 2011 The Chromium 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_UI_COCOA_LOCATION_BAR_SELECTED_KEYWORD_DECORATION_H_ -#define CHROME_BROWSER_UI_COCOA_LOCATION_BAR_SELECTED_KEYWORD_DECORATION_H_ - -#include <string> - -#import <Cocoa/Cocoa.h> - -#include "base/gtest_prod_util.h" -#include "base/macros.h" -#include "base/strings/string16.h" -#include "chrome/browser/ui/cocoa/location_bar/bubble_decoration.h" - -class SelectedKeywordDecoration : public BubbleDecoration { - public: - SelectedKeywordDecoration(); - ~SelectedKeywordDecoration() override; - - // Return the color used to draw the SelectedKeywordDecoration in MD. - NSColor* GetBackgroundBorderColor() override; - - // Calculates appropriate full and partial label strings based on - // inputs. - void SetKeyword(const base::string16& keyword, bool is_extension_keyword); - - // Determines what combination of labels and image will best fit - // within |width|, makes those current for |BubbleDecoration|, and - // return the resulting width. - CGFloat GetWidthForSpace(CGFloat width) override; - - void SetImage(NSImage* image); - - NSString* GetAccessibilityLabel() override; - bool IsAccessibilityIgnored() override; - - private: - friend class SelectedKeywordDecorationTest; - FRIEND_TEST_ALL_PREFIXES(SelectedKeywordDecorationTest, - UsesPartialKeywordIfNarrow); - - base::scoped_nsobject<NSImage> search_image_; - base::scoped_nsobject<NSString> full_string_; - base::scoped_nsobject<NSString> partial_string_; - - DISALLOW_COPY_AND_ASSIGN(SelectedKeywordDecoration); -}; - -#endif // CHROME_BROWSER_UI_COCOA_LOCATION_BAR_SELECTED_KEYWORD_DECORATION_H_
diff --git a/chrome/browser/ui/cocoa/location_bar/selected_keyword_decoration.mm b/chrome/browser/ui/cocoa/location_bar/selected_keyword_decoration.mm deleted file mode 100644 index 64438e3..0000000 --- a/chrome/browser/ui/cocoa/location_bar/selected_keyword_decoration.mm +++ /dev/null
@@ -1,114 +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. - -#import "chrome/browser/ui/cocoa/location_bar/selected_keyword_decoration.h" - -#include <stddef.h> - -#include "base/i18n/rtl.h" -#include "base/strings/string_util.h" -#include "base/strings/sys_string_conversions.h" -#include "base/strings/utf_string_conversions.h" -#import "chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.h" -#include "chrome/grit/generated_resources.h" -#include "skia/ext/skia_utils_mac.h" -#include "ui/base/l10n/l10n_util_mac.h" -#include "ui/base/material_design/material_design_controller.h" -#include "ui/gfx/color_palette.h" -#include "ui/gfx/text_elider.h" - -namespace { - -// Build a short string to use in keyword-search when the field isn't very big. -base::string16 CalculateMinString(const base::string16& description) { - // Chop at the first '.' or whitespace. - const size_t chop_index = description.find_first_of(base::kWhitespaceUTF16 + - base::ASCIIToUTF16(".")); - base::string16 min_string( - (chop_index == base::string16::npos) - ? gfx::TruncateString(description, 3, gfx::WORD_BREAK) - : description.substr(0, chop_index)); - base::i18n::AdjustStringForLocaleDirection(&min_string); - return min_string; -} - -} // namespace - -SelectedKeywordDecoration::SelectedKeywordDecoration() { - // Note: the unit test - // SelectedKeywordDecorationTest.UsesPartialKeywordIfNarrow expects to work - // with a fully-initialized SelectedKeywordDecoration (i.e. one that has a - // text color and image). During ordinary operation, - // LocationBarViewMac::Layout() sets the image before the decoration is - // actually used, which the unit test does as well. If - // SelectedKeywordDecoration's initialization process changes, the unit test - // should also be updated. - SetTextColor(GetBackgroundBorderColor()); -} - -SelectedKeywordDecoration::~SelectedKeywordDecoration() {} - -NSColor* SelectedKeywordDecoration::GetBackgroundBorderColor() { - return skia::SkColorToSRGBNSColor(gfx::kGoogleBlue700); -} - -CGFloat SelectedKeywordDecoration::GetWidthForSpace(CGFloat width) { - const CGFloat full_width = - GetWidthForImageAndLabel(search_image_, full_string_); - if (full_width <= width) { - BubbleDecoration::SetImage(search_image_); - SetLabel(full_string_); - return full_width; - } - - BubbleDecoration::SetImage(nil); - const CGFloat no_image_width = GetWidthForImageAndLabel(nil, full_string_); - if (no_image_width <= width || !partial_string_) { - SetLabel(full_string_); - return no_image_width; - } - - SetLabel(partial_string_); - return GetWidthForImageAndLabel(nil, partial_string_); -} - -void SelectedKeywordDecoration::SetKeyword(const base::string16& short_name, - bool is_extension_keyword) { - const base::string16 min_name(CalculateMinString(short_name)); - const int keyword_text_id = IDS_OMNIBOX_KEYWORD_TEXT_MD; - - NSString* full_string = - is_extension_keyword - ? base::SysUTF16ToNSString(short_name) - : l10n_util::GetNSStringF(keyword_text_id, short_name); - - // The text will be like "Search <name>:". "<name>" is a parameter - // derived from |short_name|. If we're using Material Design, the text will - // be like "Search <name>" instead. - full_string_.reset([full_string copy]); - - if (min_name.empty()) { - partial_string_.reset(); - } else { - NSString* partial_string = - is_extension_keyword - ? base::SysUTF16ToNSString(min_name) - : l10n_util::GetNSStringF(keyword_text_id, min_name); - partial_string_.reset([partial_string copy]); - } -} - -void SelectedKeywordDecoration::SetImage(NSImage* image) { - if (image != search_image_) - search_image_.reset([image retain]); - BubbleDecoration::SetImage(image); -} - -NSString* SelectedKeywordDecoration::GetAccessibilityLabel() { - return full_string_.get(); -} - -bool SelectedKeywordDecoration::IsAccessibilityIgnored() { - return true; -}
diff --git a/chrome/browser/ui/cocoa/location_bar/selected_keyword_decoration_unittest.mm b/chrome/browser/ui/cocoa/location_bar/selected_keyword_decoration_unittest.mm deleted file mode 100644 index 80add31..0000000 --- a/chrome/browser/ui/cocoa/location_bar/selected_keyword_decoration_unittest.mm +++ /dev/null
@@ -1,75 +0,0 @@ -// Copyright (c) 2010 The Chromium 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 <Cocoa/Cocoa.h> - -#include "base/strings/utf_string_conversions.h" -#import "chrome/browser/ui/cocoa/location_bar/selected_keyword_decoration.h" -#import "chrome/browser/ui/cocoa/test/cocoa_test_helper.h" -#include "components/omnibox/browser/vector_icons.h" -#include "components/vector_icons/vector_icons.h" -#include "testing/gtest/include/gtest/gtest.h" -#import "testing/gtest_mac.h" -#include "ui/base/material_design/material_design_controller.h" -#include "ui/gfx/image/image_skia_util_mac.h" -#include "ui/gfx/paint_vector_icon.h" - -namespace { - -// A wide width which should fit everything. -const CGFloat kWidth(300.0); - -// A narrow width for tests which test things that don't fit. -const CGFloat kNarrowWidth(5.0); - -} // namespace - -class SelectedKeywordDecorationTest : public CocoaTest { - public: - SelectedKeywordDecorationTest() { - // With Material Design vector images the image isn't set at creation time - // but later by the LocationBar. The unit tests fail with a nil image, so - // initialize it now. - const int kDefaultIconSize = 16; - decoration_.SetImage(NSImageFromImageSkia(gfx::CreateVectorIcon( - vector_icons::kSearchIcon, kDefaultIconSize, SK_ColorBLACK))); - } - - SelectedKeywordDecoration decoration_; -}; - -// Test that the cell correctly chooses the partial keyword if there's -// not enough room. -TEST_F(SelectedKeywordDecorationTest, UsesPartialKeywordIfNarrow) { - - const base::string16 kKeyword = base::ASCIIToUTF16("Engine"); - NSString* const kFullString = @"Search Engine"; - NSString* const kPartialString = @"Search En\u2026"; - - decoration_.SetKeyword(kKeyword, false); - - // Wide width chooses the full string and image. - const CGFloat all_width = decoration_.GetWidthForSpace(kWidth); - EXPECT_TRUE(decoration_.image_); - EXPECT_NSEQ(kFullString, decoration_.label_); - - // If not enough space to include the image, uses exactly the full - // string. - const CGFloat full_width = decoration_.GetWidthForSpace(all_width - 5.0); - EXPECT_LT(full_width, all_width); - EXPECT_FALSE(decoration_.image_); - EXPECT_NSEQ(kFullString, decoration_.label_); - - // Narrow width chooses the partial string. - const CGFloat partial_width = decoration_.GetWidthForSpace(kNarrowWidth); - EXPECT_LT(partial_width, full_width); - EXPECT_FALSE(decoration_.image_); - EXPECT_NSEQ(kPartialString, decoration_.label_); - - // Narrow doesn't choose partial string if there is not one. - decoration_.partial_string_.reset(); - decoration_.GetWidthForSpace(kNarrowWidth); - EXPECT_FALSE(decoration_.image_); - EXPECT_NSEQ(kFullString, decoration_.label_); -}
diff --git a/chrome/browser/ui/cocoa/location_bar/star_decoration.h b/chrome/browser/ui/cocoa/location_bar/star_decoration.h deleted file mode 100644 index 0ee688a..0000000 --- a/chrome/browser/ui/cocoa/location_bar/star_decoration.h +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright (c) 2011 The Chromium 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_UI_COCOA_LOCATION_BAR_STAR_DECORATION_H_ -#define CHROME_BROWSER_UI_COCOA_LOCATION_BAR_STAR_DECORATION_H_ - -#import <Cocoa/Cocoa.h> - -#include "base/macros.h" -#include "chrome/browser/ui/cocoa/location_bar/image_decoration.h" - -class CommandUpdater; - -// Star icon on the right side of the field. - -class StarDecoration : public ImageDecoration { - public: - explicit StarDecoration(CommandUpdater* command_updater); - ~StarDecoration() override; - - // Sets the image and tooltip based on |starred|. - void SetStarred(bool starred, bool locationBarIsDark); - - // Returns an anchor for GetBubblePointInFrame which points between the star - // icon's legs. - static NSPoint GetStarBubblePointInFrame(NSRect draw_frame); - - // Returns true if the star is lit. - bool starred() const { return starred_; } - - // Implement |LocationBarDecoration|. - AcceptsPress AcceptsMousePress() override; - bool OnMousePressed(NSRect frame, NSPoint location) override; - NSString* GetToolTip() override; - NSPoint GetBubblePointInFrame(NSRect frame) override; - - protected: - // Overridden from LocationBarDecoration: - SkColor GetMaterialIconColor(bool location_bar_is_dark) const override; - const gfx::VectorIcon* GetMaterialVectorIcon() const override; - - private: - // For bringing up bookmark bar. - CommandUpdater* command_updater_; // Weak, owned by Browser. - - // The string to show for a tooltip. - base::scoped_nsobject<NSString> tooltip_; - - // Whether the star icon is lit. - bool starred_; - - DISALLOW_COPY_AND_ASSIGN(StarDecoration); -}; - -#endif // CHROME_BROWSER_UI_COCOA_LOCATION_BAR_STAR_DECORATION_H_
diff --git a/chrome/browser/ui/cocoa/location_bar/star_decoration.mm b/chrome/browser/ui/cocoa/location_bar/star_decoration.mm deleted file mode 100644 index cd17c33d..0000000 --- a/chrome/browser/ui/cocoa/location_bar/star_decoration.mm +++ /dev/null
@@ -1,75 +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. - -#import "chrome/browser/ui/cocoa/location_bar/star_decoration.h" - -#include "chrome/app/chrome_command_ids.h" -#include "chrome/browser/command_updater.h" -#import "chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.h" -#import "chrome/browser/ui/cocoa/themed_window.h" -#include "chrome/grit/generated_resources.h" -#include "components/strings/grit/components_strings.h" -#include "components/toolbar/vector_icons.h" -#include "ui/base/l10n/l10n_util_mac.h" -#include "ui/base/material_design/material_design_controller.h" -#include "ui/gfx/color_palette.h" - -namespace { - -// The info-bubble point should look like it points to the point -// between the star's lower tips. The popup should be where the -// Omnibox popup ends up (2px below field). Determined via Pixie.app -// magnification. -const CGFloat kStarPointYOffset = 2.0; - -} // namespace - -StarDecoration::StarDecoration(CommandUpdater* command_updater) - : command_updater_(command_updater) { - SetVisible(true); - SetStarred(false, false); -} - -StarDecoration::~StarDecoration() { -} - -void StarDecoration::SetStarred(bool starred, bool location_bar_is_dark) { - starred_ = starred; - const int tip_id = starred ? IDS_TOOLTIP_STARRED : IDS_TOOLTIP_STAR; - SetImage(GetMaterialIcon(location_bar_is_dark)); - tooltip_.reset([l10n_util::GetNSStringWithFixup(tip_id) retain]); -} - -NSPoint StarDecoration::GetStarBubblePointInFrame(NSRect draw_frame) { - return NSMakePoint(NSMidX(draw_frame), - NSMaxY(draw_frame) - kStarPointYOffset); -} - -AcceptsPress StarDecoration::AcceptsMousePress() { - return AcceptsPress::ALWAYS; -} - -bool StarDecoration::OnMousePressed(NSRect frame, NSPoint location) { - command_updater_->ExecuteCommand(IDC_BOOKMARK_PAGE); - return true; -} - -NSString* StarDecoration::GetToolTip() { - return tooltip_.get(); -} - -NSPoint StarDecoration::GetBubblePointInFrame(NSRect frame) { - return GetStarBubblePointInFrame(GetDrawRectInFrame(frame)); -} - -SkColor StarDecoration::GetMaterialIconColor(bool location_bar_is_dark) const { - if (location_bar_is_dark) { - return starred_ ? gfx::kGoogleBlue300 : SkColorSetA(SK_ColorWHITE, 0xCC); - } - return starred_ ? gfx::kGoogleBlue500 : gfx::kChromeIconGrey; -} - -const gfx::VectorIcon* StarDecoration::GetMaterialVectorIcon() const { - return starred_ ? &toolbar::kStarActiveIcon : &toolbar::kStarIcon; -}
diff --git a/chrome/browser/ui/cocoa/location_bar/translate_decoration.h b/chrome/browser/ui/cocoa/location_bar/translate_decoration.h deleted file mode 100644 index d0d8890..0000000 --- a/chrome/browser/ui/cocoa/location_bar/translate_decoration.h +++ /dev/null
@@ -1,44 +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_UI_COCOA_LOCATION_BAR_TRANSLATE_DECORATION_H_ -#define CHROME_BROWSER_UI_COCOA_LOCATION_BAR_TRANSLATE_DECORATION_H_ - -#import <Cocoa/Cocoa.h> - -#include "base/macros.h" -#include "chrome/browser/ui/cocoa/location_bar/image_decoration.h" - -class CommandUpdater; -@class TranslateBubbleController; - -// Translate icon on the right side of the field. This appears when -// translation is available on the current page. This icon is lit when -// translation is already done, otherwise not lit. -class TranslateDecoration : public ImageDecoration { - public: - explicit TranslateDecoration(CommandUpdater* command_updater); - ~TranslateDecoration() override; - - // Toggles the icon on or off. - void SetLit(bool on, bool locationBarIsDark); - - // Implement |LocationBarDecoration| - AcceptsPress AcceptsMousePress() override; - bool OnMousePressed(NSRect frame, NSPoint location) override; - NSString* GetToolTip() override; - NSPoint GetBubblePointInFrame(NSRect frame) override; - - protected: - // Overridden from LocationBarDecoration: - const gfx::VectorIcon* GetMaterialVectorIcon() const override; - - private: - // For showing the translate bubble up. - CommandUpdater* command_updater_; // Weak, owned by Browser. - - DISALLOW_COPY_AND_ASSIGN(TranslateDecoration); -}; - -#endif // CHROME_BROWSER_UI_COCOA_LOCATION_BAR_TRANSLATE_DECORATION_H_
diff --git a/chrome/browser/ui/cocoa/location_bar/translate_decoration.mm b/chrome/browser/ui/cocoa/location_bar/translate_decoration.mm deleted file mode 100644 index b93c5a1..0000000 --- a/chrome/browser/ui/cocoa/location_bar/translate_decoration.mm +++ /dev/null
@@ -1,46 +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. - -#import "chrome/browser/ui/cocoa/location_bar/translate_decoration.h" - -#include "chrome/app/chrome_command_ids.h" -#include "chrome/app/vector_icons/vector_icons.h" -#include "chrome/browser/command_updater.h" -#import "chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.h" -#include "chrome/grit/generated_resources.h" -#include "ui/base/l10n/l10n_util_mac.h" -#include "ui/base/material_design/material_design_controller.h" - -TranslateDecoration::TranslateDecoration(CommandUpdater* command_updater) - : command_updater_(command_updater) { - SetLit(false, false); -} - -TranslateDecoration::~TranslateDecoration() {} - -void TranslateDecoration::SetLit(bool on, bool location_bar_is_dark) { - SetImage(GetMaterialIcon(location_bar_is_dark)); -} - -NSPoint TranslateDecoration::GetBubblePointInFrame(NSRect frame) { - const NSRect draw_frame = GetDrawRectInFrame(frame); - return NSMakePoint(NSMidX(draw_frame), NSMaxY(draw_frame)); -} - -AcceptsPress TranslateDecoration::AcceptsMousePress() { - return AcceptsPress::ALWAYS; -} - -bool TranslateDecoration::OnMousePressed(NSRect frame, NSPoint location) { - command_updater_->ExecuteCommand(IDC_TRANSLATE_PAGE); - return true; -} - -NSString* TranslateDecoration::GetToolTip() { - return l10n_util::GetNSStringWithFixup(IDS_TOOLTIP_TRANSLATE); -} - -const gfx::VectorIcon* TranslateDecoration::GetMaterialVectorIcon() const { - return &kTranslateIcon; -}
diff --git a/chrome/browser/ui/cocoa/location_bar/zoom_decoration.h b/chrome/browser/ui/cocoa/location_bar/zoom_decoration.h index 9deb30c0..ab15d3a 100644 --- a/chrome/browser/ui/cocoa/location_bar/zoom_decoration.h +++ b/chrome/browser/ui/cocoa/location_bar/zoom_decoration.h
@@ -8,11 +8,9 @@ #import <Cocoa/Cocoa.h> #include "base/macros.h" -#import "chrome/browser/ui/cocoa/browser/zoom_bubble_controller.h" #include "chrome/browser/ui/cocoa/location_bar/image_decoration.h" class LocationBarViewMac; -@class ZoomBubbleController; class ZoomDecorationTest; namespace zoom { @@ -21,8 +19,7 @@ // Zoom icon at the end of the omnibox (close to page actions) when at a // non-standard zoom level. -class ZoomDecoration : public ImageDecoration, - public ZoomBubbleControllerDelegate { +class ZoomDecoration : public ImageDecoration { public: explicit ZoomDecoration(LocationBarViewMac* owner); ~ZoomDecoration() override; @@ -72,16 +69,9 @@ NSString* GetToolTip() override; NSPoint GetBubblePointInFrame(NSRect frame) override; - // ZoomBubbleControllerDelegate implementation. - content::WebContents* GetWebContents() override; - void OnClose() override; - // The control that owns this. Weak. LocationBarViewMac* owner_; - // The bubble that this decoration shows. Weak, owns self. - ZoomBubbleController* bubble_; - // The string to show for a tooltip. base::scoped_nsobject<NSString> tooltip_;
diff --git a/chrome/browser/ui/cocoa/location_bar/zoom_decoration.mm b/chrome/browser/ui/cocoa/location_bar/zoom_decoration.mm index c3bb8d1..87a482e 100644 --- a/chrome/browser/ui/cocoa/location_bar/zoom_decoration.mm +++ b/chrome/browser/ui/cocoa/location_bar/zoom_decoration.mm
@@ -22,25 +22,11 @@ #include "ui/base/l10n/l10n_util_mac.h" #import "ui/gfx/mac/coordinate_conversion.h" -namespace { - -// Whether the toolkit-views zoom bubble should be used. -bool UseViews() { - return true; -} - -} // namespace - ZoomDecoration::ZoomDecoration(LocationBarViewMac* owner) - : owner_(owner), bubble_(nullptr), vector_icon_(nullptr) {} + : owner_(owner), vector_icon_(nullptr) {} ZoomDecoration::~ZoomDecoration() { - if (UseViews()) { - CloseBubble(); - return; - } - [bubble_ closeWithoutAnimation]; - bubble_.delegate = nil; + CloseBubble(); } bool ZoomDecoration::UpdateIfNecessary(zoom::ZoomController* zoom_controller, @@ -79,11 +65,7 @@ } void ZoomDecoration::CloseBubble() { - if (UseViews()) { - chrome::CloseZoomBubbleViews(); - return; - } - [bubble_ close]; + chrome::CloseZoomBubbleViews(); } void ZoomDecoration::HideUI() { @@ -103,10 +85,7 @@ tooltip_.reset([tooltip_string retain]); - if (UseViews()) - chrome::RefreshZoomBubbleViews(); - else - [bubble_ onZoomChanged]; + chrome::RefreshZoomBubbleViews(); } NSPoint ZoomDecoration::GetBubblePointInFrame(NSRect frame) { @@ -127,7 +106,7 @@ } bool ZoomDecoration::IsBubbleShown() const { - return (UseViews() && chrome::IsZoomBubbleViewsShown()) || bubble_; + return chrome::IsZoomBubbleViewsShown(); } bool ZoomDecoration::ShouldShowDecoration() const { @@ -144,10 +123,7 @@ if (IsBubbleShown()) { CloseBubble(); } else { - // With Material Design enabled the zoom bubble is no longer auto-closed - // when activated with a mouse click. - const BOOL auto_close = !UseViews(); - ShowBubble(auto_close); + ShowBubble(false); } return true; } @@ -156,25 +132,6 @@ return tooltip_.get(); } -content::WebContents* ZoomDecoration::GetWebContents() { - return owner_->GetWebContents(); -} - -void ZoomDecoration::OnClose() { - if (!UseViews()) { - bubble_.delegate = nil; - bubble_ = nil; - } - - // If the page is at default zoom then hiding the zoom decoration - // was suppressed while the bubble was open. Now that the bubble is - // closed the decoration can be hidden. - if (IsAtDefaultZoom() && IsVisible()) { - SetVisible(false); - owner_->OnDecorationsChanged(); - } -} - const gfx::VectorIcon* ZoomDecoration::GetMaterialVectorIcon() const { return vector_icon_; }
diff --git a/chrome/browser/ui/cocoa/location_bar/zoom_decoration_browsertest.mm b/chrome/browser/ui/cocoa/location_bar/zoom_decoration_browsertest.mm index b640b55d..731afb07 100644 --- a/chrome/browser/ui/cocoa/location_bar/zoom_decoration_browsertest.mm +++ b/chrome/browser/ui/cocoa/location_bar/zoom_decoration_browsertest.mm
@@ -12,7 +12,6 @@ #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser_window.h" -#import "chrome/browser/ui/cocoa/browser/zoom_bubble_controller.h" #import "chrome/browser/ui/cocoa/browser_window_controller.h" #import "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" #include "chrome/browser/ui/cocoa/test/run_loop_testing.h" @@ -134,8 +133,6 @@ } IN_PROC_BROWSER_TEST_P(ZoomDecorationTest, CloseBrowserWithOpenBubble) { - chrome::SetZoomBubbleAutoCloseDelayForTesting(0); - // Create a new browser so that it can be closed properly. Browser* browser2 = CreateBrowser(browser()->profile()); ZoomDecoration* zoom_decoration = GetZoomDecorationForBrowser(browser2);
diff --git a/chrome/browser/ui/cocoa/new_tab_button.h b/chrome/browser/ui/cocoa/new_tab_button.h deleted file mode 100644 index 642c4437..0000000 --- a/chrome/browser/ui/cocoa/new_tab_button.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright (c) 2011 The Chromium 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_UI_COCOA_NEW_TAB_BUTTON_H_ -#define CHROME_BROWSER_UI_COCOA_NEW_TAB_BUTTON_H_ - -#import <Cocoa/Cocoa.h> - -#import "chrome/browser/ui/cocoa/themed_window.h" - -// Overrides hit-test behavior to only accept clicks inside the image of the -// button, not just inside the bounding box. This could be abstracted to general -// use, but no other buttons are so irregularly shaped with respect to their -// bounding box. - -@interface NewTabButtonCocoa : NSButton<ThemedWindowDrawing> - -// Returns YES if the given point is over the button. |point| is in the -// superview's coordinate system. -- (BOOL)pointIsOverButton:(NSPoint)point; - -// Sets the images shown by the NewTabButtonCocoa's different states. -- (void)setImages; - -@end - - -#endif // CHROME_BROWSER_UI_COCOA_NEW_TAB_BUTTON_H_
diff --git a/chrome/browser/ui/cocoa/new_tab_button_cocoa.mm b/chrome/browser/ui/cocoa/new_tab_button_cocoa.mm deleted file mode 100644 index 5721b93bb..0000000 --- a/chrome/browser/ui/cocoa/new_tab_button_cocoa.mm +++ /dev/null
@@ -1,526 +0,0 @@ -// Copyright (c) 2011 The Chromium 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 "chrome/browser/ui/cocoa/new_tab_button.h" - -#include "base/mac/foundation_util.h" -#include "base/mac/sdk_forward_declarations.h" -#include "chrome/browser/ui/cocoa/cocoa_util.h" -#import "chrome/browser/ui/cocoa/image_button_cell.h" -#include "chrome/browser/ui/cocoa/l10n_util.h" -#include "chrome/browser/ui/cocoa/tabs/tab_view.h" -#include "chrome/grit/theme_resources.h" -#include "ui/base/cocoa/nsgraphics_context_additions.h" -#include "ui/base/material_design/material_design_controller.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/base/theme_provider.h" - -@class NewTabButtonCell; - -namespace { - -enum class OverlayOption { - NONE, - LIGHTEN, - DARKEN, -}; - -const NSSize newTabButtonImageSize = {34, 18}; - -NSImage* GetMaskImageFromCell(NewTabButtonCell* aCell) { - return [aCell imageForState:image_button_cell::kDefaultState view:nil]; -} - -// Creates an NSImage with size |size| and bitmap image representations for both -// 1x and 2x scale factors. |drawingHandler| is called once for every scale -// factor. This is similar to -[NSImage imageWithSize:flipped:drawingHandler:], -// but this function always evaluates drawingHandler eagerly, and it works on -// 10.6 and 10.7. -NSImage* CreateImageWithSize(NSSize size, - void (^drawingHandler)(NSSize)) { - base::scoped_nsobject<NSImage> result([[NSImage alloc] initWithSize:size]); - [NSGraphicsContext saveGraphicsState]; - for (ui::ScaleFactor scale_factor : ui::GetSupportedScaleFactors()) { - float scale = GetScaleForScaleFactor(scale_factor); - NSBitmapImageRep *bmpImageRep = [[[NSBitmapImageRep alloc] - initWithBitmapDataPlanes:NULL - pixelsWide:size.width * scale - pixelsHigh:size.height * scale - bitsPerSample:8 - samplesPerPixel:4 - hasAlpha:YES - isPlanar:NO - colorSpaceName:NSDeviceRGBColorSpace - bytesPerRow:0 - bitsPerPixel:0] autorelease]; - [bmpImageRep setSize:size]; - [NSGraphicsContext setCurrentContext: - [NSGraphicsContext graphicsContextWithBitmapImageRep:bmpImageRep]]; - drawingHandler(size); - [result addRepresentation:bmpImageRep]; - } - [NSGraphicsContext restoreGraphicsState]; - - return result.release(); -} - -// Takes a normal bitmap and a mask image and returns an image the size of the -// mask that has pixels from |image| but alpha information from |mask|. -NSImage* ApplyMask(NSImage* image, NSImage* mask) { - return [CreateImageWithSize([mask size], ^(NSSize size) { - // Skip a few pixels from the top of the tab background gradient, because - // the new tab button is not drawn at the very top of the browser window. - const int kYOffset = 10; - CGFloat width = size.width; - CGFloat height = size.height; - - // In some themes, the tab background image is narrower than the - // new tab button, so tile the background image. - CGFloat x = 0; - // The floor() is to make sure images with odd widths don't draw to the - // same pixel twice on retina displays. (Using NSDrawThreePartImage() - // caused a startup perf regression, so that cannot be used.) - CGFloat tileWidth = floor(std::min(width, [image size].width)); - while (x < width) { - [image drawAtPoint:NSMakePoint(x, 0) - fromRect:NSMakeRect(0, - [image size].height - height - kYOffset, - tileWidth, - height) - operation:NSCompositeCopy - fraction:1.0]; - x += tileWidth; - } - - [mask drawAtPoint:NSZeroPoint - fromRect:NSMakeRect(0, 0, width, height) - operation:NSCompositeDestinationIn - fraction:1.0]; - }) autorelease]; -} - -// Paints |overlay| on top of |ground|. -NSImage* Overlay(NSImage* ground, NSImage* overlay, CGFloat alpha) { - DCHECK_EQ([ground size].width, [overlay size].width); - DCHECK_EQ([ground size].height, [overlay size].height); - - return [CreateImageWithSize([ground size], ^(NSSize size) { - CGFloat width = size.width; - CGFloat height = size.height; - [ground drawAtPoint:NSZeroPoint - fromRect:NSMakeRect(0, 0, width, height) - operation:NSCompositeCopy - fraction:1.0]; - [overlay drawAtPoint:NSZeroPoint - fromRect:NSMakeRect(0, 0, width, height) - operation:NSCompositeSourceOver - fraction:alpha]; - }) autorelease]; -} - -} // namespace - -@interface NewTabButtonCustomImageRep : NSCustomImageRep -@property (assign, nonatomic) NSView* destView; -@property (copy, nonatomic) NSColor* fillColor; -@property (assign, nonatomic) NSPoint patternPhasePosition; -@property (assign, nonatomic) OverlayOption overlayOption; -@end - -@implementation NewTabButtonCustomImageRep - -@synthesize destView = destView_; -@synthesize fillColor = fillColor_; -@synthesize patternPhasePosition = patternPhasePosition_; -@synthesize overlayOption = overlayOption_; - -- (void)dealloc { - [fillColor_ release]; - [super dealloc]; -} - -@end - -// A simple override of the ImageButtonCell to disable handling of -// -mouseEntered. -@interface NewTabButtonCell : ImageButtonCell - -- (void)mouseEntered:(NSEvent*)theEvent; - -@end - -@implementation NewTabButtonCell - -- (void)mouseEntered:(NSEvent*)theEvent { - // Ignore this since the NTB enter is handled by the TabStripControllerCocoa. -} - -- (void)drawFocusRingMaskWithFrame:(NSRect)cellFrame inView:(NSView*)view { - // Match the button's shape. - [self drawImage:GetMaskImageFromCell(self) withFrame:cellFrame inView:view]; -} - -@end - -@interface NewTabButtonCocoa () - -// Returns a new tab button image appropriate for the specified button state -// (e.g. hover) and theme. In Material Design, the theme color affects the -// button color. -- (NSImage*)imageForState:(image_button_cell::ButtonState)state - theme:(const ui::ThemeProvider*)theme; - -// Returns a new tab button image bezier path with the specified line width. -+ (NSBezierPath*)newTabButtonBezierPathWithLineWidth:(CGFloat)lineWidth; - -// Draws the new tab button image to |imageRep|, with either a normal stroke or -// a heavy stroke for increased visibility. -+ (void)drawNewTabButtonImage:(NewTabButtonCustomImageRep*)imageRep - withHeavyStroke:(BOOL)heavyStroke; - -// NSCustomImageRep custom drawing method shims for normal and heavy strokes -// respectively. -+ (void)drawNewTabButtonImageWithNormalStroke: - (NewTabButtonCustomImageRep*)imageRep; -+ (void)drawNewTabButtonImageWithHeavyStroke: - (NewTabButtonCustomImageRep*)imageRep; - -// Returns a new tab button image filled with |fillColor|. -- (NSImage*)imageWithFillColor:(NSColor*)fillColor; - -@end - -@implementation NewTabButtonCocoa - -+ (Class)cellClass { - return [NewTabButtonCell class]; -} - -- (BOOL)pointIsOverButton:(NSPoint)point { - NSPoint localPoint = [self convertPoint:point fromView:[self superview]]; - NSRect pointRect = NSMakeRect(localPoint.x, localPoint.y, 1, 1); - NSImage* buttonMask = GetMaskImageFromCell([self cell]); - NSRect bounds = self.bounds; - NSSize buttonMaskSize = [buttonMask size]; - NSRect destinationRect = NSMakeRect( - (NSWidth(bounds) - buttonMaskSize.width) / 2, - (NSHeight(bounds) - buttonMaskSize.height) / 2, - buttonMaskSize.width, buttonMaskSize.height); - return [buttonMask hitTestRect:pointRect - withImageDestinationRect:destinationRect - context:nil - hints:nil - flipped:YES]; -} - -// Override to only accept clicks within the bounds of the defined path, not -// the entire bounding box. |aPoint| is in the superview's coordinate system. -- (NSView*)hitTest:(NSPoint)aPoint { - if ([self pointIsOverButton:aPoint]) - return [super hitTest:aPoint]; - return nil; -} - -// ThemedWindowDrawing implementation. - -- (void)windowDidChangeTheme { - [self setNeedsDisplay:YES]; -} - -- (void)windowDidChangeActive { - [self setNeedsDisplay:YES]; -} - -- (void)viewDidMoveToWindow { - NewTabButtonCell* cell = base::mac::ObjCCast<NewTabButtonCell>([self cell]); - - if ([self window] && - ![cell imageForState:image_button_cell::kDefaultState view:self]) { - [self setImages]; - } -} - -- (void)setImages { - const ui::ThemeProvider* theme = [[self window] themeProvider]; - if (!theme) { - return; - } - - NSImage* mask = [self imageWithFillColor:[NSColor whiteColor]]; - NSImage* normal = - [self imageForState:image_button_cell::kDefaultState theme:theme]; - NSImage* hover = - [self imageForState:image_button_cell::kHoverState theme:theme]; - NSImage* pressed = - [self imageForState:image_button_cell::kPressedState theme:theme]; - NSImage* normalBackground = nil; - NSImage* hoverBackground = nil; - - // If using a custom theme, overlay the default image with the theme's custom - // tab background image. - if (!theme->UsingSystemTheme()) { - NSImage* foreground = - ApplyMask(theme->GetNSImageNamed(IDR_THEME_TAB_BACKGROUND), mask); - normal = Overlay(foreground, normal, 1.0); - hover = Overlay(foreground, hover, 1.0); - pressed = Overlay(foreground, pressed, 1.0); - - NSImage* background = ApplyMask( - theme->GetNSImageNamed(IDR_THEME_TAB_BACKGROUND_INACTIVE), mask); - normalBackground = Overlay(background, normal, tabs::kImageNoFocusAlpha); - hoverBackground = Overlay(background, hover, tabs::kImageNoFocusAlpha); - } - - NewTabButtonCell* cell = base::mac::ObjCCast<NewTabButtonCell>([self cell]); - [cell setImage:normal forButtonState:image_button_cell::kDefaultState]; - [cell setImage:hover forButtonState:image_button_cell::kHoverState]; - [cell setImage:pressed forButtonState:image_button_cell::kPressedState]; - [cell setImage:normalBackground - forButtonState:image_button_cell::kDefaultStateBackground]; - [cell setImage:hoverBackground - forButtonState:image_button_cell::kHoverStateBackground]; -} - -- (NSImage*)imageForState:(image_button_cell::ButtonState)state - theme:(const ui::ThemeProvider*)theme { - NSColor* fillColor = nil; - OverlayOption overlayOption = OverlayOption::NONE; - - switch (state) { - case image_button_cell::kDefaultState: - // In the normal state, the NTP button looks like a background tab. - fillColor = theme->GetNSImageColorNamed(IDR_THEME_TAB_BACKGROUND); - break; - - case image_button_cell::kHoverState: - fillColor = theme->GetNSImageColorNamed(IDR_THEME_TAB_BACKGROUND); - overlayOption = OverlayOption::LIGHTEN; - - break; - - case image_button_cell::kPressedState: - fillColor = theme->GetNSImageColorNamed(IDR_THEME_TAB_BACKGROUND); - overlayOption = OverlayOption::DARKEN; - break; - - case image_button_cell::kDefaultStateBackground: - case image_button_cell::kHoverStateBackground: - fillColor = - theme->GetNSImageColorNamed(IDR_THEME_TAB_BACKGROUND_INACTIVE); - break; - - default: - fillColor = [NSColor redColor]; - // All states should be accounted for above. - NOTREACHED(); - } - - SEL drawSelector = @selector(drawNewTabButtonImageWithNormalStroke:); - if (theme && theme->ShouldIncreaseContrast()) - drawSelector = @selector(drawNewTabButtonImageWithHeavyStroke:); - - base::scoped_nsobject<NewTabButtonCustomImageRep> imageRep( - [[NewTabButtonCustomImageRep alloc] - initWithDrawSelector:drawSelector - delegate:[NewTabButtonCocoa class]]); - [imageRep setDestView:self]; - [imageRep setFillColor:fillColor]; - [imageRep setPatternPhasePosition: - [[self window] - themeImagePositionForAlignment:THEME_IMAGE_ALIGN_WITH_TAB_STRIP]]; - [imageRep setOverlayOption:overlayOption]; - - NSImage* newTabButtonImage = - [[[NSImage alloc] initWithSize:newTabButtonImageSize] autorelease]; - [newTabButtonImage addRepresentation:imageRep]; - - return newTabButtonImage; -} - -+ (NSBezierPath*)newTabButtonBezierPathWithLineWidth:(CGFloat)lineWidth { - NSBezierPath* bezierPath = [NSBezierPath bezierPath]; - - // This data comes straight from the SVG. - [bezierPath moveToPoint:NSMakePoint(15.2762236,30)]; - - [bezierPath curveToPoint:NSMakePoint(11.0354216,27.1770115) - controlPoint1:NSMakePoint(13.3667706,30) - controlPoint2:NSMakePoint(11.7297681,28.8344828)]; - - [bezierPath curveToPoint:NSMakePoint(7.28528951e-08,2.01431416) - controlPoint1:NSMakePoint(11.0354216,27.1770115) - controlPoint2:NSMakePoint(0.000412425082,3.87955717)]; - - [bezierPath curveToPoint:NSMakePoint(1.70510791,0) - controlPoint1:NSMakePoint(-0.000270516213,0.790325707) - controlPoint2:NSMakePoint(0.753255356,0)]; - - [bezierPath lineToPoint:NSMakePoint(48.7033642,0)]; - - [bezierPath curveToPoint:NSMakePoint(52.9464653,2.82643678) - controlPoint1:NSMakePoint(50.6151163,0) - controlPoint2:NSMakePoint(52.2521188,1.16666667)]; - - [bezierPath curveToPoint:NSMakePoint(64.0268555,27.5961914) - controlPoint1:NSMakePoint(52.9464653,2.82643678) - controlPoint2:NSMakePoint(64.0268555,27.4111339)]; - - [bezierPath curveToPoint:NSMakePoint(62.2756294,30) - controlPoint1:NSMakePoint(64.0268555,28.5502144) - controlPoint2:NSMakePoint(63.227482,29.9977011)]; - - [bezierPath closePath]; - - // The SVG path is flipped for some reason, so flip it back. However, in RTL, - // we'd need to flip it again below, so when in RTL mode just leave the flip - // out altogether. - if (!cocoa_l10n_util::ShouldDoExperimentalRTLLayout()) { - const CGFloat kSVGHeight = 32; - NSAffineTransformStruct flipStruct = {1, 0, 0, -1, 0, kSVGHeight}; - NSAffineTransform* flipTransform = [NSAffineTransform transform]; - [flipTransform setTransformStruct:flipStruct]; - [bezierPath transformUsingAffineTransform:flipTransform]; - } - - // The SVG data is for the 2x version so scale it down. - NSAffineTransform* scaleTransform = [NSAffineTransform transform]; - const CGFloat k50PercentScale = 0.5; - [scaleTransform scaleBy:k50PercentScale]; - [bezierPath transformUsingAffineTransform:scaleTransform]; - - // Adjust by half the line width to get crisp lines. - NSAffineTransform* transform = [NSAffineTransform transform]; - [transform translateXBy:lineWidth / 2 yBy:lineWidth / 2]; - [bezierPath transformUsingAffineTransform:transform]; - - [bezierPath setLineWidth:lineWidth]; - - return bezierPath; -} - -+ (void)drawNewTabButtonImage:(NewTabButtonCustomImageRep*)imageRep - withHeavyStroke:(BOOL)heavyStroke { - [[NSGraphicsContext currentContext] - cr_setPatternPhase:[imageRep patternPhasePosition] - forView:[imageRep destView]]; - - CGContextRef context = static_cast<CGContextRef>( - [[NSGraphicsContext currentContext] graphicsPort]); - CGFloat lineWidth = cocoa_util::LineWidthFromContext(context); - NSBezierPath* bezierPath = - [self newTabButtonBezierPathWithLineWidth:lineWidth]; - - if ([imageRep fillColor]) { - [[imageRep fillColor] set]; - [bezierPath fill]; - } - - CGFloat alpha = heavyStroke ? 1.0 : 0.25; - static NSColor* strokeColor = - [[NSColor colorWithCalibratedWhite:0 alpha:alpha] retain]; - [strokeColor set]; - [bezierPath stroke]; - - BOOL isRTL = cocoa_l10n_util::ShouldDoExperimentalRTLLayout(); - CGFloat buttonWidth = newTabButtonImageSize.width; - - // Bottom edge. - const CGFloat kBottomEdgeX = 9; - const CGFloat kBottomEdgeY = 1.2825; - const CGFloat kBottomEdgeWidth = 22; - NSPoint bottomEdgeStart = NSMakePoint(kBottomEdgeX, kBottomEdgeY); - NSPoint bottomEdgeEnd = NSMakePoint(kBottomEdgeX + kBottomEdgeWidth, - kBottomEdgeY); - if (isRTL) { - bottomEdgeStart.x = buttonWidth - bottomEdgeStart.x; - bottomEdgeEnd.x = buttonWidth - bottomEdgeEnd.x; - } - NSBezierPath* bottomEdgePath = [NSBezierPath bezierPath]; - [bottomEdgePath moveToPoint:bottomEdgeStart]; - [bottomEdgePath lineToPoint:bottomEdgeEnd]; - static NSColor* bottomEdgeColor = - [[NSColor colorWithCalibratedWhite:0 alpha:0.07] retain]; - [bottomEdgeColor set]; - [bottomEdgePath setLineWidth:lineWidth]; - [bottomEdgePath setLineCapStyle:NSRoundLineCapStyle]; - [bottomEdgePath stroke]; - - CGPoint shadowStart = NSZeroPoint; - CGPoint shadowEnd = NSZeroPoint; - NSColor* overlayColor = nil; - const CGFloat kBottomShadowX = 8; - const CGFloat kBottomShadowY = kBottomEdgeY - lineWidth; - const CGFloat kTopShadowX = 1; - const CGFloat kTopShadowY = kBottomShadowY + 15; - const CGFloat kShadowWidth = 24; - static NSColor* lightOverlayColor = - [[NSColor colorWithCalibratedWhite:1 alpha:0.20] retain]; - static NSColor* darkOverlayColor = - [[NSColor colorWithCalibratedWhite:0 alpha:0.08] retain]; - - switch ([imageRep overlayOption]) { - case OverlayOption::LIGHTEN: - overlayColor = lightOverlayColor; - break; - - case OverlayOption::DARKEN: - overlayColor = darkOverlayColor; - shadowStart = NSMakePoint(kTopShadowX, kTopShadowY); - shadowEnd = NSMakePoint(kTopShadowX + kShadowWidth, kTopShadowY); - break; - - case OverlayOption::NONE: - shadowStart = NSMakePoint(kBottomShadowX, kBottomShadowY); - shadowEnd = NSMakePoint(kBottomShadowX + kShadowWidth, kBottomShadowY); - break; - } - - // Shadow beneath the bottom or top edge. - if (!NSEqualPoints(shadowStart, NSZeroPoint)) { - if (isRTL) { - shadowStart.x = buttonWidth - shadowStart.x; - shadowEnd.x = buttonWidth - shadowEnd.x; - } - NSBezierPath* shadowPath = [NSBezierPath bezierPath]; - [shadowPath moveToPoint:shadowStart]; - [shadowPath lineToPoint:shadowEnd]; - [shadowPath setLineWidth:lineWidth]; - [shadowPath setLineCapStyle:NSRoundLineCapStyle]; - static NSColor* shadowColor = - [[NSColor colorWithCalibratedWhite:0 alpha:0.10] retain]; - [shadowColor set]; - [shadowPath stroke]; - } - - if (overlayColor) { - [overlayColor set]; - [[self newTabButtonBezierPathWithLineWidth:lineWidth] fill]; - } -} - -+ (void)drawNewTabButtonImageWithNormalStroke: - (NewTabButtonCustomImageRep*)image { - [self drawNewTabButtonImage:image withHeavyStroke:NO]; -} - -+ (void)drawNewTabButtonImageWithHeavyStroke: - (NewTabButtonCustomImageRep*)image { - [self drawNewTabButtonImage:image withHeavyStroke:YES]; -} - -- (NSImage*)imageWithFillColor:(NSColor*)fillColor { - NSImage* image = - [[[NSImage alloc] initWithSize:newTabButtonImageSize] autorelease]; - - [image lockFocus]; - [fillColor set]; - CGContextRef context = static_cast<CGContextRef>( - [[NSGraphicsContext currentContext] graphicsPort]); - CGFloat lineWidth = cocoa_util::LineWidthFromContext(context); - [[NewTabButtonCocoa newTabButtonBezierPathWithLineWidth:lineWidth] fill]; - [image unlockFocus]; - return image; -} - -@end
diff --git a/chrome/browser/ui/cocoa/omnibox_decoration_bubble_controller.h b/chrome/browser/ui/cocoa/omnibox_decoration_bubble_controller.h deleted file mode 100644 index 4f1198c5..0000000 --- a/chrome/browser/ui/cocoa/omnibox_decoration_bubble_controller.h +++ /dev/null
@@ -1,25 +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_UI_COCOA_OMNIBOX_DECORATION_BUBBLE_CONTROLLER_H_ -#define CHROME_BROWSER_UI_COCOA_OMNIBOX_DECORATION_BUBBLE_CONTROLLER_H_ - -#import <Cocoa/Cocoa.h> - -#import "chrome/browser/ui/cocoa/base_bubble_controller.h" - -class LocationBarDecoration; - -// Base bubble controller for bubbles that are anchored to an omnibox -// decoration. This controller updates the active state of the associated icon -// according to the state of the bubble. -@interface OmniboxDecorationBubbleController : BaseBubbleController - -// Returns the omnibox icon the bubble is anchored to. -// Subclasses are expected to override this. -- (LocationBarDecoration*)decorationForBubble; - -@end - -#endif // CHROME_BROWSER_UI_COCOA_OMNIBOX_DECORATION_BUBBLE_CONTROLLER_H_
diff --git a/chrome/browser/ui/cocoa/omnibox_decoration_bubble_controller.mm b/chrome/browser/ui/cocoa/omnibox_decoration_bubble_controller.mm deleted file mode 100644 index e9853e3..0000000 --- a/chrome/browser/ui/cocoa/omnibox_decoration_bubble_controller.mm +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "chrome/browser/ui/cocoa/omnibox_decoration_bubble_controller.h" - -#import <Cocoa/Cocoa.h> - -#import "chrome/browser/ui/cocoa/browser_window_controller.h" -#import "chrome/browser/ui/cocoa/location_bar/location_bar_decoration.h" - -// Base bubble controller class. -@implementation OmniboxDecorationBubbleController - -- (void)showWindow:(id)sender { - LocationBarDecoration* decoration = [self decorationForBubble]; - if (decoration) - decoration->SetActive(true); - - [super showWindow:sender]; -} - -- (void)close { - LocationBarDecoration* decoration = [self decorationForBubble]; - if (decoration) - decoration->SetActive(false); - - [super close]; -} - -- (LocationBarDecoration*)decorationForBubble { - NOTREACHED(); - return nullptr; -} - -@end
diff --git a/chrome/browser/ui/cocoa/tab_modal_confirm_dialog_mac.h b/chrome/browser/ui/cocoa/tab_modal_confirm_dialog_mac.h deleted file mode 100644 index af77bfaa..0000000 --- a/chrome/browser/ui/cocoa/tab_modal_confirm_dialog_mac.h +++ /dev/null
@@ -1,60 +0,0 @@ -// Copyright (c) 2011 The Chromium 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_UI_COCOA_TAB_MODAL_CONFIRM_DIALOG_MAC_H_ -#define CHROME_BROWSER_UI_COCOA_TAB_MODAL_CONFIRM_DIALOG_MAC_H_ - -#import <Cocoa/Cocoa.h> - -#include <memory> - -#import "base/mac/scoped_nsobject.h" -#include "base/macros.h" -#include "chrome/browser/ui/cocoa/constrained_window/constrained_window_mac.h" -#include "chrome/browser/ui/tab_modal_confirm_dialog.h" - -@class ConstrainedWindowAlert; - -namespace content { -class WebContents; -} - -class TabModalConfirmDialogDelegate; -@class TabModalConfirmDialogMacBridge; - -// Displays a tab-modal dialog, i.e. a dialog that will block the current page -// but still allow the user to switch to a different page. -// To display the dialog, allocate this object on the heap. It will open the -// dialog from its constructor and then delete itself when the user dismisses -// the dialog. -class TabModalConfirmDialogMac : public TabModalConfirmDialog, - public ConstrainedWindowMacDelegate { - public: - TabModalConfirmDialogMac(TabModalConfirmDialogDelegate* delegate, - content::WebContents* web_contents); - - private: - ~TabModalConfirmDialogMac() override; - - // TabModalConfirmDialog: - void AcceptTabModalDialog() override; - void CancelTabModalDialog() override; - - // TabModalConfirmDialogCloseDelegate: - void CloseDialog() override; - - // ConstrainedWindowMacDelegate: - void OnConstrainedWindowClosed(ConstrainedWindowMac* window) override; - - bool closing_; - - std::unique_ptr<ConstrainedWindowMac> window_; - std::unique_ptr<TabModalConfirmDialogDelegate> delegate_; - base::scoped_nsobject<ConstrainedWindowAlert> alert_; - base::scoped_nsobject<TabModalConfirmDialogMacBridge> bridge_; - - DISALLOW_COPY_AND_ASSIGN(TabModalConfirmDialogMac); -}; - -#endif // CHROME_BROWSER_UI_COCOA_TAB_MODAL_CONFIRM_DIALOG_MAC_H_
diff --git a/chrome/browser/ui/cocoa/tab_modal_confirm_dialog_mac.mm b/chrome/browser/ui/cocoa/tab_modal_confirm_dialog_mac.mm deleted file mode 100644 index 213acc135..0000000 --- a/chrome/browser/ui/cocoa/tab_modal_confirm_dialog_mac.mm +++ /dev/null
@@ -1,139 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/cocoa/tab_modal_confirm_dialog_mac.h" - -#include <utility> - -#include "base/mac/scoped_nsobject.h" -#include "chrome/browser/ui/browser_dialogs.h" -#import "chrome/browser/ui/cocoa/constrained_window/constrained_window_alert.h" -#import "chrome/browser/ui/cocoa/constrained_window/constrained_window_custom_sheet.h" -#import "chrome/browser/ui/cocoa/key_equivalent_constants.h" -#include "chrome/browser/ui/tab_modal_confirm_dialog_delegate.h" -#include "chrome/common/chrome_switches.h" -#include "ui/base/cocoa/cocoa_base_utils.h" -#include "ui/base/l10n/l10n_util_mac.h" -#include "ui/base/ui_features.h" -#include "ui/gfx/image/image.h" - -// static -TabModalConfirmDialog* TabModalConfirmDialog::CreateCocoa( - TabModalConfirmDialogDelegate* delegate, - content::WebContents* web_contents) { - // Deletes itself when closed. - return new TabModalConfirmDialogMac(delegate, web_contents); -} - -#if !BUILDFLAG(MAC_VIEWS_BROWSER) -TabModalConfirmDialog* TabModalConfirmDialog::Create( - TabModalConfirmDialogDelegate* delegate, - content::WebContents* web_contents) { - return CreateCocoa(delegate, web_contents); -} -#endif - -@interface TabModalConfirmDialogMacBridge : NSObject { - TabModalConfirmDialogDelegate* delegate_; // weak -} -@end - -@implementation TabModalConfirmDialogMacBridge - -- (id)initWithDelegate:(TabModalConfirmDialogDelegate*)delegate { - if ((self = [super init])) { - delegate_ = delegate; - DCHECK(delegate_); - } - return self; -} - -- (void)onAcceptButton:(id)sender { - delegate_->Accept(); -} - -- (void)onCancelButton:(id)sender { - delegate_->Cancel(); -} - -- (void)onCloseButton:(id)sender { - delegate_->Close(); -} - -- (void)onLinkClicked:(id)sender { - WindowOpenDisposition disposition = - ui::WindowOpenDispositionFromNSEvent([NSApp currentEvent]); - delegate_->LinkClicked(disposition); -} - -@end - -TabModalConfirmDialogMac::TabModalConfirmDialogMac( - TabModalConfirmDialogDelegate* delegate, - content::WebContents* web_contents) - : closing_(false), - delegate_(delegate) { - bridge_.reset([[TabModalConfirmDialogMacBridge alloc] - initWithDelegate:delegate]); - - alert_.reset([[ConstrainedWindowAlert alloc] init]); - [alert_ setMessageText: - l10n_util::FixUpWindowsStyleLabel(delegate->GetTitle())]; - [alert_ setLinkText:l10n_util::FixUpWindowsStyleLabel( - delegate->GetLinkText()) - target:bridge_ - action:@selector(onLinkClicked:)]; - [alert_ setInformativeText: - l10n_util::FixUpWindowsStyleLabel(delegate->GetDialogMessage())]; - [alert_ addButtonWithTitle: - l10n_util::FixUpWindowsStyleLabel(delegate->GetAcceptButtonTitle()) - keyEquivalent:kKeyEquivalentReturn - target:bridge_ - action:@selector(onAcceptButton:)]; - [alert_ addButtonWithTitle: - l10n_util::FixUpWindowsStyleLabel(delegate->GetCancelButtonTitle()) - keyEquivalent:kKeyEquivalentEscape - target:bridge_ - action:@selector(onCancelButton:)]; - [[alert_ closeButton] setTarget:bridge_]; - [[alert_ closeButton] setAction:@selector(onCloseButton:)]; - [alert_ layout]; - - base::scoped_nsobject<CustomConstrainedWindowSheet> sheet( - [[CustomConstrainedWindowSheet alloc] - initWithCustomWindow:[alert_ window]]); - window_ = CreateAndShowWebModalDialogMac(this, web_contents, sheet); - delegate_->set_close_delegate(this); -} - -TabModalConfirmDialogMac::~TabModalConfirmDialogMac() { -} - -void TabModalConfirmDialogMac::AcceptTabModalDialog() { - delegate_->Accept(); -} - -void TabModalConfirmDialogMac::CancelTabModalDialog() { - delegate_->Cancel(); -} - -void TabModalConfirmDialogMac::CloseDialog() { - if (!closing_) { - closing_ = true; - window_->CloseWebContentsModalDialog(); - } -} - -void TabModalConfirmDialogMac::OnConstrainedWindowClosed( - ConstrainedWindowMac* window) { - // If this method should mistakenly be called during Delegate::Close(), - // prevent a double-delete by moving delegate_ to a stack variable. - if (!delegate_) - return; - std::unique_ptr<TabModalConfirmDialogDelegate> delegate(std::move(delegate_)); - // Provide a disposition in case the dialog was closed without accepting or - // cancelling. - delegate->Close(); - delete this; -}
diff --git a/chrome/browser/ui/cocoa/tabs/tab_strip_controller.h b/chrome/browser/ui/cocoa/tabs/tab_strip_controller.h index dc19594c0..355b3b3 100644 --- a/chrome/browser/ui/cocoa/tabs/tab_strip_controller.h +++ b/chrome/browser/ui/cocoa/tabs/tab_strip_controller.h
@@ -19,7 +19,6 @@ @class CrTrackingArea; @class CustomWindowControlsView; -@class NewTabButtonCocoa; @class TabContentsController; @class TabControllerCocoa; @class TabViewCocoa; @@ -73,23 +72,15 @@ NSView* switchView_; // weak base::scoped_nsobject<NSView> dragBlockingView_; // avoid bad window server // drags - NewTabButtonCocoa* newTabButton_; // weak, obtained from the nib. - // The controller that manages all the interactions of dragging tabs. base::scoped_nsobject<TabStripDragController> dragController_; - // Tracks the newTabButton_ for rollovers. - base::scoped_nsobject<CrTrackingArea> newTabTrackingArea_; std::unique_ptr<TabStripModelObserverBridge> bridge_; Browser* browser_; // weak TabStripModel* tabStripModel_; // weak // Delegate that is informed about tab state changes. id<TabStripControllerDelegate> delegate_; // weak - // YES if the new tab button is currently displaying the hover image (if the - // mouse is currently over the button). - BOOL newTabButtonShowingHoverImage_; - // Access to the TabContentsControllers (which own the parent view // for the toolbar and associated tab contents) given an index. Call // |indexFromModelIndex:| to convert a |tabStripModel_| index to a @@ -116,8 +107,6 @@ // aren't coalesced, so we store frames to avoid redundant calls. base::scoped_nsobject<NSMutableDictionary> targetFrames_; NSRect newTabTargetFrame_; - // If YES, do not show the new tab button during layout. - BOOL forceNewTabButtonHidden_; // YES if we've successfully completed the initial layout. When this is // NO, we probably don't want to do any animation because we're just coming // into being. @@ -254,10 +243,6 @@ // tab strip, less the right indent for controls). - (CGFloat)tabAreaRightEdge; -// Show or hide the new tab button. The button is hidden immediately, but -// waits until the next call to |-layoutTabs| to show it again. -- (void)showNewTabButton:(BOOL)show; - // Force the tabs to rearrange themselves to reflect the current model. - (void)layoutTabs; - (void)layoutTabsWithoutAnimation;
diff --git a/chrome/browser/ui/cocoa/tabs/tab_strip_controller.mm b/chrome/browser/ui/cocoa/tabs/tab_strip_controller.mm index b2f3104..693cb3e 100644 --- a/chrome/browser/ui/cocoa/tabs/tab_strip_controller.mm +++ b/chrome/browser/ui/cocoa/tabs/tab_strip_controller.mm
@@ -35,7 +35,6 @@ #include "chrome/browser/ui/cocoa/drag_util.h" #import "chrome/browser/ui/cocoa/image_button_cell.h" #include "chrome/browser/ui/cocoa/l10n_util.h" -#import "chrome/browser/ui/cocoa/new_tab_button.h" #import "chrome/browser/ui/cocoa/tab_contents/favicon_util_mac.h" #import "chrome/browser/ui/cocoa/tab_contents/tab_contents_controller.h" #import "chrome/browser/ui/cocoa/tabs/alert_indicator_button_cocoa.h" @@ -91,9 +90,6 @@ // The amount by which pinned tabs are separated from normal tabs. const CGFloat kLastPinnedTabSpacing = 2.0; -// The amount by which the new tab button is offset (from the tabs). -const CGFloat kNewTabButtonOffset = 10.0; - const NSTimeInterval kTabAnimationDuration = 0.125; // Helper class for doing NSAnimationContext calls that takes a bool to disable @@ -172,7 +168,6 @@ forController:(TabControllerCocoa*)controller finished:(BOOL)finished; - (NSInteger)indexFromModelIndex:(NSInteger)index; -- (void)clickNewTabButton:(id)sender; - (NSInteger)numberOfOpenTabs; - (NSInteger)numberOfOpenPinnedTabs; - (NSInteger)numberOfOpenNonPinnedTabs; @@ -182,7 +177,6 @@ givesIndex:(NSInteger*)index disposition:(WindowOpenDisposition*)disposition activateTab:(BOOL)activateTab; -- (void)setNewTabButtonHoverState:(BOOL)showHover; - (void)themeDidChangeNotification:(NSNotification*)notification; - (BOOL)doesAnyOtherWebContents:(content::WebContents*)selected haveAlertState:(TabAlertState)state; @@ -453,25 +447,8 @@ controller:self]); [self addSubviewToPermanentList:dragBlockingView_]; - newTabButton_ = [view getNewTabButton]; - [newTabButton_ setWantsLayer:YES]; - [self addSubviewToPermanentList:newTabButton_]; - [newTabButton_ setTarget:self]; - [newTabButton_ setAction:@selector(clickNewTabButton:)]; - - newTabButtonShowingHoverImage_ = NO; - newTabTrackingArea_.reset( - [[CrTrackingArea alloc] initWithRect:[newTabButton_ bounds] - options:(NSTrackingMouseEnteredAndExited | - NSTrackingActiveAlways) - owner:self - userInfo:nil]); - if (browserWindow) // Nil for Browsers without a tab strip (e.g. popups). - [newTabTrackingArea_ clearOwnerWhenWindowWillClose:browserWindow]; - [newTabButton_ addTrackingArea:newTabTrackingArea_.get()]; targetFrames_.reset([[NSMutableDictionary alloc] init]); - newTabTargetFrame_ = NSZeroRect; availableResizeWidth_ = kUseFullAvailableWidth; closingControllers_.reset([[NSMutableSet alloc] init]); @@ -515,12 +492,6 @@ mouseInside_ = YES; } - // Set accessibility descriptions. http://openradar.appspot.com/7496255 - NSString* description = l10n_util::GetNSStringWithFixup(IDS_ACCNAME_NEWTAB); - [[newTabButton_ cell] - accessibilitySetOverrideValue:description - forAttribute:NSAccessibilityDescriptionAttribute]; - // Controller may have been (re-)created by switching layout modes, which // means the tab model is already fully formed with tabs. Need to walk the // list and create the UI for each. @@ -565,7 +536,6 @@ if (trackingArea_.get()) [tabStripView_ removeTrackingArea:trackingArea_.get()]; - [newTabButton_ removeTrackingArea:newTabTrackingArea_.get()]; // Invalidate all closing animations so they don't call back to us after // we're gone. for (TabControllerCocoa* controller in closingControllers_.get()) { @@ -642,14 +612,6 @@ return controller; } -// (Private) Handles a click on the new tab button. -- (void)clickNewTabButton:(id)sender { - base::RecordAction(UserMetricsAction("NewTab_Button")); - UMA_HISTOGRAM_ENUMERATION("Tab.NewTab", TabStripModel::NEW_TAB_BUTTON, - TabStripModel::NEW_TAB_ENUM_COUNT); - tabStripModel_->delegate()->AddTabAt(GURL(), -1, true); -} - // (Private) Returns the number of open tabs in the tab strip. This is the // number of TabControllers we know about (as there's a 1-to-1 mapping from // these controllers to a tab) less the number of closing tabs. @@ -922,12 +884,6 @@ return NSMaxX([tabStripView_ frame]) - rightEdge; } -- (void)showNewTabButton:(BOOL)show { - forceNewTabButtonHidden_ = show ? NO : YES; - if (forceNewTabButtonHidden_) - [newTabButton_ setHidden:YES]; -} - // Lay out all tabs in the order of their TabContentsControllers, which matches // the ordering in the TabStripModel. This call isn't that expensive, though // it is O(n) in the number of tabs. Tabs will animate to their new position @@ -964,9 +920,6 @@ } else { availableSpace = NSWidth([tabStripView_ frame]); - // Account for the width of the new tab button. - availableSpace -= - NSWidth([newTabButton_ frame]) + kNewTabButtonOffset - kTabOverlap; // Account for the trailing controls if not in rapid closure mode. // (In rapid closure mode, the available width is set based on the // position of the trailing tab, not based on the width of the tab strip, @@ -1185,58 +1138,6 @@ offset -= kTabOverlap; } - // Hide the new tab button if we're explicitly told to. It may already - // be hidden, doing it again doesn't hurt. Otherwise position it - // appropriately, showing it if necessary. - if (forceNewTabButtonHidden_) { - [newTabButton_ setHidden:YES]; - } else { - NSRect newTabNewFrame = [newTabButton_ frame]; - // We've already ensured there's enough space for the new tab button - // so we don't have to check it against the available space. We do need - // to make sure we put it after any placeholder. - CGFloat maxTabX = MAX(offset, NSMaxX(placeholderFrame_) - kTabOverlap); - if (cocoa_l10n_util::ShouldDoExperimentalRTLLayout()) { - maxTabX = FlipXInView(tabStripView_, [newTabButton_ frame].size.width, - maxTabX) - - (2 * kNewTabButtonOffset); - } - newTabNewFrame.origin = NSMakePoint(maxTabX + kNewTabButtonOffset, 0); - if ([tabContentsArray_ count]) - [newTabButton_ setHidden:NO]; - - if (!NSEqualRects(newTabTargetFrame_, newTabNewFrame)) { - // Set the new tab button image correctly based on where the cursor is. - NSWindow* window = [tabStripView_ window]; - NSPoint currentMouse = [window mouseLocationOutsideOfEventStream]; - currentMouse = [tabStripView_ convertPoint:currentMouse fromView:nil]; - - BOOL shouldShowHover = [newTabButton_ pointIsOverButton:currentMouse]; - [self setNewTabButtonHoverState:shouldShowHover]; - - // Move the new tab button into place. We want to animate the new tab - // button if it's moving back (closing a tab), but not when it's - // moving forward (inserting a new tab). If moving forward, we need - // to use a very small duration to make sure we cancel any in-flight - // animation to the left. - if (visible && animate) { - ScopedNSAnimationContextGroup localAnimationGroup(true); - BOOL movingBack = NSMinX(newTabNewFrame) < NSMinX(newTabTargetFrame_); - if (cocoa_l10n_util::ShouldDoExperimentalRTLLayout()) - movingBack = !movingBack; - - if (!movingBack) { - localAnimationGroup.SetCurrentContextShortestDuration(); - } - [[newTabButton_ animator] setFrame:newTabNewFrame]; - newTabTargetFrame_ = newTabNewFrame; - } else { - [newTabButton_ setFrame:newTabNewFrame]; - newTabTargetFrame_ = newTabNewFrame; - } - } - } - [dragBlockingView_ setFrame:enclosingRect]; // Mark that we've successfully completed layout of at least one tab. @@ -1886,11 +1787,6 @@ // Use hit test to figure out what view we are hovering over. NSView* targetView = [tabStripView_ hitTest:[event locationInWindow]]; - // Set the new tab button hover state iff the mouse is over the button. - BOOL shouldShowHoverImage = - [targetView isKindOfClass:[NewTabButtonCocoa class]]; - [self setNewTabButtonHoverState:shouldShowHoverImage]; - TabViewCocoa* tabView = base::mac::ObjCCast<TabViewCocoa>(targetView); if (!tabView) tabView = base::mac::ObjCCast<TabViewCocoa>([targetView superview]); @@ -1924,12 +1820,6 @@ availableResizeWidth_ = kUseFullAvailableWidth; [self setHoveredTab:nil]; [self layoutTabs]; - } else if ([area isEqual:newTabTrackingArea_]) { - // If the mouse is moved quickly enough, it is possible for the mouse to - // leave the tabstrip without sending any mouseMoved: messages at all. - // Since this would result in the new tab button incorrectly staying in the - // hover state, disable the hover image on every mouse exit. - [self setNewTabButtonHoverState:NO]; } else if ([area isEqual:customWindowControlsTrackingArea_]) { [customWindowControls_ setMouseInside:NO]; } @@ -1985,18 +1875,6 @@ } } -// Sets the new tab button's image based on the current hover state. Does -// nothing if the hover state is already correct. -- (void)setNewTabButtonHoverState:(BOOL)shouldShowHover { - if (shouldShowHover && !newTabButtonShowingHoverImage_) { - newTabButtonShowingHoverImage_ = YES; - [[newTabButton_ cell] setIsMouseInside:YES]; - } else if (!shouldShowHover && newTabButtonShowingHoverImage_) { - newTabButtonShowingHoverImage_ = NO; - [[newTabButton_ cell] setIsMouseInside:NO]; - } -} - // Adds the given subview to (the end of) the list of permanent subviews // (specified from bottom up). These subviews will always be below the // transitory subviews (tabs). |-regenerateSubviewList| must be called to @@ -2417,7 +2295,6 @@ } - (void)themeDidChangeNotification:(NSNotification*)notification { - [newTabButton_ setImages]; for (int i = 0; i < tabStripModel_->count(); i++) { [self updateIconsForContents:tabStripModel_->GetWebContentsAt(i) atIndex:i]; }
diff --git a/chrome/browser/ui/cocoa/tabs/tab_strip_controller_unittest.mm b/chrome/browser/ui/cocoa/tabs/tab_strip_controller_unittest.mm index 03a6c116..2437d52d 100644 --- a/chrome/browser/ui/cocoa/tabs/tab_strip_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/tabs/tab_strip_controller_unittest.mm
@@ -10,7 +10,6 @@ #include "chrome/browser/media/webrtc/media_stream_capture_indicator.h" #include "chrome/browser/ui/browser_window.h" #import "chrome/browser/ui/cocoa/browser_window_controller.h" -#import "chrome/browser/ui/cocoa/new_tab_button.h" #import "chrome/browser/ui/cocoa/tabs/tab_controller.h" #import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h" #import "chrome/browser/ui/cocoa/tabs/tab_strip_view.h" @@ -134,11 +133,6 @@ tab_strip_.reset( [[TabStripView alloc] initWithFrame:strip_frame]); [parent addSubview:tab_strip_.get()]; - NSRect button_frame = NSMakeRect(0, 0, 15, 15); - base::scoped_nsobject<NewTabButtonCocoa> new_tab_button( - [[NewTabButtonCocoa alloc] initWithFrame:button_frame]); - [tab_strip_ addSubview:new_tab_button.get()]; - [tab_strip_ setNewTabButton:new_tab_button.get()]; delegate_.reset(new TestTabStripModelDelegate()); model_ = browser()->tab_strip_model();
diff --git a/chrome/browser/ui/cocoa/tabs/tab_strip_view.h b/chrome/browser/ui/cocoa/tabs/tab_strip_view.h index 4a2809b..d18acca 100644 --- a/chrome/browser/ui/cocoa/tabs/tab_strip_view.h +++ b/chrome/browser/ui/cocoa/tabs/tab_strip_view.h
@@ -11,7 +11,6 @@ #import "chrome/browser/ui/cocoa/background_gradient_view.h" #import "chrome/browser/ui/cocoa/url_drop_target.h" -@class NewTabButtonCocoa; @class TabStripControllerCocoa; // A view class that handles rendering the tab strip and drops of URLS with @@ -26,8 +25,6 @@ // Handles being a drag-and-drop target. base::scoped_nsobject<URLDropTargetHandler> dropHandler_; - base::scoped_nsobject<NewTabButtonCocoa> newTabButton_; - // Whether the drop-indicator arrow is shown, and if it is, the coordinate of // its tip. BOOL dropArrowShown_; @@ -40,10 +37,6 @@ @property(assign, nonatomic) NSPoint dropArrowPosition; @property(assign, nonatomic) BOOL inATabDraggingOverlayWindow; -// Name starts with "get" because methods staring with "new" return retained -// objects according to Cocoa's create rule. -- (NewTabButtonCocoa*)getNewTabButton; - // Leaving visual effects enabled when fullscreen results in higher power // consumption. This is used to disable effects when fullscreen. - (void)setVisualEffectsDisabledForFullscreen:(BOOL)fullscreen; @@ -61,8 +54,4 @@ - (BOOL)doubleClickMinimizesWindow; @end -@interface TabStripView (TestingAPI) -- (void)setNewTabButton:(NewTabButtonCocoa*)button; -@end - #endif // CHROME_BROWSER_UI_COCOA_TABS_TAB_STRIP_VIEW_H_
diff --git a/chrome/browser/ui/cocoa/tabs/tab_strip_view.mm b/chrome/browser/ui/cocoa/tabs/tab_strip_view.mm index d6ac6b3..42f4b76 100644 --- a/chrome/browser/ui/cocoa/tabs/tab_strip_view.mm +++ b/chrome/browser/ui/cocoa/tabs/tab_strip_view.mm
@@ -14,7 +14,6 @@ #include "chrome/browser/themes/theme_service.h" #import "chrome/browser/ui/cocoa/browser_window_controller.h" #import "chrome/browser/ui/cocoa/browser_window_layout.h" -#import "chrome/browser/ui/cocoa/new_tab_button.h" #import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h" #import "chrome/browser/ui/cocoa/tabs/tab_view.h" #import "chrome/browser/ui/cocoa/view_id_util.h" @@ -36,10 +35,6 @@ - (id)initWithFrame:(NSRect)frame { self = [super initWithFrame:frame]; if (self) { - newTabButton_.reset( - [[NewTabButtonCocoa alloc] initWithFrame:NSMakeRect(295, 0, 40, 27)]); - [newTabButton_ setToolTip:l10n_util::GetNSString(IDS_TOOLTIP_NEW_TAB)]; - // Set lastMouseUp_ = -1000.0 so that timestamp-lastMouseUp_ is big unless // lastMouseUp_ has been reset. lastMouseUp_ = -1000.0; @@ -347,14 +342,6 @@ return VIEW_ID_TAB_STRIP; } -- (NewTabButtonCocoa*)getNewTabButton { - return newTabButton_; -} - -- (void)setNewTabButton:(NewTabButtonCocoa*)button { - newTabButton_.reset([button retain]); -} - - (NSVisualEffectView*)visualEffectView API_AVAILABLE(macos(10.10)) { return [[BrowserWindowController browserWindowControllerForWindow:[self window]] visualEffectView];
diff --git a/chrome/browser/ui/cocoa/toolbar/toolbar_controller.h b/chrome/browser/ui/cocoa/toolbar/toolbar_controller.h index a51b4a3b..0eb8782 100644 --- a/chrome/browser/ui/cocoa/toolbar/toolbar_controller.h +++ b/chrome/browser/ui/cocoa/toolbar/toolbar_controller.h
@@ -160,9 +160,6 @@ // associated window's coordinate system. - (NSPoint)bookmarkBubblePoint; -// Point on the save credit card icon for the save credit card bubble. -- (NSPoint)saveCreditCardBubblePoint; - // Point in the window's coordinate system for bubbles attached to the app menu. - (NSPoint)appMenuBubblePoint;
diff --git a/chrome/browser/ui/cocoa/toolbar/toolbar_controller.mm b/chrome/browser/ui/cocoa/toolbar/toolbar_controller.mm index 752f24aac..10ac463 100644 --- a/chrome/browser/ui/cocoa/toolbar/toolbar_controller.mm +++ b/chrome/browser/ui/cocoa/toolbar/toolbar_controller.mm
@@ -37,7 +37,6 @@ #import "chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_editor.h" #import "chrome/browser/ui/cocoa/location_bar/location_bar_decoration.h" #import "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" -#import "chrome/browser/ui/cocoa/location_bar/star_decoration.h" #import "chrome/browser/ui/cocoa/menu_button.h" #import "chrome/browser/ui/cocoa/toolbar/app_toolbar_button.h" #import "chrome/browser/ui/cocoa/toolbar/app_toolbar_button_cell.h" @@ -633,11 +632,9 @@ } - (void)setStarredState:(BOOL)isStarred { - locationBarView_->SetStarred(isStarred); } - (void)setTranslateIconLit:(BOOL)on { - locationBarView_->SetTranslateIconLit(on); } - (void)zoomChangedForActiveTab:(BOOL)canShowBubble { @@ -952,17 +949,9 @@ } - (NSPoint)bookmarkBubblePoint { - if (locationBarView_->IsStarEnabled()) - return locationBarView_->GetBubblePointForDecoration( - locationBarView_->star_decoration()); - return [self appMenuBubblePoint]; } -- (NSPoint)saveCreditCardBubblePoint { - return locationBarView_->GetSaveCreditCardBubblePoint(); -} - - (NSPoint)appMenuBubblePoint { NSRect frame = appMenuButton_.frame; NSPoint point = NSMakePoint(NSMaxX(frame), NSMinY(frame));
diff --git a/chrome/browser/ui/cocoa/toolbar/toolbar_controller_unittest.mm b/chrome/browser/ui/cocoa/toolbar/toolbar_controller_unittest.mm index 560167e..1713eb15 100644 --- a/chrome/browser/ui/cocoa/toolbar/toolbar_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/toolbar/toolbar_controller_unittest.mm
@@ -22,7 +22,6 @@ #import "chrome/browser/ui/cocoa/extensions/browser_actions_controller.h" #import "chrome/browser/ui/cocoa/image_button_cell.h" #import "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" -#import "chrome/browser/ui/cocoa/location_bar/translate_decoration.h" #include "chrome/browser/ui/cocoa/test/cocoa_profile_test.h" #include "chrome/browser/ui/cocoa/test/scoped_force_rtl_mac.h" #import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h" @@ -379,16 +378,6 @@ EXPECT_NSEQ(locationBarFrame, newLocationBarFrame); } -TEST_F(ToolbarControllerTest, TranslateBubblePoint) { - LocationBarViewMac* locationBarBridge = [bar_ locationBarBridge]; - LocationBarDecoration* decoration = locationBarBridge->translate_decoration(); - const NSPoint translatePoint = - locationBarBridge->GetBubblePointForDecoration(decoration); - const NSRect barFrame = - [[bar_ view] convertRect:[[bar_ view] bounds] toView:nil]; - EXPECT_TRUE(NSPointInRect(translatePoint, barFrame)); -} - TEST_F(ToolbarControllerTest, HoverButtonForEvent) { base::scoped_nsobject<HitView> view( [[HitView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)]);
diff --git a/chrome/browser/ui/cocoa/translate/translate_bubble_bridge_views.h b/chrome/browser/ui/cocoa/translate/translate_bubble_bridge_views.h deleted file mode 100644 index 669223c..0000000 --- a/chrome/browser/ui/cocoa/translate/translate_bubble_bridge_views.h +++ /dev/null
@@ -1,26 +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_UI_COCOA_TRANSLATE_BUBBLE_BRIDGE_VIEWS_H_ -#define CHROME_BROWSER_UI_COCOA_TRANSLATE_BUBBLE_BRIDGE_VIEWS_H_ - -#include <Cocoa/Cocoa.h> - -#include "components/translate/core/browser/translate_step.h" -#include "components/translate/core/common/translate_errors.h" - -namespace content { -class WebContents; -} - -class LocationBarViewMac; - -void ShowTranslateBubbleViews(NSWindow* parent_window, - LocationBarViewMac* location_bar, - content::WebContents* web_contents, - translate::TranslateStep step, - translate::TranslateErrors::Type error_type, - bool is_user_gesture); - -#endif // CHROME_BROWSER_UI_COCOA_TRANSLATE_BUBBLE_BRIDGE_VIEWS_H_
diff --git a/chrome/browser/ui/cocoa/translate/translate_bubble_bridge_views.mm b/chrome/browser/ui/cocoa/translate/translate_bubble_bridge_views.mm deleted file mode 100644 index bd25d9fc..0000000 --- a/chrome/browser/ui/cocoa/translate/translate_bubble_bridge_views.mm +++ /dev/null
@@ -1,33 +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 "chrome/browser/ui/cocoa/translate/translate_bubble_bridge_views.h" - -#include "chrome/browser/ui/cocoa/bubble_anchor_helper_views.h" -#include "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" -#include "chrome/browser/ui/cocoa/location_bar/translate_decoration.h" -#include "chrome/browser/ui/views/translate/translate_bubble_view.h" -#include "ui/base/cocoa/cocoa_base_utils.h" -#include "ui/gfx/mac/coordinate_conversion.h" - -void ShowTranslateBubbleViews(NSWindow* parent_window, - LocationBarViewMac* location_bar, - content::WebContents* web_contents, - translate::TranslateStep step, - translate::TranslateErrors::Type error_type, - bool is_user_gesture) { - gfx::Point anchor_point = - gfx::ScreenPointFromNSPoint(ui::ConvertPointFromWindowToScreen( - parent_window, location_bar->GetBubblePointForDecoration( - location_bar->translate_decoration()))); - TranslateBubbleView::DisplayReason reason = - is_user_gesture ? TranslateBubbleView::USER_GESTURE - : TranslateBubbleView::AUTOMATIC; - TranslateBubbleView::ShowBubble(nullptr, nullptr, anchor_point, web_contents, - step, error_type, reason); - if (TranslateBubbleView::GetCurrentBubble()) { - KeepBubbleAnchored(TranslateBubbleView::GetCurrentBubble(), - location_bar->translate_decoration()); - } -}
diff --git a/chrome/browser/ui/tab_modal_confirm_dialog.h b/chrome/browser/ui/tab_modal_confirm_dialog.h index 9468bdf..9ecc4ba0 100644 --- a/chrome/browser/ui/tab_modal_confirm_dialog.h +++ b/chrome/browser/ui/tab_modal_confirm_dialog.h
@@ -19,14 +19,6 @@ // the dialog. static TabModalConfirmDialog* Create(TabModalConfirmDialogDelegate* delegate, content::WebContents* web_contents); -#if defined(OS_MACOSX) - // Temporary shim for Polychrome. See bottom of first comment in - // https://crbug.com/80495 for details. - static TabModalConfirmDialog* CreateCocoa( - TabModalConfirmDialogDelegate* delegate, - content::WebContents* web_contents); -#endif - // Accepts the dialog. virtual void AcceptTabModalDialog() = 0;
diff --git a/chrome/browser/ui/views/autofill/autofill_popup_view_native_views.cc b/chrome/browser/ui/views/autofill/autofill_popup_view_native_views.cc index 0489bfb..d0b03e3 100644 --- a/chrome/browser/ui/views/autofill/autofill_popup_view_native_views.cc +++ b/chrome/browser/ui/views/autofill/autofill_popup_view_native_views.cc
@@ -77,8 +77,10 @@ // Describes the possible layouts which can be applied to the rows in the popup. enum class PopupItemLayoutType { - kLeadingIcon, // Icon (if any) shown on the leading (left in LTR) side. - kTrailingIcon // Icon (if any) shown on the trailing (right in LTR) side. + kLeadingIcon, // Icon (if any) shown on the leading (left in LTR) side. + kTrailingIcon, // Icon (if any) shown on the trailing (right in LTR) side. + kTwoLinesLeadingIcon, // Icon (if any) shown on the leading (left in LTR) + // side with two line display. }; // By default, this returns kLeadingIcon for passwords and kTrailingIcon for all @@ -91,6 +93,8 @@ return PopupItemLayoutType::kLeadingIcon; case ForcedPopupLayoutState::kTrailingIcon: return PopupItemLayoutType::kTrailingIcon; + case ForcedPopupLayoutState::kTwoLinesLeadingIcon: + return PopupItemLayoutType::kTwoLinesLeadingIcon; case ForcedPopupLayoutState::kDefault: switch (frontend_id) { case autofill::PopupItemId::POPUP_ITEM_ID_USERNAME_ENTRY: @@ -167,6 +171,7 @@ void CreateContent() override; void RefreshStyle() override; + PopupItemLayoutType layout_type() const { return layout_type_; } virtual int GetPrimaryTextStyle() = 0; virtual views::View* CreateValueLabel(); // Creates an optional label below the value. @@ -176,6 +181,10 @@ // Creates a label matching the style of the description label. views::Label* CreateSecondaryLabel(const base::string16& text) const; + // Creates a label with a specific context and style. + views::Label* CreateLabelWithStyleAndContext(const base::string16& text, + int text_context, + int text_style) const; // Sets |font_weight| as the font weight to be used for primary information on // the current item. Returns false if no custom font weight is undefined. @@ -210,6 +219,8 @@ int GetPrimaryTextStyle() override; bool ShouldUseCustomFontWeightForPrimaryInfo( gfx::Font::Weight* font_weight) const override; + views::View* CreateSubtextLabel() override; + views::View* CreateDescriptionLabel() override; AutofillPopupSuggestionView(AutofillPopupViewNativeViews* popup_view, int line_number); @@ -332,6 +343,8 @@ std::vector<base::string16> text; text.push_back(suggestion.value); text.push_back(suggestion.label); + // When two-line display is enabled, this value will be filled and may + // repeat information already provided in the label. text.push_back(suggestion.additional_label); base::string16 icon_description; @@ -386,6 +399,7 @@ void AutofillPopupItemView::CreateContent() { AutofillPopupController* controller = popup_view_->controller(); + auto* layout_manager = SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::kHorizontal, gfx::Insets(0, GetHorizontalMargin()))); @@ -395,14 +409,17 @@ const gfx::ImageSkia icon = controller->layout_model().GetIconImage(line_number_); - if (!icon.isNull() && layout_type_ == PopupItemLayoutType::kLeadingIcon) { + if (!icon.isNull() && + (layout_type_ == PopupItemLayoutType::kLeadingIcon || + layout_type_ == PopupItemLayoutType::kTwoLinesLeadingIcon)) { AddIcon(icon); AddSpacerWithSize(views::MenuConfig::instance().item_horizontal_padding, /*resize=*/false, layout_manager); } - views::View* value_label = CreateValueLabel(); views::View* lower_value_label = CreateSubtextLabel(); + views::View* value_label = CreateValueLabel(); + const int kStandardRowHeight = views::MenuConfig::instance().touchable_menu_height + extra_height_; if (!lower_value_label) { @@ -454,7 +471,7 @@ return CreateSecondaryLabel(text); } - views::Label* text_label = CreateLabelWithColorReadabilityDisabled( + views::Label* text_label = CreateLabelWithStyleAndContext( popup_view_->controller()->GetElidedValueAt(line_number_), ChromeTextContext::CONTEXT_BODY_TEXT_LARGE, GetPrimaryTextStyle()); @@ -463,7 +480,6 @@ text_label->SetFontList( text_label->font_list().DeriveWithWeight(font_weight)); } - text_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); return text_label; } @@ -480,12 +496,20 @@ views::Label* AutofillPopupItemView::CreateSecondaryLabel( const base::string16& text) const { - views::Label* subtext_label = CreateLabelWithColorReadabilityDisabled( + return CreateLabelWithStyleAndContext( text, ChromeTextContext::CONTEXT_BODY_TEXT_LARGE, ChromeTextStyle::STYLE_SECONDARY); - subtext_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); +} - return subtext_label; +views::Label* AutofillPopupItemView::CreateLabelWithStyleAndContext( + const base::string16& text, + int text_context, + int text_style) const { + views::Label* label = + CreateLabelWithColorReadabilityDisabled(text, text_context, text_style); + label->SetHorizontalAlignment(gfx::ALIGN_LEFT); + + return label; } void AutofillPopupItemView::AddIcon(gfx::ImageSkia icon) { @@ -551,6 +575,30 @@ SetFocusBehavior(FocusBehavior::ALWAYS); } +views::View* AutofillPopupSuggestionView::CreateDescriptionLabel() { + // When two-line display is enabled, don't display the description. + if (layout_type() == PopupItemLayoutType::kTwoLinesLeadingIcon) + return nullptr; + return AutofillPopupItemView::CreateDescriptionLabel(); +} + +views::View* AutofillPopupSuggestionView::CreateSubtextLabel() { + // When two-line display is disabled, use the default behavior for the popup + // item. + if (layout_type() != PopupItemLayoutType::kTwoLinesLeadingIcon) + return AutofillPopupItemView::CreateSubtextLabel(); + + base::string16 label_text = + popup_view_->controller()->GetSuggestionAt(line_number_).additional_label; + if (label_text.empty()) + return nullptr; + + views::Label* label = CreateLabelWithStyleAndContext( + label_text, ChromeTextContext::CONTEXT_BODY_TEXT_SMALL, + ChromeTextStyle::STYLE_SECONDARY); + return label; +} + /************** PasswordPopupSuggestionView **************/ PasswordPopupSuggestionView* PasswordPopupSuggestionView::Create(
diff --git a/chrome/browser/ui/views/autofill/autofill_popup_view_views.cc b/chrome/browser/ui/views/autofill/autofill_popup_view_views.cc index baccd57..35600fbd 100644 --- a/chrome/browser/ui/views/autofill/autofill_popup_view_views.cc +++ b/chrome/browser/ui/views/autofill/autofill_popup_view_views.cc
@@ -12,7 +12,6 @@ #include "chrome/browser/ui/autofill/autofill_popup_controller.h" #include "chrome/browser/ui/autofill/autofill_popup_layout_model.h" #include "chrome/browser/ui/views/autofill/autofill_popup_view_native_views.h" -#include "chrome/browser/ui/views_mode_controller.h" #include "components/autofill/core/browser/popup_item_ids.h" #include "components/autofill/core/browser/suggestion.h" #include "components/autofill/core/common/autofill_features.h" @@ -344,9 +343,6 @@ AutofillPopupView* AutofillPopupView::Create( AutofillPopupController* controller) { #if defined(OS_MACOSX) - if (!features::IsMacViewsAutofillPopupExperimentEnabled()) - return CreateCocoa(controller); - // It's possible for the container_view to not be in a window. In that case, // cancel the popup since we can't fully set it up. if (!platform_util::GetTopLevel(controller->container_view()))
diff --git a/chrome/browser/ui/views/exclusive_access_bubble_views_interactive_uitest.cc b/chrome/browser/ui/views/exclusive_access_bubble_views_interactive_uitest.cc index 9629e512..30f8edc 100644 --- a/chrome/browser/ui/views/exclusive_access_bubble_views_interactive_uitest.cc +++ b/chrome/browser/ui/views/exclusive_access_bubble_views_interactive_uitest.cc
@@ -38,17 +38,11 @@ DISALLOW_COPY_AND_ASSIGN(ExclusiveAccessBubbleViewsTest); }; -#if defined(OS_MACOSX) -// Encounters an internal MacOS assert: http://crbug.com/823490 -#define MAYBE_NativeClose DISABLED_NativeClose -#else -#define MAYBE_NativeClose NativeClose -#endif // Simulate obscure codepaths resulting in the bubble Widget being closed before // the ExclusiveAccessBubbleViews destructor asks for it. If a close bypasses // the destructor, animations could still be running that attempt to manipulate // a destroyed Widget and crash. -IN_PROC_BROWSER_TEST_F(ExclusiveAccessBubbleViewsTest, MAYBE_NativeClose) { +IN_PROC_BROWSER_TEST_F(ExclusiveAccessBubbleViewsTest, NativeClose) { EXPECT_FALSE(bubble()); EnterActiveTabFullscreen(); EXPECT_TRUE(bubble());
diff --git a/chrome/browser/ui/views/extensions/media_galleries_dialog_views.cc b/chrome/browser/ui/views/extensions/media_galleries_dialog_views.cc index 7e5db80..fad9f3d 100644 --- a/chrome/browser/ui/views/extensions/media_galleries_dialog_views.cc +++ b/chrome/browser/ui/views/extensions/media_galleries_dialog_views.cc
@@ -12,7 +12,6 @@ #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/views/extensions/media_gallery_checkbox_view.h" -#include "chrome/browser/ui/views_mode_controller.h" #include "chrome/grit/generated_resources.h" #include "chrome/grit/locale_settings.h" #include "components/constrained_window/constrained_window_views.h" @@ -333,9 +332,5 @@ // static MediaGalleriesDialog* MediaGalleriesDialog::Create( MediaGalleriesDialogController* controller) { -#if defined(OS_MACOSX) - if (views_mode_controller::IsViewsBrowserCocoa()) - return MediaGalleriesDialog::CreateCocoa(controller); -#endif return new MediaGalleriesDialogViews(controller); }
diff --git a/chrome/browser/ui/views/frame/browser_view_interactive_uitest.cc b/chrome/browser/ui/views/frame/browser_view_interactive_uitest.cc index d1300a4..a5d8d38d 100644 --- a/chrome/browser/ui/views/frame/browser_view_interactive_uitest.cc +++ b/chrome/browser/ui/views/frame/browser_view_interactive_uitest.cc
@@ -28,6 +28,15 @@ BrowserViewTest() = default; ~BrowserViewTest() override = default; + void InitPrefSettings() { +#if defined(OS_MACOSX) + // Set the preference to true so we expect to see the top view in + // fullscreen mode. + PrefService* prefs = browser()->profile()->GetPrefs(); + prefs->SetBoolean(prefs::kShowFullscreenToolbar, true); +#endif + } + private: test::ScopedMacViewsBrowserMode views_mode_{true}; @@ -36,20 +45,16 @@ } // namespace -#if defined(OS_MACOSX) -// Encounters an internal MacOS assert: http://crbug.com/823490 -#define MAYBE_FullscreenClearsFocus DISABLED_FullscreenClearsFocus -#else -#define MAYBE_FullscreenClearsFocus FullscreenClearsFocus -#endif -IN_PROC_BROWSER_TEST_F(BrowserViewTest, MAYBE_FullscreenClearsFocus) { +IN_PROC_BROWSER_TEST_F(BrowserViewTest, FullscreenClearsFocus) { BrowserView* browser_view = static_cast<BrowserView*>(browser()->window()); + InitPrefSettings(); LocationBarView* location_bar_view = browser_view->GetLocationBarView(); FocusManager* focus_manager = browser_view->GetFocusManager(); // Focus starts in the location bar or one of its children. EXPECT_TRUE(location_bar_view->Contains(focus_manager->GetFocusedView())); + // Enter into fullscreen mode. chrome::ToggleFullscreenMode(browser()); EXPECT_TRUE(browser_view->IsFullscreen()); @@ -61,12 +66,7 @@ // correctly in browser fullscreen mode. IN_PROC_BROWSER_TEST_F(BrowserViewTest, BrowserFullscreenShowTopView) { BrowserView* browser_view = static_cast<BrowserView*>(browser()->window()); -#if defined(OS_MACOSX) - // First, set the preference to true so we expect to see the top view in - // fullscreen mode. - PrefService* prefs = browser()->profile()->GetPrefs(); - prefs->SetBoolean(prefs::kShowFullscreenToolbar, true); -#endif + InitPrefSettings(); // The top view should always show up in regular mode. EXPECT_FALSE(browser_view->IsFullscreen());
diff --git a/chrome/browser/ui/views/overlay/overlay_window_views.cc b/chrome/browser/ui/views/overlay/overlay_window_views.cc index 8b52783..48955f92 100644 --- a/chrome/browser/ui/views/overlay/overlay_window_views.cc +++ b/chrome/browser/ui/views/overlay/overlay_window_views.cc
@@ -320,9 +320,11 @@ } void OverlayWindowViews::UpdateControlsVisibility(bool is_visible) { - GetControlsScrimLayer()->SetVisible(is_visible); GetCloseControlsLayer()->SetVisible(is_visible); - GetControlsParentLayer()->SetVisible(is_visible); + GetControlsScrimLayer()->SetVisible( + (playback_state_ == kNoVideo) ? false : is_visible); + GetControlsParentLayer()->SetVisible( + (playback_state_ == kNoVideo) ? false : is_visible); } void OverlayWindowViews::UpdateControlsBounds() { @@ -509,24 +511,28 @@ // TODO(apacible): have machine state for controls visibility. bool controls_parent_layer_visible = GetControlsParentLayer()->visible(); - switch (playback_state) { + playback_state_ = playback_state; + + switch (playback_state_) { case kPlaying: play_pause_controls_view_->SetToggled(true); controls_parent_view_->SetVisible(true); video_view_->SetVisible(true); + GetControlsParentLayer()->SetVisible(controls_parent_layer_visible); break; case kPaused: play_pause_controls_view_->SetToggled(false); controls_parent_view_->SetVisible(true); video_view_->SetVisible(true); + GetControlsParentLayer()->SetVisible(controls_parent_layer_visible); break; case kNoVideo: + controls_scrim_view_->SetVisible(false); controls_parent_view_->SetVisible(false); video_view_->SetVisible(false); + GetControlsParentLayer()->SetVisible(false); break; } - - GetControlsParentLayer()->SetVisible(controls_parent_layer_visible); } void OverlayWindowViews::SetPictureInPictureCustomControls(
diff --git a/chrome/browser/ui/views/overlay/overlay_window_views.h b/chrome/browser/ui/views/overlay/overlay_window_views.h index f7b16fb..38998aa 100644 --- a/chrome/browser/ui/views/overlay/overlay_window_views.h +++ b/chrome/browser/ui/views/overlay/overlay_window_views.h
@@ -138,6 +138,10 @@ // components has been initialized. bool has_been_shown_ = false; + // Current playback state on the video in Picture-in-Picture window. It is + // used to show/hide controls. + PlaybackState playback_state_ = kNoVideo; + // The upper and lower bounds of |current_size_|. These are determined by the // size of the primary display work area when Picture-in-Picture is initiated. // TODO(apacible): Update these bounds when the display the window is on
diff --git a/chrome/browser/ui/views/tab_modal_confirm_dialog_views.cc b/chrome/browser/ui/views/tab_modal_confirm_dialog_views.cc index 5ddf322..2b4715d 100644 --- a/chrome/browser/ui/views/tab_modal_confirm_dialog_views.cc +++ b/chrome/browser/ui/views/tab_modal_confirm_dialog_views.cc
@@ -10,7 +10,6 @@ #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" -#include "chrome/browser/ui/views_mode_controller.h" #include "chrome/common/chrome_switches.h" #include "components/constrained_window/constrained_window_views.h" #include "content/public/browser/web_contents.h" @@ -23,11 +22,6 @@ TabModalConfirmDialog* TabModalConfirmDialog::Create( TabModalConfirmDialogDelegate* delegate, content::WebContents* web_contents) { -#if defined(OS_MACOSX) - if (views_mode_controller::IsViewsBrowserCocoa()) - return CreateCocoa(delegate, web_contents); -#endif - return new TabModalConfirmDialogViews(delegate, web_contents); }
diff --git a/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc index aa1d212..e3c2649 100644 --- a/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc
@@ -1132,7 +1132,7 @@ g_browser_process->platform_part() ->browser_policy_connector_chromeos() ->GetDeviceNetworkConfigurationUpdater() - ->GetAuthorityCertificates()); + ->GetAllAuthorityCertificates()); } LoadAuthExtension(!gaia_silent_load_ /* force */, false /* offline */);
diff --git a/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.cc b/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.cc index 9c5f03fa..597a280 100644 --- a/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.cc +++ b/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.cc
@@ -183,26 +183,21 @@ void OfflineInternalsUIMessageHandler::HandleRequestQueueCallback( std::string callback_id, - offline_pages::GetRequestsResult result, std::vector<std::unique_ptr<offline_pages::SavePageRequest>> requests) { base::ListValue save_page_requests; - if (result == offline_pages::GetRequestsResult::SUCCESS) { - for (const auto& request : requests) { - auto save_page_request = std::make_unique<base::DictionaryValue>(); - save_page_request->SetString("onlineUrl", request->url().spec()); - save_page_request->SetDouble("creationTime", - request->creation_time().ToJsTime()); - save_page_request->SetString("status", GetStringFromSavePageStatus()); - save_page_request->SetString("namespace", - request->client_id().name_space); - save_page_request->SetDouble("lastAttemptTime", - request->last_attempt_time().ToJsTime()); - save_page_request->SetString("id", std::to_string(request->request_id())); - save_page_request->SetString("originalUrl", - request->original_url().spec()); - save_page_request->SetString("requestOrigin", request->request_origin()); - save_page_requests.Append(std::move(save_page_request)); - } + for (const auto& request : requests) { + auto save_page_request = std::make_unique<base::DictionaryValue>(); + save_page_request->SetString("onlineUrl", request->url().spec()); + save_page_request->SetDouble("creationTime", + request->creation_time().ToJsTime()); + save_page_request->SetString("status", GetStringFromSavePageStatus()); + save_page_request->SetString("namespace", request->client_id().name_space); + save_page_request->SetDouble("lastAttemptTime", + request->last_attempt_time().ToJsTime()); + save_page_request->SetString("id", std::to_string(request->request_id())); + save_page_request->SetString("originalUrl", request->original_url().spec()); + save_page_request->SetString("requestOrigin", request->request_origin()); + save_page_requests.Append(std::move(save_page_request)); } ResolveJavascriptCallback(base::Value(callback_id), save_page_requests); } @@ -214,7 +209,7 @@ CHECK(args->GetString(0, &callback_id)); if (request_coordinator_) { - request_coordinator_->queue()->GetRequests(base::Bind( + request_coordinator_->GetAllRequests(base::BindOnce( &OfflineInternalsUIMessageHandler::HandleRequestQueueCallback, weak_ptr_factory_.GetWeakPtr(), callback_id)); } else {
diff --git a/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h b/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h index 6092fd8..9450df7 100644 --- a/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h +++ b/chrome/browser/ui/webui/offline/offline_internals_ui_message_handler.h
@@ -95,7 +95,6 @@ // Callback for async GetRequests calls. void HandleRequestQueueCallback( std::string callback_id, - offline_pages::GetRequestsResult result, std::vector<std::unique_ptr<offline_pages::SavePageRequest>> requests); // Callback for DeletePage/DeleteAllPages calls.
diff --git a/chrome/browser/ui/webui/settings/people_handler.cc b/chrome/browser/ui/webui/settings/people_handler.cc index 1e5ab78d..16c04b5 100644 --- a/chrome/browser/ui/webui/settings/people_handler.cc +++ b/chrome/browser/ui/webui/settings/people_handler.cc
@@ -51,6 +51,7 @@ #include "components/sync/base/passphrase_enums.h" #include "components/sync/base/sync_prefs.h" #include "components/unified_consent/feature.h" +#include "components/unified_consent/unified_consent_metrics.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" @@ -243,6 +244,10 @@ "SyncSetupManageOtherPeople", base::BindRepeating(&PeopleHandler::HandleManageOtherPeople, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "UnifiedConsentToggleChanged", + base::BindRepeating(&PeopleHandler::OnUnifiedConsentToggleChanged, + base::Unretained(this))); #if defined(OS_CHROMEOS) web_ui()->RegisterMessageCallback( "AttemptUserExit", @@ -786,6 +791,15 @@ #endif // !defined(OS_CHROMEOS) } +void PeopleHandler::OnUnifiedConsentToggleChanged(const base::ListValue* args) { + bool is_toggle_checked = args->GetList()[0].GetBool(); + if (!is_toggle_checked) { + unified_consent::metrics::RecordUnifiedConsentRevoked( + unified_consent::metrics::UnifiedConsentRevokeReason:: + kUserDisabledSettingsToggle); + } +} + void PeopleHandler::CloseSyncSetup() { // Stop a timer to handle timeout in waiting for checking network connection. engine_start_timer_.reset();
diff --git a/chrome/browser/ui/webui/settings/people_handler.h b/chrome/browser/ui/webui/settings/people_handler.h index 7c7ae2fa..fd3e9d61 100644 --- a/chrome/browser/ui/webui/settings/people_handler.h +++ b/chrome/browser/ui/webui/settings/people_handler.h
@@ -175,6 +175,7 @@ void HandleSignout(const base::ListValue* args); void HandleGetSyncStatus(const base::ListValue* args); void HandleManageOtherPeople(const base::ListValue* args); + void OnUnifiedConsentToggleChanged(const base::ListValue* args); #if !defined(OS_CHROMEOS) // Displays the GAIA login form.
diff --git a/chrome/notification_helper/com_server_module.cc b/chrome/notification_helper/com_server_module.cc index f4134fd4..2454326d 100644 --- a/chrome/notification_helper/com_server_module.cc +++ b/chrome/notification_helper/com_server_module.cc
@@ -18,6 +18,8 @@ #include "chrome/notification_helper/notification_activator.h" #include "chrome/notification_helper/trace_util.h" +namespace mswr = Microsoft::WRL; + namespace { // These values are persisted to logs. Entries should not be renumbered and @@ -64,9 +66,8 @@ HRESULT ComServerModule::RegisterClassObjects() { // Create an out-of-proc COM module with caching disabled. The supplied // method is invoked when the last instance object of the module is released. - auto& module = - Microsoft::WRL::Module<Microsoft::WRL::OutOfProcDisableCaching>::Create( - this, &ComServerModule::SignalObjectCountZero); + auto& module = mswr::Module<mswr::OutOfProcDisableCaching>::Create( + this, &ComServerModule::SignalObjectCountZero); // Usually COM module classes statically define their CLSID at compile time // through the use of various macros, and WRL::Module internals takes care of @@ -74,11 +75,11 @@ // register the same object with different CLSIDs depending on a runtime // setting, so we handle that logic here. - Microsoft::WRL::ComPtr<IUnknown> factory; - unsigned int flags = Microsoft::WRL::ModuleType::OutOfProcDisableCaching; + mswr::ComPtr<IUnknown> factory; + unsigned int flags = mswr::ModuleType::OutOfProcDisableCaching; - HRESULT hr = Microsoft::WRL::Details::CreateClassFactory< - Microsoft::WRL::SimpleClassFactory<NotificationActivator>>( + HRESULT hr = mswr::Details::CreateClassFactory< + mswr::SimpleClassFactory<NotificationActivator>>( &flags, nullptr, __uuidof(IClassFactory), &factory); if (FAILED(hr)) { LogComServerModuleHistogram(ComServerModuleStatus::FACTORY_CREATION_FAILED); @@ -86,7 +87,7 @@ return hr; } - Microsoft::WRL::ComPtr<IClassFactory> class_factory; + mswr::ComPtr<IClassFactory> class_factory; hr = factory.As(&class_factory); if (FAILED(hr)) { LogComServerModuleHistogram( @@ -117,8 +118,7 @@ } HRESULT ComServerModule::UnregisterClassObjects() { - auto& module = Microsoft::WRL::Module< - Microsoft::WRL::OutOfProcDisableCaching>::GetModule(); + auto& module = mswr::Module<mswr::OutOfProcDisableCaching>::GetModule(); HRESULT hr = module.UnregisterCOMObject(nullptr, cookies_, arraysize(cookies_)); if (FAILED(hr)) {
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 20c62ce..a484fa69 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -981,6 +981,7 @@ "data/webui/signin_browsertest.h", "data/webui/webui_resource_browsertest.cc", "gpu/webgl_infobar_browsertest.cc", + "origin_policy/origin_policy_browsertest.cc", "ppapi/ppapi_browsertest.cc", "ppapi/ppapi_filechooser_browsertest.cc", "v8/wasm_trap_handler_browsertest.cc", @@ -1667,6 +1668,7 @@ "../browser/chromeos/login/demo_mode/demo_setup_test_utils.h", "../browser/chromeos/login/enable_debugging_browsertest.cc", "../browser/chromeos/login/enrollment/enrollment_screen_browsertest.cc", + "../browser/chromeos/login/enrollment/hands_off_enrollment_browsertest.cc", "../browser/chromeos/login/enrollment/mock_auto_enrollment_check_screen.cc", "../browser/chromeos/login/enrollment/mock_auto_enrollment_check_screen.h", "../browser/chromeos/login/enterprise_enrollment_browsertest.cc", @@ -1965,8 +1967,6 @@ "../browser/ui/cocoa/apps/app_shim_menu_controller_mac_browsertest.mm", "../browser/ui/cocoa/apps/native_app_window_cocoa_browsertest.mm", "../browser/ui/cocoa/dev_tools_controller_browsertest.mm", - "../browser/ui/cocoa/extensions/media_galleries_dialog_cocoa_browsertest.mm", - "../browser/ui/cocoa/location_bar/content_setting_decoration_browsertest.mm", "../browser/ui/cocoa/location_bar/zoom_decoration_browsertest.mm", "../browser/ui/cocoa/omnibox/omnibox_view_mac_browsertest.mm", "../browser/ui/cocoa/permission_bubble/permission_bubble_views_cocoa_browsertest.mm", @@ -4119,13 +4119,9 @@ cocoa_test_sources = [ "../browser/ui/cocoa/animatable_image_unittest.mm", "../browser/ui/cocoa/animatable_view_unittest.mm", - "../browser/ui/cocoa/autofill/autofill_bubble_controller_unittest.mm", - "../browser/ui/cocoa/autofill/autofill_tooltip_controller_unittest.mm", "../browser/ui/cocoa/background_gradient_view_unittest.mm", - "../browser/ui/cocoa/base_bubble_controller_unittest.mm", "../browser/ui/cocoa/bookmarks/bookmark_menu_bridge_unittest.mm", "../browser/ui/cocoa/bookmarks/bookmark_menu_cocoa_controller_unittest.mm", - "../browser/ui/cocoa/browser/zoom_bubble_controller_unittest.mm", "../browser/ui/cocoa/browser_window_cocoa_unittest.mm", "../browser/ui/cocoa/browser_window_controller_unittest.mm", "../browser/ui/cocoa/browser_window_layout_unittest.mm", @@ -4142,7 +4138,6 @@ "../browser/ui/cocoa/constrained_window/constrained_window_sheet_controller_unittest.mm", "../browser/ui/cocoa/draggable_button_unittest.mm", "../browser/ui/cocoa/extensions/browser_actions_container_view_unittest.mm", - "../browser/ui/cocoa/extensions/media_galleries_dialog_cocoa_unittest.mm", "../browser/ui/cocoa/find_pasteboard_unittest.mm", "../browser/ui/cocoa/first_run_dialog_controller_unittest.mm", "../browser/ui/cocoa/floating_bar_backing_view_unittest.mm", @@ -4155,19 +4150,14 @@ "../browser/ui/cocoa/history_overlay_controller_unittest.mm", "../browser/ui/cocoa/hover_close_button_unittest.mm", "../browser/ui/cocoa/image_button_cell_unittest.mm", - "../browser/ui/cocoa/info_bubble_view_unittest.mm", - "../browser/ui/cocoa/info_bubble_window_unittest.mm", "../browser/ui/cocoa/location_bar/autocomplete_text_field_cell_unittest.mm", "../browser/ui/cocoa/location_bar/autocomplete_text_field_editor_unittest.mm", "../browser/ui/cocoa/location_bar/autocomplete_text_field_unittest.mm", "../browser/ui/cocoa/location_bar/autocomplete_text_field_unittest_helper.h", "../browser/ui/cocoa/location_bar/autocomplete_text_field_unittest_helper.mm", "../browser/ui/cocoa/location_bar/image_decoration_unittest.mm", - "../browser/ui/cocoa/location_bar/keyword_hint_decoration_unittest.mm", "../browser/ui/cocoa/location_bar/location_bar_view_mac_unittest.mm", - "../browser/ui/cocoa/location_bar/manage_passwords_decoration_unittest.mm", "../browser/ui/cocoa/location_bar/page_info_bubble_decoration_unittest.mm", - "../browser/ui/cocoa/location_bar/selected_keyword_decoration_unittest.mm", "../browser/ui/cocoa/location_bar/zoom_decoration_unittest.mm", "../browser/ui/cocoa/main_menu_builder_unittest.mm", "../browser/ui/cocoa/md_hover_button_unittest.mm", @@ -4221,7 +4211,6 @@ if (mac_views_browser) { sources -= [ - "../browser/ui/cocoa/extensions/media_galleries_dialog_cocoa_unittest.mm", "../browser/ui/cocoa/page_info/page_info_bubble_controller_unittest.mm", ] }
diff --git a/chrome/test/chromedriver/client/chromedriver.py b/chrome/test/chromedriver/client/chromedriver.py index 4fe87a82..5afa1605 100644 --- a/chrome/test/chromedriver/client/chromedriver.py +++ b/chrome/test/chromedriver/client/chromedriver.py
@@ -580,3 +580,6 @@ for i in range(len(value)): typing.append(value[i]) self.ExecuteCommand(Command.SEND_KEYS_TO_ACTIVE_ELEMENT, {'value': typing}) + + def GenerateTestReport(self, message): + self.ExecuteCommand(Command.GENERATE_TEST_REPORT, {'message': message})
diff --git a/chrome/test/chromedriver/client/command_executor.py b/chrome/test/chromedriver/client/command_executor.py index 10f144f..ee97535 100644 --- a/chrome/test/chromedriver/client/command_executor.py +++ b/chrome/test/chromedriver/client/command_executor.py
@@ -171,6 +171,8 @@ _Method.POST, '/session/:sessionId/chromium/send_command') SEND_COMMAND_AND_GET_RESULT = ( _Method.POST, '/session/:sessionId/chromium/send_command_and_get_result') + GENERATE_TEST_REPORT = ( + _Method.POST, '/session/:sessionId/reporting/generate_test_report') # Custom Chrome commands. IS_LOADING = (_Method.GET, '/session/:sessionId/is_loading')
diff --git a/chrome/test/chromedriver/server/http_handler.cc b/chrome/test/chromedriver/server/http_handler.cc index 8eb4382..3bbe45be 100644 --- a/chrome/test/chromedriver/server/http_handler.cc +++ b/chrome/test/chromedriver/server/http_handler.cc
@@ -489,6 +489,11 @@ WrapToCommand("GetLogTypes", base::Bind(&ExecuteGetAvailableLogTypes))), + // extension commands + CommandMapping(kPost, "session/:sessionId/reporting/generate_test_report", + WrapToCommand("GenerateTestReport", + base::Bind(&ExecuteGenerateTestReport))), + // chromedriver only CommandMapping(kPost, "session/:sessionId/chromium/launch_app", WrapToCommand("LaunchApp", base::Bind(&ExecuteLaunchApp))),
diff --git a/chrome/test/chromedriver/session_commands.cc b/chrome/test/chromedriver/session_commands.cc index 35ce15d..14e31f7c 100644 --- a/chrome/test/chromedriver/session_commands.cc +++ b/chrome/test/chromedriver/session_commands.cc
@@ -1149,3 +1149,25 @@ return status; return Status(kOk); } + +Status ExecuteGenerateTestReport(Session* session, + const base::DictionaryValue& params, + std::unique_ptr<base::Value>* value) { + WebView* web_view = nullptr; + Status status = session->GetTargetWindow(&web_view); + if (status.IsError()) + return status; + + std::string message, group; + if (!params.GetString("message", &message)) + return Status(kInvalidArgument, "missing parameter 'message'"); + if (!params.GetString("group", &group)) + group = "default"; + + base::DictionaryValue body; + body.SetString("message", message); + body.SetString("group", group); + + web_view->SendCommandAndGetResult("Page.generateTestReport", body, value); + return Status(kOk); +}
diff --git a/chrome/test/chromedriver/session_commands.h b/chrome/test/chromedriver/session_commands.h index 550d42e..b02ab4b 100644 --- a/chrome/test/chromedriver/session_commands.h +++ b/chrome/test/chromedriver/session_commands.h
@@ -195,4 +195,8 @@ const base::DictionaryValue& params, std::unique_ptr<base::Value>* value); +Status ExecuteGenerateTestReport(Session* session, + const base::DictionaryValue& params, + std::unique_ptr<base::Value>* value); + #endif // CHROME_TEST_CHROMEDRIVER_SESSION_COMMANDS_H_
diff --git a/chrome/test/chromedriver/test/run_py_tests.py b/chrome/test/chromedriver/test/run_py_tests.py index a1dc076..bbaf92e 100755 --- a/chrome/test/chromedriver/test/run_py_tests.py +++ b/chrome/test/chromedriver/test/run_py_tests.py
@@ -106,9 +106,14 @@ _VERSION_SPECIFIC_FILTER['69'] = [ # https://bugs.chromium.org/p/chromedriver/issues/detail?id=2515 'HeadlessInvalidCertificateTest.*', + # Feature not yet supported in this version + 'ChromeDriverTest.testGenerateTestReport', ] -_VERSION_SPECIFIC_FILTER['68'] = [] +_VERSION_SPECIFIC_FILTER['68'] = [ + # Feature not yet supported in this version + 'ChromeDriverTest.testGenerateTestReport', +] @@ -1735,6 +1740,15 @@ imageGoldenScreenshot= open(filenameOfGoldenScreenshot, 'rb').read() self.assertEquals(imageGoldenScreenshot, dataActualScreenshot) + def testGenerateTestReport(self): + self._driver.Load(self.GetHttpUrlForFile( + '/chromedriver/reporting_observer.html')) + self._driver.GenerateTestReport('test report message'); + report = self._driver.ExecuteScript('return window.result;') + + self.assertEquals('test', report['type']); + self.assertEquals('test report message', report['body']['message']); + class ChromeDriverSiteIsolation(ChromeDriverBaseTestWithWebServer): """Tests for ChromeDriver with the new Site Isolation Chrome feature.
diff --git a/chrome/test/data/chromedriver/reporting_observer.html b/chrome/test/data/chromedriver/reporting_observer.html new file mode 100644 index 0000000..c8fab02 --- /dev/null +++ b/chrome/test/data/chromedriver/reporting_observer.html
@@ -0,0 +1,9 @@ +<html> + <script> + window.result = "bad result"; + var observer = new ReportingObserver(function(reports) { + window.result = reports[0]; + }, {buffered:true}); + observer.observe(); + </script> +</html>
diff --git a/chrome/test/data/extensions/theme_test_bgtabtext_tintonly/manifest.json b/chrome/test/data/extensions/theme_test_bgtabtext_tintonly/manifest.json new file mode 100644 index 0000000..8d923e0 --- /dev/null +++ b/chrome/test/data/extensions/theme_test_bgtabtext_tintonly/manifest.json
@@ -0,0 +1,15 @@ +{ + "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAngrAGJuOC5YkLdbZZpslN12eVb/pZ+9QmJU9kLFXqiP46zuogXxDZTNdvcmpnO1xfhEIYmQLfTgJ+0tIZdnapDK+EpyJQc79TmTTM1lfWh4GrEp5hmYk5nRmA1/CO28l+ZiHrZaz0bJsinvzQ7/S12dvmoIPgTShSr7wF2ZN205ObJbBbLuN7YIGMxH2Qlob1s0KVL3USjzYWLvoOL6B/Y/yYR3QvXgqnZGhg5/9bfkkzzDwMUjEB0QM7nH14F/VTuTVv4r8goBc6pzAYebVCjcjjb5s3thRgXyzQBBYJFz1m2BaeqzTHdqo2pwownzEtEtMbeqKGMJzZGtWFNy4vwIDAQAB", + "manifest_version": 2, + "version": "0.0.1", + "name": "test_bgtabtext_tintonly", + "theme": { + "colors": { + "frame": [255,255,255], + "tab_background_text": [0,0,0] + }, + "tints": { + "background_tab": [ -1.0, -1.0, 0.01 ] + } + } +} \ No newline at end of file
diff --git a/chrome/test/data/origin_policy_browsertest/.well-known/origin-policy/example-policy b/chrome/test/data/origin_policy_browsertest/.well-known/origin-policy/example-policy new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/chrome/test/data/origin_policy_browsertest/.well-known/origin-policy/example-policy
diff --git a/chrome/test/data/origin_policy_browsertest/OWNERS b/chrome/test/data/origin_policy_browsertest/OWNERS new file mode 100644 index 0000000..cc8f52f4 --- /dev/null +++ b/chrome/test/data/origin_policy_browsertest/OWNERS
@@ -0,0 +1 @@ +file://third_party/blink/common/origin_policy/OWNERS
diff --git a/chrome/test/data/origin_policy_browsertest/README.md b/chrome/test/data/origin_policy_browsertest/README.md new file mode 100644 index 0000000..056d3ef --- /dev/null +++ b/chrome/test/data/origin_policy_browsertest/README.md
@@ -0,0 +1,12 @@ +Support files for OriginPolicyBrowserTest. + +An origin policy needs to be announced by the server in a header, and so this +directory contains several files with ".mock-http-headers" companion files +announcing different origin policies. The test looks for the page title, and so +the headers file and the title in the .html file are the main "payload" for +the test. Additionally, the .well-known/origin-policy/ directory contains +example policies. + +The main test suite for Origin Policy is wpt/origin-policy. These tests +concentrate on aspects that can't easily be tested in the cross-browser WPT +suite, mainly error handling.
diff --git a/chrome/test/data/origin_policy_browsertest/page-policy-missing.html b/chrome/test/data/origin_policy_browsertest/page-policy-missing.html new file mode 100644 index 0000000..5881359 --- /dev/null +++ b/chrome/test/data/origin_policy_browsertest/page-policy-missing.html
@@ -0,0 +1,9 @@ +<html> +<head> + <title>Page With Policy Missing</title> +</head> +<body> + <p>Page With Policy Missing</p> +</body> +</html> +
diff --git a/chrome/test/data/origin_policy_browsertest/page-policy-missing.html.mock-http-headers b/chrome/test/data/origin_policy_browsertest/page-policy-missing.html.mock-http-headers new file mode 100644 index 0000000..9fc63e0 --- /dev/null +++ b/chrome/test/data/origin_policy_browsertest/page-policy-missing.html.mock-http-headers
@@ -0,0 +1,4 @@ +HTTP/1.0 200 OK +Content-Type: text/html; charset=utf-8 +Sec-Origin-Policy: this-policy-is-not-there +
diff --git a/chrome/test/data/origin_policy_browsertest/page-with-policy.html b/chrome/test/data/origin_policy_browsertest/page-with-policy.html new file mode 100644 index 0000000..f278f0a --- /dev/null +++ b/chrome/test/data/origin_policy_browsertest/page-with-policy.html
@@ -0,0 +1,9 @@ +<html> +<head> + <title>Page With Policy</title> +</head> +<body> + <p>Page With Policy</p> +</body> +</html> +
diff --git a/chrome/test/data/origin_policy_browsertest/page-with-policy.html.mock-http-headers b/chrome/test/data/origin_policy_browsertest/page-with-policy.html.mock-http-headers new file mode 100644 index 0000000..b65497f --- /dev/null +++ b/chrome/test/data/origin_policy_browsertest/page-with-policy.html.mock-http-headers
@@ -0,0 +1,4 @@ +HTTP/1.0 200 OK +Content-Type: text/html; charset=utf-8 +Sec-Origin-Policy: example-policy +
diff --git a/chrome/test/data/origin_policy_browsertest/page-without-policy.html b/chrome/test/data/origin_policy_browsertest/page-without-policy.html new file mode 100644 index 0000000..d68b8c9d7 --- /dev/null +++ b/chrome/test/data/origin_policy_browsertest/page-without-policy.html
@@ -0,0 +1,9 @@ +<html> +<head> + <title>Page Without Policy</title> +</head> +<body> + <p>Page Without Policy</p> +</body> +</html> +
diff --git a/chrome/test/data/origin_policy_browsertest/page-without-policy.html.mock-http-headers b/chrome/test/data/origin_policy_browsertest/page-without-policy.html.mock-http-headers new file mode 100644 index 0000000..d636cdb --- /dev/null +++ b/chrome/test/data/origin_policy_browsertest/page-without-policy.html.mock-http-headers
@@ -0,0 +1,3 @@ +HTTP/1.0 200 OK +Content-Type: text/html; charset=utf-8 +
diff --git a/chrome/test/data/webui/settings/people_page_sync_page_test.js b/chrome/test/data/webui/settings/people_page_sync_page_test.js index 82cf94a..16c4aa6 100644 --- a/chrome/test/data/webui/settings/people_page_sync_page_test.js +++ b/chrome/test/data/webui/settings/people_page_sync_page_test.js
@@ -271,6 +271,30 @@ assertFalse(ironCollapse.hidden); }); + test( + 'UnifiedConsentToggleNotifiesHandler_UnifiedConsentEnabled', + function() { + const unifiedConsentToggle = syncPage.$$('#unifiedConsentToggle'); + syncPage.syncStatus = { + signedIn: true, + disabled: false, + hasError: false, + statusAction: settings.StatusAction.NO_ACTION, + }; + syncPage.unifiedConsentEnabled = true; + Polymer.dom.flush(); + + assertFalse(unifiedConsentToggle.hidden); + assertFalse(unifiedConsentToggle.checked); + + unifiedConsentToggle.click(); + + return browserProxy.whenCalled('unifiedConsentToggleChanged') + .then(toggleChecked => { + assertTrue(toggleChecked); + }); + }); + test('SyncSectionLayout_UnifiedConsentEnabled_SignoutCollapse', function() { const ironCollapse = syncPage.$$('#sync-section'); const syncSectionToggle = syncPage.$$('#sync-section-toggle');
diff --git a/chrome/test/data/webui/settings/test_sync_browser_proxy.js b/chrome/test/data/webui/settings/test_sync_browser_proxy.js index 2440d780..c163487 100644 --- a/chrome/test/data/webui/settings/test_sync_browser_proxy.js +++ b/chrome/test/data/webui/settings/test_sync_browser_proxy.js
@@ -17,6 +17,7 @@ 'signOut', 'startSignIn', 'startSyncingWithEmail', + 'unifiedConsentToggleChanged', ]); /** @private {number} */ @@ -89,4 +90,9 @@ this.methodCalled('setSyncEncryption', syncPrefs); return Promise.resolve(this.encryptionResponse); } + + /** @override */ + unifiedConsentToggleChanged(toggleChecked) { + this.methodCalled('unifiedConsentToggleChanged', toggleChecked); + } }
diff --git a/chrome/test/origin_policy/OWNERS b/chrome/test/origin_policy/OWNERS new file mode 100644 index 0000000..cc8f52f4 --- /dev/null +++ b/chrome/test/origin_policy/OWNERS
@@ -0,0 +1 @@ +file://third_party/blink/common/origin_policy/OWNERS
diff --git a/chrome/test/origin_policy/origin_policy_browsertest.cc b/chrome/test/origin_policy/origin_policy_browsertest.cc new file mode 100644 index 0000000..9f3f634 --- /dev/null +++ b/chrome/test/origin_policy/origin_policy_browsertest.cc
@@ -0,0 +1,79 @@ +// 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 "base/strings/utf_string_conversions.h" +#include "base/test/scoped_feature_list.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "chrome/test/base/ui_test_utils.h" +#include "content/public/common/content_features.h" +#include "net/test/embedded_test_server/embedded_test_server.h" + +namespace { +const base::FilePath::CharType kDataRoot[] = + FILE_PATH_LITERAL("chrome/test/data/origin_policy_browsertest"); + +// The title of the Origin Policy error interstitial. This is used to determine +// whether the page load was blocked by the origin policy throttle. +const char kErrorInterstitialTitle[] = "Origin Policy Error Interstitial"; +} // namespace + +namespace content { + +// OriginPolicyBrowserTest tests several aspects of OriginPolicyThrottle (plus +// associated logic elsewhere). These tests focus on error conditions, since +// the normal operating conditions are already well covered in cross-browser +// Web Platform Tests (wpt/origin-policy/*). + +class OriginPolicyBrowserTest : public InProcessBrowserTest { + public: + OriginPolicyBrowserTest() : InProcessBrowserTest() {} + ~OriginPolicyBrowserTest() override {} + + void SetUpInProcessBrowserTestFixture() override { + server_ = std::make_unique<net::test_server::EmbeddedTestServer>( + net::test_server::EmbeddedTestServer::TYPE_HTTPS); + server_->AddDefaultHandlers(base::FilePath(kDataRoot)); + EXPECT_TRUE(server()->Start()); + + feature_list_.InitAndEnableFeature(features::kOriginPolicy); + } + + void TearDownInProcessBrowserTestFixture() override { server_.reset(); } + + net::test_server::EmbeddedTestServer* server() { return server_.get(); } + + // Most tests here are set up to use the page title to distinguish between + // successful load or the error page. For those tests, this method implements + // the bulk of the test logic. + base::string16 NavigateToAndReturnTitle(const char* url) { + EXPECT_TRUE(server()); + ui_test_utils::NavigateToURL(browser(), GURL(server()->GetURL(url))); + base::string16 title; + ui_test_utils::GetCurrentTabTitle(browser(), &title); + return title; + } + + private: + std::unique_ptr<net::test_server::EmbeddedTestServer> server_; + base::test::ScopedFeatureList feature_list_; + + DISALLOW_COPY_AND_ASSIGN(OriginPolicyBrowserTest); +}; + +IN_PROC_BROWSER_TEST_F(OriginPolicyBrowserTest, PageWithoutPolicy) { + EXPECT_EQ(base::ASCIIToUTF16("Page Without Policy"), + NavigateToAndReturnTitle("/page-without-policy.html")); +} + +IN_PROC_BROWSER_TEST_F(OriginPolicyBrowserTest, ApplyPolicy) { + EXPECT_EQ(base::ASCIIToUTF16("Page With Policy"), + NavigateToAndReturnTitle("/page-with-policy.html")); +} + +IN_PROC_BROWSER_TEST_F(OriginPolicyBrowserTest, ErrorCantDownloadPolicy) { + EXPECT_EQ(base::ASCIIToUTF16(kErrorInterstitialTitle), + NavigateToAndReturnTitle("/page-policy-missing.html")); +} + +} // namespace content
diff --git a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/AsyncTaskRunner.java b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/AsyncTaskRunner.java index 19041e1..3ad5e3e 100644 --- a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/AsyncTaskRunner.java +++ b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/AsyncTaskRunner.java
@@ -4,7 +4,7 @@ package org.chromium.chromecast.shell; -import org.chromium.base.AsyncTask; +import org.chromium.base.task.AsyncTask; import org.chromium.chromecast.base.Consumer; import org.chromium.chromecast.base.Scope; import org.chromium.chromecast.base.Supplier; @@ -15,7 +15,7 @@ * Runs a task on a worker thread, then run the callback with the result on the UI thread. * * This is a slightly less verbose way of doing asynchronous work than using - * org.chromium.base.AsyncTask directly. + * org.chromium.base.task.AsyncTask directly. */ public class AsyncTaskRunner { private final Executor mExecutor;
diff --git a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/ElidedLogcatProvider.java b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/ElidedLogcatProvider.java index 4f776c924..e7f8d48 100644 --- a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/ElidedLogcatProvider.java +++ b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/ElidedLogcatProvider.java
@@ -6,9 +6,9 @@ import android.os.SystemClock; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; +import org.chromium.base.task.AsyncTask; import java.io.BufferedReader; import java.io.IOException; @@ -57,4 +57,4 @@ return builder.toString(); } } -} \ No newline at end of file +}
diff --git a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/ExternalServiceDeviceLogcatProvider.java b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/ExternalServiceDeviceLogcatProvider.java index bc98f86..5d92cb4 100644 --- a/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/ExternalServiceDeviceLogcatProvider.java +++ b/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/ExternalServiceDeviceLogcatProvider.java
@@ -11,9 +11,9 @@ import android.os.IBinder; import android.os.RemoteException; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.Log; +import org.chromium.base.task.AsyncTask; import java.io.BufferedReader; import java.io.FileNotFoundException;
diff --git a/chromecast/browser/android/junit/src/org/chromium/chromecast/shell/AsyncTaskRunnerTest.java b/chromecast/browser/android/junit/src/org/chromium/chromecast/shell/AsyncTaskRunnerTest.java index e679052b..e622972 100644 --- a/chromecast/browser/android/junit/src/org/chromium/chromecast/shell/AsyncTaskRunnerTest.java +++ b/chromecast/browser/android/junit/src/org/chromium/chromecast/shell/AsyncTaskRunnerTest.java
@@ -12,7 +12,7 @@ import org.junit.runner.RunWith; import org.robolectric.annotation.Config; -import org.chromium.base.test.asynctask.ShadowAsyncTask; +import org.chromium.base.task.test.ShadowAsyncTask; import org.chromium.chromecast.base.Controller; import org.chromium.testing.local.LocalRobolectricTestRunner;
diff --git a/chromecast/media/audio/BUILD.gn b/chromecast/media/audio/BUILD.gn index a6078c92..d19d447 100644 --- a/chromecast/media/audio/BUILD.gn +++ b/chromecast/media/audio/BUILD.gn
@@ -48,3 +48,16 @@ "//chromecast/public/media", ] } + +source_set("fake_external_audio_pipeline") { + sources = [ + "fake_external_audio_pipeline.cc", + "fake_external_audio_pipeline_support.h", + ] + + deps = [ + "//base", + "//chromecast/public", + "//chromecast/public/media", + ] +}
diff --git a/chromecast/media/audio/fake_external_audio_pipeline.cc b/chromecast/media/audio/fake_external_audio_pipeline.cc new file mode 100644 index 0000000..a15bad7 --- /dev/null +++ b/chromecast/media/audio/fake_external_audio_pipeline.cc
@@ -0,0 +1,236 @@ +// 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 <algorithm> +#include <cstdint> +#include <memory> +#include <vector> + +#include "base/logging.h" +#include "base/macros.h" +#include "base/no_destructor.h" +#include "chromecast/media/audio/fake_external_audio_pipeline_support.h" +#include "chromecast/public/cast_media_shlib.h" +#include "chromecast/public/media/external_audio_pipeline_shlib.h" +#include "chromecast/public/media/mixer_output_stream.h" + +namespace chromecast { +namespace media { +namespace { + +// Library implementation for media volume/mute testing part. It stores +// observers for sending volume/mute change requests and stores volume/muted. +class TestMediaVolumeMute { + public: + TestMediaVolumeMute() = default; + // Called by library. + void AddExternalMediaVolumeChangeRequestObserver( + ExternalAudioPipelineShlib::ExternalMediaVolumeChangeRequestObserver* + observer) { + volume_change_request_observer_ = observer; + } + void RemoveExternalMediaVolumeChangeRequestObserver( + ExternalAudioPipelineShlib::ExternalMediaVolumeChangeRequestObserver* + observer) { + volume_change_request_observer_ = nullptr; + } + + void SetVolume(float volume) { volume_ = volume; } + void SetMuted(bool muted) { muted_ = muted; } + + protected: + // Used by derived class for FakeExternalAudioPipelineSupport. + ExternalAudioPipelineShlib::ExternalMediaVolumeChangeRequestObserver* + volume_change_request_observer_ = nullptr; + float volume_ = 0; + bool muted_ = false; + + private: + DISALLOW_COPY_AND_ASSIGN(TestMediaVolumeMute); +}; + +// Library implementation for loopback data testing part. It stores +// CastMediaShlib observers and does loopback audio data to it. +class TestLoopBack { + public: + TestLoopBack() = default; + // Called from FakeMixerOutputStream. + void OnData(const float* data, + int data_size, + MixerOutputStream* stream, + int channels) { + auto delay = stream->GetRenderingDelay(); + int64_t delay_microseconds = + delay.timestamp_microseconds + delay.delay_microseconds; + for (auto* observer : observers_) { + observer->OnLoopbackAudio( + delay_microseconds, kSampleFormatF32, stream->GetSampleRate(), + channels, reinterpret_cast<uint8_t*>(const_cast<float*>(data)), + data_size * sizeof(float)); + } + } + // Called from library. + void AddExternalLoopbackAudioObserver( + CastMediaShlib::LoopbackAudioObserver* observer) { + observers_.push_back(observer); + } + + void RemoveExternalLoopbackAudioObserver( + CastMediaShlib::LoopbackAudioObserver* observer) { + auto it = std::find(observers_.begin(), observers_.end(), observer); + if (it != observers_.end()) { + observers_.erase(it); + } + } + + protected: + // Used by derived class for FakeExternalAudioPipelineSupport. + std::vector<CastMediaShlib::LoopbackAudioObserver*> observers_; + + private: + DISALLOW_COPY_AND_ASSIGN(TestLoopBack); +}; + +// Final class includes library implementation for testing media volume/mute +// + loopback and FakeExternalAudioPipelineSupport implementation. +class TestMedia : public TestMediaVolumeMute, + public TestLoopBack, + public testing::FakeExternalAudioPipelineSupport { + public: + TestMedia() = default; + + bool supported() const { return supported_; } + + // FakeExternalAudioPipelineSupport implementation: + void SetSupported() override { supported_ = true; } + + void Reset() override { + supported_ = false; + volume_change_request_observer_ = nullptr; + volume_ = 0; + muted_ = false; + observers_.clear(); + } + + float GetVolume() const override { return volume_; } + bool IsMuted() const override { return muted_; } + + void OnVolumeChangeRequest(float level) override { + CHECK(volume_change_request_observer_); + volume_change_request_observer_->OnVolumeChangeRequest(level); + } + void OnMuteChangeRequest(bool muted) override { + CHECK(volume_change_request_observer_); + volume_change_request_observer_->OnMuteChangeRequest(muted); + } + + private: + bool supported_ = false; + + DISALLOW_COPY_AND_ASSIGN(TestMedia); +}; + +TestMedia* GetTestMedia() { + static base::NoDestructor<TestMedia> g_test_media; + return g_test_media.get(); +} + +// MixerOutputStream implementation, it will be created by +// ExternalAudioPipelineShlib::CreateMixerOutputStream. +class FakeMixerOutputStream : public MixerOutputStream { + public: + FakeMixerOutputStream() : test_loop_back_(GetTestMedia()) {} + + // MixerOutputStream implementation: + bool Start(int requested_sample_rate, int channels) override { + sample_rate_ = requested_sample_rate; + channels_ = channels; + return true; + } + + void Stop() override {} + + int GetSampleRate() override { return sample_rate_; } + + MediaPipelineBackend::AudioDecoder::RenderingDelay GetRenderingDelay() + override { + return MediaPipelineBackend::AudioDecoder::RenderingDelay(); + } + + int OptimalWriteFramesCount() override { return 256; } + + bool Write(const float* data, + int data_size, + bool* out_playback_interrupted) override { + // To check OnLoopbackInterrupted. + *out_playback_interrupted = true; + // Loopback data. + test_loop_back_->OnData(data, data_size, this, channels_); + return true; + } + + private: + int sample_rate_ = 0; + int channels_ = 0; + TestLoopBack* const test_loop_back_; + + DISALLOW_COPY_AND_ASSIGN(FakeMixerOutputStream); +}; + +} // namespace + +namespace testing { +// Get the interface for interaction with the library from unittests. +FakeExternalAudioPipelineSupport* GetFakeExternalAudioPipelineSupport() { + return GetTestMedia(); +} + +} // namespace testing + +// Library implementation. +bool ExternalAudioPipelineShlib::IsSupported() { + return GetTestMedia()->supported(); +} + +void ExternalAudioPipelineShlib::AddExternalMediaVolumeChangeRequestObserver( + ExternalMediaVolumeChangeRequestObserver* observer) { + GetTestMedia()->AddExternalMediaVolumeChangeRequestObserver(observer); +} + +void ExternalAudioPipelineShlib::RemoveExternalMediaVolumeChangeRequestObserver( + ExternalMediaVolumeChangeRequestObserver* observer) { + GetTestMedia()->RemoveExternalMediaVolumeChangeRequestObserver(observer); +} + +void ExternalAudioPipelineShlib::SetExternalMediaVolume(float level) { + GetTestMedia()->SetVolume(level); +} + +void ExternalAudioPipelineShlib::SetExternalMediaMuted(bool muted) { + GetTestMedia()->SetMuted(muted); +} + +void ExternalAudioPipelineShlib::AddExternalLoopbackAudioObserver( + CastMediaShlib::LoopbackAudioObserver* observer) { + GetTestMedia()->AddExternalLoopbackAudioObserver(observer); +} + +void ExternalAudioPipelineShlib::RemoveExternalLoopbackAudioObserver( + CastMediaShlib::LoopbackAudioObserver* observer) { + GetTestMedia()->RemoveExternalLoopbackAudioObserver(observer); +} + +void ExternalAudioPipelineShlib::AddExternalMediaMetadataChangeObserver( + ExternalMediaMetadataChangeObserver* observer) {} + +void ExternalAudioPipelineShlib::RemoveExternalMediaMetadataChangeObserver( + ExternalMediaMetadataChangeObserver* observer) {} + +std::unique_ptr<MixerOutputStream> +ExternalAudioPipelineShlib::CreateMixerOutputStream() { + return std::make_unique<FakeMixerOutputStream>(); +} + +} // namespace media +} // namespace chromecast
diff --git a/chromecast/media/audio/fake_external_audio_pipeline_support.h b/chromecast/media/audio/fake_external_audio_pipeline_support.h new file mode 100644 index 0000000..98bd96c --- /dev/null +++ b/chromecast/media/audio/fake_external_audio_pipeline_support.h
@@ -0,0 +1,34 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROMECAST_MEDIA_AUDIO_FAKE_EXTERNAL_AUDIO_PIPELINE_SUPPORT_H +#define CHROMECAST_MEDIA_AUDIO_FAKE_EXTERNAL_AUDIO_PIPELINE_SUPPORT_H + +namespace chromecast { +namespace media { +namespace testing { + +// Interface class for fake external pipeline library to interact with the +// library from unit tests. +class FakeExternalAudioPipelineSupport { + public: + virtual void SetSupported() = 0; + virtual void Reset() = 0; + // Get last received values. + virtual float GetVolume() const = 0; + virtual bool IsMuted() const = 0; + // Request for change values. + virtual void OnVolumeChangeRequest(float level) = 0; + virtual void OnMuteChangeRequest(bool muted) = 0; + + virtual ~FakeExternalAudioPipelineSupport() {} +}; + +FakeExternalAudioPipelineSupport* GetFakeExternalAudioPipelineSupport(); + +} // namespace testing +} // namespace media +} // namespace chromecast + +#endif // CHROMECAST_MEDIA_AUDIO_FAKE_EXTERNAL_AUDIO_PIPELINE_SUPPORT_H
diff --git a/chromecast/media/cma/backend/BUILD.gn b/chromecast/media/cma/backend/BUILD.gn index e64087e..7cfad18e 100644 --- a/chromecast/media/cma/backend/BUILD.gn +++ b/chromecast/media/cma/backend/BUILD.gn
@@ -259,6 +259,7 @@ "mock_mixer_source.h", "mock_redirected_audio_output.cc", "mock_redirected_audio_output.h", + "stream_mixer_external_audio_pipeline_unittest.cc", "stream_mixer_unittest.cc", ] @@ -270,6 +271,7 @@ ":public", "//base", "//base/test:run_all_unittests", + "//chromecast/media/audio:fake_external_audio_pipeline", "//chromecast/media/cma/backend/post_processors:unittests", "//chromecast/public", "//chromecast/public/media",
diff --git a/chromecast/media/cma/backend/stream_mixer_external_audio_pipeline_unittest.cc b/chromecast/media/cma/backend/stream_mixer_external_audio_pipeline_unittest.cc new file mode 100644 index 0000000..be47160 --- /dev/null +++ b/chromecast/media/cma/backend/stream_mixer_external_audio_pipeline_unittest.cc
@@ -0,0 +1,224 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <algorithm> +#include <memory> +#include <vector> + +#include "base/location.h" +#include "base/macros.h" +#include "base/message_loop/message_loop.h" +#include "base/run_loop.h" +#include "base/threading/thread_task_runner_handle.h" +#include "chromecast/media/audio/fake_external_audio_pipeline_support.h" +#include "chromecast/media/cma/backend/mock_mixer_source.h" +#include "chromecast/media/cma/backend/stream_mixer.h" +#include "chromecast/public/media/external_audio_pipeline_shlib.h" +#include "chromecast/public/media/mixer_output_stream.h" +#include "media/base/audio_bus.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace chromecast { +namespace media { +namespace { + +using ::testing::_; +using ::testing::AtLeast; + +// Mock for saving and checking loopback audio data. +class MockLoopbackAudioObserver : public CastMediaShlib::LoopbackAudioObserver { + public: + MockLoopbackAudioObserver() { + ON_CALL(*this, OnLoopbackAudio(_, _, _, _, _, _)) + .WillByDefault(::testing::Invoke( + this, &MockLoopbackAudioObserver::OnLoopbackAudioImpl)); + } + + MOCK_METHOD6(OnLoopbackAudio, + void(int64_t timestamp, + SampleFormat sample_format, + int sample_rate, + int num_channels, + uint8_t* data, + int length)); + MOCK_METHOD0(OnLoopbackInterrupted, void()); + MOCK_METHOD0(OnRemoved, void()); + + const std::vector<float>& data() const { return data_; } + + private: + void OnLoopbackAudioImpl(int64_t timestamp, + SampleFormat sample_format, + int sample_rate, + int num_channels, + uint8_t* data, + int length) { + data_.clear(); + // Save received data to local. + float* float_data = reinterpret_cast<float*>(const_cast<uint8_t*>(data)); + const size_t size = length / sizeof(float); + data_.insert(data_.end(), float_data, float_data + size); + } + + std::vector<float> data_; + + DISALLOW_COPY_AND_ASSIGN(MockLoopbackAudioObserver); +}; + +class ExternalAudioPipelineTest : public ::testing::Test { + public: + ExternalAudioPipelineTest() + : external_audio_pipeline_support_( + testing::GetFakeExternalAudioPipelineSupport()), + message_loop_(std::make_unique<base::MessageLoop>()) {} + + void SetUp() override { + // Set that external library is supported. + external_audio_pipeline_support_->SetSupported(); + + mixer_ = std::make_unique<StreamMixer>(nullptr, nullptr, + base::ThreadTaskRunnerHandle::Get()); + } + + void TearDown() override { + // Reset library internal state to use it for other unit tests. + external_audio_pipeline_support_->Reset(); + } + // Run async operations in the stream mixer. + void RunLoopForMixer() { + // SendLoopbackData. + base::RunLoop run_loop1; + message_loop_->task_runner()->PostTask(FROM_HERE, run_loop1.QuitClosure()); + run_loop1.Run(); + // Playbackloop. + base::RunLoop run_loop2; + message_loop_->task_runner()->PostTask(FROM_HERE, run_loop2.QuitClosure()); + run_loop2.Run(); + } + + protected: + std::unique_ptr<StreamMixer> mixer_; + testing::FakeExternalAudioPipelineSupport* const + external_audio_pipeline_support_; + + private: + const std::unique_ptr<base::MessageLoop> message_loop_; + + DISALLOW_COPY_AND_ASSIGN(ExternalAudioPipelineTest); +}; + +// Check that |expected| matches |actual| exactly. +void CompareAudioData(const ::media::AudioBus& expected, + const ::media::AudioBus& actual) { + ASSERT_EQ(expected.channels(), actual.channels()); + ASSERT_EQ(expected.frames(), actual.frames()); + for (int c = 0; c < expected.channels(); ++c) { + const float* expected_data = expected.channel(c); + const float* actual_data = actual.channel(c); + for (int f = 0; f < expected.frames(); ++f) { + EXPECT_FLOAT_EQ(*expected_data++, *actual_data++) << c << " " << f; + } + } +} + +// Unit tests for ExternalAudioPipelineShlib library. +// Test media volume notification. +TEST_F(ExternalAudioPipelineTest, SetMediaVolume) { + ASSERT_EQ(external_audio_pipeline_support_->GetVolume(), 0.0f); + + mixer_->SetVolume(AudioContentType::kMedia, 0.02); + RunLoopForMixer(); + ASSERT_EQ(external_audio_pipeline_support_->GetVolume(), 0.02f); +} +// Test media muted notification. +TEST_F(ExternalAudioPipelineTest, SetMediaMuted) { + ASSERT_EQ(external_audio_pipeline_support_->IsMuted(), false); + + mixer_->SetMuted(AudioContentType::kMedia, true); + RunLoopForMixer(); + ASSERT_EQ(external_audio_pipeline_support_->IsMuted(), true); +} +// Set media volume from library, check notification. +TEST_F(ExternalAudioPipelineTest, SetVolumeChangeRequest) { + ASSERT_EQ(external_audio_pipeline_support_->GetVolume(), 0.0f); + + external_audio_pipeline_support_->OnVolumeChangeRequest(0.03); + RunLoopForMixer(); + ASSERT_EQ(external_audio_pipeline_support_->GetVolume(), 0.03f); +} +// Set media mute from library, check notification. +TEST_F(ExternalAudioPipelineTest, SetMuteChangeRequest) { + ASSERT_EQ(external_audio_pipeline_support_->IsMuted(), false); + + external_audio_pipeline_support_->OnMuteChangeRequest(true); + RunLoopForMixer(); + ASSERT_EQ(external_audio_pipeline_support_->IsMuted(), true); +} +// Check external library loopback data. Check that passed input to StreamMixer +// comes to CastMediaShlib::LoopbackAudioObserver w/o changes. +TEST_F(ExternalAudioPipelineTest, ExternalAudioPipelineLoopbackData) { + // Set Volume to 1, because we'd like the input to be w/o changes. + mixer_->SetVolume(AudioContentType::kMedia, 1); + + // CastMediaShlib::LoopbackAudioObserver mock observer. + MockLoopbackAudioObserver mock_loopback_observer; + EXPECT_CALL(mock_loopback_observer, OnLoopbackAudio(_, _, _, _, _, _)) + .Times(AtLeast(1)); + EXPECT_CALL(mock_loopback_observer, OnLoopbackInterrupted()) + .Times(AtLeast(1)); + EXPECT_CALL(mock_loopback_observer, OnRemoved()).Times(1); + // Input. + MockMixerSource input(48000); + EXPECT_CALL(input, InitializeAudioPlayback(_, _)).Times(1); + EXPECT_CALL(input, FinalizeAudioPlayback()).Times(1); + EXPECT_CALL(input, FillAudioPlaybackFrames(_, _, _)).Times(AtLeast(1)); + + // Prepare data for test. + const size_t kSampleSize = 64; + char test_data[kSampleSize]; + for (size_t i = 0; i < kSampleSize; ++i) + test_data[i] = i; + + // Set test data in AudioBus. + const int kNumChannels = 2; + const auto kNumFrames = kSampleSize / kNumChannels; + auto data = ::media::AudioBus::Create(kNumChannels, kNumFrames); + const size_t kBytesPerSample = sizeof(test_data[0]); + data->FromInterleaved(&test_data, kNumFrames, kBytesPerSample); + // Prepare data for compare. + auto expected = ::media::AudioBus::Create(kNumChannels, kNumFrames); + data->CopyTo(expected.get()); + + // Start the test. Set loopback observer. + mixer_->AddLoopbackAudioObserver(&mock_loopback_observer); + + mixer_->AddInput(&input); + + RunLoopForMixer(); + // Send data to the stream mixer. + input.SetData(std::move(data)); + + RunLoopForMixer(); + + // Get actual data from our mocked loopback observer. + ASSERT_GE(mock_loopback_observer.data().size(), kNumFrames); + + auto actual = ::media::AudioBus::Create(kNumChannels, kNumFrames); + using FloatType = ::media::Float32SampleTypeTraits; + actual->FromInterleaved<FloatType>(mock_loopback_observer.data().data(), + kNumFrames); + + CompareAudioData(*expected, *actual); + + // Check OnRemoved. + mixer_->RemoveLoopbackAudioObserver(&mock_loopback_observer); + mixer_->RemoveInput(&input); + + RunLoopForMixer(); +} + +} // namespace +} // namespace media +} // namespace chromecast
diff --git a/chromeos/BUILD.gn b/chromeos/BUILD.gn index 92c57f2..f90144d 100644 --- a/chromeos/BUILD.gn +++ b/chromeos/BUILD.gn
@@ -464,6 +464,7 @@ "network/shill_property_util.h", "network/tether_constants.cc", "network/tether_constants.h", + "policy_certificate_provider.h", "printing/ppd_cache.cc", "printing/ppd_cache.h", "printing/ppd_line_reader.cc",
diff --git a/chromeos/cert_loader.cc b/chromeos/cert_loader.cc index 2cdc8f3c..eb131dd 100644 --- a/chromeos/cert_loader.cc +++ b/chromeos/cert_loader.cc
@@ -164,7 +164,7 @@ return false; } -// Goes through all certificates in |all_certs| and copies those certificates +// Goes through all certificates in |certs| and copies those certificates // which are on |system_slot| to a new list. net::ScopedCERTCertificateList FilterSystemTokenCertificates( net::ScopedCERTCertificateList certs, @@ -184,6 +184,26 @@ return certs; } +void AddPolicyProvidedAuthorities( + const PolicyCertificateProvider* policy_certificate_provider, + net::ScopedCERTCertificateList* out_certs) { + DCHECK(out_certs); + if (!policy_certificate_provider) + return; + for (const auto& certificate : + policy_certificate_provider->GetAllAuthorityCertificates()) { + net::ScopedCERTCertificate x509_cert = + net::x509_util::CreateCERTCertificateFromX509Certificate( + certificate.get()); + if (!x509_cert) { + LOG(ERROR) << "Unable to create CERTCertificate"; + continue; + } + + out_certs->push_back(std::move(x509_cert)); + } +} + } // namespace static CertLoader* g_cert_loader = nullptr; @@ -214,13 +234,15 @@ } CertLoader::CertLoader() : weak_factory_(this) { - system_cert_cache_ = std::make_unique<CertCache>( - base::BindRepeating(&CertLoader::CacheUpdated, base::Unretained(this))); - user_cert_cache_ = std::make_unique<CertCache>( - base::BindRepeating(&CertLoader::CacheUpdated, base::Unretained(this))); + system_cert_cache_ = std::make_unique<CertCache>(base::BindRepeating( + &CertLoader::OnCertCacheOrPolicyCertsUpdated, base::Unretained(this))); + user_cert_cache_ = std::make_unique<CertCache>(base::BindRepeating( + &CertLoader::OnCertCacheOrPolicyCertsUpdated, base::Unretained(this))); } -CertLoader::~CertLoader() = default; +CertLoader::~CertLoader() { + DCHECK(policy_certificate_providers_.empty()); +} void CertLoader::SetSystemNSSDB(net::NSSCertDatabase* system_slot_database) { system_cert_cache_->SetNSSDB(system_slot_database); @@ -230,6 +252,24 @@ user_cert_cache_->SetNSSDB(user_database); } +void CertLoader::AddPolicyCertificateProvider( + PolicyCertificateProvider* policy_certificate_provider) { + policy_certificate_provider->AddPolicyProvidedCertsObserver(this); + policy_certificate_providers_.push_back(policy_certificate_provider); + OnCertCacheOrPolicyCertsUpdated(); +} + +void CertLoader::RemovePolicyCertificateProvider( + PolicyCertificateProvider* policy_certificate_provider) { + auto iter = std::find(policy_certificate_providers_.begin(), + policy_certificate_providers_.end(), + policy_certificate_provider); + DCHECK(iter != policy_certificate_providers_.end()); + policy_certificate_providers_.erase(iter); + policy_certificate_provider->RemovePolicyProvidedCertsObserver(this); + OnCertCacheOrPolicyCertsUpdated(); +} + void CertLoader::AddObserver(CertLoader::Observer* observer) { observers_.AddObserver(observer); } @@ -296,9 +336,26 @@ return pkcs11_id; } -void CertLoader::CacheUpdated() { +void CertLoader::OnCertCacheOrPolicyCertsUpdated() { DCHECK(thread_checker_.CalledOnValidThread()); - VLOG(1) << "CacheUpdated"; + VLOG(1) << "OnCertCacheOrPolicyCertsUpdated"; + + // Only trigger a notification to observers if one of the |CertCache|s has + // already loaded certificates. Don't trigger notifications if policy-provided + // certificates change before that. + // TODO(https://crbug.com/888451): When we handle client and authority + // certificates separately in CertLoader, we could fire different + // notifications for policy-provided cert changes instead of holding back + // notifications. Note that it is possible that only |system_cert_cache_| has + // loaded certificates (e.g. on the ChromeOS sign-in screen), and it is also + // possible that only |user_cert_cache_| has loaded certificates (e.g. if the + // system slot is not available for some reason, but a primary user has signed + // in). + bool has_loaded_any_certs_from_db = + user_cert_cache_->initial_load_finished() || + system_cert_cache_->initial_load_finished(); + if (!has_loaded_any_certs_from_db) + return; // If user_cert_cache_ has access to system certificates and it has already // finished its initial load, it will contain system certificates which we can @@ -321,28 +378,39 @@ user_cert_cache_->cert_list()))); } else { // The user's cert cache does not contain system certificates. - net::ScopedCERTCertificateList system_certs = + net::ScopedCERTCertificateList system_token_client_certs = net::x509_util::DupCERTCertificateList(system_cert_cache_->cert_list()); net::ScopedCERTCertificateList all_certs = net::x509_util::DupCERTCertificateList(user_cert_cache_->cert_list()); - all_certs.reserve(all_certs.size() + system_certs.size()); - for (const net::ScopedCERTCertificate& cert : system_certs) + all_certs.reserve(all_certs.size() + system_token_client_certs.size()); + for (const net::ScopedCERTCertificate& cert : system_token_client_certs) all_certs.push_back(net::x509_util::DupCERTCertificate(cert.get())); - UpdateCertificates(std::move(all_certs), std::move(system_certs)); + UpdateCertificates(std::move(all_certs), + std::move(system_token_client_certs)); } } void CertLoader::UpdateCertificates( net::ScopedCERTCertificateList all_certs, - net::ScopedCERTCertificateList system_certs) { + net::ScopedCERTCertificateList system_token_client_certs) { CHECK(thread_checker_.CalledOnValidThread()); VLOG(1) << "UpdateCertificates: " << all_certs.size() << " (" - << system_certs.size() << " on system slot)"; + << system_token_client_certs.size() + << " client certs on system slot)"; // Ignore any existing certificates. all_certs_ = std::move(all_certs); - system_certs_ = std::move(system_certs); + system_token_client_certs_ = std::move(system_token_client_certs); + + // Add policy-provided certificates. + // TODO(https://crbug.com/888451): Instead of putting authorities and client + // certs into |all_certs_| and then filtering in NetworkCertificateHandler, we + // should separate the two categories here in |CertLoader| already (pmarko@). + for (const PolicyCertificateProvider* policy_certificate_provider : + policy_certificate_providers_) { + AddPolicyProvidedAuthorities(policy_certificate_provider, &all_certs_); + } NotifyCertificatesLoaded(); } @@ -352,4 +420,11 @@ observer.OnCertificatesLoaded(all_certs_); } +void CertLoader::OnPolicyProvidedCertsChanged( + const net::CertificateList& all_server_and_authority_certs, + const net::CertificateList& trust_anchors) { + CHECK(thread_checker_.CalledOnValidThread()); + OnCertCacheOrPolicyCertsUpdated(); +} + } // namespace chromeos
diff --git a/chromeos/cert_loader.h b/chromeos/cert_loader.h index 9361f4a2..121f0fb8 100644 --- a/chromeos/cert_loader.h +++ b/chromeos/cert_loader.h
@@ -15,6 +15,7 @@ #include "base/observer_list.h" #include "base/threading/thread_checker.h" #include "chromeos/chromeos_export.h" +#include "chromeos/policy_certificate_provider.h" #include "net/cert/scoped_nss_types.h" namespace net { @@ -34,7 +35,7 @@ // before user sign-in, and additionally with a user-specific NSSCertDatabase // after user sign-in. When both NSSCertDatabase are used, CertLoader combines // certificates from both into |all_certs()|. -class CHROMEOS_EXPORT CertLoader { +class CHROMEOS_EXPORT CertLoader : public PolicyCertificateProvider::Observer { public: class Observer { public: @@ -82,6 +83,20 @@ // with only one database or with both (system and user) databases. void SetUserNSSDB(net::NSSCertDatabase* user_database); + // Adds the passed |PolicyCertificateProvider| and starts using the authority + // certificates provided by it. CertLoader registers itself as Observer on + // |policy_certificate_provider|, so the caller must ensure to call + // |RemovePolicyCertificateProvider| before |policy_certificate_provider| is + // destroyed or before |CertLoader| is shut down. + void AddPolicyCertificateProvider( + PolicyCertificateProvider* policy_certificate_provider); + + // Removes the passed |PolicyCertificateProvider| and stops using authority + // certificates provided by it. |policy_certificate_provider| must have been + // added using |AddPolicyCertificateProvider| before. + void RemovePolicyCertificateProvider( + PolicyCertificateProvider* policy_certificate_provider); + void AddObserver(CertLoader::Observer* observer); void RemoveObserver(CertLoader::Observer* observer); @@ -117,9 +132,9 @@ // Returns certificates from the system token. This will be empty until // certificates_loaded() is true. - const net::ScopedCERTCertificateList& system_certs() const { + const net::ScopedCERTCertificateList& system_token_client_certs() const { DCHECK(thread_checker_.CalledOnValidThread()); - return system_certs_; + return system_token_client_certs_; } // Called in tests if |IsCertificateHardwareBacked()| should always return @@ -130,18 +145,24 @@ class CertCache; CertLoader(); - ~CertLoader(); + ~CertLoader() override; - // Called by |system_cert_cache_| or |user_cert_cache| when these had an - // update. - void CacheUpdated(); + // Called when |system_cert_cache_|, |user_cert_cache| or policy-provided + // certificates have potentially changed. + void OnCertCacheOrPolicyCertsUpdated(); // Called if a certificate load task is finished. - void UpdateCertificates(net::ScopedCERTCertificateList all_certs, - net::ScopedCERTCertificateList system_certs); + void UpdateCertificates( + net::ScopedCERTCertificateList all_certs, + net::ScopedCERTCertificateList system_token_client_certs); void NotifyCertificatesLoaded(); + // PolicyCertificateProvider::Observer + void OnPolicyProvidedCertsChanged( + const net::CertificateList& all_server_and_authority_certs, + const net::CertificateList& trust_anchors) override; + base::ObserverList<Observer>::Unchecked observers_; // Cache for certificates from the system-token NSSCertDatabase. @@ -149,11 +170,14 @@ // Cache for certificates from the user-specific NSSCertDatabase. std::unique_ptr<CertCache> user_cert_cache_; - // Cached certificates loaded from the database(s). + // Cached certificates loaded from the database(s) and policy-pushed Authority + // certificates. net::ScopedCERTCertificateList all_certs_; // Cached certificates from system token. - net::ScopedCERTCertificateList system_certs_; + net::ScopedCERTCertificateList system_token_client_certs_; + + std::vector<const PolicyCertificateProvider*> policy_certificate_providers_; base::ThreadChecker thread_checker_;
diff --git a/chromeos/cert_loader_unittest.cc b/chromeos/cert_loader_unittest.cc index 3fd001b..6dcbdf07 100644 --- a/chromeos/cert_loader_unittest.cc +++ b/chromeos/cert_loader_unittest.cc
@@ -11,6 +11,7 @@ #include "base/bind.h" #include "base/files/file_util.h" +#include "base/macros.h" #include "base/test/scoped_task_environment.h" #include "crypto/scoped_nss_types.h" #include "crypto/scoped_test_nss_db.h" @@ -24,11 +25,73 @@ namespace chromeos { namespace { +class FakePolicyCertificateProvider : public PolicyCertificateProvider { + public: + void AddPolicyProvidedCertsObserver(Observer* observer) override { + observer_list_.AddObserver(observer); + } + + void RemovePolicyProvidedCertsObserver(Observer* observer) override { + observer_list_.RemoveObserver(observer); + } + + net::CertificateList GetAllServerAndAuthorityCertificates() const override { + // CertLoader does not call this. + NOTREACHED(); + return net::CertificateList(); + } + + net::CertificateList GetAllAuthorityCertificates() const override { + return authority_certificates_; + } + + net::CertificateList GetWebTrustedCertificates() const override { + // CertLoader does not call this. + NOTREACHED(); + return net::CertificateList(); + } + + net::CertificateList GetCertificatesWithoutWebTrust() const override { + // CertLoader does not call this. + NOTREACHED(); + return net::CertificateList(); + } + + void SetAuthorityCertificates( + const net::CertificateList& authority_certificates) { + authority_certificates_ = authority_certificates; + } + + void NotifyObservers() { + // CertLoader does not use these parameters - it calls + // |GetAllAuthorityCertificates| explicitly. + net::CertificateList all_server_and_authority_certs; + net::CertificateList trust_anchors; + for (auto& observer : observer_list_) { + observer.OnPolicyProvidedCertsChanged(all_server_and_authority_certs, + trust_anchors); + } + } + + private: + base::ObserverList<PolicyCertificateProvider::Observer, + true /* check_empty */>::Unchecked observer_list_; + net::CertificateList authority_certificates_; +}; + bool IsCertInCertificateList(CERTCertificate* cert, const net::ScopedCERTCertificateList& cert_list) { - for (net::ScopedCERTCertificateList::const_iterator it = cert_list.begin(); - it != cert_list.end(); ++it) { - if (net::x509_util::IsSameCertificate(it->get(), cert)) + for (const auto& cert_list_element : cert_list) { + if (net::x509_util::IsSameCertificate(cert_list_element.get(), cert)) + return true; + } + return false; +} + +bool IsCertInCertificateList(const net::X509Certificate* cert, + const net::ScopedCERTCertificateList& cert_list) { + for (const auto& cert_list_element : cert_list) { + if (net::x509_util::IsSameCertificate(cert_list_element.get(), cert)) return true; } return false; @@ -231,7 +294,7 @@ EXPECT_FALSE(cert_loader_->user_cert_database_load_finished()); EXPECT_TRUE(cert_loader_->initial_load_of_any_database_running()); EXPECT_TRUE(cert_loader_->all_certs().empty()); - EXPECT_TRUE(cert_loader_->system_certs().empty()); + EXPECT_TRUE(cert_loader_->system_token_client_certs().empty()); ASSERT_EQ(0U, GetAndResetCertificatesLoadedEventsCount()); scoped_task_environment_.RunUntilIdle(); @@ -243,7 +306,7 @@ // Default CA cert roots should get loaded. EXPECT_FALSE(cert_loader_->all_certs().empty()); - EXPECT_TRUE(cert_loader_->system_certs().empty()); + EXPECT_TRUE(cert_loader_->system_token_client_certs().empty()); } TEST_F(CertLoaderTest, BasicOnlySystemDB) { @@ -296,7 +359,7 @@ EXPECT_FALSE(cert_loader_->user_cert_database_load_finished()); EXPECT_TRUE(cert_loader_->initial_load_of_any_database_running()); EXPECT_TRUE(cert_loader_->all_certs().empty()); - EXPECT_TRUE(cert_loader_->system_certs().empty()); + EXPECT_TRUE(cert_loader_->system_token_client_certs().empty()); ASSERT_EQ(0U, GetAndResetCertificatesLoadedEventsCount()); scoped_task_environment_.RunUntilIdle(); @@ -306,8 +369,8 @@ EXPECT_FALSE(cert_loader_->user_cert_database_load_finished()); EXPECT_FALSE(cert_loader_->initial_load_of_any_database_running()); - EXPECT_TRUE(IsCertInCertificateList(system_token_cert.get(), - cert_loader_->system_certs())); + EXPECT_TRUE(IsCertInCertificateList( + system_token_cert.get(), cert_loader_->system_token_client_certs())); EXPECT_TRUE(IsCertInCertificateList(system_token_cert.get(), cert_loader_->all_certs())); @@ -317,7 +380,7 @@ EXPECT_FALSE(cert_loader_->user_cert_database_load_finished()); EXPECT_TRUE(cert_loader_->initial_load_of_any_database_running()); EXPECT_FALSE(cert_loader_->all_certs().empty()); - EXPECT_FALSE(cert_loader_->system_certs().empty()); + EXPECT_FALSE(cert_loader_->system_token_client_certs().empty()); ASSERT_EQ(0U, GetAndResetCertificatesLoadedEventsCount()); scoped_task_environment_.RunUntilIdle(); @@ -327,8 +390,8 @@ EXPECT_TRUE(cert_loader_->user_cert_database_load_finished()); EXPECT_FALSE(cert_loader_->initial_load_of_any_database_running()); - EXPECT_FALSE(IsCertInCertificateList(user_token_cert.get(), - cert_loader_->system_certs())); + EXPECT_FALSE(IsCertInCertificateList( + user_token_cert.get(), cert_loader_->system_token_client_certs())); EXPECT_TRUE(IsCertInCertificateList(user_token_cert.get(), cert_loader_->all_certs())); } @@ -359,7 +422,7 @@ EXPECT_FALSE(cert_loader_->user_cert_database_load_finished()); EXPECT_TRUE(cert_loader_->initial_load_of_any_database_running()); EXPECT_TRUE(cert_loader_->all_certs().empty()); - EXPECT_TRUE(cert_loader_->system_certs().empty()); + EXPECT_TRUE(cert_loader_->system_token_client_certs().empty()); ASSERT_EQ(0U, GetAndResetCertificatesLoadedEventsCount()); scoped_task_environment_.RunUntilIdle(); @@ -369,8 +432,8 @@ EXPECT_FALSE(cert_loader_->user_cert_database_load_finished()); EXPECT_FALSE(cert_loader_->initial_load_of_any_database_running()); - EXPECT_TRUE(IsCertInCertificateList(system_token_cert.get(), - cert_loader_->system_certs())); + EXPECT_TRUE(IsCertInCertificateList( + system_token_cert.get(), cert_loader_->system_token_client_certs())); EXPECT_TRUE(IsCertInCertificateList(system_token_cert.get(), cert_loader_->all_certs())); @@ -380,7 +443,7 @@ EXPECT_FALSE(cert_loader_->user_cert_database_load_finished()); EXPECT_TRUE(cert_loader_->initial_load_of_any_database_running()); EXPECT_FALSE(cert_loader_->all_certs().empty()); - EXPECT_FALSE(cert_loader_->system_certs().empty()); + EXPECT_FALSE(cert_loader_->system_token_client_certs().empty()); ASSERT_EQ(0U, GetAndResetCertificatesLoadedEventsCount()); scoped_task_environment_.RunUntilIdle(); @@ -390,8 +453,8 @@ EXPECT_TRUE(cert_loader_->user_cert_database_load_finished()); EXPECT_FALSE(cert_loader_->initial_load_of_any_database_running()); - EXPECT_FALSE(IsCertInCertificateList(user_token_cert.get(), - cert_loader_->system_certs())); + EXPECT_FALSE(IsCertInCertificateList( + user_token_cert.get(), cert_loader_->system_token_client_certs())); EXPECT_EQ(1U, CountCertOccurencesInCertificateList( user_token_cert.get(), cert_loader_->all_certs())); } @@ -451,7 +514,7 @@ TEST_F(CertLoaderTest, ClientLoaderUpdateOnNewClientCertInSystemToken) { StartCertLoaderWithPrimaryDBAndSystemToken(); - EXPECT_TRUE(cert_loader_->system_certs().empty()); + EXPECT_TRUE(cert_loader_->system_token_client_certs().empty()); net::ScopedCERTCertificate cert(ImportClientCertAndKey( primary_certdb_.get(), primary_certdb_->GetSystemSlot().get())); ASSERT_TRUE(cert); @@ -461,9 +524,9 @@ EXPECT_EQ(1U, GetAndResetCertificatesLoadedEventsCount()); EXPECT_TRUE(IsCertInCertificateList(cert.get(), cert_loader_->all_certs())); - EXPECT_EQ(1U, cert_loader_->system_certs().size()); - EXPECT_TRUE( - IsCertInCertificateList(cert.get(), cert_loader_->system_certs())); + EXPECT_EQ(1U, cert_loader_->system_token_client_certs().size()); + EXPECT_TRUE(IsCertInCertificateList( + cert.get(), cert_loader_->system_token_client_certs())); } TEST_F(CertLoaderTest, CertLoaderNoUpdateOnNewClientCertInSecondaryDb) { @@ -526,4 +589,101 @@ EXPECT_EQ(1U, GetAndResetCertificatesLoadedEventsCount()); } +TEST_F(CertLoaderTest, UpdateSinglePolicyCertificateProvider) { + // Load a CA cert for testing. + scoped_refptr<net::X509Certificate> cert = net::ImportCertFromFile( + net::GetTestCertsDirectory(), "websocket_cacert.pem"); + ASSERT_TRUE(cert.get()); + StartCertLoaderWithPrimaryDB(); + + FakePolicyCertificateProvider device_policy_certs_provider; + + // Setting the cert provider triggers an update. + cert_loader_->AddPolicyCertificateProvider(&device_policy_certs_provider); + ASSERT_EQ(1U, GetAndResetCertificatesLoadedEventsCount()); + + // When policy changes, an update is triggered too. + EXPECT_FALSE(IsCertInCertificateList(cert.get(), cert_loader_->all_certs())); + device_policy_certs_provider.SetAuthorityCertificates({cert}); + device_policy_certs_provider.NotifyObservers(); + ASSERT_EQ(1U, GetAndResetCertificatesLoadedEventsCount()); + EXPECT_TRUE(IsCertInCertificateList(cert.get(), cert_loader_->all_certs())); + + // Removing the cert provider triggers an update. + cert_loader_->RemovePolicyCertificateProvider(&device_policy_certs_provider); + ASSERT_EQ(1U, GetAndResetCertificatesLoadedEventsCount()); + EXPECT_FALSE(IsCertInCertificateList(cert.get(), cert_loader_->all_certs())); +} + +TEST_F(CertLoaderTest, UpdateOnTwoPolicyCertificateProviders) { + // Load a CA cert for device and user policy. + scoped_refptr<net::X509Certificate> device_policy_cert = + net::ImportCertFromFile(net::GetTestCertsDirectory(), + "websocket_cacert.pem"); + ASSERT_TRUE(device_policy_cert.get()); + + scoped_refptr<net::X509Certificate> user_policy_cert = + net::ImportCertFromFile(net::GetTestCertsDirectory(), "root_ca_cert.pem"); + ASSERT_TRUE(user_policy_cert.get()); + + StartCertLoaderWithPrimaryDB(); + + FakePolicyCertificateProvider device_policy_certs_provider; + device_policy_certs_provider.SetAuthorityCertificates({device_policy_cert}); + FakePolicyCertificateProvider user_policy_certs_provider; + user_policy_certs_provider.SetAuthorityCertificates({user_policy_cert}); + + // Adding a first policy certificate provider triggers an update. In this test + // case, the device policy certs provider already contains a cert. + cert_loader_->AddPolicyCertificateProvider(&device_policy_certs_provider); + ASSERT_EQ(1U, GetAndResetCertificatesLoadedEventsCount()); + EXPECT_TRUE(IsCertInCertificateList(device_policy_cert.get(), + cert_loader_->all_certs())); + EXPECT_FALSE(IsCertInCertificateList(user_policy_cert.get(), + cert_loader_->all_certs())); + + // Adding a second policy certificate provider triggers an update. In this + // test case, the user policy certs provider already contains a cert. + cert_loader_->AddPolicyCertificateProvider(&user_policy_certs_provider); + ASSERT_EQ(1U, GetAndResetCertificatesLoadedEventsCount()); + EXPECT_TRUE(IsCertInCertificateList(device_policy_cert.get(), + cert_loader_->all_certs())); + EXPECT_TRUE(IsCertInCertificateList(user_policy_cert.get(), + cert_loader_->all_certs())); + + cert_loader_->RemovePolicyCertificateProvider(&user_policy_certs_provider); + ASSERT_EQ(1U, GetAndResetCertificatesLoadedEventsCount()); + cert_loader_->RemovePolicyCertificateProvider(&device_policy_certs_provider); + ASSERT_EQ(1U, GetAndResetCertificatesLoadedEventsCount()); +} + +TEST_F(CertLoaderTest, + NoUpdateDueToPolicyCertificateProviderBeforeCertDbLoaded) { + // Load a CA cert for testing. + scoped_refptr<net::X509Certificate> cert = net::ImportCertFromFile( + net::GetTestCertsDirectory(), "websocket_cacert.pem"); + ASSERT_TRUE(cert.get()); + + FakePolicyCertificateProvider device_policy_certs_provider; + + // Setting the cert provider does not trigger an update yet, because the + // CertLoader has not been set to use a system or user NSS Database. + cert_loader_->AddPolicyCertificateProvider(&device_policy_certs_provider); + ASSERT_EQ(0U, GetAndResetCertificatesLoadedEventsCount()); + + // Same when the policy changes. + EXPECT_FALSE(IsCertInCertificateList(cert.get(), cert_loader_->all_certs())); + device_policy_certs_provider.SetAuthorityCertificates({cert}); + device_policy_certs_provider.NotifyObservers(); + ASSERT_EQ(0U, GetAndResetCertificatesLoadedEventsCount()); + + // After starting the CertLoader, the policy-provided cert is there. + StartCertLoaderWithPrimaryDB(); + EXPECT_TRUE(IsCertInCertificateList(cert.get(), cert_loader_->all_certs())); + + // Removing the cert provider triggers an update. + cert_loader_->RemovePolicyCertificateProvider(&device_policy_certs_provider); + ASSERT_EQ(1U, GetAndResetCertificatesLoadedEventsCount()); + EXPECT_FALSE(IsCertInCertificateList(cert.get(), cert_loader_->all_certs())); +} } // namespace chromeos
diff --git a/chromeos/network/client_cert_resolver.cc b/chromeos/network/client_cert_resolver.cc index dba950495..ff099c0 100644 --- a/chromeos/network/client_cert_resolver.cc +++ b/chromeos/network/client_cert_resolver.cc
@@ -284,12 +284,13 @@ } // Searches for matches between |networks| and |all_certs| (for networks -// configured in user policy) / |system_certs| (for networks configured in -// device policy). Returns the matches that were found. Because this calls NSS -// functions and is potentially slow, it must be run on a worker thread. +// configured in user policy) / |system_token_client_certs| (for networks +// configured in device policy). Returns the matches that were found. Because +// this calls NSS functions and is potentially slow, it must be run on a worker +// thread. std::vector<NetworkAndMatchingCert> FindCertificateMatches( net::ScopedCERTCertificateList all_certs, - net::ScopedCERTCertificateList system_certs, + net::ScopedCERTCertificateList system_token_client_certs, const std::vector<NetworkAndCertPattern>& networks, base::Time now) { std::vector<NetworkAndMatchingCert> matches; @@ -297,7 +298,7 @@ std::vector<CertAndIssuer> all_client_certs( CreateSortedCertAndIssuerList(std::move(all_certs), now)); std::vector<CertAndIssuer> system_client_certs( - CreateSortedCertAndIssuerList(std::move(system_certs), now)); + CreateSortedCertAndIssuerList(std::move(system_token_client_certs), now)); for (const NetworkAndCertPattern& network_and_pattern : networks) { // Use only certs from the system token if the source of the client cert @@ -425,10 +426,10 @@ // system token if the source of the client cert pattern is device policy. std::vector<CertAndIssuer> client_certs; if (client_cert_config.onc_source == ::onc::ONC_SOURCE_DEVICE_POLICY) { - client_certs = - CreateSortedCertAndIssuerList(net::x509_util::DupCERTCertificateList( - CertLoader::Get()->system_certs()), - base::Time::Now()); + client_certs = CreateSortedCertAndIssuerList( + net::x509_util::DupCERTCertificateList( + CertLoader::Get()->system_token_client_certs()), + base::Time::Now()); } else { client_certs = CreateSortedCertAndIssuerList( net::x509_util::DupCERTCertificateList(CertLoader::Get()->all_certs()), @@ -622,7 +623,7 @@ net::x509_util::DupCERTCertificateList( CertLoader::Get()->all_certs()), net::x509_util::DupCERTCertificateList( - CertLoader::Get()->system_certs()), + CertLoader::Get()->system_token_client_certs()), networks_to_resolve, Now()), base::BindOnce(&ClientCertResolver::ConfigureCertificates, weak_ptr_factory_.GetWeakPtr()));
diff --git a/chromeos/network/client_cert_resolver_unittest.cc b/chromeos/network/client_cert_resolver_unittest.cc index d69b055f..18585a01 100644 --- a/chromeos/network/client_cert_resolver_unittest.cc +++ b/chromeos/network/client_cert_resolver_unittest.cc
@@ -595,7 +595,7 @@ StartCertLoader(); scoped_task_environment_.RunUntilIdle(); - EXPECT_EQ(1U, cert_loader_->system_certs().size()); + EXPECT_EQ(1U, cert_loader_->system_token_client_certs().size()); // Verify that the resolver positively matched the pattern in the policy with // the test client cert and configured the network. @@ -633,7 +633,7 @@ StartCertLoader(); scoped_task_environment_.RunUntilIdle(); - EXPECT_EQ(1U, cert_loader_->system_certs().size()); + EXPECT_EQ(1U, cert_loader_->system_token_client_certs().size()); // Verify that the resolver positively matched the pattern in the policy with // the test client cert and configured the network. @@ -672,7 +672,7 @@ network_properties_changed_count_ = 0; StartCertLoader(); scoped_task_environment_.RunUntilIdle(); - EXPECT_EQ(0U, cert_loader_->system_certs().size()); + EXPECT_EQ(0U, cert_loader_->system_token_client_certs().size()); // Verify that no client certificate was configured. std::string pkcs11_id;
diff --git a/chrome/browser/chromeos/policy/policy_certificate_provider.h b/chromeos/policy_certificate_provider.h similarity index 76% rename from chrome/browser/chromeos/policy/policy_certificate_provider.h rename to chromeos/policy_certificate_provider.h index ae1654ec..32b6b5d2 100644 --- a/chrome/browser/chromeos/policy/policy_certificate_provider.h +++ b/chromeos/policy_certificate_provider.h
@@ -2,10 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_CHROMEOS_POLICY_POLICY_CERTIFICATE_PROVIDER_H_ -#define CHROME_BROWSER_CHROMEOS_POLICY_POLICY_CERTIFICATE_PROVIDER_H_ +#ifndef CHROMEOS_POLICY_CERTIFICATE_PROVIDER_H_ +#define CHROMEOS_POLICY_CERTIFICATE_PROVIDER_H_ -#include <memory> #include <vector> #include "base/macros.h" @@ -16,8 +15,11 @@ using CertificateList = std::vector<scoped_refptr<X509Certificate>>; } // namespace net -namespace policy { +namespace chromeos { +// An interface for a class which makes server and authority certificates +// available from enterprise policy. Clients of this interface can register as +// |Observer|s to receive update notifications. class PolicyCertificateProvider { public: virtual ~PolicyCertificateProvider() {} @@ -40,6 +42,10 @@ // independent of their trust bits. virtual net::CertificateList GetAllServerAndAuthorityCertificates() const = 0; + // Returns all authority certificates successfully parsed from ONC, + // independent of their trust bits. + virtual net::CertificateList GetAllAuthorityCertificates() const = 0; + // Returns the server and authority certificates which were successfully // parsed from ONC and were granted web trust. This means that the // certificates had the "Web" trust bit set, and this @@ -55,6 +61,6 @@ virtual net::CertificateList GetCertificatesWithoutWebTrust() const = 0; }; -} // namespace policy +} // namespace chromeos -#endif // CHROME_BROWSER_CHROMEOS_POLICY_POLICY_CERTIFICATE_PROVIDER_H_ +#endif // CHROMEOS_POLICY_CERTIFICATE_PROVIDER_H_
diff --git a/chromeos/test/data/network/root_ca_cert.pem b/chromeos/test/data/network/root_ca_cert.pem new file mode 100644 index 0000000..6957b749 --- /dev/null +++ b/chromeos/test/data/network/root_ca_cert.pem
@@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIC8zCCAdugAwIBAgIJALF9qhLor0+aMA0GCSqGSIb3DQEBBQUAMBcxFTATBgNV +BAMMDFRlc3QgUm9vdCBDQTAeFw0xNDA4MTQwMzA1MjlaFw0yNDA4MTEwMzA1Mjla +MBcxFTATBgNVBAMMDFRlc3QgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEP +ADCCAQoCggEBALZJQeNCAVGofzx6cdP7zZE1F4QajvY2x9FwHfqG8267dm/oMi43 +/TiSPWjkin1CMxRGG9wE9pFuVEDECgn97C1i4l7huiycwbFgTNrH+CJcgiBlQh5W +d3VP65AsSupXDiKNbJWsEerM1+72cA0J3aY1YV3Jdm2w8h6/MIbYd1I2lZcO0UbF +7YE9G7DyYZU8wUA4719dumGf7yucn4WJdHBj1XboNX7OAeHzERGQHA31/Y3OEGyt +fFUaIW/XLfR4FeovOL2RnjwdB0b1Q8GCi68SU2UZimlpZgay2gv6KgChKhWESfEB +v5swBtAVoB+dUZFH4VNf717swmF5whSfxOMCAwEAAaNCMEAwDwYDVR0TAQH/BAUw +AwEB/zAdBgNVHQ4EFgQUvPcw0TzA8nn675/JbFyT84poq4MwDgYDVR0PAQH/BAQD +AgEGMA0GCSqGSIb3DQEBBQUAA4IBAQBXByn7f+j/sObYWGrDkKE4HLTzaLHs6Ikj +JNeo8iHDYOSkSVwAv9/HgniAKxj3rd3QYl6nsMzwqrTOcBJZZWd2BQAYmv/EKhfj +8VXYvlxe68rLU4cQ1QkyNqdeQfRT2n5WYNJ+TpqlCF9ddennMMsi6e8ZSYOlI6H4 +YEzlNtU5eBjxXr/OqgtTgSx4qQpr2xMQIRR/G3A9iRpAigYsXVAZYvnHRYnyPWYF +PX11W1UegEJyoZp8bQp09u6mIWw6mPt3gl/ya1bm3ZuOUPDGrv3qpgUHqSYGVrOy +2bI3oCE+eQYfuVG+9LFJTZC1M+UOx15bQMVqBNFDepRqpE9h/ILg +-----END CERTIFICATE----- +
diff --git a/components/autofill/core/browser/autofill_experiments.cc b/components/autofill/core/browser/autofill_experiments.cc index c604b82..4ca0292a 100644 --- a/components/autofill/core/browser/autofill_experiments.cc +++ b/components/autofill/core/browser/autofill_experiments.cc
@@ -47,13 +47,15 @@ } // namespace #endif // defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) -#if !defined(OS_ANDROID) +#if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) const base::Feature kAutofillDropdownLayoutExperiment{ "AutofillDropdownLayout", base::FEATURE_DISABLED_BY_DEFAULT}; const char kAutofillDropdownLayoutParameterName[] = "variant"; const char kAutofillDropdownLayoutParameterLeadingIcon[] = "leading-icon"; const char kAutofillDropdownLayoutParameterTrailingIcon[] = "trailing-icon"; -#endif // !defined(OS_ANDROID) +const char kAutofillDropdownLayoutParameterTwoLinesLeadingIcon[] = + "two-lines-leading-icon"; +#endif // defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) #if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) const base::Feature kAutofillPrimaryInfoStyleExperiment{ @@ -194,9 +196,10 @@ } #endif // defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) -#if !defined(OS_ANDROID) +#if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) ForcedPopupLayoutState GetForcedPopupLayoutState() { - if (!base::FeatureList::IsEnabled(kAutofillDropdownLayoutExperiment)) + if (!base::FeatureList::IsEnabled( + autofill::kAutofillDropdownLayoutExperiment)) return ForcedPopupLayoutState::kDefault; std::string param = base::GetFieldTrialParamValueByFeature( @@ -206,12 +209,17 @@ return ForcedPopupLayoutState::kLeadingIcon; } else if (param == kAutofillDropdownLayoutParameterTrailingIcon) { return ForcedPopupLayoutState::kTrailingIcon; + } else if (param == + autofill::kAutofillDropdownLayoutParameterTwoLinesLeadingIcon) { + return ForcedPopupLayoutState::kTwoLinesLeadingIcon; + } else if (param.empty()) { + return ForcedPopupLayoutState::kDefault; } // Unknown parameter value. NOTREACHED(); return ForcedPopupLayoutState::kDefault; } -#endif // !defined(OS_ANDROID) +#endif // defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) } // namespace autofill
diff --git a/components/autofill/core/browser/autofill_experiments.h b/components/autofill/core/browser/autofill_experiments.h index 7cada163..ee4bf603 100644 --- a/components/autofill/core/browser/autofill_experiments.h +++ b/components/autofill/core/browser/autofill_experiments.h
@@ -23,12 +23,13 @@ namespace autofill { // Parameterized Features (grouped with parameter name and options) -#if !defined(OS_ANDROID) +#if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) extern const base::Feature kAutofillDropdownLayoutExperiment; extern const char kAutofillDropdownLayoutParameterName[]; extern const char kAutofillDropdownLayoutParameterLeadingIcon[]; extern const char kAutofillDropdownLayoutParameterTrailingIcon[]; -#endif // !defined(OS_ANDROID) +extern const char kAutofillDropdownLayoutParameterTwoLinesLeadingIcon[]; +#endif // defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) #if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) extern const base::Feature kAutofillPrimaryInfoStyleExperiment; @@ -79,18 +80,21 @@ ForcedFontWeight GetForcedFontWeight(); #endif // defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) -#if !defined(OS_ANDROID) +#if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) enum class ForcedPopupLayoutState { kDefault, // No popup layout forced by experiment. kLeadingIcon, // Experiment forces leading (left in LTR) icon layout. kTrailingIcon, // Experiment forces trailing (right in LTR) icon layout. + kTwoLinesLeadingIcon, // Experiment forces leading (left in LTR) icon layout. + // with two lines display. }; + // Returns kDefault if no experimental behavior is enabled for // kAutofillDropdownLayoutExperiment; returns kLeftIcon or kRightIcon // if the experiment param matches kAutofillDropdownLayoutParameterLeadingIcon // or kAutofillDropdownLayoutParameterTrailingIcon, respectively. ForcedPopupLayoutState GetForcedPopupLayoutState(); -#endif // !defined(OS_ANDROID) +#endif // defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN) } // namespace autofill
diff --git a/components/autofill/core/browser/credit_card.cc b/components/autofill/core/browser/credit_card.cc index 2b9c8029..3c309e8b 100644 --- a/components/autofill/core/browser/credit_card.cc +++ b/components/autofill/core/browser/credit_card.cc
@@ -796,6 +796,22 @@ : BankNameAndLastFourDigits(); } +base::string16 +CreditCard::NetworkOrBankNameLastFourDigitsAndDescriptiveExpiration( + const std::string& app_locale) const { + return l10n_util::GetStringFUTF16( + IDS_AUTOFILL_CREDIT_CARD_TWO_LINE_LABEL_FROM_NAME, + NetworkOrBankNameAndLastFourDigits(), + GetInfo(AutofillType(CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR), app_locale)); +} + +base::string16 CreditCard::DescriptiveExpiration( + const std::string& app_locale) const { + return l10n_util::GetStringFUTF16( + IDS_AUTOFILL_CREDIT_CARD_TWO_LINE_LABEL_FROM_CARD_NUMBER, + GetInfo(AutofillType(CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR), app_locale)); +} + base::string16 CreditCard::AbbreviatedExpirationDateForDisplay() const { base::string16 month = ExpirationMonthAsString(); base::string16 year = Expiration2DigitYearAsString();
diff --git a/components/autofill/core/browser/credit_card.h b/components/autofill/core/browser/credit_card.h index 30c394a..9fa815d 100644 --- a/components/autofill/core/browser/credit_card.h +++ b/components/autofill/core/browser/credit_card.h
@@ -243,9 +243,22 @@ // A label for this card formatted as 'IssuerNetwork - ****2345'. base::string16 NetworkAndLastFourDigits() const; // A label for this card formatted as 'BankName' - ****2345' if bank name - // experiment turned on and bank name available; otherwise, formated as + // experiment turned on and bank name available; otherwise, formatted as // 'IssuerNetwork - ****2345'. base::string16 NetworkOrBankNameAndLastFourDigits() const; + // A label for this card formatted as + // 'BankName/Netowrk' - ****2345, expires on MM/YY' if bank name + // experiment turned on and bank name available; otherwise, formatted as + // 'IssuerNetwork - ****2345, expires on MM/YY'. + // This label is used as a second line label when the autofill dropdown + // layout experiment is enabled and the cardholder name is selected. + base::string16 NetworkOrBankNameLastFourDigitsAndDescriptiveExpiration( + const std::string& app_locale) const; + // A label for this card formatted as 'Expires on MM/YY'. + // This label is used as a second line label when the autofill dropdown + // uses a two line layout and the credit card number is selected. + base::string16 DescriptiveExpiration(const std::string& app_locale) const; + // Localized expiration for this card formatted as 'Exp: 06/17'. base::string16 AbbreviatedExpirationDateForDisplay() const; // Formatted expiration date (e.g., 05/2020).
diff --git a/components/autofill/core/browser/personal_data_manager.cc b/components/autofill/core/browser/personal_data_manager.cc index 45e5d9d..005ec0512 100644 --- a/components/autofill/core/browser/personal_data_manager.cc +++ b/components/autofill/core/browser/personal_data_manager.cc
@@ -1234,6 +1234,7 @@ LoadProfiles(); LoadCreditCards(); LoadPaymentsCustomerData(); + profile_validities_need_update = true; } std::vector<AutofillProfile*> PersonalDataManager::GetProfilesToSuggest() @@ -1408,8 +1409,11 @@ unique_matched_profiles, &other_field_types, type.GetStorableType(), 1, app_locale_, &labels); DCHECK_EQ(unique_suggestions.size(), labels.size()); - for (size_t i = 0; i < labels.size(); i++) + for (size_t i = 0; i < labels.size(); i++) { unique_suggestions[i].label = labels[i]; + // Used when two-line display is enabled. + unique_suggestions[i].additional_label = labels[i]; + } return unique_suggestions; } @@ -2161,6 +2165,9 @@ suggestion->value = credit_card->NetworkOrBankNameAndLastFourDigits(); suggestion->label = credit_card->GetInfo( AutofillType(CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR), app_locale_); + // The additional label will be used if two-line display is enabled. + suggestion->additional_label = + credit_card->DescriptiveExpiration(app_locale_); } else if (credit_card->number().empty()) { if (type.GetStorableType() != CREDIT_CARD_NAME_FULL) { suggestion->label = credit_card->GetInfo( @@ -2174,6 +2181,13 @@ suggestion->label = credit_card->NetworkOrBankNameAndLastFourDigits(); #else suggestion->label = credit_card->ObfuscatedLastFourDigits(); + // Ad the card number with expiry information in the additional + // label portion so that we an show it when two-line display is + // enabled. + suggestion->additional_label = + credit_card + ->NetworkOrBankNameLastFourDigitsAndDescriptiveExpiration( + app_locale_); #endif } }
diff --git a/components/autofill/core/browser/suggestion.h b/components/autofill/core/browser/suggestion.h index b18338b6..bef99f8 100644 --- a/components/autofill/core/browser/suggestion.h +++ b/components/autofill/core/browser/suggestion.h
@@ -47,6 +47,8 @@ base::string16 value; base::string16 label; // Used only for passwords to show the password value. + // Also used to display an extra line of information if two line + // display is enabled. base::string16 additional_label; // Contains an image to display for the suggestion. gfx::Image custom_icon;
diff --git a/components/autofill/core/common/autofill_features.cc b/components/autofill/core/common/autofill_features.cc index 40f8cac2..0ef9491 100644 --- a/components/autofill/core/common/autofill_features.cc +++ b/components/autofill/core/common/autofill_features.cc
@@ -297,11 +297,6 @@ "AutofillRefreshStyleAndroid", base::FEATURE_DISABLED_BY_DEFAULT}; #endif // OS_ANDROID -#if defined(OS_MACOSX) -const base::Feature kMacViewsAutofillPopup{"MacViewsAutofillPopup", - base::FEATURE_ENABLED_BY_DEFAULT}; -#endif // defined(OS_MACOSX) - bool IsAutofillCreditCardAssistEnabled() { #if !defined(OS_ANDROID) && !defined(OS_IOS) return false; @@ -351,17 +346,6 @@ return base::FeatureList::IsEnabled(kAutofillUpstreamUpdatePromptExplanation); } -#if defined(OS_MACOSX) -bool IsMacViewsAutofillPopupExperimentEnabled() { -#if BUILDFLAG(MAC_VIEWS_BROWSER) - if (!::features::IsViewsBrowserCocoa()) - return true; -#endif - - return base::FeatureList::IsEnabled(kMacViewsAutofillPopup); -} -#endif // defined(OS_MACOSX) - bool IsPasswordManualFallbackEnabled() { return base::FeatureList::IsEnabled(kAutofillManualFallback); }
diff --git a/components/autofill/core/common/autofill_features.h b/components/autofill/core/common/autofill_features.h index ec2ff716..681a6b7 100644 --- a/components/autofill/core/common/autofill_features.h +++ b/components/autofill/core/common/autofill_features.h
@@ -90,10 +90,6 @@ extern const base::Feature kAutofillRefreshStyleAndroid; #endif // OS_ANDROID -#if defined(OS_MACOSX) -extern const base::Feature kMacViewsAutofillPopup; -#endif // defined(OS_MACOSX) - // Returns whether the Autofill credit card assist infobar should be shown. bool IsAutofillCreditCardAssistEnabled();
diff --git a/components/autofill_strings.grdp b/components/autofill_strings.grdp index 992922d2..9c93add1 100644 --- a/components/autofill_strings.grdp +++ b/components/autofill_strings.grdp
@@ -305,6 +305,12 @@ <message name="IDS_AUTOFILL_CREDIT_CARD_EXPIRATION_DATE_LABEL_AND_ABBR" desc="Text displayed in the Autofill Credit Card popup before the credit card expiration date and the abbreviated expiration date."> , exp <ph name="EXPIRATION_DATE_ABBR">$1<ex>06/17</ex></ph> </message> + <message name="IDS_AUTOFILL_CREDIT_CARD_TWO_LINE_LABEL_FROM_NAME" desc="Second line label for the autofill credit card popup when the name is selected. This text will appear below the cardholder name. [CHAR-LIMIT=32]"> + <ph name="CREDIT_CARD">$1<ex>Visa - ****5679</ex></ph>, expires on <ph name="EXPIRATION_DATE_ABBR">$2<ex>06/17</ex></ph> + </message> + <message name="IDS_AUTOFILL_CREDIT_CARD_TWO_LINE_LABEL_FROM_CARD_NUMBER" desc="Second line label for the autofill credit card popup when the card number is selected. This text will appear below the credit card number. [CHAR-LIMIT=32]"> + Expires on <ph name="EXPIRATION_DATE_ABBR">$1<ex>06/17</ex></ph> + </message> <!-- Autofill credit card unmask prompt --> <message name="IDS_AUTOFILL_CARD_UNMASK_PROMPT_ERROR_TRY_AGAIN_CVC" desc="Error message that encourages the user to try to re-enter their credit card CVC after a previous failed attempt." formatter_data="android_java">
diff --git a/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/BackgroundTask.java b/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/BackgroundTask.java index 8e176add9..dcbe49c 100644 --- a/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/BackgroundTask.java +++ b/components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/BackgroundTask.java
@@ -13,7 +13,7 @@ * this interface must have a public constructor which takes no arguments. * The callbacks will be executed on the main thread, which means that execution logic must be * offloaded to another {@link Thread}, {@link android.os.Handler} or {@link - * org.chromium.base.AsyncTask}. + * org.chromium.base.task.AsyncTask}. */ public interface BackgroundTask { /** @@ -37,7 +37,7 @@ * from this method when you are done processing. If this is a long-running task, you should * return true from this method, and instead invoke the {@link TaskFinishedCallback} when the * processing is finished on some other {@link Thread}, {@link android.os.Handler} or - * {@link org.chromium.base.AsyncTask}. While this method is running the + * {@link org.chromium.base.task.AsyncTask}. While this method is running the * system holds a wakelock. If false is returned from this method, the wakelock is immediately * released, but if this method returns true, the wakelock is not released until either the * {@link TaskFinishedCallback} is invoked, or the system calls {@link #onStopTask(Context,
diff --git a/components/cronet/android/BUILD.gn b/components/cronet/android/BUILD.gn index 08d5a456..791de37b 100644 --- a/components/cronet/android/BUILD.gn +++ b/components/cronet/android/BUILD.gn
@@ -1363,7 +1363,6 @@ "//components/cronet/android/java/src", "//net/android/java/src", "//url/android/java/src", - "//third_party/android_async_task/java/src", ] source_deps = [ ":cronet_impl_native_base_java",
diff --git a/components/cronet/android/test/javaperftests/src/org/chromium/net/CronetPerfTestActivity.java b/components/cronet/android/test/javaperftests/src/org/chromium/net/CronetPerfTestActivity.java index 0a380ec..96c468b3 100644 --- a/components/cronet/android/test/javaperftests/src/org/chromium/net/CronetPerfTestActivity.java +++ b/components/cronet/android/test/javaperftests/src/org/chromium/net/CronetPerfTestActivity.java
@@ -14,9 +14,9 @@ import org.json.JSONException; import org.json.JSONObject; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.PathUtils; +import org.chromium.base.task.AsyncTask; import java.io.File; import java.io.FileOutputStream;
diff --git a/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GCMDriver.java b/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GCMDriver.java index 7bac546..00219cd 100644 --- a/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GCMDriver.java +++ b/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GCMDriver.java
@@ -4,12 +4,12 @@ package org.chromium.components.gcm_driver; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.task.AsyncTask; import java.io.IOException;
diff --git a/components/gcm_driver/instance_id/android/java/src/org/chromium/components/gcm_driver/instance_id/InstanceIDBridge.java b/components/gcm_driver/instance_id/android/java/src/org/chromium/components/gcm_driver/instance_id/InstanceIDBridge.java index da3a479..bfbb5a29 100644 --- a/components/gcm_driver/instance_id/android/java/src/org/chromium/components/gcm_driver/instance_id/InstanceIDBridge.java +++ b/components/gcm_driver/instance_id/android/java/src/org/chromium/components/gcm_driver/instance_id/InstanceIDBridge.java
@@ -7,11 +7,11 @@ import android.content.SharedPreferences; import android.os.Bundle; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.task.AsyncTask; import java.io.IOException; import java.util.Collections;
diff --git a/components/metrics/BUILD.gn b/components/metrics/BUILD.gn index def6ed2..2dea5dc6 100644 --- a/components/metrics/BUILD.gn +++ b/components/metrics/BUILD.gn
@@ -115,6 +115,7 @@ "//components/variations", "//components/version_info:version_info", "//extensions/buildflags", + "//services/network/public/cpp:cpp", "//third_party/zlib/google:compression_utils", ]
diff --git a/components/metrics/net/network_metrics_provider.cc b/components/metrics/net/network_metrics_provider.cc index d175648..d64d8aa 100644 --- a/components/metrics/net/network_metrics_provider.cc +++ b/components/metrics/net/network_metrics_provider.cc
@@ -54,63 +54,6 @@ return SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_UNKNOWN; } -// Listens to the changes in the effective conection type. -class NetworkMetricsProvider::EffectiveConnectionTypeObserver - : public net::EffectiveConnectionTypeObserver { - public: - // |network_quality_estimator| is used to provide the network quality - // estimates. Guaranteed to be non-null. |callback| is run on - // |callback_task_runner|, and provides notifications about the changes in the - // effective connection type. - EffectiveConnectionTypeObserver( - base::Callback<void(net::EffectiveConnectionType)> callback, - const scoped_refptr<base::SequencedTaskRunner>& callback_task_runner) - : network_quality_estimator_(nullptr), - callback_(callback), - callback_task_runner_(callback_task_runner) { - DCHECK(callback_); - DCHECK(callback_task_runner_); - // |this| is initialized and used on the IO thread using - // |network_quality_task_runner_|. - thread_checker_.DetachFromThread(); - } - - ~EffectiveConnectionTypeObserver() override { - DCHECK(thread_checker_.CalledOnValidThread()); - if (network_quality_estimator_) - network_quality_estimator_->RemoveEffectiveConnectionTypeObserver(this); - } - - // Initializes |this| on IO thread using |network_quality_task_runner_|. This - // is the same thread on which |network_quality_estimator| lives. - void Init(net::NetworkQualityEstimator* network_quality_estimator) { - network_quality_estimator_ = network_quality_estimator; - if (network_quality_estimator_) - network_quality_estimator_->AddEffectiveConnectionTypeObserver(this); - } - - private: - // net::EffectiveConnectionTypeObserver: - void OnEffectiveConnectionTypeChanged( - net::EffectiveConnectionType type) override { - DCHECK(thread_checker_.CalledOnValidThread()); - callback_task_runner_->PostTask(FROM_HERE, base::BindOnce(callback_, type)); - } - - // Notifies |this| when there is a change in the effective connection type. - net::NetworkQualityEstimator* network_quality_estimator_; - - // Called when the effective connection type is changed. - base::Callback<void(net::EffectiveConnectionType)> callback_; - - // Task runner on which |callback_| is run. - scoped_refptr<base::SequencedTaskRunner> callback_task_runner_; - - base::ThreadChecker thread_checker_; - - DISALLOW_COPY_AND_ASSIGN(EffectiveConnectionTypeObserver); -}; - NetworkMetricsProvider::NetworkMetricsProvider( std::unique_ptr<NetworkQualityEstimatorProvider> network_quality_estimator_provider) @@ -122,6 +65,7 @@ total_codes_(0), network_quality_estimator_provider_( std::move(network_quality_estimator_provider)), + network_quality_tracker_(nullptr), effective_connection_type_(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN), min_effective_connection_type_(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN), max_effective_connection_type_(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN), @@ -134,52 +78,25 @@ ProbeWifiPHYLayerProtocol(); if (network_quality_estimator_provider_) { - effective_connection_type_observer_.reset( - new EffectiveConnectionTypeObserver( - base::Bind( - &NetworkMetricsProvider::OnEffectiveConnectionTypeChanged, - base::Unretained(this)), - base::ThreadTaskRunnerHandle::Get())); - - // Get the network quality estimator and initialize - // |effective_connection_type_observer_| on the same task runner on which - // the network quality estimator lives. It is safe to use base::Unretained - // here since both |network_quality_estimator_provider_| and - // |effective_connection_type_observer_| are owned by |this|, and - // |network_quality_estimator_provider_| is deleted before - // |effective_connection_type_observer_|. - network_quality_estimator_provider_->PostReplyNetworkQualityEstimator( - base::Bind( - &EffectiveConnectionTypeObserver::Init, - base::Unretained(effective_connection_type_observer_.get()))); + // Use |network_quality_estimator_provider_| to get network quality + // tracker. + network_quality_estimator_provider_->PostReplyNetworkQualityTracker( + base::BindOnce(&NetworkMetricsProvider::SetNetworkQualityTracker, + weak_ptr_factory_.GetWeakPtr())); } } NetworkMetricsProvider::~NetworkMetricsProvider() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this); - - if (network_quality_estimator_provider_) { - scoped_refptr<base::SequencedTaskRunner> network_quality_task_runner = - network_quality_estimator_provider_->GetTaskRunner(); - - // |network_quality_estimator_provider_| must be deleted before - // |effective_connection_type_observer_| since - // |effective_connection_type_observer_| may callback into - // |effective_connection_type_observer_|. - network_quality_estimator_provider_.reset(); - - if (network_quality_task_runner && - !network_quality_task_runner->DeleteSoon( - FROM_HERE, effective_connection_type_observer_.release())) { - NOTREACHED() << " ECT observer was not deleted successfully"; - } + if (network_quality_tracker_) { + network_quality_tracker_->RemoveEffectiveConnectionTypeObserver(this); } } void NetworkMetricsProvider::ProvideCurrentSessionData( ChromeUserMetricsExtension*) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // ProvideCurrentSessionData is called on the main thread, at the time a // metrics record is being finalized. net::NetworkChangeNotifier::FinalizingMetricsLogRecord(); @@ -188,7 +105,7 @@ void NetworkMetricsProvider::ProvideSystemProfileMetrics( SystemProfileProto* system_profile) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!connection_type_is_ambiguous_ || network_change_notifier_initialized_); SystemProfileProto::Network* network = system_profile->mutable_network(); @@ -234,7 +151,7 @@ void NetworkMetricsProvider::OnNetworkChanged( net::NetworkChangeNotifier::ConnectionType type) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // To avoid reporting an ambiguous connection type for users on flaky // connections, ignore transitions to the "none" state. Note that the // connection type is refreshed in ProvideSystemProfileMetrics() each time a @@ -268,7 +185,7 @@ SystemProfileProto::Network::ConnectionType NetworkMetricsProvider::GetConnectionType() const { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); switch (connection_type_) { case net::NetworkChangeNotifier::CONNECTION_NONE: return SystemProfileProto::Network::CONNECTION_NONE; @@ -293,7 +210,7 @@ SystemProfileProto::Network::WifiPHYLayerProtocol NetworkMetricsProvider::GetWifiPHYLayerProtocol() const { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); switch (wifi_phy_layer_protocol_) { case net::WIFI_PHY_LAYER_PROTOCOL_NONE: return SystemProfileProto::Network::WIFI_PHY_LAYER_PROTOCOL_NONE; @@ -315,7 +232,7 @@ } void NetworkMetricsProvider::ProbeWifiPHYLayerProtocol() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT, @@ -327,7 +244,7 @@ void NetworkMetricsProvider::OnWifiPHYLayerProtocolResult( net::WifiPHYLayerProtocol mode) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (wifi_phy_layer_protocol_ != net::WIFI_PHY_LAYER_PROTOCOL_UNKNOWN && mode != wifi_phy_layer_protocol_) { wifi_phy_layer_protocol_is_ambiguous_ = true; @@ -338,7 +255,7 @@ void NetworkMetricsProvider::WriteWifiAccessPointProto( const WifiAccessPointInfoProvider::WifiAccessPointInfo& info, SystemProfileProto::Network* network_proto) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); SystemProfileProto::Network::WifiAccessPoint* access_point_info = network_proto->mutable_access_point_info(); SystemProfileProto::Network::WifiAccessPoint::SecurityMode security = @@ -415,7 +332,7 @@ } void NetworkMetricsProvider::LogAggregatedMetrics() { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); base::HistogramBase* error_codes = base::SparseHistogram::FactoryGet( "Net.ErrorCodesForMainFrame4", base::HistogramBase::kUmaTargetedHistogramFlag); @@ -436,7 +353,7 @@ void NetworkMetricsProvider::OnEffectiveConnectionTypeChanged( net::EffectiveConnectionType type) { - DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); effective_connection_type_ = type; if (effective_connection_type_ == net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN || @@ -480,4 +397,12 @@ max_effective_connection_type_ == net::EFFECTIVE_CONNECTION_TYPE_OFFLINE); } +void NetworkMetricsProvider::SetNetworkQualityTracker( + network::NetworkQualityTracker* network_quality_tracker) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(!network_quality_tracker_); + network_quality_tracker_ = network_quality_tracker; + network_quality_tracker_->AddEffectiveConnectionTypeObserver(this); +} + } // namespace metrics
diff --git a/components/metrics/net/network_metrics_provider.h b/components/metrics/net/network_metrics_provider.h index 3b9932f..4c0a9f0d 100644 --- a/components/metrics/net/network_metrics_provider.h +++ b/components/metrics/net/network_metrics_provider.h
@@ -7,48 +7,43 @@ #include <memory> +#include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/metrics/histogram_base.h" +#include "base/sequence_checker.h" #include "base/sequenced_task_runner.h" -#include "base/threading/thread_checker.h" +#include "base/single_thread_task_runner.h" #include "components/metrics/metrics_provider.h" #include "components/metrics/net/wifi_access_point_info_provider.h" #include "net/base/network_change_notifier.h" #include "net/base/network_interfaces.h" #include "net/nqe/effective_connection_type.h" +#include "services/network/public/cpp/network_quality_tracker.h" #include "third_party/metrics_proto/system_profile.pb.h" -namespace net { -class NetworkQualityEstimator; -} - namespace metrics { SystemProfileProto::Network::EffectiveConnectionType ConvertEffectiveConnectionType( net::EffectiveConnectionType effective_connection_type); -// Registers as observer with net::NetworkChangeNotifier and keeps track of -// the network environment. +// Registers as observer with net::NetworkChangeNotifier and +// network::NetworkQualityTracker to keep track of the network environment. class NetworkMetricsProvider : public MetricsProvider, - public net::NetworkChangeNotifier::NetworkChangeObserver { + public net::NetworkChangeNotifier::NetworkChangeObserver, + public network::NetworkQualityTracker::EffectiveConnectionTypeObserver { public: // Class that provides |this| with the network quality estimator. class NetworkQualityEstimatorProvider { public: virtual ~NetworkQualityEstimatorProvider() {} - // Returns the network quality estimator by calling |io_callback|. The - // returned network quality estimator may be nullptr. |io_callback| must be - // called on the IO thread. |io_callback| can be destroyed on IO thread only - // after |this| is destroyed. - virtual void PostReplyNetworkQualityEstimator( - base::Callback<void(net::NetworkQualityEstimator*)> io_callback) = 0; - - // Returns the task runner on which |this| should be used and destroyed. - virtual scoped_refptr<base::SequencedTaskRunner> GetTaskRunner() = 0; + // Returns the network quality tracker by calling |callback|. The + // returned network quality tracker is guaranteed to be be non-null. + virtual void PostReplyNetworkQualityTracker( + base::OnceCallback<void(network::NetworkQualityTracker*)> callback) = 0; protected: NetworkQualityEstimatorProvider() {} @@ -70,13 +65,10 @@ FRIEND_TEST_ALL_PREFIXES(NetworkMetricsProviderTest, ECTAmbiguousOnConnectionTypeChange); FRIEND_TEST_ALL_PREFIXES(NetworkMetricsProviderTest, - ECTNotAmbiguousOnOffline); + ECTNotAmbiguousOnUnknownOrOffline); FRIEND_TEST_ALL_PREFIXES(NetworkMetricsProviderTest, ConnectionTypeIsAmbiguous); - // Listens to the changes in the effective conection type. - class EffectiveConnectionTypeObserver; - // MetricsProvider: void ProvideCurrentSessionData( ChromeUserMetricsExtension* uma_proto) override; @@ -105,9 +97,14 @@ // Logs metrics that are functions of other metrics being uploaded. void LogAggregatedMetrics(); - // Notifies |this| that the effective connection type of the current network - // has changed to |type|. - void OnEffectiveConnectionTypeChanged(net::EffectiveConnectionType type); + // network::NetworkQualityTracker::EffectiveConnectionTypeObserver: + void OnEffectiveConnectionTypeChanged( + net::EffectiveConnectionType type) override; + + // Sets the network quality tracker. |network_quality_tracker| is guaranteed + // to be non-null. + void SetNetworkQualityTracker( + network::NetworkQualityTracker* network_quality_tracker); // True if |connection_type_| changed during the lifetime of the log. bool connection_type_is_ambiguous_; @@ -134,10 +131,8 @@ std::unique_ptr<NetworkQualityEstimatorProvider> network_quality_estimator_provider_; - // Listens to the changes in the effective connection type. Initialized and - // destroyed on the IO thread. May be null. - std::unique_ptr<EffectiveConnectionTypeObserver> - effective_connection_type_observer_; + // Provides the network quality estimates. May be null. + network::NetworkQualityTracker* network_quality_tracker_; // Last known effective connection type. net::EffectiveConnectionType effective_connection_type_; @@ -147,7 +142,7 @@ net::EffectiveConnectionType min_effective_connection_type_; net::EffectiveConnectionType max_effective_connection_type_; - base::ThreadChecker thread_checker_; + SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory<NetworkMetricsProvider> weak_ptr_factory_;
diff --git a/components/metrics/net/network_metrics_provider_unittest.cc b/components/metrics/net/network_metrics_provider_unittest.cc index b5e6507..f20e788 100644 --- a/components/metrics/net/network_metrics_provider_unittest.cc +++ b/components/metrics/net/network_metrics_provider_unittest.cc
@@ -13,7 +13,7 @@ #include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "net/base/network_change_notifier.h" -#include "net/nqe/network_quality_estimator_test_util.h" +#include "services/network/test/test_network_quality_tracker.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/metrics_proto/system_profile.pb.h" @@ -24,38 +24,18 @@ namespace metrics { -namespace { - -class TestNetworkQualityEstimatorProvider - : public NetworkMetricsProvider::NetworkQualityEstimatorProvider { - public: - explicit TestNetworkQualityEstimatorProvider( - net::TestNetworkQualityEstimator* estimator) - : estimator_(estimator) {} - ~TestNetworkQualityEstimatorProvider() override {} - - private: - // NetworkMetricsProvider::NetworkQualityEstimatorProvider: - scoped_refptr<base::SequencedTaskRunner> GetTaskRunner() override { - return base::ThreadTaskRunnerHandle::Get(); - } - - void PostReplyNetworkQualityEstimator( - base::Callback<void(net::NetworkQualityEstimator*)> callback) override { - callback.Run(estimator_); - } - - net::TestNetworkQualityEstimator* estimator_; - DISALLOW_COPY_AND_ASSIGN(TestNetworkQualityEstimatorProvider); -}; - -} // namespace - class NetworkMetricsProviderTest : public testing::Test { + public: + network::NetworkQualityTracker* GetNetworkQualityTracker() const { + return test_network_quality_tracker_.get(); + } + protected: NetworkMetricsProviderTest() : scoped_task_environment_( - base::test::ScopedTaskEnvironment::MainThreadType::IO) { + base::test::ScopedTaskEnvironment::MainThreadType::IO), + test_network_quality_tracker_( + std::make_unique<network::TestNetworkQualityTracker>()) { #if defined(OS_CHROMEOS) chromeos::DBusThreadManager::Initialize(); chromeos::NetworkHandler::Initialize(); @@ -64,17 +44,17 @@ private: base::test::ScopedTaskEnvironment scoped_task_environment_; + + std::unique_ptr<network::TestNetworkQualityTracker> + test_network_quality_tracker_; }; // Verifies that the effective connection type is correctly set. TEST_F(NetworkMetricsProviderTest, EffectiveConnectionType) { - net::TestNetworkQualityEstimator estimator; - std::unique_ptr<NetworkMetricsProvider::NetworkQualityEstimatorProvider> - estimator_provider(base::WrapUnique( - new TestNetworkQualityEstimatorProvider(&estimator))); SystemProfileProto system_profile; - NetworkMetricsProvider network_metrics_provider( - std::move(estimator_provider)); + NetworkMetricsProvider network_metrics_provider; + network_metrics_provider.SetNetworkQualityTracker(GetNetworkQualityTracker()); + base::RunLoop().RunUntilIdle(); EXPECT_EQ(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN, network_metrics_provider.effective_connection_type_); @@ -88,18 +68,8 @@ EXPECT_EQ(SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_UNKNOWN, system_profile.network().max_effective_connection_type()); - // Set RTT so that the effective connection type is computed as 2G. - estimator.set_recent_http_rtt(base::TimeDelta::FromMilliseconds(1500)); - estimator.SetStartTimeNullHttpRtt(base::TimeDelta::FromMilliseconds(1500)); - EXPECT_EQ(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN, - network_metrics_provider.effective_connection_type_); - EXPECT_EQ(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN, - network_metrics_provider.min_effective_connection_type_); - EXPECT_EQ(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN, - network_metrics_provider.max_effective_connection_type_); - // Running a request would cause the effective connection type to be computed - // as 2G, and observers to be notified. - estimator.RunOneRequest(); + GetNetworkQualityTracker()->ReportEffectiveConnectionTypeForTesting( + net::EFFECTIVE_CONNECTION_TYPE_2G); EXPECT_EQ(net::EFFECTIVE_CONNECTION_TYPE_2G, network_metrics_provider.effective_connection_type_); EXPECT_EQ(net::EFFECTIVE_CONNECTION_TYPE_2G, @@ -112,12 +82,8 @@ EXPECT_EQ(SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_2G, system_profile.network().max_effective_connection_type()); - // Set RTT so that the effective connection type is computed as SLOW_2G. - estimator.set_recent_http_rtt(base::TimeDelta::FromMilliseconds(3000)); - estimator.SetStartTimeNullHttpRtt(base::TimeDelta::FromMilliseconds(3000)); - // Running a request would cause the effective connection type to be computed - // as SLOW_2G, and observers to be notified. - estimator.RunOneRequest(); + GetNetworkQualityTracker()->ReportEffectiveConnectionTypeForTesting( + net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G); EXPECT_EQ(net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G, network_metrics_provider.effective_connection_type_); EXPECT_EQ(net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G, @@ -144,13 +110,10 @@ // Verifies that the effective connection type is not set to UNKNOWN when there // is a change in the connection type. TEST_F(NetworkMetricsProviderTest, ECTAmbiguousOnConnectionTypeChange) { - net::TestNetworkQualityEstimator estimator; - std::unique_ptr<NetworkMetricsProvider::NetworkQualityEstimatorProvider> - estimator_provider(base::WrapUnique( - new TestNetworkQualityEstimatorProvider(&estimator))); SystemProfileProto system_profile; - NetworkMetricsProvider network_metrics_provider( - std::move(estimator_provider)); + NetworkMetricsProvider network_metrics_provider; + network_metrics_provider.SetNetworkQualityTracker(GetNetworkQualityTracker()); + base::RunLoop().RunUntilIdle(); EXPECT_EQ(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN, network_metrics_provider.effective_connection_type_); @@ -159,12 +122,8 @@ EXPECT_EQ(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN, network_metrics_provider.max_effective_connection_type_); - // Set RTT so that the effective connection type is computed as 2G. - estimator.set_recent_http_rtt(base::TimeDelta::FromMilliseconds(1500)); - estimator.SetStartTimeNullHttpRtt(base::TimeDelta::FromMilliseconds(1500)); - // Running a request would cause the effective connection type to be computed - // as 2G, and observers to be notified. - estimator.RunOneRequest(); + GetNetworkQualityTracker()->ReportEffectiveConnectionTypeForTesting( + net::EFFECTIVE_CONNECTION_TYPE_2G); EXPECT_EQ(net::EFFECTIVE_CONNECTION_TYPE_2G, network_metrics_provider.effective_connection_type_); EXPECT_EQ(net::EFFECTIVE_CONNECTION_TYPE_2G, @@ -193,39 +152,32 @@ // Verifies that the effective connection type is not set to UNKNOWN when the // connection type is OFFLINE. -TEST_F(NetworkMetricsProviderTest, ECTNotAmbiguousOnOffline) { +TEST_F(NetworkMetricsProviderTest, ECTNotAmbiguousOnUnknownOrOffline) { for (net::EffectiveConnectionType force_ect : {net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN, net::EFFECTIVE_CONNECTION_TYPE_OFFLINE}) { - std::unique_ptr<net::NetworkQualityEstimatorParams> params = - std::make_unique<net::NetworkQualityEstimatorParams>( - std::map<std::string, std::string>()); - net::NetworkQualityEstimatorParams* params_ptr = params.get(); - net::TestNetworkQualityEstimator estimator(std::move(params)); + NetworkMetricsProvider network_metrics_provider; + network_metrics_provider.SetNetworkQualityTracker( + GetNetworkQualityTracker()); + base::RunLoop().RunUntilIdle(); - std::unique_ptr<NetworkMetricsProvider::NetworkQualityEstimatorProvider> - estimator_provider(base::WrapUnique( - new TestNetworkQualityEstimatorProvider(&estimator))); SystemProfileProto system_profile; - NetworkMetricsProvider network_metrics_provider( - std::move(estimator_provider)); - - params_ptr->SetForcedEffectiveConnectionType( + GetNetworkQualityTracker()->ReportEffectiveConnectionTypeForTesting( net::EFFECTIVE_CONNECTION_TYPE_2G); - estimator.RunOneRequest(); - params_ptr->SetForcedEffectiveConnectionType(force_ect); - estimator.RunOneRequest(); + network_metrics_provider.ProvideSystemProfileMetrics(&system_profile); + + GetNetworkQualityTracker()->ReportEffectiveConnectionTypeForTesting( + force_ect); + network_metrics_provider.ProvideSystemProfileMetrics(&system_profile); EXPECT_EQ(SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_2G, system_profile.network().min_effective_connection_type()); EXPECT_EQ(SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_2G, system_profile.network().max_effective_connection_type()); - params_ptr->SetForcedEffectiveConnectionType( + GetNetworkQualityTracker()->ReportEffectiveConnectionTypeForTesting( net::EFFECTIVE_CONNECTION_TYPE_4G); - estimator.RunOneRequest(); - network_metrics_provider.ProvideSystemProfileMetrics(&system_profile); EXPECT_EQ(SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_4G, system_profile.network().min_effective_connection_type()); @@ -236,14 +188,10 @@ // Verifies that the connection type is ambiguous boolean is correctly set. TEST_F(NetworkMetricsProviderTest, ConnectionTypeIsAmbiguous) { - net::TestNetworkQualityEstimator estimator; - std::unique_ptr<NetworkMetricsProvider::NetworkQualityEstimatorProvider> - estimator_provider(base::WrapUnique( - new TestNetworkQualityEstimatorProvider(&estimator))); SystemProfileProto system_profile; - NetworkMetricsProvider network_metrics_provider( - std::move(estimator_provider)); - estimator.RunOneRequest(); + NetworkMetricsProvider network_metrics_provider; + network_metrics_provider.SetNetworkQualityTracker(GetNetworkQualityTracker()); + base::RunLoop().RunUntilIdle(); EXPECT_EQ(net::NetworkChangeNotifier::CONNECTION_UNKNOWN, network_metrics_provider.connection_type_);
diff --git a/components/offline_pages/core/background/request_coordinator.h b/components/offline_pages/core/background/request_coordinator.h index 36b0696..3f0889f 100644 --- a/components/offline_pages/core/background/request_coordinator.h +++ b/components/offline_pages/core/background/request_coordinator.h
@@ -218,7 +218,7 @@ int64_t received_bytes) override; // Returns the request queue used for requests. Coordinator keeps ownership. - RequestQueue* queue() { return queue_.get(); } + RequestQueue* queue_for_testing() { return queue_.get(); } // Return an unowned pointer to the Scheduler. Scheduler* scheduler() { return scheduler_.get(); }
diff --git a/components/offline_pages/core/background/request_coordinator_unittest.cc b/components/offline_pages/core/background/request_coordinator_unittest.cc index f0d21cbc..8c03fce 100644 --- a/components/offline_pages/core/background/request_coordinator_unittest.cc +++ b/components/offline_pages/core/background/request_coordinator_unittest.cc
@@ -147,7 +147,9 @@ RequestCoordinator* coordinator() const { return coordinator_taco_->request_coordinator(); } - + RequestQueue* queue() { + return coordinator_taco_->request_coordinator()->queue_for_testing(); + } RequestCoordinatorState state() { return coordinator()->state(); } // Test processing callback function. @@ -446,9 +448,9 @@ // Mark request as started and add it to the queue, // then wait for callback to finish. request->MarkAttemptStarted(base::Time::Now()); - coordinator()->queue()->AddRequest( - *request, base::BindOnce(&RequestCoordinatorTest::AddRequestDone, - base::Unretained(this))); + queue()->AddRequest(*request, + base::BindOnce(&RequestCoordinatorTest::AddRequestDone, + base::Unretained(this))); PumpLoop(); // Override the processing callback for test visiblity. @@ -473,18 +475,18 @@ SavePageRequest RequestCoordinatorTest::AddRequest1() { offline_pages::SavePageRequest request1(kRequestId1, kUrl1, kClientId1, base::Time::Now(), kUserRequested); - coordinator()->queue()->AddRequest( - request1, base::BindOnce(&RequestCoordinatorTest::AddRequestDone, - base::Unretained(this))); + queue()->AddRequest(request1, + base::BindOnce(&RequestCoordinatorTest::AddRequestDone, + base::Unretained(this))); return request1; } SavePageRequest RequestCoordinatorTest::AddRequest2() { offline_pages::SavePageRequest request2(kRequestId2, kUrl2, kClientId2, base::Time::Now(), kUserRequested); - coordinator()->queue()->AddRequest( - request2, base::BindOnce(&RequestCoordinatorTest::AddRequestDone, - base::Unretained(this))); + queue()->AddRequest(request2, + base::BindOnce(&RequestCoordinatorTest::AddRequestDone, + base::Unretained(this))); return request2; } @@ -607,8 +609,8 @@ base::Unretained(this)))); // Expect that a request got placed on the queue. - coordinator()->queue()->GetRequests(base::BindOnce( - &RequestCoordinatorTest::GetRequestsDone, base::Unretained(this))); + queue()->GetRequests(base::BindOnce(&RequestCoordinatorTest::GetRequestsDone, + base::Unretained(this))); // Expect that the request is not added to the disabled list by default. EXPECT_TRUE(disabled_requests().empty()); @@ -655,8 +657,8 @@ EXPECT_NE(0, SavePageLater()); // Expect that a request got placed on the queue. - coordinator()->queue()->GetRequests(base::BindOnce( - &RequestCoordinatorTest::GetRequestsDone, base::Unretained(this))); + queue()->GetRequests(base::BindOnce(&RequestCoordinatorTest::GetRequestsDone, + base::Unretained(this))); // Wait for callbacks to finish, both request queue and offliner. PumpLoop(); @@ -702,8 +704,8 @@ EXPECT_TRUE(processing_callback_called()); // Verify the request gets removed from the queue, and wait for callbacks. - coordinator()->queue()->GetRequests(base::BindOnce( - &RequestCoordinatorTest::GetRequestsDone, base::Unretained(this))); + queue()->GetRequests(base::BindOnce(&RequestCoordinatorTest::GetRequestsDone, + base::Unretained(this))); PumpLoop(); // We should not find any requests in the queue anymore. @@ -774,8 +776,8 @@ // Busy processing 2nd request. EXPECT_TRUE(state() == RequestCoordinatorState::OFFLINING); - coordinator()->queue()->GetRequests(base::BindOnce( - &RequestCoordinatorTest::GetRequestsDone, base::Unretained(this))); + queue()->GetRequests(base::BindOnce(&RequestCoordinatorTest::GetRequestsDone, + base::Unretained(this))); PumpLoop(); // Now just one request in the queue since failed request removed @@ -816,8 +818,8 @@ // Busy processing 2nd request. EXPECT_TRUE(state() == RequestCoordinatorState::OFFLINING); - coordinator()->queue()->GetRequests(base::BindOnce( - &RequestCoordinatorTest::GetRequestsDone, base::Unretained(this))); + queue()->GetRequests(base::BindOnce(&RequestCoordinatorTest::GetRequestsDone, + base::Unretained(this))); PumpLoop(); // Now just one request in the queue since non-retryable failure. @@ -859,8 +861,8 @@ // Not busy for NO_NEXT failure. EXPECT_FALSE(state() == RequestCoordinatorState::OFFLINING); - coordinator()->queue()->GetRequests(base::BindOnce( - &RequestCoordinatorTest::GetRequestsDone, base::Unretained(this))); + queue()->GetRequests(base::BindOnce(&RequestCoordinatorTest::GetRequestsDone, + base::Unretained(this))); PumpLoop(); // Both requests still in queue. @@ -881,8 +883,8 @@ EXPECT_TRUE(processing_callback_called()); // Verify the request is not removed from the queue, and wait for callbacks. - coordinator()->queue()->GetRequests(base::BindOnce( - &RequestCoordinatorTest::GetRequestsDone, base::Unretained(this))); + queue()->GetRequests(base::BindOnce(&RequestCoordinatorTest::GetRequestsDone, + base::Unretained(this))); PumpLoop(); // Request no longer in the queue (for single attempt policy). @@ -904,8 +906,8 @@ EXPECT_TRUE(processing_callback_called()); // Verify the request is not removed from the queue, and wait for callbacks. - coordinator()->queue()->GetRequests(base::BindOnce( - &RequestCoordinatorTest::GetRequestsDone, base::Unretained(this))); + queue()->GetRequests(base::BindOnce(&RequestCoordinatorTest::GetRequestsDone, + base::Unretained(this))); PumpLoop(); // Request still in the queue. @@ -975,9 +977,9 @@ AddRequest1(); offline_pages::SavePageRequest request2(kRequestId2, kUrl2, kClientId2, base::Time::Now(), !kUserRequested); - coordinator()->queue()->AddRequest( - request2, base::BindOnce(&RequestCoordinatorTest::AddRequestDone, - base::Unretained(this))); + queue()->AddRequest(request2, + base::BindOnce(&RequestCoordinatorTest::AddRequestDone, + base::Unretained(this))); PumpLoop(); // Trigger the scheduler to schedule for the least restrictive condition. @@ -1193,9 +1195,9 @@ // Set request to allow one more completed attempt. int max_tries = coordinator()->policy()->GetMaxCompletedTries(); request.set_completed_attempt_count(max_tries - 1); - coordinator()->queue()->AddRequest( - request, base::BindOnce(&RequestCoordinatorTest::AddRequestDone, - base::Unretained(this))); + queue()->AddRequest(request, + base::BindOnce(&RequestCoordinatorTest::AddRequestDone, + base::Unretained(this))); PumpLoop(); // Ensure that the new request does not finish - we simulate it being @@ -1266,9 +1268,9 @@ offline_pages::SavePageRequest request2(kRequestId1 + 1, kUrl1, kClientId1, base::Time::Now(), kUserRequested); request2.set_completed_attempt_count(kAttemptCount); - coordinator()->queue()->AddRequest( - request2, base::BindOnce(&RequestCoordinatorTest::AddRequestDone, - base::Unretained(this))); + queue()->AddRequest(request2, + base::BindOnce(&RequestCoordinatorTest::AddRequestDone, + base::Unretained(this))); PumpLoop(); // Sending the request to the offliner. @@ -1285,8 +1287,8 @@ // TryNextRequest should decide that there is no more work to be done, // and call back to the scheduler, even though there is another request in the // queue. Both requests should be left in the queue. - coordinator()->queue()->GetRequests(base::BindOnce( - &RequestCoordinatorTest::GetRequestsDone, base::Unretained(this))); + queue()->GetRequests(base::BindOnce(&RequestCoordinatorTest::GetRequestsDone, + base::Unretained(this))); PumpLoop(); // We should find two requests in the queue. @@ -1322,8 +1324,8 @@ EXPECT_FALSE(state() == RequestCoordinatorState::OFFLINING); // Get queued requests. - coordinator()->queue()->GetRequests(base::BindOnce( - &RequestCoordinatorTest::GetRequestsDone, base::Unretained(this))); + queue()->GetRequests(base::BindOnce(&RequestCoordinatorTest::GetRequestsDone, + base::Unretained(this))); PumpLoop(); // We should find one request in the queue. @@ -1541,9 +1543,9 @@ // be the last retry. int max_tries = coordinator()->policy()->GetMaxCompletedTries(); request.set_completed_attempt_count(max_tries - 1); - coordinator()->queue()->AddRequest( - request, base::BindOnce(&RequestCoordinatorTest::AddRequestDone, - base::Unretained(this))); + queue()->AddRequest(request, + base::BindOnce(&RequestCoordinatorTest::AddRequestDone, + base::Unretained(this))); PumpLoop(); // Ensure that the new request does not finish - we simulate it being
diff --git a/components/password_manager/content/browser/password_requirements_service_factory.cc b/components/password_manager/content/browser/password_requirements_service_factory.cc index cfa3976..d35683a1 100644 --- a/components/password_manager/content/browser/password_requirements_service_factory.cc +++ b/components/password_manager/content/browser/password_requirements_service_factory.cc
@@ -49,20 +49,8 @@ if (context->IsOffTheRecord()) return nullptr; - VLOG(1) << "PasswordGenerationRequirements experiment enabled? " - << base::FeatureList::IsEnabled( - features::kPasswordGenerationRequirements); - - if (!base::FeatureList::IsEnabled( - features::kPasswordGenerationRequirements) && - !base::FeatureList::IsEnabled(::features::kExperimentalUi)) { - return nullptr; - } - - bool enable_domain_overrides = - base::FeatureList::IsEnabled( - features::kPasswordGenerationRequirementsDomainOverrides) || - base::FeatureList::IsEnabled(::features::kExperimentalUi); + bool enable_domain_overrides = base::FeatureList::IsEnabled( + features::kPasswordGenerationRequirementsDomainOverrides); VLOG(1) << "PasswordGenerationRequirementsDomainOverrides experiment enabled? " @@ -72,7 +60,7 @@ return new PasswordRequirementsService(nullptr); // Default parameters. - int version = 0; + int version = 1; int prefix_length = 0; int timeout_in_ms = 5000; @@ -97,15 +85,6 @@ timeout_in_ms = tmp; } - // If no experiment configuration is set to a user with experimental-ui flag, - // set a default that exercises the full new code. - if (version == 0 && - base::FeatureList::IsEnabled(::features::kExperimentalUi)) { - version = 1; - prefix_length = 0; - timeout_in_ms = 5000; - } - VLOG(1) << "PasswordGenerationRequirements parameters: " << version << ", " << prefix_length << ", " << timeout_in_ms << " ms";
diff --git a/components/password_manager/core/common/password_manager_features.cc b/components/password_manager/core/common/password_manager_features.cc index bc6139a0..14af7d2 100644 --- a/components/password_manager/core/common/password_manager_features.cc +++ b/components/password_manager/core/common/password_manager_features.cc
@@ -28,10 +28,6 @@ const base::Feature kHtmlBasedUsernameDetector = { "HtmlBaseUsernameDetector", base::FEATURE_ENABLED_BY_DEFAULT}; -// Controls the ability to generate passwords that fit sites' requirements. -const base::Feature kPasswordGenerationRequirements = { - "PasswordGenerationRequirements", base::FEATURE_ENABLED_BY_DEFAULT}; - // Controls whether password requirements can be overridden for domains // (as opposed to only relying on the autofill server). const base::Feature kPasswordGenerationRequirementsDomainOverrides = {
diff --git a/components/password_manager/core/common/password_manager_features.h b/components/password_manager/core/common/password_manager_features.h index 64b538d9..b4e22b8 100644 --- a/components/password_manager/core/common/password_manager_features.h +++ b/components/password_manager/core/common/password_manager_features.h
@@ -21,7 +21,6 @@ extern const base::Feature kAutofillHome; extern const base::Feature kDeleteCorruptedPasswords; extern const base::Feature kHtmlBasedUsernameDetector; -extern const base::Feature kPasswordGenerationRequirements; extern const base::Feature kPasswordGenerationRequirementsDomainOverrides; extern const base::Feature kFillOnAccountSelect; extern const base::Feature kMigrateLinuxToLoginDB;
diff --git a/components/resources/security_interstitials_resources.grdp b/components/resources/security_interstitials_resources.grdp index d290349..f6327679 100644 --- a/components/resources/security_interstitials_resources.grdp +++ b/components/resources/security_interstitials_resources.grdp
@@ -8,4 +8,5 @@ <include name="IDR_SECURITY_INTERSTITIAL_CONNECTION_HELP_HTML" file="../security_interstitials/content/resources/connection_help.html" compress="gzip" type="BINDATA" /> <include name="IDR_SECURITY_INTERSTITIAL_CONNECTION_HELP_CSS" file="../security_interstitials/content/resources/connection_help.css" compress="gzip" type="BINDATA" /> <include name="IDR_SECURITY_INTERSTITIAL_CONNECTION_HELP_JS" file="../security_interstitials/content/resources/connection_help.js" compress="gzip" type="BINDATA" /> + <include name="IDR_SECURITY_INTERSTITIAL_ORIGIN_POLICY_HTML" compress="gzip" file="../security_interstitials/core/browser/resources/interstitial_origin_policy.html" type="BINDATA" /> </grit-part>
diff --git a/components/security_interstitials/content/BUILD.gn b/components/security_interstitials/content/BUILD.gn index 7b6d5b3..7d1a57e 100644 --- a/components/security_interstitials/content/BUILD.gn +++ b/components/security_interstitials/content/BUILD.gn
@@ -6,6 +6,8 @@ sources = [ "connection_help_ui.cc", "connection_help_ui.h", + "origin_policy_ui.cc", + "origin_policy_ui.h", "security_interstitial_controller_client.cc", "security_interstitial_controller_client.h", "security_interstitial_page.cc", @@ -33,6 +35,7 @@ "//components/strings:components_strings_grit", "//content/public/browser", "//content/public/common", + "//third_party/zlib/google:compression_utils", ] }
diff --git a/components/security_interstitials/content/DEPS b/components/security_interstitials/content/DEPS index 84d5909..b458216 100644 --- a/components/security_interstitials/content/DEPS +++ b/components/security_interstitials/content/DEPS
@@ -9,4 +9,5 @@ "+content/public/test", "+net", "+net/test", + "+third_party/zlib/google/compression_utils.h", ]
diff --git a/components/security_interstitials/content/origin_policy_ui.cc b/components/security_interstitials/content/origin_policy_ui.cc new file mode 100644 index 0000000..9f83d411 --- /dev/null +++ b/components/security_interstitials/content/origin_policy_ui.cc
@@ -0,0 +1,39 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/security_interstitials/content/origin_policy_ui.h" + +#include "components/grit/components_resources.h" +#include "third_party/zlib/google/compression_utils.h" +#include "ui/base/resource/resource_bundle.h" +#include "ui/base/template_expressions.h" +#include "url/gurl.h" +#include "url/origin.h" + +namespace security_interstitials { + +base::Optional<std::string> OriginPolicyUI::GetErrorPage( + content::OriginPolicyErrorReason error_reason, + const url::Origin& origin, + const GURL& url) { + const base::StringPiece raw_interstitial_page_resource = + ui::ResourceBundle::GetSharedInstance().GetRawDataResource( + IDR_SECURITY_INTERSTITIAL_ORIGIN_POLICY_HTML); + + // The resource is gzip compressed. + std::string interstitial_page_resource; + interstitial_page_resource.resize( + compression::GetUncompressedSize(raw_interstitial_page_resource)); + base::StringPiece buffer(interstitial_page_resource.c_str(), + interstitial_page_resource.size()); + CHECK(compression::GzipUncompress(raw_interstitial_page_resource, buffer)); + + ui::TemplateReplacements params; + params["url"] = url.spec(); + params["origin"] = origin.Serialize(); + + return ui::ReplaceTemplateExpressions(interstitial_page_resource, params); +} + +} // namespace security_interstitials
diff --git a/components/security_interstitials/content/origin_policy_ui.h b/components/security_interstitials/content/origin_policy_ui.h new file mode 100644 index 0000000..6f8fbd4 --- /dev/null +++ b/components/security_interstitials/content/origin_policy_ui.h
@@ -0,0 +1,35 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_SECURITY_INTERSTITIALS_CONTENT_ORIGIN_POLICY_UI_H_ +#define COMPONENTS_SECURITY_INTERSTITIALS_CONTENT_ORIGIN_POLICY_UI_H_ + +#include <memory> + +#include "base/macros.h" +#include "base/optional.h" +#include "base/strings/string16.h" + +class GURL; +namespace url { +class Origin; +} // namespace url +namespace content { +enum class OriginPolicyErrorReason; +} // namespace content + +namespace security_interstitials { + +// A helper class to build the error page for Origin Policy errors. +class OriginPolicyUI { + public: + static base::Optional<std::string> GetErrorPage( + content::OriginPolicyErrorReason error_reason, + const url::Origin& origin, + const GURL& url); +}; + +} // namespace security_interstitials + +#endif // COMPONENTS_SECURITY_INTERSTITIALS_CONTENT_ORIGIN_POLICY_UI_H_
diff --git a/components/security_interstitials/core/BUILD.gn b/components/security_interstitials/core/BUILD.gn index 83e09b3..c854b51 100644 --- a/components/security_interstitials/core/BUILD.gn +++ b/components/security_interstitials/core/BUILD.gn
@@ -47,6 +47,7 @@ "//components/strings", "//components/url_formatter", "//net", + "//third_party/zlib/google:compression_utils", "//ui/base", ]
diff --git a/components/security_interstitials/core/browser/resources/interstitial_origin_policy.html b/components/security_interstitials/core/browser/resources/interstitial_origin_policy.html new file mode 100644 index 0000000..3fe3c0d --- /dev/null +++ b/components/security_interstitials/core/browser/resources/interstitial_origin_policy.html
@@ -0,0 +1,15 @@ +<!doctype html> +<html> +<head> + <title>Origin Policy Error Interstitial</title> +</head> +<body> + <p>Well, well, well. What do we have here? An Origin Policy violation.</p> + <p>And what do we not have? A page!</p> + + <p><ul> + <li>You're trying to go to: $i18n{url}</li> + <li>The policy applies to: $i18n{origin}</li> + </ul></p> +</body> +</html>
diff --git a/components/signin/core/browser/android/java/src/org/chromium/components/signin/AccountManagerFacade.java b/components/signin/core/browser/android/java/src/org/chromium/components/signin/AccountManagerFacade.java index 27868ce9..cdd021b7 100644 --- a/components/signin/core/browser/android/java/src/org/chromium/components/signin/AccountManagerFacade.java +++ b/components/signin/core/browser/android/java/src/org/chromium/components/signin/AccountManagerFacade.java
@@ -21,7 +21,6 @@ import android.support.annotation.MainThread; import android.support.annotation.Nullable; -import org.chromium.base.AsyncTask; import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.Log; @@ -29,6 +28,7 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.CachedMetrics; +import org.chromium.base.task.AsyncTask; import org.chromium.components.signin.util.PatternMatcher; import org.chromium.net.NetworkChangeNotifier;
diff --git a/components/signin/core/browser/android/junit/src/org/chromium/components/signin/test/AccountManagerFacadeRobolectricTest.java b/components/signin/core/browser/android/junit/src/org/chromium/components/signin/test/AccountManagerFacadeRobolectricTest.java index 312baf0..5eaf1fa3 100644 --- a/components/signin/core/browser/android/junit/src/org/chromium/components/signin/test/AccountManagerFacadeRobolectricTest.java +++ b/components/signin/core/browser/android/junit/src/org/chromium/components/signin/test/AccountManagerFacadeRobolectricTest.java
@@ -23,8 +23,8 @@ import org.robolectric.annotation.Config; import org.chromium.base.Callback; +import org.chromium.base.task.test.CustomShadowAsyncTask; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.base.test.asynctask.CustomShadowAsyncTask; import org.chromium.components.signin.AccountManagerDelegateException; import org.chromium.components.signin.AccountManagerFacade; import org.chromium.components.signin.ChildAccountStatus;
diff --git a/components/subresource_filter/content/browser/subframe_navigation_filtering_throttle.cc b/components/subresource_filter/content/browser/subframe_navigation_filtering_throttle.cc index 669e65a..15b8882 100644 --- a/components/subresource_filter/content/browser/subframe_navigation_filtering_throttle.cc +++ b/components/subresource_filter/content/browser/subframe_navigation_filtering_throttle.cc
@@ -93,14 +93,14 @@ if (policy == LoadPolicy::DISALLOW) { if (parent_frame_filter_->activation_state().enable_logging) { - std::ostringstream oss(kDisallowSubframeConsoleMessagePrefix); - oss << navigation_handle()->GetURL(); - oss << kDisallowSubframeConsoleMessageSuffix; + std::string console_message = base::StringPrintf( + kDisallowSubframeConsoleMessageFormat, + navigation_handle()->GetURL().possibly_invalid_spec().c_str()); navigation_handle() ->GetWebContents() ->GetMainFrame() ->AddMessageToConsole(content::CONSOLE_MESSAGE_LEVEL_ERROR, - oss.str()); + console_message); } parent_frame_filter_->ReportDisallowedLoad();
diff --git a/components/subresource_filter/content/browser/subframe_navigation_filtering_throttle_unittest.cc b/components/subresource_filter/content/browser/subframe_navigation_filtering_throttle_unittest.cc index 7d02a72b..379c684 100644 --- a/components/subresource_filter/content/browser/subframe_navigation_filtering_throttle_unittest.cc +++ b/components/subresource_filter/content/browser/subframe_navigation_filtering_throttle_unittest.cc
@@ -158,10 +158,8 @@ } std::string GetFilterConsoleMessage(const GURL& filtered_url) { - std::ostringstream oss(kDisallowSubframeConsoleMessagePrefix); - oss << filtered_url; - oss << kDisallowSubframeConsoleMessageSuffix; - return oss.str(); + return base::StringPrintf(kDisallowSubframeConsoleMessageFormat, + filtered_url.possibly_invalid_spec().c_str()); } private:
diff --git a/components/subresource_filter/core/browser/subresource_filter_constants.h b/components/subresource_filter/core/browser/subresource_filter_constants.h index 3d5e0da..c99c719e 100644 --- a/components/subresource_filter/core/browser/subresource_filter_constants.h +++ b/components/subresource_filter/core/browser/subresource_filter_constants.h
@@ -62,12 +62,9 @@ "https://www.chromestatus.com/feature/5738264052891648"; // Console message to be displayed on disallowing subframe. -constexpr char kDisallowSubframeConsoleMessagePrefix[] = - "Chrome blocked resource "; - -constexpr char kDisallowSubframeConsoleMessageSuffix[] = - " on this site because this site tends to show ads that interrupt, " - "distract, or prevent user control. Learn more at " +constexpr char kDisallowSubframeConsoleMessageFormat[] = + "Chrome blocked resource %s on this site because this site tends to show " + "ads that interrupt, distract, or prevent user control. Learn more at " "https://www.chromestatus.com/feature/5738264052891648"; constexpr char kLearnMoreLink[] =
diff --git a/components/sync/driver/model_type_controller.cc b/components/sync/driver/model_type_controller.cc index c5ced37..4fb7770b 100644 --- a/components/sync/driver/model_type_controller.cc +++ b/components/sync/driver/model_type_controller.cc
@@ -50,7 +50,7 @@ ModelTypeController::ModelTypeController( ModelType type, std::unique_ptr<ModelTypeControllerDelegate> delegate_on_disk) - : DataTypeController(type), state_(NOT_RUNNING) { + : DataTypeController(type) { delegate_map_.emplace(ConfigureContext::STORAGE_ON_DISK, std::move(delegate_on_disk)); } @@ -76,13 +76,13 @@ const ConfigureContext& configure_context, const ModelLoadCallback& model_load_callback) { DCHECK(CalledOnValidThread()); - CHECK(!model_load_callback.is_null()); - CHECK_EQ(NOT_RUNNING, state_); + DCHECK(!model_load_callback.is_null()); + DCHECK_EQ(NOT_RUNNING, state_); auto it = delegate_map_.find(configure_context.storage_option); - CHECK(it != delegate_map_.end()); + DCHECK(it != delegate_map_.end()); delegate_ = it->second.get(); - CHECK(delegate_); + DCHECK(delegate_); DVLOG(1) << "Sync starting for " << ModelTypeToString(type()); state_ = MODEL_STARTING; @@ -110,7 +110,7 @@ void ModelTypeController::LoadModelsDone(ConfigureResult result, const SyncError& error) { DCHECK(CalledOnValidThread()); - CHECK_NE(NOT_RUNNING, state_); + DCHECK_NE(NOT_RUNNING, state_); if (state_ == STOPPING) { DCHECK(!model_stop_callbacks_.empty()); @@ -137,7 +137,7 @@ } if (IsSuccessfulResult(result)) { - CHECK_EQ(MODEL_STARTING, state_); + DCHECK_EQ(MODEL_STARTING, state_); state_ = MODEL_LOADED; DVLOG(1) << "Sync start completed for " << ModelTypeToString(type()); } else { @@ -168,7 +168,7 @@ return; DCHECK(configurer); DCHECK(activation_response_); - CHECK_EQ(MODEL_LOADED, state_); + DCHECK_EQ(MODEL_LOADED, state_); // Inform the DataTypeManager whether our initial download is complete. set_downloaded.Run( activation_response_->model_type_state.initial_sync_done()); @@ -183,7 +183,7 @@ const StartCallback& start_callback) { DCHECK(CalledOnValidThread()); DCHECK(!start_callback.is_null()); - CHECK_EQ(MODEL_LOADED, state_); + DCHECK_EQ(MODEL_LOADED, state_); state_ = RUNNING; DVLOG(1) << "Sync running for " << ModelTypeToString(type()); @@ -196,11 +196,11 @@ void ModelTypeController::ActivateDataType(ModelTypeConfigurer* configurer) { DCHECK(CalledOnValidThread()); DCHECK(configurer); - CHECK_EQ(RUNNING, state_); + DCHECK_EQ(RUNNING, state_); // In contrast with directory datatypes, non-blocking data types should be // activated in RegisterWithBackend. activation_response_ should be // passed to backend before call to ActivateDataType. - CHECK(!activation_response_); + DCHECK(!activation_response_); } void ModelTypeController::DeactivateDataType(ModelTypeConfigurer* configurer) { @@ -230,15 +230,15 @@ return; case STOPPING: - CHECK(!model_stop_callbacks_.empty()); + DCHECK(!model_stop_callbacks_.empty()); model_stop_metadata_fate_ = TakeStrictestMetadataFate(model_stop_metadata_fate_, metadata_fate); model_stop_callbacks_.push_back(std::move(callback)); break; case MODEL_STARTING: - CHECK(!model_load_callback_.is_null()); - CHECK(model_stop_callbacks_.empty()); + DCHECK(!model_load_callback_.is_null()); + DCHECK(model_stop_callbacks_.empty()); DLOG(WARNING) << "Deferring stop for " << ModelTypeToString(type()) << " because it's still starting"; model_stop_metadata_fate_ = metadata_fate;
diff --git a/components/sync/driver/model_type_controller.h b/components/sync/driver/model_type_controller.h index 1370159b..c455a4a 100644 --- a/components/sync/driver/model_type_controller.h +++ b/components/sync/driver/model_type_controller.h
@@ -76,10 +76,10 @@ delegate_map_; // State of this datatype controller. - State state_; + State state_ = NOT_RUNNING; // Owned by |delegate_map_|. Null while NOT_RUNNING. - ModelTypeControllerDelegate* delegate_; + ModelTypeControllerDelegate* delegate_ = nullptr; // Callback for use when starting the datatype (usually MODEL_STARTING, but // STOPPING if abort requested while starting).
diff --git a/components/sync/engine_impl/uss_migrator.cc b/components/sync/engine_impl/uss_migrator.cc index 2f63f19..55d407c 100644 --- a/components/sync/engine_impl/uss_migrator.cc +++ b/components/sync/engine_impl/uss_migrator.cc
@@ -23,7 +23,8 @@ namespace { -bool ExtractSyncEntity(ReadTransaction* trans, +bool ExtractSyncEntity(ModelType type, + ReadTransaction* trans, int64_t id, sync_pb::SyncEntity* entity) { ReadNode read_node(trans); @@ -50,6 +51,11 @@ if (entry.GetServerUniquePosition().IsValid()) { *entity->mutable_unique_position() = entry.GetServerUniquePosition().ToProto(); + } else { + // All boookmarks should have valid unique_positions including legacy + // bookmarks that are missing the field. Directory should have taken care of + // assigning proper unique_position during the first sync flow. + DCHECK_NE(BOOKMARKS, type); } entity->set_server_defined_unique_tag(entry.GetUniqueServerTag()); @@ -103,7 +109,7 @@ const size_t batch_limit = std::min(i + batch_size, child_ids.size()); for (; i < batch_limit; i++) { auto entity = std::make_unique<sync_pb::SyncEntity>(); - if (!ExtractSyncEntity(&trans, child_ids[i], entity.get())) { + if (!ExtractSyncEntity(type, &trans, child_ids[i], entity.get())) { LOG(ERROR) << "Failed to fetch child node for " << ModelTypeToString(type); // Inform the worker so it can clear any partial data and trigger a
diff --git a/components/sync/model/fake_model_type_change_processor.cc b/components/sync/model/fake_model_type_change_processor.cc index 92fd5dd5..5dc1f37 100644 --- a/components/sync/model/fake_model_type_change_processor.cc +++ b/components/sync/model/fake_model_type_change_processor.cc
@@ -56,6 +56,10 @@ return true; } +std::string FakeModelTypeChangeProcessor::TrackedAccountId() { + return ""; +} + void FakeModelTypeChangeProcessor::ReportError(const ModelError& error) { EXPECT_TRUE(expect_error_) << error.ToString(); expect_error_ = false;
diff --git a/components/sync/model/fake_model_type_change_processor.h b/components/sync/model/fake_model_type_change_processor.h index 3a23d50d..e7010a9 100644 --- a/components/sync/model/fake_model_type_change_processor.h +++ b/components/sync/model/fake_model_type_change_processor.h
@@ -40,6 +40,7 @@ void OnModelStarting(ModelTypeSyncBridge* bridge) override; void ModelReadyToSync(std::unique_ptr<MetadataBatch> batch) override; bool IsTrackingMetadata() override; + std::string TrackedAccountId() override; void ReportError(const ModelError& error) override; base::WeakPtr<ModelTypeControllerDelegate> GetControllerDelegate() override;
diff --git a/components/sync/model/mock_model_type_change_processor.cc b/components/sync/model/mock_model_type_change_processor.cc index 8d240d3..043e9af 100644 --- a/components/sync/model/mock_model_type_change_processor.cc +++ b/components/sync/model/mock_model_type_change_processor.cc
@@ -58,6 +58,8 @@ bool IsTrackingMetadata() override { return other_->IsTrackingMetadata(); } + std::string TrackedAccountId() override { return other_->TrackedAccountId(); } + void ReportError(const ModelError& error) override { other_->ReportError(error); } @@ -114,6 +116,9 @@ ON_CALL(*this, IsTrackingMetadata()) .WillByDefault( Invoke(delegate, &ModelTypeChangeProcessor::IsTrackingMetadata)); + ON_CALL(*this, TrackedAccountId()) + .WillByDefault( + Invoke(delegate, &ModelTypeChangeProcessor::TrackedAccountId)); ON_CALL(*this, ReportError(_)) .WillByDefault(Invoke(delegate, &ModelTypeChangeProcessor::ReportError)); ON_CALL(*this, GetControllerDelegate())
diff --git a/components/sync/model/mock_model_type_change_processor.h b/components/sync/model/mock_model_type_change_processor.h index b870c806..574f7f7 100644 --- a/components/sync/model/mock_model_type_change_processor.h +++ b/components/sync/model/mock_model_type_change_processor.h
@@ -36,6 +36,7 @@ MOCK_METHOD1(OnModelStarting, void(ModelTypeSyncBridge* bridge)); MOCK_METHOD1(ModelReadyToSync, void(std::unique_ptr<MetadataBatch> batch)); MOCK_METHOD0(IsTrackingMetadata, bool()); + MOCK_METHOD0(TrackedAccountId, std::string()); MOCK_METHOD1(ReportError, void(const ModelError& error)); MOCK_METHOD0(GetControllerDelegate, base::WeakPtr<ModelTypeControllerDelegate>());
diff --git a/components/sync/model/model_type_change_processor.h b/components/sync/model/model_type_change_processor.h index 69c535e8..399a9b36 100644 --- a/components/sync/model/model_type_change_processor.h +++ b/components/sync/model/model_type_change_processor.h
@@ -83,6 +83,10 @@ // will no-op and can be omitted by bridge. virtual bool IsTrackingMetadata() = 0; + // Returns the account ID for which metadata is being tracked, or empty if not + // tracking metadata. + virtual std::string TrackedAccountId() = 0; + // Report an error in the model to sync. Should be called for any persistence // or consistency error the bridge encounters outside of a method that allows // returning a ModelError directly. Outstanding callbacks are not expected to
diff --git a/components/sync/model/recording_model_type_change_processor.cc b/components/sync/model/recording_model_type_change_processor.cc index 0e1c1a5..0071ad9a 100644 --- a/components/sync/model/recording_model_type_change_processor.cc +++ b/components/sync/model/recording_model_type_change_processor.cc
@@ -57,6 +57,10 @@ return is_tracking_metadata_; } +std::string RecordingModelTypeChangeProcessor::TrackedAccountId() { + return ""; +} + void RecordingModelTypeChangeProcessor::SetIsTrackingMetadata( bool is_tracking) { is_tracking_metadata_ = is_tracking;
diff --git a/components/sync/model/recording_model_type_change_processor.h b/components/sync/model/recording_model_type_change_processor.h index c7853c0..6237238 100644 --- a/components/sync/model/recording_model_type_change_processor.h +++ b/components/sync/model/recording_model_type_change_processor.h
@@ -35,6 +35,7 @@ void UntrackEntityForStorageKey(const std::string& storage_key) override; void ModelReadyToSync(std::unique_ptr<MetadataBatch> batch) override; bool IsTrackingMetadata() override; + std::string TrackedAccountId() override; void SetIsTrackingMetadata(bool is_tracking);
diff --git a/components/sync/model_impl/client_tag_based_model_type_processor.cc b/components/sync/model_impl/client_tag_based_model_type_processor.cc index bd18024..a2ff46a5 100644 --- a/components/sync/model_impl/client_tag_based_model_type_processor.cc +++ b/components/sync/model_impl/client_tag_based_model_type_processor.cc
@@ -88,56 +88,10 @@ StartCallback start_callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DVLOG(1) << "Sync is starting for " << ModelTypeToString(type_); - // TODO(crbug.com/876490): Here and elsewhere in this file, CHECKs have been - // introduced to investigate some crashes in the wild. Let's downgrade all - // CHECKs to DCHECKs as soon as the investigation is completed. - CHECK(this); - CHECK(request.error_handler); - CHECK(start_callback); - - // Switch used to distinguish which datatypes contribute to CHECK failures. - switch (type_) { - case DEVICE_INFO: - CHECK(!start_callback_); - CHECK(!IsConnected()); - break; - case USER_CONSENTS: - CHECK(!start_callback_); - CHECK(!IsConnected()); - break; - case USER_EVENTS: - CHECK(!start_callback_); - CHECK(!IsConnected()); - break; - case SESSIONS: - CHECK(!start_callback_); - CHECK(!IsConnected()); - break; - case AUTOFILL: - CHECK(!start_callback_); - CHECK(!IsConnected()); - break; - case AUTOFILL_PROFILE: - CHECK(!start_callback_); - CHECK(!IsConnected()); - break; - case AUTOFILL_WALLET_DATA: - CHECK(!start_callback_); - CHECK(!IsConnected()); - break; - case AUTOFILL_WALLET_METADATA: - CHECK(!start_callback_); - CHECK(!IsConnected()); - break; - case TYPED_URLS: - CHECK(!start_callback_); - CHECK(!IsConnected()); - break; - default: - CHECK(!start_callback_); - CHECK(!IsConnected()); - break; - } + DCHECK(request.error_handler) << ModelTypeToString(type_); + DCHECK(start_callback) << ModelTypeToString(type_); + DCHECK(!start_callback_) << ModelTypeToString(type_); + DCHECK(!IsConnected()) << ModelTypeToString(type_); start_callback_ = std::move(start_callback); activation_request_ = request; @@ -151,15 +105,15 @@ void ClientTagBasedModelTypeProcessor::OnModelStarting( ModelTypeSyncBridge* bridge) { - CHECK(bridge); + DCHECK(bridge); bridge_ = bridge; } void ClientTagBasedModelTypeProcessor::ModelReadyToSync( std::unique_ptr<MetadataBatch> batch) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - CHECK(entities_.empty()); - CHECK(!model_ready_to_sync_); + DCHECK(entities_.empty()); + DCHECK(!model_ready_to_sync_); model_ready_to_sync_ = true; @@ -211,13 +165,13 @@ return; } - CHECK(model_ready_to_sync_); + DCHECK(model_ready_to_sync_); if (!model_type_state_.has_cache_guid()) { model_type_state_.set_cache_guid(activation_request_.cache_guid); } else if (model_type_state_.cache_guid() != activation_request_.cache_guid) { // There is a mismatch between the cache guid stored in |model_type_state_| - // and the one received from sync and stored it |activation_request|. This + // and the one received from sync and stored it |activation_request_|. This // indicates that the stored metadata are invalid (e.g. has been // manipulated) and don't belong to the current syncing client. const ModelTypeSyncBridge::StopSyncResponse response = @@ -235,7 +189,7 @@ case ModelTypeSyncBridge::StopSyncResponse::kModelNoLongerReadyToSync: // Model not ready to sync, so wait until the bridge calls // ModelReadyToSync(). - CHECK(!model_ready_to_sync_); + DCHECK(!model_ready_to_sync_); break; } @@ -243,6 +197,10 @@ bridge_->OnSyncStarting(activation_request_); } + // Cache GUID verification guarantees the user is the same. + model_type_state_.set_authenticated_account_id( + activation_request_.authenticated_account_id); + auto activation_response = std::make_unique<DataTypeActivationResponse>(); activation_response->model_type_state = model_type_state_; activation_response->type_processor = @@ -261,8 +219,8 @@ SyncStopMetadataFate metadata_fate) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Disabling sync for a type never happens before the model is ready to sync. - CHECK(model_ready_to_sync_); - CHECK(!start_callback_); + DCHECK(model_ready_to_sync_); + DCHECK(!start_callback_); switch (metadata_fate) { case KEEP_METADATA: { @@ -272,13 +230,13 @@ // The model is still ready to sync (with the same |bridge_|) and same // sync metadata. ResetState(KEEP_METADATA); - CHECK(model_ready_to_sync_); + DCHECK(model_ready_to_sync_); break; case ModelTypeSyncBridge::StopSyncResponse::kModelNoLongerReadyToSync: // Model not ready to sync, so wait until the bridge calls // ModelReadyToSync(), and meanwhile throw away all metadata. ResetState(CLEAR_METADATA); - CHECK(!model_ready_to_sync_); + DCHECK(!model_ready_to_sync_); break; } break; @@ -290,19 +248,19 @@ // The model is still ready to sync (with the same |bridge_|) - replay // the initialization. ModelReadyToSync(std::make_unique<MetadataBatch>()); - CHECK(model_ready_to_sync_); + DCHECK(model_ready_to_sync_); break; case ModelTypeSyncBridge::StopSyncResponse::kModelNoLongerReadyToSync: // Model not ready to sync, so wait until the bridge calls // ModelReadyToSync(). - CHECK(!model_ready_to_sync_); + DCHECK(!model_ready_to_sync_); break; } break; } } - CHECK(!IsConnected()); + DCHECK(!IsConnected()); } ModelTypeSyncBridge::StopSyncResponse @@ -327,6 +285,17 @@ return model_type_state_.initial_sync_done(); } +std::string ClientTagBasedModelTypeProcessor::TrackedAccountId() { + // Returning non-empty here despite !IsTrackingMetadata() has weird semantics, + // e.g. initial updates are being fetched but we haven't received the response + // (i.e. prior to exercising MergeSyncData()). Let's be cautious and hide the + // account ID. + if (!IsTrackingMetadata()) { + return ""; + } + return model_type_state_.authenticated_account_id(); +} + void ClientTagBasedModelTypeProcessor::ReportError(const ModelError& error) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -368,7 +337,7 @@ void ClientTagBasedModelTypeProcessor::DisconnectSync() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - CHECK(IsConnected()); + DCHECK(IsConnected()); DVLOG(1) << "Disconnecting sync for " << ModelTypeToString(type_); weak_ptr_factory_for_worker_.InvalidateWeakPtrs(); @@ -635,7 +604,7 @@ const sync_pb::ModelTypeState& model_type_state, const UpdateResponseDataList& updates) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - CHECK(model_ready_to_sync_); + DCHECK(model_ready_to_sync_); if (!ValidateUpdate(model_type_state, updates)) { return; @@ -891,11 +860,11 @@ const UpdateResponseDataList& updates) { std::unique_ptr<MetadataChangeList> metadata_changes = bridge_->CreateMetadataChangeList(); - CHECK(model_ready_to_sync_); + DCHECK(model_ready_to_sync_); // Check that the worker correctly marked initial sync as done // for this update. - CHECK(model_type_state.initial_sync_done()); + DCHECK(model_type_state.initial_sync_done()); if (HasClearAllDirective(model_type_state)) { ExpireAllEntries(metadata_changes.get()); @@ -953,8 +922,8 @@ ClientTagBasedModelTypeProcessor::OnIncrementalUpdateReceived( const sync_pb::ModelTypeState& model_type_state, const UpdateResponseDataList& updates) { - CHECK(model_ready_to_sync_); - CHECK(model_type_state.initial_sync_done()); + DCHECK(model_ready_to_sync_); + DCHECK(model_type_state.initial_sync_done()); std::unique_ptr<MetadataChangeList> metadata_changes = bridge_->CreateMetadataChangeList();
diff --git a/components/sync/model_impl/client_tag_based_model_type_processor.h b/components/sync/model_impl/client_tag_based_model_type_processor.h index ca98d4df..f669942 100644 --- a/components/sync/model_impl/client_tag_based_model_type_processor.h +++ b/components/sync/model_impl/client_tag_based_model_type_processor.h
@@ -69,6 +69,7 @@ void OnModelStarting(ModelTypeSyncBridge* bridge) override; void ModelReadyToSync(std::unique_ptr<MetadataBatch> batch) override; bool IsTrackingMetadata() override; + std::string TrackedAccountId() override; void ReportError(const ModelError& error) override; base::WeakPtr<ModelTypeControllerDelegate> GetControllerDelegate() override;
diff --git a/components/sync/model_impl/client_tag_based_model_type_processor_unittest.cc b/components/sync/model_impl/client_tag_based_model_type_processor_unittest.cc index fa6a9d0..99025bed 100644 --- a/components/sync/model_impl/client_tag_based_model_type_processor_unittest.cc +++ b/components/sync/model_impl/client_tag_based_model_type_processor_unittest.cc
@@ -225,13 +225,14 @@ void OnCommitDataLoaded() { bridge()->OnCommitDataLoaded(); } - void OnSyncStarting() { + void OnSyncStarting( + const std::string& authenticated_account_id = "SomeAccountId") { DataTypeActivationRequest request; request.error_handler = base::BindRepeating( &ClientTagBasedModelTypeProcessorTest::ErrorReceived, base::Unretained(this)); request.cache_guid = "TestCacheGuid"; - request.authenticated_account_id = "SomeAccountId"; + request.authenticated_account_id = authenticated_account_id; type_processor()->OnSyncStarting( request, base::BindOnce(&ClientTagBasedModelTypeProcessorTest::OnReadyToConnect, @@ -367,6 +368,32 @@ bool expect_error_ = false; }; +TEST_F(ClientTagBasedModelTypeProcessorTest, + ShouldExposeNewlyTrackedAccountId) { + ModelReadyToSync(); + ASSERT_EQ("", type_processor()->TrackedAccountId()); + OnSyncStarting("SomeAccountId"); + worker()->UpdateFromServer(); + EXPECT_EQ("SomeAccountId", type_processor()->TrackedAccountId()); +} + +TEST_F(ClientTagBasedModelTypeProcessorTest, + ShouldExposePreviouslyTrackedAccountId) { + std::unique_ptr<MetadataBatch> metadata_batch = db().CreateMetadataBatch(); + sync_pb::ModelTypeState model_type_state(metadata_batch->GetModelTypeState()); + model_type_state.set_initial_sync_done(true); + model_type_state.set_authenticated_account_id("PersistedAccountId"); + metadata_batch->SetModelTypeState(model_type_state); + type_processor()->ModelReadyToSync(std::move(metadata_batch)); + + // Even prior to starting sync, the account ID should already be tracked. + EXPECT_EQ("PersistedAccountId", type_processor()->TrackedAccountId()); + + // If sync gets started, the account should still be tracked. + OnSyncStarting("PersistedAccountId"); + EXPECT_EQ("PersistedAccountId", type_processor()->TrackedAccountId()); +} + // Test that an initial sync handles local and remote items properly. TEST_F(ClientTagBasedModelTypeProcessorTest, ShouldMergeLocalAndRemoteChanges) { ModelReadyToSync(); @@ -2035,6 +2062,31 @@ bool IsCommitOnly() override { return true; } }; +TEST_F(CommitOnlyClientTagBasedModelTypeProcessorTest, + ShouldExposeNewlyTrackedAccountId) { + ModelReadyToSync(); + ASSERT_EQ("", type_processor()->TrackedAccountId()); + OnSyncStarting("SomeAccountId"); + EXPECT_EQ("SomeAccountId", type_processor()->TrackedAccountId()); +} + +TEST_F(CommitOnlyClientTagBasedModelTypeProcessorTest, + ShouldExposePreviouslyTrackedAccountId) { + std::unique_ptr<MetadataBatch> metadata_batch = db().CreateMetadataBatch(); + sync_pb::ModelTypeState model_type_state(metadata_batch->GetModelTypeState()); + model_type_state.set_initial_sync_done(true); + model_type_state.set_authenticated_account_id("PersistedAccountId"); + metadata_batch->SetModelTypeState(model_type_state); + type_processor()->ModelReadyToSync(std::move(metadata_batch)); + + // Even prior to starting sync, the account ID should already be tracked. + EXPECT_EQ("PersistedAccountId", type_processor()->TrackedAccountId()); + + // If sync gets started, the account should still be tracked. + OnSyncStarting("PersistedAccountId"); + EXPECT_EQ("PersistedAccountId", type_processor()->TrackedAccountId()); +} + // Test that commit only types are deleted after commit response. TEST_F(CommitOnlyClientTagBasedModelTypeProcessorTest, ShouldCommitAndDeleteWhenAcked) {
diff --git a/components/sync/model_impl/proxy_model_type_controller_delegate.cc b/components/sync/model_impl/proxy_model_type_controller_delegate.cc index 9cdd430..7dd02f3b 100644 --- a/components/sync/model_impl/proxy_model_type_controller_delegate.cc +++ b/components/sync/model_impl/proxy_model_type_controller_delegate.cc
@@ -17,7 +17,7 @@ const DataTypeActivationRequest& request, ModelTypeControllerDelegate::StartCallback callback_bound_to_ui_thread, base::WeakPtr<ModelTypeControllerDelegate> delegate) { - CHECK(delegate); + DCHECK(delegate); delegate->OnSyncStarting(request, std::move(callback_bound_to_ui_thread)); } @@ -25,7 +25,7 @@ ProxyModelTypeControllerDelegate::AllNodesCallback callback_bound_to_ui_thread, base::WeakPtr<ModelTypeControllerDelegate> delegate) { - CHECK(delegate); + DCHECK(delegate); delegate->GetAllNodesForDebugging(std::move(callback_bound_to_ui_thread)); } @@ -33,7 +33,7 @@ ProxyModelTypeControllerDelegate::StatusCountersCallback callback_bound_to_ui_thread, base::WeakPtr<ModelTypeControllerDelegate> delegate) { - CHECK(delegate); + DCHECK(delegate); delegate->GetStatusCountersForDebugging( std::move(callback_bound_to_ui_thread)); } @@ -41,13 +41,13 @@ void StopSyncHelperOnModelThread( SyncStopMetadataFate metadata_fate, base::WeakPtr<ModelTypeControllerDelegate> delegate) { - CHECK(delegate); + DCHECK(delegate); delegate->OnSyncStopping(metadata_fate); } void RecordMemoryUsageAndCountsHistogramsHelperOnModelThread( base::WeakPtr<ModelTypeControllerDelegate> delegate) { - CHECK(delegate); + DCHECK(delegate); delegate->RecordMemoryUsageAndCountsHistograms(); } @@ -57,9 +57,9 @@ const ProxyModelTypeControllerDelegate::DelegateProvider& delegate_provider, base::OnceCallback<void(base::WeakPtr<ModelTypeControllerDelegate>)> task) { base::WeakPtr<ModelTypeControllerDelegate> delegate = delegate_provider.Run(); - // TODO(crbug.com/876490): Remove/revisit this CHECK once investigations are - // finalized. - CHECK(delegate); + // TODO(mastiz): Migrate away from weak pointers, since there is no actual + // need, provided that KeyedServices have proper dependencies. + DCHECK(delegate); std::move(task).Run(delegate); }
diff --git a/components/sync/protocol/model_type_state.proto b/components/sync/protocol/model_type_state.proto index b22652430..fb24429 100644 --- a/components/sync/protocol/model_type_state.proto +++ b/components/sync/protocol/model_type_state.proto
@@ -37,4 +37,7 @@ // persisted sync metadata, because cache_guid is reset when sync is disabled, // and disabling sync is supposed to clear sync metadata. optional string cache_guid = 5; + + // Syncing account ID, representing the user. + optional string authenticated_account_id = 6; }
diff --git a/components/sync/test/android/javatests/src/org/chromium/components/sync/test/util/MockSyncContentResolverDelegate.java b/components/sync/test/android/javatests/src/org/chromium/components/sync/test/util/MockSyncContentResolverDelegate.java index 934f332..ca7386fb1 100644 --- a/components/sync/test/android/javatests/src/org/chromium/components/sync/test/util/MockSyncContentResolverDelegate.java +++ b/components/sync/test/android/javatests/src/org/chromium/components/sync/test/util/MockSyncContentResolverDelegate.java
@@ -11,9 +11,9 @@ import org.junit.Assert; -import org.chromium.base.AsyncTask; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; +import org.chromium.base.task.AsyncTask; import org.chromium.components.sync.SyncContentResolverDelegate; import java.util.HashMap;
diff --git a/components/sync_sessions/session_sync_bridge.cc b/components/sync_sessions/session_sync_bridge.cc index 7e6d0049..501cee1 100644 --- a/components/sync_sessions/session_sync_bridge.cc +++ b/components/sync_sessions/session_sync_bridge.cc
@@ -172,11 +172,8 @@ base::Optional<syncer::ModelError> SessionSyncBridge::MergeSyncData( std::unique_ptr<MetadataChangeList> metadata_change_list, syncer::EntityChangeList entity_data) { - // TODO(crbug.com/876490): Here and elsewhere in this file, CHECKs have been - // introduced to investigate some crashes in the wild. Let's downgrade all - // CHECKs to DCHECKs as soon as the investigation is completed. - CHECK(syncing_); - CHECK(change_processor()->IsTrackingMetadata()); + DCHECK(syncing_); + DCHECK(change_processor()->IsTrackingMetadata()); StartLocalSessionEventHandler(); @@ -186,9 +183,9 @@ void SessionSyncBridge::StartLocalSessionEventHandler() { // We should be ready to propagate local state to sync. - CHECK(syncing_); - CHECK(!syncing_->local_session_event_handler); - CHECK(change_processor()->IsTrackingMetadata()); + DCHECK(syncing_); + DCHECK(!syncing_->local_session_event_handler); + DCHECK(change_processor()->IsTrackingMetadata()); syncing_->local_session_event_handler = std::make_unique<LocalSessionEventHandlerImpl>( @@ -204,8 +201,8 @@ base::Optional<syncer::ModelError> SessionSyncBridge::ApplySyncChanges( std::unique_ptr<MetadataChangeList> metadata_change_list, syncer::EntityChangeList entity_changes) { - CHECK(change_processor()->IsTrackingMetadata()); - CHECK(syncing_); + DCHECK(change_processor()->IsTrackingMetadata()); + DCHECK(syncing_); // Merging sessions is simple: remote entities are expected to be foreign // sessions (identified by the session tag) and hence must simply be @@ -310,7 +307,7 @@ std::unique_ptr<LocalSessionEventHandlerImpl::WriteBatch> SessionSyncBridge::CreateLocalSessionWriteBatch() { - CHECK(syncing_); + DCHECK(syncing_); // If a remote client mangled with our local session (typically deleted // entities due to garbage collection), we resubmit all local entities at this @@ -345,7 +342,7 @@ void SessionSyncBridge::OnSyncStarting( const syncer::DataTypeActivationRequest& request) { - CHECK(!syncing_); + DCHECK(!syncing_); session_store_factory_.Run(base::BindOnce( &SessionSyncBridge::OnStoreInitialized, weak_ptr_factory_.GetWeakPtr())); @@ -355,15 +352,15 @@ const base::Optional<syncer::ModelError>& error, std::unique_ptr<SessionStore> store, std::unique_ptr<syncer::MetadataBatch> metadata_batch) { - CHECK(!syncing_); + DCHECK(!syncing_); if (error) { change_processor()->ReportError(*error); return; } - CHECK(store); - CHECK(metadata_batch); + DCHECK(store); + DCHECK(metadata_batch); syncing_.emplace(); syncing_->store = std::move(store);
diff --git a/components/unified_consent/unified_consent_metrics.h b/components/unified_consent/unified_consent_metrics.h index 229c8e53..c275b8f 100644 --- a/components/unified_consent/unified_consent_metrics.h +++ b/components/unified_consent/unified_consent_metrics.h
@@ -23,7 +23,8 @@ kUserSignedOut = 0, kServiceWasDisabled, kCustomPassphrase, - kMaxValue = kCustomPassphrase + kUserDisabledSettingsToggle, + kMaxValue = kUserDisabledSettingsToggle }; // Records histogram action for the unified consent bump.
diff --git a/components/unified_consent/unified_consent_service.cc b/components/unified_consent/unified_consent_service.cc index e41796f..7db6822 100644 --- a/components/unified_consent/unified_consent_service.cc +++ b/components/unified_consent/unified_consent_service.cc
@@ -298,9 +298,11 @@ void UnifiedConsentService::OnPrimaryAccountCleared( const AccountInfo& account_info) { // When signing out, the unfied consent is revoked. - pref_service_->SetBoolean(prefs::kUnifiedConsentGiven, false); - RecordUnifiedConsentRevoked( - metrics::UnifiedConsentRevokeReason::kUserSignedOut); + if (IsUnifiedConsentGiven()) { + SetUnifiedConsentGiven(false); + RecordUnifiedConsentRevoked( + metrics::UnifiedConsentRevokeReason::kUserSignedOut); + } // By design, signing out of Chrome automatically disables off-by-default // services. @@ -355,23 +357,38 @@ void UnifiedConsentService::UpdateSyncSettingsIfPossible( bool sync_everything, - syncer::ModelTypeSet sync_data_types) { + syncer::ModelTypeSet enable_data_types, + syncer::ModelTypeSet disable_data_types) { + DCHECK(Intersection(enable_data_types, disable_data_types).Empty()); + if (sync_service_->GetDisableReasons() != syncer::SyncService::DISABLE_REASON_NONE || !sync_service_->IsEngineInitialized()) { return; } - sync_service_->OnUserChoseDatatypes(sync_everything, sync_data_types); + + if (sync_everything) { + sync_service_->OnUserChoseDatatypes(/*sync_everything=*/true, + syncer::UserSelectableTypes()); + return; + } + + syncer::ModelTypeSet data_types = sync_service_->GetPreferredDataTypes(); + data_types.PutAll(enable_data_types); + data_types.RemoveAll(disable_data_types); + data_types.RetainAll(syncer::UserSelectableTypes()); + sync_service_->OnUserChoseDatatypes(/*sync_everything=*/false, data_types); } void UnifiedConsentService::PostTaskToUpdateSyncSettings( bool sync_everything, - syncer::ModelTypeSet sync_data_types) { + syncer::ModelTypeSet enable_data_types, + syncer::ModelTypeSet disable_data_types) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&UnifiedConsentService::UpdateSyncSettingsIfPossible, weak_ptr_factory_.GetWeakPtr(), sync_everything, - sync_data_types)); + enable_data_types, disable_data_types)); } void UnifiedConsentService::OnUnifiedConsentGivenPrefChanged() { @@ -488,12 +505,9 @@ // Disable the datatype user events for newly migrated users. Also set // sync-everything to false, so it matches unified consent given. - syncer::ModelTypeSet preferred_types_without_user_events = - sync_service_->GetPreferredDataTypes(); - preferred_types_without_user_events.RetainAll(syncer::UserSelectableTypes()); - preferred_types_without_user_events.Remove(syncer::USER_EVENTS); - PostTaskToUpdateSyncSettings(/*sync_everything=*/false, - preferred_types_without_user_events); + PostTaskToUpdateSyncSettings( + /*sync_everything=*/false, /*enable_data_types=*/syncer::ModelTypeSet(), + /*disable_data_types=*/syncer::ModelTypeSet(syncer::USER_EVENTS)); SetMigrationState(MigrationState::kCompleted); }
diff --git a/components/unified_consent/unified_consent_service.h b/components/unified_consent/unified_consent_service.h index bff9bc4..800fba5e 100644 --- a/components/unified_consent/unified_consent_service.h +++ b/components/unified_consent/unified_consent_service.h
@@ -134,14 +134,22 @@ // Updates the sync settings if sync isn't disabled and the sync engine is // initialized. + // When |sync_everything| is false: + // - All sync data types in |enable_data_types| will be enabled. + // - All sync data types in |disable_data_types| will be disabled. + // - All data types in neither of the two sets will remain in the same state. + // When |sync_everything| is true, |enable_data_types| and + // |disable_data_types| will be ignored. void UpdateSyncSettingsIfPossible( bool sync_everything, - syncer::ModelTypeSet sync_data_types = syncer::UserSelectableTypes()); + syncer::ModelTypeSet enable_data_types = syncer::ModelTypeSet(), + syncer::ModelTypeSet disable_data_types = syncer::ModelTypeSet()); // Posts a task to call |UpdateSyncSettingsIfPossible|. void PostTaskToUpdateSyncSettings( bool sync_everything, - syncer::ModelTypeSet sync_data_types = syncer::UserSelectableTypes()); + syncer::ModelTypeSet enable_data_types = syncer::ModelTypeSet(), + syncer::ModelTypeSet disable_data_types = syncer::ModelTypeSet()); // Called when |prefs::kUnifiedConsentGiven| pref value changes. // When set to true, it enables syncing of all data types and it enables all
diff --git a/components/unified_consent/unified_consent_service_unittest.cc b/components/unified_consent/unified_consent_service_unittest.cc index 0880c43..a0a8394c 100644 --- a/components/unified_consent/unified_consent_service_unittest.cc +++ b/components/unified_consent/unified_consent_service_unittest.cc
@@ -167,6 +167,7 @@ service_client_ = (FakeUnifiedConsentServiceClient*) consent_service_->service_client_.get(); + sync_service_.FireStateChanged(); // Run until idle so the migration can finish. base::RunLoop().RunUntilIdle(); }
diff --git a/components/viz/common/features.cc b/components/viz/common/features.cc index ad28d64..1d6ccb77 100644 --- a/components/viz/common/features.cc +++ b/components/viz/common/features.cc
@@ -62,7 +62,6 @@ } bool IsVizHitTestingSurfaceLayerEnabled() { - // TODO(riajiang): Check feature flag as well. https://crbug.com/804888 // TODO(riajiang): Check kVizDisplayCompositor feature when it works with // that config. return (base::CommandLine::ForCurrentProcess()->HasSwitch(
diff --git a/components/viz/common/surfaces/local_surface_id.cc b/components/viz/common/surfaces/local_surface_id.cc index 897e83c..d5fc6333 100644 --- a/components/viz/common/surfaces/local_surface_id.cc +++ b/components/viz/common/surfaces/local_surface_id.cc
@@ -38,4 +38,8 @@ return IsNewerThan(other) || *this == other; } +LocalSurfaceId LocalSurfaceId::ToSmallestId() const { + return LocalSurfaceId(1, 1, embed_token_); +} + } // namespace viz
diff --git a/components/viz/common/surfaces/local_surface_id.h b/components/viz/common/surfaces/local_surface_id.h index 88cccf2..7a832c0 100644 --- a/components/viz/common/surfaces/local_surface_id.h +++ b/components/viz/common/surfaces/local_surface_id.h
@@ -144,6 +144,10 @@ // it. bool IsSameOrNewerThan(const LocalSurfaceId& other) const; + // Returns the smallest valid LocalSurfaceId with the same embed token as this + // LocalSurfaceID. + LocalSurfaceId ToSmallestId() const; + private: friend struct mojo::StructTraits<mojom::LocalSurfaceIdDataView, LocalSurfaceId>;
diff --git a/components/viz/common/surfaces/surface_id.cc b/components/viz/common/surfaces/surface_id.cc index 45b8850..02dc2a4 100644 --- a/components/viz/common/surfaces/surface_id.cc +++ b/components/viz/common/surfaces/surface_id.cc
@@ -32,6 +32,10 @@ other.local_surface_id().child_sequence_number())); } +SurfaceId SurfaceId::ToSmallestId() const { + return SurfaceId(frame_sink_id_, local_surface_id_.ToSmallestId()); +} + std::ostream& operator<<(std::ostream& out, const SurfaceId& surface_id) { return out << surface_id.ToString(); } @@ -42,4 +46,8 @@ return local_surface_id_.IsNewerThan(other.local_surface_id()); } +bool SurfaceId::IsSameOrNewerThan(const SurfaceId& other) const { + return (*this == other) || IsNewerThan(other); +} + } // namespace viz
diff --git a/components/viz/common/surfaces/surface_id.h b/components/viz/common/surfaces/surface_id.h index a1ddf17..f0dd7c4b 100644 --- a/components/viz/common/surfaces/surface_id.h +++ b/components/viz/common/surfaces/surface_id.h
@@ -62,10 +62,18 @@ // Returns whether this SurfaceId was generated after |other|. bool IsNewerThan(const SurfaceId& other) const; + // Returns whether this SurfaceId is the same as or was generated after + // |other|. + bool IsSameOrNewerThan(const SurfaceId& other) const; + // Compare this SurfaceId with |other| and returns the difference between the // parent sequence numbers plus the difference between child sequence numbers. uint32_t ManhattanDistanceTo(const SurfaceId& other) const; + // Returns the smallest valid SurfaceId with the same FrameSinkId and embed + // token as this SurfaceId. + SurfaceId ToSmallestId() const; + bool operator==(const SurfaceId& other) const { return frame_sink_id_ == other.frame_sink_id_ && local_surface_id_ == other.local_surface_id_;
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index cefe5880..dcc7cb4 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -2346,7 +2346,8 @@ "renderer_host/popup_window_mac.mm", "renderer_host/render_widget_host_ns_view_bridge_local.h", "renderer_host/render_widget_host_ns_view_bridge_local.mm", - "renderer_host/render_widget_host_ns_view_client.h", + "renderer_host/render_widget_host_ns_view_client_helper.h", + "renderer_host/render_widget_host_ns_view_client_helper.mm", "renderer_host/render_widget_host_view_cocoa.h", "renderer_host/render_widget_host_view_cocoa.mm", ]
diff --git a/content/browser/accessibility/accessibility_event_recorder_win.cc b/content/browser/accessibility/accessibility_event_recorder_win.cc index be122ba..0f1c7120 100644 --- a/content/browser/accessibility/accessibility_event_recorder_win.cc +++ b/content/browser/accessibility/accessibility_event_recorder_win.cc
@@ -210,8 +210,33 @@ return; } + std::string event_str = AccessibilityEventToStringUTF8(event); + if (event_str.empty()) { + VLOG(1) << "Ignoring event " << event; + return; + } + + base::win::ScopedVariant childid_self(CHILDID_SELF); + base::win::ScopedVariant role; + iaccessible->get_accRole(childid_self, role.Receive()); + base::win::ScopedVariant state; + iaccessible->get_accState(childid_self, state.Receive()); + int ia_state = V_I4(state.ptr()); + std::string hwnd_class_name = base::UTF16ToUTF8(gfx::GetClassName(hwnd)); + + // Caret is special: + // Log all caret events that occur, with their window class, so that we can + // test to make sure they are only occurring on the desired window class. + if (ROLE_SYSTEM_CARET == V_I4(role.ptr())) { + base::string16 state_str = IAccessibleStateToString(ia_state); + std::string log = base::StringPrintf( + "%s role=ROLE_SYSTEM_CARET %ls window_class=%s", event_str.c_str(), + state_str.c_str(), hwnd_class_name.c_str()); + OnEvent(log); + return; + } + if (only_web_events_) { - std::string hwnd_class_name = base::UTF16ToUTF8(gfx::GetClassName(hwnd)); if (hwnd_class_name != "Chrome_RenderWidgetHostHWND") return; @@ -227,22 +252,10 @@ return; } - std::string event_str = AccessibilityEventToStringUTF8(event); - if (event_str.empty()) { - VLOG(1) << "Ignoring event " << event; - return; - } - - base::win::ScopedVariant childid_self(CHILDID_SELF); - base::win::ScopedVariant role; - iaccessible->get_accRole(childid_self, role.Receive()); base::win::ScopedBstr name_bstr; iaccessible->get_accName(childid_self, name_bstr.Receive()); base::win::ScopedBstr value_bstr; iaccessible->get_accValue(childid_self, value_bstr.Receive()); - base::win::ScopedVariant state; - iaccessible->get_accState(childid_self, state.Receive()); - int ia_state = V_I4(state.ptr()); // Avoid flakiness. Events fired on a WINDOW are out of the control // of a test.
diff --git a/content/browser/accessibility/browser_accessibility_manager.cc b/content/browser/accessibility/browser_accessibility_manager.cc index 74e61f8d..8c86aa15 100644 --- a/content/browser/accessibility/browser_accessibility_manager.cc +++ b/content/browser/accessibility/browser_accessibility_manager.cc
@@ -373,7 +373,7 @@ // Fire any events related to changes to the tree. for (auto targeted_event : *this) { BrowserAccessibility* event_target = GetFromAXNode(targeted_event.node); - if (!event_target) + if (!event_target || event_target->PlatformIsChildOfLeaf()) continue; FireGeneratedEvent(targeted_event.event_params.event, event_target); @@ -386,7 +386,7 @@ // Fire the native event. BrowserAccessibility* event_target = GetFromID(event.id); - if (!event_target) + if (!event_target || event_target->PlatformIsChildOfLeaf()) return; if (event.event_type == ax::mojom::Event::kHover)
diff --git a/content/browser/accessibility/browser_accessibility_manager_win.cc b/content/browser/accessibility/browser_accessibility_manager_win.cc index c8237527..7091aaa 100644 --- a/content/browser/accessibility/browser_accessibility_manager_win.cc +++ b/content/browser/accessibility/browser_accessibility_manager_win.cc
@@ -19,6 +19,10 @@ namespace content { +// See OnScreenReaderHoneyPotQueried, below. +bool g_screen_reader_honeypot_queried = false; +bool g_acc_name_called = false; + // static BrowserAccessibilityManager* BrowserAccessibilityManager::Create( const ui::AXTreeUpdate& initial_tree, @@ -40,6 +44,7 @@ load_complete_pending_(false) { ui::win::CreateATLModuleIfNeeded(); Initialize(initial_tree); + ui::GetIAccessible2UsageObserverList().AddObserver(this); } BrowserAccessibilityManagerWin::~BrowserAccessibilityManagerWin() { @@ -47,6 +52,7 @@ // destructor, otherwise our overrides of functions like // OnNodeWillBeDeleted won't be called. tree_.reset(NULL); + ui::GetIAccessible2UsageObserverList().RemoveObserver(this); } // static @@ -70,6 +76,38 @@ return delegate->AccessibilityGetAcceleratedWidget(); } +void BrowserAccessibilityManagerWin::OnIAccessible2Used() { + // When IAccessible2 APIs have been used elsewhere in the codebase, + // enable basic web accessibility support. (Full screen reader support is + // detected later when specific more advanced APIs are accessed.) + BrowserAccessibilityStateImpl::GetInstance()->AddAccessibilityModeFlags( + ui::AXMode::kNativeAPIs | ui::AXMode::kWebContents); +} + +void BrowserAccessibilityManagerWin::OnScreenReaderHoneyPotQueried() { + // We used to trust this as a signal that a screen reader is running, + // but it's been abused. Now only enable accessibility if we also + // detect a call to get_accName. + if (g_screen_reader_honeypot_queried) + return; + g_screen_reader_honeypot_queried = true; + if (g_acc_name_called) { + BrowserAccessibilityStateImpl::GetInstance()->AddAccessibilityModeFlags( + ui::AXMode::kNativeAPIs | ui::AXMode::kWebContents); + } +} + +void BrowserAccessibilityManagerWin::OnAccNameCalled() { + // See OnScreenReaderHoneyPotQueried, above. + if (g_acc_name_called) + return; + g_acc_name_called = true; + if (g_screen_reader_honeypot_queried) { + BrowserAccessibilityStateImpl::GetInstance()->AddAccessibilityModeFlags( + ui::AXMode::kNativeAPIs | ui::AXMode::kWebContents); + } +} + void BrowserAccessibilityManagerWin::UserIsReloading() { if (GetRoot()) FireWinAccessibilityEvent(IA2_EVENT_DOCUMENT_RELOAD, GetRoot()); @@ -197,6 +235,9 @@ void BrowserAccessibilityManagerWin::FireWinAccessibilityEvent( LONG win_event_type, BrowserAccessibility* node) { + if (node->PlatformIsChildOfLeaf()) + return; + // If there's no root delegate, this may be a new frame that hasn't // yet been swapped in or added to the frame tree. Suppress firing events // until then.
diff --git a/content/browser/accessibility/browser_accessibility_manager_win.h b/content/browser/accessibility/browser_accessibility_manager_win.h index 88fd18b4..76d3434 100644 --- a/content/browser/accessibility/browser_accessibility_manager_win.h +++ b/content/browser/accessibility/browser_accessibility_manager_win.h
@@ -18,7 +18,8 @@ // Manages a tree of BrowserAccessibilityWin objects. class CONTENT_EXPORT BrowserAccessibilityManagerWin - : public BrowserAccessibilityManager { + : public BrowserAccessibilityManager, + public ui::IAccessible2UsageObserver { public: BrowserAccessibilityManagerWin( const ui::AXTreeUpdate& initial_tree, @@ -32,6 +33,11 @@ // Get the closest containing HWND. HWND GetParentHWND(); + // IAccessible2UsageObserver + void OnIAccessible2Used() override; + void OnScreenReaderHoneyPotQueried() override; + void OnAccNameCalled() override; + // BrowserAccessibilityManager methods void UserIsReloading() override; BrowserAccessibility* GetFocus() override;
diff --git a/content/browser/accessibility/browser_accessibility_state_impl.cc b/content/browser/accessibility/browser_accessibility_state_impl.cc index 9df6401..cbd461a 100644 --- a/content/browser/accessibility/browser_accessibility_state_impl.cc +++ b/content/browser/accessibility/browser_accessibility_state_impl.cc
@@ -168,8 +168,6 @@ } #if !defined(OS_WIN) && !defined(OS_MACOSX) -void BrowserAccessibilityStateImpl::PlatformInitialize() {} - void BrowserAccessibilityStateImpl::UpdatePlatformSpecificHistograms() { } #endif
diff --git a/content/browser/accessibility/browser_accessibility_state_impl.h b/content/browser/accessibility/browser_accessibility_state_impl.h index 1b592367..d3d09e3 100644 --- a/content/browser/accessibility/browser_accessibility_state_impl.h +++ b/content/browser/accessibility/browser_accessibility_state_impl.h
@@ -84,7 +84,6 @@ // Leaky singleton, destructor generally won't be called. ~BrowserAccessibilityStateImpl() override; - void PlatformInitialize(); void UpdatePlatformSpecificHistograms(); ui::AXMode accessibility_mode_;
diff --git a/content/browser/accessibility/browser_accessibility_state_impl_mac.mm b/content/browser/accessibility/browser_accessibility_state_impl_mac.mm index 262083f..e3a743e 100644 --- a/content/browser/accessibility/browser_accessibility_state_impl_mac.mm +++ b/content/browser/accessibility/browser_accessibility_state_impl_mac.mm
@@ -18,8 +18,6 @@ namespace content { -void BrowserAccessibilityStateImpl::PlatformInitialize() {} - void BrowserAccessibilityStateImpl::UpdatePlatformSpecificHistograms() { // NOTE: This function is running on the file thread. NSWorkspace* workspace = [NSWorkspace sharedWorkspace];
diff --git a/content/browser/accessibility/browser_accessibility_state_impl_win.cc b/content/browser/accessibility/browser_accessibility_state_impl_win.cc index 16314d71..df3b54b 100644 --- a/content/browser/accessibility/browser_accessibility_state_impl_win.cc +++ b/content/browser/accessibility/browser_accessibility_state_impl_win.cc
@@ -15,65 +15,9 @@ #include "base/macros.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_util.h" -#include "ui/accessibility/platform/ax_platform_node_win.h" namespace content { -namespace { - -// Enables accessibility based on three possible clues that indicate -// accessibility API usage. -// -// TODO(dmazzoni): Rename IAccessible2UsageObserver to something more general. -class WindowsAccessibilityEnabler : public ui::IAccessible2UsageObserver { - public: - WindowsAccessibilityEnabler() {} - - private: - // IAccessible2UsageObserver - void OnIAccessible2Used() override { - // When IAccessible2 APIs have been used elsewhere in the codebase, - // enable basic web accessibility support. (Full screen reader support is - // detected later when specific more advanced APIs are accessed.) - BrowserAccessibilityStateImpl::GetInstance()->AddAccessibilityModeFlags( - ui::AXMode::kNativeAPIs | ui::AXMode::kWebContents); - } - - void OnScreenReaderHoneyPotQueried() override { - // We used to trust this as a signal that a screen reader is running, - // but it's been abused. Now only enable accessibility if we also - // detect a call to get_accName. - if (screen_reader_honeypot_queried_) - return; - screen_reader_honeypot_queried_ = true; - if (acc_name_called_) { - BrowserAccessibilityStateImpl::GetInstance()->AddAccessibilityModeFlags( - ui::AXMode::kNativeAPIs | ui::AXMode::kWebContents); - } - } - - void OnAccNameCalled() override { - // See OnScreenReaderHoneyPotQueried, above. - if (acc_name_called_) - return; - acc_name_called_ = true; - if (screen_reader_honeypot_queried_) { - BrowserAccessibilityStateImpl::GetInstance()->AddAccessibilityModeFlags( - ui::AXMode::kNativeAPIs | ui::AXMode::kWebContents); - } - } - - bool screen_reader_honeypot_queried_ = false; - bool acc_name_called_ = false; -}; - -} // namespace - -void BrowserAccessibilityStateImpl::PlatformInitialize() { - ui::GetIAccessible2UsageObserverList().AddObserver( - new WindowsAccessibilityEnabler()); -} - void BrowserAccessibilityStateImpl::UpdatePlatformSpecificHistograms() { // NOTE: this method is run from the file thread to reduce jank, since // there's no guarantee these system calls will return quickly. Be careful
diff --git a/content/browser/accessibility/dump_accessibility_browsertest_base.cc b/content/browser/accessibility/dump_accessibility_browsertest_base.cc index 76f0cce..77b9831 100644 --- a/content/browser/accessibility/dump_accessibility_browsertest_base.cc +++ b/content/browser/accessibility/dump_accessibility_browsertest_base.cc
@@ -142,7 +142,8 @@ void DumpAccessibilityTestBase::ParseHtmlForExtraDirectives( const std::string& test_html, std::vector<Filter>* filters, - std::vector<std::string>* wait_for) { + std::vector<std::string>* wait_for, + std::vector<std::string>* run_until) { for (const std::string& line : base::SplitString(test_html, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) { @@ -150,6 +151,7 @@ const std::string& allow_str = formatter_->GetAllowString(); const std::string& deny_str = formatter_->GetDenyString(); const std::string& wait_str = "@WAIT-FOR:"; + const std::string& until_str = "@RUN-UNTIL-EVENT:"; if (base::StartsWith(line, allow_empty_str, base::CompareCase::SENSITIVE)) { filters->push_back( @@ -168,6 +170,9 @@ } else if (base::StartsWith(line, wait_str, base::CompareCase::SENSITIVE)) { wait_for->push_back(line.substr(wait_str.size())); + } else if (base::StartsWith(line, until_str, + base::CompareCase::SENSITIVE)) { + run_until->push_back(line.substr(until_str.size())); } } } @@ -254,9 +259,10 @@ // Parse filters and other directives in the test file. std::vector<std::string> wait_for; + std::vector<std::string> run_until; filters_.clear(); AddDefaultFilters(&filters_); - ParseHtmlForExtraDirectives(html_contents, &filters_, &wait_for); + ParseHtmlForExtraDirectives(html_contents, &filters_, &wait_for, &run_until); // Get the test URL. GURL url(embedded_test_server()->GetURL( @@ -354,7 +360,7 @@ } // Call the subclass to dump the output. - std::vector<std::string> actual_lines = Dump(); + std::vector<std::string> actual_lines = Dump(run_until); std::string actual_contents_for_output = base::JoinString(actual_lines, "\n") + "\n";
diff --git a/content/browser/accessibility/dump_accessibility_browsertest_base.h b/content/browser/accessibility/dump_accessibility_browsertest_base.h index 0dfb953b..35a8e57 100644 --- a/content/browser/accessibility/dump_accessibility_browsertest_base.h +++ b/content/browser/accessibility/dump_accessibility_browsertest_base.h
@@ -47,7 +47,8 @@ // including the load complete accessibility event. The subclass should // dump whatever that specific test wants to dump, returning the result // as a sequence of strings. - virtual std::vector<std::string> Dump() = 0; + virtual std::vector<std::string> Dump( + std::vector<std::string>& run_until) = 0; // Add the default filters that are applied to all tests. virtual void AddDefaultFilters( @@ -92,7 +93,8 @@ void ParseHtmlForExtraDirectives( const std::string& test_html, std::vector<AccessibilityTreeFormatter::Filter>* filters, - std::vector<std::string>* wait_for); + std::vector<std::string>* wait_for, + std::vector<std::string>* run_until); // Create the right AccessibilityTreeFormatter subclass. AccessibilityTreeFormatter* CreateAccessibilityTreeFormatter();
diff --git a/content/browser/accessibility/dump_accessibility_events_browsertest.cc b/content/browser/accessibility/dump_accessibility_events_browsertest.cc index 28df2b6b4..b94eabb 100644 --- a/content/browser/accessibility/dump_accessibility_events_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_events_browsertest.cc
@@ -69,7 +69,7 @@ base::ASCIIToUTF16("EVENT_OBJECT_FOCUS*DOCUMENT*"), Filter::DENY)); } - std::vector<std::string> Dump() override; + std::vector<std::string> Dump(std::vector<std::string>& run_until) override; void OnDiffFailed() override; void RunEventTest(const base::FilePath::CharType* file_path); @@ -79,7 +79,24 @@ base::string16 final_tree_; }; -std::vector<std::string> DumpAccessibilityEventsTest::Dump() { +bool IsRecordingComplete(AccessibilityEventRecorder& event_recorder, + std::vector<std::string>& run_until) { + // If no @RUN-UNTIL-EVENT directives, then having any events is enough. + if (run_until.empty()) + return true; + + std::vector<std::string> event_logs = event_recorder.event_logs(); + + for (size_t i = 0; i < event_logs.size(); ++i) + for (size_t j = 0; j < run_until.size(); ++j) + if (event_logs[i].find(run_until[j]) != std::string::npos) + return true; + + return false; +} + +std::vector<std::string> DumpAccessibilityEventsTest::Dump( + std::vector<std::string>& run_until) { WebContentsImpl* web_contents = static_cast<WebContentsImpl*>( shell()->web_contents()); base::ProcessId pid = base::GetCurrentProcId(); @@ -103,9 +120,11 @@ web_contents->GetMainFrame()->ExecuteJavaScriptForTests( base::ASCIIToUTF16("go()")); - // Wait for at least one accessibility event generated in response to - // that function. - waiter->WaitForNotification(); + for (;;) { + waiter->WaitForNotification(); // Run at least once. + if (IsRecordingComplete(*event_recorder, run_until)) + break; + } // More than one accessibility event could have been generated. // To make sure we've received all accessibility events, add a @@ -270,6 +289,11 @@ } IN_PROC_BROWSER_TEST_F(DumpAccessibilityEventsTest, + AccessibilityEventsCaretMove) { + RunEventTest(FILE_PATH_LITERAL("caret-move.html")); +} + +IN_PROC_BROWSER_TEST_F(DumpAccessibilityEventsTest, AccessibilityEventsCSSDisplay) { RunEventTest(FILE_PATH_LITERAL("css-display.html")); }
diff --git a/content/browser/accessibility/dump_accessibility_tree_browsertest.cc b/content/browser/accessibility/dump_accessibility_tree_browsertest.cc index 5436917..2117370 100644 --- a/content/browser/accessibility/dump_accessibility_tree_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_tree_browsertest.cc
@@ -125,7 +125,7 @@ RunTest(test_file, "accessibility/regression"); } - std::vector<std::string> Dump() override { + std::vector<std::string> Dump(std::vector<std::string>& unused) override { std::unique_ptr<AccessibilityTreeFormatter> formatter( CreateAccessibilityTreeFormatter()); formatter->SetFilters(filters_);
diff --git a/content/browser/frame_host/navigation_controller_impl_browsertest.cc b/content/browser/frame_host/navigation_controller_impl_browsertest.cc index 11c10c0..cecd091 100644 --- a/content/browser/frame_host/navigation_controller_impl_browsertest.cc +++ b/content/browser/frame_host/navigation_controller_impl_browsertest.cc
@@ -8197,4 +8197,44 @@ } } +// history.back() called twice in the renderer process should not make the user +// navigate back twice. +// Regression test for https://crbug.com/869710 +IN_PROC_BROWSER_TEST_F(NavigationControllerBrowserTest, + HistoryBackTwiceFromRendererWithoutUserGesture) { + GURL url1(embedded_test_server()->GetURL("a.com", "/title1.html")); + GURL url2(embedded_test_server()->GetURL("b.com", "/title2.html")); + GURL url3(embedded_test_server()->GetURL("c.com", "/title3.html")); + + EXPECT_TRUE(NavigateToURL(shell(), url1)); + EXPECT_TRUE(NavigateToURL(shell(), url2)); + EXPECT_TRUE(NavigateToURL(shell(), url3)); + + EXPECT_TRUE(ExecuteScriptWithoutUserGesture( + shell(), "history.back(); history.back();")); + EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); + + EXPECT_EQ(url2, shell()->web_contents()->GetLastCommittedURL()); +} + +// history.back() called twice in the renderer process should not make the user +// navigate back twice. Even with a user gesture. +// Regression test for https://crbug.com/869710 +IN_PROC_BROWSER_TEST_F(NavigationControllerBrowserTest, + HistoryBackTwiceFromRendererWithUserGesture) { + GURL url1(embedded_test_server()->GetURL("a.com", "/title1.html")); + GURL url2(embedded_test_server()->GetURL("b.com", "/title2.html")); + GURL url3(embedded_test_server()->GetURL("c.com", "/title3.html")); + + EXPECT_TRUE(NavigateToURL(shell(), url1)); + EXPECT_TRUE(NavigateToURL(shell(), url2)); + EXPECT_TRUE(NavigateToURL(shell(), url3)); + + EXPECT_TRUE(ExecuteScript(shell(), "history.back(); history.back();")); + EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); + + // TODO(https://crbug.com/869710): This should be url2. + EXPECT_EQ(url1, shell()->web_contents()->GetLastCommittedURL()); +} + } // namespace content
diff --git a/content/browser/frame_host/origin_policy_throttle.cc b/content/browser/frame_host/origin_policy_throttle.cc index b444afa..479dc14 100644 --- a/content/browser/frame_host/origin_policy_throttle.cc +++ b/content/browser/frame_host/origin_policy_throttle.cc
@@ -11,6 +11,7 @@ #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_handle.h" +#include "content/public/browser/origin_policy_error_reason.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" @@ -236,7 +237,7 @@ // Fail hard if the policy could not be loaded. if (!policy_content) { - CancelDeferredNavigation(NavigationThrottle::CANCEL_AND_IGNORE); + CancelNavigation(OriginPolicyErrorReason::kCannotLoadPolicy); return; } @@ -248,4 +249,12 @@ Resume(); } +void OriginPolicyThrottle::CancelNavigation(OriginPolicyErrorReason reason) { + base::Optional<std::string> error_page = + GetContentClient()->browser()->GetOriginPolicyErrorPage( + reason, GetRequestOrigin(), navigation_handle()->GetURL()); + CancelDeferredNavigation(NavigationThrottle::ThrottleCheckResult( + NavigationThrottle::CANCEL, net::ERR_BLOCKED_BY_CLIENT, error_page)); +} + } // namespace content
diff --git a/content/browser/frame_host/origin_policy_throttle.h b/content/browser/frame_host/origin_policy_throttle.h index 320558cc..35a4373 100644 --- a/content/browser/frame_host/origin_policy_throttle.h +++ b/content/browser/frame_host/origin_policy_throttle.h
@@ -25,6 +25,7 @@ namespace content { class NavigationHandle; +enum class OriginPolicyErrorReason; // The OriginPolicyThrottle is responsible for deciding whether an origin // policy should be fetched, and doing so when that is positive. @@ -72,6 +73,7 @@ void FetchPolicy(const GURL& url, FetchCallback done); void OnTheGloriousPolicyHasArrived( std::unique_ptr<std::string> policy_content); + void CancelNavigation(OriginPolicyErrorReason reason); // We may need the SimpleURLLoader to download the policy. The loader must // be kept alive while the load is ongoing.
diff --git a/content/browser/renderer_host/delegated_frame_host.cc b/content/browser/renderer_host/delegated_frame_host.cc index 27b9a199..769bc582 100644 --- a/content/browser/renderer_host/delegated_frame_host.cc +++ b/content/browser/renderer_host/delegated_frame_host.cc
@@ -484,20 +484,45 @@ } void DelegatedFrameHost::TakeFallbackContentFrom(DelegatedFrameHost* other) { - if (!other->HasFallbackSurface() || HasFallbackSurface()) + // If the other view is not showing anything, we can't obtain a fallback. + if (!other->HasPrimarySurface()) return; + // This method should not overwrite the existing fallback. This method is only + // supposed to be called when the view was just created and there is no + // existing fallback. + if (HasFallbackSurface()) + return; + + const viz::SurfaceId* other_primary = + other->client_->DelegatedFrameHostGetLayer()->GetPrimarySurfaceId(); + + const viz::SurfaceId* other_fallback = + other->client_->DelegatedFrameHostGetLayer()->GetFallbackSurfaceId(); + + // In two cases we need to obtain a new fallback from the primary id of the + // other view instead of using its fallback: + // - When the other view has no fallback, + // - When a fallback exists but has a different FrameSinkId or embed token + // than the primary. If we use the fallback, then the resulting SurfaceRange + // in this view will not cover any surface with the FrameSinkId / embed token + // of the old view's primary. + viz::SurfaceId desired_fallback; + if (!other_fallback || !other_primary->IsSameOrNewerThan(*other_fallback)) { + desired_fallback = other_primary->ToSmallestId(); + } else { + desired_fallback = *other_fallback; + } + if (!HasPrimarySurface()) { client_->DelegatedFrameHostGetLayer()->SetShowPrimarySurface( - *other->client_->DelegatedFrameHostGetLayer()->GetFallbackSurfaceId(), - other->client_->DelegatedFrameHostGetLayer()->size(), + desired_fallback, other->client_->DelegatedFrameHostGetLayer()->size(), other->client_->DelegatedFrameHostGetLayer()->background_color(), cc::DeadlinePolicy::UseDefaultDeadline(), false /* stretch_content_to_fill_bounds */); } - client_->DelegatedFrameHostGetLayer()->SetFallbackSurfaceId( - *other->client_->DelegatedFrameHostGetLayer()->GetFallbackSurfaceId()); + client_->DelegatedFrameHostGetLayer()->SetFallbackSurfaceId(desired_fallback); } } // namespace content
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.cc b/content/browser/renderer_host/render_widget_host_input_event_router.cc index 7c35654..62dc498e 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.cc +++ b/content/browser/renderer_host/render_widget_host_input_event_router.cc
@@ -353,6 +353,7 @@ RenderWidgetHostViewBase* target = nullptr; bool needs_transform_point = true; bool latched_target = true; + bool should_verify_result = false; if (root_view->IsMouseLocked()) { target = root_view->host()->delegate()->GetMouseLockWidget()->GetView(); } @@ -371,8 +372,14 @@ auto result = FindViewAtLocation( root_view, event.PositionInWidget(), event.PositionInScreen(), viz::EventSource::MOUSE, &transformed_point); + // Due to performance concerns we do not verify mouse move events. + should_verify_result = (event.GetType() == blink::WebInputEvent::kMouseMove) + ? false + : result.should_verify_result; if (result.should_query_view) { - return {result.view, true, transformed_point, latched_target}; + DCHECK(!should_verify_result); + return {result.view, true, transformed_point, latched_target, + should_verify_result}; } target = result.view; // |transformed_point| is already transformed. @@ -383,10 +390,11 @@ if (!root_view->TransformPointToCoordSpaceForView( event.PositionInWidget(), target, &transformed_point, viz::EventSource::MOUSE)) { - return {nullptr, false, base::nullopt, latched_target}; + return {nullptr, false, base::nullopt, latched_target, false}; } } - return {target, false, transformed_point, latched_target}; + return {target, false, transformed_point, latched_target, + should_verify_result}; } RenderWidgetTargetResult @@ -400,25 +408,21 @@ if (!root_view->TransformPointToCoordSpaceForView( event.PositionInWidget(), target, &transformed_point, viz::EventSource::MOUSE)) { - return {nullptr, false, base::nullopt, true}; + return {nullptr, false, base::nullopt, true, false}; } - return {target, false, transformed_point, true}; + return {target, false, transformed_point, true, false}; } - if (event.phase == blink::WebMouseWheelEvent::kPhaseBegan) { - auto result = FindViewAtLocation( - root_view, event.PositionInWidget(), event.PositionInScreen(), - viz::EventSource::MOUSE, &transformed_point); - return {result.view, result.should_query_view, transformed_point, false}; - } - // For non-begin events, the target found for the previous phaseBegan is - // used. - return {nullptr, false, base::nullopt, true}; - - auto result = FindViewAtLocation(root_view, event.PositionInWidget(), - event.PositionInScreen(), - viz::EventSource::MOUSE, &transformed_point); - return {result.view, result.should_query_view, transformed_point, false}; + if (event.phase == blink::WebMouseWheelEvent::kPhaseBegan) { + auto result = FindViewAtLocation( + root_view, event.PositionInWidget(), event.PositionInScreen(), + viz::EventSource::MOUSE, &transformed_point); + return {result.view, result.should_query_view, transformed_point, false, + result.should_verify_result}; + } + // For non-begin events, the target found for the previous phaseBegan is + // used. + return {nullptr, false, base::nullopt, true, false}; } RenderWidgetTargetResult RenderWidgetHostInputEventRouter::FindViewAtLocation( @@ -431,16 +435,17 @@ // hit testing. if (owner_map_.size() <= 1) { *transformed_point = point; - return {root_view, false, *transformed_point, false}; + return {root_view, false, *transformed_point, false, false}; } viz::FrameSinkId frame_sink_id; bool query_renderer = false; + bool should_verify_result = false; if (use_viz_hit_test_) { viz::HitTestQuery* query = GetHitTestQuery(GetHostFrameSinkManager(), root_view->GetRootFrameSinkId()); if (!query) - return {root_view, false, base::nullopt, false}; + return {root_view, false, base::nullopt, false, false}; // |point_in_screen| is in the coordinate space of of the screen, but the // display HitTestQuery does a hit test in the coordinate space of the root // window. The following translation should account for that discrepancy. @@ -458,8 +463,18 @@ } else { *transformed_point = point; } + // To ensure the correctness of viz hit testing with cc generated data, we + // verify hit test results when: + // a) We use cc generated data to do synchronous hit testing and + // b) We use HitTestQuery to find the target (instead of reusing previous + // targets when hit testing latched events) and + // c) We are not hit testing MouseMove events which is too frequent to + // verify it without impacting performance. + // The code that implements c) locates in |FindMouseEventTarget|. if (target.flags & viz::HitTestRegionFlags::kHitTestAsk) query_renderer = true; + else if (features::IsVizHitTestingSurfaceLayerEnabled()) + should_verify_result = true; } else { // The hittest delegate is used to reject hittesting quads based on extra // hittesting data send by the renderer. @@ -481,7 +496,8 @@ *transformed_point = point; } - return {view, query_renderer, *transformed_point, false}; + return {view, query_renderer, *transformed_point, false, + should_verify_result}; } void RenderWidgetHostInputEventRouter::RouteMouseEvent( @@ -685,7 +701,7 @@ // Tests may call this without an initial TouchStart, so check event type // explicitly here. if (active_touches_ || event.GetType() != blink::WebInputEvent::kTouchStart) - return {nullptr, false, base::nullopt, true}; + return {nullptr, false, base::nullopt, true, false}; active_touches_ += CountChangedTouchPoints(event); gfx::PointF original_point = gfx::PointF(event.touches[0].PositionInWidget()); @@ -1180,7 +1196,7 @@ // target we could just return nullptr for pinch events, but since we know // where they are going we return the correct target. if (blink::WebInputEvent::IsPinchGestureEventType(gesture_event.GetType())) - return {root_view, false, gesture_event.PositionInWidget(), true}; + return {root_view, false, gesture_event.PositionInWidget(), true, false}; // Android sends gesture events that have no corresponding touch sequence, so // these we hit-test explicitly. @@ -1195,7 +1211,7 @@ // Remaining gesture events will defer to the gesture event target queue // during dispatch. - return {nullptr, false, base::nullopt, true}; + return {nullptr, false, base::nullopt, true, false}; } bool RenderWidgetHostInputEventRouter::IsViewInMap( @@ -1409,7 +1425,7 @@ const blink::WebGestureEvent& event) const { if (event.GetType() != blink::WebInputEvent::kGesturePinchBegin && event.GetType() != blink::WebInputEvent::kGestureFlingCancel) { - return {nullptr, false, base::nullopt, true}; + return {nullptr, false, base::nullopt, true, false}; } gfx::PointF transformed_point;
diff --git a/content/browser/renderer_host/render_widget_host_ns_view_bridge_local.h b/content/browser/renderer_host/render_widget_host_ns_view_bridge_local.h index 42c1f7d..20f43f5 100644 --- a/content/browser/renderer_host/render_widget_host_ns_view_bridge_local.h +++ b/content/browser/renderer_host/render_widget_host_ns_view_bridge_local.h
@@ -26,7 +26,7 @@ public: RenderWidgetHostNSViewBridgeLocal( mojom::RenderWidgetHostNSViewClient* client, - RenderWidgetHostNSViewLocalClient* local_client); + RenderWidgetHostNSViewClientHelper* client_helper); ~RenderWidgetHostNSViewBridgeLocal() override; // TODO(ccameron): RenderWidgetHostViewMac and other functions currently use
diff --git a/content/browser/renderer_host/render_widget_host_ns_view_bridge_local.mm b/content/browser/renderer_host/render_widget_host_ns_view_bridge_local.mm index 570cbe1..3152fec 100644 --- a/content/browser/renderer_host/render_widget_host_ns_view_bridge_local.mm +++ b/content/browser/renderer_host/render_widget_host_ns_view_bridge_local.mm
@@ -17,12 +17,12 @@ RenderWidgetHostNSViewBridgeLocal::RenderWidgetHostNSViewBridgeLocal( mojom::RenderWidgetHostNSViewClient* client, - RenderWidgetHostNSViewLocalClient* local_client) { + RenderWidgetHostNSViewClientHelper* client_helper) { display::Screen::GetScreen()->AddObserver(this); cocoa_view_.reset([[RenderWidgetHostViewCocoa alloc] - initWithClient:client - withLocalClient:local_client]); + initWithClient:client + withClientHelper:client_helper]); background_layer_.reset([[CALayer alloc] init]); display_ca_layer_tree_ =
diff --git a/content/browser/renderer_host/render_widget_host_ns_view_client.h b/content/browser/renderer_host/render_widget_host_ns_view_client_helper.h similarity index 80% rename from content/browser/renderer_host/render_widget_host_ns_view_client.h rename to content/browser/renderer_host/render_widget_host_ns_view_client_helper.h index 5efb19f2..b8f764e 100644 --- a/content/browser/renderer_host/render_widget_host_ns_view_client.h +++ b/content/browser/renderer_host/render_widget_host_ns_view_client_helper.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_CLIENT_H_ -#define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_CLIENT_H_ +#ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_CLIENT_HELPER_H_ +#define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_CLIENT_HELPER_H_ #include "base/macros.h" @@ -22,6 +22,10 @@ namespace content { +namespace mojom { +class RenderWidgetHostNSViewClient; +} // namespace mojom + class BrowserAccessibilityManager; struct EditCommand; struct NativeWebKeyboardEvent; @@ -32,10 +36,16 @@ // instantiated in the local process. This is to implement functions that // cannot be sent across mojo (e.g, GetRootBrowserAccessibilityManager), or // to avoid unnecessary translation of event types. -class RenderWidgetHostNSViewLocalClient { +class RenderWidgetHostNSViewClientHelper { public: - RenderWidgetHostNSViewLocalClient() {} - virtual ~RenderWidgetHostNSViewLocalClient() {} + // Create a RenderWidgetHostNSViewClientHelper that will only implement + // functionality through mojo (this is in contrast with an in-process + // RenderWidgetHostNSViewClientHelper that would use raw pointer access). + static std::unique_ptr<RenderWidgetHostNSViewClientHelper> + CreateForMojoClient(content::mojom::RenderWidgetHostNSViewClient* client); + + RenderWidgetHostNSViewClientHelper() {} + virtual ~RenderWidgetHostNSViewClientHelper() {} // Return the RenderWidget's BrowserAccessibilityManager. // TODO(ccameron): This returns nullptr for non-local NSViews. A scheme for @@ -73,9 +83,9 @@ const blink::WebGestureEvent& smart_magnify_event) = 0; private: - DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostNSViewLocalClient); + DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostNSViewClientHelper); }; } // namespace content -#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_CLIENT_H_ +#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_NS_VIEW_CLIENT_HELPER_H_
diff --git a/content/browser/renderer_host/render_widget_host_ns_view_client_helper.mm b/content/browser/renderer_host/render_widget_host_ns_view_client_helper.mm new file mode 100644 index 0000000..40bac26 --- /dev/null +++ b/content/browser/renderer_host/render_widget_host_ns_view_client_helper.mm
@@ -0,0 +1,100 @@ +// 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 "render_widget_host_ns_view_client_helper.h" + +#include "content/browser/renderer_host/input/web_input_event_builders_mac.h" +#include "content/common/render_widget_host_ns_view.mojom.h" +#include "content/public/browser/native_web_keyboard_event.h" + +namespace content { + +namespace { + +class ForwardingClientHelper : public RenderWidgetHostNSViewClientHelper { + public: + explicit ForwardingClientHelper(mojom::RenderWidgetHostNSViewClient* client) + : client_(client) {} + + private: + std::unique_ptr<InputEvent> TranslateEvent( + const blink::WebInputEvent& web_event) { + return std::make_unique<InputEvent>(web_event, ui::LatencyInfo()); + } + + // RenderWidgetHostNSViewClientHelper implementation. + BrowserAccessibilityManager* GetRootBrowserAccessibilityManager() override { + return nullptr; + } + void ForwardKeyboardEvent(const NativeWebKeyboardEvent& key_event, + const ui::LatencyInfo& latency_info) override { + const blink::WebKeyboardEvent* web_event = + static_cast<const blink::WebKeyboardEvent*>(&key_event); + std::unique_ptr<InputEvent> input_event = + std::make_unique<InputEvent>(*web_event, latency_info); + client_->ForwardKeyboardEvent(std::move(input_event), + key_event.skip_in_browser); + } + void ForwardKeyboardEventWithCommands( + const NativeWebKeyboardEvent& key_event, + const ui::LatencyInfo& latency_info, + const std::vector<EditCommand>& commands) override { + const blink::WebKeyboardEvent* web_event = + static_cast<const blink::WebKeyboardEvent*>(&key_event); + std::unique_ptr<InputEvent> input_event = + std::make_unique<InputEvent>(*web_event, latency_info); + client_->ForwardKeyboardEventWithCommands( + std::move(input_event), key_event.skip_in_browser, commands); + } + void RouteOrProcessMouseEvent( + const blink::WebMouseEvent& web_event) override { + client_->RouteOrProcessMouseEvent(TranslateEvent(web_event)); + } + void RouteOrProcessTouchEvent( + const blink::WebTouchEvent& web_event) override { + client_->RouteOrProcessTouchEvent(TranslateEvent(web_event)); + } + void RouteOrProcessWheelEvent( + const blink::WebMouseWheelEvent& web_event) override { + client_->RouteOrProcessWheelEvent(TranslateEvent(web_event)); + } + void ForwardMouseEvent(const blink::WebMouseEvent& web_event) override { + client_->ForwardMouseEvent(TranslateEvent(web_event)); + } + void ForwardWheelEvent(const blink::WebMouseWheelEvent& web_event) override { + client_->ForwardWheelEvent(TranslateEvent(web_event)); + } + void GestureBegin(blink::WebGestureEvent begin_event, + bool is_synthetically_injected) override { + // The gesture type is not yet known, but assign a type to avoid + // serialization asserts (the type will be stripped on the other side). + begin_event.SetType(blink::WebInputEvent::kGestureScrollBegin); + client_->GestureBegin(TranslateEvent(begin_event), + is_synthetically_injected); + } + void GestureUpdate(blink::WebGestureEvent update_event) override { + client_->GestureUpdate(TranslateEvent(update_event)); + } + void GestureEnd(blink::WebGestureEvent end_event) override { + client_->GestureEnd(TranslateEvent(end_event)); + } + void SmartMagnify(const blink::WebGestureEvent& web_event) override { + client_->SmartMagnify(TranslateEvent(web_event)); + } + + mojom::RenderWidgetHostNSViewClient* client_ = nullptr; + + DISALLOW_COPY_AND_ASSIGN(ForwardingClientHelper); +}; + +} // namespace + +// static +std::unique_ptr<RenderWidgetHostNSViewClientHelper> +RenderWidgetHostNSViewClientHelper::CreateForMojoClient( + content::mojom::RenderWidgetHostNSViewClient* client) { + return std::make_unique<ForwardingClientHelper>(client); +} + +} // namespace content
diff --git a/content/browser/renderer_host/render_widget_host_view_cocoa.h b/content/browser/renderer_host/render_widget_host_view_cocoa.h index 83af25a..fc0105d 100644 --- a/content/browser/renderer_host/render_widget_host_view_cocoa.h +++ b/content/browser/renderer_host/render_widget_host_view_cocoa.h
@@ -31,7 +31,7 @@ class RenderWidgetHostNSViewClient; } -class RenderWidgetHostNSViewLocalClient; +class RenderWidgetHostNSViewClientHelper; class RenderWidgetHostViewMac; class RenderWidgetHostViewMacEditCommandHelper; } @@ -68,15 +68,13 @@ // This includes events (where the extra translation is unnecessary or loses // information) and access to accessibility structures (only present in the // browser process). - content::RenderWidgetHostNSViewLocalClient* localClient_; + content::RenderWidgetHostNSViewClientHelper* clientHelper_; - // An implementation of the in-process interface that will translate and - // forward messages through |client_|. - std::unique_ptr<content::RenderWidgetHostNSViewLocalClient> - forwardingLocalClient_; - - // Dummy client that is always valid (see above comments about client_). + // Dummy client and client helper that are always valid (see above comments + // about client_). content::mojom::RenderWidgetHostNSViewClientPtr dummyClient_; + std::unique_ptr<content::RenderWidgetHostNSViewClientHelper> + dummyClientHelper_; // This ivar is the cocoa delegate of the NSResponder. base::scoped_nsobject<NSObject<RenderWidgetHostViewMacDelegate>> @@ -251,7 +249,7 @@ // Methods previously marked as private. - (id)initWithClient:(content::mojom::RenderWidgetHostNSViewClient*)client - withLocalClient:(content::RenderWidgetHostNSViewLocalClient*)localClient; + withClientHelper:(content::RenderWidgetHostNSViewClientHelper*)clientHelper; - (void)setResponderDelegate: (NSObject<RenderWidgetHostViewMacDelegate>*)delegate; - (void)processedGestureScrollEvent:(const blink::WebGestureEvent&)event
diff --git a/content/browser/renderer_host/render_widget_host_view_cocoa.mm b/content/browser/renderer_host/render_widget_host_view_cocoa.mm index b1a29045..ee6cde81 100644 --- a/content/browser/renderer_host/render_widget_host_view_cocoa.mm +++ b/content/browser/renderer_host/render_widget_host_view_cocoa.mm
@@ -38,7 +38,7 @@ using content::InputEvent; using content::NativeWebKeyboardEvent; using content::mojom::RenderWidgetHostNSViewClient; -using content::RenderWidgetHostNSViewLocalClient; +using content::RenderWidgetHostNSViewClientHelper; using content::RenderWidgetHostViewMacEditCommandHelper; using content::WebGestureEventBuilder; using content::WebMouseEventBuilder; @@ -52,82 +52,6 @@ namespace { -class ForwardingLocalClient : public RenderWidgetHostNSViewLocalClient { - public: - explicit ForwardingLocalClient(RenderWidgetHostNSViewClient* client) - : client_(client) {} - - private: - std::unique_ptr<InputEvent> TranslateEvent( - const blink::WebInputEvent& web_event) { - return std::make_unique<InputEvent>(web_event, ui::LatencyInfo()); - } - - // RenderWidgetHostNSViewLocalClient implementation. - BrowserAccessibilityManager* GetRootBrowserAccessibilityManager() override { - return nullptr; - } - void ForwardKeyboardEvent(const NativeWebKeyboardEvent& key_event, - const ui::LatencyInfo& latency_info) override { - const blink::WebKeyboardEvent* web_event = - static_cast<const blink::WebKeyboardEvent*>(&key_event); - std::unique_ptr<InputEvent> input_event = - std::make_unique<InputEvent>(*web_event, latency_info); - client_->ForwardKeyboardEvent(std::move(input_event), - key_event.skip_in_browser); - } - void ForwardKeyboardEventWithCommands( - const NativeWebKeyboardEvent& key_event, - const ui::LatencyInfo& latency_info, - const std::vector<EditCommand>& commands) override { - const blink::WebKeyboardEvent* web_event = - static_cast<const blink::WebKeyboardEvent*>(&key_event); - std::unique_ptr<InputEvent> input_event = - std::make_unique<InputEvent>(*web_event, latency_info); - client_->ForwardKeyboardEventWithCommands( - std::move(input_event), key_event.skip_in_browser, commands); - } - void RouteOrProcessMouseEvent( - const blink::WebMouseEvent& web_event) override { - client_->RouteOrProcessMouseEvent(TranslateEvent(web_event)); - } - void RouteOrProcessTouchEvent( - const blink::WebTouchEvent& web_event) override { - client_->RouteOrProcessTouchEvent(TranslateEvent(web_event)); - } - void RouteOrProcessWheelEvent( - const blink::WebMouseWheelEvent& web_event) override { - client_->RouteOrProcessWheelEvent(TranslateEvent(web_event)); - } - void ForwardMouseEvent(const blink::WebMouseEvent& web_event) override { - client_->ForwardMouseEvent(TranslateEvent(web_event)); - } - void ForwardWheelEvent(const blink::WebMouseWheelEvent& web_event) override { - client_->ForwardWheelEvent(TranslateEvent(web_event)); - } - void GestureBegin(blink::WebGestureEvent begin_event, - bool is_synthetically_injected) override { - // The gesture type is not yet known, but assign a type to avoid - // serialization asserts (the type will be stripped on the other side). - begin_event.SetType(blink::WebInputEvent::kGestureScrollBegin); - client_->GestureBegin(TranslateEvent(begin_event), - is_synthetically_injected); - } - void GestureUpdate(blink::WebGestureEvent update_event) override { - client_->GestureUpdate(TranslateEvent(update_event)); - } - void GestureEnd(blink::WebGestureEvent end_event) override { - client_->GestureEnd(TranslateEvent(end_event)); - } - void SmartMagnify(const blink::WebGestureEvent& web_event) override { - client_->SmartMagnify(TranslateEvent(web_event)); - } - - RenderWidgetHostNSViewClient* client_ = nullptr; - - DISALLOW_COPY_AND_ASSIGN(ForwardingLocalClient); -}; - // Whether a keyboard event has been reserved by OSX. BOOL EventIsReservedBySystem(NSEvent* event) { content::SystemHotkeyHelperMac* helper = @@ -213,7 +137,7 @@ @synthesize textInputType = textInputType_; - (id)initWithClient:(RenderWidgetHostNSViewClient*)client - withLocalClient:(RenderWidgetHostNSViewLocalClient*)localClient { + withClientHelper:(RenderWidgetHostNSViewClientHelper*)clientHelper { self = [super initWithFrame:NSZeroRect]; if (self) { self.acceptsTouchEvents = YES; @@ -221,12 +145,7 @@ editCommandHelper_->AddEditingSelectorsToClass([self class]); client_ = client; - if (localClient) { - localClient_ = localClient; - } else { - forwardingLocalClient_ = std::make_unique<ForwardingLocalClient>(client_); - localClient_ = forwardingLocalClient_.get(); - } + clientHelper_ = clientHelper; canBeKeyView_ = YES; isStylusEnteringProximity_ = false; keyboardLockActive_ = false; @@ -373,13 +292,14 @@ } - (void)setClientDisconnected { - // Set the client to be an abandoned message pipe, and set the localClient + // Set the client to be an abandoned message pipe, and set the clientHelper // to forward messages to that client. content::mojom::RenderWidgetHostNSViewClientRequest dummyClientRequest = mojo::MakeRequest(&dummyClient_); + dummyClientHelper_ = RenderWidgetHostNSViewClientHelper::CreateForMojoClient( + dummyClient_.get()); client_ = dummyClient_.get(); - forwardingLocalClient_ = std::make_unique<ForwardingLocalClient>(client_); - localClient_ = forwardingLocalClient_.get(); + clientHelper_ = dummyClientHelper_.get(); // |responderDelegate_| may attempt to access the RenderWidgetHostViewMac // through its internal pointers, so detach it here. @@ -422,7 +342,7 @@ WebMouseEvent web_event = WebMouseEventBuilder::Build(event, self); web_event.SetModifiers(web_event.GetModifiers() | WebInputEvent::kRelativeMotionEvent); - localClient_->ForwardMouseEvent(web_event); + clientHelper_->ForwardMouseEvent(web_event); } - (BOOL)shouldIgnoreMouseEvent:(NSEvent*)theEvent { @@ -512,7 +432,7 @@ WebMouseEventBuilder::Build(theEvent, self, pointerType_); exitEvent.SetType(WebInputEvent::kMouseLeave); exitEvent.button = WebMouseEvent::Button::kNoButton; - localClient_->ForwardMouseEvent(exitEvent); + clientHelper_->ForwardMouseEvent(exitEvent); } mouseEventWasIgnored_ = YES; return; @@ -525,7 +445,7 @@ WebMouseEventBuilder::Build(theEvent, self, pointerType_); enterEvent.SetType(WebInputEvent::kMouseMove); enterEvent.button = WebMouseEvent::Button::kNoButton; - localClient_->RouteOrProcessMouseEvent(enterEvent); + clientHelper_->RouteOrProcessMouseEvent(enterEvent); } mouseEventWasIgnored_ = NO; @@ -579,10 +499,10 @@ if (!send_touch) { WebMouseEvent event = WebMouseEventBuilder::Build(theEvent, self, pointerType_); - localClient_->RouteOrProcessMouseEvent(event); + clientHelper_->RouteOrProcessMouseEvent(event); } else { WebTouchEvent event = WebTouchEventBuilder::Build(theEvent, self); - localClient_->RouteOrProcessTouchEvent(event); + clientHelper_->RouteOrProcessTouchEvent(event); } } @@ -729,7 +649,7 @@ // We only handle key down events and just simply forward other events. if (eventType != NSKeyDown) { - localClient_->ForwardKeyboardEvent(event, latency_info); + clientHelper_->ForwardKeyboardEvent(event, latency_info); // Possibly autohide the cursor. if (shouldAutohideCursor) { @@ -787,7 +707,7 @@ NativeWebKeyboardEvent fakeEvent = event; fakeEvent.windows_key_code = 0xE5; // VKEY_PROCESSKEY fakeEvent.skip_in_browser = true; - localClient_->ForwardKeyboardEvent(fakeEvent, latency_info); + clientHelper_->ForwardKeyboardEvent(fakeEvent, latency_info); // If this key event was handled by the input method, but // -doCommandBySelector: (invoked by the call to -interpretKeyEvents: above) // enqueued edit commands, then in order to let webkit handle them @@ -798,8 +718,8 @@ if (hasEditCommands_ && !hasMarkedText_) delayEventUntilAfterImeCompostion = YES; } else { - localClient_->ForwardKeyboardEventWithCommands(event, latency_info, - editCommands_); + clientHelper_->ForwardKeyboardEventWithCommands(event, latency_info, + editCommands_); } // Then send keypress and/or composition related events. @@ -857,8 +777,8 @@ fakeEvent.skip_in_browser = true; ui::LatencyInfo fake_event_latency_info = latency_info; fake_event_latency_info.set_source_event_type(ui::SourceEventType::OTHER); - localClient_->ForwardKeyboardEvent(fakeEvent, fake_event_latency_info); - localClient_->ForwardKeyboardEventWithCommands( + clientHelper_->ForwardKeyboardEvent(fakeEvent, fake_event_latency_info); + clientHelper_->ForwardKeyboardEventWithCommands( event, fake_event_latency_info, editCommands_); } @@ -872,7 +792,7 @@ event.text[0] = textToBeInserted_[0]; event.text[1] = 0; event.skip_in_browser = true; - localClient_->ForwardKeyboardEvent(event, latency_info); + clientHelper_->ForwardKeyboardEvent(event, latency_info); } else if ((!textInserted || delayEventUntilAfterImeCompostion) && event.text[0] != '\0' && ((modifierFlags & kCtrlCmdKeyMask) || @@ -882,7 +802,7 @@ // cases, unless the key event generated any other command. event.SetType(blink::WebInputEvent::kChar); event.skip_in_browser = true; - localClient_->ForwardKeyboardEvent(event, latency_info); + clientHelper_->ForwardKeyboardEvent(event, latency_info); } } @@ -913,7 +833,7 @@ // History-swiping is not possible if the logic reaches this point. WebMouseWheelEvent webEvent = WebMouseWheelEventBuilder::Build(event, self); webEvent.rails_mode = mouseWheelFilter_.UpdateRailsMode(webEvent); - localClient_->ForwardWheelEvent(webEvent); + clientHelper_->ForwardWheelEvent(webEvent); if (endWheelMonitor_) { [NSEvent removeMonitor:endWheelMonitor_]; @@ -927,7 +847,7 @@ WebGestureEvent gestureBeginEvent(WebGestureEventBuilder::Build(event, self)); - localClient_->GestureBegin(gestureBeginEvent, isSyntheticallyInjected); + clientHelper_->GestureBegin(gestureBeginEvent, isSyntheticallyInjected); } - (void)handleEndGestureWithEvent:(NSEvent*)event { @@ -943,7 +863,7 @@ endEvent.SetSourceDevice( blink::WebGestureDevice::kWebGestureDeviceTouchpad); endEvent.SetNeedsWheelEvent(true); - localClient_->GestureEnd(endEvent); + clientHelper_->GestureEnd(endEvent); } } @@ -998,7 +918,7 @@ - (void)smartMagnifyWithEvent:(NSEvent*)event { const WebGestureEvent& smartMagnifyEvent = WebGestureEventBuilder::Build(event, self); - localClient_->SmartMagnify(smartMagnifyEvent); + clientHelper_->SmartMagnify(smartMagnifyEvent); } - (void)showLookUpDictionaryOverlayFromRange:(NSRange)range { @@ -1080,7 +1000,7 @@ // This is responsible for content scrolling! WebMouseWheelEvent webEvent = WebMouseWheelEventBuilder::Build(event, self); webEvent.rails_mode = mouseWheelFilter_.UpdateRailsMode(webEvent); - localClient_->RouteOrProcessWheelEvent(webEvent); + clientHelper_->RouteOrProcessWheelEvent(webEvent); } // Called repeatedly during a pinch gesture, with incremental change values. @@ -1113,7 +1033,7 @@ } WebGestureEvent updateEvent = WebGestureEventBuilder::Build(event, self); - localClient_->GestureUpdate(updateEvent); + clientHelper_->GestureUpdate(updateEvent); } - (void)viewWillMoveToWindow:(NSWindow*)newWindow { @@ -1361,7 +1281,7 @@ - (id)accessibilityAttributeValue:(NSString*)attribute { BrowserAccessibilityManager* manager = - localClient_->GetRootBrowserAccessibilityManager(); + clientHelper_->GetRootBrowserAccessibilityManager(); // Contents specifies document view of RenderWidgetHostViewCocoa provided by // BrowserAccessibilityManager. Children includes all subviews in addition to @@ -1387,7 +1307,7 @@ - (id)accessibilityHitTest:(NSPoint)point { BrowserAccessibilityManager* manager = - localClient_->GetRootBrowserAccessibilityManager(); + clientHelper_->GetRootBrowserAccessibilityManager(); if (!manager) return self; NSPoint pointInWindow = @@ -1402,13 +1322,13 @@ - (BOOL)accessibilityIsIgnored { BrowserAccessibilityManager* manager = - localClient_->GetRootBrowserAccessibilityManager(); + clientHelper_->GetRootBrowserAccessibilityManager(); return !manager; } - (NSUInteger)accessibilityGetIndexOf:(id)child { BrowserAccessibilityManager* manager = - localClient_->GetRootBrowserAccessibilityManager(); + clientHelper_->GetRootBrowserAccessibilityManager(); // Only child is root. if (manager && ToBrowserAccessibilityCocoa(manager->GetRoot()) == child) { return 0; @@ -1429,7 +1349,7 @@ return popup_focus_override; BrowserAccessibilityManager* manager = - localClient_->GetRootBrowserAccessibilityManager(); + clientHelper_->GetRootBrowserAccessibilityManager(); if (manager) { BrowserAccessibility* focused_item = manager->GetFocus(); DCHECK(focused_item); @@ -1791,7 +1711,7 @@ WebMouseEvent event(WebInputEvent::kMouseUp, WebInputEvent::kNoModifiers, ui::EventTimeForNow()); event.button = WebMouseEvent::Button::kLeft; - localClient_->ForwardMouseEvent(event); + clientHelper_->ForwardMouseEvent(event); hasOpenMouseDown_ = NO; } }
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 ebe4e9c..a546516 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.h +++ b/content/browser/renderer_host/render_widget_host_view_mac.h
@@ -17,7 +17,7 @@ #include "components/viz/common/surfaces/surface_id.h" #include "content/browser/renderer_host/browser_compositor_view_mac.h" #include "content/browser/renderer_host/input/mouse_wheel_phase_handler.h" -#include "content/browser/renderer_host/render_widget_host_ns_view_client.h" +#include "content/browser/renderer_host/render_widget_host_ns_view_client_helper.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/browser/renderer_host/text_input_manager.h" #include "content/common/content_export.h" @@ -65,7 +65,7 @@ // RenderWidgetHostView class hierarchy described in render_widget_host_view.h. class CONTENT_EXPORT RenderWidgetHostViewMac : public RenderWidgetHostViewBase, - public RenderWidgetHostNSViewLocalClient, + public RenderWidgetHostNSViewClientHelper, public mojom::RenderWidgetHostNSViewClient, public BrowserCompositorMacClient, public TextInputManager::Observer, @@ -300,7 +300,7 @@ // RenderWidgetHostImpl as well. void UpdateNSViewAndDisplayProperties(); - // RenderWidgetHostNSViewLocalClient implementation. + // RenderWidgetHostNSViewClientHelper implementation. BrowserAccessibilityManager* GetRootBrowserAccessibilityManager() override; void ForwardKeyboardEvent(const NativeWebKeyboardEvent& key_event, const ui::LatencyInfo& latency_info) override;
diff --git a/content/browser/renderer_host/render_widget_host_view_mac.mm b/content/browser/renderer_host/render_widget_host_view_mac.mm index 896109a..baa3d80 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.mm +++ b/content/browser/renderer_host/render_widget_host_view_mac.mm
@@ -1381,7 +1381,7 @@ } /////////////////////////////////////////////////////////////////////////////// -// RenderWidgetHostNSViewLocalClient and mojom::RenderWidgetHostNSViewClient +// RenderWidgetHostNSViewClientHelper and mojom::RenderWidgetHostNSViewClient // implementation: BrowserAccessibilityManager* @@ -1861,7 +1861,7 @@ /////////////////////////////////////////////////////////////////////////////// // mojom::RenderWidgetHostNSViewClient functions that translate events and -// forward them to the RenderWidgetHostNSViewLocalClient implementation: +// forward them to the RenderWidgetHostNSViewClientHelper implementation: void RenderWidgetHostViewMac::ForwardKeyboardEvent( std::unique_ptr<InputEvent> input_event,
diff --git a/content/browser/renderer_host/render_widget_targeter.cc b/content/browser/renderer_host/render_widget_targeter.cc index eef715fc..815bdf0 100644 --- a/content/browser/renderer_host/render_widget_targeter.cc +++ b/content/browser/renderer_host/render_widget_targeter.cc
@@ -6,6 +6,7 @@ #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" +#include "components/viz/common/features.h" #include "content/browser/renderer_host/input/one_shot_timeout_monitor.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" @@ -93,11 +94,13 @@ RenderWidgetHostViewBase* in_view, bool in_should_query_view, base::Optional<gfx::PointF> in_location, - bool in_latched_target) + bool in_latched_target, + bool in_should_verify_result) : view(in_view), should_query_view(in_should_query_view), target_location(in_location), - latched_target(in_latched_target) {} + latched_target(in_latched_target), + should_verify_result(in_should_verify_result) {} RenderWidgetTargetResult::~RenderWidgetTargetResult() = default; @@ -160,11 +163,20 @@ // Currently it has to return the surface hit test target, for event types // that ignore |result.should_query_view|, and therefore we have to use // root_view and the original event location for the initial query. + // Do not compare hit test results if we are forced to do async hit testing + // by HitTestQuery. QueryClient(root_view, root_view, *event_ptr, latency, ComputeEventLocation(event), nullptr, gfx::PointF()); } else { FoundTarget(root_view, target, *event_ptr, latency, result.target_location, - result.latched_target); + result.latched_target, viz::FrameSinkId()); + // Verify the event targeting results from surface layer viz hit testing if + // --use-viz-hit-test-surface-layer is enabled. + if (result.should_verify_result && !target->IsRenderWidgetHostViewGuest()) { + QueryAndVerifyClient(root_view, root_view, *event_ptr, latency, + ComputeEventLocation(event), nullptr, gfx::PointF(), + target->GetFrameSinkId()); + } } } @@ -172,6 +184,60 @@ unresponsive_views_.erase(view); } +void RenderWidgetTargeter::QueryClientInternal( + RenderWidgetHostViewBase* root_view, + RenderWidgetHostViewBase* target, + const blink::WebInputEvent& event, + const ui::LatencyInfo& latency, + const gfx::PointF& target_location, + RenderWidgetHostViewBase* last_request_target, + const gfx::PointF& last_target_location, + const viz::FrameSinkId& expected_frame_sink_id) { + // Async event targeting and verifying use two different queues, so they don't + // block each other. + bool is_verifying = expected_frame_sink_id.is_valid(); + DCHECK((!is_verifying && !request_in_flight_) || + (is_verifying && !verify_request_in_flight_)); + + auto* target_client = target->host()->input_target_client(); + // |target_client| may not be set yet for this |target| on Mac, need to + // understand why this happens. https://crbug.com/859492. + // We do not verify hit testing result under this circumstance. + if (!target_client) { + FoundTarget(root_view, target, event, latency, target_location, false, + viz::FrameSinkId()); + return; + } + + if (is_verifying) { + verify_request_in_flight_ = true; + } else { + request_in_flight_ = true; + async_depth_++; + } + TracingUmaTracker tracker("Event.AsyncTargeting.ResponseTime", + "input,latency"); + auto& hit_test_timeout = + is_verifying ? async_verify_hit_test_timeout_ : async_hit_test_timeout_; + hit_test_timeout.reset(new OneShotTimeoutMonitor( + base::BindOnce( + &RenderWidgetTargeter::AsyncHitTestTimedOut, + weak_ptr_factory_.GetWeakPtr(), root_view->GetWeakPtr(), + target->GetWeakPtr(), target_location, + last_request_target ? last_request_target->GetWeakPtr() : nullptr, + last_target_location, ui::WebInputEventTraits::Clone(event), latency, + expected_frame_sink_id), + async_hit_test_timeout_delay_)); + target_client->FrameSinkIdAt( + gfx::ToCeiledPoint(target_location), + base::BindOnce( + &RenderWidgetTargeter::FoundFrameSinkId, + weak_ptr_factory_.GetWeakPtr(), root_view->GetWeakPtr(), + target->GetWeakPtr(), ui::WebInputEventTraits::Clone(event), latency, + is_verifying ? ++last_verify_request_id_ : ++last_request_id_, + target_location, std::move(tracker), expected_frame_sink_id)); +} + void RenderWidgetTargeter::QueryClient( RenderWidgetHostViewBase* root_view, RenderWidgetHostViewBase* target, @@ -180,58 +246,67 @@ const gfx::PointF& target_location, RenderWidgetHostViewBase* last_request_target, const gfx::PointF& last_target_location) { - DCHECK(!request_in_flight_); - - auto* target_client = target->host()->input_target_client(); - // |target_client| may not be set yet for this |target| on Mac, need to - // understand why this happens. https://crbug.com/859492 - if (!target_client) { - FoundTarget(root_view, target, event, latency, target_location, false); - return; - } - - request_in_flight_ = true; - async_depth_++; - TracingUmaTracker tracker("Event.AsyncTargeting.ResponseTime", - "input,latency"); - async_hit_test_timeout_.reset(new OneShotTimeoutMonitor( - base::BindOnce( - &RenderWidgetTargeter::AsyncHitTestTimedOut, - weak_ptr_factory_.GetWeakPtr(), root_view->GetWeakPtr(), - target->GetWeakPtr(), target_location, - last_request_target ? last_request_target->GetWeakPtr() : nullptr, - last_target_location, ui::WebInputEventTraits::Clone(event), latency), - async_hit_test_timeout_delay_)); - target_client->FrameSinkIdAt( - gfx::ToCeiledPoint(target_location), - base::BindOnce(&RenderWidgetTargeter::FoundFrameSinkId, - weak_ptr_factory_.GetWeakPtr(), root_view->GetWeakPtr(), - target->GetWeakPtr(), - ui::WebInputEventTraits::Clone(event), latency, - ++last_request_id_, target_location, std::move(tracker))); + QueryClientInternal(root_view, target, event, latency, target_location, + last_request_target, last_target_location, + viz::FrameSinkId()); } -void RenderWidgetTargeter::FlushEventQueue() { +void RenderWidgetTargeter::QueryAndVerifyClient( + RenderWidgetHostViewBase* root_view, + RenderWidgetHostViewBase* target, + const blink::WebInputEvent& event, + const ui::LatencyInfo& latency, + const gfx::PointF& target_location, + RenderWidgetHostViewBase* last_request_target, + const gfx::PointF& last_target_location, + const viz::FrameSinkId& expected_frame_sink_id) { + if (verify_request_in_flight_) { + TargetingRequest request; + request.root_view = root_view->GetWeakPtr(); + request.event = ui::WebInputEventTraits::Clone(event); + request.latency = latency; + request.expected_frame_sink_id = expected_frame_sink_id; + verify_requests_.push(std::move(request)); + return; + } + QueryClientInternal(root_view, target, event, latency, target_location, + last_request_target, last_target_location, + expected_frame_sink_id); +} + +void RenderWidgetTargeter::FlushEventQueue(bool is_verifying) { bool events_being_flushed = false; - while (!request_in_flight_ && !requests_.empty()) { - auto request = std::move(requests_.front()); - requests_.pop(); + bool& request_in_flight = + is_verifying ? verify_request_in_flight_ : request_in_flight_; + auto* requests = is_verifying ? &verify_requests_ : &requests_; + while (!request_in_flight && !requests->empty()) { + auto request = std::move(requests->front()); + requests->pop(); // The root-view has gone away. Ignore this event, and try to process the // next event. if (!request.root_view) { continue; } - request.tracker->Stop(); + if (request.tracker) + request.tracker->Stop(); // Only notify the delegate once that the current event queue is being // flushed. Once all the events are flushed, notify the delegate again. - if (!events_being_flushed) { + if (!is_verifying && !events_being_flushed) { delegate_->SetEventsBeingFlushed(true); events_being_flushed = true; } - FindTargetAndDispatch(request.root_view.get(), *request.event, - request.latency); + if (is_verifying) { + QueryAndVerifyClient(request.root_view.get(), request.root_view.get(), + *request.event, request.latency, + ComputeEventLocation(*request.event), nullptr, + gfx::PointF(), request.expected_frame_sink_id); + } else { + FindTargetAndDispatch(request.root_view.get(), *request.event, + request.latency); + } } - delegate_->SetEventsBeingFlushed(false); + if (!is_verifying) + delegate_->SetEventsBeingFlushed(false); } void RenderWidgetTargeter::FoundFrameSinkId( @@ -242,10 +317,15 @@ uint32_t request_id, const gfx::PointF& target_location, TracingUmaTracker tracker, + const viz::FrameSinkId& expected_frame_sink_id, const viz::FrameSinkId& frame_sink_id, const gfx::PointF& transformed_location) { tracker.Stop(); - if (request_id != last_request_id_ || !request_in_flight_) { + uint32_t last_id = expected_frame_sink_id.is_valid() ? last_verify_request_id_ + : last_request_id_; + bool in_flight = expected_frame_sink_id.is_valid() ? verify_request_in_flight_ + : request_in_flight_; + if (request_id != last_id || !in_flight) { // This is a response to a request that already timed out, so the event // should have already been dispatched. Mark the renderer as responsive // and otherwise ignore this response. @@ -253,8 +333,13 @@ return; } - request_in_flight_ = false; - async_hit_test_timeout_.reset(nullptr); + if (expected_frame_sink_id.is_valid()) { + verify_request_in_flight_ = false; + async_verify_hit_test_timeout_.reset(nullptr); + } else { + request_in_flight_ = false; + async_hit_test_timeout_.reset(nullptr); + } auto* view = delegate_->FindViewFromFrameSinkId(frame_sink_id); if (!view) view = target.get(); @@ -263,10 +348,12 @@ // asking the clients until a client claims an event for itself. if (view == target.get() || unresponsive_views_.find(view) != unresponsive_views_.end()) { - FoundTarget(root_view.get(), view, *event, latency, target_location, false); + FoundTarget(root_view.get(), view, *event, latency, target_location, false, + expected_frame_sink_id); } else { - QueryClient(root_view.get(), view, *event, latency, transformed_location, - target.get(), target_location); + QueryClientInternal(root_view.get(), view, *event, latency, + transformed_location, target.get(), target_location, + expected_frame_sink_id); } } @@ -276,19 +363,27 @@ const blink::WebInputEvent& event, const ui::LatencyInfo& latency, const base::Optional<gfx::PointF>& target_location, - bool latched_target) { + bool latched_target, + const viz::FrameSinkId& expected_frame_sink_id) { if (SiteIsolationPolicy::UseDedicatedProcessesForAllSites() && - !latched_target) { + !latched_target && !expected_frame_sink_id.is_valid()) { UMA_HISTOGRAM_COUNTS_100("Event.AsyncTargeting.AsyncClientDepth", async_depth_); } + if (features::IsVizHitTestingSurfaceLayerEnabled() && + expected_frame_sink_id.is_valid()) { + UMA_HISTOGRAM_BOOLEAN("Event.VizHitTestSurfaceLayer.ResultsMatch", + target->GetFrameSinkId() == expected_frame_sink_id); + FlushEventQueue(true); + return; + } // RenderWidgetHostViewMac can be deleted asynchronously, in which case the // View will be valid but there will no longer be a RenderWidgetHostImpl. if (!root_view || !root_view->GetRenderWidgetHost()) return; delegate_->DispatchEventToTarget(root_view, target, event, latency, target_location); - FlushEventQueue(); + FlushEventQueue(false); } void RenderWidgetTargeter::AsyncHitTestTimedOut( @@ -298,9 +393,17 @@ base::WeakPtr<RenderWidgetHostViewBase> last_request_target, const gfx::PointF& last_target_location, ui::WebScopedInputEvent event, - const ui::LatencyInfo& latency) { - DCHECK(request_in_flight_); - request_in_flight_ = false; + const ui::LatencyInfo& latency, + const viz::FrameSinkId& expected_frame_sink_id) { + DCHECK(request_in_flight_ || verify_request_in_flight_); + // If we time out during a verification, we early out to avoid dispatching + // event to root frame. + if (expected_frame_sink_id.is_valid()) { + verify_request_in_flight_ = false; + return; + } else { + request_in_flight_ = false; + } if (!current_request_root_view) return; @@ -315,10 +418,11 @@ // renderer fails to process it. FoundTarget(current_request_root_view.get(), current_request_root_view.get(), *event, latency, - current_target_location, false); + current_target_location, false, viz::FrameSinkId()); } else { FoundTarget(current_request_root_view.get(), last_request_target.get(), - *event, latency, last_target_location, false); + *event, latency, last_target_location, false, + viz::FrameSinkId()); } }
diff --git a/content/browser/renderer_host/render_widget_targeter.h b/content/browser/renderer_host/render_widget_targeter.h index 5e6dda1d..f5d2d1c 100644 --- a/content/browser/renderer_host/render_widget_targeter.h +++ b/content/browser/renderer_host/render_widget_targeter.h
@@ -11,6 +11,7 @@ #include "base/memory/weak_ptr.h" #include "base/optional.h" #include "base/time/time.h" +#include "components/viz/common/surfaces/frame_sink_id.h" #include "content/common/content_constants_internal.h" #include "content/common/content_export.h" #include "ui/events/blink/web_input_event_traits.h" @@ -24,22 +25,22 @@ class PointF; } -namespace viz { -class FrameSinkId; -} - namespace content { class RenderWidgetHostViewBase; class OneShotTimeoutMonitor; +// TODO(sunxd): Make |RenderWidgetTargetResult| a class. Merge the booleans into +// a mask to reduce the size. Make the constructor take in enums for better +// readability. struct CONTENT_EXPORT RenderWidgetTargetResult { RenderWidgetTargetResult(); RenderWidgetTargetResult(const RenderWidgetTargetResult&); RenderWidgetTargetResult(RenderWidgetHostViewBase* view, bool should_query_view, base::Optional<gfx::PointF> location, - bool latched_target); + bool latched_target, + bool should_verify_result); ~RenderWidgetTargetResult(); RenderWidgetHostViewBase* view = nullptr; @@ -48,6 +49,11 @@ // When |latched_target| is false, we explicitly hit-tested events instead of // using a known target. bool latched_target = false; + // When |should_verify_result| is true, RenderWidgetTargeter will do async hit + // testing and compare the target with the result of synchronous hit testing. + // |should_verify_result| will always be false if we are doing draw quad based + // hit testing. + bool should_verify_result = false; }; class TracingUmaTracker; @@ -99,7 +105,7 @@ private: // Attempts to target and dispatch all events in the queue. It stops if it has // to query a client, or if the queue becomes empty. - void FlushEventQueue(); + void FlushEventQueue(bool is_verifying); // Queries |target| to find the correct target for |event|. // |event| is in the coordinate space of |root_view|. @@ -107,6 +113,22 @@ // |last_request_target| and |last_target_location| provide a fallback target // the case that the query times out. These should be null values when // querying the root view, and the target's immediate parent view otherwise. + // |expected_frame_sink_id| is temporarily added for v2 viz hit testing. + // V2 uses cc generated hit test data and we need to verify its correctness. + // The variable is the target frame sink id v2 finds in synchronous hit + // testing. It should be the same as the async hit testing target if v2 works + // correctly. + // TODO(sunxd): Remove |expected_frame_sink_id| after verifying synchronous + // hit testing correctness. See https://crbug.com/871996. + void QueryClientInternal(RenderWidgetHostViewBase* root_view, + RenderWidgetHostViewBase* target, + const blink::WebInputEvent& event, + const ui::LatencyInfo& latency, + const gfx::PointF& target_location, + RenderWidgetHostViewBase* last_request_target, + const gfx::PointF& last_target_location, + const viz::FrameSinkId& expected_frame_sink_id); + void QueryClient(RenderWidgetHostViewBase* root_view, RenderWidgetHostViewBase* target, const blink::WebInputEvent& event, @@ -115,6 +137,15 @@ RenderWidgetHostViewBase* last_request_target, const gfx::PointF& last_target_location); + void QueryAndVerifyClient(RenderWidgetHostViewBase* root_view, + RenderWidgetHostViewBase* target, + const blink::WebInputEvent& event, + const ui::LatencyInfo& latency, + const gfx::PointF& target_location, + RenderWidgetHostViewBase* last_request_target, + const gfx::PointF& last_target_location, + const viz::FrameSinkId& expected_frame_sink_id); + // |event| is in the coordinate space of |root_view|. |target_location|, if // set, is the location in |target|'s coordinate space. // |target| is the current target that will be queried using its @@ -122,6 +153,8 @@ // |frame_sink_id| is returned from the InputTargetClient to indicate where // the event should be routed, and |transformed_location| is the point in // that new target's coordinate space. + // |expected_frame_sink_id| is the expected hit test result based on + // synchronous event targeting with cc generated data. void FoundFrameSinkId(base::WeakPtr<RenderWidgetHostViewBase> root_view, base::WeakPtr<RenderWidgetHostViewBase> target, ui::WebScopedInputEvent event, @@ -129,6 +162,7 @@ uint32_t request_id, const gfx::PointF& target_location, TracingUmaTracker tracker, + const viz::FrameSinkId& expected_frame_sink_id, const viz::FrameSinkId& frame_sink_id, const gfx::PointF& transformed_location); @@ -141,7 +175,8 @@ const blink::WebInputEvent& event, const ui::LatencyInfo& latency, const base::Optional<gfx::PointF>& target_location, - bool latched_target); + bool latched_target, + const viz::FrameSinkId& expected_frame_sink_id); // Callback when the hit testing timer fires, to resume event processing // without further waiting for a response to the last targeting request. @@ -152,7 +187,8 @@ base::WeakPtr<RenderWidgetHostViewBase> last_request_target, const gfx::PointF& last_target_location, ui::WebScopedInputEvent event, - const ui::LatencyInfo& latency); + const ui::LatencyInfo& latency, + const viz::FrameSinkId& expected_frame_sink_id); base::TimeDelta async_hit_test_timeout_delay() { return async_hit_test_timeout_delay_; @@ -167,6 +203,7 @@ base::WeakPtr<RenderWidgetHostViewBase> root_view; ui::WebScopedInputEvent event; ui::LatencyInfo latency; + viz::FrameSinkId expected_frame_sink_id; std::unique_ptr<TracingUmaTracker> tracker; }; @@ -174,6 +211,13 @@ uint32_t last_request_id_ = 0; std::queue<TargetingRequest> requests_; + // With viz-hit-testing-surface-layer being enabled, we do async hit testing + // for already dispatched events for verification. These verification requests + // should not block normal hit testing requests. + bool verify_request_in_flight_ = false; + uint32_t last_verify_request_id_ = 0; + std::queue<TargetingRequest> verify_requests_; + std::unordered_set<RenderWidgetHostViewBase*> unresponsive_views_; // This value keeps track of the number of clients we have asked in order to @@ -186,6 +230,7 @@ base::TimeDelta::FromMilliseconds(kAsyncHitTestTimeoutMs); std::unique_ptr<OneShotTimeoutMonitor> async_hit_test_timeout_; + std::unique_ptr<OneShotTimeoutMonitor> async_verify_hit_test_timeout_; Delegate* const delegate_; base::WeakPtrFactory<RenderWidgetTargeter> weak_ptr_factory_;
diff --git a/content/browser/utility_process_host.cc b/content/browser/utility_process_host.cc index 57474fa..985aac6 100644 --- a/content/browser/utility_process_host.cc +++ b/content/browser/utility_process_host.cc
@@ -294,9 +294,11 @@ #if defined(OS_MACOSX) service_manager::switches::kEnableSandboxLogging, #endif + switches::kEnableLogging, switches::kForceTextDirection, switches::kForceUIDirection, switches::kIgnoreCertificateErrors, + switches::kLoggingLevel, switches::kOverrideUseSoftwareGLForTests, switches::kOverrideEnabledCdmInterfaceVersion, switches::kProxyServer, @@ -307,6 +309,8 @@ switches::kUseMockCertVerifierForTesting, switches::kUtilityStartupDialog, switches::kUseGL, + switches::kV, + switches::kVModule, #if defined(OS_ANDROID) switches::kOrderfileMemoryOptimization, #endif
diff --git a/content/public/android/java/src/org/chromium/content/browser/selection/SmartSelectionProvider.java b/content/public/android/java/src/org/chromium/content/browser/selection/SmartSelectionProvider.java index f1656c4..2760dd1 100644 --- a/content/public/android/java/src/org/chromium/content/browser/selection/SmartSelectionProvider.java +++ b/content/public/android/java/src/org/chromium/content/browser/selection/SmartSelectionProvider.java
@@ -16,7 +16,7 @@ import android.view.textclassifier.TextClassifier; import android.view.textclassifier.TextSelection; -import org.chromium.base.AsyncTask; +import org.chromium.base.task.AsyncTask; import org.chromium.content_public.browser.SelectionClient; import org.chromium.ui.base.WindowAndroid;
diff --git a/content/public/browser/BUILD.gn b/content/public/browser/BUILD.gn index c9c7512..93bf086 100644 --- a/content/public/browser/BUILD.gn +++ b/content/public/browser/BUILD.gn
@@ -202,6 +202,7 @@ "notification_service.h", "notification_source.h", "notification_types.h", + "origin_policy_error_reason.h", "overlay_window.h", "overscroll_configuration.h", "page_navigator.cc",
diff --git a/content/public/browser/content_browser_client.cc b/content/public/browser/content_browser_client.cc index cbd9987..76796f9 100644 --- a/content/public/browser/content_browser_client.cc +++ b/content/public/browser/content_browser_client.cc
@@ -806,4 +806,11 @@ BrowserContext* browser_context, mojom::RendererPreferenceWatcherPtr watcher) {} +base::Optional<std::string> ContentBrowserClient::GetOriginPolicyErrorPage( + OriginPolicyErrorReason error_reason, + const url::Origin& origin, + const GURL& url) { + return base::nullopt; +} + } // namespace content
diff --git a/content/public/browser/content_browser_client.h b/content/public/browser/content_browser_client.h index 32fb2b5..59cfc78 100644 --- a/content/public/browser/content_browser_client.h +++ b/content/public/browser/content_browser_client.h
@@ -179,6 +179,7 @@ class VpnServiceProxy; class WebContents; class WebContentsViewDelegate; +enum class OriginPolicyErrorReason; struct MainFunctionParams; struct OpenURLParams; struct Referrer; @@ -1330,6 +1331,13 @@ virtual void RegisterRendererPreferenceWatcherForWorkers( BrowserContext* browser_context, mojom::RendererPreferenceWatcherPtr watcher); + + // Returns the HTML content of the error page for Origin Policy related + // errors. + virtual base::Optional<std::string> GetOriginPolicyErrorPage( + OriginPolicyErrorReason error_reason, + const url::Origin& origin, + const GURL& url); }; } // namespace content
diff --git a/content/public/browser/origin_policy_error_reason.h b/content/public/browser/origin_policy_error_reason.h new file mode 100644 index 0000000..50787a12 --- /dev/null +++ b/content/public/browser/origin_policy_error_reason.h
@@ -0,0 +1,19 @@ +// Copyright (c) 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_PUBLIC_BROWSER_ORIGIN_POLICY_ERROR_REASON_H_ +#define CONTENT_PUBLIC_BROWSER_ORIGIN_POLICY_ERROR_REASON_H_ + +namespace content { + +// Enumerate the reasons why an origin policy was rejected. +enum class OriginPolicyErrorReason : int { + kCannotLoadPolicy, // The policy document could not be downloaded. + kPolicyShouldNotRedirect, // The policy doc request was met with a redirect. + kOther, +}; + +} // namespace content + +#endif // CONTENT_PUBLIC_BROWSER_ORIGIN_POLICY_ERROR_REASON_H_
diff --git a/content/public/common/web_preferences.cc b/content/public/common/web_preferences.cc index 73b159e41..581c666 100644 --- a/content/public/common/web_preferences.cc +++ b/content/public/common/web_preferences.cc
@@ -187,12 +187,15 @@ user_gesture_required_for_presentation(true), text_track_margin_percentage(0.0f), immersive_mode_enabled(false), +#if defined(OS_ANDROID) || defined(OS_MACOSX) + double_tap_to_zoom_enabled(true), +#else + double_tap_to_zoom_enabled(false), +#endif #if !defined(OS_ANDROID) text_autosizing_enabled(false), - double_tap_to_zoom_enabled(false), #else text_autosizing_enabled(true), - double_tap_to_zoom_enabled(true), font_scale_factor(1.0f), device_scale_adjustment(1.0f), force_enable_zoom(false),
diff --git a/content/public/common/web_preferences.h b/content/public/common/web_preferences.h index 38d1c85..c1881cb0 100644 --- a/content/public/common/web_preferences.h +++ b/content/public/common/web_preferences.h
@@ -229,10 +229,10 @@ bool immersive_mode_enabled; - bool text_autosizing_enabled; - bool double_tap_to_zoom_enabled; + bool text_autosizing_enabled; + #if defined(OS_ANDROID) float font_scale_factor; float device_scale_adjustment;
diff --git a/content/renderer/media/stream/media_stream_constraints_util.cc b/content/renderer/media/stream/media_stream_constraints_util.cc index d4111ac35..5708fae 100644 --- a/content/renderer/media/stream/media_stream_constraints_util.cc +++ b/content/renderer/media/stream/media_stream_constraints_util.cc
@@ -152,14 +152,12 @@ AudioCaptureSettings::AudioCaptureSettings( std::string device_id, - const media::AudioParameters& audio_parameters, bool enable_hotword, bool disable_local_echo, bool enable_automatic_output_device_selection, const AudioProcessingProperties& audio_processing_properties) : failed_constraint_name_(nullptr), device_id_(std::move(device_id)), - audio_parameters_(audio_parameters), hotword_enabled_(enable_hotword), disable_local_echo_(disable_local_echo), render_to_associated_sink_(enable_automatic_output_device_selection),
diff --git a/content/renderer/media/stream/media_stream_constraints_util.h b/content/renderer/media/stream/media_stream_constraints_util.h index 1e73420..4bcbf10 100644 --- a/content/renderer/media/stream/media_stream_constraints_util.h +++ b/content/renderer/media/stream/media_stream_constraints_util.h
@@ -182,7 +182,6 @@ // Creates an object with the given values. explicit AudioCaptureSettings( std::string device_id, - const media::AudioParameters& audio_parameters, bool enable_hotword, bool disable_local_echo, bool enable_automatic_output_device_selection, @@ -200,11 +199,6 @@ DCHECK(HasValue()); return device_id_; } - // This field is meaningless in content capture. - const media::AudioParameters& device_parameters() const { - DCHECK(HasValue()); - return audio_parameters_; - } bool hotword_enabled() const { DCHECK(HasValue()); return hotword_enabled_; @@ -225,7 +219,6 @@ private: const char* failed_constraint_name_; std::string device_id_; - media::AudioParameters audio_parameters_; bool hotword_enabled_; bool disable_local_echo_; bool render_to_associated_sink_;
diff --git a/content/renderer/media/stream/media_stream_constraints_util_audio.cc b/content/renderer/media/stream/media_stream_constraints_util_audio.cc index ac494175f..735fda48 100644 --- a/content/renderer/media/stream/media_stream_constraints_util_audio.cc +++ b/content/renderer/media/stream/media_stream_constraints_util_audio.cc
@@ -400,9 +400,9 @@ basic_constraint_set, is_device_capture, should_disable_hardware_noise_suppression); - return AudioCaptureSettings( - std::move(device_id), parameters_, hotword_enabled, disable_local_echo, - render_to_associated_sink, audio_processing_properties); + return AudioCaptureSettings(std::move(device_id), hotword_enabled, + disable_local_echo, render_to_associated_sink, + audio_processing_properties); } private:
diff --git a/content/renderer/media/stream/media_stream_constraints_util_audio_unittest.cc b/content/renderer/media/stream/media_stream_constraints_util_audio_unittest.cc index bce1de0..8757ba3 100644 --- a/content/renderer/media/stream/media_stream_constraints_util_audio_unittest.cc +++ b/content/renderer/media/stream/media_stream_constraints_util_audio_unittest.cc
@@ -343,12 +343,6 @@ void CheckDevice(const AudioDeviceCaptureCapability& expected_device, const AudioCaptureSettings& result) { EXPECT_EQ(expected_device.DeviceID(), result.device_id()); - EXPECT_EQ(expected_device.Parameters().sample_rate(), - result.device_parameters().sample_rate()); - EXPECT_EQ(expected_device.Parameters().channels(), - result.device_parameters().channels()); - EXPECT_EQ(expected_device.Parameters().effects(), - result.device_parameters().effects()); } void CheckDeviceDefaults(const AudioCaptureSettings& result) {
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index 0da183c8..7036d48 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -1009,7 +1009,6 @@ } #if defined(OS_MACOSX) - settings->SetDoubleTapToZoomEnabled(true); web_view->SetMaximumLegibleScale(prefs.default_maximum_page_scale_factor); #endif
diff --git a/content/test/data/accessibility/event/aria-combo-box-focus.html b/content/test/data/accessibility/event/aria-combo-box-focus.html index 58eb56a..7f95c02 100644 --- a/content/test/data/accessibility/event/aria-combo-box-focus.html +++ b/content/test/data/accessibility/event/aria-combo-box-focus.html
@@ -1,6 +1,7 @@ <!-- This line is to unflake the test, but may not be necessary (crbug.com/c/791268): @WIN-DENY:EVENT_OBJECT_LOCATIONCHANGE* +@WIN-DENY:EVENT_OBJECT_SHOW* --> <!DOCTYPE html> <html>
diff --git a/content/test/data/accessibility/event/caret-move-expected-win.txt b/content/test/data/accessibility/event/caret-move-expected-win.txt new file mode 100644 index 0000000..ce8ad57 --- /dev/null +++ b/content/test/data/accessibility/event/caret-move-expected-win.txt
@@ -0,0 +1,8 @@ +EVENT_OBJECT_FOCUS on <input#in1> role=ROLE_SYSTEM_TEXT value="abcde" FOCUSED,FOCUSABLE IA2_STATE_EDITABLE,IA2_STATE_SELECTABLE_TEXT,IA2_STATE_SINGLE_LINE +EVENT_OBJECT_HIDE role=ROLE_SYSTEM_CARET INVISIBLE window_class=Chrome_WidgetWin_0 +EVENT_OBJECT_LOCATIONCHANGE role=ROLE_SYSTEM_CARET window_class=Chrome_WidgetWin_0 +EVENT_OBJECT_LOCATIONCHANGE role=ROLE_SYSTEM_CARET window_class=Chrome_WidgetWin_0 +EVENT_OBJECT_SHOW role=ROLE_SYSTEM_CARET window_class=Chrome_WidgetWin_0 +EVENT_OBJECT_VALUECHANGE on <input#in1> role=ROLE_SYSTEM_TEXT value="end" FOCUSABLE IA2_STATE_EDITABLE,IA2_STATE_SELECTABLE_TEXT,IA2_STATE_SINGLE_LINE +IA2_EVENT_TEXT_CARET_MOVED on <input#in1> role=ROLE_SYSTEM_TEXT value="abcde" FOCUSED,FOCUSABLE IA2_STATE_EDITABLE,IA2_STATE_SELECTABLE_TEXT,IA2_STATE_SINGLE_LINE +IA2_EVENT_TEXT_CARET_MOVED on <input#in1> role=ROLE_SYSTEM_TEXT value="abcde" FOCUSED,FOCUSABLE IA2_STATE_EDITABLE,IA2_STATE_SELECTABLE_TEXT,IA2_STATE_SINGLE_LINE
diff --git a/content/test/data/accessibility/event/caret-move.html b/content/test/data/accessibility/event/caret-move.html new file mode 100644 index 0000000..a4b641b --- /dev/null +++ b/content/test/data/accessibility/event/caret-move.html
@@ -0,0 +1,25 @@ +<!-- +@RUN-UNTIL-EVENT:EVENT_OBJECT_VALUECHANGE +@WIN-DENY:IA2_EVENT_TEXT_INSERTED* +@WIN-DENY:IA2_EVENT_TEXT_REMOVED* +--> +<!DOCTYPE html> +<html> +<body> +<input id="in1" type="text" value="abcde"> +<script> + function go() { + const inp = document.getElementById('in1'); + inp.focus(); + inp.setSelectionRange(0, 0); + setTimeout(() => { + inp.setSelectionRange(1, 1); + setTimeout(() => { + inp.blur(); + inp.value = 'end'; // Trigger test end. + }, 50); + }, 50); +} +</script> +</body> +</html> \ No newline at end of file
diff --git a/content/test/data/accessibility/html/input-checkbox-label-expected-blink.txt b/content/test/data/accessibility/html/input-checkbox-label-expected-blink.txt index 47548f89..75e73837 100644 --- a/content/test/data/accessibility/html/input-checkbox-label-expected-blink.txt +++ b/content/test/data/accessibility/html/input-checkbox-label-expected-blink.txt
@@ -1,4 +1,4 @@ rootWebArea ++genericContainer ++++labelText -++++++checkBox name=' Checkbox Title' checkedState=false \ No newline at end of file +++++++checkBox name='Checkbox Title' checkedState=false
diff --git a/content/test/data/accessibility/html/input-checkbox-label-expected-mac.txt b/content/test/data/accessibility/html/input-checkbox-label-expected-mac.txt index cca501c..293d884 100644 --- a/content/test/data/accessibility/html/input-checkbox-label-expected-mac.txt +++ b/content/test/data/accessibility/html/input-checkbox-label-expected-mac.txt
@@ -1,4 +1,4 @@ AXWebArea ++AXGroup ++++AXGroup -++++++AXCheckBox AXTitle=' Checkbox Title' AXValue='0' +++++++AXCheckBox AXTitle='Checkbox Title' AXValue='0'
diff --git a/content/test/data/accessibility/html/input-list-expected-auralinux.txt b/content/test/data/accessibility/html/input-list-expected-auralinux.txt index b326e16..2d07280 100644 --- a/content/test/data/accessibility/html/input-list-expected-auralinux.txt +++ b/content/test/data/accessibility/html/input-list-expected-auralinux.txt
@@ -2,4 +2,4 @@ ++[section] ++++[label] ++++++[text] name='Choose a pokemon ' -++++++[combo box] name='Choose a pokemon ' editable focusable selectable-text autocomplete:list haspopup:listbox +++++++[combo box] name='Choose a pokemon' editable focusable selectable-text autocomplete:list haspopup:listbox
diff --git a/content/test/data/accessibility/html/input-list-expected-blink.txt b/content/test/data/accessibility/html/input-list-expected-blink.txt index c983163a..a2dcb7b 100644 --- a/content/test/data/accessibility/html/input-list-expected-blink.txt +++ b/content/test/data/accessibility/html/input-list-expected-blink.txt
@@ -3,4 +3,4 @@ ++++labelText ++++++staticText name='Choose a pokemon ' ++++++++inlineTextBox name='Choose a pokemon ' -++++++textFieldWithComboBox editable focusable autoComplete='list' name='Choose a pokemon ' haspopup=listbox +++++++textFieldWithComboBox editable focusable autoComplete='list' name='Choose a pokemon' haspopup=listbox
diff --git a/content/test/data/accessibility/html/input-list-expected-mac.txt b/content/test/data/accessibility/html/input-list-expected-mac.txt index f5478ba..4c02e92 100644 --- a/content/test/data/accessibility/html/input-list-expected-mac.txt +++ b/content/test/data/accessibility/html/input-list-expected-mac.txt
@@ -2,4 +2,4 @@ ++AXGroup ++++AXGroup ++++++AXStaticText AXValue='Choose a pokemon ' -++++++AXComboBox AXTitle='Choose a pokemon ' AXAutocompleteValue='list' +++++++AXComboBox AXTitle='Choose a pokemon' AXAutocompleteValue='list'
diff --git a/content/test/data/accessibility/html/input-list-expected-win.txt b/content/test/data/accessibility/html/input-list-expected-win.txt index 0ba24987..a8575ff 100644 --- a/content/test/data/accessibility/html/input-list-expected-win.txt +++ b/content/test/data/accessibility/html/input-list-expected-win.txt
@@ -2,4 +2,4 @@ ++IA2_ROLE_SECTION ++++IA2_ROLE_LABEL ++++++ROLE_SYSTEM_STATICTEXT name='Choose a pokemon ' -++++++ROLE_SYSTEM_COMBOBOX name='Choose a pokemon ' FOCUSABLE HASPOPUP autocomplete:list haspopup:listbox +++++++ROLE_SYSTEM_COMBOBOX name='Choose a pokemon' FOCUSABLE HASPOPUP autocomplete:list haspopup:listbox
diff --git a/content/test/data/accessibility/html/input-types-expected-android.txt b/content/test/data/accessibility/html/input-types-expected-android.txt index 92a7d1e..b3263bad9 100644 --- a/content/test/data/accessibility/html/input-types-expected-android.txt +++ b/content/test/data/accessibility/html/input-types-expected-android.txt
@@ -2,48 +2,48 @@ ++android.view.View ++++android.view.View ++++++android.view.View name='Default: ' -++++++android.widget.EditText clickable editable_text focusable hint='Default: ' input_type=1 +++++++android.widget.EditText clickable editable_text focusable hint='Default:' input_type=1 ++++android.view.View ++++++android.view.View name='Button: ' -++++++android.widget.Button role_description='button' clickable focusable name='Button: ' -++++android.widget.CheckBox role_description='checkbox' checkable clickable focusable name='Checkbox: ' +++++++android.widget.Button role_description='button' clickable focusable name='Button:' +++++android.widget.CheckBox role_description='checkbox' checkable clickable focusable name='Checkbox:' ++++android.view.View ++++++android.view.View name='Color: ' ++++++android.widget.Spinner role_description='color picker' clickable focusable name='#000000' ++++android.view.View ++++++android.view.View name='Email: ' -++++++android.widget.EditText clickable editable_text focusable hint='Email: ' input_type=209 +++++++android.widget.EditText clickable editable_text focusable hint='Email:' input_type=209 ++++android.view.View ++++++android.view.View name='File: ' -++++++android.widget.Button role_description='button' clickable focusable name='File: ' +++++++android.widget.Button role_description='button' clickable focusable name='File:' ++++android.view.View ++++++android.view.View name='Image: ' -++++++android.widget.Button role_description='button' clickable focusable name='Image: ' +++++++android.widget.Button role_description='button' clickable focusable name='Image:' ++++android.view.View ++++++android.view.View name='Number: ' -++++++android.widget.EditText role_description='spin button' clickable editable_text focusable hint='Number: ' input_type=2 +++++++android.widget.EditText role_description='spin button' clickable editable_text focusable hint='Number:' input_type=2 ++++android.view.View ++++++android.view.View name='Password: ' -++++++android.widget.EditText clickable editable_text focusable password hint='Password: ' input_type=225 -++++android.widget.RadioButton role_description='radio button' checkable clickable focusable name='Radio: ' +++++++android.widget.EditText clickable editable_text focusable password hint='Password:' input_type=225 +++++android.widget.RadioButton role_description='radio button' checkable clickable focusable name='Radio:' ++++android.view.View ++++++android.view.View name='Range: ' -++++++android.widget.SeekBar role_description='slider' clickable focusable range name='Range: ' item_index=50 item_count=100 range_max=100 range_current_value=50 +++++++android.widget.SeekBar role_description='slider' clickable focusable range name='Range:' item_index=50 item_count=100 range_max=100 range_current_value=50 ++++android.view.View ++++++android.view.View name='Reset: ' -++++++android.widget.Button role_description='button' clickable focusable name='Reset: ' +++++++android.widget.Button role_description='button' clickable focusable name='Reset:' ++++android.view.View ++++++android.view.View name='Search: ' -++++++android.widget.EditText clickable editable_text focusable hint='Search: ' input_type=1 +++++++android.widget.EditText clickable editable_text focusable hint='Search:' input_type=1 ++++android.view.View ++++++android.view.View name='Submit: ' -++++++android.widget.Button role_description='button' clickable focusable name='Submit: ' +++++++android.widget.Button role_description='button' clickable focusable name='Submit:' ++++android.view.View ++++++android.view.View name='Tel: ' -++++++android.widget.EditText clickable editable_text focusable hint='Tel: ' input_type=3 +++++++android.widget.EditText clickable editable_text focusable hint='Tel:' input_type=3 ++++android.view.View ++++++android.view.View name='Text: ' -++++++android.widget.EditText clickable editable_text focusable hint='Text: ' input_type=1 +++++++android.widget.EditText clickable editable_text focusable hint='Text:' input_type=1 ++++android.view.View ++++++android.view.View name='Url: ' -++++++android.widget.EditText clickable editable_text focusable hint='Url: ' input_type=17 \ No newline at end of file +++++++android.widget.EditText clickable editable_text focusable hint='Url:' input_type=17
diff --git a/content/test/data/accessibility/html/input-types-expected-auralinux.txt b/content/test/data/accessibility/html/input-types-expected-auralinux.txt index d67ced67..8772799 100644 --- a/content/test/data/accessibility/html/input-types-expected-auralinux.txt +++ b/content/test/data/accessibility/html/input-types-expected-auralinux.txt
@@ -2,48 +2,48 @@ ++[section] ++++[label] ++++++[text] name='Default: ' -++++++[entry] name='Default: ' selectable-text +++++++[entry] name='Default:' selectable-text ++++[label] ++++++[text] name='Button: ' -++++++[push button] name='Button: ' -++++[check box] name='Checkbox: ' checkable:true +++++++[push button] name='Button:' +++++[check box] name='Checkbox:' checkable:true ++++[label] ++++++[text] name='Color: ' -++++++[push button] name='Color: ' +++++++[push button] name='Color:' ++++[label] ++++++[text] name='Email: ' -++++++[entry] name='Email: ' selectable-text text-input-type:email +++++++[entry] name='Email:' selectable-text text-input-type:email ++++[label] ++++++[text] name='File: ' -++++++[push button] name='File: ' +++++++[push button] name='File:' ++++[label] ++++++[text] name='Image: ' -++++++[push button] name='Image: ' +++++++[push button] name='Image:' ++++[label] ++++++[text] name='Number: ' -++++++[spin button] name='Number: ' selectable-text text-input-type:number +++++++[spin button] name='Number:' selectable-text text-input-type:number ++++[label] ++++++[text] name='Password: ' -++++++[password text] name='Password: ' selectable-text text-input-type:password -++++[radio button] name='Radio: ' checkable:true +++++++[password text] name='Password:' selectable-text text-input-type:password +++++[radio button] name='Radio:' checkable:true ++++[label] ++++++[text] name='Range: ' -++++++[slider] name='Range: ' horizontal +++++++[slider] name='Range:' horizontal ++++[label] ++++++[text] name='Reset: ' -++++++[push button] name='Reset: ' +++++++[push button] name='Reset:' ++++[label] ++++++[text] name='Search: ' -++++++[entry] name='Search: ' selectable-text text-input-type:search +++++++[entry] name='Search:' selectable-text text-input-type:search ++++[label] ++++++[text] name='Submit: ' -++++++[push button] name='Submit: ' +++++++[push button] name='Submit:' ++++[label] ++++++[text] name='Tel: ' -++++++[entry] name='Tel: ' selectable-text text-input-type:tel +++++++[entry] name='Tel:' selectable-text text-input-type:tel ++++[label] ++++++[text] name='Text: ' -++++++[entry] name='Text: ' selectable-text text-input-type:text +++++++[entry] name='Text:' selectable-text text-input-type:text ++++[label] ++++++[text] name='Url: ' -++++++[entry] name='Url: ' selectable-text text-input-type:url +++++++[entry] name='Url:' selectable-text text-input-type:url
diff --git a/content/test/data/accessibility/html/input-types-expected-mac.txt b/content/test/data/accessibility/html/input-types-expected-mac.txt index 5f39d2f..bc21408 100644 --- a/content/test/data/accessibility/html/input-types-expected-mac.txt +++ b/content/test/data/accessibility/html/input-types-expected-mac.txt
@@ -2,48 +2,48 @@ ++AXGroup ++++AXGroup ++++++AXStaticText AXValue='Default: ' -++++++AXTextField AXTitle='Default: ' +++++++AXTextField AXTitle='Default:' ++++AXGroup ++++++AXStaticText AXValue='Button: ' -++++++AXButton AXTitle='Button: ' -++++AXCheckBox AXTitle='Checkbox: ' AXValue='0' +++++++AXButton AXTitle='Button:' +++++AXCheckBox AXTitle='Checkbox:' AXValue='0' ++++AXGroup ++++++AXStaticText AXValue='Color: ' -++++++AXColorWell AXTitle='Color: ' AXValue='rgb 0.00000 0.00000 0.00000 1' +++++++AXColorWell AXTitle='Color:' AXValue='rgb 0.00000 0.00000 0.00000 1' ++++AXGroup ++++++AXStaticText AXValue='Email: ' -++++++AXTextField AXTitle='Email: ' +++++++AXTextField AXTitle='Email:' ++++AXGroup ++++++AXStaticText AXValue='File: ' -++++++AXButton AXTitle='File: ' +++++++AXButton AXTitle='File:' ++++AXGroup ++++++AXStaticText AXValue='Image: ' -++++++AXButton AXTitle='Image: ' +++++++AXButton AXTitle='Image:' ++++AXGroup ++++++AXStaticText AXValue='Number: ' -++++++AXIncrementor AXTitle='Number: ' +++++++AXIncrementor AXTitle='Number:' ++++AXGroup ++++++AXStaticText AXValue='Password: ' -++++++AXTextField AXTitle='Password: ' -++++AXRadioButton AXTitle='Radio: ' AXValue='0' +++++++AXTextField AXTitle='Password:' +++++AXRadioButton AXTitle='Radio:' AXValue='0' ++++AXGroup ++++++AXStaticText AXValue='Range: ' -++++++AXSlider AXTitle='Range: ' AXValue='50' +++++++AXSlider AXTitle='Range:' AXValue='50' ++++AXGroup ++++++AXStaticText AXValue='Reset: ' -++++++AXButton AXTitle='Reset: ' +++++++AXButton AXTitle='Reset:' ++++AXGroup ++++++AXStaticText AXValue='Search: ' -++++++AXTextField AXTitle='Search: ' +++++++AXTextField AXTitle='Search:' ++++AXGroup ++++++AXStaticText AXValue='Submit: ' -++++++AXButton AXTitle='Submit: ' +++++++AXButton AXTitle='Submit:' ++++AXGroup ++++++AXStaticText AXValue='Tel: ' -++++++AXTextField AXTitle='Tel: ' +++++++AXTextField AXTitle='Tel:' ++++AXGroup ++++++AXStaticText AXValue='Text: ' -++++++AXTextField AXTitle='Text: ' +++++++AXTextField AXTitle='Text:' ++++AXGroup ++++++AXStaticText AXValue='Url: ' -++++++AXTextField AXTitle='Url: ' \ No newline at end of file +++++++AXTextField AXTitle='Url:'
diff --git a/content/test/data/accessibility/html/input-types-expected-win.txt b/content/test/data/accessibility/html/input-types-expected-win.txt index 016be4e..5fa646d 100644 --- a/content/test/data/accessibility/html/input-types-expected-win.txt +++ b/content/test/data/accessibility/html/input-types-expected-win.txt
@@ -2,48 +2,48 @@ ++IA2_ROLE_SECTION ++++IA2_ROLE_LABEL ++++++ROLE_SYSTEM_STATICTEXT name='Default: ' -++++++ROLE_SYSTEM_TEXT name='Default: ' FOCUSABLE +++++++ROLE_SYSTEM_TEXT name='Default:' FOCUSABLE ++++IA2_ROLE_LABEL ++++++ROLE_SYSTEM_STATICTEXT name='Button: ' -++++++ROLE_SYSTEM_PUSHBUTTON name='Button: ' FOCUSABLE -++++ROLE_SYSTEM_CHECKBUTTON name='Checkbox: ' FOCUSABLE IA2_STATE_CHECKABLE checkable:true +++++++ROLE_SYSTEM_PUSHBUTTON name='Button:' FOCUSABLE +++++ROLE_SYSTEM_CHECKBUTTON name='Checkbox:' FOCUSABLE IA2_STATE_CHECKABLE checkable:true ++++IA2_ROLE_LABEL ++++++ROLE_SYSTEM_STATICTEXT name='Color: ' -++++++IA2_ROLE_COLOR_CHOOSER name='Color: ' value='0% red 0% green 0% blue' FOCUSABLE +++++++IA2_ROLE_COLOR_CHOOSER name='Color:' value='0% red 0% green 0% blue' FOCUSABLE ++++IA2_ROLE_LABEL ++++++ROLE_SYSTEM_STATICTEXT name='Email: ' -++++++ROLE_SYSTEM_TEXT name='Email: ' FOCUSABLE text-input-type:email +++++++ROLE_SYSTEM_TEXT name='Email:' FOCUSABLE text-input-type:email ++++IA2_ROLE_LABEL ++++++ROLE_SYSTEM_STATICTEXT name='File: ' -++++++ROLE_SYSTEM_PUSHBUTTON name='File: ' value='No file chosen' FOCUSABLE +++++++ROLE_SYSTEM_PUSHBUTTON name='File:' value='No file chosen' FOCUSABLE ++++IA2_ROLE_LABEL ++++++ROLE_SYSTEM_STATICTEXT name='Image: ' -++++++ROLE_SYSTEM_PUSHBUTTON name='Image: ' FOCUSABLE +++++++ROLE_SYSTEM_PUSHBUTTON name='Image:' FOCUSABLE ++++IA2_ROLE_LABEL ++++++ROLE_SYSTEM_STATICTEXT name='Number: ' -++++++ROLE_SYSTEM_SPINBUTTON name='Number: ' FOCUSABLE text-input-type:number +++++++ROLE_SYSTEM_SPINBUTTON name='Number:' FOCUSABLE text-input-type:number ++++IA2_ROLE_LABEL ++++++ROLE_SYSTEM_STATICTEXT name='Password: ' -++++++ROLE_SYSTEM_TEXT name='Password: ' FOCUSABLE PROTECTED text-input-type:password -++++ROLE_SYSTEM_RADIOBUTTON name='Radio: ' FOCUSABLE IA2_STATE_CHECKABLE checkable:true +++++++ROLE_SYSTEM_TEXT name='Password:' FOCUSABLE PROTECTED text-input-type:password +++++ROLE_SYSTEM_RADIOBUTTON name='Radio:' FOCUSABLE IA2_STATE_CHECKABLE checkable:true ++++IA2_ROLE_LABEL ++++++ROLE_SYSTEM_STATICTEXT name='Range: ' -++++++ROLE_SYSTEM_SLIDER name='Range: ' value='50' FOCUSABLE IA2_STATE_HORIZONTAL +++++++ROLE_SYSTEM_SLIDER name='Range:' value='50' FOCUSABLE IA2_STATE_HORIZONTAL ++++IA2_ROLE_LABEL ++++++ROLE_SYSTEM_STATICTEXT name='Reset: ' -++++++ROLE_SYSTEM_PUSHBUTTON name='Reset: ' FOCUSABLE +++++++ROLE_SYSTEM_PUSHBUTTON name='Reset:' FOCUSABLE ++++IA2_ROLE_LABEL ++++++ROLE_SYSTEM_STATICTEXT name='Search: ' -++++++ROLE_SYSTEM_TEXT name='Search: ' FOCUSABLE text-input-type:search +++++++ROLE_SYSTEM_TEXT name='Search:' FOCUSABLE text-input-type:search ++++IA2_ROLE_LABEL ++++++ROLE_SYSTEM_STATICTEXT name='Submit: ' -++++++ROLE_SYSTEM_PUSHBUTTON name='Submit: ' FOCUSABLE +++++++ROLE_SYSTEM_PUSHBUTTON name='Submit:' FOCUSABLE ++++IA2_ROLE_LABEL ++++++ROLE_SYSTEM_STATICTEXT name='Tel: ' -++++++ROLE_SYSTEM_TEXT name='Tel: ' FOCUSABLE text-input-type:tel +++++++ROLE_SYSTEM_TEXT name='Tel:' FOCUSABLE text-input-type:tel ++++IA2_ROLE_LABEL ++++++ROLE_SYSTEM_STATICTEXT name='Text: ' -++++++ROLE_SYSTEM_TEXT name='Text: ' FOCUSABLE text-input-type:text +++++++ROLE_SYSTEM_TEXT name='Text:' FOCUSABLE text-input-type:text ++++IA2_ROLE_LABEL ++++++ROLE_SYSTEM_STATICTEXT name='Url: ' -++++++ROLE_SYSTEM_TEXT name='Url: ' FOCUSABLE text-input-type:url +++++++ROLE_SYSTEM_TEXT name='Url:' FOCUSABLE text-input-type:url
diff --git a/content/test/data/accessibility/readme.md b/content/test/data/accessibility/readme.md index 893dc47..05e1f46 100644 --- a/content/test/data/accessibility/readme.md +++ b/content/test/data/accessibility/readme.md
@@ -85,8 +85,8 @@ Normally the system waits for the document to finish loading before dumping the accessibility tree. -Occasionally you may need to write a test that makes some changes to the -document before it runs the test. In that case you can use a special +Occasionally you may need to write a dump tree test that makes some changes to +the document before it runs the test. In that case you can use a special @WAIT-FOR: directive. It should be in an HTML comment, just like @ALLOW-WIN: directives. The WAIT-FOR directive just specifies a text substring that should be present in the dump when the document is ready. The system @@ -95,6 +95,16 @@ You can add as many @WAIT-FOR: directives as you want, the test won't finish until all strings appear. +Or, you may need to write an event test that keeps dumping events until a +specific event line. In this case, use @RUN-UNTIL-EVENT with a substring that +should occur in the event log, e.g. @RUN-UNTIL-EVENT:IA2_EVENT_TEXT_CARET_MOVED. +Note that @RUN-UNTIL-EVENT is only used in dump events tests, and not used in +dump tree tests. + +If you add multiple @RUN-UNTIL-EVENT directives, the test will finish once any +of them are satisfied. Note that any other events that come along with the last +event will also be logged. + To skip dumping a particular element, make its accessible name equal to @NO_DUMP, for example <div aria-label="@NO_DUMP"></div>.
diff --git a/content/test/gpu/gpu_tests/color_profile_manager_mac.py b/content/test/gpu/gpu_tests/color_profile_manager_mac.py index a3719c7..40c70ec 100644 --- a/content/test/gpu/gpu_tests/color_profile_manager_mac.py +++ b/content/test/gpu/gpu_tests/color_profile_manager_mac.py
@@ -80,6 +80,8 @@ device_info = ColorSyncDeviceCopyDeviceInfo( kColorSyncDisplayDeviceClass, CGDisplayCreateUUIDFromDisplayID(display_id)) + if not device_info: + raise Exception('KVM connection on bot is broken, please file a bug') device_id = device_info['DeviceID'] custom_profile_url = None if 'CustomProfiles' in device_info and '1' in device_info['CustomProfiles']:
diff --git a/docs/android_test_instructions.md b/docs/android_test_instructions.md index 6fc4649..25c447add 100644 --- a/docs/android_test_instructions.md +++ b/docs/android_test_instructions.md
@@ -158,9 +158,7 @@ When adding a new JUnit test, the associated `BUILD.gn` file must be updated. For example, adding a test to `chrome_junit_tests` requires to update -`chrome/android/BUILD.gn`. If you are a GYP user, you will not need to do that -step in order to run the test locally but it is still required for GN users to -run the test. +`chrome/android/BUILD.gn`. ```shell # Build the test suite.
diff --git a/docs/angle_in_chromium.md b/docs/angle_in_chromium.md index eacc6f4..282a2cf 100644 --- a/docs/angle_in_chromium.md +++ b/docs/angle_in_chromium.md
@@ -23,8 +23,7 @@ > gclient runhooks ``` -To check ANGLE builds (assumes you ran hooks with GYP\_GENERATORS=ninja) without -building all of Chromium. +To check ANGLE builds without building all of Chromium. ```shell ninja -C out\Release libEGL.dll
diff --git a/docs/ccache_mac.md b/docs/ccache_mac.md index 7eed51a6..4b3eacd 100644 --- a/docs/ccache_mac.md +++ b/docs/ccache_mac.md
@@ -36,8 +36,8 @@ Make sure ccache can be found in your `$PATH`. You can also just use the current released version of ccache (3.1.8 or 3.1.9) -and disable the chromium style plugin with `clang_use_chrome_plugins=0` in your -`GYP_DEFINES`. +and disable the chromium style plugin with `clang_use_chrome_plugins = false` +in your args.gn. ## Use with GN
diff --git a/docs/eclipse.md b/docs/eclipse.md index af35097..d71522c 100644 --- a/docs/eclipse.md +++ b/docs/eclipse.md
@@ -59,13 +59,6 @@ * Disable build before launching * Select Run/Debug > Launching * Uncheck Build (if required) before launching - * File types for .gyp and .gypi - * Go to General > Editors > File Associations - * Add `*.gyp` and `*.gypi` file types, and associate them with Python Editor - * See http://pydev.org/index.html for instructions on getting a Python - Editor configured in Eclipse - * Enjoy a happy life with Ctrl+Shift+P and automatic matching bracket - highlight. * Tab ordering * If you prefer ordering your tabs by most recently used, go to General > Appearance and check Show most recently used tabs @@ -122,17 +115,6 @@ * Uncheck Index source files not included in the build * Uncheck Allow heuristic resolution of includes * Click Apply to commit the changes - * C/C++ Paths and Symbols. This help Eclipse build the symbol table for Chrome. - * From a shell, run `GYP_GENERATORS=eclipse build/gyp_chromium` - * This generates `<project root>/out/Release/eclipse-cdt-settings.xml` which - is used below. - * Select C/C++ General > Paths and Symbols from the tree on the left - * Click Restore Defaults to clear any old settings - * Click Import Settings... The import dialog should appear. - * Click Browse... A file browser should appear. - * Select `<project root>/out/Release/eclipse-cdt-settings.xml`. - * Click the Finish button. The entire preferences dialog should go away. - * Right click on the project and select Index > Rebuild * Java * Create a link from `<project root>/.classpath` to `<project root>/tools/android/eclipse/.classpath`:
diff --git a/docs/emacs.md b/docs/emacs.md index 434d3252..a35bafa 100644 --- a/docs/emacs.md +++ b/docs/emacs.md
@@ -187,21 +187,7 @@ Note: You might need to grab the latest version of [whitespace.el](http://www.emacswiki.org/emacs-en/download/whitespace.el). -## gyp - -### `gyp` style -There is a gyp mode that provides basic indentation and font-lock (syntax -highlighting) support. The mode derives from python.el (bundled with newer -emacsen). - -You can find it in /src/tools/gyp/tools/emacs - -See the README file there for installation instructions. - -**Important**: the mode is only tested with `python.el` (bundled with newer -emacsen), not with `python-mode.el` (outdated and less maintained these days). - -### deep nesting +## deep nesting A couple of helpers that show a summary of where you are; the first by tracing the indentation hierarchy upwards, the second by only showing `#if`s and
diff --git a/docs/gpu/debugging_gpu_related_code.md b/docs/gpu/debugging_gpu_related_code.md index 765942c..0c350e6 100644 --- a/docs/gpu/debugging_gpu_related_code.md +++ b/docs/gpu/debugging_gpu_related_code.md
@@ -88,7 +88,7 @@ You can often make a simple OpenGL-ES-2.0-only C++ reduced test case that is relatively quick to compile and test, by adding tests to the `gl_tests` target. Those tests exist in `src/gpu/command_buffer/tests` and are made part of the -build in `src/gpu/gpu.gyp`. Build with `ninja -C out/Debug gl_tests`. All the +build in `src/gpu/BUILD.gn`. Build with `ninja -C out/Debug gl_tests`. All the same command line options listed on this page will work with the `gl_tests`, plus `--gtest_filter=NameOfTest` to run a specific test. Note the `gl_tests` are not multi-process, so they probably won't help with race conditions, but
diff --git a/docs/gpu/gpu_testing.md b/docs/gpu/gpu_testing.md index 2dcc5a7b1..3becd8b3 100644 --- a/docs/gpu/gpu_testing.md +++ b/docs/gpu/gpu_testing.md
@@ -422,7 +422,7 @@ If you are adding a new test to one of the existing tests (e.g., `pixel_test`), all you need to do is make sure that your new test runs correctly via isolates. See the documentation from the GPU bot details on [adding new isolated -tests][new-isolates] for the `GYP_DEFINES` and authentication needed to upload +tests][new-isolates] for the gn args and authentication needed to upload isolates to the isolate server. Most likely the new test will be Telemetry based, and included in the `telemetry_gpu_test_run` isolate. You can then invoke it via:
diff --git a/docs/gpu/pixel_wrangling.md b/docs/gpu/pixel_wrangling.md index f900b103..42b73463 100644 --- a/docs/gpu/pixel_wrangling.md +++ b/docs/gpu/pixel_wrangling.md
@@ -83,11 +83,11 @@ `pixel_integration_test.py` * Stress tests of the screenshot functionality other tests use: `screenshot_sync_integration_test.py` -* `angle_unittests`: see `src/gpu/gpu.gyp` +* `angle_unittests`: see `src/third_party/angle/src/tests/BUILD.gn` * drawElements tests (on the chromium.gpu.fyi waterfall): see `src/third_party/angle/src/tests/BUILD.gn` * `gles2_conform_test` (requires internal sources): see - `src/gpu/gles2_conform_support/gles2_conform_test.gyp` + `src/gpu/gles2_conform_support/BUILD.gn` * `gl_tests`: see `src/gpu/BUILD.gn` * `gl_unittests`: see `src/ui/gl/BUILD.gn`
diff --git a/docs/ipc_fuzzer.md b/docs/ipc_fuzzer.md index 7cf3c96..79331c94 100644 --- a/docs/ipc_fuzzer.md +++ b/docs/ipc_fuzzer.md
@@ -13,8 +13,7 @@ ### Build instructions -* Run `gn args` and add `enable_ipc_fuzzer = true` to your args.gn. If you use - GYP, add `enable_ipc_fuzzer=1` to `GYP_DEFINES`. +* Run `gn args` and add `enable_ipc_fuzzer = true` to your args.gn. * build `ipc_fuzzer_all` target * component builds are currently broken, sorry * Debug builds are broken; only Release mode works. @@ -43,7 +42,7 @@ ### ipcdump logger -* add `enable_ipc_fuzzer=1` to `GYP_DEFINES` +* add `enable_ipc_fuzzer = true` to `args.gn` * build `chrome` and `ipc_message_dump` targets * run chrome with `--no-sandbox --ipc-dump-directory=/path/to/ipcdump/directory`
diff --git a/docs/linux_chromium_arm.md b/docs/linux_chromium_arm.md index 180a497..0013f68 100644 --- a/docs/linux_chromium_arm.md +++ b/docs/linux_chromium_arm.md
@@ -23,8 +23,8 @@ ### Installing the sysroot A prebuilt sysroot image is kept up to date on Cloud Storage. It will -automatically be installed by gclient runhooks installed if you have -`target_arch=arm` in your `GYP_DEFINES`. +automatically be installed by gclient runhooks if `target_cpu=["arm"]` +is present in your `.gclient` file. To install the sysroot manually you can run:
diff --git a/docs/linux_debugging.md b/docs/linux_debugging.md index c69b0fa..fb8947f 100644 --- a/docs/linux_debugging.md +++ b/docs/linux_debugging.md
@@ -458,9 +458,7 @@ ## Breakpad -See the last section of [Linux Crash Dumping](linux_crash_dumping.md); you -need to set a gyp variable and an environment variable for the crash dump tests -to work. +See the last section of [Linux Crash Dumping](linux_crash_dumping.md). ## Drag and Drop
diff --git a/docs/linux_hw_video_decode.md b/docs/linux_hw_video_decode.md index 44d2b8f7..a64f14a2 100644 --- a/docs/linux_hw_video_decode.md +++ b/docs/linux_hw_video_decode.md
@@ -47,11 +47,11 @@ make -j32 && rm -f ${DEST}/lib/dri/{nvidia_drv_video.so,s3g_drv_video.so} && make install ``` -* Add to `$GYP_DEFINES`: - * `chromeos=1` to link in `VaapiVideoDecodeAccelerator` - * `proprietary_codecs=1 ffmpeg_branding=Chrome` to allow Chrome to play - h.264 content, which is the only codec VAVDA knows about today. -* Re-run gyp (`./build/gyp_chromium` or `gclient runhooks`) +* Add to args.gn: + * `target_os = "chromeos"` to link in `VaapiVideoDecodeAccelerator` + * `proprietary_codecs = true` and `ffmpeg_branding = "Chrome"` to + allow Chrome to play h.264 content, which is the only codec + VAVDA knows about today. * Rebuild chrome * Run chrome with `LD_LIBRARY_PATH=${HOME}/apps/libva/lib` in the environment, and with the `--no-sandbox` command line flag.
diff --git a/docs/linux_profiling.md b/docs/linux_profiling.md index 694e4e9..4265909 100644 --- a/docs/linux_profiling.md +++ b/docs/linux_profiling.md
@@ -55,16 +55,11 @@ ### google-perftools -google-perftools code is enabled when the `use_allocator` variable in gyp is set +google-perftools code is enabled when the `use_allocator` gn variable is set to `tcmalloc` (currently the default). That will build the tcmalloc library, including the cpu profiling and heap profiling code into Chromium. In order to get stacktraces in release builds on 64 bit, you will need to build with some -extra flags enabled by setting `profiling=1` in gyp. - -If the stack traces in your profiles are incomplete, this may be due to missing -frame pointers in some of the libraries. A workaround is to use the -`linux_keep_shadow_stacks=1` gyp option. This will keep a shadow stack using the -`-finstrument-functions` option of gcc and consult the stack when unwinding. +extra flags enabled by setting `enable_profiling = true` in args.gn In order to enable cpu profiling, run Chromium with the environment variable `CPUPROFILE` set to a filename. For example:
diff --git a/docs/linux_suid_sandbox_development.md b/docs/linux_suid_sandbox_development.md index 03aceca..9ce6808 100644 --- a/docs/linux_suid_sandbox_development.md +++ b/docs/linux_suid_sandbox_development.md
@@ -83,4 +83,4 @@ The `CHROME_DEVEL_SANDBOX` variable is intended for developers and won't work for a system-wide installation of Chromium. Package maintainers should make sure -the `setuid` binary is installed and defined in GYP as `linux_sandbox_path`. +the `setuid` binary is installed.
diff --git a/docs/memory-infra/README.md b/docs/memory-infra/README.md index 37404df..f73d843 100644 --- a/docs/memory-infra/README.md +++ b/docs/memory-infra/README.md
@@ -140,9 +140,8 @@ event? Which subsystem increased? Did memory not go down as expected after closing a tab? Which other threads were active during a bloat? * **Works out of the box on desktop and mobile.** - No recompilations with unmaintained `GYP_DEFINES`, no time-consuming - symbolizations stages. All the logic is already into Chrome, ready to dump at - any time. + No recompilations, no time-consuming symbolizations stages. All the + logic is already in Chrome, ready to dump at any time. * **The same technology is used for telemetry and the ChromePerf dashboard.** See [the slides][chromeperf-slides] and take a look at [some ChromePerf dashboards][chromeperf] and
diff --git a/docs/using_a_linux_chroot.md b/docs/using_a_linux_chroot.md index da37cfe..a8f4304 100644 --- a/docs/using_a_linux_chroot.md +++ b/docs/using_a_linux_chroot.md
@@ -16,7 +16,7 @@ Run `build /install-build-deps.sh`, then exit the rooted chroot. * Delete your out/ directory if you had a previous non-chrooted build. * To enter your chroot as normal user, run `schroot -c lucid64`. -* Now run `build/gyp_chromium`, compile and run DumpRenderTree within chroot. +* Now compile and run DumpRenderTree within chroot. ## Tips and Tricks
diff --git a/docs/vanilla_msysgit_workflow.md b/docs/vanilla_msysgit_workflow.md index b834874a..2c04cb00 100644 --- a/docs/vanilla_msysgit_workflow.md +++ b/docs/vanilla_msysgit_workflow.md
@@ -73,10 +73,10 @@ you use my naming convention or not), you can know before hand when you switch between branches on Windows whether you should expect a major rebuild, or a minor rebuild. If you are able to remember which of your - topic branches have .gyp changes and which don't (or I guess you could use + topic branches have gn changes and which don't (or I guess you could use `git diff` to figure this out), then you will also have a good idea whether you need to run `gclient runhooks` or not when you switch branches. Another - nice thing is that yu should never have to run `gclient sync` when you + nice thing is that you should never have to run `gclient sync` when you switch between branches with the same base revision, unless some of your branches have changes to DEPS files.
diff --git a/docs/windows_split_dll.md b/docs/windows_split_dll.md index e7f4c2cf..e8aac58 100644 --- a/docs/windows_split_dll.md +++ b/docs/windows_split_dll.md
@@ -5,37 +5,10 @@ ## How -Normally, you probably don't need to worry about doing this build. If for some -reason you need to build it locally: +Split DLL is now default on Windows and controlled by the +`is_multi_dll_chrome` gn variable. -1. From a _Visual Studio Command Prompt_ running as **Administrator** run - `python tools\win\split_link\install_split_link.py`. -1. Set `GYP_DEFINES=chrome_split_dll=1`. In particular, don't have - `component=shared_library`. Other things, like `buildtype` or `fastbuild` - are fine. -1. `gclient runhooks` -1. `ninja -C out\Release chrome` - -`chrome_split_dll` currently applies only to chrome.dll (and not test binaries). - -## What - -This is intended to be a temporary measure until either the toolchain is -improved or the code can be physically separated into two DLLs (based on a -browser/child split). - -The link replacement forcibly splits chrome.dll into two halves based on a -description in `build\split_link_partition.py`. Code is primarily split along -browser/renderer lines. Roughly, Blink and its direct dependencies are in the -"chrome1.dll", and the rest of the browser code remains in "chrome.dll". - -TODO: build\split_link_partition.py doesn't exist. - -Splitting the code this way allows keeping maximum optimization on the Blink -portion of the code, which is important for performance. - -There is a compile time define set when building in this mode -`CHROME_SPLIT_DLL`, however it should be used very sparingly-to-not-at-all. +`is_multi_dll_chrome` applies only to chrome.dll (and not test binaries). ## Details @@ -44,15 +17,6 @@ forcibly exported from the other DLL. This works relatively cleanly for function import/export, however it cannot work for data export. -There are relatively few instances where data exports are required across the -DLL boundary. The waterfall builder -https://build.chromium.org/p/chromium/waterfall?show=Win%20Split will detect when -new data exports are added, and these will need to be repaired. For constants, -the data can be duplicated to both DLLs, but for writeable data, a wrapping -set/get function will need to be added. - -https://build.chromium.org/p/chromium/waterfall?show=Win%20Split does not exist. - Some more details can be found on the initial commit of the split_link script https://src.chromium.org/viewvc/chrome?revision=200049&view=revision and the associated bugs: https://crbug.com/237249 https://crbug.com/237267.
diff --git a/extensions/shell/browser/shell_desktop_controller_aura.cc b/extensions/shell/browser/shell_desktop_controller_aura.cc index f330d1b..4b9cc24 100644 --- a/extensions/shell/browser/shell_desktop_controller_aura.cc +++ b/extensions/shell/browser/shell_desktop_controller_aura.cc
@@ -337,7 +337,7 @@ user_activity_detector_ = std::make_unique<ui::UserActivityDetector>(); user_activity_notifier_ = std::make_unique<ui::UserActivityPowerManagerNotifier>( - user_activity_detector_.get()); + user_activity_detector_.get(), nullptr /*connector*/); #endif }
diff --git a/gpu/config/gpu_driver_bug_list.json b/gpu/config/gpu_driver_bug_list.json index 3c70907..7d3976e2 100644 --- a/gpu/config/gpu_driver_bug_list.json +++ b/gpu/config/gpu_driver_bug_list.json
@@ -2841,6 +2841,7 @@ ], "disabled_extensions": [ "GL_ARB_timer_query", + "GL_EXT_timer_query", "GL_EXT_disjoint_timer_query", "GL_EXT_disjoint_timer_query_webgl2" ]
diff --git a/headless/lib/browser/headless_shell_application_mac.mm b/headless/lib/browser/headless_shell_application_mac.mm index d1ac000..fddf2bf5 100644 --- a/headless/lib/browser/headless_shell_application_mac.mm +++ b/headless/lib/browser/headless_shell_application_mac.mm
@@ -5,6 +5,15 @@ #include "headless/lib/browser/headless_shell_application_mac.h" #include "base/auto_reset.h" +#include "base/observer_list.h" +#include "content/public/browser/native_event_processor_mac.h" +#include "content/public/browser/native_event_processor_observer_mac.h" + +@interface HeadlessShellCrApplication ()<NativeEventProcessor> { + base::ObserverList<content::NativeEventProcessorObserver>::Unchecked + observers_; +} +@end @implementation HeadlessShellCrApplication @@ -17,4 +26,20 @@ - (void)setHandlingSendEvent:(BOOL)handlingSendEvent { } +- (void)sendEvent:(NSEvent*)event { + content::ScopedNotifyNativeEventProcessorObserver scopedObserverNotifier( + &observers_, event); + [super sendEvent:event]; +} + +- (void)addNativeEventProcessorObserver: + (content::NativeEventProcessorObserver*)observer { + observers_.AddObserver(observer); +} + +- (void)removeNativeEventProcessorObserver: + (content::NativeEventProcessorObserver*)observer { + observers_.RemoveObserver(observer); +} + @end
diff --git a/ios/chrome/app/main_controller.mm b/ios/chrome/app/main_controller.mm index 9b70135..2ea71bd4 100644 --- a/ios/chrome/app/main_controller.mm +++ b/ios/chrome/app/main_controller.mm
@@ -158,7 +158,7 @@ #include "ios/web/public/webui/web_ui_ios_controller_factory.h" #include "mojo/core/embedder/embedder.h" #import "net/base/mac/url_conversions.h" -#include "net/url_request/url_request_context.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -1054,12 +1054,12 @@ [[DeferredInitializationRunner sharedInstance] enqueueBlockNamed:kSendInstallPingIfNecessary block:^{ - net::URLRequestContextGetter* context = - _mainBrowserState->GetRequestContext(); + auto URLLoaderFactory = + _mainBrowserState->GetSharedURLLoaderFactory(); bool is_first_run = FirstRun::IsChromeFirstRun(); ios::GetChromeBrowserProvider() ->GetAppDistributionProvider() - ->ScheduleDistributionNotifications(context, + ->ScheduleDistributionNotifications(URLLoaderFactory, is_first_run); InitializeFirebase(is_first_run); }];
diff --git a/ios/chrome/browser/BUILD.gn b/ios/chrome/browser/BUILD.gn index 55bf0b0..d245b44 100644 --- a/ios/chrome/browser/BUILD.gn +++ b/ios/chrome/browser/BUILD.gn
@@ -124,6 +124,7 @@ "//ios/chrome/browser/itunes_urls", "//ios/chrome/browser/mailto:feature_flags", "//ios/chrome/browser/payments:constants", + "//ios/chrome/browser/search_engines:feature_flags", "//ios/chrome/browser/signin:feature_flags", "//ios/chrome/browser/ssl:feature_flags", "//ios/chrome/browser/sync/glue",
diff --git a/ios/chrome/browser/about_flags.mm b/ios/chrome/browser/about_flags.mm index b0dd2940..b8241082 100644 --- a/ios/chrome/browser/about_flags.mm +++ b/ios/chrome/browser/about_flags.mm
@@ -47,6 +47,7 @@ #include "ios/chrome/browser/ios_chrome_flag_descriptions.h" #include "ios/chrome/browser/itunes_urls/itunes_urls_flag.h" #include "ios/chrome/browser/mailto/features.h" +#include "ios/chrome/browser/search_engines/feature_flags.h" #include "ios/chrome/browser/signin/feature_flags.h" #include "ios/chrome/browser/ssl/captive_portal_features.h" #include "ios/chrome/browser/ui/external_search/features.h" @@ -391,6 +392,9 @@ {"wk-web-view-snapshots", flag_descriptions::kWKWebViewSnapshotsName, flag_descriptions::kWKWebViewSnapshotsDescription, flags_ui::kOsIos, FEATURE_VALUE_TYPE(kWKWebViewSnapshots)}, + {"custom-search-engines", flag_descriptions::kCustomSearchEnginesName, + flag_descriptions::kCustomSearchEnginesDescription, flags_ui::kOsIos, + FEATURE_VALUE_TYPE(kCustomSearchEngines)}, }; // Add all switches from experimental flags to |command_line|.
diff --git a/ios/chrome/browser/ios_chrome_flag_descriptions.cc b/ios/chrome/browser/ios_chrome_flag_descriptions.cc index e851885..d094f76 100644 --- a/ios/chrome/browser/ios_chrome_flag_descriptions.cc +++ b/ios/chrome/browser/ios_chrome_flag_descriptions.cc
@@ -304,6 +304,10 @@ const char kWKWebViewSnapshotsDescription[] = "When enabled, the WKWebView snapshotting API is used for iOS 11+."; +const char kCustomSearchEnginesName[] = "Custom Search Engines"; +const char kCustomSearchEnginesDescription[] = + "When enabled, user can add custom search engines in settings."; + // Please insert your name/description above in alphabetical order. } // namespace flag_descriptions
diff --git a/ios/chrome/browser/ios_chrome_flag_descriptions.h b/ios/chrome/browser/ios_chrome_flag_descriptions.h index 5e1c766..a9803ee 100644 --- a/ios/chrome/browser/ios_chrome_flag_descriptions.h +++ b/ios/chrome/browser/ios_chrome_flag_descriptions.h
@@ -255,6 +255,10 @@ extern const char kWKWebViewSnapshotsName[]; extern const char kWKWebViewSnapshotsDescription[]; +// Title and description for the flag to allow custom search engines. +extern const char kCustomSearchEnginesName[]; +extern const char kCustomSearchEnginesDescription[]; + // Please insert your name/description above in alphabetical order. } // namespace flag_descriptions
diff --git a/ios/chrome/browser/net/retryable_url_fetcher.h b/ios/chrome/browser/net/retryable_url_fetcher.h index f9c4a14..1d56aa5 100644 --- a/ios/chrome/browser/net/retryable_url_fetcher.h +++ b/ios/chrome/browser/net/retryable_url_fetcher.h
@@ -13,7 +13,7 @@ namespace network { class SharedURLLoaderFactory; -} +} // namespace network // Delegate protocol for RetryableURLFetcher object. @protocol RetryableURLFetcherDelegate<NSObject>
diff --git a/ios/chrome/browser/search_engines/BUILD.gn b/ios/chrome/browser/search_engines/BUILD.gn index 15326790..e6593a1 100644 --- a/ios/chrome/browser/search_engines/BUILD.gn +++ b/ios/chrome/browser/search_engines/BUILD.gn
@@ -5,6 +5,17 @@ import("//build/config/features.gni") import("//rlz/buildflags/buildflags.gni") +source_set("feature_flags") { + configs += [ "//build/config/compiler:enable_arc" ] + sources = [ + "feature_flags.cc", + "feature_flags.h", + ] + deps = [ + "//base", + ] +} + source_set("search_engines") { sources = [ "search_engine_observer_bridge.h",
diff --git a/ios/chrome/browser/search_engines/feature_flags.cc b/ios/chrome/browser/search_engines/feature_flags.cc new file mode 100644 index 0000000..2c9e964 --- /dev/null +++ b/ios/chrome/browser/search_engines/feature_flags.cc
@@ -0,0 +1,8 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ios/chrome/browser/search_engines/feature_flags.h" + +const base::Feature kCustomSearchEngines{"CustomSearchEngines", + base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/ios/chrome/browser/search_engines/feature_flags.h b/ios/chrome/browser/search_engines/feature_flags.h new file mode 100644 index 0000000..9323536 --- /dev/null +++ b/ios/chrome/browser/search_engines/feature_flags.h
@@ -0,0 +1,13 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_BROWSER_SEARCH_ENGINES_FEATURE_FLAGS_H_ +#define IOS_CHROME_BROWSER_SEARCH_ENGINES_FEATURE_FLAGS_H_ + +#include "base/feature_list.h" + +// Feature to allow user to add custom search engines. +extern const base::Feature kCustomSearchEngines; + +#endif // IOS_CHROME_BROWSER_SEARCH_ENGINES_FEATURE_FLAGS_H_
diff --git a/ios/chrome/browser/ui/autofill/BUILD.gn b/ios/chrome/browser/ui/autofill/BUILD.gn index cc8b809..5b7b1f1 100644 --- a/ios/chrome/browser/ui/autofill/BUILD.gn +++ b/ios/chrome/browser/ui/autofill/BUILD.gn
@@ -101,6 +101,7 @@ testonly = true sources = [ "save_card_infobar_egtest.mm", + "save_profile_egtest.mm", ] deps = [ ":autofill_ui",
diff --git a/ios/chrome/browser/ui/autofill/save_card_infobar_egtest.mm b/ios/chrome/browser/ui/autofill/save_card_infobar_egtest.mm index bdeccd2..985c134 100644 --- a/ios/chrome/browser/ui/autofill/save_card_infobar_egtest.mm +++ b/ios/chrome/browser/ui/autofill/save_card_infobar_egtest.mm
@@ -18,6 +18,7 @@ #include "ios/chrome/browser/autofill/personal_data_manager_factory.h" #import "ios/chrome/browser/ui/autofill/save_card_infobar_controller.h" #import "ios/chrome/test/app/chrome_test_util.h" +#import "ios/chrome/test/app/web_view_interaction_test_util.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" @@ -38,6 +39,7 @@ using base::test::ios::kWaitForDownloadTimeout; using base::test::ios::kWaitForUIElementTimeout; using base::test::ios::WaitUntilConditionOrTimeout; +using chrome_test_util::TapWebViewElementWithId; // URLs of the test pages. const char kCreditCardUploadForm[] = @@ -197,31 +199,19 @@ #pragma mark - Page interaction helper methods - (void)fillAndSubmitFormWithCardDetailsOnly { - NSError* error = nil; - chrome_test_util::ExecuteJavaScript( - @"(function() { document.getElementById('fill_card_only').click(); })();", - &error); - GREYAssert(!error, @"Error during script execution: %@", error); - + GREYAssert(TapWebViewElementWithId("fill_card_only"), + @"Failed to tap \"fill_card_only\""); [self submitForm]; } - (void)fillAndSubmitForm { - NSError* error = nil; - chrome_test_util::ExecuteJavaScript( - @"(function() { document.getElementById('fill_form').click(); })();", - &error); - GREYAssert(!error, @"Error during script execution: %@", error); - + GREYAssert(TapWebViewElementWithId("fill_form"), + @"Failed to tap \"fill_form\""); [self submitForm]; } - (void)submitForm { - NSError* error = nil; - chrome_test_util::ExecuteJavaScript( - @"(function() { document.getElementById('submit').click(); })();", - &error); - GREYAssert(!error, @"Error during script execution: %@", error); + GREYAssert(TapWebViewElementWithId("submit"), @"Failed to tap \"submit\""); } #pragma mark - Helper methods @@ -514,6 +504,10 @@ [ChromeEarlGrey loadURL:web::test::HttpServer::MakeUrl(kCreditCardUploadForm)]; + // Ensure there are no saved credit cards. + GREYAssertEqual(0U, personal_data_manager_->GetCreditCards().size(), + @"There should be no saved credit card."); + // Set up the Google Payments server response. test_url_loader_factory_.AddResponse(kURLGetUploadDetailsRequest, kResponseGetUploadDetailsFailure);
diff --git a/ios/chrome/browser/ui/autofill/save_profile_egtest.mm b/ios/chrome/browser/ui/autofill/save_profile_egtest.mm new file mode 100644 index 0000000..f39bada --- /dev/null +++ b/ios/chrome/browser/ui/autofill/save_profile_egtest.mm
@@ -0,0 +1,83 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <memory> + +#include "base/logging.h" +#import "base/test/ios/wait_util.h" +#include "components/autofill/core/browser/personal_data_manager.h" +#include "ios/chrome/browser/autofill/personal_data_manager_factory.h" +#import "ios/chrome/test/app/chrome_test_util.h" +#import "ios/chrome/test/app/web_view_interaction_test_util.h" +#import "ios/chrome/test/earl_grey/chrome_earl_grey.h" +#import "ios/chrome/test/earl_grey/chrome_test_case.h" +#import "ios/web/public/test/http_server/http_server.h" +#include "testing/gtest/include/gtest/gtest.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +namespace { + +using chrome_test_util::TapWebViewElementWithId; + +// URLs of the test pages. +const char kProfileForm[] = + "http://ios/testing/data/http_server_files/autofill_smoke_test.html"; + +} // namepsace + +@interface SaveProfileEGTest : ChromeTestCase { + autofill::PersonalDataManager* personal_data_manager_; +} + +@end + +@implementation SaveProfileEGTest + +- (void)setUp { + [super setUp]; + + personal_data_manager_ = + autofill::PersonalDataManagerFactory::GetForBrowserState( + chrome_test_util::GetOriginalBrowserState()); +} + +- (void)tearDown { + // Clear existing profile. + for (const auto* profile : personal_data_manager_->GetProfiles()) { + personal_data_manager_->RemoveByGUID(profile->guid()); + } + + [super tearDown]; +} + +#pragma mark - Page interaction helper methods + +- (void)fillAndSubmitForm { + GREYAssert(TapWebViewElementWithId("fill_profile_president"), + @"Failed to tap \"fill_profile_president\""); + GREYAssert(TapWebViewElementWithId("submit_profile"), + @"Failed to tap \"submit_profile\""); +} + +#pragma mark - Tests + +// Ensures that the profile is saved to Chrome after submitting the form. +- (void)testUserData_LocalSave { + [ChromeEarlGrey loadURL:web::test::HttpServer::MakeUrl(kProfileForm)]; + + // Ensure there are no saved profiles. + GREYAssertEqual(0U, personal_data_manager_->GetProfiles().size(), + @"There should be no saved profile."); + + [self fillAndSubmitForm]; + + // Ensure profile is saved locally. + GREYAssertEqual(1U, personal_data_manager_->GetProfiles().size(), + @"Profile should have been saved."); +} + +@end
diff --git a/ios/chrome/browser/ui/bookmarks/bookmark_home_view_controller.mm b/ios/chrome/browser/ui/bookmarks/bookmark_home_view_controller.mm index 8d82c198..64d32bb 100644 --- a/ios/chrome/browser/ui/bookmarks/bookmark_home_view_controller.mm +++ b/ios/chrome/browser/ui/bookmarks/bookmark_home_view_controller.mm
@@ -736,7 +736,8 @@ } - (void)showSignin:(ShowSigninCommand*)command { - [self.dispatcher showSignin:command baseViewController:self]; + [self.dispatcher showSignin:command + baseViewController:self.navigationController]; } - (void)configureSigninPromoWithConfigurator:
diff --git a/ios/chrome/browser/ui/history/history_search_view_controller_unittest.mm b/ios/chrome/browser/ui/history/history_search_view_controller_unittest.mm index 5d1322c..35ecd7a7 100644 --- a/ios/chrome/browser/ui/history/history_search_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/history/history_search_view_controller_unittest.mm
@@ -52,7 +52,7 @@ // Test that invocation of // textField:shouldChangeCharactersInRange:replacementString: on the text field // delegate results invokes delegate callback to request search. -TEST_F(HistorySearchViewControllerTest, SearchButtonPressed) { +TEST_F(HistorySearchViewControllerTest, DISABLED_SearchButtonPressed) { UITextField* text_field = base::mac::ObjCCastStrict<HistorySearchView>(search_view_controller_.view) .textField; @@ -67,7 +67,7 @@ // Test that disabling HistorySearchViewController disables the search view text // field. -TEST_F(HistorySearchViewControllerTest, DisableSearchBar) { +TEST_F(HistorySearchViewControllerTest, DISABLED_DisableSearchBar) { UITextField* text_field = base::mac::ObjCCastStrict<HistorySearchView>(search_view_controller_.view) .textField;
diff --git a/ios/public/provider/chrome/browser/distribution/app_distribution_provider.h b/ios/public/provider/chrome/browser/distribution/app_distribution_provider.h index 58878454..b60afcf 100644 --- a/ios/public/provider/chrome/browser/distribution/app_distribution_provider.h +++ b/ios/public/provider/chrome/browser/distribution/app_distribution_provider.h
@@ -8,10 +8,11 @@ #include <string> #include "base/macros.h" +#include "base/memory/scoped_refptr.h" -namespace net { -class URLRequestContextGetter; -} +namespace network { +class SharedURLLoaderFactory; +} // namespace network class AppDistributionProvider { public: @@ -23,7 +24,7 @@ // Schedules distribution notifications to be sent using the given |context|. virtual void ScheduleDistributionNotifications( - net::URLRequestContextGetter* context, + scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory, bool is_first_run); // Cancels any pending distribution notifications.
diff --git a/ios/public/provider/chrome/browser/distribution/app_distribution_provider.mm b/ios/public/provider/chrome/browser/distribution/app_distribution_provider.mm index 0b586b92..3f744451 100644 --- a/ios/public/provider/chrome/browser/distribution/app_distribution_provider.mm +++ b/ios/public/provider/chrome/browser/distribution/app_distribution_provider.mm
@@ -17,7 +17,7 @@ } void AppDistributionProvider::ScheduleDistributionNotifications( - net::URLRequestContextGetter* context, + scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory, bool is_first_run) {} void AppDistributionProvider::CancelDistributionNotifications() {}
diff --git a/ios/public/provider/chrome/browser/distribution/test_app_distribution_provider.h b/ios/public/provider/chrome/browser/distribution/test_app_distribution_provider.h index c366e07..7efef29 100644 --- a/ios/public/provider/chrome/browser/distribution/test_app_distribution_provider.h +++ b/ios/public/provider/chrome/browser/distribution/test_app_distribution_provider.h
@@ -5,9 +5,15 @@ #ifndef IOS_PUBLIC_PROVIDER_CHROME_BROWSER_DISTRIBUTION_TEST_APP_DISTRIBUTION_PROVIDER_H_ #define IOS_PUBLIC_PROVIDER_CHROME_BROWSER_DISTRIBUTION_TEST_APP_DISTRIBUTION_PROVIDER_H_ -#include "base/macros.h" #import "ios/public/provider/chrome/browser/distribution/app_distribution_provider.h" +#include "base/macros.h" +#include "base/memory/scoped_refptr.h" + +namespace network { +class SharedURLLoaderFactory; +} // namespace network + class TestAppDistributionProvider : public AppDistributionProvider { public: TestAppDistributionProvider(); @@ -15,8 +21,9 @@ // AppDistributionProvider. std::string GetDistributionBrandCode() override; - void ScheduleDistributionNotifications(net::URLRequestContextGetter* context, - bool is_first_run) override; + void ScheduleDistributionNotifications( + scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory, + bool is_first_run) override; void CancelDistributionNotifications() override; private:
diff --git a/ios/public/provider/chrome/browser/distribution/test_app_distribution_provider.mm b/ios/public/provider/chrome/browser/distribution/test_app_distribution_provider.mm index 47938e4..eb89745 100644 --- a/ios/public/provider/chrome/browser/distribution/test_app_distribution_provider.mm +++ b/ios/public/provider/chrome/browser/distribution/test_app_distribution_provider.mm
@@ -17,7 +17,7 @@ } void TestAppDistributionProvider::ScheduleDistributionNotifications( - net::URLRequestContextGetter* context, + scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory, bool is_first_run) {} void TestAppDistributionProvider::CancelDistributionNotifications() {}
diff --git a/media/base/android/java/src/org/chromium/media/MediaPlayerBridge.java b/media/base/android/java/src/org/chromium/media/MediaPlayerBridge.java index 3a40863f..bc60148 100644 --- a/media/base/android/java/src/org/chromium/media/MediaPlayerBridge.java +++ b/media/base/android/java/src/org/chromium/media/MediaPlayerBridge.java
@@ -16,12 +16,12 @@ import android.view.Surface; import org.chromium.base.ApiCompatibilityUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.StreamUtil; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import org.chromium.base.task.AsyncTask; import java.io.ByteArrayInputStream; import java.io.File;
diff --git a/media/gpu/android/media_codec_video_decoder.cc b/media/gpu/android/media_codec_video_decoder.cc index 7b27a50a..544a808 100644 --- a/media/gpu/android/media_codec_video_decoder.cc +++ b/media/gpu/android/media_codec_video_decoder.cc
@@ -439,6 +439,8 @@ media_crypto_); config->initial_expected_coded_size = decoder_config_.coded_size(); config->surface_bundle = target_surface_bundle_; + config->container_color_space = decoder_config_.color_space_info(); + config->hdr_metadata = decoder_config_.hdr_metadata(); // Use the asynchronous API if we can. if (device_info_->IsAsyncApiSupported()) {
diff --git a/media/gpu/android/media_codec_video_decoder_unittest.cc b/media/gpu/android/media_codec_video_decoder_unittest.cc index 503cf06..48ffee8 100644 --- a/media/gpu/android/media_codec_video_decoder_unittest.cc +++ b/media/gpu/android/media_codec_video_decoder_unittest.cc
@@ -279,6 +279,7 @@ // Tests which only work for a single codec. class MediaCodecVideoDecoderH264Test : public MediaCodecVideoDecoderTest {}; class MediaCodecVideoDecoderVp8Test : public MediaCodecVideoDecoderTest {}; +class MediaCodecVideoDecoderVp9Test : public MediaCodecVideoDecoderTest {}; TEST_P(MediaCodecVideoDecoderTest, UnknownCodecIsRejected) { ASSERT_FALSE(Initialize(TestVideoConfig::Invalid())); @@ -904,6 +905,43 @@ EXPECT_EQ(csd1, codec_allocator_->most_recent_config->csd1); } +TEST_P(MediaCodecVideoDecoderVp9Test, ColorSpaceIsIncludedInCodecConfig) { + VideoDecoderConfig config = TestVideoConfig::Normal(kCodecVP9); + VideoColorSpace color_space_info(VideoColorSpace::PrimaryID::BT2020, + VideoColorSpace::TransferID::SMPTEST2084, + VideoColorSpace::MatrixID::BT2020_CL, + gfx::ColorSpace::RangeID::LIMITED); + + config.set_color_space_info(color_space_info); + EXPECT_TRUE(InitializeFully_OneDecodePending(config)); + + EXPECT_EQ(color_space_info, + codec_allocator_->most_recent_config->container_color_space); +} + +TEST_P(MediaCodecVideoDecoderVp9Test, HdrMetadataIsIncludedInCodecConfig) { + VideoDecoderConfig config = TestVideoConfig::Normal(kCodecVP9); + HDRMetadata hdr_metadata; + hdr_metadata.max_frame_average_light_level = 123; + hdr_metadata.max_content_light_level = 456; + hdr_metadata.mastering_metadata.primary_r.set_x(0.1f); + hdr_metadata.mastering_metadata.primary_r.set_y(0.2f); + hdr_metadata.mastering_metadata.primary_g.set_x(0.3f); + hdr_metadata.mastering_metadata.primary_g.set_y(0.4f); + hdr_metadata.mastering_metadata.primary_b.set_x(0.5f); + hdr_metadata.mastering_metadata.primary_b.set_y(0.6f); + hdr_metadata.mastering_metadata.white_point.set_x(0.7f); + hdr_metadata.mastering_metadata.white_point.set_y(0.8f); + hdr_metadata.mastering_metadata.luminance_max = 1000; + hdr_metadata.mastering_metadata.luminance_min = 0; + + config.set_hdr_metadata(hdr_metadata); + + EXPECT_TRUE(InitializeFully_OneDecodePending(config)); + + EXPECT_EQ(hdr_metadata, codec_allocator_->most_recent_config->hdr_metadata); +} + static std::vector<VideoCodec> GetTestList() { std::vector<VideoCodec> test_codecs;
diff --git a/remoting/android/java/src/org/chromium/chromoting/OAuthTokenConsumer.java b/remoting/android/java/src/org/chromium/chromoting/OAuthTokenConsumer.java index 3eabbfa..eb29b85 100644 --- a/remoting/android/java/src/org/chromium/chromoting/OAuthTokenConsumer.java +++ b/remoting/android/java/src/org/chromium/chromoting/OAuthTokenConsumer.java
@@ -11,7 +11,7 @@ import com.google.android.gms.auth.GoogleAuthException; import com.google.android.gms.auth.GoogleAuthUtil; -import org.chromium.base.AsyncTask; +import org.chromium.base.task.AsyncTask; import org.chromium.chromoting.base.OAuthTokenFetcher; import java.io.IOException;
diff --git a/remoting/android/java/src/org/chromium/chromoting/base/OAuthTokenFetcher.java b/remoting/android/java/src/org/chromium/chromoting/base/OAuthTokenFetcher.java index 5b97493..4f69ac76 100644 --- a/remoting/android/java/src/org/chromium/chromoting/base/OAuthTokenFetcher.java +++ b/remoting/android/java/src/org/chromium/chromoting/base/OAuthTokenFetcher.java
@@ -14,7 +14,7 @@ import com.google.android.gms.auth.GoogleAuthUtil; import com.google.android.gms.auth.UserRecoverableAuthException; -import org.chromium.base.AsyncTask; +import org.chromium.base.task.AsyncTask; import java.io.IOException;
diff --git a/services/service_manager/sandbox/win/sandbox_win.cc b/services/service_manager/sandbox/win/sandbox_win.cc index d330dd2..79ae61d 100644 --- a/services/service_manager/sandbox/win/sandbox_win.cc +++ b/services/service_manager/sandbox/win/sandbox_win.cc
@@ -938,9 +938,10 @@ return result; } - // Allow the renderer and gpu processes to access the log file. + // Allow the renderer, gpu and utility processes to access the log file. if (process_type == service_manager::switches::kRendererProcess || - process_type == service_manager::switches::kGpuProcess) { + process_type == service_manager::switches::kGpuProcess || + process_type == service_manager::switches::kUtilityProcess) { if (logging::IsLoggingToFileEnabled()) { DCHECK(base::FilePath(logging::GetLogFileFullPath()).IsAbsolute()); result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
diff --git a/services/shape_detection/android/java/src/org/chromium/shape_detection/FaceDetectionImpl.java b/services/shape_detection/android/java/src/org/chromium/shape_detection/FaceDetectionImpl.java index 3f05b29b..6cbbd65 100644 --- a/services/shape_detection/android/java/src/org/chromium/shape_detection/FaceDetectionImpl.java +++ b/services/shape_detection/android/java/src/org/chromium/shape_detection/FaceDetectionImpl.java
@@ -10,8 +10,8 @@ import android.media.FaceDetector; import android.media.FaceDetector.Face; -import org.chromium.base.AsyncTask; import org.chromium.base.Log; +import org.chromium.base.task.AsyncTask; import org.chromium.gfx.mojom.RectF; import org.chromium.mojo.system.MojoException; import org.chromium.shape_detection.mojom.FaceDetection;
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 4a6ba6f..3a17142 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -3102,7 +3102,6 @@ "version": "1" }, "enable_features": [ - "PasswordGenerationRequirements", "PasswordGenerationRequirementsDomainOverrides" ] } @@ -4247,6 +4246,26 @@ ] } ], + "SyncUSSAutofillWalletData": [ + { + "platforms": [ + "android", + "chromeos", + "ios", + "linux", + "mac", + "windows" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "SyncUSSAutofillWalletData" + ] + } + ] + } + ], "TLS13Variant": [ { "platforms": [
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG b/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG index caedc7de..82faed7 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG
@@ -238,7 +238,7 @@ crbug.com/591099 external/wpt/fetch/api/redirect/redirect-count.any.worker.html [ Pass ] crbug.com/591099 external/wpt/fetch/api/request/request-keepalive-quota.html?include=slow-2 [ Pass ] crbug.com/591099 external/wpt/fetch/http-cache/basic-auth-cache-test.html [ Timeout ] -crbug.com/591099 external/wpt/geolocation-API/PositionOptions.https.html [ Failure Pass ] +crbug.com/591099 external/wpt/geolocation-API/PositionOptions.https.html [ Failure ] crbug.com/591099 external/wpt/html-media-capture/capture_audio_cancel-manual.html [ Failure ] crbug.com/591099 external/wpt/html-media-capture/capture_image_cancel-manual.html [ Failure ] crbug.com/591099 external/wpt/html-media-capture/capture_video_cancel-manual.html [ Failure ] @@ -345,7 +345,7 @@ crbug.com/591099 fast/borders/bidi-002.html [ Failure ] crbug.com/859497 fast/borders/bidi-009a.html [ Failure ] crbug.com/591099 fast/borders/inline-mask-overlay-image-outset-vertical-rl.html [ Failure ] -crbug.com/591099 fast/box-sizing/replaced.html [ Failure ] +crbug.com/591099 fast/box-sizing/replaced.html [ Failure Pass ] crbug.com/591099 fast/css-grid-layout/maximize-tracks-definite-indefinite-width.html [ Failure ] crbug.com/591099 fast/css-intrinsic-dimensions/height-positioned.html [ Failure ] crbug.com/807708 fast/css-intrinsic-dimensions/width-avoid-floats.html [ Failure ] @@ -357,7 +357,13 @@ crbug.com/835484 fast/css/outline-auto-empty-rects.html [ Failure ] crbug.com/835484 fast/css/outline-narrowLine.html [ Failure ] crbug.com/591099 fast/css3-text/css3-text-decoration/text-underline-position/text-underline-position-under.html [ Failure ] +crbug.com/591099 fast/events/touch/compositor-touch-hit-rects-continuation.html [ Failure ] +crbug.com/591099 fast/events/touch/compositor-touch-hit-rects-non-composited-scroll.html [ Failure ] +crbug.com/591099 fast/events/touch/compositor-touch-hit-rects-scroll.html [ Failure ] +crbug.com/591099 fast/events/touch/compositor-touch-hit-rects-table.html [ Failure ] crbug.com/591099 fast/events/touch/compositor-touch-hit-rects.html [ Failure ] +crbug.com/591099 fast/events/touch/touch-rect-assert-first-layer-special.html [ Failure ] +crbug.com/591099 fast/events/touch/touch-rect-crash-on-unpromote-layer.html [ Failure ] crbug.com/591099 fast/events/wheel/mainthread-touchpad-fling-latching.html [ Pass ] crbug.com/591099 fast/events/wheel/wheel-scroll-latching-on-scrollbar.html [ Pass ] crbug.com/591099 fast/forms/placeholder-position.html [ Failure ] @@ -372,7 +378,7 @@ crbug.com/591099 fast/overflow/overflow-update-transform.html [ Failure ] crbug.com/591099 fast/overflow/recompute-overflow-of-layout-root-container.html [ Failure ] crbug.com/591099 fast/replaced/table-replaced-element.html [ Failure ] -crbug.com/591099 fast/scrolling/scrollbar-tickmarks-hittest.html [ Failure Pass ] +crbug.com/591099 fast/scrolling/scrollbar-tickmarks-hittest.html [ Pass ] crbug.com/591099 fast/sub-pixel/sub-pixel-border-2.html [ Failure ] crbug.com/591099 fast/table/border-collapsing/004-vertical.html [ Failure ] crbug.com/591099 fast/table/border-collapsing/composited-cell-collapsed-border.html [ Failure ] @@ -415,7 +421,7 @@ crbug.com/591099 http/tests/security/cors-rfc1918/addressspace-document-appcache.https.html [ Crash Failure ] crbug.com/591099 http/tests/security/cors-rfc1918/addressspace-document-csp-appcache.https.html [ Crash Failure Pass ] crbug.com/591099 http/tests/security/setDomainRelaxationForbiddenForURLScheme.html [ Crash ] -crbug.com/591099 idle-callback/test-runner-run-idle-tasks.html [ Crash Pass ] +crbug.com/591099 idle-callback/test-runner-run-idle-tasks.html [ Crash Pass Timeout ] crbug.com/591099 images/color-profile-image-filter-all.html [ Failure ] crbug.com/591099 images/rendering-broken-block-flow-images.html [ Failure ] crbug.com/591099 images/rendering-broken-images.html [ Failure ] @@ -507,13 +513,20 @@ crbug.com/591099 virtual/layout_ng/ [ Skip ] crbug.com/824918 virtual/layout_ng_experimental/ [ Skip ] crbug.com/591099 virtual/mojo-blob-urls/external/wpt/FileAPI/url/sandboxed-iframe.html [ Pass ] +crbug.com/591099 virtual/mouseevent_fractional/fast/events/touch/compositor-touch-hit-rects-continuation.html [ Failure ] +crbug.com/591099 virtual/mouseevent_fractional/fast/events/touch/compositor-touch-hit-rects-non-composited-scroll.html [ Failure ] +crbug.com/591099 virtual/mouseevent_fractional/fast/events/touch/compositor-touch-hit-rects-scroll.html [ Failure ] +crbug.com/591099 virtual/mouseevent_fractional/fast/events/touch/compositor-touch-hit-rects-table.html [ Failure ] crbug.com/591099 virtual/mouseevent_fractional/fast/events/touch/compositor-touch-hit-rects.html [ Failure ] +crbug.com/591099 virtual/mouseevent_fractional/fast/events/touch/touch-rect-assert-first-layer-special.html [ Failure ] +crbug.com/591099 virtual/mouseevent_fractional/fast/events/touch/touch-rect-crash-on-unpromote-layer.html [ Failure ] crbug.com/591099 virtual/mouseevent_fractional/fast/events/wheel/mainthread-touchpad-fling-latching.html [ Pass ] crbug.com/591099 virtual/mouseevent_fractional/fast/events/wheel/wheel-scroll-latching-on-scrollbar.html [ Pass ] crbug.com/591099 virtual/new-remote-playback-pipeline/ [ Skip ] crbug.com/591099 virtual/outofblink-cors-ns/external/wpt/fetch/api/redirect/redirect-count.any.html [ Pass ] crbug.com/591099 virtual/outofblink-cors-ns/external/wpt/fetch/api/redirect/redirect-count.any.worker.html [ Pass ] crbug.com/591099 virtual/outofblink-cors-ns/external/wpt/fetch/api/request/request-keepalive-quota.html?include=slow-2 [ Pass ] +crbug.com/591099 virtual/outofblink-cors-ns/http/tests/fetch/chromium/release-handle-crash.html [ Crash Pass ] crbug.com/591099 virtual/outofblink-cors-ns/http/tests/security/cors-rfc1918/addressspace-document-appcache.https.html [ Crash Failure ] crbug.com/591099 virtual/outofblink-cors-ns/http/tests/security/cors-rfc1918/addressspace-document-csp-appcache.https.html [ Crash Failure Pass ] crbug.com/591099 virtual/outofblink-cors-ns/http/tests/security/document-domain-canonicalizes.html [ Pass ] @@ -541,7 +554,13 @@ crbug.com/591099 virtual/stable/ [ Skip ] crbug.com/591099 virtual/threaded/ [ Skip ] crbug.com/591099 virtual/user-activation-v2/fast/events/mouse-cursor.html [ Failure ] +crbug.com/591099 virtual/user-activation-v2/fast/events/touch/compositor-touch-hit-rects-continuation.html [ Failure ] +crbug.com/591099 virtual/user-activation-v2/fast/events/touch/compositor-touch-hit-rects-non-composited-scroll.html [ Failure ] +crbug.com/591099 virtual/user-activation-v2/fast/events/touch/compositor-touch-hit-rects-scroll.html [ Failure ] +crbug.com/591099 virtual/user-activation-v2/fast/events/touch/compositor-touch-hit-rects-table.html [ Failure ] crbug.com/591099 virtual/user-activation-v2/fast/events/touch/compositor-touch-hit-rects.html [ Failure ] +crbug.com/591099 virtual/user-activation-v2/fast/events/touch/touch-rect-assert-first-layer-special.html [ Failure ] +crbug.com/591099 virtual/user-activation-v2/fast/events/touch/touch-rect-crash-on-unpromote-layer.html [ Failure ] crbug.com/591099 virtual/video-surface-layer/media/video-aspect-ratio.html [ Failure ] crbug.com/591099 virtual/video-surface-layer/media/video-display-toggle.html [ Failure ] crbug.com/591099 virtual/video-surface-layer/media/video-layer-crash.html [ Failure ]
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 b/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 index 1e4ee666..b398290 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2
@@ -1420,20 +1420,3 @@ Bug(none) fast/events/touch/compositor-touch-hit-rects-svg-root.html [ Failure ] Bug(none) fast/events/touch/compositor-touch-hit-rects-table.html [ Failure ] Bug(none) virtual/paint-touchaction-rects/fast/events/touch/compositor-touch-hit-rects-table.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/compositor-touch-hit-rects-animation.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/compositor-touch-hit-rects-global.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/compositor-touch-hit-rects-many.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/compositor-touch-hit-rects-non-composited-scroll-overflow-with-handler.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/compositor-touch-hit-rects-non-composited-scroll.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/compositor-touch-hit-rects-scroll.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/compositor-touch-hit-rects-squashing.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/compositor-touch-hit-rects-transform-changed-nolayout.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/compositor-touch-hit-rects-trigger-commit.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/compositor-touch-hit-rects-with-negative-child.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/gesture/gesture-scroll-by-page.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/gesture/touch-gesture-scroll-div-scaled.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/page-scaled-touch-gesture-click.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/touch-handler-assert-input-range.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/touch-rect-assert-first-layer-special.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/touch-rect-crash-on-unpromote-layer.html [ Failure ] -Bug(none) virtual/paint-touchaction-rects/fast/events/touch/touch-scaled-scrolled.html [ Failure ]
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index 1e0859c..42f4088 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -767,6 +767,7 @@ crbug.com/591099 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-table-cell-height-001.xht [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-table-cell-height-002.xht [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-table-cell-vertical-align-001.xht [ Failure ] +crbug.com/591099 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-under-vertical-rl-scroll.html [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-width-001.xht [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-width-002.xht [ Failure ] crbug.com/591099 virtual/layout_ng_experimental/external/wpt/css/css-multicol/multicol-width-003.xht [ Failure ] @@ -1869,8 +1870,6 @@ crbug.com/522648 fast/events/touch/compositor-touch-hit-rects-iframes.html [ Crash Failure Pass ] crbug.com/522648 virtual/mouseevent_fractional/fast/events/touch/compositor-touch-hit-rects-iframes.html [ Crash Failure Pass ] crbug.com/522648 virtual/paint-touchaction-rects/fast/events/touch/compositor-touch-hit-rects-iframes.html [ Skip ] -crbug.com/522648 virtual/scroll_customization/fast/events/touch/compositor-touch-hit-rects-iframes.html [ Skip ] -crbug.com/522648 virtual/user-activation-v2/fast/events/touch/compositor-touch-hit-rects-iframes.html [ Skip ] crbug.com/520170 fast/dom/timer-throttling-hidden-page.html [ Failure Pass ] crbug.com/652536 fast/events/mouse-cursor-change-after-image-load.html [ Failure Pass Crash ] crbug.com/652536 virtual/mouseevent_fractional/fast/events/mouse-cursor-change-after-image-load.html [ Failure Pass Crash ] @@ -3732,6 +3731,10 @@ crbug.com/888443 external/wpt/css/cssom-view/scroll-behavior-subframe-root.html [ Skip ] crbug.com/888443 external/wpt/css/cssom-view/scroll-behavior-subframe-window.html [ Skip ] +# Can't add baselines because a generated unique ID is part of the failure message. +crbug.com/888470 external/wpt/referrer-policy/css-integration/child-css/internal-import-stylesheet.html [ Failure ] +crbug.com/888470 external/wpt/referrer-policy/css-integration/child-css/processing-instruction.html [ Failure ] + # This test times out on debug builds, see https://crbug.com/755810 crbug.com/626703 [ Debug ] external/wpt/html/semantics/tabular-data/processing-model-1/span-limits.html [ Skip ] @@ -5204,3 +5207,7 @@ crbug.com/887659 animations/animationworklet/worklet-animation-set-keyframes.html [ Crash ] crbug.com/887659 animations/animationworklet/worklet-animation-set-timing.html [ Crash ] crbug.com/887659 animations/animationworklet/worklet-animation-style-update.html [ Failure ] + +# Sheriff 2018-09-24 +crbug.com/888634 external/wpt/webrtc/RTCDTMFSender-ontonechange.https.html [ Failure ] +crbug.com/888634 virtual/webrtc-wpt-unified-plan/external/wpt/webrtc/RTCDTMFSender-ontonechange.https.html [ Failure ]
diff --git a/third_party/WebKit/LayoutTests/accessibility/name-calc-inputs.html b/third_party/WebKit/LayoutTests/accessibility/name-calc-inputs.html index 4319d33a..bd7190c1 100644 --- a/third_party/WebKit/LayoutTests/accessibility/name-calc-inputs.html +++ b/third_party/WebKit/LayoutTests/accessibility/name-calc-inputs.html
@@ -92,7 +92,7 @@ <script> test(function(t) { var axTextInput7 = accessibilityController.accessibleElementById("text7"); - assert_equals(axTextInput7.name, "label-wrapping-text7 "); + assert_equals(axTextInput7.name, "label-wrapping-text7"); assert_equals(axTextInput7.nameFrom, "relatedElement"); }, "Text input with title and label-wrapped"); </script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-backgrounds/background-clip-color-repaint.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-backgrounds/background-clip-color-repaint.html index 6052db52..4a5cee08 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/css/css-backgrounds/background-clip-color-repaint.html +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-backgrounds/background-clip-color-repaint.html
@@ -31,5 +31,4 @@ document.documentElement.classList.remove("reftest-wait"); }); }); - inner.style.backgroundClip = "border-box"; </script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-001.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-001.html new file mode 100644 index 0000000..25ce061 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-001.html
@@ -0,0 +1,62 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>CSS Grid Layout Test: Changing Self-Alignment properties to interfere in Baseline Alignment</title> +<link rel="author" title="Javier Fernandez Garcia-Boente" href="mailto:jfernandez@igalia.com"> +<link rel="help" href="https://drafts.csswg.org/css-grid-1/#grid-align"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#self-alignment"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#align-self-property"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#typedef-baseline-position"> +<meta name="assert" content="Changing the 'align-self' property's value of a grid item from 'baseline' will exclude such item from its baseline context, which implies recomputing all the baseline offsets and aligning the items left in such context."> +<style> +#container { + position: relative; + display: inline-grid; + grid: 100px / 50px 50px 50px; + background: grey; + align-items: baseline; +} +#item1 { + height: 20px; + background: blue; +} +#item2 { + height: 50px; + background: green; +} +#item3 { + height: 30px; + background: red; +} +</style> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/check-layout-th.js"></script> +<script src="support/style-change.js"></script> +<script> +function runTest() { + let before = { + item1: {"data-offset-y": 30 }, + item2: {"data-offset-y": 0 }, + item3: {"data-offset-y": 20 } + }; + + let after = { + item1: {"data-offset-y": 10 }, + item2: {"data-offset-y": 50 }, + item3: {"data-offset-y": 0 } + }; + + evaluateStyleChangeMultiple("before", before); + item2.style.alignSelf = "end"; + evaluateStyleChangeMultiple("after", after); + done(); +} +</script> +<body onload="runTest()"> + <div id="container"> + <div id="item1" data-expected-width="50" data-expected-height="20" data-offset-x="0"></div> + <div id="item2" data-expected-width="50" data-expected-height="50" data-offset-x="50"></div> + <div id="item3" data-expected-width="50" data-expected-height="30" data-offset-x="100"></div> + </div> + <div id="log"></div> +</body>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-002.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-002.html new file mode 100644 index 0000000..c97be7ddb --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-002.html
@@ -0,0 +1,63 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>CSS Grid Layout Test: Changing Self-Alignment properties to interfere in Baseline Alignment</title> +<link rel="author" title="Javier Fernandez Garcia-Boente" href="mailto:jfernandez@igalia.com"> +<link rel="help" href="https://drafts.csswg.org/css-grid-1/#grid-align"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#self-alignment"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#align-self-property"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#typedef-baseline-position"> +<meta name="assert" content="Changing the 'align-self' property's value of a grid item to 'baseline' will include such item into a baseline context, which implies recomputing all the baseline offsets and aligning the items in such context."> +<style> +#container { + position: relative; + display: inline-grid; + grid: 100px / 50px 50px 50px; + background: grey; + align-items: baseline; +} +#item1 { + height: 20px; + background: blue; +} +#item2 { + height: 50px; + background: green; + align-self: center; +} +#item3 { + height: 30px; + background: red; +} +</style> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/check-layout-th.js"></script> +<script src="support/style-change.js"></script> +<script> +function runTest() { + let before = { + item1: {"data-offset-y": 10 }, + item2: {"data-offset-y": 25 }, + item3: {"data-offset-y": 0 } + }; + + let after = { + item1: {"data-offset-y": 30 }, + item2: {"data-offset-y": 0 }, + item3: {"data-offset-y": 20 } + }; + + evaluateStyleChangeMultiple("before", before); + item2.style.alignSelf = "baseline"; + evaluateStyleChangeMultiple("after", after); + done(); +} +</script> +<body onload="runTest()"> + <div id="container"> + <div id="item1" data-expected-width="50" data-expected-height="20" data-offset-x="0"></div> + <div id="item2" data-expected-width="50" data-expected-height="50" data-offset-x="50"></div> + <div id="item3" data-expected-width="50" data-expected-height="30" data-offset-x="100"></div> + </div> + <div id="log"></div> +</body>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-003.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-003.html new file mode 100644 index 0000000..bca78d7 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-003.html
@@ -0,0 +1,63 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>CSS Grid Layout Test: Changing the Self-Alignment properties to interfere in Baseline Alignment</title> +<link rel="author" title="Javier Fernandez Garcia-Boente" href="mailto:jfernandez@igalia.com"> +<link rel="help" href="https://drafts.csswg.org/css-grid-1/#grid-align"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#self-alignment"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#justify-self-property"> +<link rel="help" href="https://drafts.csswg.org/css-align/#typedef-baseline-position"> +<meta name="assert" content="Changing the justify-self' property's value of a grid item from 'baseline' will exclude such item from its baseline context, which implies recomputing all the baseline offsets and aligning the items left in such context."> +<style> +#container { + position: relative; + display: inline-grid; + grid: 50px 50px 50px / 100px; + background: grey; + justify-items: baseline; +} +#container > div { writing-mode: vertical-rl; } +#item1 { + width: 20px; + background: blue; +} +#item2 { + width: 50px; + background: green; +} +#item3 { + width: 30px; + background: red; +} +</style> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/check-layout-th.js"></script> +<script src="support/style-change.js"></script> +<script> +function runTest() { + let before = { + item1: {"data-offset-x": 30 }, + item2: {"data-offset-x": 0 }, + item3: {"data-offset-x": 20 } + }; + + let after = { + item1: {"data-offset-x": 10 }, + item2: {"data-offset-x": 50 }, + item3: {"data-offset-x": 0 } + }; + + evaluateStyleChangeMultiple("before", before); + item2.style.justifySelf = "end"; + evaluateStyleChangeMultiple("after", after); + done(); +} +</script> +<body onload="runTest()"> + <div id="container"> + <div id="item1" data-expected-width="20" data-expected-height="50" data-offset-y="0"></div> + <div id="item2" data-expected-width="50" data-expected-height="50" data-offset-y="50"></div> + <div id="item3" data-expected-width="30" data-expected-height="50" data-offset-y="100"></div> + </div> + <div id="log"></div> +</body>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-004.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-004.html new file mode 100644 index 0000000..3064f42 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-004.html
@@ -0,0 +1,64 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>CSS Grid Layout Test: Changing the Self-Alignment properties to interfere in Baseline Alignment</title> +<link rel="author" title="Javier Fernandez Garcia-Boente" href="mailto:jfernandez@igalia.com"> +<link rel="help" href="https://drafts.csswg.org/css-grid-1/#grid-align"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#self-alignment"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#justify-self-property"> +<link rel="help" href="https://drafts.csswg.org/css-align/#typedef-baseline-position"> +<meta name="assert" content="Changing the 'justify-self' property's value of a grid item to 'baseline' will include such item into a baseline context, which implies recomputing all the baseline offsets and aligning the items in such context."> +<style> +#container { + position: relative; + display: inline-grid; + grid: 50px 50px 50px / 100px; + background: grey; + justify-items: baseline; +} +#container > div { writing-mode: vertical-rl; } +#item1 { + width: 20px; + background: blue; +} +#item2 { + width: 50px; + background: green; + justify-self: center; +} +#item3 { + width: 30px; + background: red; +} +</style> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/check-layout-th.js"></script> +<script src="support/style-change.js"></script> +<script> +function runTest() { + let before = { + item1: {"data-offset-x": 10 }, + item2: {"data-offset-x": 25 }, + item3: {"data-offset-x": 0 } + }; + + let after = { + item1: {"data-offset-x": 30 }, + item2: {"data-offset-x": 0 }, + item3: {"data-offset-x": 20 } + }; + + evaluateStyleChangeMultiple("before", before); + item2.style.justifySelf = "baseline"; + evaluateStyleChangeMultiple("after", after); + done(); +} +</script> +<body onload="runTest()"> + <div id="container"> + <div id="item1" data-expected-width="20" data-expected-height="50" data-offset-y="0"></div> + <div id="item2" data-expected-width="50" data-expected-height="50" data-offset-y="50"></div> + <div id="item3" data-expected-width="30" data-expected-height="50" data-offset-y="100"></div> + </div> + <div id="log"></div> +</body>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-005.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-005.html new file mode 100644 index 0000000..550eed7 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-005.html
@@ -0,0 +1,63 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>CSS Grid Layout Test: Changing Self-Alignment properties to interfere in Baseline Alignment</title> +<link rel="author" title="Javier Fernandez Garcia-Boente" href="mailto:jfernandez@igalia.com"> +<link rel="help" href="https://drafts.csswg.org/css-grid-1/#grid-align"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#self-alignment"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#align-self-property"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#typedef-baseline-position"> +<meta name="assert" content="Changing the 'align-self' property's value of a grid item from 'baseline' will exclude such item from its baseline context, which implies recomputing all the baseline offsets and aligning the items left in such context."> +<style> +#container { + position: relative; + display: inline-grid; + grid: 100px / 50px 50px 50px; + background: grey; + align-items: baseline; + font-family: Ahem; +} +#item1 { + font-size: 20px; + background: blue; +} +#item2 { + font-size: 40px; + background: green; +} +#item3 { + font-size: 30px; + background: red; +} +</style> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/check-layout-th.js"></script> +<script src="support/style-change.js"></script> +<script> +function runTest() { + let before = { + item1: {"data-offset-y": 16 }, + item2: {"data-offset-y": 0 }, + item3: {"data-offset-y": 8 } + } + + let after = { + item1: {"data-offset-y": 8 }, + item2: {"data-offset-y": 60 }, + item3: {"data-offset-y": 0 } + } + + evaluateStyleChangeMultiple("before", before); + item2.style.alignSelf = "end"; + evaluateStyleChangeMultiple("after", after); + done(); +} +</script> +<body onload="runTest()"> + <div id="container"> + <div id="item1" data-expected-width="50" data-expected-height="20" data-offset-x="0">É</div> + <div id="item2" data-expected-width="50" data-expected-height="40" data-offset-x="50">É</div> + <div id="item3" data-expected-width="50" data-expected-height="30" data-offset-x="100">É</div> + </div> + <div id="log"></div> +</body>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-006.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-006.html new file mode 100644 index 0000000..1df78c0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-006.html
@@ -0,0 +1,64 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>CSS Grid Layout Test: Changing Self-Alignment properties to interfere in Baseline Alignment</title> +<link rel="author" title="Javier Fernandez Garcia-Boente" href="mailto:jfernandez@igalia.com"> +<link rel="help" href="https://drafts.csswg.org/css-grid-1/#grid-align"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#self-alignment"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#align-self-property"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#typedef-baseline-position"> +<meta name="assert" content="Changing the 'align-self' property's value of a grid item to 'baseline' will include such item into a baseline context, which implies recomputing all the baseline offsets and aligning the items in such context."> +<style> +#container { + position: relative; + display: inline-grid; + grid: 100px / 50px 50px 50px; + background: grey; + align-items: baseline; + font-family: Ahem; +} +#item1 { + font-size: 20px; + background: blue; +} +#item2 { + font-size: 40px; + background: green; + align-self: center; +} +#item3 { + font-size: 30px; + background: red; +} +</style> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/check-layout-th.js"></script> +<script src="support/style-change.js"></script> +<script> +function runTest() { + let before = { + item1: {"data-offset-y": 8 }, + item2: {"data-offset-y": 30 }, + item3: {"data-offset-y": 0 } + } + + let after = { + item1: {"data-offset-y": 16 }, + item2: {"data-offset-y": 0 }, + item3: {"data-offset-y": 8 } + } + + evaluateStyleChangeMultiple("before", before); + item2.style.alignSelf = "baseline"; + evaluateStyleChangeMultiple("after", after); + done(); +} +</script> +<body onload="runTest()"> + <div id="container"> + <div id="item1" data-expected-width="50" data-expected-height="20" data-offset-x="0">É</div> + <div id="item2" data-expected-width="50" data-expected-height="40" data-offset-x="50">É</div> + <div id="item3" data-expected-width="50" data-expected-height="30" data-offset-x="100">É</div> + </div> + <div id="log"></div> +</body>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-007.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-007.html new file mode 100644 index 0000000..4d0231b --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-007.html
@@ -0,0 +1,65 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>CSS Grid Layout Test: Changing the value of Self-Alignment properties</title> +<link rel="author" title="Javier Fernandez Garcia-Boente" href="mailto:jfernandez@igalia.com"> +<link rel="help" href="https://drafts.csswg.org/css-grid-1/#grid-align"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#self-alignment"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#justify-self-property"> +<link rel="help" href="https://drafts.csswg.org/css-align/#typedef-baseline-position"> +<meta name="assert" content="Changing the 'align-self' property's value of a grid item from 'baseline' will exclude such item from its baseline context, which implies recomputing all the baseline offsets and aligning the items left in such context."> +<style> +#container { + position: relative; + display: inline-grid; + grid: 50px 50px 50px / 100px; + background: grey; + justify-items: baseline; + font-family: Ahem; + text-orientation: sideways; +} +#container > div { writing-mode: vertical-lr; } +#item1 { + font-size: 20px; + background: blue; +} +#item2 { + font-size: 40px; + background: green; +} +#item3 { + font-size: 30px; + background: red; +} +</style> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/check-layout-th.js"></script> +<script src="support/style-change.js"></script> +<script> +function runTest() { + let before = { + item1: {"data-offset-x": 4 }, + item2: {"data-offset-x": 0 }, + item3: {"data-offset-x": 2 } + } + + let after = { + item1: {"data-offset-x": 2 }, + item2: {"data-offset-x": 60 }, + item3: {"data-offset-x": 0 } + } + + evaluateStyleChangeMultiple("before", before); + item2.style.justifySelf = "end"; + evaluateStyleChangeMultiple("after", after); + done(); +} +</script> +<body onload="runTest()"> + <div id="container"> + <div id="item1" data-expected-width="20" data-expected-height="50" data-offset-y="0">É</div> + <div id="item2" data-expected-width="40" data-expected-height="50" data-offset-y="50">É</div> + <div id="item3" data-expected-width="30" data-expected-height="50" data-offset-y="100">É</div> + </div> + <div id="log"></div> +</body>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-008.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-008.html new file mode 100644 index 0000000..026f035b --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-alignment-style-changes-008.html
@@ -0,0 +1,65 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>CSS Grid Layout Test: Changing the Self-Alignment properties to interfere in Baseline Alignment</title> +<link rel="author" title="Javier Fernandez Garcia-Boente" href="mailto:jfernandez@igalia.com"> +<link rel="help" href="https://drafts.csswg.org/css-grid-1/#grid-align"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#self-alignment"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#justify-self-property"> +<link rel="help" href="https://drafts.csswg.org/css-align/#typedef-baseline-position"> +<meta name="assert" content="Changing the 'justify-self' property's value of a grid item to 'baseline' will include such item into a baseline context, which implies recomputing all the baseline offsets and aligning the items in such context."> +<style> +#container { + position: relative; + display: inline-grid; + grid: 50px 50px 50px / 100px; + background: grey; + justify-items: baseline; + font-family: Ahem; +} +#container > div { writing-mode: vertical-lr; } +#item1 { + font-size: 20px; + background: blue; +} +#item2 { + font-size: 40px; + background: green; + justify-self: center; +} +#item3 { + font-size: 30px; + background: red; +} +</style> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/check-layout-th.js"></script> +<script src="support/style-change.js"></script> +<script> +function runTest() { + let before = { + item1: {"data-offset-x": 5 }, + item2: {"data-offset-x": 30 }, + item3: {"data-offset-x": 0 } + }; + + let after = { + item1: {"data-offset-x": 10 }, + item2: {"data-offset-x": 0 }, + item3: {"data-offset-x": 5 } + }; + + evaluateStyleChangeMultiple("before", before); + item2.style.justifySelf = "baseline"; + evaluateStyleChangeMultiple("after", after); + done(); +} +</script> +<body onload="runTest()"> + <div id="container"> + <div id="item1" data-expected-width="20" data-expected-height="50" data-offset-y="0">É</div> + <div id="item2" data-expected-width="40" data-expected-height="50" data-offset-y="50">É</div> + <div id="item3" data-expected-width="30" data-expected-height="50" data-offset-y="100">É</div> + </div> + <div id="log"></div> +</body>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-self-baseline-not-applied-if-sizing-cyclic-dependency-003.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-self-baseline-not-applied-if-sizing-cyclic-dependency-003.html new file mode 100644 index 0000000..5ffacfd --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/grid-self-baseline-not-applied-if-sizing-cyclic-dependency-003.html
@@ -0,0 +1,89 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>CSS Grid Layout Test: Self-Baseline alignment and sizing cyclic dependency</title> +<link rel="author" title="Javier Fernandez Garcia-Boente" href="mailto:jfernandez@igalia.com"> +<link rel="help" href="https://drafts.csswg.org/css-grid-1/#alignment"> +<link rel="help" href="https://drafts.csswg.org/css-grid-1/#column-align"> +<link rel="help" href="https://drafts.csswg.org/css-grid-1/#row-align"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#propdef-align-items"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#propdef-justify-items"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#baseline-alignment"> +<link rel="help" href="https://drafts.csswg.org/css-align-3/#valdef-justify-self-baseline"> +<link rel="stylesheet" href="../../support/grid.css"> +<link rel="stylesheet" href="../../support/alignment.css"> +<meta name="assert" content="Items not participating in baseline may later participate if there is an extra pass of the track sizing algorithm."> +<!-- https://github.com/w3c/csswg-drafts/issues/3046 --> +<style> +.grid { + position: relative; + display: inline-grid; + background: grey; + text-orientation: sideways; + font-family: Ahem; +} +.row { grid: minmax(0px, 1fr) / 50px 50px 100px } +.column { grid: 50px 50px 100px / minmax(0px, 1fr); } +.item1 { + font-size: 30px; + background: blue; +} +.item2 { + font-size: 20px; + background: red; +} +.item3 { + font-size: 80px; + background: green; +} +.height50 { height: 50px; } +.relativeHeight { height: 50%; } +.relativeWidth { width: 50%; } +</style> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/check-layout-th.js"></script> +<body onload="checkLayout('.grid')"> + +<pre>flex rows - column-axis baseline - the blue orthogonal item didn't participate in the first iteration</pre> +<div class="grid row alignItemsBaseline"> + <div class="item1 verticalLR" data-offset-x="0" data-offset-y="34" data-expected-width="50" data-expected-height="30">É</div> + <div class="item2" data-offset-x="50" data-offset-y="48" data-expected-width="50" data-expected-height="20">É</div> + <div class="item3" data-offset-x="100" data-offset-y="0" data-expected-width="100" data-expected-height="80">É</div> +</div> + +<pre>flex row - column-axis baseline - the blue relative sized item didn't participate in the first iterarion</pre> +<div class="grid row alignItemsBaseline "> + <div class="item1 relativeHeight" data-offset-x="0" data-offset-y="40" data-expected-width="50" data-expected-height="40"></div> + <div class="item2" data-offset-x="50" data-offset-y="64" data-expected-width="50" data-expected-height="20">É</div> + <div class="item3 verticalLR" data-offset-x="100" data-offset-y="0" data-expected-width="100" data-expected-height="80">É</div> +</div> + +<pre>flex row - both the blue relative sized and red orthogonal didn't participate in the first iteration</pre> +<div class="grid row alignItemsBaseline"> + <div class="item1 relativeHeight" data-offset-x="0" data-offset-y="24" data-expected-width="50" data-expected-height="40"></div> + <div class="item2 verticalLR" data-offset-x="50" data-offset-y="44" data-expected-width="50" data-expected-height="20">É</div> + <div class="item3" data-offset-x="100" data-offset-y="0" data-expected-width="100" data-expected-height="80">É</div> +</div> + +<pre>flex column - row-axis baseline - the blue orthogonal item didn't participate in the first iteration</pre> +<div class="grid column justifyItemsBaseline"> + <div class="item1" data-offset-x="16" data-offset-y="0" data-expected-width="30" data-expected-height="50">É</div> + <div class="item2 verticalLR" data-offset-x="12" data-offset-y="50" data-expected-width="20" data-expected-height="50">É</div> + <div class="item3 verticalLR" data-offset-x="0" data-offset-y="100" data-expected-width="80" data-expected-height="100">É</div> +</div> + +<pre>flex column - column-axis baseline - the blue relative sized item didn't participate in the first iterarion</pre> +<div class="grid column justifyItemsBaseline"> + <div class="item1 relativeWidth height50" data-offset-x="16" data-offset-y="0" data-expected-width="40" data-expected-height="50"></div> + <div class="item2 verticalLR" data-offset-x="12" data-offset-y="50" data-expected-width="20" data-expected-height="50">É</div> + <div class="item3 verticalLR" data-offset-x="0" data-offset-y="100" data-expected-width="80" data-expected-height="100">É</div> +</div> + +<pre>flex columns - both the blue relative sized and red orthogonal didn't participate in the first iteration</pre> +<div class="grid column justifyItemsBaseline"> + <div class="item1 relativeWidth height50" data-offset-x="16" data-offset-y="0" data-expected-width="40" data-expected-height="50"></div> + <div class="item2" data-offset-x="16" data-offset-y="50" data-expected-width="20" data-expected-height="50">É</div> + <div class="item3 verticalLR" data-offset-x="0" data-offset-y="100" data-expected-width="80" data-expected-height="100">É</div> +</div> + +</body>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/support/style-change.js b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/support/style-change.js index 5619394..766d140d2 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/support/style-change.js +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-grid/alignment/support/style-change.js
@@ -3,3 +3,12 @@ element.setAttribute(expectedProperty, expectedResult); checkLayout("." + phase, false); } +function evaluateStyleChangeMultiple(phase, expectedResult) { + for (var item in expectedResult) { + var element = document.getElementById(item); + element.className += " " + phase; + for (var key in expectedResult[item]) + element.setAttribute(key, expectedResult[item][key]); + } + checkLayout("." + phase, false); +}
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-multicol/multicol-under-vertical-rl-scroll-ref.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-multicol/multicol-under-vertical-rl-scroll-ref.html new file mode 100644 index 0000000..1a7cfb6 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-multicol/multicol-under-vertical-rl-scroll-ref.html
@@ -0,0 +1,16 @@ +<!DOCTYPE html> +<title>Multicol under vertical-rl scrolling container</title> +<p>Passes if there are two green squares</p> +<div id="scroller" style="width: 200px; height: 200px; overflow: scroll; border: 1px solid black"> + <div style="width: 580px; height: 500px; position: relative"> + <div style="position: absolute; right: 0"> + <div style="width: 80px; height: 80px; background: green"></div> + <div style="height: 20px"></div> + <div style="width: 80px; height: 80px; background: green"></div> + </div> + </div> +</div> +<script> +// Scroll all the way to the right. +scroller.scrollLeft = 800; +</script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-multicol/multicol-under-vertical-rl-scroll.html b/third_party/WebKit/LayoutTests/external/wpt/css/css-multicol/multicol-under-vertical-rl-scroll.html new file mode 100644 index 0000000..f96a26ae --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-multicol/multicol-under-vertical-rl-scroll.html
@@ -0,0 +1,11 @@ +<!DOCTYPE html> +<title>Multicol under vertical-rl scrolling container</title> +<link rel="match" href="multicol-under-vertical-rl-scroll-ref.html"> +<link rel="help" href="https://drafts.csswg.org/css-multicol"> +<p>Passes if there are two green squares</p> +<div style="width: 200px; height: 200px; overflow: scroll; writing-mode: vertical-rl; border: 1px solid black"> + <div style="columns: 2; column-gap: 20px; width: 80px; height: 180px"> + <div style="width: 160px; background: green"></div> + </div> + <div style="width: 500px; height: 500px"></div> +</div>
diff --git a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-global-expected.txt b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-global-expected.txt index 99046ce..d41b3708e 100644 --- a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-global-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-global-expected.txt
@@ -1,11 +1,10 @@ This tests verifies the hit test regions given to the compositor in the simple case where touch handles cover (or nearly cover) the entire document. It can only be run in DumpRenderTree. -document: #document scrolling (0, 0, 800, 600) -document: #document scrolling (0, 600, 785, 1400) +document: #document (0, 0, 800, 600) -html: #document scrolling (0, 0, 785, 2000) +html: #document (0, 0, 800, 600) -body: #document scrolling (5, 16, 775, 1968) +body: #document (0, 0, 800, 600) webPageOverlay: no rects
diff --git a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-many-expected.txt b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-many-expected.txt index ac27131..a89749fa 100644 --- a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-many-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-many-expected.txt
@@ -1,111 +1,8 @@ Tests that there is an upper limit on the number of hit rects generated per layer. http://crbug.com/299177. Test node has 99 children with 100 rects -Test node has 100 children with 101 rects -FAIL - got 101 rects, expected 1. -Test node has 101 children with 102 rects -FAIL - got 102 rects, expected 1. -manychildren: DIV#layer (0, 0, 290, 12) -manychildren: DIV#layer (301, 21, 7, 7) -manychildren: DIV#layer (301, 33, 7, 7) -manychildren: DIV#layer (301, 45, 7, 7) -manychildren: DIV#layer (301, 57, 7, 7) -manychildren: DIV#layer (301, 69, 7, 7) -manychildren: DIV#layer (301, 81, 7, 7) -manychildren: DIV#layer (301, 93, 7, 7) -manychildren: DIV#layer (301, 105, 7, 7) -manychildren: DIV#layer (301, 117, 7, 7) -manychildren: DIV#layer (301, 129, 7, 7) -manychildren: DIV#layer (301, 141, 7, 7) -manychildren: DIV#layer (301, 153, 7, 7) -manychildren: DIV#layer (301, 165, 7, 7) -manychildren: DIV#layer (301, 177, 7, 7) -manychildren: DIV#layer (301, 189, 7, 7) -manychildren: DIV#layer (301, 201, 7, 7) -manychildren: DIV#layer (301, 213, 7, 7) -manychildren: DIV#layer (301, 225, 7, 7) -manychildren: DIV#layer (301, 237, 7, 7) -manychildren: DIV#layer (301, 249, 7, 7) -manychildren: DIV#layer (301, 261, 7, 7) -manychildren: DIV#layer (301, 273, 7, 7) -manychildren: DIV#layer (301, 285, 7, 7) -manychildren: DIV#layer (301, 297, 7, 7) -manychildren: DIV#layer (301, 309, 7, 7) -manychildren: DIV#layer (301, 321, 7, 7) -manychildren: DIV#layer (301, 333, 7, 7) -manychildren: DIV#layer (301, 345, 7, 7) -manychildren: DIV#layer (301, 357, 7, 7) -manychildren: DIV#layer (301, 369, 7, 7) -manychildren: DIV#layer (301, 381, 7, 7) -manychildren: DIV#layer (301, 393, 7, 7) -manychildren: DIV#layer (301, 405, 7, 7) -manychildren: DIV#layer (301, 417, 7, 7) -manychildren: DIV#layer (301, 429, 7, 7) -manychildren: DIV#layer (301, 441, 7, 7) -manychildren: DIV#layer (301, 453, 7, 7) -manychildren: DIV#layer (301, 465, 7, 7) -manychildren: DIV#layer (301, 477, 7, 7) -manychildren: DIV#layer (301, 489, 7, 7) -manychildren: DIV#layer (301, 501, 7, 7) -manychildren: DIV#layer (301, 513, 7, 7) -manychildren: DIV#layer (301, 525, 7, 7) -manychildren: DIV#layer (301, 537, 7, 7) -manychildren: DIV#layer (301, 549, 7, 7) -manychildren: DIV#layer (301, 561, 7, 7) -manychildren: DIV#layer (301, 573, 7, 7) -manychildren: DIV#layer (301, 585, 7, 7) -manychildren: DIV#layer (301, 597, 7, 7) -manychildren: DIV#layer (301, 609, 7, 7) -manychildren: DIV#layer (301, 621, 7, 7) -manychildren: DIV#layer (301, 633, 7, 7) -manychildren: DIV#layer (301, 645, 7, 7) -manychildren: DIV#layer (301, 657, 7, 7) -manychildren: DIV#layer (301, 669, 7, 7) -manychildren: DIV#layer (301, 681, 7, 7) -manychildren: DIV#layer (301, 693, 7, 7) -manychildren: DIV#layer (301, 705, 7, 7) -manychildren: DIV#layer (301, 717, 7, 7) -manychildren: DIV#layer (301, 729, 7, 7) -manychildren: DIV#layer (301, 741, 7, 7) -manychildren: DIV#layer (301, 753, 7, 7) -manychildren: DIV#layer (301, 765, 7, 7) -manychildren: DIV#layer (301, 777, 7, 7) -manychildren: DIV#layer (301, 789, 7, 7) -manychildren: DIV#layer (301, 801, 7, 7) -manychildren: DIV#layer (301, 813, 7, 7) -manychildren: DIV#layer (301, 825, 7, 7) -manychildren: DIV#layer (301, 837, 7, 7) -manychildren: DIV#layer (301, 849, 7, 7) -manychildren: DIV#layer (301, 861, 7, 7) -manychildren: DIV#layer (301, 873, 7, 7) -manychildren: DIV#layer (301, 885, 7, 7) -manychildren: DIV#layer (301, 897, 7, 7) -manychildren: DIV#layer (301, 909, 7, 7) -manychildren: DIV#layer (301, 921, 7, 7) -manychildren: DIV#layer (301, 933, 7, 7) -manychildren: DIV#layer (301, 945, 7, 7) -manychildren: DIV#layer (301, 957, 7, 7) -manychildren: DIV#layer (301, 969, 7, 7) -manychildren: DIV#layer (301, 981, 7, 7) -manychildren: DIV#layer (301, 993, 7, 7) -manychildren: DIV#layer (301, 1005, 7, 7) -manychildren: DIV#layer (301, 1017, 7, 7) -manychildren: DIV#layer (301, 1029, 7, 7) -manychildren: DIV#layer (301, 1041, 7, 7) -manychildren: DIV#layer (301, 1053, 7, 7) -manychildren: DIV#layer (301, 1065, 7, 7) -manychildren: DIV#layer (301, 1077, 7, 7) -manychildren: DIV#layer (301, 1089, 7, 7) -manychildren: DIV#layer (301, 1101, 7, 7) -manychildren: DIV#layer (301, 1113, 7, 7) -manychildren: DIV#layer (301, 1125, 7, 7) -manychildren: DIV#layer (301, 1137, 7, 7) -manychildren: DIV#layer (301, 1149, 7, 7) -manychildren: DIV#layer (301, 1161, 7, 7) -manychildren: DIV#layer (301, 1173, 7, 7) -manychildren: DIV#layer (301, 1185, 7, 7) -manychildren: DIV#layer (301, 1197, 7, 7) -manychildren: DIV#layer (301, 1209, 7, 7) -manychildren: DIV#layer (301, 1221, 7, 7) +Test node has 100 children with 1 rects +Test node has 101 children with 1 rects +manychildren: DIV#layer (0, 0, 308, 1228)
diff --git a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-non-composited-scroll-expected.txt b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-non-composited-scroll-expected.txt index 896f9bd..22f1582 100644 --- a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-non-composited-scroll-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-non-composited-scroll-expected.txt
@@ -1,17 +1,20 @@ This test verifies the hit test regions given to the compositor specifically around non-composited overflow scroll elements. -scrollContent: #document scrolling (14, 63, 273, 12) +scrollContent: #document scrolling (13, 52, 290, 32) scrollContainerWithHandler: #document scrolling (13, 89, 290, 32) -nestedContent: #document scrolling (15, 148, 256, 9) +nestedContent: #document scrolling (13, 126, 290, 32) +nestedContent: #document scrolling (15, 158, 256, 2) -fixedPositionContentContainer: #document scrolling (14, 179, 273, 12) +fixedPositionContentContainer: #document scrolling (13, 168, 290, 32) fixedPositionContentContainer: #document scrolling (310, 190, 132, 12) -overflowwithhandler: #document scrolling (14, 221, 273, 20) +overflowwithhandler: #document scrolling (13, 210, 290, 32) +overflowwithhandler: #document scrolling (14, 242, 273, 6) -divInsideNonScrollableLayer: #document scrolling (14, 273, 273, 10) +divInsideNonScrollableLayer: #document scrolling (13, 252, 290, 32) +divInsideNonScrollableLayer: #document scrolling (14, 284, 273, 1) divInsideCompositedLayer: DIV#compositedLayer (0, 10, 273, 12)
diff --git a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-non-composited-scroll-overflow-with-handler-expected.txt b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-non-composited-scroll-overflow-with-handler-expected.txt index 7323ab8..5168077 100644 --- a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-non-composited-scroll-overflow-with-handler-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-non-composited-scroll-overflow-with-handler-expected.txt
@@ -1,5 +1,6 @@ -notclipped: #document scrolling (1, 51, 200, 25) +notclipped: #document scrolling (0, 0, 302, 102) -clipped: no rects +clipped: #document scrolling (0, 0, 302, 102) +clipped: #document scrolling (1, 176, 200, 25)
diff --git a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-scroll-expected.txt b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-scroll-expected.txt index a8c8042c..5d52bd4 100644 --- a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-scroll-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-scroll-expected.txt
@@ -1,20 +1,20 @@ This test verifies the hit test regions given to the compositor specifically around composited overflow scroll elements. -scrollContent: DIV#scroll1 scrolling (0, 13, 273, 12) +scrollContent: DIV#scroll1 (1, 14, 273, 12) -scrollContent5: DIV#scroll5 scrolling (0, 13, 273, 12) +scrollContent5: DIV#scroll5 (1, 14, 273, 12) scrollContent6: DIV#scroll6 scrolling[-1,-14] (0, 0, 273, 12) -nestedContent: DIV#scroll2b scrolling (0, 30, 256, 12) +nestedContent: DIV#scroll2b (1, 31, 256, 12) -overflowwithhandler: DIV#overflowwithhandler scrolling (0, 0, 256, 116) -overflowwithhandler: DIV#overflowwithhandler (0, 0, 273, 52) +overflowwithhandler: DIV#overflowwithhandler (1, 1, 256, 116) +overflowwithhandler: DIV#scroll4 (1, 11, 273, 52) -overflowwithborder: DIV#overflowwithborder (0, 0, 290, 70) -overflowwithborder: DIV#overflowwithborder scrolling (4, 4, 255, 116) +overflowwithborder: DIV#overflowwithborder (6, 6, 263, 124) +overflowwithborder: HTML (13, 365, 290, 70) withTransform: DIV#transformed (0, 0, 271, 12) -withTransform: DIV#scroll3 scrolling (0, 13, 273, 14) +withTransform: DIV#scroll3 (1, 14, 273, 14)
diff --git a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-container-expected.txt b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-container-expected.txt index a179388..b485e25 100644 --- a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-container-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-container-expected.txt
@@ -1,3 +1,3 @@ -: #document scrolling (8, 14, 54, 18) +: #document scrolling (8, 8, 100, 100)
diff --git a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-expected.txt b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-expected.txt index bf0adf9..381c8eb9 100644 --- a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-expected.txt
@@ -1,5 +1,5 @@ This tests verifies the hit test regions given to the compositor for svg elements. It can only be run in DumpRenderTree. -svgline: #document scrolling (13, 84, 22, 3) +svgline: #document scrolling (13, 80, 100, 10)
diff --git a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-image-expected.txt b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-image-expected.txt index a1836ee..b485e25 100644 --- a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-image-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-image-expected.txt
@@ -1,3 +1,3 @@ -: #document scrolling (8, 8, 20, 20) +: #document scrolling (8, 8, 100, 100)
diff --git a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-root-expected.txt b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-root-expected.txt index 267634b..22fa57e2 100644 --- a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-root-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-root-expected.txt
@@ -1,3 +1,3 @@ -: #document scrolling (9, 9, 51, 52) +: #document scrolling (8, 8, 53, 54)
diff --git a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-text-expected.txt b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-text-expected.txt index a179388..75eec0c3 100644 --- a/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-text-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/events/touch/compositor-touch-hit-rects-svg-text-expected.txt
@@ -1,3 +1,3 @@ -: #document scrolling (8, 14, 54, 18) +: #document scrolling (8, 8, 54, 1)
diff --git a/third_party/WebKit/LayoutTests/fullscreen/compositor-touch-hit-rects-fullscreen-video-controls-expected.txt b/third_party/WebKit/LayoutTests/fullscreen/compositor-touch-hit-rects-fullscreen-video-controls-expected.txt index 1f4d4f1..cd1ef64 100644 --- a/third_party/WebKit/LayoutTests/fullscreen/compositor-touch-hit-rects-fullscreen-video-controls-expected.txt +++ b/third_party/WebKit/LayoutTests/fullscreen/compositor-touch-hit-rects-fullscreen-video-controls-expected.txt
@@ -1,15 +1,11 @@ This test makes sure that touch hit rects are reported for fullscreen HTML5 video control elements even when there is a document handler. Should have single rect on document before fullscreen -handler: #document scrolling (0, 0, 800, 600) +handler: #document (0, 0, 800, 600) EVENT(webkitfullscreenchange) Should keep rect on document -handler: INPUT (0, 0, 130, 130) -handler: DIV (0, 0, 800, 600) -handler: DIV (0, 0, 800, 600) -handler: #document scrolling (0, 0, 800, 600) -handler: DIV[19,19] (19, 19, 90, 90) +handler: #document (0, 0, 800, 600) END OF TEST
diff --git a/third_party/WebKit/LayoutTests/media/encrypted-media/encrypted-media-utils.js b/third_party/WebKit/LayoutTests/media/encrypted-media/encrypted-media-utils.js index 20268e4..a059c76 100644 --- a/third_party/WebKit/LayoutTests/media/encrypted-media/encrypted-media-utils.js +++ b/third_party/WebKit/LayoutTests/media/encrypted-media/encrypted-media-utils.js
@@ -118,10 +118,18 @@ // Copied from LayoutTests/resources/js-test.js. // See it for details of why this is necessary. -function asyncGC(callback) -{ - GCController.collectAll(); - setTimeout(callback, 0); +function asyncGC(callback) { + if (!callback) { + return new Promise(resolve => asyncGC(resolve)); + } + var documentsBefore = internals.numberOfLiveDocuments(); + GCController.asyncCollectAll(function () { + var documentsAfter = internals.numberOfLiveDocuments(); + if (documentsAfter < documentsBefore) + asyncGC(callback); + else + callback(); + }); } function createGCPromise()
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-from-baseline-expected.html b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-from-baseline-expected.html new file mode 100644 index 0000000..ece7436 --- /dev/null +++ b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-from-baseline-expected.html
@@ -0,0 +1,13 @@ +<!DOCTYPE HTML> +<style> +body { + margin: 0; +} +#container { + width: 100px; + height: 100px; + background: green; +} +</style> +<p style="height: 20px">Tests invalidation on align-items style change from 'baseline'. Passes if there is no red.</p> +<div id="container"></div>
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-from-baseline-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-from-baseline-expected.txt new file mode 100644 index 0000000..4947764 --- /dev/null +++ b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-from-baseline-expected.txt
@@ -0,0 +1,44 @@ +{ + "layers": [ + { + "name": "LayoutView #document", + "bounds": [800, 600], + "drawsContent": false, + "backgroundColor": "#FFFFFF" + }, + { + "name": "Scrolling Layer", + "bounds": [800, 600], + "drawsContent": false + }, + { + "name": "Scrolling Contents Layer", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "paintInvalidations": [ + { + "object": "LayoutBlockFlow DIV class='item2'", + "rect": [50, 77, 50, 50], + "reason": "geometry" + }, + { + "object": "LayoutBlockFlow DIV class='item2'", + "rect": [50, 52, 50, 50], + "reason": "geometry" + }, + { + "object": "LayoutBlockFlow DIV class='item1'", + "rect": [0, 77, 50, 25], + "reason": "geometry" + }, + { + "object": "LayoutBlockFlow DIV class='item1'", + "rect": [0, 52, 50, 25], + "reason": "geometry" + } + ] + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-from-baseline.html b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-from-baseline.html new file mode 100644 index 0000000..34ab4ae --- /dev/null +++ b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-from-baseline.html
@@ -0,0 +1,40 @@ +<!DOCTYPE HTML> +<script src="../resources/text-based-repaint.js"></script> +<script> +function repaintTest() { + document.getElementById('container').style.alignItems = 'center'; +} +onload = runRepaintAndPixelTest; +</script> +<style> +body { + margin: 0; +} +#container { + display: inline-grid; + grid: 100px / 50px 50px; + align-items: baseline; +} +.item1 { + grid-row: 1; + grid-column: 1; + height: 25px; + align-self: baseline; + background-color: green; +} +.item2 { + grid-row: 1; + grid-column: 2; + height: 50px; + background-color: green; +} +</style> +<p style="height: 20px">Tests invalidation on align-items style change from 'baseline'. Passes if there is no red.</p> +<div style="position: absolute; z-index: -1; background: green; width: 100px; height: 100px;"> + <div style="position: absolute; top: 0px; width: 50px; height: 25px; background: red;"></div> + <div style="position: absolute; left: 50px; top: 25px; width: 50px; height: 50px; background: red;"></div> +</div> +<div id="container"> + <div class="item1"></div> + <div class="item2"></div> +</div>
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-to-baseline-expected.html b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-to-baseline-expected.html new file mode 100644 index 0000000..d329306 --- /dev/null +++ b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-to-baseline-expected.html
@@ -0,0 +1,13 @@ +<!DOCTYPE HTML> +<style> +body { + margin: 0; +} +#container { + width: 100px; + height: 100px; + background: green; +} +</style> +<p style="height: 20px">Tests invalidation on align-items style change to 'baseline'. Passes if there is no red.</p> +<div id="container"></div>
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-to-baseline-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-to-baseline-expected.txt new file mode 100644 index 0000000..4947764 --- /dev/null +++ b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-to-baseline-expected.txt
@@ -0,0 +1,44 @@ +{ + "layers": [ + { + "name": "LayoutView #document", + "bounds": [800, 600], + "drawsContent": false, + "backgroundColor": "#FFFFFF" + }, + { + "name": "Scrolling Layer", + "bounds": [800, 600], + "drawsContent": false + }, + { + "name": "Scrolling Contents Layer", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "paintInvalidations": [ + { + "object": "LayoutBlockFlow DIV class='item2'", + "rect": [50, 77, 50, 50], + "reason": "geometry" + }, + { + "object": "LayoutBlockFlow DIV class='item2'", + "rect": [50, 52, 50, 50], + "reason": "geometry" + }, + { + "object": "LayoutBlockFlow DIV class='item1'", + "rect": [0, 77, 50, 25], + "reason": "geometry" + }, + { + "object": "LayoutBlockFlow DIV class='item1'", + "rect": [0, 52, 50, 25], + "reason": "geometry" + } + ] + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-to-baseline.html b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-to-baseline.html new file mode 100644 index 0000000..be6286bf --- /dev/null +++ b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-items-change-to-baseline.html
@@ -0,0 +1,40 @@ +<!DOCTYPE HTML> +<script src="../resources/text-based-repaint.js"></script> +<script> +function repaintTest() { + document.getElementById('container').style.alignItems = 'baseline'; +} +onload = runRepaintAndPixelTest; +</script> +<style> +body { + margin: 0; +} +#container { + display: inline-grid; + grid: 100px / 50px 50px; + align-items: center; +} +.item1 { + grid-row: 1; + grid-column: 1; + height: 25px; + align-self: baseline; + background-color: green; +} +.item2 { + grid-row: 1; + grid-column: 2; + height: 50px; + background-color: green; +} +</style> +<p style="height: 20px">Tests invalidation on align-items style change to 'baseline'. Passes if there is no red.</p> +<div style="position: absolute; z-index: -1; background: green; width: 100px; height: 100px;"> + <div style="position: absolute; top: 25px; width: 50px; height: 25px; background: red;"></div> + <div style="position: absolute; left: 50px; width: 50px; height: 50px; background: red;"></div> +</div> +<div id="container"> + <div class="item1"></div> + <div class="item2"></div> +</div>
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-from-baseline-expected.html b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-from-baseline-expected.html new file mode 100644 index 0000000..075f427 --- /dev/null +++ b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-from-baseline-expected.html
@@ -0,0 +1,13 @@ +<!DOCTYPE HTML> +<style> +body { + margin: 0; +} +#container { + width: 100px; + height: 100px; + background: green; +} +</style> +<p style="height: 20px">Tests invalidation on align-self style change from 'baseline'. Passes if there is no red.</p> +<div id="container"></div>
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-from-baseline-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-from-baseline-expected.txt new file mode 100644 index 0000000..2c0fab90 --- /dev/null +++ b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-from-baseline-expected.txt
@@ -0,0 +1,44 @@ +{ + "layers": [ + { + "name": "LayoutView #document", + "bounds": [800, 600], + "drawsContent": false, + "backgroundColor": "#FFFFFF" + }, + { + "name": "Scrolling Layer", + "bounds": [800, 600], + "drawsContent": false + }, + { + "name": "Scrolling Contents Layer", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "paintInvalidations": [ + { + "object": "LayoutBlockFlow DIV class='item2'", + "rect": [50, 77, 50, 50], + "reason": "geometry" + }, + { + "object": "LayoutBlockFlow DIV class='item2'", + "rect": [50, 52, 50, 50], + "reason": "geometry" + }, + { + "object": "LayoutBlockFlow DIV class='item1'", + "rect": [0, 127, 50, 25], + "reason": "geometry" + }, + { + "object": "LayoutBlockFlow DIV class='item1'", + "rect": [0, 77, 50, 25], + "reason": "geometry" + } + ] + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-from-baseline.html b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-from-baseline.html new file mode 100644 index 0000000..7757c41 --- /dev/null +++ b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-from-baseline.html
@@ -0,0 +1,41 @@ +<!DOCTYPE HTML> +<script src="../resources/text-based-repaint.js"></script> +<script> +function repaintTest() { + document.getElementsByClassName('item1')[0].style.alignSelf = 'end'; + document.getElementsByClassName('item2')[0].style.alignSelf = 'center'; +} +onload = runRepaintAndPixelTest; +</script> +<style> +body { + margin: 0; +} +#container { + display: inline-grid; + grid: 100px / 50px 50px; +} +.item1 { + grid-row: 1; + grid-column: 1; + align-self: baseline; + height: 25px; + background-color: green; +} +.item2 { + grid-row: 1; + grid-column: 2; + align-self: baseline; + height: 50px; + background-color: green; +} +</style> +<p style="height: 20px">Tests invalidation on align-self style change from 'baseline'. Passes if there is no red.</p> +<div style="position: absolute; z-index: -1; background: green; width: 100px; height: 100px;"> + <div style="position: absolute; top: 75px; width: 50px; height: 25px; background: red;"></div> + <div style="position: absolute; left: 50px; top: 25px; width: 50px; height: 50px; background: red;"></div> +</div> +<div id="container"> + <div class="item1"></div> + <div class="item2"></div> +</div>
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-to-baseline-expected.html b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-to-baseline-expected.html new file mode 100644 index 0000000..17f56915 --- /dev/null +++ b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-to-baseline-expected.html
@@ -0,0 +1,13 @@ +<!DOCTYPE HTML> +<style> +body { + margin: 0; +} +#container { + width: 100px; + height: 100px; + background: green; +} +</style> +<p style="height: 20px">Tests invalidation on align-self style change to 'baseline'. Passes if there is no red.</p> +<div id="container"></div>
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-to-baseline-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-to-baseline-expected.txt new file mode 100644 index 0000000..2c0fab90 --- /dev/null +++ b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-to-baseline-expected.txt
@@ -0,0 +1,44 @@ +{ + "layers": [ + { + "name": "LayoutView #document", + "bounds": [800, 600], + "drawsContent": false, + "backgroundColor": "#FFFFFF" + }, + { + "name": "Scrolling Layer", + "bounds": [800, 600], + "drawsContent": false + }, + { + "name": "Scrolling Contents Layer", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "paintInvalidations": [ + { + "object": "LayoutBlockFlow DIV class='item2'", + "rect": [50, 77, 50, 50], + "reason": "geometry" + }, + { + "object": "LayoutBlockFlow DIV class='item2'", + "rect": [50, 52, 50, 50], + "reason": "geometry" + }, + { + "object": "LayoutBlockFlow DIV class='item1'", + "rect": [0, 127, 50, 25], + "reason": "geometry" + }, + { + "object": "LayoutBlockFlow DIV class='item1'", + "rect": [0, 77, 50, 25], + "reason": "geometry" + } + ] + } + ] +} +
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-to-baseline.html b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-to-baseline.html new file mode 100644 index 0000000..2da1f6e2 --- /dev/null +++ b/third_party/WebKit/LayoutTests/paint/invalidation/css-grid-layout/align-self-change-to-baseline.html
@@ -0,0 +1,41 @@ +<!DOCTYPE HTML> +<script src="../resources/text-based-repaint.js"></script> +<script> +function repaintTest() { + document.getElementsByClassName('item1')[0].style.alignSelf = 'baseline'; + document.getElementsByClassName('item2')[0].style.alignSelf = 'baseline'; +} +onload = runRepaintAndPixelTest; +</script> +<style> +body { + margin: 0; +} +#container { + display: inline-grid; + grid: 100px / 50px 50px; +} +.item1 { + grid-row: 1; + grid-column: 1; + align-self: end; + height: 25px; + background-color: green; +} +.item2 { + grid-row: 1; + grid-column: 2; + align-self: center; + height: 50px; + background-color: green; +} +</style> +<p style="height: 20px">Tests invalidation on align-self style change to 'baseline'. Passes if there is no red.</p> +<div style="position: absolute; z-index: -1; background: green; width: 100px; height: 100px;"> + <div style="position: absolute; top: 25px; width: 50px; height: 25px; background: red;"></div> + <div style="position: absolute; left: 50px; width: 50px; height: 50px; background: red;"></div> +</div> +<div id="container"> + <div class="item1"></div> + <div class="item2"></div> +</div>
diff --git a/third_party/WebKit/LayoutTests/platform/linux/fast/events/touch/compositor-touch-hit-rects-svg-container-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/fast/events/touch/compositor-touch-hit-rects-svg-container-expected.txt deleted file mode 100644 index 798c042..0000000 --- a/third_party/WebKit/LayoutTests/platform/linux/fast/events/touch/compositor-touch-hit-rects-svg-container-expected.txt +++ /dev/null
@@ -1,3 +0,0 @@ -: #document scrolling (8, 13, 54, 19) - -
diff --git a/third_party/WebKit/LayoutTests/platform/linux/fast/events/touch/compositor-touch-hit-rects-svg-text-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/fast/events/touch/compositor-touch-hit-rects-svg-text-expected.txt deleted file mode 100644 index 798c042..0000000 --- a/third_party/WebKit/LayoutTests/platform/linux/fast/events/touch/compositor-touch-hit-rects-svg-text-expected.txt +++ /dev/null
@@ -1,3 +0,0 @@ -: #document scrolling (8, 13, 54, 19) - -
diff --git a/third_party/WebKit/LayoutTests/platform/linux/virtual/android/fullscreen/compositor-touch-hit-rects-fullscreen-video-controls-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/virtual/android/fullscreen/compositor-touch-hit-rects-fullscreen-video-controls-expected.txt index 899ecd0..bdd2f7af 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/virtual/android/fullscreen/compositor-touch-hit-rects-fullscreen-video-controls-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/linux/virtual/android/fullscreen/compositor-touch-hit-rects-fullscreen-video-controls-expected.txt
@@ -1,14 +1,11 @@ This test makes sure that touch hit rects are reported for fullscreen HTML5 video control elements even when there is a document handler. Should have single rect on document before fullscreen -handler: #document scrolling (0, 0, 800, 600) +handler: #document (0, 0, 800, 600) EVENT(webkitfullscreenchange) Should report no rect or another rect which is not on the document -handler: INPUT (0, 0, 130, 130) -handler: DIV (0, 0, 800, 600) -handler: DIV (0, 0, 800, 600) -handler: DIV[19,19] (19, 19, 90, 90) +handler: no rects END OF TEST
diff --git a/third_party/WebKit/LayoutTests/storage/indexeddb/connection-leak-expected.txt b/third_party/WebKit/LayoutTests/storage/indexeddb/connection-leak-expected.txt index 9dd0cfa1..a20689cc 100644 --- a/third_party/WebKit/LayoutTests/storage/indexeddb/connection-leak-expected.txt +++ b/third_party/WebKit/LayoutTests/storage/indexeddb/connection-leak-expected.txt
@@ -25,7 +25,6 @@ db = null request = null Run GC outside of request's callback via setTimeout() -window.gc() doThirdOpen(): request = indexedDB.open(dbname, 2)
diff --git a/third_party/WebKit/LayoutTests/storage/indexeddb/connection-leak.html b/third_party/WebKit/LayoutTests/storage/indexeddb/connection-leak.html index 86db507..b0132f3c 100644 --- a/third_party/WebKit/LayoutTests/storage/indexeddb/connection-leak.html +++ b/third_party/WebKit/LayoutTests/storage/indexeddb/connection-leak.html
@@ -48,10 +48,9 @@ evalAndLog("request = null"); debug("Run GC outside of request's callback via setTimeout()"); - setTimeout( function() { - evalAndLog("window.gc()"); + asyncGC(function () { doThirdOpen(); - }, 0); + }); }; }
diff --git a/third_party/WebKit/LayoutTests/storage/indexeddb/cursor-leak.html b/third_party/WebKit/LayoutTests/storage/indexeddb/cursor-leak.html index 4c64e349..3dcd979 100644 --- a/third_party/WebKit/LayoutTests/storage/indexeddb/cursor-leak.html +++ b/third_party/WebKit/LayoutTests/storage/indexeddb/cursor-leak.html
@@ -49,10 +49,10 @@ cursorRequest = null; cursor = null; - gc(); - - shouldBeTrue("cursorObserver.wasCollected"); - finishJSTest(); + asyncGC(function () { + shouldBeTrue("cursorObserver.wasCollected"); + finishJSTest(); + }); }; }
diff --git a/third_party/WebKit/LayoutTests/storage/indexeddb/delete-closed-database-object-expected.txt b/third_party/WebKit/LayoutTests/storage/indexeddb/delete-closed-database-object-expected.txt index 1f4e7cd3..f6f14dc 100644 --- a/third_party/WebKit/LayoutTests/storage/indexeddb/delete-closed-database-object-expected.txt +++ b/third_party/WebKit/LayoutTests/storage/indexeddb/delete-closed-database-object-expected.txt
@@ -9,7 +9,6 @@ db.close() indexedDB.open(dbname) Dropping references to new connection. -gc() Open request should not receive a blocked event: indexedDB.open(dbname, 2) PASS successfullyParsed is true
diff --git a/third_party/WebKit/LayoutTests/storage/indexeddb/resources/delete-closed-database-object.js b/third_party/WebKit/LayoutTests/storage/indexeddb/resources/delete-closed-database-object.js index 32a2291..72d814b 100644 --- a/third_party/WebKit/LayoutTests/storage/indexeddb/resources/delete-closed-database-object.js +++ b/third_party/WebKit/LayoutTests/storage/indexeddb/resources/delete-closed-database-object.js
@@ -10,6 +10,15 @@ { } +function setVersion() +{ + debug("Open request should not receive a blocked event:"); + var request = evalAndLog("indexedDB.open(dbname, 2)"); + request.onerror = unexpectedErrorCallback; + request.onblocked = unexpectedBlockedCallback; + request.onsuccess = finishJSTest; +} + function openSuccess() { db = event.target.result; @@ -23,16 +32,8 @@ debug("Dropping references to new connection."); // After leaving this function, there are no remaining references to the // db, so it should get deleted. - setTimeout(setVersion, 2); + setTimeout(function () { + asyncGC(setVersion); + }, 2); }; } - -function setVersion() -{ - evalAndLog("gc()"); - debug("Open request should not receive a blocked event:"); - var request = evalAndLog("indexedDB.open(dbname, 2)"); - request.onerror = unexpectedErrorCallback; - request.onblocked = unexpectedBlockedCallback; - request.onsuccess = finishJSTest; -}
diff --git a/third_party/android_async_task/LICENSE b/third_party/android_async_task/LICENSE deleted file mode 100644 index 9c247a8..0000000 --- a/third_party/android_async_task/LICENSE +++ /dev/null
@@ -1,218 +0,0 @@ -Notice for all the files in this folder. ------------------------------------------------------------- - - - - Copyright (c) 2005-2008, The Android Open Source Project - - Licensed under the Apache License, Version 2.0 (the "License"); you may not - use this file except in compliance with the License. - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - License for the specific language governing permissions and limitations under - the License. - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2011 Google Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -
diff --git a/third_party/android_async_task/OWNERS b/third_party/android_async_task/OWNERS deleted file mode 100644 index c723862..0000000 --- a/third_party/android_async_task/OWNERS +++ /dev/null
@@ -1,5 +0,0 @@ -agrieve@chromium.org -hartmanng@chromium.org -smaier@chromium.org -torne@chromium.org -wnwen@chromium.org
diff --git a/third_party/android_async_task/README.chromium b/third_party/android_async_task/README.chromium deleted file mode 100644 index 73976851..0000000 --- a/third_party/android_async_task/README.chromium +++ /dev/null
@@ -1,22 +0,0 @@ -Name: AsyncTask -URL: https://android.googlesource.com/platform/frameworks/base/+/oreo-release/core/java/android/os/AsyncTask.java -Version: 1488a3a19d4681a41fb45570c15e14d99db1cb66 -License: Apache 2.0 -License File: LICENSE -Security Critical: yes - -Description: -This contains a copy of Android Oreo's AsyncTask.java. - -Local Modifications: -- Renamed package to org.chromium.base. -- Explicitly import android.os objects. -- Switch to using android.support.annotations (from android.support.v13). -- Added annotations to help it compile issue-free. -- Changed THREAD_POOL_EXECUTOR to use our extension of Android's - ThreadPoolExecutor (which adds information about the work queue when it fills - up) -- Added function which shuts down Android's ThreadPoolExecutor, and rerouted - runnables sent to Android's ThreadPoolExecutor to our Executor. -- Changed SERIAL_EXECUTOR to reuse the executor from android.os.AsyncTask -- Removed Params, Progress generics
diff --git a/third_party/android_async_task/java/src/org/chromium/base/AsyncTask.java b/third_party/android_async_task/java/src/org/chromium/base/AsyncTask.java deleted file mode 100644 index 616af3e..0000000 --- a/third_party/android_async_task/java/src/org/chromium/base/AsyncTask.java +++ /dev/null
@@ -1,661 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.chromium.base; - -import android.os.Binder; -import android.os.Handler; -import android.os.Process; -import android.support.annotation.MainThread; -import android.support.annotation.WorkerThread; - -import java.lang.reflect.Field; -import java.util.ArrayDeque; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Callable; -import java.util.concurrent.CancellationException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executor; -import java.util.concurrent.FutureTask; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.RejectedExecutionHandler; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * <p>AsyncTask enables proper and easy use of the UI thread. This class allows you - * to perform background operations and publish results on the UI thread without - * having to manipulate threads and/or handlers.</p> - * - * <p>AsyncTask is designed to be a helper class around {@link Thread} and {@link Handler} - * and does not constitute a generic threading framework. AsyncTasks should ideally be - * used for short operations (a few seconds at the most.) If you need to keep threads - * running for long periods of time, it is highly recommended you use the various APIs - * provided by the <code>java.util.concurrent</code> package such as {@link Executor}, - * {@link ThreadPoolExecutor} and {@link FutureTask}.</p> - * - * <p>An asynchronous task is defined by a computation that runs on a background thread and - * whose result is published on the UI thread. An asynchronous task is defined by 1 generic - * type, called <code>Result</code>, and 3 steps, called <code>onPreExecute</code>, - * <code>doInBackground</code> and <code>onPostExecute</code>.</p> - * - * <div class="special reference"> - * <h3>Developer Guides</h3> - * <p>For more information about using tasks and threads, read the - * <a href="{@docRoot}guide/components/processes-and-threads.html">Processes and - * Threads</a> developer guide.</p> - * </div> - * - * <h2>Usage</h2> - * <p>AsyncTask must be subclassed to be used. The subclass will override at least - * one method ({@link #doInBackground}), and most often will override a - * second one ({@link #onPostExecute}.)</p> - * - * <p>Here is an example of subclassing:</p> - * <pre class="prettyprint"> - * private class DownloadFilesTask extends AsyncTask<Long> { - * protected Long doInBackground() { - * int count = urls.length; - * long totalSize = 0; - * for (int i = 0; i < count; i++) { - * totalSize += Downloader.downloadFile(urls[i]); - * // Escape early if cancel() is called - * if (isCancelled()) break; - * } - * return totalSize; - * } - * - * protected void onPostExecute(Long result) { - * showDialog("Downloaded " + result + " bytes"); - * } - * } - * </pre> - * - * <p>Once created, a task is executed very simply:</p> - * <pre class="prettyprint"> - * new DownloadFilesTask().execute(url1, url2, url3); - * </pre> - * - * <h2>AsyncTask's generic types</h2> - * <p>The two types used by an asynchronous task are the following:</p> - * <ol> - * execution.</li> - * <li><code>Result</code>, the type of the result of the background - * computation.</li> - * </ol> - * <p>Not all types are always used by an asynchronous task. To mark a type as unused, - * simply use the type {@link Void}:</p> - * <pre> - * private class MyTask extends AsyncTask<Void> { ... } - * </pre> - * - * <h2>The 3 steps</h2> - * <p>When an asynchronous task is executed, the task goes through 3 steps:</p> - * <ol> - * <li>{@link #onPreExecute()}, invoked on the UI thread before the task - * is executed. This step is normally used to setup the task, for instance by - * showing a progress bar in the user interface.</li> - * <li>{@link #doInBackground}, invoked on the background thread - * immediately after {@link #onPreExecute()} finishes executing. This step is used - * to perform background computation that can take a long time.The result of the computation - * must be returned by this step and will be passed back to the last step.</li> - * <li>{@link #onPostExecute}, invoked on the UI thread after the background - * computation finishes. The result of the background computation is passed to - * this step as a parameter.</li> - * </ol> - * - * <h2>Cancelling a task</h2> - * <p>A task can be cancelled at any time by invoking {@link #cancel(boolean)}. Invoking - * this method will cause subsequent calls to {@link #isCancelled()} to return true. - * After invoking this method, {@link #onCancelled(Object)}, instead of - * {@link #onPostExecute(Object)} will be invoked after {@link #doInBackground()} returns. To ensure - * that a task is cancelled as quickly as possible, you should always check the return value of - * {@link #isCancelled()} periodically from {@link #doInBackground()}, if possible (inside a loop - * for instance.)</p> - * - * <h2>Threading rules</h2> - * <p>There are a few threading rules that must be followed for this class to - * work properly:</p> - * <ul> - * <li>The AsyncTask class must be loaded on the UI thread. This is done - * automatically as of {@link android.os.Build.VERSION_CODES#JELLY_BEAN}.</li> - * <li>The task instance must be created on the UI thread.</li> - * <li>{@link #executeOnExecutor(Executor)} must be invoked on the UI thread.</li> - * <li>Do not call {@link #onPreExecute()}, {@link #onPostExecute}, - * {@link #doInBackground} manually.</li> - * <li>The task can be executed only once (an exception will be thrown if - * a second execution is attempted.)</li> - * </ul> - * - * <h2>Memory observability</h2> - * <p>AsyncTask guarantees that all callback calls are synchronized in such a way that the following - * operations are safe without explicit synchronizations.</p> - * <ul> - * <li>Set member fields in the constructor or {@link #onPreExecute}, and refer to them - * in {@link #doInBackground}. - * <li>Set member fields in {@link #doInBackground}, and refer to them in - * {@link #onPostExecute}. - * </ul> - * - * <h2>Order of execution</h2> - * <p>When first introduced, AsyncTasks were executed serially on a single background - * thread. Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed - * to a pool of threads allowing multiple tasks to operate in parallel. Starting with - * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are executed on a single - * thread to avoid common application errors caused by parallel execution.</p> - * <p>If you truly want parallel execution, you can invoke - * {@link #executeOnExecutor(java.util.concurrent.Executor)} with - * {@link #THREAD_POOL_EXECUTOR}.</p> - */ -public abstract class AsyncTask<Result> { - private static final String TAG = "AsyncTask"; - - private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); - // We want at least 2 threads and at most 4 threads in the core pool, - // preferring to have 1 less than the CPU count to avoid saturating - // the CPU with background work - private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4)); - private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; - private static final int KEEP_ALIVE_SECONDS = 30; - - private static final ThreadFactory sThreadFactory = new ThreadFactory() { - private final AtomicInteger mCount = new AtomicInteger(1); - - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "CrAsyncTask #" + mCount.getAndIncrement()); - } - }; - - private static final BlockingQueue<Runnable> sPoolWorkQueue = - new ArrayBlockingQueue<Runnable>(128); - - /** - * An {@link Executor} that can be used to execute tasks in parallel. - */ - public static final Executor THREAD_POOL_EXECUTOR = new ChromeThreadPoolExecutor(); - - /** - * An {@link Executor} that executes tasks one at a time in serial - * order. This serialization is global to a particular process. - */ - public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); - - private static final int MESSAGE_POST_RESULT = 0x1; - private static final int MESSAGE_POST_PROGRESS = 0x2; - - private static final StealRunnableHandler STEAL_RUNNABLE_HANDLER = new StealRunnableHandler(); - - private final Callable<Result> mWorker; - private final FutureTask<Result> mFuture; - - private volatile Status mStatus = Status.PENDING; - - private final AtomicBoolean mCancelled = new AtomicBoolean(); - private final AtomicBoolean mTaskInvoked = new AtomicBoolean(); - - public static class ChromeThreadPoolExecutor extends ThreadPoolExecutor { - // May have to be lowered if we are not capturing any Runnable sources. - private static final int RUNNABLE_WARNING_COUNT = 32; - - ChromeThreadPoolExecutor() { - this(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS, - sPoolWorkQueue, sThreadFactory); - } - - @VisibleForTesting - ChromeThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, - TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) { - super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); - allowCoreThreadTimeOut(true); - } - - @SuppressWarnings("NoAndroidAsyncTaskCheck") - private static String getClassName(Runnable runnable) { - Class blamedClass = runnable.getClass(); - try { - if (blamedClass == AsyncTask.NamedFutureTask.class) { - blamedClass = ((AsyncTask.NamedFutureTask) runnable).getBlamedClass(); - } else if (blamedClass.getEnclosingClass() == android.os.AsyncTask.class) { - // This gets the AsyncTask that produced the runnable. - Field field = blamedClass.getDeclaredField("this$0"); - field.setAccessible(true); - blamedClass = field.get(runnable).getClass(); - } - } catch (NoSuchFieldException e) { - if (BuildConfig.DCHECK_IS_ON) { - throw new RuntimeException(e); - } - } catch (IllegalAccessException e) { - if (BuildConfig.DCHECK_IS_ON) { - throw new RuntimeException(e); - } - } - return blamedClass.getName(); - } - - private Map<String, Integer> getNumberOfClassNameOccurrencesInQueue() { - Map<String, Integer> counts = new HashMap<>(); - Runnable[] copiedQueue = getQueue().toArray(new Runnable[0]); - for (Runnable runnable : copiedQueue) { - String className = getClassName(runnable); - int count = counts.containsKey(className) ? counts.get(className) : 0; - counts.put(className, count + 1); - } - return counts; - } - - private String findClassNamesWithTooManyRunnables(Map<String, Integer> counts) { - // We only show the classes over RUNNABLE_WARNING_COUNT appearances so that these - // crashes group up together in the reporting dashboards. If we were to print all - // the Runnables or their counts, this would fragment the reporting, with one for - // each unique set of Runnables/counts. - StringBuilder classesWithTooManyRunnables = new StringBuilder(); - for (Map.Entry<String, Integer> entry : counts.entrySet()) { - if (entry.getValue() > RUNNABLE_WARNING_COUNT) { - classesWithTooManyRunnables.append(entry.getKey()).append(' '); - } - } - if (classesWithTooManyRunnables.length() == 0) { - return "NO CLASSES FOUND"; - } - return classesWithTooManyRunnables.toString(); - } - - @Override - public void execute(Runnable command) { - try { - super.execute(command); - } catch (RejectedExecutionException e) { - Map<String, Integer> counts = getNumberOfClassNameOccurrencesInQueue(); - - throw new RejectedExecutionException("Prominent classes in AsyncTask: " - + findClassNamesWithTooManyRunnables(counts), - e); - } - } - } - - private static class SerialExecutor implements Executor { - final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>(); - Runnable mActive; - - @Override - public synchronized void execute(final Runnable r) { - mTasks.offer(new Runnable() { - @Override - public void run() { - try { - r.run(); - } finally { - scheduleNext(); - } - } - }); - if (mActive == null) { - scheduleNext(); - } - } - - protected synchronized void scheduleNext() { - if ((mActive = mTasks.poll()) != null) { - THREAD_POOL_EXECUTOR.execute(mActive); - } - } - } - - private static class StealRunnableHandler implements RejectedExecutionHandler { - @Override - public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { - THREAD_POOL_EXECUTOR.execute(r); - } - } - - /** - * Indicates the current status of the task. Each status will be set only once - * during the lifetime of a task. - */ - public enum Status { - /** - * Indicates that the task has not been executed yet. - */ - PENDING, - /** - * Indicates that the task is running. - */ - RUNNING, - /** - * Indicates that {@link AsyncTask#onPostExecute} has finished. - */ - FINISHED, - } - - @SuppressWarnings("NoAndroidAsyncTaskCheck") - public static void takeOverAndroidThreadPool() { - ThreadPoolExecutor exec = (ThreadPoolExecutor) android.os.AsyncTask.THREAD_POOL_EXECUTOR; - exec.setRejectedExecutionHandler(STEAL_RUNNABLE_HANDLER); - exec.shutdown(); - } - - /** - * Creates a new asynchronous task. This constructor must be invoked on the UI thread. - */ - public AsyncTask() { - mWorker = new Callable<Result>() { - @Override - public Result call() throws Exception { - mTaskInvoked.set(true); - Result result = null; - try { - Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); - result = doInBackground(); - Binder.flushPendingCommands(); - } catch (Throwable tr) { - mCancelled.set(true); - throw tr; - } finally { - postResult(result); - } - return result; - } - }; - - mFuture = new NamedFutureTask(mWorker); - } - - private void postResultIfNotInvoked(Result result) { - final boolean wasTaskInvoked = mTaskInvoked.get(); - if (!wasTaskInvoked) { - postResult(result); - } - } - - private void postResult(Result result) { - ThreadUtils.postOnUiThread(() -> { finish(result); }); - } - - /** - * Returns the current status of this task. - * - * @return The current status. - */ - public final Status getStatus() { - return mStatus; - } - - /** - * Override this method to perform a computation on a background thread. - * - * @return A result, defined by the subclass of this task. - * - * @see #onPreExecute() - * @see #onPostExecute - */ - @WorkerThread - protected abstract Result doInBackground(); - - /** - * Runs on the UI thread before {@link #doInBackground}. - * - * @see #onPostExecute - * @see #doInBackground - */ - @MainThread - protected void onPreExecute() {} - - /** - * <p>Runs on the UI thread after {@link #doInBackground}. The - * specified result is the value returned by {@link #doInBackground}.</p> - * - * <p>This method won't be invoked if the task was cancelled.</p> - * - * @param result The result of the operation computed by {@link #doInBackground}. - * - * @see #onPreExecute - * @see #doInBackground - * @see #onCancelled(Object) - */ - @SuppressWarnings({"UnusedDeclaration"}) - @MainThread - protected void onPostExecute(Result result) {} - - /** - * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and - * {@link #doInBackground()} has finished.</p> - * - * <p>The default implementation simply invokes {@link #onCancelled()} and - * ignores the result. If you write your own implementation, do not call - * <code>super.onCancelled(result)</code>.</p> - * - * @param result The result, if any, computed in - * {@link #doInBackground()}, can be null - * - * @see #cancel(boolean) - * @see #isCancelled() - */ - @SuppressWarnings({"UnusedParameters"}) - @MainThread - protected void onCancelled(Result result) { - onCancelled(); - } - - /** - * <p>Applications should preferably override {@link #onCancelled(Object)}. - * This method is invoked by the default implementation of - * {@link #onCancelled(Object)}.</p> - * - * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and - * {@link #doInBackground()} has finished.</p> - * - * @see #onCancelled(Object) - * @see #cancel(boolean) - * @see #isCancelled() - */ - @MainThread - protected void onCancelled() {} - - /** - * Returns <tt>true</tt> if this task was cancelled before it completed - * normally. If you are calling {@link #cancel(boolean)} on the task, - * the value returned by this method should be checked periodically from - * {@link #doInBackground()} to end the task as soon as possible. - * - * @return <tt>true</tt> if task was cancelled before it completed - * - * @see #cancel(boolean) - */ - public final boolean isCancelled() { - return mCancelled.get(); - } - - /** - * <p>Attempts to cancel execution of this task. This attempt will - * fail if the task has already completed, already been cancelled, - * or could not be cancelled for some other reason. If successful, - * and this task has not started when <tt>cancel</tt> is called, - * this task should never run. If the task has already started, - * then the <tt>mayInterruptIfRunning</tt> parameter determines - * whether the thread executing this task should be interrupted in - * an attempt to stop the task.</p> - * - * <p>Calling this method will result in {@link #onCancelled(Object)} being - * invoked on the UI thread after {@link #doInBackground()} - * returns. Calling this method guarantees that {@link #onPostExecute(Object)} - * is never invoked. After invoking this method, you should check the - * value returned by {@link #isCancelled()} periodically from - * {@link #doInBackground()} to finish the task as early as - * possible.</p> - * - * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this - * task should be interrupted; otherwise, in-progress tasks are allowed - * to complete. - * - * @return <tt>false</tt> if the task could not be cancelled, - * typically because it has already completed normally; - * <tt>true</tt> otherwise - * - * @see #isCancelled() - * @see #onCancelled(Object) - */ - public final boolean cancel(boolean mayInterruptIfRunning) { - mCancelled.set(true); - return mFuture.cancel(mayInterruptIfRunning); - } - - /** - * Waits if necessary for the computation to complete, and then - * retrieves its result. - * - * TODO(smaier): Don't inline so that stack traces can be read easily for tracing once in base/. - * - * @return The computed result. - * - * @throws CancellationException If the computation was cancelled. - * @throws ExecutionException If the computation threw an exception. - * @throws InterruptedException If the current thread was interrupted - * while waiting. - */ - public final Result get() throws InterruptedException, ExecutionException { - Result r; - if (getStatus() != Status.FINISHED && ThreadUtils.runningOnUiThread()) { - StackTraceElement[] stackTrace = new Exception().getStackTrace(); - String caller = ""; - if (stackTrace.length > 1) { - caller = stackTrace[1].getClassName() + '.' + stackTrace[1].getMethodName() + '.'; - } - try (TraceEvent e = TraceEvent.scoped(caller + "AsyncTask.get")) { - r = mFuture.get(); - } - } else { - r = mFuture.get(); - } - return r; - } - - /** - * Waits if necessary for at most the given time for the computation - * to complete, and then retrieves its result. - * - * @param timeout Time to wait before cancelling the operation. - * @param unit The time unit for the timeout. - * - * @return The computed result. - * - * @throws CancellationException If the computation was cancelled. - * @throws ExecutionException If the computation threw an exception. - * @throws InterruptedException If the current thread was interrupted - * while waiting. - * @throws TimeoutException If the wait timed out. - */ - public final Result get(long timeout, TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException { - return mFuture.get(timeout, unit); - } - - /** - * Executes the task with the specified parameters. The task returns - * itself (this) so that the caller can keep a reference to it. - * - * <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to - * allow multiple tasks to run in parallel on a pool of threads managed by - * AsyncTask, however you can also use your own {@link Executor} for custom - * behavior. - * - * <p><em>Warning:</em> Allowing multiple tasks to run in parallel from - * a thread pool is generally <em>not</em> what one wants, because the order - * of their operation is not defined. For example, if these tasks are used - * to modify any state in common (such as writing a file due to a button click), - * there are no guarantees on the order of the modifications. - * Without careful work it is possible in rare cases for the newer version - * of the data to be over-written by an older one, leading to obscure data - * loss and stability issues. Such changes are best - * executed in serial; to guarantee such work is serialized regardless of - * platform version you can use this function with {@link #SERIAL_EXECUTOR}. - * - * <p>This method must be invoked on the UI thread. - * - * @param exec The executor to use. {@link #THREAD_POOL_EXECUTOR} is available as a - * convenient process-wide thread pool for tasks that are loosely coupled. - * - * @return This instance of AsyncTask. - * - * @throws IllegalStateException If {@link #getStatus()} returns either - * {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}. - */ - @SuppressWarnings({"MissingCasesInEnumSwitch"}) - @MainThread - public final AsyncTask<Result> executeOnExecutor(Executor exec) { - if (mStatus != Status.PENDING) { - switch (mStatus) { - case RUNNING: - throw new IllegalStateException("Cannot execute task:" - + " the task is already running."); - case FINISHED: - throw new IllegalStateException("Cannot execute task:" - + " the task has already been executed " - + "(a task can be executed only once)"); - } - } - - mStatus = Status.RUNNING; - - onPreExecute(); - - exec.execute(mFuture); - - return this; - } - - private void finish(Result result) { - if (isCancelled()) { - onCancelled(result); - } else { - onPostExecute(result); - } - mStatus = Status.FINISHED; - } - - private class NamedFutureTask extends FutureTask<Result> { - NamedFutureTask(Callable<Result> c) { - super(c); - } - - Class getBlamedClass() { - return AsyncTask.this.getClass(); - } - - @Override - protected void done() { - try { - postResultIfNotInvoked(get()); - } catch (InterruptedException e) { - android.util.Log.w(TAG, e); - } catch (ExecutionException e) { - throw new RuntimeException( - "An error occurred while executing doInBackground()", e.getCause()); - } catch (CancellationException e) { - postResultIfNotInvoked(null); - } - } - } -}
diff --git a/third_party/blink/public/platform/web_input_event.h b/third_party/blink/public/platform/web_input_event.h index 3c6b089..3f54e7b 100644 --- a/third_party/blink/public/platform/web_input_event.h +++ b/third_party/blink/public/platform/web_input_event.h
@@ -162,12 +162,14 @@ // because it may still turn into a GestureDoubleTap. kGestureTapUnconfirmed, - // Double-tap is two single-taps spread apart in time, like a double-click. - // This event is only sent on desktop pages viewed on an Android phone, and - // is always preceded by GestureTapUnconfirmed. It's an instruction to - // Blink to perform a PageScaleAnimation zoom onto the double-tapped - // content. (It's treated differently from GestureTap with tapCount=2, - // which can also happen.) + // On Android, double-tap is two single-taps spread apart in time, like a + // double-click. This event is only sent on desktop pages, and is always + // preceded by GestureTapUnconfirmed. It's an instruction to Blink to + // perform a PageScaleAnimation zoom onto the double-tapped content. (It's + // treated differently from GestureTap with tapCount=2, which can also + // happen.) + // On desktop, this event may be used for a double-tap with two fingers on + // a touchpad, as the desired effect is similar to Android's double-tap. kGestureDoubleTap, kGestureTypeLast = kGestureDoubleTap,
diff --git a/third_party/blink/renderer/bindings/core/v8/v8_script_runner.cc b/third_party/blink/renderer/bindings/core/v8/v8_script_runner.cc index 3ef6240..74a15a6d 100644 --- a/third_party/blink/renderer/bindings/core/v8/v8_script_runner.cc +++ b/third_party/blink/renderer/bindings/core/v8/v8_script_runner.cc
@@ -278,10 +278,14 @@ v8::Isolate::SafeForTerminationScope safe_for_termination(isolate); v8::MicrotasksScope microtasks_scope(isolate, v8::MicrotasksScope::kRunMicrotasks); + v8::Local<v8::String> script_url; + if (!script_name->ToString(isolate->GetCurrentContext()) + .ToLocal(&script_url)) + return result; + // ToCoreString here should be zero copy due to externalized string // unpacked. - String script_url = ToCoreString(script_name->ToString(isolate)); - probe::ExecuteScript probe(context, script_url); + probe::ExecuteScript probe(context, ToCoreString(script_url)); result = script->Run(isolate->GetCurrentContext()); }
diff --git a/third_party/blink/renderer/core/css/css_basic_shape_values.cc b/third_party/blink/renderer/core/css/css_basic_shape_values.cc index 5a5d1e0..28776fe 100644 --- a/third_party/blink/renderer/core/css/css_basic_shape_values.cc +++ b/third_party/blink/renderer/core/css/css_basic_shape_values.cc
@@ -236,8 +236,8 @@ "polygon string openings should be the same length"); // Compute the required capacity in advance to reduce allocations. - size_t length = sizeof(kEvenOddOpening) - 1; - for (size_t i = 0; i < points.size(); i += 2) { + wtf_size_t length = sizeof(kEvenOddOpening) - 1; + for (wtf_size_t i = 0; i < points.size(); i += 2) { if (i) length += (sizeof(kCommaSeparator) - 1); // add length of two strings, plus one for the space separator. @@ -250,7 +250,7 @@ else result.Append(kNonZeroOpening); - for (size_t i = 0; i < points.size(); i += 2) { + for (wtf_size_t i = 0; i < points.size(); i += 2) { if (i) result.Append(kCommaSeparator); result.Append(points[i]); @@ -266,7 +266,7 @@ Vector<String> points; points.ReserveInitialCapacity(values_.size()); - for (size_t i = 0; i < values_.size(); ++i) + for (wtf_size_t i = 0; i < values_.size(); ++i) points.push_back(values_.at(i)->CssText()); return BuildPolygonString(wind_rule_, points); @@ -353,7 +353,7 @@ result.Append(separator); result.Append(corners_separator); - for (size_t i = 0; i < horizontal_radii.size(); ++i) { + for (wtf_size_t i = 0; i < horizontal_radii.size(); ++i) { result.Append(separator); result.Append(horizontal_radii[i]); } @@ -361,7 +361,7 @@ result.Append(separator); result.Append('/'); - for (size_t i = 0; i < vertical_radii.size(); ++i) { + for (wtf_size_t i = 0; i < vertical_radii.size(); ++i) { result.Append(separator); result.Append(vertical_radii[i]); }
diff --git a/third_party/blink/renderer/core/css/css_calculation_value_test.cc b/third_party/blink/renderer/core/css/css_calculation_value_test.cc index 79ed2a91..6a7376f 100644 --- a/third_party/blink/renderer/core/css/css_calculation_value_test.cc +++ b/third_party/blink/renderer/core/css/css_calculation_value_test.cc
@@ -69,7 +69,7 @@ } bool LengthArraysEqual(CSSLengthArray& a, CSSLengthArray& b) { - for (size_t i = 0; i < CSSPrimitiveValue::kLengthUnitTypeCount; ++i) { + for (wtf_size_t i = 0; i < CSSPrimitiveValue::kLengthUnitTypeCount; ++i) { if (a.values.at(i) != b.values.at(i)) return false; }
diff --git a/third_party/blink/renderer/core/css/css_gradient_value.cc b/third_party/blink/renderer/core/css/css_gradient_value.cc index 44f7f400..8e7d83f 100644 --- a/third_party/blink/renderer/core/css/css_gradient_value.cc +++ b/third_party/blink/renderer/core/css/css_gradient_value.cc
@@ -210,12 +210,12 @@ int index_offset = 0; // The first and the last color stops cannot be color hints. - for (size_t i = 1; i < css_gradient_stops.size() - 1; ++i) { + for (wtf_size_t i = 1; i < css_gradient_stops.size() - 1; ++i) { if (!css_gradient_stops[i].IsHint()) continue; // The current index of the stops vector. - size_t x = i + index_offset; + wtf_size_t x = i + index_offset; DCHECK_GE(x, 1u); // offsetLeft offset offsetRight @@ -361,7 +361,7 @@ DCHECK_GT(span, 0); - for (size_t i = 0; i < stops.size(); ++i) { + for (wtf_size_t i = 0; i < stops.size(); ++i) { const float normalized_offset = (stops[i].offset - first_offset) / span; // stop offsets should be monotonically increasing in [0 , 1] @@ -381,7 +381,7 @@ void ClampNegativeOffsets(Vector<GradientStop>& stops) { float last_negative_offset = 0; - for (size_t i = 0; i < stops.size(); ++i) { + for (wtf_size_t i = 0; i < stops.size(); ++i) { const float current_offset = stops[i].offset; if (current_offset >= 0) { if (i > 0) { @@ -464,7 +464,7 @@ return; } - size_t num_stops = stops_.size(); + wtf_size_t num_stops = stops_.size(); Vector<GradientStop> stops(num_stops); @@ -485,7 +485,7 @@ } bool has_hints = false; - for (size_t i = 0; i < num_stops; ++i) { + for (wtf_size_t i = 0; i < num_stops; ++i) { const CSSGradientColorStop& stop = stops_[i]; if (stop.IsHint()) @@ -530,7 +530,7 @@ // of any color-stop before it in the list, its position is changed to be // equal to the largest specified position of any color-stop before it. if (stops[i].specified && i > 0) { - size_t prev_specified_index; + wtf_size_t prev_specified_index; for (prev_specified_index = i - 1; prev_specified_index; --prev_specified_index) { if (stops[prev_specified_index].specified) @@ -550,15 +550,15 @@ // are evenly spaced between the preceding and following color-stops with // positions. if (num_stops > 2) { - size_t unspecified_run_start = 0; + wtf_size_t unspecified_run_start = 0; bool in_unspecified_run = false; - for (size_t i = 0; i < num_stops; ++i) { + for (wtf_size_t i = 0; i < num_stops; ++i) { if (!stops[i].specified && !in_unspecified_run) { unspecified_run_start = i; in_unspecified_run = true; } else if (stops[i].specified && in_unspecified_run) { - size_t unspecified_run_end = i; + wtf_size_t unspecified_run_end = i; if (unspecified_run_start < unspecified_run_end) { float last_specified_offset = stops[unspecified_run_start - 1].offset; @@ -566,7 +566,8 @@ float delta = (next_specified_offset - last_specified_offset) / (unspecified_run_end - unspecified_run_start + 1); - for (size_t j = unspecified_run_start; j < unspecified_run_end; ++j) + for (wtf_size_t j = unspecified_run_start; j < unspecified_run_end; + ++j) stops[j].offset = last_specified_offset + (j - unspecified_run_start + 1) * delta; }
diff --git a/third_party/blink/renderer/core/css/css_image_set_value.cc b/third_party/blink/renderer/core/css/css_image_set_value.cc index a5d7fff..879635b 100644 --- a/third_party/blink/renderer/core/css/css_image_set_value.cc +++ b/third_party/blink/renderer/core/css/css_image_set_value.cc
@@ -50,8 +50,8 @@ CSSImageSetValue::~CSSImageSetValue() = default; void CSSImageSetValue::FillImageSet() { - size_t length = this->length(); - size_t i = 0; + wtf_size_t length = this->length(); + wtf_size_t i = 0; while (i < length) { const CSSImageValue& image_value = ToCSSImageValue(Item(i)); String image_url = image_value.Url(); @@ -81,8 +81,8 @@ CSSImageSetValue::ImageWithScale CSSImageSetValue::BestImageForScaleFactor( float scale_factor) { ImageWithScale image; - size_t number_of_images = images_in_set_.size(); - for (size_t i = 0; i < number_of_images; ++i) { + wtf_size_t number_of_images = images_in_set_.size(); + for (wtf_size_t i = 0; i < number_of_images; ++i) { image = images_in_set_.at(i); if (image.scale_factor >= scale_factor) return image; @@ -145,8 +145,8 @@ StringBuilder result; result.Append("-webkit-image-set("); - size_t length = this->length(); - size_t i = 0; + wtf_size_t length = this->length(); + wtf_size_t i = 0; while (i < length) { if (i > 0) result.Append(", ");
diff --git a/third_party/blink/renderer/core/css/css_keyframes_rule.cc b/third_party/blink/renderer/core/css/css_keyframes_rule.cc index 1a3e9b7..4a7b8e2e 100644 --- a/third_party/blink/renderer/core/css/css_keyframes_rule.cc +++ b/third_party/blink/renderer/core/css/css_keyframes_rule.cc
@@ -63,9 +63,9 @@ std::unique_ptr<Vector<double>> keys = CSSParser::ParseKeyframeKeyList(key); if (!keys) return -1; - for (size_t i = keyframes_.size(); i--;) { + for (wtf_size_t i = keyframes_.size(); i--;) { if (keyframes_[i]->Keys() == *keys) - return i; + return static_cast<int>(i); } return -1; }
diff --git a/third_party/blink/renderer/core/css/css_paint_value.cc b/third_party/blink/renderer/core/css/css_paint_value.cc index 78a4816..d97f41b 100644 --- a/third_party/blink/renderer/core/css/css_paint_value.cc +++ b/third_party/blink/renderer/core/css/css_paint_value.cc
@@ -85,7 +85,7 @@ parsed_input_arguments_ = new CSSStyleValueVector(); - for (size_t i = 0; i < argument_variable_data_.size(); ++i) { + for (wtf_size_t i = 0; i < argument_variable_data_.size(); ++i) { // If we are parsing a paint() function, we must be a secure context. DCHECK_EQ(SecureContextMode::kSecureContext, document.GetSecureContextMode());
diff --git a/third_party/blink/renderer/core/css/css_property_value_set.cc b/third_party/blink/renderer/core/css/css_property_value_set.cc index 1af565c..25f4878 100644 --- a/third_party/blink/renderer/core/css/css_property_value_set.cc +++ b/third_party/blink/renderer/core/css/css_property_value_set.cc
@@ -41,7 +41,7 @@ namespace blink { -static size_t SizeForImmutableCSSPropertyValueSetWithPropertyCount( +static wtf_size_t SizeForImmutableCSSPropertyValueSetWithPropertyCount( unsigned count) { return sizeof(ImmutableCSSPropertyValueSet) - sizeof(void*) + sizeof(Member<CSSValue>) * count + @@ -634,7 +634,7 @@ id, property); }); - return (it == end) ? -1 : it - begin; + return (it == end) ? -1 : static_cast<int>(it - begin); } template CORE_EXPORT int MutableCSSPropertyValueSet::FindPropertyIndex( CSSPropertyID) const;
diff --git a/third_party/blink/renderer/core/css/css_selector.h b/third_party/blink/renderer/core/css/css_selector.h index 515b466..ff52599 100644 --- a/third_party/blink/renderer/core/css/css_selector.h +++ b/third_party/blink/renderer/core/css/css_selector.h
@@ -461,7 +461,7 @@ } inline bool CSSSelector::IsASCIILower(const AtomicString& value) { - for (size_t i = 0; i < value.length(); ++i) { + for (wtf_size_t i = 0; i < value.length(); ++i) { if (IsASCIIUpper(value[i])) return false; }
diff --git a/third_party/blink/renderer/core/css/css_selector_list.cc b/third_party/blink/renderer/core/css/css_selector_list.cc index 3f475853..ac9ac12e 100644 --- a/third_party/blink/renderer/core/css/css_selector_list.cc +++ b/third_party/blink/renderer/core/css/css_selector_list.cc
@@ -145,8 +145,8 @@ const CSSSelector* selector_to_expand_begin = selector_boundaries[i]; const CSSSelector* selector_to_expand_end = selector_boundaries[i + 1]; - size_t selector_to_expand_length = - selector_to_expand_end - selector_to_expand_begin; + unsigned selector_to_expand_length = + static_cast<unsigned>(selector_to_expand_end - selector_to_expand_begin); const CSSSelector* simple_selector = selector_to_expand_begin; while (simple_selector->GetPseudoType() != CSSSelector::kPseudoMatches && @@ -159,10 +159,11 @@ std::vector<const CSSSelector*> selector_arg_boundaries = SelectorBoundaries(*simple_selector->SelectorList()); - size_t num_args = selector_arg_boundaries.size() - 1; + wtf_size_t num_args = + SafeCast<wtf_size_t>(selector_arg_boundaries.size()) - 1; unsigned other_selectors_length = original_length - selector_to_expand_length; - unsigned expanded_selector_list_length = + wtf_size_t expanded_selector_list_length = (selector_to_expand_length - 1) * num_args + inner_selector_length + other_selectors_length; @@ -181,7 +182,7 @@ CSSSelector* destination = list.selector_array_; AddToList(destination, selector_boundaries[0], selector_to_expand_begin); - for (size_t i = 0; i < num_args; ++i) { + for (wtf_size_t i = 0; i < num_args; ++i) { AddToList(destination, selector_to_expand_begin, simple_selector); AddToList(destination, selector_arg_boundaries[i], selector_arg_boundaries[i + 1], simple_selector); @@ -243,7 +244,7 @@ CSSSelectorList CSSSelectorList::AdoptSelectorVector( Vector<std::unique_ptr<CSSParserSelector>>& selector_vector) { size_t flattened_size = 0; - for (size_t i = 0; i < selector_vector.size(); ++i) { + for (wtf_size_t i = 0; i < selector_vector.size(); ++i) { for (CSSParserSelector* selector = selector_vector[i].get(); selector; selector = selector->TagHistory()) ++flattened_size; @@ -255,8 +256,8 @@ WTF::Partitions::FastMalloc(WTF::Partitions::ComputeAllocationSize( flattened_size, sizeof(CSSSelector)), kCSSSelectorTypeName)); - size_t array_index = 0; - for (size_t i = 0; i < selector_vector.size(); ++i) { + wtf_size_t array_index = 0; + for (wtf_size_t i = 0; i < selector_vector.size(); ++i) { CSSParserSelector* current = selector_vector[i].get(); while (current) { // Move item from the parser selector vector into selector_array_ without @@ -299,7 +300,7 @@ CSSSelector* current = selector_array_; while (!current->IsLastInSelectorList()) ++current; - return (current - selector_array_) + 1; + return static_cast<unsigned>(current - selector_array_) + 1; } void CSSSelectorList::DeleteSelectors() {
diff --git a/third_party/blink/renderer/core/css/css_selector_list.h b/third_party/blink/renderer/core/css/css_selector_list.h index de61b99..db3b8b8 100644 --- a/third_party/blink/renderer/core/css/css_selector_list.h +++ b/third_party/blink/renderer/core/css/css_selector_list.h
@@ -105,15 +105,15 @@ bool HasOneSelector() const { return selector_array_ && !Next(*selector_array_); } - const CSSSelector& SelectorAt(size_t index) const { + const CSSSelector& SelectorAt(wtf_size_t index) const { return selector_array_[index]; } - size_t SelectorIndex(const CSSSelector& selector) const { - return &selector - selector_array_; + wtf_size_t SelectorIndex(const CSSSelector& selector) const { + return static_cast<wtf_size_t>(&selector - selector_array_); } - size_t IndexOfNextSelectorAfter(size_t index) const { + wtf_size_t IndexOfNextSelectorAfter(wtf_size_t index) const { const CSSSelector& current = SelectorAt(index); const CSSSelector* next = this->Next(current); if (!next)
diff --git a/third_party/blink/renderer/core/css/css_syntax_descriptor.cc b/third_party/blink/renderer/core/css/css_syntax_descriptor.cc index 136020d..a60e1327 100644 --- a/third_party/blink/renderer/core/css/css_syntax_descriptor.cc +++ b/third_party/blink/renderer/core/css/css_syntax_descriptor.cc
@@ -18,14 +18,14 @@ namespace blink { -void ConsumeWhitespace(const String& string, size_t& offset) { +void ConsumeWhitespace(const String& string, wtf_size_t& offset) { while (IsHTMLSpace(string[offset])) offset++; } bool ConsumeCharacterAndWhitespace(const String& string, char character, - size_t& offset) { + wtf_size_t& offset) { if (string[offset] != character) return false; offset++; @@ -68,11 +68,11 @@ } bool ConsumeSyntaxType(const String& input, - size_t& offset, + wtf_size_t& offset, CSSSyntaxType& type) { DCHECK_EQ(input[offset], '<'); offset++; - size_t type_start = offset; + wtf_size_t type_start = offset; while (offset < input.length() && input[offset] != '>') offset++; if (offset == input.length()) @@ -84,8 +84,10 @@ return true; } -bool ConsumeSyntaxIdent(const String& input, size_t& offset, String& ident) { - size_t ident_start = offset; +bool ConsumeSyntaxIdent(const String& input, + wtf_size_t& offset, + String& ident) { + wtf_size_t ident_start = offset; while (IsNameCodePoint(input[offset])) offset++; if (offset == ident_start) @@ -95,7 +97,7 @@ } CSSSyntaxDescriptor::CSSSyntaxDescriptor(const String& input) { - size_t offset = 0; + wtf_size_t offset = 0; ConsumeWhitespace(input, offset); if (ConsumeCharacterAndWhitespace(input, '*', offset)) {
diff --git a/third_party/blink/renderer/core/css/css_value_list.cc b/third_party/blink/renderer/core/css/css_value_list.cc index 4cb3feb6..1e02ae2 100644 --- a/third_party/blink/renderer/core/css/css_value_list.cc +++ b/third_party/blink/renderer/core/css/css_value_list.cc
@@ -57,7 +57,7 @@ } bool CSSValueList::HasValue(const CSSValue& val) const { - for (size_t index = 0; index < values_.size(); index++) { + for (wtf_size_t index = 0; index < values_.size(); index++) { const Member<const CSSValue>& value = values_.at(index); if (value && *value == val) { return true;
diff --git a/third_party/blink/renderer/core/css/css_value_list.h b/third_party/blink/renderer/core/css/css_value_list.h index d1c0b3d..085c2021 100644 --- a/third_party/blink/renderer/core/css/css_value_list.h +++ b/third_party/blink/renderer/core/css/css_value_list.h
@@ -54,8 +54,8 @@ const_iterator begin() const { return values_.begin(); } const_iterator end() const { return values_.end(); } - size_t length() const { return values_.size(); } - const CSSValue& Item(size_t index) const { return *values_[index]; } + wtf_size_t length() const { return values_.size(); } + const CSSValue& Item(wtf_size_t index) const { return *values_[index]; } void Append(const CSSValue& value) { values_.push_back(value); } bool RemoveAll(const CSSValue&);
diff --git a/third_party/blink/renderer/core/css/cssom/css_math_product.cc b/third_party/blink/renderer/core/css/cssom/css_math_product.cc index 80a528e8..88a6435c 100644 --- a/third_party/blink/renderer/core/css/cssom/css_math_product.cc +++ b/third_party/blink/renderer/core/css/cssom/css_math_product.cc
@@ -89,7 +89,7 @@ NumericValues()[0]->ToCalcExpressionNode(), NumericValues()[1]->ToCalcExpressionNode(), kCalcMultiply); - for (size_t i = 2; i < NumericValues().size(); i++) { + for (wtf_size_t i = 2; i < NumericValues().size(); i++) { node = CSSCalcValue::CreateExpressionNode( node, NumericValues()[i]->ToCalcExpressionNode(), kCalcMultiply); } @@ -107,7 +107,7 @@ DCHECK(!values.IsEmpty()); values[0]->BuildCSSText(Nested::kYes, ParenLess::kNo, result); - for (size_t i = 1; i < values.size(); i++) { + for (wtf_size_t i = 1; i < values.size(); i++) { const auto& arg = *values[i]; if (arg.GetType() == CSSStyleValue::kInvertType) { result.Append(" / ");
diff --git a/third_party/blink/renderer/core/css/cssom/css_math_sum.cc b/third_party/blink/renderer/core/css/cssom/css_math_sum.cc index 615a96f..b468e1d7 100644 --- a/third_party/blink/renderer/core/css/cssom/css_math_sum.cc +++ b/third_party/blink/renderer/core/css/cssom/css_math_sum.cc
@@ -84,7 +84,7 @@ // Collect like-terms for (const auto& term : child_sum->terms) { - size_t index = sum.terms.Find(UnitMapComparator{term}); + wtf_size_t index = sum.terms.Find(UnitMapComparator{term}); if (index == kNotFound) sum.terms.push_back(term); else @@ -107,7 +107,7 @@ NumericValues()[0]->ToCalcExpressionNode(), NumericValues()[1]->ToCalcExpressionNode(), kCalcAdd); - for (size_t i = 2; i < NumericValues().size(); i++) { + for (wtf_size_t i = 2; i < NumericValues().size(); i++) { node = CSSCalcValue::CreateExpressionNode( node, NumericValues()[i]->ToCalcExpressionNode(), kCalcAdd); } @@ -125,7 +125,7 @@ DCHECK(!values.IsEmpty()); values[0]->BuildCSSText(Nested::kYes, ParenLess::kNo, result); - for (size_t i = 1; i < values.size(); i++) { + for (wtf_size_t i = 1; i < values.size(); i++) { const auto& arg = *values[i]; if (arg.GetType() == CSSStyleValue::kNegateType) { result.Append(" - ");
diff --git a/third_party/blink/renderer/core/css/cssom/css_math_variadic.h b/third_party/blink/renderer/core/css/cssom/css_math_variadic.h index b5b5c73..e6f714d 100644 --- a/third_party/blink/renderer/core/css/cssom/css_math_variadic.h +++ b/third_party/blink/renderer/core/css/cssom/css_math_variadic.h
@@ -50,7 +50,7 @@ error = false; CSSNumericValueType final_type = values.front()->Type(); - for (size_t i = 1; i < values.size(); i++) { + for (wtf_size_t i = 1; i < values.size(); i++) { final_type = op(final_type, values[i]->Type(), error); if (error) return final_type;
diff --git a/third_party/blink/renderer/core/css/cssom/css_numeric_value.cc b/third_party/blink/renderer/core/css/cssom/css_numeric_value.cc index ca43018c..14b9576b6 100644 --- a/third_party/blink/renderer/core/css/cssom/css_numeric_value.cc +++ b/third_party/blink/renderer/core/css/cssom/css_numeric_value.cc
@@ -43,7 +43,7 @@ return nullptr; double final_value = first_unit_value->value(); - for (size_t i = 1; i < values.size(); i++) { + for (wtf_size_t i = 1; i < values.size(); i++) { CSSUnitValue* unit_value = ToCSSUnitValueOrNull(values[i]); if (!unit_value || unit_value->GetInternalUnit() != first_unit_value->GetInternalUnit()) @@ -62,7 +62,7 @@ auto unit_other_than_number = CSSPrimitiveValue::UnitType::kNumber; double final_value = 1.0; - for (size_t i = 0; i < values.size(); i++) { + for (wtf_size_t i = 0; i < values.size(); i++) { CSSUnitValue* unit_value = ToCSSUnitValueOrNull(values[i]); if (!unit_value) return nullptr;
diff --git a/third_party/blink/renderer/core/css/cssom/css_transform_value.cc b/third_party/blink/renderer/core/css/cssom/css_transform_value.cc index 9939dd3..3a85ef3 100644 --- a/third_party/blink/renderer/core/css/cssom/css_transform_value.cc +++ b/third_party/blink/renderer/core/css/cssom/css_transform_value.cc
@@ -54,7 +54,7 @@ DOMMatrix* CSSTransformValue::toMatrix(ExceptionState& exception_state) const { DOMMatrix* matrix = DOMMatrix::Create(); - for (size_t i = 0; i < transform_components_.size(); i++) { + for (wtf_size_t i = 0; i < transform_components_.size(); i++) { const DOMMatrix* matrixComponent = transform_components_[i]->toMatrix(exception_state); if (matrixComponent) { @@ -66,7 +66,7 @@ const CSSValue* CSSTransformValue::ToCSSValue() const { CSSValueList* transform_css_value = CSSValueList::CreateSpaceSeparated(); - for (size_t i = 0; i < transform_components_.size(); i++) { + for (wtf_size_t i = 0; i < transform_components_.size(); i++) { const CSSValue* component = transform_components_[i]->ToCSSValue(); // TODO(meade): Remove this check once numbers and lengths are rewritten. if (!component)
diff --git a/third_party/blink/renderer/core/css/cssom/css_transform_value.h b/third_party/blink/renderer/core/css/cssom/css_transform_value.h index 8a78738..8a6dc7a523 100644 --- a/third_party/blink/renderer/core/css/cssom/css_transform_value.h +++ b/third_party/blink/renderer/core/css/cssom/css_transform_value.h
@@ -38,14 +38,14 @@ StyleValueType GetType() const override { return kTransformType; } - CSSTransformComponent* AnonymousIndexedGetter(uint32_t index) { + CSSTransformComponent* AnonymousIndexedGetter(wtf_size_t index) { return transform_components_.at(index); } bool AnonymousIndexedSetter(unsigned, const Member<CSSTransformComponent>, ExceptionState&); - size_t length() const { return transform_components_.size(); } + wtf_size_t length() const { return transform_components_.size(); } void Trace(blink::Visitor* visitor) override { visitor->Trace(transform_components_);
diff --git a/third_party/blink/renderer/core/css/cssom/css_unparsed_value.h b/third_party/blink/renderer/core/css/cssom/css_unparsed_value.h index 866b340c..a8b7d226 100644 --- a/third_party/blink/renderer/core/css/cssom/css_unparsed_value.h +++ b/third_party/blink/renderer/core/css/cssom/css_unparsed_value.h
@@ -43,7 +43,7 @@ const CSSUnparsedSegment&, ExceptionState&); - size_t length() const { return tokens_.size(); } + wtf_size_t length() const { return tokens_.size(); } void Trace(Visitor* visitor) override { visitor->Trace(tokens_);
diff --git a/third_party/blink/renderer/core/css/cssom/style_property_map_read_only.cc b/third_party/blink/renderer/core/css/cssom/style_property_map_read_only.cc index a69916c..1844279 100644 --- a/third_party/blink/renderer/core/css/cssom/style_property_map_read_only.cc +++ b/third_party/blink/renderer/core/css/cssom/style_property_map_read_only.cc
@@ -49,7 +49,7 @@ } private: - size_t index_; + wtf_size_t index_; const HeapVector<StylePropertyMapReadOnly::StylePropertyMapEntry> values_; };
diff --git a/third_party/blink/renderer/core/css/element_rule_collector.cc b/third_party/blink/renderer/core/css/element_rule_collector.cc index 25a5828..73d56c10 100644 --- a/third_party/blink/renderer/core/css/element_rule_collector.cc +++ b/third_party/blink/renderer/core/css/element_rule_collector.cc
@@ -223,7 +223,7 @@ match_request.rule_set->IdRules(element.IdForStyleResolution()), cascade_order, match_request); if (element.IsStyledElement() && element.HasClass()) { - for (size_t i = 0; i < element.ClassNames().size(); ++i) + for (wtf_size_t i = 0; i < element.ClassNames().size(); ++i) CollectMatchingRulesForList( match_request.rule_set->ClassRules(element.ClassNames()[i]), cascade_order, match_request);
diff --git a/third_party/blink/renderer/core/css/font_face.cc b/third_party/blink/renderer/core/css/font_face.cc index 5d8343b..f60ab07 100644 --- a/third_party/blink/renderer/core/css/font_face.cc +++ b/third_party/blink/renderer/core/css/font_face.cc
@@ -455,7 +455,7 @@ void FontFace::RunCallbacks() { HeapVector<Member<LoadFontCallback>> callbacks; callbacks_.swap(callbacks); - for (size_t i = 0; i < callbacks.size(); ++i) { + for (wtf_size_t i = 0; i < callbacks.size(); ++i) { if (status_ == kLoaded) callbacks[i]->NotifyLoaded(this); else
diff --git a/third_party/blink/renderer/core/css/font_face_set.cc b/third_party/blink/renderer/core/css/font_face_set.cc index 573b2d7..2c3ab8e 100644 --- a/third_party/blink/renderer/core/css/font_face_set.cc +++ b/third_party/blink/renderer/core/css/font_face_set.cc
@@ -118,7 +118,7 @@ FontFace::LoadFontCallback::Trace(visitor); } -size_t FontFaceSet::size() const { +wtf_size_t FontFaceSet::size() const { if (!InActiveContext()) return non_css_connected_faces_.size(); return CSSConnectedFontFaceList().size() + non_css_connected_faces_.size(); @@ -153,7 +153,7 @@ return; } - for (size_t i = 0; i < font_faces_.size(); i++) + for (wtf_size_t i = 0; i < font_faces_.size(); i++) font_faces_[i]->LoadWithCallback(this); }
diff --git a/third_party/blink/renderer/core/css/font_face_set.h b/third_party/blink/renderer/core/css/font_face_set.h index 0a51fc0..5568339a 100644 --- a/third_party/blink/renderer/core/css/font_face_set.h +++ b/third_party/blink/renderer/core/css/font_face_set.h
@@ -79,7 +79,7 @@ void Unpause() override; void ContextDestroyed(ExecutionContext*) override; - size_t size() const; + wtf_size_t size() const; virtual AtomicString status() const = 0; void Trace(blink::Visitor*) override; @@ -134,7 +134,7 @@ } private: - size_t index_; + wtf_size_t index_; HeapVector<Member<FontFace>> font_faces_; };
diff --git a/third_party/blink/renderer/core/css/media_list.cc b/third_party/blink/renderer/core/css/media_list.cc index 8928969..b2b24560 100644 --- a/third_party/blink/renderer/core/css/media_list.cc +++ b/third_party/blink/renderer/core/css/media_list.cc
@@ -90,7 +90,7 @@ // If comparing with any of the media queries in the collection of media // queries returns true terminate these steps. - for (size_t i = 0; i < queries_.size(); ++i) { + for (wtf_size_t i = 0; i < queries_.size(); ++i) { MediaQuery& query = *queries_[i]; if (query == *new_query) return false; @@ -117,7 +117,7 @@ // Remove any media query from the collection of media queries for which // comparing with the media query returns true. bool found = false; - for (size_t i = 0; i < queries_.size(); ++i) { + for (wtf_size_t i = 0; i < queries_.size(); ++i) { MediaQuery& query = *queries_[i]; if (query == *new_query) { queries_.EraseAt(i); @@ -139,7 +139,7 @@ StringBuilder text; bool first = true; - for (size_t i = 0; i < queries_.size(); ++i) { + for (wtf_size_t i = 0; i < queries_.size(); ++i) { if (!first) text.Append(", "); else
diff --git a/third_party/blink/renderer/core/css/media_query.cc b/third_party/blink/renderer/core/css/media_query.cc index e7e6c405..2a002db 100644 --- a/third_party/blink/renderer/core/css/media_query.cc +++ b/third_party/blink/renderer/core/css/media_query.cc
@@ -62,7 +62,7 @@ } result.Append(expressions_.at(0).Serialize()); - for (size_t i = 1; i < expressions_.size(); ++i) { + for (wtf_size_t i = 1; i < expressions_.size(); ++i) { result.Append(" and "); result.Append(expressions_.at(i).Serialize()); }
diff --git a/third_party/blink/renderer/core/css/media_query_evaluator.cc b/third_party/blink/renderer/core/css/media_query_evaluator.cc index dbe9f93..5c6aa02 100644 --- a/third_party/blink/renderer/core/css/media_query_evaluator.cc +++ b/third_party/blink/renderer/core/css/media_query_evaluator.cc
@@ -118,7 +118,7 @@ const ExpressionHeapVector& expressions = query.Expressions(); // Iterate through expressions, stop if any of them eval to false (AND // semantics). - size_t i = 0; + wtf_size_t i = 0; for (; i < expressions.size(); ++i) { bool expr_result = Eval(expressions.at(i)); if (viewport_dependent_media_query_results && @@ -149,7 +149,7 @@ // Iterate over queries, stop if any of them eval to true (OR semantics). bool result = false; - for (size_t i = 0; i < queries.size() && !result; ++i) + for (wtf_size_t i = 0; i < queries.size() && !result; ++i) result = Eval(*queries[i], viewport_dependent_media_query_results, device_dependent_media_query_results);
diff --git a/third_party/blink/renderer/core/css/media_query_set_test.cc b/third_party/blink/renderer/core/css/media_query_set_test.cc index 5f91370a..abc7506b 100644 --- a/third_party/blink/renderer/core/css/media_query_set_test.cc +++ b/third_party/blink/renderer/core/css/media_query_set_test.cc
@@ -18,7 +18,7 @@ static void TestMediaQuery(MediaQuerySetTestCase test, MediaQuerySet& query_set) { StringBuilder output; - size_t j = 0; + wtf_size_t j = 0; while (j < query_set.QueryVector().size()) { String query_text = query_set.QueryVector()[j]->CssText(); output.Append(query_text);
diff --git a/third_party/blink/renderer/core/css/media_values.cc b/third_party/blink/renderer/core/css/media_values.cc index 445ada7..7325011 100644 --- a/third_party/blink/renderer/core/css/media_values.cc +++ b/third_party/blink/renderer/core/css/media_values.cc
@@ -47,8 +47,10 @@ blink::WebScreenInfo screen_info = frame->GetPage()->GetChromeClient().GetScreenInfo(); int device_width = screen_info.rect.width; - if (frame->GetSettings()->GetReportScreenSizeInPhysicalPixelsQuirk()) - device_width = lroundf(device_width * screen_info.device_scale_factor); + if (frame->GetSettings()->GetReportScreenSizeInPhysicalPixelsQuirk()) { + device_width = static_cast<int>( + lroundf(device_width * screen_info.device_scale_factor)); + } return device_width; } @@ -57,8 +59,10 @@ blink::WebScreenInfo screen_info = frame->GetPage()->GetChromeClient().GetScreenInfo(); int device_height = screen_info.rect.height; - if (frame->GetSettings()->GetReportScreenSizeInPhysicalPixelsQuirk()) - device_height = lroundf(device_height * screen_info.device_scale_factor); + if (frame->GetSettings()->GetReportScreenSizeInPhysicalPixelsQuirk()) { + device_height = static_cast<int>( + lroundf(device_height * screen_info.device_scale_factor)); + } return device_height; }
diff --git a/third_party/blink/renderer/core/css/parser/css_lazy_parsing_test.cc b/third_party/blink/renderer/core/css/parser/css_lazy_parsing_test.cc index 73f942f..961cfad 100644 --- a/third_party/blink/renderer/core/css/parser/css_lazy_parsing_test.cc +++ b/third_party/blink/renderer/core/css/parser/css_lazy_parsing_test.cc
@@ -23,7 +23,7 @@ return rule->HasParsedProperties(); } - StyleRule* RuleAt(StyleSheetContents* sheet, size_t index) { + StyleRule* RuleAt(StyleSheetContents* sheet, wtf_size_t index) { return ToStyleRule(sheet->ChildRules()[index]); }
diff --git a/third_party/blink/renderer/core/css/parser/css_lazy_property_parser_impl.cc b/third_party/blink/renderer/core/css/parser/css_lazy_property_parser_impl.cc index d43f0e7..8b7d622 100644 --- a/third_party/blink/renderer/core/css/parser/css_lazy_property_parser_impl.cc +++ b/third_party/blink/renderer/core/css/parser/css_lazy_property_parser_impl.cc
@@ -9,7 +9,7 @@ namespace blink { -CSSLazyPropertyParserImpl::CSSLazyPropertyParserImpl(size_t offset, +CSSLazyPropertyParserImpl::CSSLazyPropertyParserImpl(wtf_size_t offset, CSSLazyParsingState* state) : CSSLazyPropertyParser(), offset_(offset), lazy_state_(state) {}
diff --git a/third_party/blink/renderer/core/css/parser/css_lazy_property_parser_impl.h b/third_party/blink/renderer/core/css/parser/css_lazy_property_parser_impl.h index e31232d..2d9670e 100644 --- a/third_party/blink/renderer/core/css/parser/css_lazy_property_parser_impl.h +++ b/third_party/blink/renderer/core/css/parser/css_lazy_property_parser_impl.h
@@ -16,7 +16,7 @@ // This class is responsible for lazily parsing a single CSS declaration list. class CSSLazyPropertyParserImpl : public CSSLazyPropertyParser { public: - CSSLazyPropertyParserImpl(size_t offset, CSSLazyParsingState*); + CSSLazyPropertyParserImpl(wtf_size_t offset, CSSLazyParsingState*); // CSSLazyPropertyParser: CSSPropertyValueSet* ParseProperties() override; @@ -27,7 +27,7 @@ } private: - size_t offset_; + wtf_size_t offset_; Member<CSSLazyParsingState> lazy_state_; };
diff --git a/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.cc b/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.cc index 66f07a3..19be541 100644 --- a/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.cc +++ b/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.cc
@@ -192,7 +192,7 @@ const CharacterType* end, const bool terminated_by_space, const char terminator) { - int length = end - string; + int length = static_cast<int>(end - string); if (length < 1) return 0; @@ -388,7 +388,7 @@ value = 0; - int length = end - string; + size_t length = end - string; if (length < 2) return false; @@ -1063,8 +1063,8 @@ unsigned expected_count, CSSFunctionValue* transform_value) { while (expected_count) { - size_t delimiter = - WTF::Find(pos, end - pos, expected_count == 1 ? ')' : ','); + wtf_size_t delimiter = WTF::Find(pos, static_cast<wtf_size_t>(end - pos), + expected_count == 1 ? ')' : ','); if (delimiter == kNotFound) return false; unsigned argument_length = static_cast<unsigned>(delimiter); @@ -1089,8 +1089,8 @@ unsigned expected_count, CSSFunctionValue* transform_value) { while (expected_count) { - size_t delimiter = - WTF::Find(pos, end - pos, expected_count == 1 ? ')' : ','); + wtf_size_t delimiter = WTF::Find(pos, static_cast<wtf_size_t>(end - pos), + expected_count == 1 ? ')' : ','); if (delimiter == kNotFound) return false; unsigned argument_length = static_cast<unsigned>(delimiter); @@ -1223,7 +1223,7 @@ // All other things, ex. rotate. return false; } - size_t arguments_end = WTF::Find(chars, length, ')', i); + wtf_size_t arguments_end = WTF::Find(chars, length, ')', i); if (arguments_end == kNotFound) return false; // Advance to the end of the arguments.
diff --git a/third_party/blink/renderer/core/css/parser/css_parser_impl.cc b/third_party/blink/renderer/core/css/parser/css_parser_impl.cc index 1aab233..3e2de46a 100644 --- a/third_party/blink/renderer/core/css/parser/css_parser_impl.cc +++ b/third_party/blink/renderer/core/css/parser/css_parser_impl.cc
@@ -130,12 +130,12 @@ bool important, const HeapVector<CSSPropertyValue, 256>& input, HeapVector<CSSPropertyValue, 256>& output, - size_t& unused_entries, + wtf_size_t& unused_entries, std::bitset<numCSSProperties>& seen_properties, HashSet<AtomicString>& seen_custom_properties) { // Add properties in reverse order so that highest priority definitions are // reached first. Duplicate definitions can then be ignored when found. - for (size_t i = input.size(); i--;) { + for (wtf_size_t i = input.size(); i--;) { const CSSPropertyValue& property = input[i]; if (property.IsImportant() != important) continue; @@ -160,7 +160,7 @@ HeapVector<CSSPropertyValue, 256>& parsed_properties, CSSParserMode mode) { std::bitset<numCSSProperties> seen_properties; - size_t unused_entries = parsed_properties.size(); + wtf_size_t unused_entries = parsed_properties.size(); HeapVector<CSSPropertyValue, 256> results(unused_entries); HashSet<AtomicString> seen_custom_properties; @@ -207,7 +207,7 @@ return false; std::bitset<numCSSProperties> seen_properties; - size_t unused_entries = parser.parsed_properties_.size(); + wtf_size_t unused_entries = parser.parsed_properties_.size(); HeapVector<CSSPropertyValue, 256> results(unused_entries); HashSet<AtomicString> seen_custom_properties; FilterProperties(true, parser.parsed_properties_, results, unused_entries, @@ -375,7 +375,7 @@ CSSPropertyValueSet* CSSParserImpl::ParseDeclarationListForLazyStyle( const String& string, - size_t offset, + wtf_size_t offset, const CSSParserContext* context) { CSSTokenizer tokenizer(string, offset); CSSParserTokenStream stream(tokenizer); @@ -466,7 +466,7 @@ import_prelude_uri = ConsumeStringOrURI(stream); stream.EnsureLookAhead(); - const size_t prelude_offset_start = stream.LookAheadOffset(); + const wtf_size_t prelude_offset_start = stream.LookAheadOffset(); const CSSParserTokenRange prelude = stream.ConsumeUntilPeekedTypeIs<kLeftBraceToken, kSemicolonToken>(); const RangeOffset prelude_offset(prelude_offset_start, @@ -529,7 +529,7 @@ if (allowed_rules == kKeyframeRules) { stream.EnsureLookAhead(); - const size_t prelude_offset_start = stream.LookAheadOffset(); + const wtf_size_t prelude_offset_start = stream.LookAheadOffset(); const CSSParserTokenRange prelude = stream.ConsumeUntilPeekedTypeIs<kLeftBraceToken>(); const RangeOffset prelude_offset(prelude_offset_start, @@ -846,7 +846,7 @@ if (use_observer && !stream.HasLookAhead()) { while (true) { - size_t start_offset = stream.Offset(); + wtf_size_t start_offset = stream.Offset(); if (!stream.ConsumeCommentOrNothing()) break; observer_->ObserveComment(start_offset, stream.Offset()); @@ -863,7 +863,7 @@ break; case kIdentToken: { // TODO(crbug.com/661854): Use streams instead of ranges - const size_t decl_offset_start = stream.Offset(); + const wtf_size_t decl_offset_start = stream.Offset(); const CSSParserTokenRange decl = stream.ConsumeUntilPeekedTypeIs<kSemicolonToken>(); // We want the offset of the kSemicolonToken, which is peeked but not
diff --git a/third_party/blink/renderer/core/css/parser/css_parser_impl.h b/third_party/blink/renderer/core/css/parser/css_parser_impl.h index b67f9aa6..e53aa95 100644 --- a/third_party/blink/renderer/core/css/parser/css_parser_impl.h +++ b/third_party/blink/renderer/core/css/parser/css_parser_impl.h
@@ -60,9 +60,9 @@ // Represents the start and end offsets of a CSSParserTokenRange. struct RangeOffset { - size_t start, end; + wtf_size_t start, end; - RangeOffset(size_t start, size_t end) : start(start), end(end) { + RangeOffset(wtf_size_t start, wtf_size_t end) : start(start), end(end) { DCHECK(start <= end); } @@ -117,7 +117,7 @@ static CSSPropertyValueSet* ParseDeclarationListForLazyStyle( const String&, - size_t offset, + wtf_size_t offset, const CSSParserContext*); private:
diff --git a/third_party/blink/renderer/core/css/parser/css_parser_token_range.h b/third_party/blink/renderer/core/css/parser/css_parser_token_range.h index 2d5b74e2..87a53423 100644 --- a/third_party/blink/renderer/core/css/parser/css_parser_token_range.h +++ b/third_party/blink/renderer/core/css/parser/css_parser_token_range.h
@@ -32,7 +32,7 @@ bool AtEnd() const { return first_ == last_; } const CSSParserToken* end() const { return last_; } - const CSSParserToken& Peek(unsigned offset = 0) const { + const CSSParserToken& Peek(wtf_size_t offset = 0) const { if (first_ + offset >= last_) return g_static_eof_token; return *(first_ + offset);
diff --git a/third_party/blink/renderer/core/css/parser/css_parser_token_stream.h b/third_party/blink/renderer/core/css/parser/css_parser_token_stream.h index 51d12b2..b613d71 100644 --- a/third_party/blink/renderer/core/css/parser/css_parser_token_stream.h +++ b/third_party/blink/renderer/core/css/parser/css_parser_token_stream.h
@@ -122,10 +122,10 @@ } // Get the index of the character in the original string to be consumed next. - size_t Offset() const { return offset_; } + wtf_size_t Offset() const { return offset_; } // Get the index of the starting character of the look-ahead token. - size_t LookAheadOffset() const { + wtf_size_t LookAheadOffset() const { DCHECK(HasLookAhead()); return tokenizer_.PreviousOffset(); } @@ -191,7 +191,7 @@ Vector<CSSParserToken, 32> buffer_; CSSTokenizer& tokenizer_; CSSParserToken next_; - size_t offset_ = 0; + wtf_size_t offset_ = 0; bool has_look_ahead_ = false; DISALLOW_COPY_AND_ASSIGN(CSSParserTokenStream); };
diff --git a/third_party/blink/renderer/core/css/parser/css_selector_parser.cc b/third_party/blink/renderer/core/css/parser/css_selector_parser.cc index 0715324..c6994ea 100644 --- a/third_party/blink/renderer/core/css/parser/css_selector_parser.cc +++ b/third_party/blink/renderer/core/css/parser/css_selector_parser.cc
@@ -82,10 +82,10 @@ Vector<std::unique_ptr<CSSParserSelector>> selector_list; while (true) { - const size_t selector_offset_start = stream.LookAheadOffset(); + const wtf_size_t selector_offset_start = stream.LookAheadOffset(); CSSParserTokenRange complex_selector = stream.ConsumeUntilPeekedTypeIs<kLeftBraceToken, kCommaToken>(); - const size_t selector_offset_end = stream.LookAheadOffset(); + const wtf_size_t selector_offset_end = stream.LookAheadOffset(); if (stream.UncheckedAtEnd()) return CSSSelectorList();
diff --git a/third_party/blink/renderer/core/css/parser/css_tokenizer.cc b/third_party/blink/renderer/core/css/parser/css_tokenizer.cc index 73b6eb1..94e41a16 100644 --- a/third_party/blink/renderer/core/css/parser/css_tokenizer.cc +++ b/third_party/blink/renderer/core/css/parser/css_tokenizer.cc
@@ -15,7 +15,7 @@ namespace blink { -CSSTokenizer::CSSTokenizer(const String& string, size_t offset) +CSSTokenizer::CSSTokenizer(const String& string, wtf_size_t offset) : input_(string) { // According to the spec, we should perform preprocessing here. // See: https://drafts.csswg.org/css-syntax/#input-preprocessing @@ -63,7 +63,7 @@ return NextToken(); } -unsigned CSSTokenizer::TokenCount() { +wtf_size_t CSSTokenizer::TokenCount() { return token_count_; }
diff --git a/third_party/blink/renderer/core/css/parser/css_tokenizer.h b/third_party/blink/renderer/core/css/parser/css_tokenizer.h index dfdcb32..04fa997 100644 --- a/third_party/blink/renderer/core/css/parser/css_tokenizer.h +++ b/third_party/blink/renderer/core/css/parser/css_tokenizer.h
@@ -24,13 +24,13 @@ DISALLOW_NEW(); public: - CSSTokenizer(const String&, size_t offset = 0); + CSSTokenizer(const String&, wtf_size_t offset = 0); Vector<CSSParserToken, 32> TokenizeToEOF(); - unsigned TokenCount(); + wtf_size_t TokenCount(); - size_t Offset() const { return input_.Offset(); } - size_t PreviousOffset() const { return prev_offset_; } + wtf_size_t Offset() const { return input_.Offset(); } + wtf_size_t PreviousOffset() const { return prev_offset_; } private: CSSParserToken TokenizeSingle(); @@ -109,8 +109,8 @@ friend class CSSParserTokenStream; - size_t prev_offset_ = 0; - size_t token_count_ = 0; + wtf_size_t prev_offset_ = 0; + wtf_size_t token_count_ = 0; DISALLOW_COPY_AND_ASSIGN(CSSTokenizer); };
diff --git a/third_party/blink/renderer/core/css/parser/css_tokenizer_input_stream.h b/third_party/blink/renderer/core/css/parser/css_tokenizer_input_stream.h index 5d67083..8d8c0013 100644 --- a/third_party/blink/renderer/core/css/parser/css_tokenizer_input_stream.h +++ b/third_party/blink/renderer/core/css/parser/css_tokenizer_input_stream.h
@@ -72,8 +72,8 @@ } private: - size_t offset_; - const size_t string_length_; + wtf_size_t offset_; + const wtf_size_t string_length_; const scoped_refptr<StringImpl> string_; DISALLOW_COPY_AND_ASSIGN(CSSTokenizerInputStream); };
diff --git a/third_party/blink/renderer/core/css/part_names.cc b/third_party/blink/renderer/core/css/part_names.cc index b343b1e..ccd1489 100644 --- a/third_party/blink/renderer/core/css/part_names.cc +++ b/third_party/blink/renderer/core/css/part_names.cc
@@ -13,7 +13,7 @@ // Adds the names to the set. static void AddToSet(const SpaceSplitString& strings, HashSet<AtomicString>* set) { - for (size_t i = 0; i < strings.size(); i++) { + for (wtf_size_t i = 0; i < strings.size(); i++) { set->insert(strings[i]); } }
diff --git a/third_party/blink/renderer/core/css/properties/computed_style_utils.cc b/third_party/blink/renderer/core/css/properties/computed_style_utils.cc index c2f51f6..547b35f 100644 --- a/third_party/blink/renderer/core/css/properties/computed_style_utils.cc +++ b/third_party/blink/renderer/core/css/properties/computed_style_utils.cc
@@ -1218,14 +1218,14 @@ OrderedNamedLinesCollector collector(style, is_row_axis, auto_repeat_total_tracks); CSSValueList* list = CSSValueList::CreateSpaceSeparated(); - size_t insertion_index; + wtf_size_t insertion_index; if (is_layout_grid) { const auto* grid = ToLayoutGrid(layout_object); Vector<LayoutUnit> computed_track_sizes = grid->TrackSizesForComputedStyle(direction); - size_t num_tracks = computed_track_sizes.size(); + wtf_size_t num_tracks = computed_track_sizes.size(); - for (size_t i = 0; i < num_tracks; ++i) { + for (wtf_size_t i = 0; i < num_tracks; ++i) { AddValuesForNamedGridLinesAtIndex(collector, i, *list); list->Append(*ZoomAdjustedPixelValue(computed_track_sizes[i], style)); } @@ -1233,7 +1233,7 @@ insertion_index = num_tracks; } else { - for (size_t i = 0; i < track_sizes.size(); ++i) { + for (wtf_size_t i = 0; i < track_sizes.size(); ++i) { AddValuesForNamedGridLinesAtIndex(collector, i, *list); list->Append(*SpecifiedValueForGridTrackSize(track_sizes[i], style)); } @@ -1362,7 +1362,7 @@ list->Append(*CSSIdentifierValue::Create(CSSValueContents)); if (will_change_scroll_position) list->Append(*CSSIdentifierValue::Create(CSSValueScrollPosition)); - for (size_t i = 0; i < will_change_properties.size(); ++i) + for (wtf_size_t i = 0; i < will_change_properties.size(); ++i) list->Append(*CSSCustomIdentValue::Create(will_change_properties[i])); if (!list->length()) list->Append(*CSSIdentifierValue::Create(CSSValueAuto)); @@ -1373,7 +1373,7 @@ const CSSTimingData* timing_data) { CSSValueList* list = CSSValueList::CreateCommaSeparated(); if (timing_data) { - for (size_t i = 0; i < timing_data->DelayList().size(); ++i) { + for (wtf_size_t i = 0; i < timing_data->DelayList().size(); ++i) { list->Append(*CSSPrimitiveValue::Create( timing_data->DelayList()[i], CSSPrimitiveValue::UnitType::kSeconds)); } @@ -1405,7 +1405,7 @@ const CSSTimingData* timing_data) { CSSValueList* list = CSSValueList::CreateCommaSeparated(); if (timing_data) { - for (size_t i = 0; i < timing_data->DurationList().size(); ++i) { + for (wtf_size_t i = 0; i < timing_data->DurationList().size(); ++i) { list->Append( *CSSPrimitiveValue::Create(timing_data->DurationList()[i], CSSPrimitiveValue::UnitType::kSeconds)); @@ -1517,7 +1517,7 @@ const CSSTimingData* timing_data) { CSSValueList* list = CSSValueList::CreateCommaSeparated(); if (timing_data) { - for (size_t i = 0; i < timing_data->TimingFunctionList().size(); ++i) { + for (wtf_size_t i = 0; i < timing_data->TimingFunctionList().size(); ++i) { list->Append(*CreateTimingFunctionValue( timing_data->TimingFunctionList()[i].get())); } @@ -1663,7 +1663,7 @@ const CSSTransitionData* transition_data) { CSSValueList* list = CSSValueList::CreateCommaSeparated(); if (transition_data) { - for (size_t i = 0; i < transition_data->PropertyList().size(); ++i) { + for (wtf_size_t i = 0; i < transition_data->PropertyList().size(); ++i) { list->Append( *CreateTransitionPropertyValue(transition_data->PropertyList()[i])); } @@ -1923,8 +1923,8 @@ return CSSIdentifierValue::Create(CSSValueNone); CSSValueList* list = CSSValueList::CreateCommaSeparated(); - size_t shadow_count = shadow_list->Shadows().size(); - for (size_t i = 0; i < shadow_count; ++i) { + wtf_size_t shadow_count = shadow_list->Shadows().size(); + for (wtf_size_t i = 0; i < shadow_count; ++i) { list->Append( *ValueForShadowData(shadow_list->Shadows()[i], style, use_spread)); } @@ -2147,7 +2147,7 @@ Node* styled_node, bool allow_visited_style) { CSSValueList* list = CSSValueList::CreateSpaceSeparated(); - for (size_t i = 0; i < shorthand.length(); ++i) { + for (unsigned i = 0; i < shorthand.length(); ++i) { const CSSValue* value = shorthand.properties()[i]->CSSValueFromComputedStyle( style, layout_object, styled_node, allow_visited_style); @@ -2164,7 +2164,7 @@ Node* styled_node, bool allow_visited_style) { CSSValueList* list = CSSValueList::CreateSlashSeparated(); - for (size_t i = 0; i < shorthand.length(); ++i) { + for (unsigned i = 0; i < shorthand.length(); ++i) { const CSSValue* value = shorthand.properties()[i]->CSSValueFromComputedStyle( style, layout_object, styled_node, allow_visited_style); @@ -2256,7 +2256,7 @@ }; StylePropertyShorthand shorthand = fontVariantShorthand(); VariantShorthandCases shorthand_case = kAllNormal; - for (size_t i = 0; i < shorthand.length(); ++i) { + for (unsigned i = 0; i < shorthand.length(); ++i) { const CSSValue* value = shorthand.properties()[i]->CSSValueFromComputedStyle( style, layout_object, styled_node, allow_visited_style); @@ -2279,7 +2279,7 @@ return CSSIdentifierValue::Create(CSSValueNone); case kConcatenateNonNormal: { CSSValueList* list = CSSValueList::CreateSpaceSeparated(); - for (size_t i = 0; i < shorthand.length(); ++i) { + for (unsigned i = 0; i < shorthand.length(); ++i) { const CSSValue* value = shorthand.properties()[i]->CSSValueFromComputedStyle( style, layout_object, styled_node, allow_visited_style);
diff --git a/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc b/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc index c2dd683c..b686b57 100644 --- a/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc +++ b/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc
@@ -564,14 +564,14 @@ const unsigned longhand_count = shorthand.length(); DCHECK_LE(longhand_count, kMaxNumAnimationLonghands); - for (size_t i = 0; i < longhand_count; ++i) + for (unsigned i = 0; i < longhand_count; ++i) longhands[i] = CSSValueList::CreateCommaSeparated(); do { bool parsed_longhand[kMaxNumAnimationLonghands] = {false}; do { bool found_property = false; - for (size_t i = 0; i < longhand_count; ++i) { + for (unsigned i = 0; i < longhand_count; ++i) { if (parsed_longhand[i]) continue; @@ -589,7 +589,7 @@ return false; } while (!range.AtEnd() && range.Peek().GetType() != kCommaToken); - for (size_t i = 0; i < longhand_count; ++i) { + for (unsigned i = 0; i < longhand_count; ++i) { if (!parsed_longhand[i]) { longhands[i]->Append( *ToLonghand(shorthand.properties()[i])->InitialValue()); @@ -821,7 +821,7 @@ CSSValue* origin_value = nullptr; do { bool found_property = false; - for (size_t i = 0; i < longhand_count; ++i) { + for (unsigned i = 0; i < longhand_count; ++i) { if (parsed_longhand[i]) continue; @@ -882,7 +882,7 @@ } while (!range.AtEnd() && range.Peek().GetType() != kCommaToken); // TODO(timloh): This will make invalid longhands, see crbug.com/386459 - for (size_t i = 0; i < longhand_count; ++i) { + for (unsigned i = 0; i < longhand_count; ++i) { const CSSProperty& property = *shorthand.properties()[i]; if (property.IDEquals(CSSPropertyBackgroundColor) && !range.AtEnd()) { if (parsed_longhand[i]) @@ -903,7 +903,7 @@ if (!range.AtEnd()) return false; - for (size_t i = 0; i < longhand_count; ++i) { + for (unsigned i = 0; i < longhand_count; ++i) { const CSSProperty& property = *shorthand.properties()[i]; if (property.IDEquals(CSSPropertyBackgroundSize) && longhands[i] && context.UseLegacyBackgroundSizeShorthandBehavior())
diff --git a/third_party/blink/renderer/core/css/properties/longhands/animation_direction_custom.cc b/third_party/blink/renderer/core/css/properties/longhands/animation_direction_custom.cc index 7ac8597..454d4f52 100644 --- a/third_party/blink/renderer/core/css/properties/longhands/animation_direction_custom.cc +++ b/third_party/blink/renderer/core/css/properties/longhands/animation_direction_custom.cc
@@ -32,7 +32,7 @@ CSSValueList* list = CSSValueList::CreateCommaSeparated(); const CSSAnimationData* animation_data = style.Animations(); if (animation_data) { - for (size_t i = 0; i < animation_data->DirectionList().size(); ++i) { + for (wtf_size_t i = 0; i < animation_data->DirectionList().size(); ++i) { list->Append(*ComputedStyleUtils::ValueForAnimationDirection( animation_data->DirectionList()[i])); }
diff --git a/third_party/blink/renderer/core/css/properties/longhands/animation_fill_mode_custom.cc b/third_party/blink/renderer/core/css/properties/longhands/animation_fill_mode_custom.cc index 7808abf..a2e15918 100644 --- a/third_party/blink/renderer/core/css/properties/longhands/animation_fill_mode_custom.cc +++ b/third_party/blink/renderer/core/css/properties/longhands/animation_fill_mode_custom.cc
@@ -31,7 +31,7 @@ CSSValueList* list = CSSValueList::CreateCommaSeparated(); const CSSAnimationData* animation_data = style.Animations(); if (animation_data) { - for (size_t i = 0; i < animation_data->FillModeList().size(); ++i) { + for (wtf_size_t i = 0; i < animation_data->FillModeList().size(); ++i) { list->Append(*ComputedStyleUtils::ValueForAnimationFillMode( animation_data->FillModeList()[i])); }
diff --git a/third_party/blink/renderer/core/css/properties/longhands/animation_iteration_count_custom.cc b/third_party/blink/renderer/core/css/properties/longhands/animation_iteration_count_custom.cc index 4cdef1c6..a60bce0 100644 --- a/third_party/blink/renderer/core/css/properties/longhands/animation_iteration_count_custom.cc +++ b/third_party/blink/renderer/core/css/properties/longhands/animation_iteration_count_custom.cc
@@ -30,7 +30,8 @@ CSSValueList* list = CSSValueList::CreateCommaSeparated(); const CSSAnimationData* animation_data = style.Animations(); if (animation_data) { - for (size_t i = 0; i < animation_data->IterationCountList().size(); ++i) { + for (wtf_size_t i = 0; i < animation_data->IterationCountList().size(); + ++i) { list->Append(*ComputedStyleUtils::ValueForAnimationIterationCount( animation_data->IterationCountList()[i])); }
diff --git a/third_party/blink/renderer/core/css/properties/longhands/animation_name_custom.cc b/third_party/blink/renderer/core/css/properties/longhands/animation_name_custom.cc index e2c3168..960f30a8 100644 --- a/third_party/blink/renderer/core/css/properties/longhands/animation_name_custom.cc +++ b/third_party/blink/renderer/core/css/properties/longhands/animation_name_custom.cc
@@ -31,7 +31,7 @@ CSSValueList* list = CSSValueList::CreateCommaSeparated(); const CSSAnimationData* animation_data = style.Animations(); if (animation_data) { - for (size_t i = 0; i < animation_data->NameList().size(); ++i) + for (wtf_size_t i = 0; i < animation_data->NameList().size(); ++i) list->Append(*CSSCustomIdentValue::Create(animation_data->NameList()[i])); } else { list->Append(*InitialValue());
diff --git a/third_party/blink/renderer/core/css/properties/longhands/animation_play_state_custom.cc b/third_party/blink/renderer/core/css/properties/longhands/animation_play_state_custom.cc index b93148a..534e768 100644 --- a/third_party/blink/renderer/core/css/properties/longhands/animation_play_state_custom.cc +++ b/third_party/blink/renderer/core/css/properties/longhands/animation_play_state_custom.cc
@@ -30,7 +30,7 @@ CSSValueList* list = CSSValueList::CreateCommaSeparated(); const CSSAnimationData* animation_data = style.Animations(); if (animation_data) { - for (size_t i = 0; i < animation_data->PlayStateList().size(); ++i) { + for (wtf_size_t i = 0; i < animation_data->PlayStateList().size(); ++i) { list->Append(*ComputedStyleUtils::ValueForAnimationPlayState( animation_data->PlayStateList()[i])); }
diff --git a/third_party/blink/renderer/core/css/properties/longhands/font_feature_settings_custom.cc b/third_party/blink/renderer/core/css/properties/longhands/font_feature_settings_custom.cc index 4aaeee33..41f0a94 100644 --- a/third_party/blink/renderer/core/css/properties/longhands/font_feature_settings_custom.cc +++ b/third_party/blink/renderer/core/css/properties/longhands/font_feature_settings_custom.cc
@@ -29,7 +29,7 @@ if (!feature_settings || !feature_settings->size()) return CSSIdentifierValue::Create(CSSValueNormal); CSSValueList* list = CSSValueList::CreateCommaSeparated(); - for (unsigned i = 0; i < feature_settings->size(); ++i) { + for (wtf_size_t i = 0; i < feature_settings->size(); ++i) { const FontFeature& feature = feature_settings->at(i); cssvalue::CSSFontFeatureValue* feature_value = cssvalue::CSSFontFeatureValue::Create(feature.Tag(), feature.Value());
diff --git a/third_party/blink/renderer/core/css/properties/longhands/font_variation_settings_custom.cc b/third_party/blink/renderer/core/css/properties/longhands/font_variation_settings_custom.cc index 519e4b3..6c71543e 100644 --- a/third_party/blink/renderer/core/css/properties/longhands/font_variation_settings_custom.cc +++ b/third_party/blink/renderer/core/css/properties/longhands/font_variation_settings_custom.cc
@@ -17,7 +17,7 @@ cssvalue::CSSFontVariationValue* ConsumeFontVariationTag( CSSParserTokenRange& range) { // Feature tag name consists of 4-letter characters. - static const unsigned kTagNameLength = 4; + static const wtf_size_t kTagNameLength = 4; const CSSParserToken& token = range.ConsumeIncludingWhitespace(); // Feature tag name comes first @@ -26,7 +26,7 @@ if (token.Value().length() != kTagNameLength) return nullptr; AtomicString tag = token.Value().ToAtomicString(); - for (unsigned i = 0; i < kTagNameLength; ++i) { + for (wtf_size_t i = 0; i < kTagNameLength; ++i) { // Limits the range of characters to 0x20-0x7E, following the tag name rules // defined in the OpenType specification. UChar character = tag[i]; @@ -72,7 +72,7 @@ if (!variation_settings || !variation_settings->size()) return CSSIdentifierValue::Create(CSSValueNormal); CSSValueList* list = CSSValueList::CreateCommaSeparated(); - for (unsigned i = 0; i < variation_settings->size(); ++i) { + for (wtf_size_t i = 0; i < variation_settings->size(); ++i) { const FontVariationAxis& variation_axis = variation_settings->at(i); cssvalue::CSSFontVariationValue* variation_value = cssvalue::CSSFontVariationValue::Create(variation_axis.Tag(),
diff --git a/third_party/blink/renderer/core/css/properties/shorthands/animation_custom.cc b/third_party/blink/renderer/core/css/properties/shorthands/animation_custom.cc index 3804a99..29e35a17 100644 --- a/third_party/blink/renderer/core/css/properties/shorthands/animation_custom.cc +++ b/third_party/blink/renderer/core/css/properties/shorthands/animation_custom.cc
@@ -71,7 +71,7 @@ return false; } - for (size_t i = 0; i < longhand_count; ++i) { + for (unsigned i = 0; i < longhand_count; ++i) { CSSPropertyParserHelpers::AddProperty( shorthand.properties()[i]->PropertyID(), shorthand.id(), *longhands[i], important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, @@ -89,7 +89,7 @@ const CSSAnimationData* animation_data = style.Animations(); if (animation_data) { CSSValueList* animations_list = CSSValueList::CreateCommaSeparated(); - for (size_t i = 0; i < animation_data->NameList().size(); ++i) { + for (wtf_size_t i = 0; i < animation_data->NameList().size(); ++i) { CSSValueList* list = CSSValueList::CreateSpaceSeparated(); list->Append(*CSSCustomIdentValue::Create(animation_data->NameList()[i])); list->Append(*CSSPrimitiveValue::Create(
diff --git a/third_party/blink/renderer/core/css/properties/shorthands/transition_custom.cc b/third_party/blink/renderer/core/css/properties/shorthands/transition_custom.cc index 38fa2ee..ddce931 100644 --- a/third_party/blink/renderer/core/css/properties/shorthands/transition_custom.cc +++ b/third_party/blink/renderer/core/css/properties/shorthands/transition_custom.cc
@@ -56,13 +56,13 @@ return false; } - for (size_t i = 0; i < longhand_count; ++i) { + for (unsigned i = 0; i < longhand_count; ++i) { if (shorthand.properties()[i]->IDEquals(CSSPropertyTransitionProperty) && !CSSParsingUtils::IsValidPropertyList(*longhands[i])) return false; } - for (size_t i = 0; i < longhand_count; ++i) { + for (unsigned i = 0; i < longhand_count; ++i) { CSSPropertyParserHelpers::AddProperty( shorthand.properties()[i]->PropertyID(), shorthand.id(), *longhands[i], important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, @@ -81,7 +81,7 @@ const CSSTransitionData* transition_data = style.Transitions(); if (transition_data) { CSSValueList* transitions_list = CSSValueList::CreateCommaSeparated(); - for (size_t i = 0; i < transition_data->PropertyList().size(); ++i) { + for (wtf_size_t i = 0; i < transition_data->PropertyList().size(); ++i) { CSSValueList* list = CSSValueList::CreateSpaceSeparated(); list->Append(*ComputedStyleUtils::CreateTransitionPropertyValue( transition_data->PropertyList()[i]));
diff --git a/third_party/blink/renderer/core/css/remote_font_face_source.cc b/third_party/blink/renderer/core/css/remote_font_face_source.cc index bcd6e8c..4c8976e 100644 --- a/third_party/blink/renderer/core/css/remote_font_face_source.cc +++ b/third_party/blink/renderer/core/css/remote_font_face_source.cc
@@ -371,7 +371,7 @@ return; } - unsigned size = font->EncodedSize(); + size_t size = font->EncodedSize(); if (size < 10 * 1024) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, under10k_histogram,
diff --git a/third_party/blink/renderer/core/css/resolver/element_style_resources.cc b/third_party/blink/renderer/core/css/resolver/element_style_resources.cc index fa6724c..c1ea3013 100644 --- a/third_party/blink/renderer/core/css/resolver/element_style_resources.cc +++ b/third_party/blink/renderer/core/css/resolver/element_style_resources.cc
@@ -239,7 +239,7 @@ } case CSSPropertyCursor: { if (CursorList* cursor_list = style->Cursors()) { - for (size_t i = 0; i < cursor_list->size(); ++i) { + for (wtf_size_t i = 0; i < cursor_list->size(); ++i) { CursorData& current_cursor = cursor_list->at(i); if (StyleImage* image = current_cursor.GetImage()) { if (image->IsPendingImage()) {
diff --git a/third_party/blink/renderer/core/css/resolver/matched_properties_cache.cc b/third_party/blink/renderer/core/css/resolver/matched_properties_cache.cc index f5cb5ba..59d40531 100644 --- a/third_party/blink/renderer/core/css/resolver/matched_properties_cache.cc +++ b/third_party/blink/renderer/core/css/resolver/matched_properties_cache.cc
@@ -69,13 +69,13 @@ if (!cache_item) return nullptr; - size_t size = properties.size(); + wtf_size_t size = properties.size(); if (size != cache_item->matched_properties.size()) return nullptr; if (cache_item->computed_style->InsideLink() != style_resolver_state.Style()->InsideLink()) return nullptr; - for (size_t i = 0; i < size; ++i) { + for (wtf_size_t i = 0; i < size; ++i) { if (properties[i] != cache_item->matched_properties[i]) return nullptr; }
diff --git a/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc b/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc index d2c2122..b60eabca 100644 --- a/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc +++ b/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.cc
@@ -217,7 +217,7 @@ void ScopedStyleResolver::CollectMatchingAuthorRules( ElementRuleCollector& collector, ShadowV0CascadeOrder cascade_order) { - size_t sheet_index = 0; + wtf_size_t sheet_index = 0; for (auto sheet : author_style_sheets_) { if (!RuntimeEnabledFeatures::ConstructableStylesheetsEnabled()) DCHECK(sheet->ownerNode()); @@ -230,7 +230,7 @@ void ScopedStyleResolver::CollectMatchingShadowHostRules( ElementRuleCollector& collector, ShadowV0CascadeOrder cascade_order) { - size_t sheet_index = 0; + wtf_size_t sheet_index = 0; for (auto sheet : author_style_sheets_) { if (!RuntimeEnabledFeatures::ConstructableStylesheetsEnabled()) DCHECK(sheet->ownerNode()); @@ -272,7 +272,7 @@ ShadowV0CascadeOrder cascade_order) { if (!RuntimeEnabledFeatures::CSSPartPseudoElementEnabled()) return; - size_t sheet_index = 0; + wtf_size_t sheet_index = 0; for (auto sheet : author_style_sheets_) { if (!RuntimeEnabledFeatures::ConstructableStylesheetsEnabled()) DCHECK(sheet->ownerNode());
diff --git a/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc b/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc index 93e012ed..750b9f99 100644 --- a/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc +++ b/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc
@@ -551,7 +551,7 @@ if (value.IsValueList()) { FontDescription::VariantLigatures ligatures; const CSSValueList& value_list = ToCSSValueList(value); - for (size_t i = 0; i < value_list.length(); ++i) { + for (wtf_size_t i = 0; i < value_list.length(); ++i) { const CSSValue& item = value_list.Item(i); switch (ToCSSIdentifierValue(item).GetValueID()) { case CSSValueNoCommonLigatures: @@ -1237,7 +1237,7 @@ if (value.IsValueList()) { const CSSValueList& list = ToCSSValueList(value); scoped_refptr<QuotesData> quotes = QuotesData::Create(); - for (size_t i = 0; i < list.length(); i += 2) { + for (wtf_size_t i = 0; i < list.length(); i += 2) { String start_quote = ToCSSStringValue(list.Item(i)).Value(); String end_quote = ToCSSStringValue(list.Item(i + 1)).Value(); quotes->AddPair(std::make_pair(start_quote, end_quote)); @@ -1371,8 +1371,8 @@ const CSSValueList& dashes = ToCSSValueList(value); scoped_refptr<SVGDashArray> array = SVGDashArray::Create(); - size_t length = dashes.length(); - for (size_t i = 0; i < length; ++i) { + wtf_size_t length = dashes.length(); + for (wtf_size_t i = 0; i < length; ++i) { array->push_back(ConvertLength(state, ToCSSPrimitiveValue(dashes.Item(i)))); }
diff --git a/third_party/blink/renderer/core/css/rule_feature_set_test.cc b/third_party/blink/renderer/core/css/rule_feature_set_test.cc index 05ac04dd..b3e32f31 100644 --- a/third_party/blink/renderer/core/css/rule_feature_set_test.cc +++ b/third_party/blink/renderer/core/css/rule_feature_set_test.cc
@@ -38,7 +38,7 @@ StrictCSSParserContext(SecureContextMode::kInsecureContext), nullptr, selector_text); - std::vector<size_t> indices; + std::vector<wtf_size_t> indices; for (const CSSSelector* s = selector_list.First(); s; s = selector_list.Next(*s)) { indices.push_back(selector_list.SelectorIndex(*s));
diff --git a/third_party/blink/renderer/core/css/rule_set.cc b/third_party/blink/renderer/core/css/rule_set.cc index b09913a..0233c8a 100644 --- a/third_party/blink/renderer/core/css/rule_set.cc +++ b/third_party/blink/renderer/core/css/rule_set.cc
@@ -273,7 +273,7 @@ const CSSSelectorList& selector_list = style_rule->SelectorList(); for (const CSSSelector* selector = selector_list.First(); selector; selector = selector_list.Next(*selector)) { - size_t selector_index = selector_list.SelectorIndex(*selector); + wtf_size_t selector_index = selector_list.SelectorIndex(*selector); if (selector->HasDeepCombinatorOrShadowPseudo()) { deep_combinator_or_shadow_pseudo_rules_.push_back( MinimalRuleData(style_rule, selector_index, add_rule_flags)); @@ -331,7 +331,7 @@ } void RuleSet::AddStyleRule(StyleRule* rule, AddRuleFlags add_rule_flags) { - for (size_t selector_index = + for (wtf_size_t selector_index = rule->SelectorList().SelectorIndex(*rule->SelectorList().First()); selector_index != kNotFound; selector_index =
diff --git a/third_party/blink/renderer/core/css/selector_checker.cc b/third_party/blink/renderer/core/css/selector_checker.cc index 34360b38..1f579e95 100644 --- a/third_party/blink/renderer/core/css/selector_checker.cc +++ b/third_party/blink/renderer/core/css/selector_checker.cc
@@ -564,7 +564,7 @@ unsigned start_search_at = 0; while (true) { - size_t found_pos = + wtf_size_t found_pos = value.Find(selector_value, start_search_at, case_sensitivity); if (found_pos == kNotFound) return false;
diff --git a/third_party/blink/renderer/core/css/selector_filter.cc b/third_party/blink/renderer/core/css/selector_filter.cc index 92450b3c..9fb0fb7 100644 --- a/third_party/blink/renderer/core/css/selector_filter.cc +++ b/third_party/blink/renderer/core/css/selector_filter.cc
@@ -51,8 +51,8 @@ kIdAttributeSalt); if (element.IsStyledElement() && element.HasClass()) { const SpaceSplitString& class_names = element.ClassNames(); - size_t count = class_names.size(); - for (size_t i = 0; i < count; ++i) { + wtf_size_t count = class_names.size(); + for (wtf_size_t i = 0; i < count; ++i) { DCHECK(class_names[i].Impl()); // Speculative fix for https://crbug.com/646026 if (class_names[i].Impl()) @@ -72,8 +72,8 @@ // Mix tags, class names and ids into some sort of weird bouillabaisse. // The filter is used for fast rejection of child and descendant selectors. CollectElementIdentifierHashes(parent, parent_frame.identifier_hashes); - size_t count = parent_frame.identifier_hashes.size(); - for (size_t i = 0; i < count; ++i) + wtf_size_t count = parent_frame.identifier_hashes.size(); + for (wtf_size_t i = 0; i < count; ++i) ancestor_identifier_filter_->Add(parent_frame.identifier_hashes[i]); } @@ -81,8 +81,8 @@ DCHECK(!parent_stack_.IsEmpty()); DCHECK(ancestor_identifier_filter_); const ParentStackFrame& parent_frame = parent_stack_.back(); - size_t count = parent_frame.identifier_hashes.size(); - for (size_t i = 0; i < count; ++i) + wtf_size_t count = parent_frame.identifier_hashes.size(); + for (wtf_size_t i = 0; i < count; ++i) ancestor_identifier_filter_->Remove(parent_frame.identifier_hashes[i]); parent_stack_.pop_back(); if (parent_stack_.IsEmpty()) {
diff --git a/third_party/blink/renderer/core/css/style_color.cc b/third_party/blink/renderer/core/css/style_color.cc index ea63435..75ebc0b4 100644 --- a/third_party/blink/renderer/core/css/style_color.cc +++ b/third_party/blink/renderer/core/css/style_color.cc
@@ -11,7 +11,7 @@ Color StyleColor::ColorFromKeyword(CSSValueID keyword) { if (const char* value_name = getValueName(keyword)) { if (const NamedColor* named_color = - FindColor(value_name, strlen(value_name))) + FindColor(value_name, static_cast<wtf_size_t>(strlen(value_name)))) return Color(named_color->argb_value); } return LayoutTheme::GetTheme().SystemColor(keyword);
diff --git a/third_party/blink/renderer/core/css/style_engine.cc b/third_party/blink/renderer/core/css/style_engine.cc index d98cbcb..6075361e 100644 --- a/third_party/blink/renderer/core/css/style_engine.cc +++ b/third_party/blink/renderer/core/css/style_engine.cc
@@ -934,7 +934,7 @@ if (element.HasClass()) { const SpaceSplitString& class_names = element.ClassNames(); - for (size_t i = 0; i < class_names.size(); i++) { + for (wtf_size_t i = 0; i < class_names.size(); i++) { features.CollectSiblingInvalidationSetForClass( invalidation_lists, element, class_names[i], min_direct_adjacent); } @@ -1025,8 +1025,8 @@ element, id); } if (class_names) { - unsigned class_name_count = class_names->size(); - for (size_t i = 0; i < class_name_count; i++) { + wtf_size_t class_name_count = class_names->size(); + for (wtf_size_t i = 0; i < class_name_count; i++) { rule_set->Features().CollectInvalidationSetsForClass( invalidation_lists, element, (*class_names)[i]); }
diff --git a/third_party/blink/renderer/core/css/style_property_serializer.cc b/third_party/blink/renderer/core/css/style_property_serializer.cc index 2344a9fe..b9406ce 100644 --- a/third_party/blink/renderer/core/css/style_property_serializer.cc +++ b/third_party/blink/renderer/core/css/style_property_serializer.cc
@@ -872,11 +872,11 @@ // Begin by collecting the properties into a vector. HeapVector<Member<const CSSValue>> values(size); // If the below loop succeeds, there should always be at minimum 1 layer. - size_t num_layers = 1U; + wtf_size_t num_layers = 1U; // TODO(timloh): Shouldn't we fail if the lists are differently sized, with // the exception of background-color? - for (size_t i = 0; i < size; i++) { + for (unsigned i = 0; i < size; i++) { values[i] = property_set_.GetPropertyCSSValue(*shorthand.properties()[i]); if (values[i]->IsBaseValueList()) { const CSSValueList* value_list = ToCSSValueList(values[i]); @@ -887,7 +887,7 @@ StringBuilder result; // Now stitch the properties together. - for (size_t layer = 0; layer < num_layers; layer++) { + for (wtf_size_t layer = 0; layer < num_layers; layer++) { StringBuilder layer_result; bool use_repeat_x_shorthand = false; bool use_repeat_y_shorthand = false;
diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc index 8f7ebcf..f23aeb9f 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.cc +++ b/third_party/blink/renderer/core/exported/web_view_impl.cc
@@ -543,9 +543,6 @@ AnimateDoubleTapZoom( FlooredIntPoint(scaled_event.PositionInRootFrame())); } - // GestureDoubleTap is currently only used by Android for zooming. For - // WebCore, GestureTap with tap count = 2 is used instead. So we drop - // GestureDoubleTap here. event_result = WebInputEventResult::kHandledSystem; WidgetClient()->DidHandleGestureEvent(event, event_cancelled); return event_result; @@ -1515,8 +1512,7 @@ bool is_rotation = GetPage()->GetSettings().GetMainFrameResizesAreOrientationChanges() && - size_.width && ContentsSize().Width() && new_size.width == size_.height && - new_size.height == size_.width && + size_.width && ContentsSize().Width() && new_size.width != size_.width && !fullscreen_controller_->IsFullscreenOrTransitioning(); size_ = new_size;
diff --git a/third_party/blink/renderer/core/frame/rotation_viewport_anchor_test.cc b/third_party/blink/renderer/core/frame/rotation_viewport_anchor_test.cc index 46fe5e78..0bc00725 100644 --- a/third_party/blink/renderer/core/frame/rotation_viewport_anchor_test.cc +++ b/third_party/blink/renderer/core/frame/rotation_viewport_anchor_test.cc
@@ -25,9 +25,7 @@ } }; -// This tests that the rotation anchor doesn't make any changes to scroll -// when nothing on the page changes. -TEST_F(RotationViewportAnchorTest, SimpleAbsolutePositionNoOpRotation) { +TEST_F(RotationViewportAnchorTest, SimpleAbsolutePosition) { WebView().Resize(WebSize(400, 600)); SimRequest request("https://example.com/test.html", "text/html"); LoadURL("https://example.com/test.html"); @@ -119,60 +117,6 @@ EXPECT_EQ(expected_offset.Y(), layout_viewport->GetScrollOffset().Height()); } -// Ensure that only a size change that looks like a rotation (i.e. width and -// height are swapped) causes the rotation viewport anchoring behavior. Other -// resizes don't cause anchoring. -TEST_F(RotationViewportAnchorTest, OnlyRotationEngagesAnchor) { - WebView().Resize(WebSize(100, 600)); - SimRequest request("https://example.com/test.html", "text/html"); - LoadURL("https://example.com/test.html"); - request.Complete(R"HTML( - <!DOCTYPE html> - <style> - body { - width: 10000px; - height: 10000px; - margin: 0px; - } - - #target { - width: 50px; - height: 50px; - position: absolute; - left: 500%; - top: 500%; - } - </style> - <div id="target"></div> - )HTML"); - Compositor().BeginFrame(); - - Document& document = GetDocument(); - ScrollableArea* layout_viewport = document.View()->LayoutViewport(); - - IntPoint target_position(5 * WebView().Size().width, - 5 * WebView().Size().height); - - // Place the target at the top-center of the viewport. This is where the - // rotation anchor finds the node to anchor to. - layout_viewport->SetScrollOffset( - ScrollOffset(target_position.X() - WebView().Size().width / 2 + 25, - target_position.Y()), - kProgrammaticScroll); - - ScrollOffset expected_offset = layout_viewport->GetScrollOffset(); - - // Change just the width - we shouldn't consider this a rotation so the - // expectation is that the scroll offset won't change. - WebView().Resize(WebSize(600, 600)); - Compositor().BeginFrame(); - - EXPECT_EQ(expected_offset.Width(), - layout_viewport->GetScrollOffset().Width()); - EXPECT_EQ(expected_offset.Height(), - layout_viewport->GetScrollOffset().Height()); -} - } // namespace } // namespace blink
diff --git a/third_party/blink/renderer/core/html/image_document.h b/third_party/blink/renderer/core/html/image_document.h index d58b5ce..6732122 100644 --- a/third_party/blink/renderer/core/html/image_document.h +++ b/third_party/blink/renderer/core/html/image_document.h
@@ -98,12 +98,7 @@ ShrinkToFitMode shrink_to_fit_mode_; FRIEND_TEST_ALL_PREFIXES(ImageDocumentViewportTest, ZoomForDSFScaleImage); - FRIEND_TEST_ALL_PREFIXES(ImageDocumentViewportTest, - DivWidthWithZoomForDSFSmallerThanView); - FRIEND_TEST_ALL_PREFIXES(ImageDocumentViewportTest, - DivWidthWithZoomForDSFLargerThanView); - FRIEND_TEST_ALL_PREFIXES(ImageDocumentViewportTest, - DivWidthWithZoomForDSFMuchLargerThanView); + FRIEND_TEST_ALL_PREFIXES(ImageDocumentViewportTest, DivWidthWithZoomForDSF); }; DEFINE_DOCUMENT_TYPE_CASTS(ImageDocument);
diff --git a/third_party/blink/renderer/core/html/image_document_test.cc b/third_party/blink/renderer/core/html/image_document_test.cc index 8289d0a..4a293f7 100644 --- a/third_party/blink/renderer/core/html/image_document_test.cc +++ b/third_party/blink/renderer/core/html/image_document_test.cc
@@ -348,15 +348,11 @@ // Tests that with zoom factor for device scale factor, image with different // size fit in the viewport correctly. -TEST_F(ImageDocumentViewportTest, DivWidthWithZoomForDSFSmallerThanView) { +TEST_F(ImageDocumentViewportTest, DivWidthWithZoomForDSF) { v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); SimRequest request("https://example.com/test.jpg", "image/jpeg"); LoadURL("https://example.com/test.jpg"); - // Viewport is 100px (px == CSS pixels) width and height. - WebView().SetZoomFactorForDeviceScaleFactor(2.f); - WebView().Resize(IntSize(200, 200)); - Vector<unsigned char> jpeg = JpegImage(); Vector<char> data = Vector<char>(); data.Append(jpeg.data(), jpeg.size()); @@ -364,8 +360,11 @@ HTMLImageElement* img = GetDocument().ImageElement(); + WebView().SetZoomFactorForDeviceScaleFactor(2.f); + // Image smaller then webview size, visual viewport is not zoomed, and image // will be centered in the viewport. + WebView().Resize(IntSize(200, 200)); Compositor().BeginFrame(); EXPECT_EQ(50u, img->width()); EXPECT_EQ(50u, img->height()); @@ -376,25 +375,10 @@ DOMRect* rect = img->getBoundingClientRect(); EXPECT_EQ(25, rect->x()); EXPECT_EQ(25, rect->y()); -} - -TEST_F(ImageDocumentViewportTest, DivWidthWithZoomForDSFLargerThanView) { - v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); - SimRequest request("https://example.com/test.jpg", "image/jpeg"); - LoadURL("https://example.com/test.jpg"); - - WebView().SetZoomFactorForDeviceScaleFactor(2.f); - WebView().Resize(IntSize(50, 50)); - - Vector<unsigned char> jpeg = JpegImage(); - Vector<char> data = Vector<char>(); - data.Append(jpeg.data(), jpeg.size()); - request.Complete(data); - - HTMLImageElement* img = GetDocument().ImageElement(); // Image wider than webview size, image should fill the visual viewport, and // visual viewport zoom out to 0.5. + WebView().Resize(IntSize(50, 50)); Compositor().BeginFrame(); EXPECT_EQ(50u, img->width()); EXPECT_EQ(50u, img->height()); @@ -402,27 +386,10 @@ EXPECT_EQ(0.5f, GetVisualViewport().Scale()); EXPECT_EQ(50, GetVisualViewport().Width()); EXPECT_EQ(50, GetVisualViewport().Height()); -} -TEST_F(ImageDocumentViewportTest, DivWidthWithZoomForDSFMuchLargerThanView) { - v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); - SimRequest request("https://example.com/test.jpg", "image/jpeg"); - LoadURL("https://example.com/test.jpg"); - - WebView().SetZoomFactorForDeviceScaleFactor(2.f); - WebView().Resize(IntSize(4, 20)); - - Vector<unsigned char> jpeg = JpegImage(); - Vector<char> data = Vector<char>(); - data.Append(jpeg.data(), jpeg.size()); - request.Complete(data); - - HTMLImageElement* img = GetDocument().ImageElement(); - - // Image wider than webview size, image should fill the visual viewport, and - // visual viewport zoom out to 0.5. // When image is more than 10X wider than webview, shrink the image to fit the // width of the screen. + WebView().Resize(IntSize(4, 20)); Compositor().BeginFrame(); EXPECT_EQ(20u, img->width()); EXPECT_EQ(20u, img->height()); @@ -430,7 +397,7 @@ EXPECT_EQ(0.1f, GetVisualViewport().Scale()); EXPECT_EQ(20, GetVisualViewport().Width()); EXPECT_EQ(100, GetVisualViewport().Height()); - DOMRect* rect = img->getBoundingClientRect(); + rect = img->getBoundingClientRect(); EXPECT_EQ(0, rect->x()); EXPECT_EQ(40, rect->y()); }
diff --git a/third_party/blink/renderer/core/layout/grid_baseline_alignment.cc b/third_party/blink/renderer/core/layout/grid_baseline_alignment.cc index 07d539ed..08b2e63 100644 --- a/third_party/blink/renderer/core/layout/grid_baseline_alignment.cc +++ b/third_party/blink/renderer/core/layout/grid_baseline_alignment.cc
@@ -117,7 +117,7 @@ void GridBaselineAlignment::UpdateBaselineAlignmentContext( ItemPosition preference, unsigned shared_context, - LayoutBox& child, + const LayoutBox& child, GridAxis baseline_axis) { DCHECK(IsBaselinePosition(preference)); DCHECK(!child.NeedsLayout());
diff --git a/third_party/blink/renderer/core/layout/grid_baseline_alignment.h b/third_party/blink/renderer/core/layout/grid_baseline_alignment.h index e39ab6d7..43c017b 100644 --- a/third_party/blink/renderer/core/layout/grid_baseline_alignment.h +++ b/third_party/blink/renderer/core/layout/grid_baseline_alignment.h
@@ -142,7 +142,7 @@ // added item. void UpdateBaselineAlignmentContext(ItemPosition, unsigned shared_context, - LayoutBox&, + const LayoutBox&, GridAxis); // Returns the baseline offset of a particular item, based on the
diff --git a/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.cc b/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.cc index cbc3c20..2b74ea7 100644 --- a/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.cc +++ b/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.cc
@@ -420,9 +420,9 @@ bool GridTrackSizingAlgorithm::CanParticipateInBaselineAlignment( const LayoutBox& child, GridAxis baseline_axis) const { - if (child.NeedsLayout() || - !layout_grid_->IsBaselineAlignmentForChild(child, baseline_axis)) - return false; + DCHECK(baseline_axis == kGridColumnAxis + ? column_baseline_items_map_.Contains(&child) + : row_baseline_items_map_.Contains(&child)); // Baseline cyclic dependencies only happen with synthesized // baselines. These cases include orthogonal or empty grid items @@ -445,8 +445,16 @@ !child.StyleRef().LogicalWidth().IsAuto(); } +bool GridTrackSizingAlgorithm::ParticipateInBaselineAlignment( + const LayoutBox& child, + GridAxis baseline_axis) const { + return baseline_axis == kGridColumnAxis + ? column_baseline_items_map_.at(&child) + : row_baseline_items_map_.at(&child); +} + void GridTrackSizingAlgorithm::UpdateBaselineAlignmentContext( - LayoutBox& child, + const LayoutBox& child, GridAxis baseline_axis) { DCHECK(WasSetup()); DCHECK(CanParticipateInBaselineAlignment(child, baseline_axis)); @@ -463,7 +471,7 @@ LayoutUnit GridTrackSizingAlgorithm::BaselineOffsetForChild( const LayoutBox& child, GridAxis baseline_axis) const { - if (!CanParticipateInBaselineAlignment(child, baseline_axis)) + if (!ParticipateInBaselineAlignment(child, baseline_axis)) return LayoutUnit(); ItemPosition align = @@ -474,6 +482,29 @@ child, baseline_axis); } +void GridTrackSizingAlgorithm::ClearBaselineItemsCache() { + column_baseline_items_map_.clear(); + row_baseline_items_map_.clear(); +} + +void GridTrackSizingAlgorithm::CacheBaselineAlignedItem(const LayoutBox& item, + GridAxis axis) { + DCHECK(layout_grid_->IsBaselineAlignmentForChild(item, axis)); + if (axis == kGridColumnAxis) + column_baseline_items_map_.insert(&item, true); + else + row_baseline_items_map_.insert(&item, true); +} + +void GridTrackSizingAlgorithm::CopyBaselineItemsCache( + const GridTrackSizingAlgorithm& source, + GridAxis axis) { + if (axis == kGridColumnAxis) + column_baseline_items_map_ = source.column_baseline_items_map_; + else + row_baseline_items_map_ = source.row_baseline_items_map_; +} + LayoutUnit GridTrackSizingAlgorithmStrategy::ComputeTrackBasedSize() const { return algorithm_.ComputeTrackBasedSize(); } @@ -1596,10 +1627,19 @@ GridAxis axis = GridAxisForDirection(direction_); baseline_alignment_.Clear(axis); baseline_alignment_.SetBlockFlow(layout_grid_->StyleRef().GetWritingMode()); - for (auto* child = layout_grid_->FirstInFlowChildBox(); child; - child = child->NextInFlowSiblingBox()) { - if (CanParticipateInBaselineAlignment(*child, axis)) + BaselineItemsCache& baseline_items_cache = axis == kGridColumnAxis + ? column_baseline_items_map_ + : row_baseline_items_map_; + for (auto* child : baseline_items_cache.Keys()) { + // TODO (jfernandez): We may have to get rid of the baseline participation + // flag (hence just using a HashSet) depending on the CSS WG resolution on + // https://github.com/w3c/csswg-drafts/issues/3046 + if (CanParticipateInBaselineAlignment(*child, axis)) { UpdateBaselineAlignmentContext(*child, axis); + baseline_items_cache.Set(child, true); + } else { + baseline_items_cache.Set(child, false); + } } }
diff --git a/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.h b/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.h index 36ae436b6..33f9299 100644 --- a/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.h +++ b/third_party/blink/renderer/core/layout/grid_track_sizing_algorithm.h
@@ -102,6 +102,10 @@ LayoutUnit BaselineOffsetForChild(const LayoutBox&, GridAxis) const; + void CacheBaselineAlignedItem(const LayoutBox&, GridAxis); + void CopyBaselineItemsCache(const GridTrackSizingAlgorithm&, GridAxis); + void ClearBaselineItemsCache(); + LayoutSize EstimatedGridAreaBreadthForChild(const LayoutBox& child) const; Vector<GridTrack>& Tracks(GridTrackSizingDirection); @@ -161,8 +165,9 @@ GridTrackSizingDirection) const; void ComputeBaselineAlignmentContext(); - void UpdateBaselineAlignmentContext(LayoutBox&, GridAxis); + void UpdateBaselineAlignmentContext(const LayoutBox&, GridAxis); bool CanParticipateInBaselineAlignment(const LayoutBox&, GridAxis) const; + bool ParticipateInBaselineAlignment(const LayoutBox&, GridAxis) const; bool IsIntrinsicSizedGridArea(const LayoutBox&, GridAxis) const; void ComputeGridContainerIntrinsicSizes(); @@ -239,6 +244,9 @@ SizingState sizing_state_; GridBaselineAlignment baseline_alignment_; + typedef HashMap<const LayoutBox*, bool> BaselineItemsCache; + BaselineItemsCache column_baseline_items_map_; + BaselineItemsCache row_baseline_items_map_; // This is a RAII class used to ensure that the track sizing algorithm is // executed as it is suppossed to be, i.e., first resolve columns and then
diff --git a/third_party/blink/renderer/core/layout/layout_grid.cc b/third_party/blink/renderer/core/layout/layout_grid.cc index 3c574a62..aa0d5c3 100644 --- a/third_party/blink/renderer/core/layout/layout_grid.cc +++ b/third_party/blink/renderer/core/layout/layout_grid.cc
@@ -267,18 +267,35 @@ LayoutSize previous_size = Size(); has_definite_logical_height_ = HasDefiniteLogicalHeight(); - // Grid's layout logic controls the grid item's override height, hence - // we need to clear any override height set previously, so it doesn't - // interfere in current layout execution. - // Grid never uses the override width, that's why we don't need to clear it. has_any_orthogonal_item_ = false; for (auto* child = FirstInFlowChildBox(); child; child = child->NextInFlowSiblingBox()) { + // Grid's layout logic controls the grid item's override height, hence + // we need to clear any override height set previously, so it doesn't + // interfere in current layout execution. + // Grid never uses the override width, that's why we don't need to clear + // it. child->ClearOverrideLogicalHeight(); + + // We may need to repeat the track sizing in case of any grid item was + // orthogonal. if (GridLayoutUtils::IsOrthogonalChild(*this, *child)) has_any_orthogonal_item_ = true; - } + // We keep a cache of items with baseline as alignment values so + // that we only compute the baseline shims for such items. This + // cache is needed for performance related reasons due to the + // cost of evaluating the item's participation in a baseline + // context during the track sizing algorithm. + if (IsBaselineAlignmentForChild(*child, kGridColumnAxis)) { + track_sizing_algorithm_.CacheBaselineAlignedItem(*child, + kGridColumnAxis); + } + if (IsBaselineAlignmentForChild(*child, kGridRowAxis)) { + track_sizing_algorithm_.CacheBaselineAlignedItem(*child, kGridRowAxis); + } + } + baseline_items_cached_ = true; UpdateLogicalWidth(); TextAutosizer::LayoutScope text_autosizer_layout_scope(this, &layout_scope); @@ -358,6 +375,9 @@ UpdateAfterLayout(); ClearNeedsLayout(); + + track_sizing_algorithm_.ClearBaselineItemsCache(); + baseline_items_cached_ = false; } LayoutUnit LayoutGrid::GridGap( @@ -483,6 +503,17 @@ PerformGridItemsPreLayout(algorithm); + if (baseline_items_cached_) { + algorithm.CopyBaselineItemsCache(track_sizing_algorithm_, kGridRowAxis); + } else { + for (auto* child = FirstInFlowChildBox(); child; + child = child->NextInFlowSiblingBox()) { + if (IsBaselineAlignmentForChild(*child, kGridRowAxis)) { + algorithm.CacheBaselineAlignedItem(*child, kGridRowAxis); + } + } + } + ComputeTrackSizesForIndefiniteSize(algorithm, kForColumns, min_logical_width, max_logical_width);
diff --git a/third_party/blink/renderer/core/layout/layout_grid.h b/third_party/blink/renderer/core/layout/layout_grid.h index e43d3f3..00cd7ee 100644 --- a/third_party/blink/renderer/core/layout/layout_grid.h +++ b/third_party/blink/renderer/core/layout/layout_grid.h
@@ -284,8 +284,6 @@ LayoutUnit FirstLineBoxBaseline() const override; LayoutUnit InlineBlockBaseline(LineDirectionMode) const override; - void ComputeBaselineAlignmentContext(); - LayoutUnit ColumnAxisBaselineOffsetForChild(const LayoutBox&) const; LayoutUnit RowAxisBaselineOffsetForChild(const LayoutBox&) const; @@ -325,6 +323,7 @@ LayoutUnit max_content_height_{-1}; bool has_any_orthogonal_item_{false}; + bool baseline_items_cached_{false}; base::Optional<bool> has_definite_logical_height_; };
diff --git a/third_party/blink/renderer/core/layout/scroll_anchor.cc b/third_party/blink/renderer/core/layout/scroll_anchor.cc index 2f3ab2d..3edcb634 100644 --- a/third_party/blink/renderer/core/layout/scroll_anchor.cc +++ b/third_party/blink/renderer/core/layout/scroll_anchor.cc
@@ -465,7 +465,7 @@ } bool ScrollAnchor::RestoreAnchor(const SerializedAnchor& serialized_anchor) { - if (!scroller_ || anchor_object_ || !serialized_anchor.IsValid()) { + if (!scroller_ || !serialized_anchor.IsValid()) { return false; } @@ -473,6 +473,14 @@ DEFINE_STATIC_LOCAL(EnumerationHistogram, restoration_status_histogram, ("Layout.ScrollAnchor.RestorationStatus", kStatusCount)); + if (anchor_object_ && serialized_anchor.selector == saved_selector_) { + return true; + } + + if (anchor_object_) { + return false; + } + Document* document = &(ScrollerLayoutBox(scroller_)->GetDocument()); // This is a considered and deliberate usage of DummyExceptionStateForTesting. @@ -533,6 +541,7 @@ saved_selector_ = serialized_anchor.selector; restoration_status_histogram.Count(kSuccess); + return true; }
diff --git a/third_party/blink/renderer/core/layout/scroll_anchor.h b/third_party/blink/renderer/core/layout/scroll_anchor.h index 6810f83b..56ebdf6a 100644 --- a/third_party/blink/renderer/core/layout/scroll_anchor.h +++ b/third_party/blink/renderer/core/layout/scroll_anchor.h
@@ -128,6 +128,7 @@ bool viable; Corner corner; }; + ExamineResult Examine(const LayoutObject*) const; IntSize ComputeAdjustment() const;
diff --git a/third_party/blink/renderer/core/layout/scroll_anchor_test.cc b/third_party/blink/renderer/core/layout/scroll_anchor_test.cc index fabe57d..1ac0b4d 100644 --- a/third_party/blink/renderer/core/layout/scroll_anchor_test.cc +++ b/third_party/blink/renderer/core/layout/scroll_anchor_test.cc
@@ -885,4 +885,26 @@ GetScrollAnchor(LayoutViewport()).RestoreAnchor(serialized_anchor)); EXPECT_EQ(LayoutViewport()->ScrollOffsetInt().Height(), 100); } + +TEST_F(ScrollAnchorTest, RestoreAnchorSucceedsWithExistingAnchorObject) { + SetBodyInnerHTML( + "<style> body { height: 1000px; margin: 0; } div { height: 100px } " + "</style>" + "<div id='block1'>abc</div>" + "<div id='block2'>def</div>"); + + EXPECT_FALSE(GetScrollAnchor(LayoutViewport()).AnchorObject()); + + SerializedAnchor serialized_anchor("#block1", LayoutPoint(0, 0)); + + EXPECT_TRUE( + GetScrollAnchor(LayoutViewport()).RestoreAnchor(serialized_anchor)); + EXPECT_TRUE(GetScrollAnchor(LayoutViewport()).AnchorObject()); + EXPECT_EQ(LayoutViewport()->ScrollOffsetInt().Height(), 0); + + EXPECT_TRUE( + GetScrollAnchor(LayoutViewport()).RestoreAnchor(serialized_anchor)); + EXPECT_TRUE(GetScrollAnchor(LayoutViewport()).AnchorObject()); + EXPECT_EQ(LayoutViewport()->ScrollOffsetInt().Height(), 0); +} }
diff --git a/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc b/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc index 13d214c5..3b1a2aa 100644 --- a/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc +++ b/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc
@@ -1199,10 +1199,14 @@ &painting_layer->GetLayoutObject())); } - // Don't include scroll offset of paint_offset_root. Any scroll is - // already included in a separate transform node. - if (paint_offset_root->HasOverflowClip()) - result += ToLayoutBox(paint_offset_root)->ScrolledContentOffset(); + // Convert the result into the space of the scrolling contents space. + if (const auto* properties = + paint_offset_root->FirstFragment().PaintProperties()) { + if (const auto* scroll_translation = properties->ScrollTranslation()) { + DCHECK(scroll_translation->Matrix().IsIdentityOr2DTranslation()); + result += -LayoutSize(scroll_translation->Matrix().To2DTranslation()); + } + } return result; } @@ -1848,16 +1852,8 @@ const auto& paint_offset_root_fragment = context_.current.paint_offset_root->FirstFragment(); paint_offset.MoveBy(paint_offset_root_fragment.PaintOffset()); - if (paint_offset_root_fragment.PaintProperties() && - paint_offset_root_fragment.PaintProperties()->ScrollTranslation()) { - // This duplicates the logic of the additional paint offset for scrolling - // contents in UpdateScrollTranslation(). - paint_offset.MoveBy( - ToLayoutBox(context_.current.paint_offset_root)->ScrollOrigin()); - } context_.current.paint_offset = paint_offset; - return; }
diff --git a/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc b/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc index 60cb1768..73c7521 100644 --- a/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc +++ b/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc
@@ -439,6 +439,49 @@ EXPECT_EQ(FloatRoundedRect(25, 10, 85, 85), overflow_clip->ClipRect()); } +TEST_P(PaintPropertyTreeBuilderTest, OverflowScrollVerticalRLMulticol) { + SetBodyInnerHTML(R"HTML( + <style>::-webkit-scrollbar {width: 15px; height: 15px}</style> + <div id='scroller' + style='width: 100px; height: 100px; overflow: scroll; + writing-mode: vertical-rl; border: 10px solid blue'> + <div id="multicol" + style="width: 50px; height: 400px; columns: 2; column-gap: 0"> + <div style="width: 100px"></div> + </div> + <div style='width: 400px; height: 400px'></div> + </div> + )HTML"); + + const auto* flow_thread = + GetLayoutObjectByElementId("multicol")->SlowFirstChild(); + auto check_fragments = [flow_thread]() { + ASSERT_EQ(2u, NumFragments(flow_thread)); + EXPECT_EQ(410, FragmentAt(flow_thread, 0) + .PaintProperties() + ->FragmentClip() + ->ClipRect() + .Rect() + .X()); + EXPECT_EQ(LayoutPoint(360, 10), FragmentAt(flow_thread, 0).PaintOffset()); + EXPECT_EQ(460, FragmentAt(flow_thread, 1) + .PaintProperties() + ->FragmentClip() + ->ClipRect() + .Rect() + .MaxX()); + EXPECT_EQ(LayoutPoint(410, 210), FragmentAt(flow_thread, 1).PaintOffset()); + }; + check_fragments(); + + // Fragment geometries are not affected by parent scrolling. + ToLayoutBox(GetLayoutObjectByElementId("scroller")) + ->GetScrollableArea() + ->ScrollBy(ScrollOffset(-100, 200), kUserScroll); + GetDocument().View()->UpdateAllLifecyclePhases(); + check_fragments(); +} + TEST_P(PaintPropertyTreeBuilderTest, DocScrollingTraditional) { SetBodyInnerHTML("<style> body { height: 10000px; } </style>");
diff --git a/third_party/blink/renderer/core/style/fill_layer.cc b/third_party/blink/renderer/core/style/fill_layer.cc index 16d68469..4d521a02 100644 --- a/third_party/blink/renderer/core/style/fill_layer.cc +++ b/third_party/blink/renderer/core/style/fill_layer.cc
@@ -189,6 +189,8 @@ if (image_ || o.image_) { if (!LayerPropertiesEqual(o)) return false; + } else if (clip_ != o.clip_) { + return false; } if (next_ && o.next_) return next_->VisuallyEqual(*o.next_);
diff --git a/third_party/blink/renderer/modules/accessibility/ax_node_object.cc b/third_party/blink/renderer/modules/accessibility/ax_node_object.cc index c11807c..17072ba0 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_node_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_node_object.cc
@@ -2601,7 +2601,7 @@ source.related_objects = *related_objects; source.text = text_alternative; } else { - return text_alternative; + return text_alternative.StripWhiteSpace(); } } else if (name_sources) { name_sources->back().invalid = true;
diff --git a/third_party/blink/renderer/modules/payments/payment_request.cc b/third_party/blink/renderer/modules/payments/payment_request.cc index 040d260..295bb34 100644 --- a/third_party/blink/renderer/modules/payments/payment_request.cc +++ b/third_party/blink/renderer/modules/payments/payment_request.cc
@@ -675,7 +675,7 @@ return; } - if (input.hasError() && !input.error().IsNull()) { + if (input.hasError()) { String error_message; if (!PaymentsValidators::IsValidErrorMsgFormat(input.error(), &error_message)) { @@ -683,8 +683,6 @@ return; } output->error = input.error(); - } else { - output->error = ""; } if (input.hasShippingAddressErrors()) {
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index ca5fcd5c..ecc90cd 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -845,6 +845,9 @@ status: "experimental", }, { + name: "OffMainThreadCSSPaint", + }, + { name: "OffMainThreadWebSocket", }, { @@ -908,7 +911,6 @@ // Compute touch action rects in paint instead of ScrollingCoordinator. { name: "PaintTouchActionRects", - status: "stable", }, // PaintTracking enables the Largest Text Paint metric, Last Text Paint // metric, Largest Image Paint metric and Last Image Paint metric.
diff --git a/third_party/libvpx/README.chromium b/third_party/libvpx/README.chromium index bb1c583..dc770bee 100644 --- a/third_party/libvpx/README.chromium +++ b/third_party/libvpx/README.chromium
@@ -5,9 +5,9 @@ License File: source/libvpx/LICENSE Security Critical: yes -Date: Thursday September 20 2018 +Date: Saturday September 22 2018 Branch: master -Commit: 282087a14c84a65f10b3a8d0e81c255e13a7a746 +Commit: 3448987ab20aa05716ffc4aedf6d02e23f75920b Description: Contains the sources used to compile libvpx binaries used by Google Chrome and
diff --git a/third_party/libvpx/source/config/vpx_version.h b/third_party/libvpx/source/config/vpx_version.h index 4037c435..b3f6a26 100644 --- a/third_party/libvpx/source/config/vpx_version.h +++ b/third_party/libvpx/source/config/vpx_version.h
@@ -2,7 +2,7 @@ #define VERSION_MAJOR 1 #define VERSION_MINOR 7 #define VERSION_PATCH 0 -#define VERSION_EXTRA "1035-g282087a14" +#define VERSION_EXTRA "1064-g3448987ab" #define VERSION_PACKED ((VERSION_MAJOR<<16)|(VERSION_MINOR<<8)|(VERSION_PATCH)) -#define VERSION_STRING_NOSP "v1.7.0-1035-g282087a14" -#define VERSION_STRING " v1.7.0-1035-g282087a14" +#define VERSION_STRING_NOSP "v1.7.0-1064-g3448987ab" +#define VERSION_STRING " v1.7.0-1064-g3448987ab"
diff --git a/third_party/robolectric/custom_asynctask/java/src/org/chromium/base/task/test/ShadowAsyncTaskBridge.java b/third_party/robolectric/custom_asynctask/java/src/org/chromium/base/task/test/ShadowAsyncTaskBridge.java index 11a6af6..2e9be02b 100644 --- a/third_party/robolectric/custom_asynctask/java/src/org/chromium/base/task/test/ShadowAsyncTaskBridge.java +++ b/third_party/robolectric/custom_asynctask/java/src/org/chromium/base/task/test/ShadowAsyncTaskBridge.java
@@ -6,7 +6,7 @@ import org.robolectric.util.ReflectionHelpers.ClassParameter; /** - * Bridge between shadows and {@link org.chromium.base.AsyncTask}. + * Bridge between shadows and {@link org.chromium.base.task.AsyncTask}. */ @DoNotInstrument public class ShadowAsyncTaskBridge<Result> {
diff --git a/third_party/robolectric/custom_asynctask/java/src/org/chromium/base/test/asynctask/ShadowAsyncTask.java b/third_party/robolectric/custom_asynctask/java/src/org/chromium/base/test/asynctask/ShadowAsyncTask.java deleted file mode 100644 index e4443e7..0000000 --- a/third_party/robolectric/custom_asynctask/java/src/org/chromium/base/test/asynctask/ShadowAsyncTask.java +++ /dev/null
@@ -1,135 +0,0 @@ -package org.chromium.base.test.asynctask; - -import org.chromium.base.AsyncTask; -import java.util.concurrent.Callable; -import java.util.concurrent.CancellationException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executor; -import java.util.concurrent.FutureTask; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import org.robolectric.annotation.Implementation; -import org.robolectric.annotation.Implements; -import org.robolectric.annotation.RealObject; -import org.robolectric.shadows.ShadowApplication; - -@Implements(AsyncTask.class) -public class ShadowAsyncTask<Result> { - @RealObject - private AsyncTask<Result> realAsyncTask; - - private final FutureTask<Result> future; - private final Callable<Result> worker; - private AsyncTask.Status status = AsyncTask.Status.PENDING; - - public ShadowAsyncTask() { - worker = new Callable<Result>() { - @Override - public Result call() throws Exception { - return getBridge().doInBackground(); - } - }; - future = new FutureTask<Result>(worker) { - @Override - protected void done() { - status = AsyncTask.Status.FINISHED; - try { - final Result result = get(); - - try { - ShadowApplication.getInstance().getForegroundThreadScheduler().post( - new Runnable() { - @Override - public void run() { - getBridge().onPostExecute(result); - } - }); - } catch (Throwable t) { - throw new OnPostExecuteException(t); - } - } catch (CancellationException e) { - ShadowApplication.getInstance().getForegroundThreadScheduler().post( - new Runnable() { - @Override - public void run() { - getBridge().onCancelled(); - } - }); - } catch (InterruptedException e) { - // Ignore. - } catch (OnPostExecuteException e) { - throw new RuntimeException(e.getCause()); - } catch (Throwable t) { - throw new RuntimeException( - "An error occured while executing doInBackground()", t.getCause()); - } - } - }; - } - - @Implementation - public boolean isCancelled() { - return future.isCancelled(); - } - - @Implementation - public boolean cancel(boolean mayInterruptIfRunning) { - return future.cancel(mayInterruptIfRunning); - } - - @Implementation - public Result get() throws InterruptedException, ExecutionException { - return future.get(); - } - - @Implementation - public Result get(long timeout, TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException { - return future.get(timeout, unit); - } - - public AsyncTask<Result> executeInRobolectric() { - status = AsyncTask.Status.RUNNING; - getBridge().onPreExecute(); - - ShadowApplication.getInstance().getBackgroundThreadScheduler().post(new Runnable() { - @Override - public void run() { - future.run(); - } - }); - - return realAsyncTask; - } - - @SuppressWarnings("unchecked") - @Implementation - public AsyncTask<Result> executeOnExecutor(Executor executor) { - status = AsyncTask.Status.RUNNING; - getBridge().onPreExecute(); - - executor.execute(new Runnable() { - @Override - public void run() { - future.run(); - } - }); - - return realAsyncTask; - } - - @Implementation - public AsyncTask.Status getStatus() { - return status; - } - - private ShadowAsyncTaskBridge<Result> getBridge() { - return new ShadowAsyncTaskBridge<>(realAsyncTask); - } - - private static class OnPostExecuteException extends Exception { - public OnPostExecuteException(Throwable throwable) { - super(throwable); - } - } -}
diff --git a/third_party/robolectric/custom_asynctask/java/src/org/chromium/base/test/asynctask/ShadowAsyncTaskBridge.java b/third_party/robolectric/custom_asynctask/java/src/org/chromium/base/test/asynctask/ShadowAsyncTaskBridge.java deleted file mode 100644 index e6d6a7a..0000000 --- a/third_party/robolectric/custom_asynctask/java/src/org/chromium/base/test/asynctask/ShadowAsyncTaskBridge.java +++ /dev/null
@@ -1,35 +0,0 @@ -package org.chromium.base.test.asynctask; - -import org.chromium.base.AsyncTask; -import org.robolectric.annotation.internal.DoNotInstrument; -import org.robolectric.util.ReflectionHelpers; -import org.robolectric.util.ReflectionHelpers.ClassParameter; - -/** - * Bridge between shadows and {@link org.chromium.base.AsyncTask}. - */ -@DoNotInstrument -public class ShadowAsyncTaskBridge<Result> { - private AsyncTask<Result> asyncTask; - - public ShadowAsyncTaskBridge(AsyncTask<Result> asyncTask) { - this.asyncTask = asyncTask; - } - - public Result doInBackground() { - return ReflectionHelpers.callInstanceMethod(asyncTask, "doInBackground"); - } - - public void onPreExecute() { - ReflectionHelpers.callInstanceMethod(asyncTask, "onPreExecute"); - } - - public void onPostExecute(Result result) { - ReflectionHelpers.callInstanceMethod( - asyncTask, "onPostExecute", ClassParameter.from(Object.class, result)); - } - - public void onCancelled() { - ReflectionHelpers.callInstanceMethod(asyncTask, "onCancelled"); - } -}
diff --git a/tools/DEPS b/tools/DEPS index 88fa2ec..4a8eca10 100644 --- a/tools/DEPS +++ b/tools/DEPS
@@ -1,7 +1,6 @@ # checkdeps.py shouldn't check include paths for files in these dirs: skip_child_includes = [ "clang", - "gyp", "traceline", "perf/page_sets", ]
diff --git a/tools/android/errorprone_plugin/src/org/chromium/tools/errorprone/plugin/NoAndroidAsyncTaskCheck.java b/tools/android/errorprone_plugin/src/org/chromium/tools/errorprone/plugin/NoAndroidAsyncTaskCheck.java index 32161cd0..9fb2a49 100644 --- a/tools/android/errorprone_plugin/src/org/chromium/tools/errorprone/plugin/NoAndroidAsyncTaskCheck.java +++ b/tools/android/errorprone_plugin/src/org/chromium/tools/errorprone/plugin/NoAndroidAsyncTaskCheck.java
@@ -18,7 +18,7 @@ */ @AutoService(BugChecker.class) @BugPattern(name = "NoAndroidAsyncTaskCheck", category = BugPattern.Category.ANDROID, - summary = "Do not use android.os.AsyncTask - use org.chromium.base.AsyncTask instead", + summary = "Do not use android.os.AsyncTask - use org.chromium.base.task.AsyncTask instead", severity = BugPattern.SeverityLevel.ERROR, linkType = BugPattern.LinkType.CUSTOM, link = "https://bugs.chromium.org/p/chromium/issues/detail?id=843745") public class NoAndroidAsyncTaskCheck @@ -30,7 +30,7 @@ if (symbol.getQualifiedName().contentEquals("android.os")) { return buildDescription(tree) .setMessage("Do not use android.os.AsyncTask - " - + "use org.chromium.base.AsyncTask instead") + + "use org.chromium.base.task.AsyncTask instead") .build(); } }
diff --git a/tools/binary_size/libsupersize/generate_milestone_report.py b/tools/binary_size/libsupersize/generate_milestone_report.py index 70b1d10fd..eb13d7ce 100755 --- a/tools/binary_size/libsupersize/generate_milestone_report.py +++ b/tools/binary_size/libsupersize/generate_milestone_report.py
@@ -254,7 +254,7 @@ skip_existing=args.skip_existing) _SetPushedReports(args.directory) logging.warning('Reports saved to %s', args.directory) - cmd = ['gsutil.py', '-m', 'rsync', '-J', '-a', 'publicRead', '-r', + cmd = ['gsutil.py', '-m', 'rsync', '-J', '-a', 'public-read', '-r', args.directory, PUSH_URL] if args.sync:
diff --git a/tools/binary_size/libsupersize/html_report.py b/tools/binary_size/libsupersize/html_report.py index 48f9a94..fa8873b 100644 --- a/tools/binary_size/libsupersize/html_report.py +++ b/tools/binary_size/libsupersize/html_report.py
@@ -291,7 +291,7 @@ 'View using a local server via: ', ' %s start_server %s', 'or upload to the hosted version here:', - ' https://storage.googleapis.com/chrome-supersize/index.html' + ' https://storage.googleapis.com/chrome-supersize/viewer.html' ] supersize_path = os.path.relpath(os.path.join( path_util.SRC_ROOT, 'tools', 'binary_size', 'supersize'))
diff --git a/tools/binary_size/libsupersize/start_server.py b/tools/binary_size/libsupersize/start_server.py index e956108e..a253d4e 100644 --- a/tools/binary_size/libsupersize/start_server.py +++ b/tools/binary_size/libsupersize/start_server.py
@@ -47,6 +47,7 @@ httpd = BaseHTTPServer.HTTPServer(server_addr, SupersizeHTTPRequestHandler) sa = httpd.socket.getsockname() - logging.warning('Server ready at http://%s:%d?data_url=data.ndjson', - sa[0], sa[1]) + logging.warning( + 'Server ready at http://%s:%d/viewer.html?load_url=data.ndjson', + sa[0], sa[1]) httpd.serve_forever()
diff --git a/tools/binary_size/libsupersize/static/index.html b/tools/binary_size/libsupersize/static/index.html index c3a724c8..aae68e1 100644 --- a/tools/binary_size/libsupersize/static/index.html +++ b/tools/binary_size/libsupersize/static/index.html
@@ -8,502 +8,166 @@ <head> <title>Super Size Tiger View</title> - <script src="start-worker.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="theme-color" content="#4285f4"> <link href="https://fonts.googleapis.com/css?family=Google+Sans:400,500|Roboto:400,500" rel="stylesheet"> <link rel="stylesheet" href="main.css"> <link rel="stylesheet" href="options.css"> - <link rel="icon" href="favicon.ico" sizes="16x16 32x32 256x256" type="image/x-icon"> - <link rel="manifest" href="manifest.json"> - <script defer src="shared.js"></script> - <script defer src="state.js"></script> - <script defer src="infocard-ui.js"></script> - <script defer src="tree-ui.js"></script> - <script defer async> -if ('serviceWorker' in navigator) { - navigator.serviceWorker.register('sw.js') - .catch(() => console.warn('ServiceWorker not loaded.')); + <style> +body { + grid-template-columns: auto; + grid-template-areas: "appbar" "select"; } +form { + grid-area: 'select'; + margin: auto; +} + </style> + <link rel="icon" href="favicon.ico" sizes="16x16 32x32 256x256" type="image/x-icon"> + <script> +/** + * @param {string[]} options + */ +function buildOptions(options) { + const fragment = document.createDocumentFragment(); + for (const option of options) { + const optionEl = document.createElement('option'); + optionEl.value = option; + optionEl.textContent = option; + fragment.appendChild(optionEl); + } + return fragment; +} + +/** + * Is `v1` a larger version than `v2`? + * @param {string} v1 + * @param {string} v2 + */ +function isGreaterOrEqual(v1, v2) { + const [version1] = v1.split('.', 1).map(n => parseInt(n, 10)); + const [version2] = v2.split('.', 1).map(n => parseInt(n, 10)); + return version1 >= version2; +} + +(async () => { + const response = await fetch('milestones/milestones.json'); + const {pushed} = await response.json(); + + if (document.readyState === 'loading') { + await new Promise(resolve => { + document.onreadystatechange = () => { + if (document.readyState !== 'loading') { + resolve(); + document.onreadystatechange = null; + } + } + }); + } + + /** @type {HTMLFormElement} */ + const form = document.getElementById('select-form'); + const selMode = form.elements.namedItem('mode'); + const selCpu = form.elements.namedItem('cpu'); + const selApk = form.elements.namedItem('apk'); + const selVersion1 = form.elements.namedItem('version1'); + const selVersion2 = form.elements.namedItem('version2'); + const btnOpen = form.querySelector('button[type="submit"]'); + const msgBadCompare = form.querySelector('.msg-bad-compare'); + + selCpu.appendChild(buildOptions(pushed.cpu)); + selApk.appendChild(buildOptions(pushed.apk)); + const versionOptions = buildOptions(pushed.version); + selVersion1.appendChild(versionOptions.cloneNode(true)); + selVersion2.appendChild(versionOptions); + + function selectOption(optList, index) { + const n = optList.length; + if (n > 0) optList[((index % n) + n) % n].selected = true; + } + selectOption(selVersion1.querySelectorAll('option'), -2); + selectOption(selVersion2.querySelectorAll('option'), -1); + + let viewMode = null; + function readViewMode() { + viewMode = document.querySelector('#sel-mode').value; + form.classList.toggle('mode-view', viewMode === 'view'); + } + readViewMode(); + + function disableButtonIfNoDiffPair() { + const isDisabled = (viewMode === 'compare') && + isGreaterOrEqual(selVersion1.value, selVersion2.value); + btnOpen.disabled = isDisabled; + msgBadCompare.classList.toggle('visible', isDisabled); + } + disableButtonIfNoDiffPair(); + + selMode.addEventListener('change', () => { + readViewMode(); + disableButtonIfNoDiffPair(); + }); + + function getDataUrl() { + let ret = `${cpu.value}/${apk.value}/`; + if (viewMode === 'view') { + ret += `report_${selVersion2.value}.ndjson`; + } else if (viewMode === 'compare') { + ret += `report_${selVersion1.value}_${selVersion2.value}.ndjson`; + } + return ret; + } + + selVersion1.addEventListener('change', disableButtonIfNoDiffPair); + selVersion2.addEventListener('change', disableButtonIfNoDiffPair); + form.addEventListener('submit', event => { + event.preventDefault(); + const dataUrl = getDataUrl(); + window.open(`viewer.html?load_url=milestones/${dataUrl}`); + }); +})(); </script> </head> <body> <div class="scrim toggle-options" hidden></div> - <!-- App Toolbar --> <header class="appbar"> <div class="appbar-inner"> <h1 class="headline">Super Size Tiger View</h1> - <input type="file" name="upload" id="upload" accept=".ndjson" > - <label for="upload" class="text-button filled-button with-icon"> - <svg class="icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="#fff"> - <!-- - Icons from https://material.io/tools/icons/?style=outline - with some custom icons designed in the same style - --> - <path d="M6 2a2 2 0 0 0-2 2v16c0 1.1.9 2 2 2h12a2 2 0 0 0 2-2V8l-6-6H6zm0 2h7v5h5v11H6V4zm6 7l-4 4h3v4h2v-4h3l-4-4z" /> - </svg> - <span class="label-text">Upload data</span> - </label> - <a href="https://chromium.googlesource.com/chromium/src/+/master/tools/binary_size/html_report_faq.md" class="icon-button" - title="FAQ" id="faq" target="_blank"> - <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#5f6368"> - <path d="M11,18h2v-2h-2V18z M12,2C6.48,2,2,6.48,2,12s4.48,10,10,10s10-4.48,10-10S17.52,2,12,2z M12,20c-4.41,0-8-3.59-8-8 - s3.59-8,8-8s8,3.59,8,8S16.41,20,12,20z M12,6c-2.21,0-4,1.79-4,4h2c0-1.1,0.9-2,2-2s2,0.9,2,2c0,2-3,1.75-3,5h2c0-2.25,3-2.5,3-5 - C16,7.79,14.21,6,12,6z" /> - </svg> - </a> - <button type="button" class="icon-button toggle-options" title="Settings"> - <svg class="settings" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#5f6368"> - <path d="M19.43,12.98c0.04-0.32,0.07-0.64,0.07-0.98c0-0.34-0.03-0.66-0.07-0.98l2.11-1.65c0.19-0.15,0.24-0.42,0.12-0.64l-2-3.46 - c-0.09-0.16-0.26-0.25-0.44-0.25c-0.06,0-0.12,0.01-0.17,0.03l-2.49,1c-0.52-0.4-1.08-0.73-1.69-0.98l-0.38-2.65 - C14.46,2.18,14.25,2,14,2h-4C9.75,2,9.54,2.18,9.51,2.42L9.13,5.07C8.52,5.32,7.96,5.66,7.44,6.05l-2.49-1 - C4.89,5.03,4.83,5.02,4.77,5.02c-0.17,0-0.34,0.09-0.43,0.25l-2,3.46C2.21,8.95,2.27,9.22,2.46,9.37l2.11,1.65 - C4.53,11.34,4.5,11.67,4.5,12c0,0.33,0.03,0.66,0.07,0.98l-2.11,1.65c-0.19,0.15-0.24,0.42-0.12,0.64l2,3.46 - c0.09,0.16,0.26,0.25,0.44,0.25c0.06,0,0.12-0.01,0.17-0.03l2.49-1c0.52,0.4,1.08,0.73,1.69,0.98l0.38,2.65 - C9.54,21.82,9.75,22,10,22h4c0.25,0,0.46-0.18,0.49-0.42l0.38-2.65c0.61-0.25,1.17-0.59,1.69-0.98l2.49,1 - c0.06,0.02,0.12,0.03,0.18,0.03c0.17,0,0.34-0.09,0.43-0.25l2-3.46c0.12-0.22,0.07-0.49-0.12-0.64L19.43,12.98z M17.45,11.27 - c0.04,0.31,0.05,0.52,0.05,0.73c0,0.21-0.02,0.43-0.05,0.73l-0.14,1.13l0.89,0.7l1.08,0.84l-0.7,1.21l-1.27-0.51l-1.04-0.42 - l-0.9,0.68c-0.43,0.32-0.84,0.56-1.25,0.73l-1.06,0.43l-0.16,1.13L12.7,20H11.3l-0.19-1.35l-0.16-1.13l-1.06-0.43 - c-0.43-0.18-0.83-0.41-1.23-0.71l-0.91-0.7l-1.06,0.43l-1.27,0.51l-0.7-1.21l1.08-0.84l0.89-0.7l-0.14-1.13 - C6.52,12.43,6.5,12.2,6.5,12s0.02-0.43,0.05-0.73l0.14-1.13L5.8,9.44L4.72,8.6l0.7-1.21l1.27,0.51l1.04,0.42l0.9-0.68 - c0.43-0.32,0.84-0.56,1.25-0.73l1.06-0.43l0.16-1.13L11.3,4h1.39l0.19,1.35l0.16,1.13l1.06,0.43c0.43,0.18,0.83,0.41,1.23,0.71 - l0.91,0.7l1.06-0.43l1.27-0.51l0.7,1.21L18.2,9.44l-0.89,0.7L17.45,11.27z" /> - <path d="M12,8c-2.21,0-4,1.79-4,4s1.79,4,4,4s4-1.79,4-4S14.21,8,12,8z M12,14c-1.1,0-2-0.9-2-2s0.9-2,2-2s2,0.9,2,2 - S13.1,14,12,14z" /> - </svg> - </button> </div> - <progress value="0" id="progress" class="appbar-progress"></progress> </header> - <!-- Options side panel --> - <form id="options" class="options" method="GET"> - <header class="form-bar"> - <button type="button" class="icon-button toggle-options" title="Close"> - <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#5f6368"> - <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" /> - </svg> - </button> - </header> - <input type="hidden" name="data_url" data-dynamic> - - <fieldset> - <legend class="subhead">Size options</legend> - <div class="checkbox-wrapper"> - <input type="checkbox" id="methodcount" name="method_count" value="on"> - <label class="checkbox-label" for="methodcount">Method Count Mode</label> - </div> - <p class="select-wrapper"> - <select id="byteunit" name="byteunit" data-dynamic> - <option value="B">B - bytes</option> - <option value="KiB" selected>KiB - kibibytes</option> - <option value="MiB">MiB - mebibytes</option> - <option value="GiB">GiB - gibibytes</option> - </select> - <label class="select-label" for="byteunit">Byte unit</label> - </p> - <p class="input-wrapper"> - <input type="number" id="minsize" name="min_size" value="0" min="0"> - <label class="input-label" for="minsize"> - Minimum size (bytes) - </label> - </p> - </fieldset> - - <fieldset> - <legend class="subhead">Group symbols by</legend> - <div class="radio-wrapper"> - <input type="radio" id="sourcepath" name="group_by" value="source_path" checked> - <label class="radio-label" for="sourcepath">Source path</label> - </div> - <div class="radio-wrapper"> - <input type="radio" id="component" name="group_by" value="component"> - <label class="radio-label" for="component">Component</label> - </div> - </fieldset> - - <fieldset> - <legend class="subhead">Search by regex</legend> - <div class="input-wrapper"> - <input class="input-regex" type="text" id="includeregex" name="include" placeholder=".+@.+" aria-describedby="include-error"> - <label class="input-label" for="includeregex"> - Symbols must contain - </label> - <p class="input-error" id="include-error"></p> - </div> - <div class="input-wrapper"> - <input class="input-regex" type="text" id="excluderegex" name="exclude" placeholder="\(.+\)" aria-describedby="exclude-error"> - <label class="input-label" for="excluderegex"> - Symbols must exclude - </label> - <p class="input-error" id="exclude-error"></p> - </div> - </fieldset> - - <fieldset id="types-filter"> - <legend class="subhead">Symbol types to show</legend> - <div class="checkbox-wrapper"> - <input type="checkbox" id="filtertext" name="type" value="t" checked> - <label class="checkbox-label" for="filtertext"> - Native code: .text - </label> - </div> - <div class="checkbox-wrapper"> - <input type="checkbox" id="filterdata" name="type" value="d" checked> - <label class="checkbox-label" for="filterdata"> - Native code: .data - </label> - </div> - <div class="checkbox-wrapper"> - <input type="checkbox" id="filterrodata" name="type" value="r" checked> - <label class="checkbox-label" for="filterrodata"> - Native code: .rodata - </label> - </div> - <div class="checkbox-wrapper"> - <input type="checkbox" id="filterrelro" name="type" value="R" checked> - <label class="checkbox-label" for="filterrelro"> - Native code: .data.rel.ro - </label> - </div> - <div class="checkbox-wrapper"> - <input type="checkbox" id="filterdex" name="type" value="m" checked> - <label class="checkbox-label" for="filterdex"> - Dex: Methods - </label> - </div> - <div class="checkbox-wrapper"> - <input type="checkbox" id="filterdexnon" name="type" value="x" checked> - <label class="checkbox-label" for="filterdexnon"> - Dex: Other - </label> - </div> - <div class="checkbox-wrapper"> - <input type="checkbox" id="filterpak" name="type" value="p" checked> - <label class="checkbox-label" for="filterpak"> - Pak: Translations - </label> - </div> - <div class="checkbox-wrapper"> - <input type="checkbox" id="filterpaknon" name="type" value="P" checked> - <label class="checkbox-label" for="filterpaknon"> - Pak: Non-translations - </label> - </div> - <div class="checkbox-wrapper"> - <input type="checkbox" id="filterother" name="type" value="o" checked> - <label class="checkbox-label" for="filterother"> - Assets & Miscellaneous Entries - </label> - </div> - <div class="checkbox-wrapper"> - <input type="checkbox" id="filterbss" name="type" value="b"> - <label class="checkbox-label" for="filterbss"> - Native Code: .bss - </label> - </div> - <button type="button" class="text-button" id="type-all">Select all</button> - <button type="button" class="text-button" id="type-none">Select none</button> - </fieldset> - - <fieldset id="highlight-container"> - <legend class="subhead">Highlight symbols</legend> - <div class="radio-wrapper"> - <input type="radio" id="clearhighlight" name="highlight" value="clear" checked> - <label class="radio-label" for="clearhighlight">None</label> - </div> - <div class="radio-wrapper"> - <input type="radio" id="hothighlight" name="highlight" value="hot"> - <label class="radio-label" for="hothighlight">Hot code</label> - </div> - <div class="radio-wrapper"> - <input type="radio" id="generatedhighlight" name="highlight" value="generated"> - <label class="radio-label" for="generatedhighlight">Generated files</label> - </div> - <div class="radio-wrapper"> - <input type="radio" id="coveragehightlight" name="highlight" value="coverage"> - <label class="radio-label" for="coveragehightlight">Code coverage (not implemented)</label> - </div> - <div class="radio-wrapper"> - <input type="radio" id="uncompressedhighlight" name="highlight" value="uncompressed"> - <label class="radio-label" for="uncompressedhighlight">Uncompressed .pak files</label> - </div> - </fieldset> - - <p class="checkbox-wrapper"> - <input type="checkbox" id="generatedfilter" name="generated_filter" value="on"> - <label class="checkbox-label" for="generatedfilter">Show only generated files</label> + <form id="select-form"> + <h2 class="subhead">Select milestones to + <select id="sel-mode" class="sel-small" name="mode"> + <option value="view">view</option> + <option value="compare" selected="selected">compare</option> + </select> + </h2> + <p class="select-wrapper"> + <select id="cpu" class="sel-big" name="cpu"></select> + <label class="select-label" for="cpu">Architecture</label> </p> + <p class="select-wrapper"> + <select id="apk" class="sel-big" name="apk"></select> + <label class="select-label" for="apk">APK</label> + </p> + <p class="select-wrapper hide-on-mode-view"> + <select id="version1" class="sel-big" name="version1"></select> + <label class="select-label" for="version1">Version 1</label> + </p> + <p class="select-wrapper"> + <select id="version2" class="sel-big" name="version2"></select> + <label class="select-label" for="version2"> + Version <span class="hide-on-mode-view"> 2</span> + </label> + </p> + + <button type="submit" class="text-button filled-button"> + Open report + </button> + <div class="msg-bad-compare">Version 1 must be older than Version 2</div> </form> - <div class="symbols"> - <!-- Icons for symbols are stored here and cloned. --> - <div hidden id="icons"> - <svg class="icon foldericon" height="24" width="24" fill="#5f6368"> - <title>Directory</title> - <path d="M9.17,6l2,2H20v10L4,18V6H9.17 M10,4H4C2.9,4,2.01,4.9,2.01,6L2,18c0,1.1,0.9,2,2,2h16c1.1,0,2-0.9,2-2V8c0-1.1-0.9-2-2-2 - h-8L10,4L10,4z" /> - </svg> - <svg class="icon componenticon" height="24" width="24" fill="#5f6368"> - <title>Component</title> - <path d="M9,13.75c-2.34,0-7,1.17-7,3.5V19h14v-1.75C16,14.92,11.34,13.75,9,13.75z M4.34,17c0.84-0.58,2.87-1.25,4.66-1.25 - s3.82,0.67,4.66,1.25H4.34z" /> - <path d="M9,12c1.93,0,3.5-1.57,3.5-3.5C12.5,6.57,10.93,5,9,5S5.5,6.57,5.5,8.5C5.5,10.43,7.07,12,9,12z M9,7 - c0.83,0,1.5,0.67,1.5,1.5S9.83,10,9,10S7.5,9.33,7.5,8.5S8.17,7,9,7z" /> - <path d="M16.04,13.81C17.2,14.65,18,15.77,18,17.25V19h4v-1.75C22,15.23,18.5,14.08,16.04,13.81z" /> - <path d="M15,12c1.93,0,3.5-1.57,3.5-3.5C18.5,6.57,16.93,5,15,5c-0.54,0-1.04,0.13-1.5,0.35c0.63,0.89,1,1.98,1,3.15 - s-0.37,2.26-1,3.15C13.96,11.87,14.46,12,15,12z" /> - </svg> - <svg class="icon javaclassicon" height="24" width="24" fill="#5f6368"> - <title>Java class</title> - <path d="M6.6 1.44l-.82.83 2.1 2.1A6.96 6.96 0 0 0 5 10v1h14v-1a6.96 6.96 0 0 0-2.88-5.63l2.1-2.1-.82-.83-2.3 2.31a6.81 6.81 0 0 0-6.19 0L6.6 1.44zM9 7a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zm6 0a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zM5 12v4.27C5 20 8.17 23 12 23s7-3 7-6.73V12H5zm2 2h10v2.27c0 2.6-2.2 4.73-5 4.73s-5-2.13-5-4.73V14z" - /> - </svg> - <svg class="icon fileicon" height="24" width="24" fill="#5f6368"> - <title>File</title> - <path d="M14,2H6C4.9,2,4.01,2.9,4.01,4L4,20c0,1.1,0.89,2,1.99,2H18c1.1,0,2-0.9,2-2V8L14,2z M6,20V4h7v5h5v11 - L6,20z" /> - </svg> - <svg class="icon bssicon" height="24" width="24" fill="#a142f4"> - <title>Uninitialized data</title> - <path d="M6 2a2 2 0 0 0-2 2v16c0 1.1.9 2 2 2h12a2 2 0 0 0 2-2V8l-6-6H6zm0 2h7v5h5v11H6V4zm4 6v4h2v-4h-2zm0 6v2h2v-2h-2z" - /> - </svg> - <svg class="icon dataicon" height="24" width="24" fill="#fa7b17"> - <title>Initialized data</title> - <path d="M6 2a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6H6m0 2h7v5h5v11H6V4m2 8v2h8v-2H8m0 4v2h5v-2z" /> - </svg> - <svg class="icon readonlyicon" height="24" width="24" fill="#24c1e0"> - <title>Read-only data</title> - <path d="M6 2a2 2 0 0 0-2 2v16c0 1.1.9 2 2 2h12a2 2 0 0 0 2-2V8l-6-6H6zm0 2h7v5h5v11H6V4zm5.9 8c-2 0-3.7 1.2-4.4 3a4.7 4.7 0 0 0 8.8 0c-.7-1.8-2.4-3-4.4-3zm0 1a2 2 0 0 1 2 2 2 2 0 0 1-2 2 2 2 0 0 1-2-2 2 2 0 0 1 2-2zm0 .8a1.2 1.2 0 0 0-1.2 1.2 1.2 1.2 0 0 0 1.2 1.2 1.2 1.2 0 0 0 1.2-1.2 1.2 1.2 0 0 0-1.2-1.2z" - /> - </svg> - <svg class="icon codeicon" height="24" width="24" fill="#1a73e8"> - <title>Code</title> - <path d="M9.4,16.6L4.8,12l4.6-4.6L8,6l-6,6l6,6L9.4,16.6z M14.6,16.6l4.6-4.6l-4.6-4.6L16,6l6,6l-6,6L14.6,16.6z" /> - </svg> - <svg class="icon relroicon" height="24" width="24" fill="#fbbc04"> - <title>Vtable entry</title> - <path d="M20,3H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h15c1.1,0,2-0.9,2-2V5C22,3.9,21.1,3,20,3z M20,5v3H5V5H20z M15,19h-5v-9h5V19z - M5,10h3v9H5V10z M17,19v-9h3v9H17z" /> - </svg> - <svg class="icon dexicon" height="24" width="24" fill="#ea4335"> - <title>Dex non-method entry</title> - <path d="M6.6 1.44l-.82.83 2.1 2.1A6.96 6.96 0 0 0 5 10v1h14v-1a6.96 6.96 0 0 0-2.88-5.63l2.1-2.1-.82-.83-2.3 2.31a6.81 6.81 0 0 0-6.19 0L6.6 1.44zM9 7a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zm6 0a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zM5 12v4.27C5 20 8.17 23 12 23s7-3 7-6.73V12H5zm2 2h10v2.27c0 2.6-2.2 4.73-5 4.73s-5-2.13-5-4.73V14z" - /> - </svg> - <svg class="icon dexmethodicon" height="24" width="24" fill="#a50e0e"> - <title>Dex method</title> - <path d="M6.6 1.44l-.82.83 2.1 2.1A6.96 6.96 0 0 0 5 10v1h14v-1a6.96 6.96 0 0 0-2.88-5.63l2.1-2.1-.82-.83-2.3 2.31a6.81 6.81 0 0 0-6.19 0L6.6 1.44zM9 7a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zm6 0a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zM5 12v4.27C5 20 8.17 23 12 23s7-3 7-6.73V12H5zm2 2h10v2.27c0 2.6-2.2 4.73-5 4.73s-5-2.13-5-4.73V14z" - /> - </svg> - <svg class="icon localpakicon" height="24" width="24" fill="#34a853"> - <title>Locale pak entry</title> - <path d="M5 3a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H5zm0 2h5v2h2V5h7v14H5V5zm7 2v2h2V7h-2zm0 2h-2v2h2V9zm0 2v2h2v-2h-2zm0 2h-2v2h2v-2zm0 2v2h2v-2h-2z" - /> - </svg> - <svg class="icon nonlocalpakicon" height="24" width="24" fill="#0d652d"> - <title>Non-locale pak entry</title> - <path d="M5 3a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H5zm0 2h5v2h2V5h7v14H5V5zm7 2v2h2V7h-2zm0 2h-2v2h2V9zm0 2v2h2v-2h-2zm0 2h-2v2h2v-2zm0 2v2h2v-2h-2z" - /> - </svg> - <svg class="icon othericon" height="24" width="24" fill="#5f6368"> - <title>Other entry</title> - <path d="M10.88 2l-.85 1.36L4 13h6v-2H7.6l3.28-5.23L12.28 8h2.35l-3.75-6zM12 10v10h10V10H12zm2 2h6v6h-6v-6zM2.21 15A5.52 5.52 0 0 0 10 21.4v-2.45A3.48 3.48 0 0 1 7.5 20a3.48 3.48 0 0 1-3.15-5H2.2z" - /> - </svg> - </div> - <!-- Template for trees and leaves --> - <template id="treenode-container"> - <li role="treeitem" aria-expanded="false" aria-describedby="infocard-container"> - <a class="node" href="#" tabindex="-1" role="presentation"> - <span class="symbol-name"></span> - <span class="size"></span> - </a> - <ul role="group"></ul> - </li> - </template> - <template id="treenode-symbol"> - <li role="treeitem" aria-describedby="infocard-symbol"> - <span class="node" tabindex="-1"> - <span class="symbol-name"></span> - <span class="size"></span> - </span> - </li> - </template> - <!-- Tree view --> - <main class="tree-container"> - <header class="tree-header"> - <span class="subtitle">Name</span> - <span class="subtitle size-header" id="size-header">Size</span> - </header> - <ul id="symboltree" class="tree" role="tree" aria-labelledby="headline"></ul> - </main> - <!-- Symbol and container breakdown cards --> - <link href="infocard.css" rel="stylesheet"> - <footer class="infocards"> - <div class="infocard infocard-container open" id="infocard-container" hidden> - <div class="icon-info container-icon-info"> - <canvas class="type-pie-info" height="80" width="80"></canvas> - <div></div> - </div> - <header class="header-info"> - <h4 class="subhead size-info"></h4> - <p class="body-2 path-info"></p> - <p class="caption type-info-container"> - <span class="type-info"></span> - <span class="flags-info"></span> - </p> - </header> - <div class="type-breakdown-info"> - <table> - <thead> - <tr> - <th class="subhead-2">Icon</th> - <th class="subhead-2">Type</th> - <th class="subhead-2 count">Count</th> - <th class="subhead-2 size">Total size</th> - <th class="subhead-2 percent">Percent</th> - </tr> - </thead> - <tbody> - <tr class="bss-info"> - <td> - <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#a142f4"> - <path d="M6 2a2 2 0 0 0-2 2v16c0 1.1.9 2 2 2h12a2 2 0 0 0 2-2V8l-6-6H6zm0 2h7v5h5v11H6V4zm4 6v4h2v-4h-2zm0 6v2h2v-2h-2z" - /> - </svg> - </td> - <th scope="row">.bss</th> - <td class="count"></td> - <td class="size"></td> - <td class="percent"></td> - </tr> - <tr class="data-info"> - <td> - <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#fa7b17"> - <path d="M6 2a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6H6m0 2h7v5h5v11H6V4m2 8v2h8v-2H8m0 4v2h5v-2z" /> - </svg> - </td> - <th scope="row">.data and .data.*</th> - <td class="count"></td> - <td class="size"></td> - <td class="percent"></td> - </tr> - <tr class="rodata-info"> - <td> - <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#24c1e0"> - <path d="M6 2a2 2 0 0 0-2 2v16c0 1.1.9 2 2 2h12a2 2 0 0 0 2-2V8l-6-6H6zm0 2h7v5h5v11H6V4zm5.9 8c-2 0-3.7 1.2-4.4 3a4.7 4.7 0 0 0 8.8 0c-.7-1.8-2.4-3-4.4-3zm0 1a2 2 0 0 1 2 2 2 2 0 0 1-2 2 2 2 0 0 1-2-2 2 2 0 0 1 2-2zm0 .8a1.2 1.2 0 0 0-1.2 1.2 1.2 1.2 0 0 0 1.2 1.2 1.2 1.2 0 0 0 1.2-1.2 1.2 1.2 0 0 0-1.2-1.2z" - /> - </svg> - </td> - <th scope="row">.rodata</th> - <td class="count"></td> - <td class="size"></td> - <td class="percent"></td> - </tr> - <tr class="relro-info"> - <td> - <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#fbbc04"> - <path d="M20,3H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h15c1.1,0,2-0.9,2-2V5C22,3.9,21.1,3,20,3z M20,5v3H5V5H20z M15,19h-5v-9h5V19z - M5,10h3v9H5V10z M17,19v-9h3v9H17z" /> - </svg> - </td> - <th scope="row">Vtable entry</th> - <td class="count"></td> - <td class="size"></td> - <td class="percent"></td> - </tr> - <tr class="text-info"> - <td> - <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#1a73e8"> - <path d="M9.4,16.6L4.8,12l4.6-4.6L8,6l-6,6l6,6L9.4,16.6z M14.6,16.6l4.6-4.6l-4.6-4.6L16,6l6,6l-6,6L14.6,16.6z" /> - </svg> - </td> - <th scope="row">.text</th> - <td class="count"></td> - <td class="size"></td> - <td class="percent"></td> - </tr> - <tr class="dexnon-info"> - <td> - <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#ea4335"> - <path d="M6.6 1.44l-.82.83 2.1 2.1A6.96 6.96 0 0 0 5 10v1h14v-1a6.96 6.96 0 0 0-2.88-5.63l2.1-2.1-.82-.83-2.3 2.31a6.81 6.81 0 0 0-6.19 0L6.6 1.44zM9 7a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zm6 0a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zM5 12v4.27C5 20 8.17 23 12 23s7-3 7-6.73V12H5zm2 2h10v2.27c0 2.6-2.2 4.73-5 4.73s-5-2.13-5-4.73V14z" - /> - </svg> - </td> - <th scope="row">Dex non-method entries</th> - <td class="count"></td> - <td class="size"></td> - <td class="percent"></td> - </tr> - <tr class="dex-info"> - <td> - <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#a50e0e"> - <path d="M6.6 1.44l-.82.83 2.1 2.1A6.96 6.96 0 0 0 5 10v1h14v-1a6.96 6.96 0 0 0-2.88-5.63l2.1-2.1-.82-.83-2.3 2.31a6.81 6.81 0 0 0-6.19 0L6.6 1.44zM9 7a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zm6 0a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zM5 12v4.27C5 20 8.17 23 12 23s7-3 7-6.73V12H5zm2 2h10v2.27c0 2.6-2.2 4.73-5 4.73s-5-2.13-5-4.73V14z" - /> - </svg> - </td> - <th scope="row">Dex methods</th> - <td class="count"></td> - <td class="size"></td> - <td class="percent"></td> - </tr> - <tr class="pak-info"> - <td> - <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#34a853"> - <path d="M5 3a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H5zm0 2h5v2h2V5h7v14H5V5zm7 2v2h2V7h-2zm0 2h-2v2h2V9zm0 2v2h2v-2h-2zm0 2h-2v2h2v-2zm0 2v2h2v-2h-2z" - /> - </svg> - </td> - <th scope="row">Locale pak entries</th> - <td class="count"></td> - <td class="size"></td> - <td class="percent"></td> - </tr> - <tr class="paknon-info"> - <td> - <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#0d652d"> - <path d="M5 3a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H5zm0 2h5v2h2V5h7v14H5V5zm7 2v2h2V7h-2zm0 2h-2v2h2V9zm0 2v2h2v-2h-2zm0 2h-2v2h2v-2zm0 2v2h2v-2h-2z" - /> - </svg> - </td> - <th scope="row">Non-locale pak entries</th> - <td class="count"></td> - <td class="size"></td> - <td class="percent"></td> - </tr> - <tr class="other-info"> - <td> - <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#5f6368"> - <path d="M10.88 2l-.85 1.36L4 13h6v-2H7.6l3.28-5.23L12.28 8h2.35l-3.75-6zM12 10v10h10V10H12zm2 2h6v6h-6v-6zM2.21 15A5.52 5.52 0 0 0 10 21.4v-2.45A3.48 3.48 0 0 1 7.5 20a3.48 3.48 0 0 1-3.15-5H2.2z" - /> - </svg> - </td> - <th scope="row">Other entries</th> - <td class="count"></td> - <td class="size"></td> - <td class="percent"></td> - </tr> - </tbody> - </table> - </div> - </div> - <div class="infocard infocard-symbol" id="infocard-symbol" hidden> - <div class="icon-info"> - <div></div> - </div> - <header class="header-info"> - <h4 class="subhead size-info"></h4> - <p class="body-2 path-info"></p> - </header> - <p class="caption type-info-container"> - <span class="type-info"></span> - <span class="flags-info"></span> - </p> - </div> - </footer> - </div> </body> </html>
diff --git a/tools/binary_size/libsupersize/static/manifest.json b/tools/binary_size/libsupersize/static/manifest.json index 355e862..15d2a16 100644 --- a/tools/binary_size/libsupersize/static/manifest.json +++ b/tools/binary_size/libsupersize/static/manifest.json
@@ -14,7 +14,7 @@ } ], "lang": "en", - "start_url": "index.html", + "start_url": "viewer.html", "background_color": "#fff", "display": "standalone", "scope": "./",
diff --git a/tools/binary_size/libsupersize/static/milestones.html b/tools/binary_size/libsupersize/static/milestones.html deleted file mode 100644 index 80507b2..0000000 --- a/tools/binary_size/libsupersize/static/milestones.html +++ /dev/null
@@ -1,151 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> -<!-- - 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. ---> - -<head> - <title>Super Size Tiger View</title> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <meta name="theme-color" content="#4285f4"> - <link href="https://fonts.googleapis.com/css?family=Google+Sans:400,500|Roboto:400,500" rel="stylesheet"> - <link rel="stylesheet" href="main.css"> - <link rel="stylesheet" href="options.css"> - <style> -body { - grid-template-columns: auto; - grid-template-areas: "appbar" "select"; -} -form { - grid-area: 'select'; - margin: auto; -} - </style> - <link rel="icon" href="favicon.ico" sizes="16x16 32x32 256x256" type="image/x-icon"> - <script> -const DESIRED_CPUS = ['arm', 'arm_64']; -const DESIRED_APKS = ['Monochrome.apk', 'ChromeModern.apk']; -const DESIRED_VERSION = [ - '60.0.3112.116', - '61.0.3163.98', - '62.0.3202.84', - '63.0.3239.111', - '64.0.3282.137', - '65.0.3325.85', - '66.0.3359.158', - '67.0.3396.87', - '68.0.3440.70', -]; - -/** - * @param {string[]} options - */ -function buildOptions(options) { - const fragment = document.createDocumentFragment(); - for (const option of options) { - const optionEl = document.createElement('option'); - optionEl.value = option; - optionEl.textContent = option; - fragment.appendChild(optionEl); - } - return fragment; -} - -/** - * Is `v1` a larger version than `v2`? - * @param {string} v1 - * @param {string} v2 - */ -function isGreaterOrEqual(v1, v2) { - const [version1] = v1.split('.', 1).map(n => parseInt(n, 10)); - const [version2] = v2.split('.', 1).map(n => parseInt(n, 10)); - return version1 >= version2; -} - -(async () => { - const response = await fetch('milestones/milestones.json'); - const {pushed} = await response.json(); - - if (document.readyState === 'loading') { - await new Promise(resolve => { - document.onreadystatechange = () => { - if (document.readyState !== 'loading') { - resolve(); - document.onreadystatechange = null; - } - } - }); - } - - /** @type {HTMLFormElement} */ - const form = document.getElementById('select-form'); - const cpu = form.elements.namedItem('cpu'); - const apk = form.elements.namedItem('apk'); - const version1 = form.elements.namedItem('version1'); - const version2 = form.elements.namedItem('version2'); - - cpu.appendChild(buildOptions(pushed.cpu)); - apk.appendChild(buildOptions(pushed.apk)); - const versionOptions = buildOptions(pushed.version); - version1.appendChild(versionOptions.cloneNode(true)); - version2.appendChild(versionOptions); - const version2Options = version2.querySelectorAll('option'); - if (version2Options.length > 1) { - version2Options[1].selected = true; - } - - function disableSmallerAfterVersions() { - const newVersion = version1.value; - for (const opt of version2Options) { - opt.disabled = isGreaterOrEqual(newVersion, opt.value); - } - } - - disableSmallerAfterVersions(); - version1.addEventListener('change', disableSmallerAfterVersions); - form.addEventListener('submit', event => { - event.preventDefault(); - const dataUrl = `${cpu.value}/${apk.value}/` + - `report_${version1.value}_${version2.value}.ndjson`; - location.href = `index.html?data_url=milestones/${dataUrl}`; - }); -})(); - </script> -</head> - -<body> - <div class="scrim toggle-options" hidden></div> - <header class="appbar"> - <div class="appbar-inner"> - <h1 class="headline">Super Size Tiger View</h1> - </div> - </header> - - <form id="select-form"> - <h2 class="subhead">Select milestones to compare</h2> - <p class="select-wrapper"> - <select id="cpu" name="cpu"></select> - <label class="select-label" for="cpu">Architecture</label> - </p> - <p class="select-wrapper"> - <select id="apk" name="apk"></select> - <label class="select-label" for="apk">APK</label> - </p> - <p class="select-wrapper"> - <select id="version1" name="version1"></select> - <label class="select-label" for="version1">Version 1</label> - </p> - <p class="select-wrapper"> - <select id="version2" name="version2"></select> - <label class="select-label" for="version2">Version 2</label> - </p> - - <button type="submit" class="text-button filled-button"> - Open report - </button> - </form> -</body> - -</html>
diff --git a/tools/binary_size/libsupersize/static/options.css b/tools/binary_size/libsupersize/static/options.css index de9c097..d0fc6375 100644 --- a/tools/binary_size/libsupersize/static/options.css +++ b/tools/binary_size/libsupersize/static/options.css
@@ -25,6 +25,11 @@ background: #00000050; } +/** Fix height to prevent vertical shift on view mode change. */ +#select-form { + min-height: 380px; +} + /** Options side panel */ .options { z-index: 5; /* Side panel layer */ @@ -100,6 +105,13 @@ .text-button:active { background: #d2e3fce6; } +.text-button:disabled { + background: #ccc; + cursor: not-allowed; +} +.text-button:disabled:hover { + background: #bbb; +} .text-button.with-icon { display: flex; @@ -130,6 +142,18 @@ box-shadow: 0 1px 2px #3c40434d, 0 2px 6px 2px #3c404326; } +select { + cursor: pointer; +} + +select.sel-small { + background: #fff; + color: #3c4043; + font-family: "Google Sans", Arial, sans-serif; + font-weight: 500; + font-size: 16px; +} + /** <input type='text'> or <select> elements */ .input-wrapper, .select-wrapper { @@ -139,7 +163,7 @@ } input[type='text'], input[type='number'], -select { +select.sel-big { box-sizing: border-box; -webkit-appearance: none; -moz-appearance: none; @@ -179,14 +203,17 @@ } input[type='text']:focus + .input-label, input[type='number']:focus + .input-label, -select:focus + .select-label { +select.sel-big:focus + .select-label { color: #1a73e8; bottom: -2px; border-width: 2px; } -select:focus + .select-label::after { +select.sel-big:focus + .select-label::after { transform: rotate(180deg); } +.mode-view .hide-on-mode-view { + display: none; +} .input-error { margin: 4px 0; @@ -293,6 +320,16 @@ opacity: 0; } +#select-form .msg-bad-compare { + color: #f00; + font-size: 0.7em; + margin-top: 5px; + visibility: hidden; +} +#select-form .msg-bad-compare.visible { + visibility: visible; +} + /** Tweaks for smaller screen sizes */ @media (max-width: 700px) { .show-options {
diff --git a/tools/binary_size/libsupersize/static/tree-ui.js b/tools/binary_size/libsupersize/static/tree-ui.js index c22f789..9b6472b 100644 --- a/tools/binary_size/libsupersize/static/tree-ui.js +++ b/tools/binary_size/libsupersize/static/tree-ui.js
@@ -417,7 +417,7 @@ /** @type {HTMLInputElement} */ const _fileUpload = document.getElementById('upload'); /** @type {HTMLInputElement} */ - const _dataUrlInput = form.elements.namedItem('data_url'); + const _dataUrlInput = form.elements.namedItem('load_url'); const _progress = new ProgressBar('progress'); /**
diff --git a/tools/binary_size/libsupersize/static/tree-worker.js b/tools/binary_size/libsupersize/static/tree-worker.js index 44db920..b23453b 100644 --- a/tools/binary_size/libsupersize/static/tree-worker.js +++ b/tools/binary_size/libsupersize/static/tree-worker.js
@@ -37,7 +37,6 @@ importScripts('./shared.js'); const _PATH_SEP = '/'; -const _DEMO_DATA_URL = 'demo.ndjson'; const _NAMES_TO_FLAGS = Object.freeze({ hot: _FLAGS.HOT, generated: _FLAGS.GENERATED_SOURCE, @@ -600,7 +599,7 @@ function parseOptions(options) { const params = new URLSearchParams(options); - const url = params.get('data_url'); + const url = params.get('load_url'); const groupBy = params.get('group_by') || 'source_path'; const methodCountMode = params.has('method_count'); const filterGeneratedFiles = params.has('generated_filter'); @@ -793,19 +792,10 @@ /** @param {{input:string|null,options:string}} param0 */ load({input, options}) { const {groupBy, filterTest, highlightTest, url} = parseOptions(options); - if (input === 'from-url://') { - if (url) { - // Display the data from the `data_url` query parameter - console.info('Displaying data from', url); - fetcher.setInput(url); - } else { - // Display starter content if nothing was specified. - console.info('Displaying demo data'); - // The demo file only exists in the GCS bucket where the UI is hosted. - // When using `start_server`, no data is shown until the user uploads - // something. - fetcher.setInput(_DEMO_DATA_URL); - } + if (input === 'from-url://' && url) { + // Display the data from the `load_url` query parameter + console.info('Displaying data from', url); + fetcher.setInput(url); } else if (input != null) { console.info('Displaying uploaded data'); fetcher.setInput(input);
diff --git a/tools/binary_size/libsupersize/static/viewer.html b/tools/binary_size/libsupersize/static/viewer.html new file mode 100644 index 0000000..0b24204d --- /dev/null +++ b/tools/binary_size/libsupersize/static/viewer.html
@@ -0,0 +1,509 @@ +<!DOCTYPE html> +<html lang="en"> +<!-- + 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. +--> + +<head> + <title>Super Size Tiger View</title> + <script src="start-worker.js"></script> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <meta name="theme-color" content="#4285f4"> + <link href="https://fonts.googleapis.com/css?family=Google+Sans:400,500|Roboto:400,500" rel="stylesheet"> + <link rel="stylesheet" href="main.css"> + <link rel="stylesheet" href="options.css"> + <link rel="icon" href="favicon.ico" sizes="16x16 32x32 256x256" type="image/x-icon"> + <link rel="manifest" href="manifest.json"> + <script defer src="shared.js"></script> + <script defer src="state.js"></script> + <script defer src="infocard-ui.js"></script> + <script defer src="tree-ui.js"></script> + <script defer async> +if ('serviceWorker' in navigator) { + navigator.serviceWorker.register('sw.js') + .catch(() => console.warn('ServiceWorker not loaded.')); +} + </script> +</head> + +<body> + <div class="scrim toggle-options" hidden></div> + <!-- App Toolbar --> + <header class="appbar"> + <div class="appbar-inner"> + <h1 class="headline">Super Size Tiger View</h1> + <input type="file" name="upload" id="upload" accept=".ndjson" > + <label for="upload" class="text-button filled-button with-icon"> + <svg class="icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="#fff"> + <!-- + Icons from https://material.io/tools/icons/?style=outline + with some custom icons designed in the same style + --> + <path d="M6 2a2 2 0 0 0-2 2v16c0 1.1.9 2 2 2h12a2 2 0 0 0 2-2V8l-6-6H6zm0 2h7v5h5v11H6V4zm6 7l-4 4h3v4h2v-4h3l-4-4z" /> + </svg> + <span class="label-text">Upload data</span> + </label> + <a href="https://chromium.googlesource.com/chromium/src/+/master/tools/binary_size/html_report_faq.md" class="icon-button" + title="FAQ" id="faq" target="_blank"> + <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#5f6368"> + <path d="M11,18h2v-2h-2V18z M12,2C6.48,2,2,6.48,2,12s4.48,10,10,10s10-4.48,10-10S17.52,2,12,2z M12,20c-4.41,0-8-3.59-8-8 + s3.59-8,8-8s8,3.59,8,8S16.41,20,12,20z M12,6c-2.21,0-4,1.79-4,4h2c0-1.1,0.9-2,2-2s2,0.9,2,2c0,2-3,1.75-3,5h2c0-2.25,3-2.5,3-5 + C16,7.79,14.21,6,12,6z" /> + </svg> + </a> + <button type="button" class="icon-button toggle-options" title="Settings"> + <svg class="settings" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#5f6368"> + <path d="M19.43,12.98c0.04-0.32,0.07-0.64,0.07-0.98c0-0.34-0.03-0.66-0.07-0.98l2.11-1.65c0.19-0.15,0.24-0.42,0.12-0.64l-2-3.46 + c-0.09-0.16-0.26-0.25-0.44-0.25c-0.06,0-0.12,0.01-0.17,0.03l-2.49,1c-0.52-0.4-1.08-0.73-1.69-0.98l-0.38-2.65 + C14.46,2.18,14.25,2,14,2h-4C9.75,2,9.54,2.18,9.51,2.42L9.13,5.07C8.52,5.32,7.96,5.66,7.44,6.05l-2.49-1 + C4.89,5.03,4.83,5.02,4.77,5.02c-0.17,0-0.34,0.09-0.43,0.25l-2,3.46C2.21,8.95,2.27,9.22,2.46,9.37l2.11,1.65 + C4.53,11.34,4.5,11.67,4.5,12c0,0.33,0.03,0.66,0.07,0.98l-2.11,1.65c-0.19,0.15-0.24,0.42-0.12,0.64l2,3.46 + c0.09,0.16,0.26,0.25,0.44,0.25c0.06,0,0.12-0.01,0.17-0.03l2.49-1c0.52,0.4,1.08,0.73,1.69,0.98l0.38,2.65 + C9.54,21.82,9.75,22,10,22h4c0.25,0,0.46-0.18,0.49-0.42l0.38-2.65c0.61-0.25,1.17-0.59,1.69-0.98l2.49,1 + c0.06,0.02,0.12,0.03,0.18,0.03c0.17,0,0.34-0.09,0.43-0.25l2-3.46c0.12-0.22,0.07-0.49-0.12-0.64L19.43,12.98z M17.45,11.27 + c0.04,0.31,0.05,0.52,0.05,0.73c0,0.21-0.02,0.43-0.05,0.73l-0.14,1.13l0.89,0.7l1.08,0.84l-0.7,1.21l-1.27-0.51l-1.04-0.42 + l-0.9,0.68c-0.43,0.32-0.84,0.56-1.25,0.73l-1.06,0.43l-0.16,1.13L12.7,20H11.3l-0.19-1.35l-0.16-1.13l-1.06-0.43 + c-0.43-0.18-0.83-0.41-1.23-0.71l-0.91-0.7l-1.06,0.43l-1.27,0.51l-0.7-1.21l1.08-0.84l0.89-0.7l-0.14-1.13 + C6.52,12.43,6.5,12.2,6.5,12s0.02-0.43,0.05-0.73l0.14-1.13L5.8,9.44L4.72,8.6l0.7-1.21l1.27,0.51l1.04,0.42l0.9-0.68 + c0.43-0.32,0.84-0.56,1.25-0.73l1.06-0.43l0.16-1.13L11.3,4h1.39l0.19,1.35l0.16,1.13l1.06,0.43c0.43,0.18,0.83,0.41,1.23,0.71 + l0.91,0.7l1.06-0.43l1.27-0.51l0.7,1.21L18.2,9.44l-0.89,0.7L17.45,11.27z" /> + <path d="M12,8c-2.21,0-4,1.79-4,4s1.79,4,4,4s4-1.79,4-4S14.21,8,12,8z M12,14c-1.1,0-2-0.9-2-2s0.9-2,2-2s2,0.9,2,2 + S13.1,14,12,14z" /> + </svg> + </button> + </div> + <progress value="0" id="progress" class="appbar-progress"></progress> + </header> + <!-- Options side panel --> + <form id="options" class="options" method="GET"> + <header class="form-bar"> + <button type="button" class="icon-button toggle-options" title="Close"> + <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#5f6368"> + <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" /> + </svg> + </button> + </header> + + <input type="hidden" name="load_url" data-dynamic> + + <fieldset> + <legend class="subhead">Size options</legend> + <div class="checkbox-wrapper"> + <input type="checkbox" id="methodcount" name="method_count" value="on"> + <label class="checkbox-label" for="methodcount">Method Count Mode</label> + </div> + <p class="select-wrapper"> + <select id="byteunit" name="byteunit" data-dynamic> + <option value="B">B - bytes</option> + <option value="KiB" selected>KiB - kibibytes</option> + <option value="MiB">MiB - mebibytes</option> + <option value="GiB">GiB - gibibytes</option> + </select> + <label class="select-label" for="byteunit">Byte unit</label> + </p> + <p class="input-wrapper"> + <input type="number" id="minsize" name="min_size" value="0" min="0"> + <label class="input-label" for="minsize"> + Minimum size (bytes) + </label> + </p> + </fieldset> + + <fieldset> + <legend class="subhead">Group symbols by</legend> + <div class="radio-wrapper"> + <input type="radio" id="sourcepath" name="group_by" value="source_path" checked> + <label class="radio-label" for="sourcepath">Source path</label> + </div> + <div class="radio-wrapper"> + <input type="radio" id="component" name="group_by" value="component"> + <label class="radio-label" for="component">Component</label> + </div> + </fieldset> + + <fieldset> + <legend class="subhead">Search by regex</legend> + <div class="input-wrapper"> + <input class="input-regex" type="text" id="includeregex" name="include" placeholder=".+@.+" aria-describedby="include-error"> + <label class="input-label" for="includeregex"> + Symbols must contain + </label> + <p class="input-error" id="include-error"></p> + </div> + <div class="input-wrapper"> + <input class="input-regex" type="text" id="excluderegex" name="exclude" placeholder="\(.+\)" aria-describedby="exclude-error"> + <label class="input-label" for="excluderegex"> + Symbols must exclude + </label> + <p class="input-error" id="exclude-error"></p> + </div> + </fieldset> + + <fieldset id="types-filter"> + <legend class="subhead">Symbol types to show</legend> + <div class="checkbox-wrapper"> + <input type="checkbox" id="filtertext" name="type" value="t" checked> + <label class="checkbox-label" for="filtertext"> + Native code: .text + </label> + </div> + <div class="checkbox-wrapper"> + <input type="checkbox" id="filterdata" name="type" value="d" checked> + <label class="checkbox-label" for="filterdata"> + Native code: .data + </label> + </div> + <div class="checkbox-wrapper"> + <input type="checkbox" id="filterrodata" name="type" value="r" checked> + <label class="checkbox-label" for="filterrodata"> + Native code: .rodata + </label> + </div> + <div class="checkbox-wrapper"> + <input type="checkbox" id="filterrelro" name="type" value="R" checked> + <label class="checkbox-label" for="filterrelro"> + Native code: .data.rel.ro + </label> + </div> + <div class="checkbox-wrapper"> + <input type="checkbox" id="filterdex" name="type" value="m" checked> + <label class="checkbox-label" for="filterdex"> + Dex: Methods + </label> + </div> + <div class="checkbox-wrapper"> + <input type="checkbox" id="filterdexnon" name="type" value="x" checked> + <label class="checkbox-label" for="filterdexnon"> + Dex: Other + </label> + </div> + <div class="checkbox-wrapper"> + <input type="checkbox" id="filterpak" name="type" value="p" checked> + <label class="checkbox-label" for="filterpak"> + Pak: Translations + </label> + </div> + <div class="checkbox-wrapper"> + <input type="checkbox" id="filterpaknon" name="type" value="P" checked> + <label class="checkbox-label" for="filterpaknon"> + Pak: Non-translations + </label> + </div> + <div class="checkbox-wrapper"> + <input type="checkbox" id="filterother" name="type" value="o" checked> + <label class="checkbox-label" for="filterother"> + Assets & Miscellaneous Entries + </label> + </div> + <div class="checkbox-wrapper"> + <input type="checkbox" id="filterbss" name="type" value="b"> + <label class="checkbox-label" for="filterbss"> + Native Code: .bss + </label> + </div> + <button type="button" class="text-button" id="type-all">Select all</button> + <button type="button" class="text-button" id="type-none">Select none</button> + </fieldset> + + <fieldset id="highlight-container"> + <legend class="subhead">Highlight symbols</legend> + <div class="radio-wrapper"> + <input type="radio" id="clearhighlight" name="highlight" value="clear" checked> + <label class="radio-label" for="clearhighlight">None</label> + </div> + <div class="radio-wrapper"> + <input type="radio" id="hothighlight" name="highlight" value="hot"> + <label class="radio-label" for="hothighlight">Hot code</label> + </div> + <div class="radio-wrapper"> + <input type="radio" id="generatedhighlight" name="highlight" value="generated"> + <label class="radio-label" for="generatedhighlight">Generated files</label> + </div> + <div class="radio-wrapper"> + <input type="radio" id="coveragehightlight" name="highlight" value="coverage"> + <label class="radio-label" for="coveragehightlight">Code coverage (not implemented)</label> + </div> + <div class="radio-wrapper"> + <input type="radio" id="uncompressedhighlight" name="highlight" value="uncompressed"> + <label class="radio-label" for="uncompressedhighlight">Uncompressed .pak files</label> + </div> + </fieldset> + + <p class="checkbox-wrapper"> + <input type="checkbox" id="generatedfilter" name="generated_filter" value="on"> + <label class="checkbox-label" for="generatedfilter">Show only generated files</label> + </p> + </form> + <div class="symbols"> + <!-- Icons for symbols are stored here and cloned. --> + <div hidden id="icons"> + <svg class="icon foldericon" height="24" width="24" fill="#5f6368"> + <title>Directory</title> + <path d="M9.17,6l2,2H20v10L4,18V6H9.17 M10,4H4C2.9,4,2.01,4.9,2.01,6L2,18c0,1.1,0.9,2,2,2h16c1.1,0,2-0.9,2-2V8c0-1.1-0.9-2-2-2 + h-8L10,4L10,4z" /> + </svg> + <svg class="icon componenticon" height="24" width="24" fill="#5f6368"> + <title>Component</title> + <path d="M9,13.75c-2.34,0-7,1.17-7,3.5V19h14v-1.75C16,14.92,11.34,13.75,9,13.75z M4.34,17c0.84-0.58,2.87-1.25,4.66-1.25 + s3.82,0.67,4.66,1.25H4.34z" /> + <path d="M9,12c1.93,0,3.5-1.57,3.5-3.5C12.5,6.57,10.93,5,9,5S5.5,6.57,5.5,8.5C5.5,10.43,7.07,12,9,12z M9,7 + c0.83,0,1.5,0.67,1.5,1.5S9.83,10,9,10S7.5,9.33,7.5,8.5S8.17,7,9,7z" /> + <path d="M16.04,13.81C17.2,14.65,18,15.77,18,17.25V19h4v-1.75C22,15.23,18.5,14.08,16.04,13.81z" /> + <path d="M15,12c1.93,0,3.5-1.57,3.5-3.5C18.5,6.57,16.93,5,15,5c-0.54,0-1.04,0.13-1.5,0.35c0.63,0.89,1,1.98,1,3.15 + s-0.37,2.26-1,3.15C13.96,11.87,14.46,12,15,12z" /> + </svg> + <svg class="icon javaclassicon" height="24" width="24" fill="#5f6368"> + <title>Java class</title> + <path d="M6.6 1.44l-.82.83 2.1 2.1A6.96 6.96 0 0 0 5 10v1h14v-1a6.96 6.96 0 0 0-2.88-5.63l2.1-2.1-.82-.83-2.3 2.31a6.81 6.81 0 0 0-6.19 0L6.6 1.44zM9 7a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zm6 0a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zM5 12v4.27C5 20 8.17 23 12 23s7-3 7-6.73V12H5zm2 2h10v2.27c0 2.6-2.2 4.73-5 4.73s-5-2.13-5-4.73V14z" + /> + </svg> + <svg class="icon fileicon" height="24" width="24" fill="#5f6368"> + <title>File</title> + <path d="M14,2H6C4.9,2,4.01,2.9,4.01,4L4,20c0,1.1,0.89,2,1.99,2H18c1.1,0,2-0.9,2-2V8L14,2z M6,20V4h7v5h5v11 + L6,20z" /> + </svg> + <svg class="icon bssicon" height="24" width="24" fill="#a142f4"> + <title>Uninitialized data</title> + <path d="M6 2a2 2 0 0 0-2 2v16c0 1.1.9 2 2 2h12a2 2 0 0 0 2-2V8l-6-6H6zm0 2h7v5h5v11H6V4zm4 6v4h2v-4h-2zm0 6v2h2v-2h-2z" + /> + </svg> + <svg class="icon dataicon" height="24" width="24" fill="#fa7b17"> + <title>Initialized data</title> + <path d="M6 2a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6H6m0 2h7v5h5v11H6V4m2 8v2h8v-2H8m0 4v2h5v-2z" /> + </svg> + <svg class="icon readonlyicon" height="24" width="24" fill="#24c1e0"> + <title>Read-only data</title> + <path d="M6 2a2 2 0 0 0-2 2v16c0 1.1.9 2 2 2h12a2 2 0 0 0 2-2V8l-6-6H6zm0 2h7v5h5v11H6V4zm5.9 8c-2 0-3.7 1.2-4.4 3a4.7 4.7 0 0 0 8.8 0c-.7-1.8-2.4-3-4.4-3zm0 1a2 2 0 0 1 2 2 2 2 0 0 1-2 2 2 2 0 0 1-2-2 2 2 0 0 1 2-2zm0 .8a1.2 1.2 0 0 0-1.2 1.2 1.2 1.2 0 0 0 1.2 1.2 1.2 1.2 0 0 0 1.2-1.2 1.2 1.2 0 0 0-1.2-1.2z" + /> + </svg> + <svg class="icon codeicon" height="24" width="24" fill="#1a73e8"> + <title>Code</title> + <path d="M9.4,16.6L4.8,12l4.6-4.6L8,6l-6,6l6,6L9.4,16.6z M14.6,16.6l4.6-4.6l-4.6-4.6L16,6l6,6l-6,6L14.6,16.6z" /> + </svg> + <svg class="icon relroicon" height="24" width="24" fill="#fbbc04"> + <title>Vtable entry</title> + <path d="M20,3H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h15c1.1,0,2-0.9,2-2V5C22,3.9,21.1,3,20,3z M20,5v3H5V5H20z M15,19h-5v-9h5V19z + M5,10h3v9H5V10z M17,19v-9h3v9H17z" /> + </svg> + <svg class="icon dexicon" height="24" width="24" fill="#ea4335"> + <title>Dex non-method entry</title> + <path d="M6.6 1.44l-.82.83 2.1 2.1A6.96 6.96 0 0 0 5 10v1h14v-1a6.96 6.96 0 0 0-2.88-5.63l2.1-2.1-.82-.83-2.3 2.31a6.81 6.81 0 0 0-6.19 0L6.6 1.44zM9 7a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zm6 0a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zM5 12v4.27C5 20 8.17 23 12 23s7-3 7-6.73V12H5zm2 2h10v2.27c0 2.6-2.2 4.73-5 4.73s-5-2.13-5-4.73V14z" + /> + </svg> + <svg class="icon dexmethodicon" height="24" width="24" fill="#a50e0e"> + <title>Dex method</title> + <path d="M6.6 1.44l-.82.83 2.1 2.1A6.96 6.96 0 0 0 5 10v1h14v-1a6.96 6.96 0 0 0-2.88-5.63l2.1-2.1-.82-.83-2.3 2.31a6.81 6.81 0 0 0-6.19 0L6.6 1.44zM9 7a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zm6 0a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zM5 12v4.27C5 20 8.17 23 12 23s7-3 7-6.73V12H5zm2 2h10v2.27c0 2.6-2.2 4.73-5 4.73s-5-2.13-5-4.73V14z" + /> + </svg> + <svg class="icon localpakicon" height="24" width="24" fill="#34a853"> + <title>Locale pak entry</title> + <path d="M5 3a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H5zm0 2h5v2h2V5h7v14H5V5zm7 2v2h2V7h-2zm0 2h-2v2h2V9zm0 2v2h2v-2h-2zm0 2h-2v2h2v-2zm0 2v2h2v-2h-2z" + /> + </svg> + <svg class="icon nonlocalpakicon" height="24" width="24" fill="#0d652d"> + <title>Non-locale pak entry</title> + <path d="M5 3a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H5zm0 2h5v2h2V5h7v14H5V5zm7 2v2h2V7h-2zm0 2h-2v2h2V9zm0 2v2h2v-2h-2zm0 2h-2v2h2v-2zm0 2v2h2v-2h-2z" + /> + </svg> + <svg class="icon othericon" height="24" width="24" fill="#5f6368"> + <title>Other entry</title> + <path d="M10.88 2l-.85 1.36L4 13h6v-2H7.6l3.28-5.23L12.28 8h2.35l-3.75-6zM12 10v10h10V10H12zm2 2h6v6h-6v-6zM2.21 15A5.52 5.52 0 0 0 10 21.4v-2.45A3.48 3.48 0 0 1 7.5 20a3.48 3.48 0 0 1-3.15-5H2.2z" + /> + </svg> + </div> + <!-- Template for trees and leaves --> + <template id="treenode-container"> + <li role="treeitem" aria-expanded="false" aria-describedby="infocard-container"> + <a class="node" href="#" tabindex="-1" role="presentation"> + <span class="symbol-name"></span> + <span class="size"></span> + </a> + <ul role="group"></ul> + </li> + </template> + <template id="treenode-symbol"> + <li role="treeitem" aria-describedby="infocard-symbol"> + <span class="node" tabindex="-1"> + <span class="symbol-name"></span> + <span class="size"></span> + </span> + </li> + </template> + <!-- Tree view --> + <main class="tree-container"> + <header class="tree-header"> + <span class="subtitle">Name</span> + <span class="subtitle size-header" id="size-header">Size</span> + </header> + <ul id="symboltree" class="tree" role="tree" aria-labelledby="headline"></ul> + </main> + <!-- Symbol and container breakdown cards --> + <link href="infocard.css" rel="stylesheet"> + <footer class="infocards"> + <div class="infocard infocard-container open" id="infocard-container" hidden> + <div class="icon-info container-icon-info"> + <canvas class="type-pie-info" height="80" width="80"></canvas> + <div></div> + </div> + <header class="header-info"> + <h4 class="subhead size-info"></h4> + <p class="body-2 path-info"></p> + <p class="caption type-info-container"> + <span class="type-info"></span> + <span class="flags-info"></span> + </p> + </header> + <div class="type-breakdown-info"> + <table> + <thead> + <tr> + <th class="subhead-2">Icon</th> + <th class="subhead-2">Type</th> + <th class="subhead-2 count">Count</th> + <th class="subhead-2 size">Total size</th> + <th class="subhead-2 percent">Percent</th> + </tr> + </thead> + <tbody> + <tr class="bss-info"> + <td> + <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#a142f4"> + <path d="M6 2a2 2 0 0 0-2 2v16c0 1.1.9 2 2 2h12a2 2 0 0 0 2-2V8l-6-6H6zm0 2h7v5h5v11H6V4zm4 6v4h2v-4h-2zm0 6v2h2v-2h-2z" + /> + </svg> + </td> + <th scope="row">.bss</th> + <td class="count"></td> + <td class="size"></td> + <td class="percent"></td> + </tr> + <tr class="data-info"> + <td> + <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#fa7b17"> + <path d="M6 2a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6H6m0 2h7v5h5v11H6V4m2 8v2h8v-2H8m0 4v2h5v-2z" /> + </svg> + </td> + <th scope="row">.data and .data.*</th> + <td class="count"></td> + <td class="size"></td> + <td class="percent"></td> + </tr> + <tr class="rodata-info"> + <td> + <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#24c1e0"> + <path d="M6 2a2 2 0 0 0-2 2v16c0 1.1.9 2 2 2h12a2 2 0 0 0 2-2V8l-6-6H6zm0 2h7v5h5v11H6V4zm5.9 8c-2 0-3.7 1.2-4.4 3a4.7 4.7 0 0 0 8.8 0c-.7-1.8-2.4-3-4.4-3zm0 1a2 2 0 0 1 2 2 2 2 0 0 1-2 2 2 2 0 0 1-2-2 2 2 0 0 1 2-2zm0 .8a1.2 1.2 0 0 0-1.2 1.2 1.2 1.2 0 0 0 1.2 1.2 1.2 1.2 0 0 0 1.2-1.2 1.2 1.2 0 0 0-1.2-1.2z" + /> + </svg> + </td> + <th scope="row">.rodata</th> + <td class="count"></td> + <td class="size"></td> + <td class="percent"></td> + </tr> + <tr class="relro-info"> + <td> + <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#fbbc04"> + <path d="M20,3H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h15c1.1,0,2-0.9,2-2V5C22,3.9,21.1,3,20,3z M20,5v3H5V5H20z M15,19h-5v-9h5V19z + M5,10h3v9H5V10z M17,19v-9h3v9H17z" /> + </svg> + </td> + <th scope="row">Vtable entry</th> + <td class="count"></td> + <td class="size"></td> + <td class="percent"></td> + </tr> + <tr class="text-info"> + <td> + <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#1a73e8"> + <path d="M9.4,16.6L4.8,12l4.6-4.6L8,6l-6,6l6,6L9.4,16.6z M14.6,16.6l4.6-4.6l-4.6-4.6L16,6l6,6l-6,6L14.6,16.6z" /> + </svg> + </td> + <th scope="row">.text</th> + <td class="count"></td> + <td class="size"></td> + <td class="percent"></td> + </tr> + <tr class="dexnon-info"> + <td> + <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#ea4335"> + <path d="M6.6 1.44l-.82.83 2.1 2.1A6.96 6.96 0 0 0 5 10v1h14v-1a6.96 6.96 0 0 0-2.88-5.63l2.1-2.1-.82-.83-2.3 2.31a6.81 6.81 0 0 0-6.19 0L6.6 1.44zM9 7a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zm6 0a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zM5 12v4.27C5 20 8.17 23 12 23s7-3 7-6.73V12H5zm2 2h10v2.27c0 2.6-2.2 4.73-5 4.73s-5-2.13-5-4.73V14z" + /> + </svg> + </td> + <th scope="row">Dex non-method entries</th> + <td class="count"></td> + <td class="size"></td> + <td class="percent"></td> + </tr> + <tr class="dex-info"> + <td> + <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#a50e0e"> + <path d="M6.6 1.44l-.82.83 2.1 2.1A6.96 6.96 0 0 0 5 10v1h14v-1a6.96 6.96 0 0 0-2.88-5.63l2.1-2.1-.82-.83-2.3 2.31a6.81 6.81 0 0 0-6.19 0L6.6 1.44zM9 7a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zm6 0a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1zM5 12v4.27C5 20 8.17 23 12 23s7-3 7-6.73V12H5zm2 2h10v2.27c0 2.6-2.2 4.73-5 4.73s-5-2.13-5-4.73V14z" + /> + </svg> + </td> + <th scope="row">Dex methods</th> + <td class="count"></td> + <td class="size"></td> + <td class="percent"></td> + </tr> + <tr class="pak-info"> + <td> + <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#34a853"> + <path d="M5 3a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H5zm0 2h5v2h2V5h7v14H5V5zm7 2v2h2V7h-2zm0 2h-2v2h2V9zm0 2v2h2v-2h-2zm0 2h-2v2h2v-2zm0 2v2h2v-2h-2z" + /> + </svg> + </td> + <th scope="row">Locale pak entries</th> + <td class="count"></td> + <td class="size"></td> + <td class="percent"></td> + </tr> + <tr class="paknon-info"> + <td> + <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#0d652d"> + <path d="M5 3a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H5zm0 2h5v2h2V5h7v14H5V5zm7 2v2h2V7h-2zm0 2h-2v2h2V9zm0 2v2h2v-2h-2zm0 2h-2v2h2v-2zm0 2v2h2v-2h-2z" + /> + </svg> + </td> + <th scope="row">Non-locale pak entries</th> + <td class="count"></td> + <td class="size"></td> + <td class="percent"></td> + </tr> + <tr class="other-info"> + <td> + <svg class="icon" viewBox="0 0 24 24" height="18" width="18" fill="#5f6368"> + <path d="M10.88 2l-.85 1.36L4 13h6v-2H7.6l3.28-5.23L12.28 8h2.35l-3.75-6zM12 10v10h10V10H12zm2 2h6v6h-6v-6zM2.21 15A5.52 5.52 0 0 0 10 21.4v-2.45A3.48 3.48 0 0 1 7.5 20a3.48 3.48 0 0 1-3.15-5H2.2z" + /> + </svg> + </td> + <th scope="row">Other entries</th> + <td class="count"></td> + <td class="size"></td> + <td class="percent"></td> + </tr> + </tbody> + </table> + </div> + </div> + <div class="infocard infocard-symbol" id="infocard-symbol" hidden> + <div class="icon-info"> + <div></div> + </div> + <header class="header-info"> + <h4 class="subhead size-info"></h4> + <p class="body-2 path-info"></p> + </header> + <p class="caption type-info-container"> + <span class="type-info"></span> + <span class="flags-info"></span> + </p> + </div> + </footer> + </div> +</body> + +</html>
diff --git a/tools/binary_size/libsupersize/templates/sw.js b/tools/binary_size/libsupersize/templates/sw.js index 4028290..f187979 100644 --- a/tools/binary_size/libsupersize/templates/sw.js +++ b/tools/binary_size/libsupersize/templates/sw.js
@@ -8,7 +8,7 @@ const cacheName = '{{cache_hash}}'; const filesToCache = [ 'favicon.ico', - 'index.html', + 'viewer.html', 'infocard-ui.js', 'infocard.css', 'main.css',
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 6b4d241..50886c3a 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -49164,6 +49164,7 @@ <int value="0" label="User signed out of Chrome"/> <int value="1" label="Service was disabled"/> <int value="2" label="Custom passphrase was detected"/> + <int value="3" label="User disabled Unity settings toggle"/> </enum> <enum name="UnifiedConsentSyncAndGoogleServicesSettings">
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index c5e1908..3b9f8575 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -27460,6 +27460,15 @@ </summary> </histogram> +<histogram name="Event.VizHitTestSurfaceLayer.ResultsMatch" enum="Boolean"> + <owner>sunxd@chormium.org</owner> + <owner>event-targeting@chromium.org</owner> + <summary> + This tracks how often the cc layer based hit testing fast path result + matches or doesn't match the asynchronous blink hit test result. + </summary> +</histogram> + <histogram name="ExclusiveAccess.BubbleReshowsPerSession.Fullscreen" units="reshows"> <owner>mgiuca@chromium.org</owner> @@ -60389,6 +60398,19 @@ </summary> </histogram> +<histogram name="Network.Shill.CumulativeTimeOnline" units="seconds"> + <owner>kirtika@chromium.org</owner> + <owner>semenzato@chromium.org</owner> + <summary> + Chrome OS device time on line in the previous 24-hour sample period. + "On line" means shill believes the device is on the internet. The + shill state is sampled every 5 minutes. The start of each 24-hour period is + the end of the previous period, unless the device is inactive at that time + (suspended or off), in which case it is the time of the next + resume/power-on. + </summary> +</histogram> + <histogram name="Network.Shill.DarkResumeActionResult" enum="ShillSuspendTerminationDarkResumeActionResult"> <owner>benchan@chromium.org</owner> @@ -71972,16 +71994,16 @@ <histogram name="PasswordManager.Android.PasswordCredentialEntry" enum="PasswordManagerAndroidPasswordEntryActions"> <owner>jdoerrie@chromium.org</owner> - <owner>melandory@chromium.org</owner> + <owner>vabr@chromium.org</owner> <summary> Records the action taken with a password credential entry on Android. </summary> </histogram> <histogram name="PasswordManager.Android.PasswordCredentialEntry.Password" - enum="PasswordManagerAndroidWebsiteActions"> + enum="PasswordManagerAndroidPasswordActions"> <owner>jdoerrie@chromium.org</owner> - <owner>melandory@chromium.org</owner> + <owner>vabr@chromium.org</owner> <summary> Records the action taken with a password of a password credential entry on Android. @@ -71989,9 +72011,9 @@ </histogram> <histogram name="PasswordManager.Android.PasswordCredentialEntry.Username" - enum="PasswordManagerAndroidWebsiteActions"> + enum="PasswordManagerAndroidUsernameActions"> <owner>jdoerrie@chromium.org</owner> - <owner>melandory@chromium.org</owner> + <owner>vabr@chromium.org</owner> <summary> Records the action taken with a username of a password credential entry on Android. @@ -72001,7 +72023,7 @@ <histogram name="PasswordManager.Android.PasswordCredentialEntry.Website" enum="PasswordManagerAndroidWebsiteActions"> <owner>jdoerrie@chromium.org</owner> - <owner>melandory@chromium.org</owner> + <owner>vabr@chromium.org</owner> <summary> Records the action taken with a website of a password credential entry on Android. @@ -72011,7 +72033,7 @@ <histogram name="PasswordManager.Android.PasswordExceptionEntry" enum="PasswordManagerAndroidPasswordEntryActions"> <owner>jdoerrie@chromium.org</owner> - <owner>melandory@chromium.org</owner> + <owner>vabr@chromium.org</owner> <summary> Records the action taken with a password exception entry on Android. </summary> @@ -72020,7 +72042,7 @@ <histogram name="PasswordManager.Android.PasswordExceptionEntry.Website" enum="PasswordManagerAndroidWebsiteActions"> <owner>jdoerrie@chromium.org</owner> - <owner>melandory@chromium.org</owner> + <owner>vabr@chromium.org</owner> <summary> Records the action taken with a website of a password exception entry on Android. @@ -131108,6 +131130,13 @@ <affected-histogram name="Setup.Install.UnpackFullArchiveTime"/> </histogram_suffixes> +<histogram_suffixes name="ShillCumulativeTimeOnline" separator="."> + <suffix name="Any" label="Any connection type"/> + <suffix name="Cellular" label="Cellular connection"/> + <suffix name="Wifi" label="WiFi connection"/> + <affected-histogram name="Network.Shill.CumulativeTimeOnline"/> +</histogram_suffixes> + <histogram_suffixes name="ShillWiFiRememberedNetworkSecurityMode" separator="."> <suffix name="802_1x" label="Network is secured with 802.1x"/> <suffix name="none" label="Network is not secured"/>
diff --git a/tools/perf/expectations.config b/tools/perf/expectations.config index 15798af..f486f8c 100644 --- a/tools/perf/expectations.config +++ b/tools/perf/expectations.config
@@ -65,6 +65,7 @@ crbug.com/876636 [ ChromeOS ] loading.desktop/TheOnion_cold [ Skip ] crbug.com/876636 [ ChromeOS ] loading.desktop/TheOnion_warm [ Skip ] crbug.com/876636 [ Win_10 ] loading.desktop/TheOnion_warm [ Skip ] +crbug.com/876636 [ Win_7 ] loading.desktop/TheOnion_warm [ Skip ] crbug.com/876636 [ ChromeOS ] loading.desktop/AllRecipes_cold [ Skip ] crbug.com/876636 [ ChromeOS ] loading.desktop/AllRecipes_warm [ Skip ] crbug.com/879833 [ Mac_10.12 ] loading.desktop/AllRecipes_cold [ Skip ]
diff --git a/ui/accessibility/ax_node_data.cc b/ui/accessibility/ax_node_data.cc index 9db9aed2..76810a1a 100644 --- a/ui/accessibility/ax_node_data.cc +++ b/ui/accessibility/ax_node_data.cc
@@ -565,6 +565,11 @@ actions = ModifyFlag(actions, static_cast<uint32_t>(action_enum), true); } +void AXNodeData::RemoveState(ax::mojom::State state_enum) { + DCHECK_NE(state_enum, ax::mojom::State::kNone); + state = ModifyFlag(state, static_cast<uint32_t>(state_enum), false); +} + std::string AXNodeData::ToString() const { std::string result;
diff --git a/ui/accessibility/ax_node_data.h b/ui/accessibility/ax_node_data.h index 468b13f..c7d3320e 100644 --- a/ui/accessibility/ax_node_data.h +++ b/ui/accessibility/ax_node_data.h
@@ -134,6 +134,9 @@ void AddState(ax::mojom::State state_enum); void AddAction(ax::mojom::Action action_enum); + // Remove bits in the given enum's corresponding bitfield. + void RemoveState(ax::mojom::State state_enum); + // Helper functions to get some common int attributes with some specific // enum types: ax::mojom::CheckedState GetCheckedState() const {
diff --git a/ui/accessibility/platform/ax_system_caret_win.cc b/ui/accessibility/platform/ax_system_caret_win.cc index bd475d5..dd91704c 100644 --- a/ui/accessibility/platform/ax_system_caret_win.cc +++ b/ui/accessibility/platform/ax_system_caret_win.cc
@@ -24,6 +24,7 @@ data_.role = ax::mojom::Role::kCaret; // |get_accState| should return 0 which means that the caret is visible. data_.state = 0; + data_.AddState(ax::mojom::State::kInvisible); // According to MSDN, "Edit" should be the name of the caret object. data_.SetName(L"Edit"); data_.offset_container_id = -1; @@ -54,13 +55,43 @@ void AXSystemCaretWin::MoveCaretTo(const gfx::Rect& bounds) { if (bounds.IsEmpty()) return; - data_.location = gfx::RectF(bounds); - if (event_target_) { + + // If the caret has non-empty bounds, assume it has been made visible. + bool newly_visible = false; + if (data_.HasState(ax::mojom::State::kInvisible)) { + newly_visible = true; + data_.RemoveState(ax::mojom::State::kInvisible); + } + + if (!event_target_) + return; + + if (newly_visible) { + ::NotifyWinEvent(EVENT_OBJECT_SHOW, event_target_, OBJID_CARET, + -caret_->GetUniqueId()); + } + + gfx::RectF new_location(bounds); + // Avoid redundant caret move events (if the location stays the same), but + // always fire when it's made visible again. + if (data_.location != new_location || newly_visible) { + data_.location = new_location; ::NotifyWinEvent(EVENT_OBJECT_LOCATIONCHANGE, event_target_, OBJID_CARET, -caret_->GetUniqueId()); } } +void AXSystemCaretWin::Hide() { + if (!data_.HasState(ax::mojom::State::kInvisible)) { + data_.AddState(ax::mojom::State::kInvisible); + data_.location.set_width(0); + if (event_target_) { + ::NotifyWinEvent(EVENT_OBJECT_HIDE, event_target_, OBJID_CARET, + -caret_->GetUniqueId()); + } + } +} + const AXNodeData& AXSystemCaretWin::GetData() const { return data_; }
diff --git a/ui/accessibility/platform/ax_system_caret_win.h b/ui/accessibility/platform/ax_system_caret_win.h index 03f4bf9..a4d2392 100644 --- a/ui/accessibility/platform/ax_system_caret_win.h +++ b/ui/accessibility/platform/ax_system_caret_win.h
@@ -31,6 +31,7 @@ Microsoft::WRL::ComPtr<IAccessible> GetCaret() const; void MoveCaretTo(const gfx::Rect& bounds); + void Hide(); private: // |AXPlatformNodeDelegate| members.
diff --git a/ui/android/delegated_frame_host_android.cc b/ui/android/delegated_frame_host_android.cc index e33fd00..74162a94 100644 --- a/ui/android/delegated_frame_host_android.cc +++ b/ui/android/delegated_frame_host_android.cc
@@ -470,6 +470,10 @@ : viz::SurfaceId(); } +bool DelegatedFrameHostAndroid::HasPrimarySurface() const { + return content_layer_ && content_layer_->primary_surface_id().is_valid(); +} + bool DelegatedFrameHostAndroid::HasFallbackSurface() const { return content_layer_ && content_layer_->fallback_surface_id() && content_layer_->fallback_surface_id()->is_valid(); @@ -477,27 +481,42 @@ void DelegatedFrameHostAndroid::TakeFallbackContentFrom( DelegatedFrameHostAndroid* other) { - if (HasFallbackSurface() || !other->HasFallbackSurface()) + if (HasFallbackSurface() || !other->HasPrimarySurface()) return; - if (!enable_surface_synchronization_) { - if (content_layer_) { - content_layer_->SetPrimarySurfaceId( - *other->content_layer_->fallback_surface_id(), - cc::DeadlinePolicy::UseDefaultDeadline()); + if (enable_surface_synchronization_) { + const viz::SurfaceId& other_primary = + other->content_layer_->primary_surface_id(); + const base::Optional<viz::SurfaceId>& other_fallback = + other->content_layer_->fallback_surface_id(); + viz::SurfaceId desired_fallback; + if (!other->HasFallbackSurface() || + !other_primary.IsSameOrNewerThan(*other_fallback)) { + desired_fallback = other_primary.ToSmallestId(); } else { - const auto& surface_id = other->SurfaceId(); - active_local_surface_id_ = surface_id.local_surface_id(); - pending_local_surface_id_ = active_local_surface_id_; - active_device_scale_factor_ = other->active_device_scale_factor_; - pending_surface_size_in_pixels_ = other->pending_surface_size_in_pixels_; - has_transparent_background_ = other->has_transparent_background_; - content_layer_ = CreateSurfaceLayer( - surface_id, surface_id, other->content_layer_->bounds(), - cc::DeadlinePolicy::UseDefaultDeadline(), - other->content_layer_->contents_opaque()); - view_->GetLayer()->AddChild(content_layer_); + desired_fallback = *other_fallback; } + content_layer_->SetFallbackSurfaceId( + other->content_layer_->primary_surface_id().ToSmallestId()); + return; + } + + if (content_layer_) { + content_layer_->SetPrimarySurfaceId( + *other->content_layer_->fallback_surface_id(), + cc::DeadlinePolicy::UseDefaultDeadline()); + } else { + const auto& surface_id = other->SurfaceId(); + active_local_surface_id_ = surface_id.local_surface_id(); + pending_local_surface_id_ = active_local_surface_id_; + active_device_scale_factor_ = other->active_device_scale_factor_; + pending_surface_size_in_pixels_ = other->pending_surface_size_in_pixels_; + has_transparent_background_ = other->has_transparent_background_; + content_layer_ = CreateSurfaceLayer( + surface_id, surface_id, other->content_layer_->bounds(), + cc::DeadlinePolicy::UseDefaultDeadline(), + other->content_layer_->contents_opaque()); + view_->GetLayer()->AddChild(content_layer_); } content_layer_->SetFallbackSurfaceId( *other->content_layer_->fallback_surface_id());
diff --git a/ui/android/delegated_frame_host_android.h b/ui/android/delegated_frame_host_android.h index ed91cad..7ceee3b 100644 --- a/ui/android/delegated_frame_host_android.h +++ b/ui/android/delegated_frame_host_android.h
@@ -134,6 +134,7 @@ // Returns the ID for the current Surface. Returns an invalid ID if no // surface exists (!HasDelegatedContent()). viz::SurfaceId SurfaceId() const; + bool HasPrimarySurface() const; bool HasFallbackSurface() const; void TakeFallbackContentFrom(DelegatedFrameHostAndroid* other);
diff --git a/ui/android/java/src/org/chromium/ui/base/SelectFileDialog.java b/ui/android/java/src/org/chromium/ui/base/SelectFileDialog.java index f382d7f..33cff06f4 100644 --- a/ui/android/java/src/org/chromium/ui/base/SelectFileDialog.java +++ b/ui/android/java/src/org/chromium/ui/base/SelectFileDialog.java
@@ -20,7 +20,6 @@ import android.webkit.MimeTypeMap; import org.chromium.base.ApiCompatibilityUtils; -import org.chromium.base.AsyncTask; import org.chromium.base.ContentUriUtils; import org.chromium.base.ContextUtils; import org.chromium.base.Log; @@ -29,6 +28,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.task.AsyncTask; import org.chromium.ui.ContactsPickerListener; import org.chromium.ui.PhotoPickerListener; import org.chromium.ui.R;
diff --git a/ui/android/java/src/org/chromium/ui/resources/ResourceExtractor.java b/ui/android/java/src/org/chromium/ui/resources/ResourceExtractor.java index 3f7affbe..38dc095 100644 --- a/ui/android/java/src/org/chromium/ui/resources/ResourceExtractor.java +++ b/ui/android/java/src/org/chromium/ui/resources/ResourceExtractor.java
@@ -8,7 +8,6 @@ import android.os.Handler; import android.os.Looper; -import org.chromium.base.AsyncTask; import org.chromium.base.BuildConfig; import org.chromium.base.BuildInfo; import org.chromium.base.ContextUtils; @@ -18,6 +17,7 @@ import org.chromium.base.PathUtils; import org.chromium.base.ThreadUtils; import org.chromium.base.TraceEvent; +import org.chromium.base.task.AsyncTask; import org.chromium.ui.base.LocalizationUtils; import java.io.File;
diff --git a/ui/android/java/src/org/chromium/ui/resources/async/AsyncPreloadResourceLoader.java b/ui/android/java/src/org/chromium/ui/resources/async/AsyncPreloadResourceLoader.java index cbcbbdf..599c804d4 100644 --- a/ui/android/java/src/org/chromium/ui/resources/async/AsyncPreloadResourceLoader.java +++ b/ui/android/java/src/org/chromium/ui/resources/async/AsyncPreloadResourceLoader.java
@@ -6,8 +6,8 @@ import android.util.SparseArray; -import org.chromium.base.AsyncTask; import org.chromium.base.TraceEvent; +import org.chromium.base.task.AsyncTask; import org.chromium.ui.resources.Resource; import org.chromium.ui.resources.ResourceLoader;
diff --git a/ui/chromeos/BUILD.gn b/ui/chromeos/BUILD.gn index bccdfb4..7c4de18 100644 --- a/ui/chromeos/BUILD.gn +++ b/ui/chromeos/BUILD.gn
@@ -34,6 +34,8 @@ "//components/device_event_log", "//components/onc", "//mojo/public/cpp/bindings", + "//services/device/public/mojom", + "//services/service_manager/public/cpp", "//services/ws/public/cpp", "//services/ws/public/mojom", "//skia",
diff --git a/ui/chromeos/DEPS b/ui/chromeos/DEPS index c303b6e..31ddc40 100644 --- a/ui/chromeos/DEPS +++ b/ui/chromeos/DEPS
@@ -5,6 +5,8 @@ "+grit/ui_chromeos_resources.h", "+grit/ui_chromeos_strings.h", "+mojo/public/cpp/bindings", + "+services/device/public", + "+services/service_manager/public", "+services/ws/public/cpp", "+services/ws/public/mojom", "+third_party/cros_system_api",
diff --git a/ui/chromeos/user_activity_power_manager_notifier.cc b/ui/chromeos/user_activity_power_manager_notifier.cc index 5babd90..10f649d6 100644 --- a/ui/chromeos/user_activity_power_manager_notifier.cc +++ b/ui/chromeos/user_activity_power_manager_notifier.cc
@@ -6,6 +6,8 @@ #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power_manager_client.h" +#include "services/device/public/mojom/constants.mojom.h" +#include "services/service_manager/public/cpp/connector.h" #include "ui/base/user_activity/user_activity_detector.h" #include "ui/events/devices/input_device_manager.h" #include "ui/events/devices/stylus_state.h" @@ -44,10 +46,21 @@ } // namespace UserActivityPowerManagerNotifier::UserActivityPowerManagerNotifier( - UserActivityDetector* detector) - : detector_(detector) { + UserActivityDetector* detector, + service_manager::Connector* connector) + : detector_(detector), fingerprint_observer_binding_(this) { detector_->AddObserver(this); ui::InputDeviceManager::GetInstance()->AddObserver(this); + + // Connector can be null in tests. + if (connector) { + // Treat fingerprint attempts as user activies to turn on the screen. + // I.e., when user tried to use fingerprint to unlock. + connector->BindInterface(device::mojom::kServiceName, &fingerprint_ptr_); + device::mojom::FingerprintObserverPtr observer; + fingerprint_observer_binding_.Bind(mojo::MakeRequest(&observer)); + fingerprint_ptr_->AddFingerprintObserver(std::move(observer)); + } } UserActivityPowerManagerNotifier::~UserActivityPowerManagerNotifier() { @@ -65,6 +78,23 @@ MaybeNotifyUserActivity(GetUserActivityTypeForEvent(event)); } +void UserActivityPowerManagerNotifier::OnAuthScanDone( + uint32_t scan_result, + const base::flat_map<std::string, std::vector<std::string>>& matches) { + MaybeNotifyUserActivity(power_manager::USER_ACTIVITY_OTHER); +} + +void UserActivityPowerManagerNotifier::OnSessionFailed() {} + +void UserActivityPowerManagerNotifier::OnRestarted() {} + +void UserActivityPowerManagerNotifier::OnEnrollScanDone( + uint32_t scan_result, + bool enroll_session_complete, + int percent_complete) { + MaybeNotifyUserActivity(power_manager::USER_ACTIVITY_OTHER); +} + void UserActivityPowerManagerNotifier::MaybeNotifyUserActivity( power_manager::UserActivityType user_activity_type) { base::TimeTicks now = base::TimeTicks::Now();
diff --git a/ui/chromeos/user_activity_power_manager_notifier.h b/ui/chromeos/user_activity_power_manager_notifier.h index be97bceb..9bf384f 100644 --- a/ui/chromeos/user_activity_power_manager_notifier.h +++ b/ui/chromeos/user_activity_power_manager_notifier.h
@@ -8,11 +8,17 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/time/time.h" +#include "mojo/public/cpp/bindings/binding.h" +#include "services/device/public/mojom/fingerprint.mojom.h" #include "third_party/cros_system_api/dbus/service_constants.h" #include "ui/base/user_activity/user_activity_observer.h" #include "ui/chromeos/ui_chromeos_export.h" #include "ui/events/devices/input_device_event_observer.h" +namespace service_manager { +class Connector; +} + namespace ui { class UserActivityDetector; @@ -20,11 +26,13 @@ // Notifies the power manager via D-Bus when the user is active. class UI_CHROMEOS_EXPORT UserActivityPowerManagerNotifier : public InputDeviceEventObserver, - public UserActivityObserver { + public UserActivityObserver, + public device::mojom::FingerprintObserver { public: // Registers and unregisters itself as an observer of |detector| on // construction and destruction. - explicit UserActivityPowerManagerNotifier(UserActivityDetector* detector); + UserActivityPowerManagerNotifier(UserActivityDetector* detector, + service_manager::Connector* connector); ~UserActivityPowerManagerNotifier() override; // InputDeviceEventObserver implementation. @@ -33,6 +41,17 @@ // UserActivityObserver implementation. void OnUserActivity(const Event* event) override; + // fingerprint::mojom::FingerprintObserver: + void OnAuthScanDone( + uint32_t scan_result, + const base::flat_map<std::string, std::vector<std::string>>& matches) + override; + void OnSessionFailed() override; + void OnRestarted() override; + void OnEnrollScanDone(uint32_t scan_result, + bool enroll_session_complete, + int percent_complete) override; + private: // Notifies power manager that the user is active and activity type. No-op if // it is within 5 seconds from |last_notify_time_|. @@ -41,6 +60,10 @@ UserActivityDetector* detector_; // not owned + device::mojom::FingerprintPtr fingerprint_ptr_; + mojo::Binding<device::mojom::FingerprintObserver> + fingerprint_observer_binding_; + // Last time that the power manager was notified. base::TimeTicks last_notify_time_;
diff --git a/ui/gfx/color_analysis.cc b/ui/gfx/color_analysis.cc index 07c3cfb..5aa02fc 100644 --- a/ui/gfx/color_analysis.cc +++ b/ui/gfx/color_analysis.cc
@@ -137,16 +137,6 @@ uint32_t weight_; }; -// Un-premultiplies each pixel in |bitmap| into an output |buffer|. Requires -// approximately 10 microseconds for a 16x16 icon on an Intel Core i5. -void UnPreMultiply(const SkBitmap& bitmap, uint32_t* buffer, int buffer_size) { - uint32_t* in = static_cast<uint32_t*>(bitmap.getPixels()); - uint32_t* out = buffer; - int pixel_count = std::min(bitmap.width() * bitmap.height(), buffer_size); - for (int i = 0; i < pixel_count; ++i) - *out++ = SkUnPreMultiply::PMColorToColor(*in++); -} - // Prominent color utilities --------------------------------------------------- // A color value with an associated weight. @@ -713,12 +703,24 @@ const HSL& lower_bound, const HSL& upper_bound, bool find_closest) { + // Clamp the height being used to the height of the provided image (otherwise, + // we can end up creating a larger buffer than we have data for, and the end + // of the buffer will remain uninitialized after we copy/UnPreMultiply the + // image data into it). + height = std::min(height, bitmap.height()); + // SkBitmap uses pre-multiplied alpha but the KMean clustering function // above uses non-pre-multiplied alpha. Transform the bitmap before we // analyze it because the function reads each pixel multiple times. int pixel_count = bitmap.width() * height; std::unique_ptr<uint32_t[]> image(new uint32_t[pixel_count]); - UnPreMultiply(bitmap, image.get(), pixel_count); + + // Un-premultiplies each pixel in bitmap into the buffer. Requires + // approximately 10 microseconds for a 16x16 icon on an Intel Core i5. + uint32_t* in = static_cast<uint32_t*>(bitmap.getPixels()); + uint32_t* out = image.get(); + for (int i = 0; i < pixel_count; ++i) + *out++ = SkUnPreMultiply::PMColorToColor(*in++); GridSampler sampler; return CalculateKMeanColorOfBuffer(reinterpret_cast<uint8_t*>(image.get()),
diff --git a/ui/gfx/color_utils.cc b/ui/gfx/color_utils.cc index 62a98b0..6bb5a66 100644 --- a/ui/gfx/color_utils.cc +++ b/ui/gfx/color_utils.cc
@@ -189,9 +189,10 @@ } bool IsHSLShiftMeaningful(const HSL& hsl) { - // -1 in any channel is no-op, but additionally 0.5 is no-op for S/L. - return hsl.h != -1 && hsl.s != -1 && hsl.s != 0.5 && hsl.l != -1 && - hsl.l != 0.5; + // -1 in any channel has no effect, and 0.5 has no effect for S/L. A shift + // with an effective value in ANY channel is meaningful. + return hsl.h != -1 || (hsl.s != -1 && hsl.s != 0.5) || + (hsl.l != -1 && hsl.l != 0.5); } SkColor HSLShift(SkColor color, const HSL& shift) {
diff --git a/ui/gfx/color_utils_unittest.cc b/ui/gfx/color_utils_unittest.cc index 966205a..bb0a542 100644 --- a/ui/gfx/color_utils_unittest.cc +++ b/ui/gfx/color_utils_unittest.cc
@@ -103,6 +103,32 @@ EXPECT_FALSE(IsWithinHSLRange(hsl, lower, upper)); } +TEST(ColorUtils, IsHSLShiftMeaningful) { + HSL noop_all_neg_one{-1.0, -1.0, -1.0}; + HSL noop_s_point_five{-1.0, 0.5, -1.0}; + HSL noop_l_point_five{-1.0, -1.0, 0.5}; + + HSL only_h{0.1, -1.0, -1.0}; + HSL only_s{-1.0, 0.1, -1.0}; + HSL only_l{-1.0, -1.0, 0.1}; + HSL only_hs{0.1, 0.1, -1.0}; + HSL only_hl{0.1, -1.0, 0.1}; + HSL only_sl{-1.0, 0.1, 0.1}; + HSL all_set{0.1, 0.2, 0.3}; + + EXPECT_FALSE(IsHSLShiftMeaningful(noop_all_neg_one)); + EXPECT_FALSE(IsHSLShiftMeaningful(noop_s_point_five)); + EXPECT_FALSE(IsHSLShiftMeaningful(noop_l_point_five)); + + EXPECT_TRUE(IsHSLShiftMeaningful(only_h)); + EXPECT_TRUE(IsHSLShiftMeaningful(only_s)); + EXPECT_TRUE(IsHSLShiftMeaningful(only_l)); + EXPECT_TRUE(IsHSLShiftMeaningful(only_hs)); + EXPECT_TRUE(IsHSLShiftMeaningful(only_hl)); + EXPECT_TRUE(IsHSLShiftMeaningful(only_sl)); + EXPECT_TRUE(IsHSLShiftMeaningful(all_set)); +} + TEST(ColorUtils, ColorToHSLRegisterSpill) { // In a opt build on Linux, this was causing a register spill on my laptop // (Pentium M) when converting from SkColor to HSL.
diff --git a/ui/views/win/hwnd_message_handler.cc b/ui/views/win/hwnd_message_handler.cc index 314c562b..9ca4bdad 100644 --- a/ui/views/win/hwnd_message_handler.cc +++ b/ui/views/win/hwnd_message_handler.cc
@@ -1000,12 +1000,14 @@ void HWNDMessageHandler::OnCaretBoundsChanged( const ui::TextInputClient* client) { - if (!client || client->GetTextInputType() == ui::TEXT_INPUT_TYPE_NONE) - return; - if (!ax_system_caret_) ax_system_caret_ = std::make_unique<ui::AXSystemCaretWin>(hwnd()); + if (!client || client->GetTextInputType() == ui::TEXT_INPUT_TYPE_NONE) { + ax_system_caret_->Hide(); + return; + } + const gfx::Rect dip_caret_bounds(client->GetCaretBounds()); gfx::Rect caret_bounds = display::win::ScreenWin::DIPToScreenRect(hwnd(), dip_caret_bounds);