diff --git a/DEPS b/DEPS index 6366bf5..40087840 100644 --- a/DEPS +++ b/DEPS
@@ -40,11 +40,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': 'c86d377a4c595ef33a5d8f854bfdc72c81be91ca', + 'skia_revision': '3a3bc42b7d5b9d996debab1d2a05d2137c875bd7', # 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': 'd924131db259af39eaf887c70282182fbc834d76', + 'v8_revision': '4f7d985201a09efb3069343fe5c9f78c110f6160', # 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. @@ -96,7 +96,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': 'cabc13146729eeee3d96d42c345c07da760bb31c', + 'catapult_revision': '24e36dadf5b1aff6cebffa55b476cd7ef64eba0a', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other.
diff --git a/WATCHLISTS b/WATCHLISTS index 2207316..26c3533 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -893,9 +893,6 @@ 'filepath': 'chrome/browser/plugin|chrome/plugin/|'\ 'chrome/common/plugin', }, - 'policy_definitions': { - 'filepath': 'components/policy/resources/policy_templates.json', - }, 'polymer': { 'filepath': 'third_party/polymer/|'\ 'third_party/web-animations-js/|'\ @@ -2134,7 +2131,6 @@ 'permissions': ['mlamouri+watch-permissions@chromium.org', 'raymes+watch@chromium.org'], 'plugin': ['jam@chromium.org'], - 'policy_definitions': ['tnagel+watch@chromium.org'], 'polymer': ['dbeam+watch-polymer@chromium.org', 'michaelpg+watch-polymer@chromium.org'], 'precache': ['wifiprefetch-reviews@google.com'],
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/crash/MinidumpUploaderTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/crash/MinidumpUploaderTest.java index 0cbf835..af3c1153 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/crash/MinidumpUploaderTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/crash/MinidumpUploaderTest.java
@@ -4,8 +4,6 @@ package org.chromium.android_webview.test.crash; -import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout; - import android.os.ParcelFileDescriptor; import android.support.test.filters.MediumTest; import android.webkit.ValueCallback; @@ -19,9 +17,11 @@ import org.chromium.components.minidump_uploader.CrashTestCase; import org.chromium.components.minidump_uploader.MinidumpUploadCallable; import org.chromium.components.minidump_uploader.MinidumpUploadCallableTest; +import org.chromium.components.minidump_uploader.MinidumpUploadTestUtility; import org.chromium.components.minidump_uploader.MinidumpUploader; import org.chromium.components.minidump_uploader.MinidumpUploaderDelegate; import org.chromium.components.minidump_uploader.MinidumpUploaderImpl; +import org.chromium.components.minidump_uploader.TestMinidumpUploaderImpl; import org.chromium.components.minidump_uploader.util.CrashReportingPermissionManager; import org.chromium.components.minidump_uploader.util.HttpURLConnectionFactory; @@ -37,7 +37,6 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; /** * Instrumentation tests for MinidumpUploader. @@ -46,8 +45,6 @@ private static final String TAG = "MinidumpUploaderTest"; private static final String BOUNDARY = "TESTBOUNDARY"; - private static final long TIME_OUT_MILLIS = 3000; - @Override protected File getExistingCacheDir() { return CrashReceiverService.getOrCreateWebViewCrashDir(); @@ -72,44 +69,12 @@ } } - private class TestMinidumpUploaderImpl extends MinidumpUploaderImpl { - private final CrashReportingPermissionManager mPermissionManager; - - TestMinidumpUploaderImpl(CrashReportingPermissionManager permissionManager) { - super(new AwMinidumpUploaderDelegate()); - mPermissionManager = permissionManager; - } - - TestMinidumpUploaderImpl(MinidumpUploaderDelegate delegate, - CrashReportingPermissionManager permissionManager) { - super(delegate); - mPermissionManager = permissionManager; - } - - @Override - public CrashFileManager createCrashFileManager(File crashDir) { - return new CrashFileManager(crashDir) { - @Override - public void cleanOutAllNonFreshMinidumpFiles() {} - }; - } - - @Override - public MinidumpUploadCallable createMinidumpUploadCallable( - File minidumpFile, File logfile) { - return new MinidumpUploadCallable(minidumpFile, logfile, - new MinidumpUploadCallableTest.TestHttpURLConnectionFactory(), - mPermissionManager); - } - } - /** * Test to ensure the minidump uploading mechanism behaves as expected when we fail to upload * minidumps. */ @MediumTest public void testFailUploadingMinidumps() throws IOException { - PlatformServiceBridge.injectInstance(new TestPlatformServiceBridge(true)); final CrashReportingPermissionManager permManager = new MockCrashReportingPermissionManager() { { @@ -119,7 +84,8 @@ mIsEnabledForTests = false; } }; - MinidumpUploader minidumpUploader = new TestMinidumpUploaderImpl(permManager); + MinidumpUploader minidumpUploader = + new TestMinidumpUploaderImpl(getExistingCacheDir(), permManager); File firstFile = createMinidumpFileInCrashDir("1_abc.dmp0"); File secondFile = createMinidumpFileInCrashDir("12_abc.dmp0"); @@ -134,7 +100,8 @@ File expectedJustBelowMaxTriesFile = new File(mCrashDir, justBelowMaxTriesFile.getName().replace(triesBelowMaxString, maxTriesString)); - uploadMinidumpsSync(minidumpUploader, true /* expectReschedule */); + MinidumpUploadTestUtility.uploadMinidumpsSync( + minidumpUploader, true /* expectReschedule */); assertFalse(firstFile.exists()); assertFalse(secondFile.exists()); assertFalse(justBelowMaxTriesFile.exists()); @@ -146,55 +113,6 @@ } /** - * Utility method for running {@param minidumpUploader}.uploadAllMinidumps on the UI thread to - * avoid breaking any assertions about running on the UI thread. - */ - private static void uploadAllMinidumpsOnUiThread(final MinidumpUploader minidumpUploader, - final MinidumpUploader.UploadsFinishedCallback uploadsFinishedCallback) { - uploadAllMinidumpsOnUiThread( - minidumpUploader, uploadsFinishedCallback, false /* blockUntilJobPosted */); - } - - private static void uploadAllMinidumpsOnUiThread(final MinidumpUploader minidumpUploader, - final MinidumpUploader.UploadsFinishedCallback uploadsFinishedCallback, - boolean blockUntilJobPosted) { - final CountDownLatch jobPostedLatch = new CountDownLatch(1); - ThreadUtils.runOnUiThread(new Runnable() { - @Override - public void run() { - minidumpUploader.uploadAllMinidumps(uploadsFinishedCallback); - jobPostedLatch.countDown(); - } - }); - if (blockUntilJobPosted) { - try { - jobPostedLatch.await(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - } - - private static void uploadMinidumpsSync( - MinidumpUploader minidumpUploader, final boolean expectReschedule) { - final CountDownLatch uploadsFinishedLatch = new CountDownLatch(1); - uploadAllMinidumpsOnUiThread( - minidumpUploader, new MinidumpUploader.UploadsFinishedCallback() { - @Override - public void uploadsFinished(boolean reschedule) { - assertEquals(expectReschedule, reschedule); - uploadsFinishedLatch.countDown(); - } - }); - try { - assertTrue(uploadsFinishedLatch.await( - scaleTimeout(TIME_OUT_MILLIS), TimeUnit.MILLISECONDS)); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - - /** * Ensure MinidumpUploaderImpl doesn't crash even if the WebView Crash dir doesn't exist (could * happen e.g. if a Job persists across WebView-updates? * @@ -212,7 +130,15 @@ new MockCrashReportingPermissionManager() { { mIsEnabledForTests = true; } }; - MinidumpUploader minidumpUploader = new TestMinidumpUploaderImpl(permManager); + MinidumpUploader minidumpUploader = + // Use AwMinidumpUploaderDelegate instead of TestMinidumpUploaderDelegate here + // since AwMinidumpUploaderDelegate defines the WebView crash directory. + new TestMinidumpUploaderImpl(new AwMinidumpUploaderDelegate() { + @Override + public CrashReportingPermissionManager createCrashReportingPermissionManager() { + return permManager; + } + }); File firstFile = createMinidumpFileInCrashDir("1_abc.dmp0"); File secondFile = createMinidumpFileInCrashDir("12_abcd.dmp0"); @@ -221,7 +147,8 @@ File expectedSecondUploadFile = new File(mCrashDir, secondFile.getName().replace(".dmp", ".up")); - uploadMinidumpsSync(minidumpUploader, false /* expectReschedule */); + MinidumpUploadTestUtility.uploadMinidumpsSync( + minidumpUploader, false /* expectReschedule */); assertFalse(firstFile.exists()); assertTrue(expectedFirstUploadFile.exists()); @@ -235,8 +162,7 @@ private MinidumpUploaderImpl createCallableListMinidumpUploader( final List<MinidumpUploadCallableCreator> callables, final boolean userPermitted) { - PlatformServiceBridge.injectInstance(new TestPlatformServiceBridge(userPermitted)); - return new TestMinidumpUploaderImpl(null) { + return new TestMinidumpUploaderImpl(getExistingCacheDir(), null) { private int mIndex = 0; @Override @@ -277,7 +203,8 @@ File firstFile = createMinidumpFileInCrashDir("firstFile.dmp0"); File secondFile = createMinidumpFileInCrashDir("secondFile.dmp0"); - uploadMinidumpsSync(minidumpUploader, true /* expectReschedule */); + MinidumpUploadTestUtility.uploadMinidumpsSync( + minidumpUploader, true /* expectReschedule */); assertFalse(firstFile.exists()); assertFalse(secondFile.exists()); File expectedSecondFile; @@ -354,13 +281,13 @@ } private void testCancellation(final boolean successfulUpload) throws IOException { - PlatformServiceBridge.injectInstance(new TestPlatformServiceBridge(true)); final CrashReportingPermissionManager permManager = new MockCrashReportingPermissionManager() { { mIsEnabledForTests = true; } }; final CountDownLatch stopStallingLatch = new CountDownLatch(1); - MinidumpUploaderImpl minidumpUploader = new TestMinidumpUploaderImpl(permManager) { + MinidumpUploaderImpl minidumpUploader = new TestMinidumpUploaderImpl( + getExistingCacheDir(), permManager) { @Override public MinidumpUploadCallable createMinidumpUploadCallable( File minidumpFile, File logfile) { @@ -376,7 +303,7 @@ File expectedFirstRetryFile = new File(mCrashDir, firstFile.getName() + ".try1"); // This is run on the UI thread to avoid failing any assertOnUiThread assertions. - uploadAllMinidumpsOnUiThread(minidumpUploader, + MinidumpUploadTestUtility.uploadAllMinidumpsOnUiThread(minidumpUploader, new MinidumpUploader.UploadsFinishedCallback() { @Override public void uploadsFinished(boolean reschedule) { @@ -497,8 +424,7 @@ PlatformServiceBridge.injectInstance(new TestPlatformServiceBridge(userConsent)); MinidumpUploaderDelegate delegate = new WebViewUserConsentMinidumpUploaderDelegate(userConsent); - MinidumpUploader minidumpUploader = new TestMinidumpUploaderImpl( - delegate, delegate.createCrashReportingPermissionManager()); + MinidumpUploader minidumpUploader = new TestMinidumpUploaderImpl(delegate); File firstFile = createMinidumpFileInCrashDir("1_abc.dmp0"); File secondFile = createMinidumpFileInCrashDir("12_abcd.dmp0"); @@ -507,7 +433,8 @@ File expectedSecondFile = new File( mCrashDir, secondFile.getName().replace(".dmp", userConsent ? ".up" : ".skipped")); - uploadMinidumpsSync(minidumpUploader, false /* expectReschedule */); + MinidumpUploadTestUtility.uploadMinidumpsSync( + minidumpUploader, false /* expectReschedule */); assertFalse(firstFile.exists()); assertTrue(expectedFirstFile.exists()); @@ -595,14 +522,23 @@ uids[n] /* uid */, fileDescriptors[n], false /* scheduleUploads */); } - PlatformServiceBridge.injectInstance(new TestPlatformServiceBridge(true)); final CrashReportingPermissionManager permManager = new MockCrashReportingPermissionManager() { { mIsEnabledForTests = true; } }; - MinidumpUploader minidumpUploader = new TestMinidumpUploaderImpl(permManager); + MinidumpUploader minidumpUploader = + // Use AwMinidumpUploaderDelegate instead of TestMinidumpUploaderDelegate to ensure + // AwMinidumpUploaderDelegate works well together with the minidump-copying methods + // of CrashReceiverService. + new TestMinidumpUploaderImpl(new AwMinidumpUploaderDelegate() { + @Override + public CrashReportingPermissionManager createCrashReportingPermissionManager() { + return permManager; + } + }); - uploadMinidumpsSync(minidumpUploader, false /* expectReschedule */); + MinidumpUploadTestUtility.uploadMinidumpsSync( + minidumpUploader, false /* expectReschedule */); // Ensure there are no minidumps left to upload. File[] nonUploadedMinidumps = fileManager.getAllMinidumpFiles(MinidumpUploaderImpl.MAX_UPLOAD_TRIES_ALLOWED);
diff --git a/ash/resources/vector_icons/shelf_overview.1x.icon b/ash/resources/vector_icons/shelf_overview.1x.icon index f443ef1..1a6790c 100644 --- a/ash/resources/vector_icons/shelf_overview.1x.icon +++ b/ash/resources/vector_icons/shelf_overview.1x.icon
@@ -3,36 +3,28 @@ // found in the LICENSE file. CANVAS_DIMENSIONS, 16, -MOVE_TO, 2, 3, -R_CUBIC_TO, -0.53f, 0, -1, 0.45f, -1, 1, +MOVE_TO, 2, 4, +R_H_LINE_TO, 9, R_V_LINE_TO, 8, -R_CUBIC_TO, 0, 0.55f, 0.47f, 1, 1, 1, -R_H_LINE_TO, 8, -R_CUBIC_TO, 0.53f, 0, 1, -0.45f, 1, -1, -V_LINE_TO, 4, -R_CUBIC_TO, 0, -0.55f, -0.47f, -1, -1, -1, H_LINE_TO, 2, +V_LINE_TO, 4, CLOSE, -R_MOVE_TO, 1, 8, -V_LINE_TO, 5, -R_H_LINE_TO, 6, +R_MOVE_TO, 1, 1, R_V_LINE_TO, 6, +R_CUBIC_TO, 0, 0, 6.95f, 0.01f, 7, 0, +R_CUBIC_TO, 0.05f, -0.01f, 0, -6, 0, -6, H_LINE_TO, 3, CLOSE, -MOVE_TO, 12.29f, 13, -R_CUBIC_TO, 0.39f, 0, 0.71f, -0.45f, 0.71f, -1.01f, -V_LINE_TO, 4.01f, -CUBIC_TO, 13, 3.45f, 12.68f, 3, 12.29f, 3, -H_LINE_TO, 12, -R_V_LINE_TO, 10, -R_H_LINE_TO, 0.29f, +R_MOVE_TO, 11, -1, +R_H_LINE_TO, 1, +R_V_LINE_TO, 8, +R_H_LINE_TO, -1, +V_LINE_TO, 4, CLOSE, -MOVE_TO, 14.29f, 13, -R_CUBIC_TO, 0.39f, 0, 0.71f, -0.45f, 0.71f, -1.01f, -V_LINE_TO, 4.01f, -CUBIC_TO, 15, 3.45f, 14.68f, 3, 14.29f, 3, -H_LINE_TO, 14, -R_V_LINE_TO, 10, -R_H_LINE_TO, 0.29f, +R_MOVE_TO, -2, 0, +R_H_LINE_TO, 1, +R_V_LINE_TO, 8, +R_H_LINE_TO, -1, +V_LINE_TO, 4, CLOSE, END
diff --git a/ash/resources/vector_icons/shelf_overview.icon b/ash/resources/vector_icons/shelf_overview.icon index 5bfc8c88..17f9031 100644 --- a/ash/resources/vector_icons/shelf_overview.icon +++ b/ash/resources/vector_icons/shelf_overview.icon
@@ -3,36 +3,28 @@ // found in the LICENSE file. CANVAS_DIMENSIONS, 32, -MOVE_TO, 4, 7, -R_CUBIC_TO, -1.06f, 0, -2, 0.9f, -2, 2, -R_V_LINE_TO, 14, -R_CUBIC_TO, 0, 1.1f, 0.94f, 2, 2, 2, +MOVE_TO, 1, 7, +R_H_LINE_TO, 20, +R_V_LINE_TO, 18, +H_LINE_TO, 1, +V_LINE_TO, 7, +CLOSE, +R_MOVE_TO, 3, 3, +R_V_LINE_TO, 12, R_H_LINE_TO, 14, -R_CUBIC_TO, 1.06f, 0, 2, -0.9f, 2, -2, -V_LINE_TO, 9, -R_CUBIC_TO, 0, -1.1f, -0.94f, -2, -2, -2, +V_LINE_TO, 10, H_LINE_TO, 4, CLOSE, -R_MOVE_TO, 13, 15, -H_LINE_TO, 5, -V_LINE_TO, 10, -R_H_LINE_TO, 12, -R_V_LINE_TO, 12, -CLOSE, -MOVE_TO, 22.88f, 25, -CUBIC_TO, 24.05f, 25, 25, 24.1f, 25, 22.99f, -V_LINE_TO, 9.01f, -CUBIC_TO, 25, 7.9f, 24.05f, 7, 22.88f, 7, -H_LINE_TO, 22, +R_MOVE_TO, 24, -3, +R_H_LINE_TO, 3, R_V_LINE_TO, 18, -R_H_LINE_TO, 0.88f, +R_H_LINE_TO, -3, +V_LINE_TO, 7, CLOSE, -MOVE_TO, 27.88f, 25, -CUBIC_TO, 29.05f, 25, 30, 24.1f, 30, 22.99f, -V_LINE_TO, 9.01f, -CUBIC_TO, 30, 7.9f, 29.05f, 7, 27.88f, 7, -H_LINE_TO, 27, +R_MOVE_TO, -5, 0, +R_H_LINE_TO, 3, R_V_LINE_TO, 18, -R_H_LINE_TO, 0.88f, +R_H_LINE_TO, -3, +V_LINE_TO, 7, CLOSE, END
diff --git a/ash/wm/resize_shadow.cc b/ash/wm/resize_shadow.cc index 53eba70..7bc460f 100644 --- a/ash/wm/resize_shadow.cc +++ b/ash/wm/resize_shadow.cc
@@ -19,6 +19,11 @@ // window. constexpr int kVisualThickness = 8; +// The corner radius of the resize shadow, which not coincidentally matches +// the corner radius of the actual window. +static constexpr int kCornerRadiusOfResizeShadow = 2; +static constexpr int kCornerRadiusOfWindow = 2; + // This class simply draws a roundrect. The layout and tiling is handled by // ResizeShadow and NinePatchLayer. class ResizeShadowImageSource : public gfx::CanvasImageSource { @@ -34,12 +39,16 @@ cc::PaintFlags paint; paint.setAntiAlias(true); paint.setColor(SK_ColorBLACK); - canvas->DrawRoundRect(gfx::RectF(gfx::SizeF(size())), kCornerRadius, paint); + canvas->DrawRoundRect(gfx::RectF(gfx::SizeF(size())), + kCornerRadiusOfResizeShadow, paint); } private: - static constexpr int kCornerRadius = 2; - static constexpr int kImageSide = 2 * kVisualThickness + 1; + // The image has to have enough space to depict the visual thickness (left and + // right) plus an inset for extending beneath the window's rounded corner plus + // one pixel for the center of the nine patch. + static constexpr int kImageSide = + 2 * (kVisualThickness + kCornerRadiusOfWindow) + 1; DISALLOW_COPY_AND_ASSIGN(ResizeShadowImageSource); }; @@ -69,7 +78,8 @@ } layer_->UpdateNinePatchLayerImage(*g_shadow_image.Get()); gfx::Rect aperture(g_shadow_image.Get()->size()); - constexpr gfx::Insets kApertureInsets(kVisualThickness); + constexpr gfx::Insets kApertureInsets(kVisualThickness + + kCornerRadiusOfWindow); aperture.Inset(kApertureInsets); layer_->UpdateNinePatchLayerAperture(aperture); layer_->UpdateNinePatchLayerBorder(
diff --git a/base/android/java/src/org/chromium/base/ResourceExtractor.java b/base/android/java/src/org/chromium/base/ResourceExtractor.java index c1d18560..ce30ba6 100644 --- a/base/android/java/src/org/chromium/base/ResourceExtractor.java +++ b/base/android/java/src/org/chromium/base/ResourceExtractor.java
@@ -44,8 +44,9 @@ private void extractResourceHelper(InputStream is, File outFile, byte[] buffer) throws IOException { OutputStream os = null; + File tmpOutputFile = new File(outFile.getPath() + ".tmp"); try { - os = new FileOutputStream(outFile); + os = new FileOutputStream(tmpOutputFile); Log.i(TAG, "Extracting resource %s", outFile); int count = 0; @@ -53,15 +54,11 @@ os.write(buffer, 0, count); } } finally { - try { - if (os != null) { - os.close(); - } - } finally { - if (is != null) { - is.close(); - } - } + StreamUtil.closeQuietly(os); + StreamUtil.closeQuietly(is); + } + if (!tmpOutputFile.renameTo(outFile)) { + throw new IOException(); } } @@ -88,7 +85,7 @@ } TraceEvent.begin("WalkAssets"); - byte[] buffer = new byte[BUFFER_SIZE]; + byte[] buffer = null; try { for (String assetName : mAssetsToExtract) { File output = new File(outputDir, assetName); @@ -98,6 +95,9 @@ continue; } TraceEvent.begin("ExtractResource"); + if (buffer == null) { + buffer = new byte[BUFFER_SIZE]; + } InputStream inputStream = ContextUtils.getApplicationContext().getAssets().open(assetName); try {
diff --git a/base/profiler/stack_sampling_profiler.cc b/base/profiler/stack_sampling_profiler.cc index fa98bed..0263a9f 100644 --- a/base/profiler/stack_sampling_profiler.cc +++ b/base/profiler/stack_sampling_profiler.cc
@@ -5,16 +5,23 @@ #include "base/profiler/stack_sampling_profiler.h" #include <algorithm> +#include <map> #include <utility> +#include "base/atomic_sequence_num.h" +#include "base/atomicops.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" #include "base/lazy_instance.h" #include "base/location.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" +#include "base/memory/singleton.h" #include "base/profiler/native_stack_sampler.h" #include "base/synchronization/lock.h" +#include "base/threading/thread.h" +#include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/timer/elapsed_timer.h" @@ -22,65 +29,9 @@ namespace { -// Used to ensure only one profiler is running at a time. -LazyInstance<Lock>::Leaky concurrent_profiling_lock = LAZY_INSTANCE_INITIALIZER; - -// AsyncRunner ---------------------------------------------------------------- - -// Helper class to allow a profiler to be run completely asynchronously from the -// initiator, without being concerned with the profiler's lifetime. -class AsyncRunner { - public: - // Sets up a profiler and arranges for it to be deleted on its completed - // callback. - static void Run(PlatformThreadId thread_id, - const StackSamplingProfiler::SamplingParams& params, - const StackSamplingProfiler::CompletedCallback& callback); - - private: - AsyncRunner(); - - // Runs the callback and deletes the AsyncRunner instance. |profiles| is not - // const& because it must be passed with std::move. - static void RunCallbackAndDeleteInstance( - std::unique_ptr<AsyncRunner> object_to_be_deleted, - const StackSamplingProfiler::CompletedCallback& callback, - scoped_refptr<SingleThreadTaskRunner> task_runner, - StackSamplingProfiler::CallStackProfiles profiles); - - std::unique_ptr<StackSamplingProfiler> profiler_; - - DISALLOW_COPY_AND_ASSIGN(AsyncRunner); -}; - -// static -void AsyncRunner::Run( - PlatformThreadId thread_id, - const StackSamplingProfiler::SamplingParams& params, - const StackSamplingProfiler::CompletedCallback &callback) { - std::unique_ptr<AsyncRunner> runner(new AsyncRunner); - AsyncRunner* temp_ptr = runner.get(); - temp_ptr->profiler_.reset( - new StackSamplingProfiler(thread_id, params, - Bind(&AsyncRunner::RunCallbackAndDeleteInstance, - Passed(&runner), callback, - ThreadTaskRunnerHandle::Get()))); - // The callback won't be called until after Start(), so temp_ptr will still - // be valid here. - temp_ptr->profiler_->Start(); -} - -AsyncRunner::AsyncRunner() {} - -void AsyncRunner::RunCallbackAndDeleteInstance( - std::unique_ptr<AsyncRunner> object_to_be_deleted, - const StackSamplingProfiler::CompletedCallback& callback, - scoped_refptr<SingleThreadTaskRunner> task_runner, - StackSamplingProfiler::CallStackProfiles profiles) { - callback.Run(std::move(profiles)); - // Delete the instance on the original calling thread. - task_runner->DeleteSoon(FROM_HERE, object_to_be_deleted.release()); -} +// This value is used when there is no collection in progress and thus no ID +// for referencing the active collection to the SamplingThread. +const int NULL_COLLECTION_ID = -1; void ChangeAtomicFlags(subtle::Atomic32* flags, subtle::Atomic32 set, @@ -160,136 +111,647 @@ // StackSamplingProfiler::SamplingThread -------------------------------------- -StackSamplingProfiler::SamplingThread::SamplingThread( - std::unique_ptr<NativeStackSampler> native_sampler, - const SamplingParams& params, - const CompletedCallback& completed_callback) - : native_sampler_(std::move(native_sampler)), - params_(params), - stop_event_(WaitableEvent::ResetPolicy::AUTOMATIC, - WaitableEvent::InitialState::NOT_SIGNALED), - completed_callback_(completed_callback) {} +class StackSamplingProfiler::SamplingThread : public Thread { + public: + class TestAPI { + public: + // Reset the existing sampler. This will unfortunately create the object + // unnecessarily if it doesn't already exist but there's no way around that. + static void Reset(); -StackSamplingProfiler::SamplingThread::~SamplingThread() {} + // Disables inherent idle-shutdown behavior. + static void DisableIdleShutdown(); -void StackSamplingProfiler::SamplingThread::ThreadMain() { - PlatformThread::SetName("Chrome_SamplingProfilerThread"); + // Begins an idle shutdown as if the idle-timer had expired and wait for + // it to execute. Since the timer would have only been started at a time + // when the sampling thread actually was idle, this must be called only + // when it is known that there are no active sampling threads. If + // |simulate_intervening_add| is true then, when executed, the shutdown + // task will believe that a new collection has been added since it was + // posted. + static void ShutdownAssumingIdle(bool simulate_intervening_add); - // For now, just ignore any requests to profile while another profiler is - // working. - if (!concurrent_profiling_lock.Get().Try()) - return; + private: + // Calls the sampling threads ShutdownTask and then signals an event. + static void ShutdownTaskAndSignalEvent(SamplingThread* sampler, + int add_events, + WaitableEvent* event); + }; - CallStackProfiles profiles; - CollectProfiles(&profiles); - concurrent_profiling_lock.Get().Release(); - completed_callback_.Run(std::move(profiles)); -} + struct CollectionContext { + CollectionContext(PlatformThreadId target, + const SamplingParams& params, + const CompletedCallback& callback, + WaitableEvent* finished, + std::unique_ptr<NativeStackSampler> sampler) + : collection_id(next_collection_id_.GetNext()), + target(target), + params(params), + callback(callback), + finished(finished), + native_sampler(std::move(sampler)) {} + ~CollectionContext() {} -// Depending on how long the sampling takes and the length of the sampling -// interval, a burst of samples could take arbitrarily longer than -// samples_per_burst * sampling_interval. In this case, we (somewhat -// arbitrarily) honor the number of samples requested rather than strictly -// adhering to the sampling intervals. Once we have established users for the -// StackSamplingProfiler and the collected data to judge, we may go the other -// way or make this behavior configurable. -void StackSamplingProfiler::SamplingThread::CollectProfile( - CallStackProfile* profile, - TimeDelta* elapsed_time, - bool* was_stopped) { - ElapsedTimer profile_timer; - native_sampler_->ProfileRecordingStarting(&profile->modules); - profile->sampling_period = params_.sampling_interval; - *was_stopped = false; - TimeDelta previous_elapsed_sample_time; - for (int i = 0; i < params_.samples_per_burst; ++i) { - if (i != 0) { - // Always wait, even if for 0 seconds, so we can observe a signal on - // stop_event_. - if (stop_event_.TimedWait( - std::max(params_.sampling_interval - previous_elapsed_sample_time, - TimeDelta()))) { - *was_stopped = true; - break; - } - } - ElapsedTimer sample_timer; - profile->samples.push_back(Sample()); - native_sampler_->RecordStackSample(&profile->samples.back()); - previous_elapsed_sample_time = sample_timer.Elapsed(); + // An identifier for this collection, used to uniquely identify it to + // outside interests. + const int collection_id; + + const PlatformThreadId target; // ID of The thread being sampled. + const SamplingParams params; // Information about how to sample. + const CompletedCallback callback; // Callback made when sampling complete. + WaitableEvent* const finished; // Signaled when all sampling complete. + + // Platform-specific module that does the actual sampling. + std::unique_ptr<NativeStackSampler> native_sampler; + + // The absolute time for the next sample. + Time next_sample_time; + + // The time that a profile was started, for calculating the total duration. + Time profile_start_time; + + // Counters that indicate the current position along the acquisition. + int burst = 0; + int sample = 0; + + // The collected stack samples. The active profile is always at the back(). + CallStackProfiles profiles; + + private: + static StaticAtomicSequenceNumber next_collection_id_; + }; + + // Gets the single instance of this class. + static SamplingThread* GetInstance(); + + // Adds a new CollectionContext to the thread. This can be called externally + // from any thread. This returns an ID that can later be used to stop + // the sampling. + int Add(std::unique_ptr<CollectionContext> collection); + + // Removes an active collection based on its ID, forcing it to run its + // callback if any data has been collected. This can be called externally + // from any thread. + void Remove(int id); + + private: + friend class TestAPI; + friend struct DefaultSingletonTraits<SamplingThread>; + + // The different states in which the sampling-thread can be. + enum ThreadExecutionState { + // The thread is not running because it has never been started. It will be + // started when a sampling request is received. + NOT_STARTED, + + // The thread is running and processing tasks. This is the state when any + // sampling requests are active and during the "idle" period afterward + // before the thread is stopped. + RUNNING, + + // Once all sampling requests have finished and the "idle" period has + // expired, the thread will be set to this state and its shutdown + // initiated. A call to Stop() must be made to ensure the previous thread + // has completely exited before calling Start() and moving back to the + // RUNNING state. + EXITING, + }; + + SamplingThread(); + ~SamplingThread() override; + + // Get task runner that is usable from the outside. + scoped_refptr<SingleThreadTaskRunner> GetOrCreateTaskRunnerForAdd(); + scoped_refptr<SingleThreadTaskRunner> GetTaskRunner( + ThreadExecutionState* out_state); + + // Get task runner that is usable from the sampling thread itself. + scoped_refptr<SingleThreadTaskRunner> GetTaskRunnerOnSamplingThread(); + + // Finishes a collection and reports collected data via callback. + void FinishCollection(CollectionContext* collection); + + // Records a single sample of a collection. + void RecordSample(CollectionContext* collection); + + // Check if the sampling thread is idle and begin a shutdown if it is. + void ScheduleShutdownIfIdle(); + + // These methods are tasks that get posted to the internal message queue. + void AddCollectionTask(std::unique_ptr<CollectionContext> collection); + void RemoveCollectionTask(int id); + void PerformCollectionTask(int id); + void ShutdownTask(int add_events); + + // Updates the |next_sample_time| time based on configured parameters. + // Returns true if there is a next sample or false if sampling is complete. + bool UpdateNextSampleTime(CollectionContext* collection); + + // Thread: + void CleanUp() override; + + // A map of IDs to collection contexts. Because this class is a singleton + // that is never destroyed, context objects will never be destructed except + // by explicit action. Thus, it's acceptable to pass unretained pointers + // to these objects when posting tasks. + std::map<int, std::unique_ptr<CollectionContext>> active_collections_; + + // State maintained about the current execution (or non-execution) of + // the thread. This state must always be accessed while holding the + // lock. A copy of the task-runner is maintained here for use by any + // calling thread; this is necessary because Thread's accessor for it is + // not itself thread-safe. The lock is also used to order calls to the + // Thread API (Start, Stop, StopSoon, & DetachFromSequence) so that + // multiple threads may make those calls. + Lock thread_execution_state_lock_; // Protects all thread_execution_state_* + ThreadExecutionState thread_execution_state_ = NOT_STARTED; + scoped_refptr<SingleThreadTaskRunner> thread_execution_state_task_runner_; + bool thread_execution_state_disable_idle_shutdown_for_testing_ = false; + + // A counter that notes adds of new collection requests. It is incremented + // when changes occur so that delayed shutdown tasks are able to detect if + // samething new has happened while it was waiting. Like all "execution_state" + // vars, this must be accessed while holding |thread_execution_state_lock_|. + int thread_execution_state_add_events_ = 0; + + DISALLOW_COPY_AND_ASSIGN(SamplingThread); +}; + +// static +void StackSamplingProfiler::SamplingThread::TestAPI::Reset() { + SamplingThread* sampler = SamplingThread::GetInstance(); + + ThreadExecutionState state; + { + AutoLock lock(sampler->thread_execution_state_lock_); + state = sampler->thread_execution_state_; + DCHECK(sampler->active_collections_.empty()); } - *elapsed_time = profile_timer.Elapsed(); - profile->profile_duration = *elapsed_time; - native_sampler_->ProfileRecordingStopped(); + // Stop the thread and wait for it to exit. This has to be done through by + // the thread itself because it has taken ownership of its own lifetime. + if (state == RUNNING) { + ShutdownAssumingIdle(false); + state = EXITING; + } + // Make sure thread is cleaned up since state will be reset to NOT_STARTED. + if (state == EXITING) + sampler->Stop(); + + // Reset internal variables to the just-initialized state. + { + AutoLock lock(sampler->thread_execution_state_lock_); + sampler->thread_execution_state_ = NOT_STARTED; + sampler->thread_execution_state_task_runner_ = nullptr; + sampler->thread_execution_state_disable_idle_shutdown_for_testing_ = false; + sampler->thread_execution_state_add_events_ = 0; + } } -// In an analogous manner to CollectProfile() and samples exceeding the expected -// total sampling time, bursts may also exceed the burst_interval. We adopt the -// same wait-and-see approach here. -void StackSamplingProfiler::SamplingThread::CollectProfiles( - CallStackProfiles* profiles) { - if (stop_event_.TimedWait(params_.initial_delay)) +// static +void StackSamplingProfiler::SamplingThread::TestAPI::DisableIdleShutdown() { + SamplingThread* sampler = SamplingThread::GetInstance(); + + { + AutoLock lock(sampler->thread_execution_state_lock_); + sampler->thread_execution_state_disable_idle_shutdown_for_testing_ = true; + } +} + +// static +void StackSamplingProfiler::SamplingThread::TestAPI::ShutdownAssumingIdle( + bool simulate_intervening_add) { + SamplingThread* sampler = SamplingThread::GetInstance(); + + ThreadExecutionState state; + scoped_refptr<SingleThreadTaskRunner> task_runner = + sampler->GetTaskRunner(&state); + DCHECK_EQ(RUNNING, state); + DCHECK(task_runner); + + int add_events; + { + AutoLock lock(sampler->thread_execution_state_lock_); + add_events = sampler->thread_execution_state_add_events_; + if (simulate_intervening_add) + ++sampler->thread_execution_state_add_events_; + } + + WaitableEvent executed(WaitableEvent::ResetPolicy::MANUAL, + WaitableEvent::InitialState::NOT_SIGNALED); + // PostTaskAndReply won't work because thread and associated message-loop may + // be shut down. + task_runner->PostTask(FROM_HERE, + Bind(&ShutdownTaskAndSignalEvent, Unretained(sampler), + add_events, Unretained(&executed))); + executed.Wait(); +} + +// static +void StackSamplingProfiler::SamplingThread::TestAPI::ShutdownTaskAndSignalEvent( + SamplingThread* sampler, + int add_events, + WaitableEvent* event) { + sampler->ShutdownTask(add_events); + event->Signal(); +} + +StaticAtomicSequenceNumber StackSamplingProfiler::SamplingThread:: + CollectionContext::next_collection_id_; + +StackSamplingProfiler::SamplingThread::SamplingThread() + : Thread("StackSamplingProfiler") {} + +StackSamplingProfiler::SamplingThread::~SamplingThread() = default; + +StackSamplingProfiler::SamplingThread* +StackSamplingProfiler::SamplingThread::GetInstance() { + return Singleton<SamplingThread, LeakySingletonTraits<SamplingThread>>::get(); +} + +int StackSamplingProfiler::SamplingThread::Add( + std::unique_ptr<CollectionContext> collection) { + // This is not to be run on the sampling thread. + + int id = collection->collection_id; + scoped_refptr<SingleThreadTaskRunner> task_runner = + GetOrCreateTaskRunnerForAdd(); + + task_runner->PostTask(FROM_HERE, Bind(&SamplingThread::AddCollectionTask, + Unretained(this), Passed(&collection))); + + return id; +} + +void StackSamplingProfiler::SamplingThread::Remove(int id) { + // This is not to be run on the sampling thread. + + ThreadExecutionState state; + scoped_refptr<SingleThreadTaskRunner> task_runner = GetTaskRunner(&state); + if (state != RUNNING) + return; + DCHECK(task_runner); + + // This can fail if the thread were to exit between acquisition of the task + // runner above and the call below. In that case, however, everything has + // stopped so there's no need to try to stop it. + task_runner->PostTask(FROM_HERE, Bind(&SamplingThread::RemoveCollectionTask, + Unretained(this), id)); +} + +scoped_refptr<SingleThreadTaskRunner> +StackSamplingProfiler::SamplingThread::GetOrCreateTaskRunnerForAdd() { + AutoLock lock(thread_execution_state_lock_); + + // The increment of the "add events" count is why this method is to be only + // called from "add". + ++thread_execution_state_add_events_; + + if (thread_execution_state_ == RUNNING) { + DCHECK(thread_execution_state_task_runner_); + // This shouldn't be called from the sampling thread as it's inefficient. + // Use GetTaskRunnerOnSamplingThread() instead. + DCHECK_NE(GetThreadId(), PlatformThread::CurrentId()); + return thread_execution_state_task_runner_; + } + + if (thread_execution_state_ == EXITING) { + // The previous instance has only been partially cleaned up. It is necessary + // to call Stop() before Start(). + Stop(); + } + + // The thread is not running. Start it and get associated runner. The task- + // runner has to be saved for future use because though it can be used from + // any thread, it can be acquired via task_runner() only on the created + // thread and the thread that creates it (i.e. this thread) for thread-safety + // reasons which are alleviated in SamplingThread by gating access to it with + // the |thread_execution_state_lock_|. + Start(); + thread_execution_state_ = RUNNING; + thread_execution_state_task_runner_ = Thread::task_runner(); + + // Detach the sampling thread from the "sequence" (i.e. thread) that + // started it so that it can be self-managed or stopped by another thread. + DetachFromSequence(); + + return thread_execution_state_task_runner_; +} + +scoped_refptr<SingleThreadTaskRunner> +StackSamplingProfiler::SamplingThread::GetTaskRunner( + ThreadExecutionState* out_state) { + AutoLock lock(thread_execution_state_lock_); + if (out_state) + *out_state = thread_execution_state_; + if (thread_execution_state_ == RUNNING) { + // This shouldn't be called from the sampling thread as it's inefficient. + // Use GetTaskRunnerOnSamplingThread() instead. + DCHECK_NE(GetThreadId(), PlatformThread::CurrentId()); + DCHECK(thread_execution_state_task_runner_); + } else { + DCHECK(!thread_execution_state_task_runner_); + } + + return thread_execution_state_task_runner_; +} + +scoped_refptr<SingleThreadTaskRunner> +StackSamplingProfiler::SamplingThread::GetTaskRunnerOnSamplingThread() { + // This should be called only from the sampling thread as it has limited + // accessibility. + DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); + + return Thread::task_runner(); +} + +void StackSamplingProfiler::SamplingThread::FinishCollection( + CollectionContext* collection) { + DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); + + // If there is no duration for the final profile (because it was stopped), + // calculate it now. + if (!collection->profiles.empty() && + collection->profiles.back().profile_duration == TimeDelta()) { + collection->profiles.back().profile_duration = + Time::Now() - collection->profile_start_time; + } + + // Extract some information so callback and event-signalling can still be + // done after the collection has been removed from the list of "active" ones. + // This allows the the controlling object (and tests using it) to be confident + // that collection is fully finished when those things occur. + const CompletedCallback callback = collection->callback; + CallStackProfiles profiles = std::move(collection->profiles); + WaitableEvent* finished = collection->finished; + + // Remove this collection from the map of known ones. The |collection| + // parameter is invalid after this point. + size_t count = active_collections_.erase(collection->collection_id); + DCHECK_EQ(1U, count); + + // Run the associated callback, passing the collected profiles. + callback.Run(std::move(profiles)); + + // Signal that this collection is finished. + finished->Signal(); +} + +void StackSamplingProfiler::SamplingThread::RecordSample( + CollectionContext* collection) { + DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); + DCHECK(collection->native_sampler); + + // If this is the first sample of a burst, a new Profile needs to be created + // and filled. + if (collection->sample == 0) { + collection->profiles.push_back(CallStackProfile()); + CallStackProfile& profile = collection->profiles.back(); + profile.sampling_period = collection->params.sampling_interval; + collection->profile_start_time = Time::Now(); + collection->native_sampler->ProfileRecordingStarting(&profile.modules); + } + + // The currently active profile being captured. + CallStackProfile& profile = collection->profiles.back(); + + // Record a single sample. + profile.samples.push_back(Sample()); + collection->native_sampler->RecordStackSample(&profile.samples.back()); + + // If this is the last sample of a burst, record the total time. + if (collection->sample == collection->params.samples_per_burst - 1) { + profile.profile_duration = Time::Now() - collection->profile_start_time; + collection->native_sampler->ProfileRecordingStopped(); + } +} + +void StackSamplingProfiler::SamplingThread::ScheduleShutdownIfIdle() { + DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); + + if (!active_collections_.empty()) return; - TimeDelta previous_elapsed_profile_time; - for (int i = 0; i < params_.bursts; ++i) { - if (i != 0) { - // Always wait, even if for 0 seconds, so we can observe a signal on - // stop_event_. - if (stop_event_.TimedWait( - std::max(params_.burst_interval - previous_elapsed_profile_time, - TimeDelta()))) - return; - } - - CallStackProfile profile; - bool was_stopped = false; - CollectProfile(&profile, &previous_elapsed_profile_time, &was_stopped); - if (!profile.samples.empty()) - profiles->push_back(std::move(profile)); - - if (was_stopped) + int add_events; + { + AutoLock lock(thread_execution_state_lock_); + if (thread_execution_state_disable_idle_shutdown_for_testing_) return; + add_events = thread_execution_state_add_events_; + } + + GetTaskRunnerOnSamplingThread()->PostDelayedTask( + FROM_HERE, + Bind(&SamplingThread::ShutdownTask, Unretained(this), add_events), + TimeDelta::FromSeconds(60)); +} + +void StackSamplingProfiler::SamplingThread::AddCollectionTask( + std::unique_ptr<CollectionContext> collection) { + DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); + + const int collection_id = collection->collection_id; + const TimeDelta initial_delay = collection->params.initial_delay; + + active_collections_.insert( + std::make_pair(collection_id, std::move(collection))); + + GetTaskRunnerOnSamplingThread()->PostDelayedTask( + FROM_HERE, + Bind(&SamplingThread::PerformCollectionTask, Unretained(this), + collection_id), + initial_delay); + + // Another increment of "add events" serves to invalidate any pending + // shutdown tasks that may have been initiated between the Add() and this + // task running. + { + AutoLock lock(thread_execution_state_lock_); + ++thread_execution_state_add_events_; } } -void StackSamplingProfiler::SamplingThread::Stop() { - stop_event_.Signal(); +void StackSamplingProfiler::SamplingThread::RemoveCollectionTask(int id) { + DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); + + auto found = active_collections_.find(id); + if (found == active_collections_.end()) + return; + + FinishCollection(found->second.get()); + ScheduleShutdownIfIdle(); +} + +void StackSamplingProfiler::SamplingThread::PerformCollectionTask(int id) { + DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); + + auto found = active_collections_.find(id); + + // The task won't be found if it has been stopped. + if (found == active_collections_.end()) + return; + + CollectionContext* collection = found->second.get(); + + // Handle first-run with no "next time". + if (collection->next_sample_time == Time()) + collection->next_sample_time = Time::Now(); + + // Do the collection of a single sample. + RecordSample(collection); + + // Update the time of the next sample recording. + if (UpdateNextSampleTime(collection)) { + bool success = GetTaskRunnerOnSamplingThread()->PostDelayedTask( + FROM_HERE, + Bind(&SamplingThread::PerformCollectionTask, Unretained(this), id), + std::max(collection->next_sample_time - Time::Now(), TimeDelta())); + DCHECK(success); + } else { + // All capturing has completed so finish the collection. By not re-adding + // it to the task queue, the collection will "expire" (i.e. no further work + // will be done). The |collection| variable will be invalid after this call. + FinishCollection(collection); + ScheduleShutdownIfIdle(); + } +} + +void StackSamplingProfiler::SamplingThread::ShutdownTask(int add_events) { + DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); + + // Holding this lock ensures that any attempt to start another job will + // get postponed until |thread_execution_state_| is updated, thus eliminating + // the race in starting a new thread while the previous one is exiting. + AutoLock lock(thread_execution_state_lock_); + + // If the current count of creation requests doesn't match the passed count + // then other tasks have been created since this was posted. Abort shutdown. + if (thread_execution_state_add_events_ != add_events) + return; + + // There can be no new AddCollectionTasks at this point because creating + // those always increments "add events". There may be other requests, like + // Remove, but it's okay to schedule the thread to stop once they've been + // executed (i.e. "soon"). + DCHECK(active_collections_.empty()); + StopSoon(); + + // StopSoon will have set the owning sequence (again) so it must be detached + // (again) in order for Stop/Start to be called (again) should more work + // come in. Holding the |thread_execution_state_lock_| ensures the necessary + // happens-after with regard to this detach and future Thread API calls. + DetachFromSequence(); + + // Set the thread_state variable so the thread will be restarted when new + // work comes in. Remove the |thread_execution_state_task_runner_| to avoid + // confusion. + thread_execution_state_ = EXITING; + thread_execution_state_task_runner_ = nullptr; +} + +bool StackSamplingProfiler::SamplingThread::UpdateNextSampleTime( + CollectionContext* collection) { + // This will keep a consistent average interval between samples but will + // result in constant series of acquisitions, thus nearly locking out the + // target thread, if the interval is smaller than the time it takes to + // actually acquire the sample. Anything sampling that quickly is going + // to be a problem anyway so don't worry about it. + if (++collection->sample < collection->params.samples_per_burst) { + collection->next_sample_time += collection->params.sampling_interval; + return true; + } + + if (++collection->burst < collection->params.bursts) { + collection->sample = 0; + collection->next_sample_time += collection->params.burst_interval; + return true; + } + + return false; +} + +void StackSamplingProfiler::SamplingThread::CleanUp() { + DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); + + // There should be no collections remaining when the thread stops. + DCHECK(active_collections_.empty()); + + // Let the parent clean up. + Thread::CleanUp(); } // StackSamplingProfiler ------------------------------------------------------ +// static +void StackSamplingProfiler::TestAPI::Reset() { + SamplingThread::TestAPI::Reset(); + ResetAnnotations(); +} + +// static +void StackSamplingProfiler::TestAPI::ResetAnnotations() { + subtle::NoBarrier_Store(&process_milestones_, 0u); +} + +// static +bool StackSamplingProfiler::TestAPI::IsSamplingThreadRunning() { + return SamplingThread::GetInstance()->IsRunning(); +} + +// static +void StackSamplingProfiler::TestAPI::DisableIdleShutdown() { + SamplingThread::TestAPI::DisableIdleShutdown(); +} + +// static +void StackSamplingProfiler::TestAPI::PerformSamplingThreadIdleShutdown( + bool simulate_intervening_start) { + SamplingThread::TestAPI::ShutdownAssumingIdle(simulate_intervening_start); +} + subtle::Atomic32 StackSamplingProfiler::process_milestones_ = 0; StackSamplingProfiler::StackSamplingProfiler( - PlatformThreadId thread_id, const SamplingParams& params, - const CompletedCallback& callback) - : StackSamplingProfiler(thread_id, params, callback, nullptr) {} + const CompletedCallback& callback, + NativeStackSamplerTestDelegate* test_delegate) + : StackSamplingProfiler(base::PlatformThread::CurrentId(), + params, + callback, + test_delegate) {} StackSamplingProfiler::StackSamplingProfiler( PlatformThreadId thread_id, const SamplingParams& params, const CompletedCallback& callback, NativeStackSamplerTestDelegate* test_delegate) - : thread_id_(thread_id), params_(params), completed_callback_(callback), - test_delegate_(test_delegate) { -} + : thread_id_(thread_id), + params_(params), + completed_callback_(callback), + // The event starts "signaled" so code knows it's safe to start thread + // and "manual" so that it can be waited in multiple places. + profiling_inactive_(WaitableEvent::ResetPolicy::MANUAL, + WaitableEvent::InitialState::SIGNALED), + collection_id_(NULL_COLLECTION_ID), + test_delegate_(test_delegate) {} StackSamplingProfiler::~StackSamplingProfiler() { + // Stop returns immediately but the shutdown runs asynchronously. There is a + // non-zero probability that one more sample will be taken after this call + // returns. Stop(); - if (!sampling_thread_handle_.is_null()) - PlatformThread::Join(sampling_thread_handle_); -} -// static -void StackSamplingProfiler::StartAndRunAsync( - PlatformThreadId thread_id, - const SamplingParams& params, - const CompletedCallback& callback) { - CHECK(ThreadTaskRunnerHandle::Get()); - AsyncRunner::Run(thread_id, params, callback); + // The behavior of sampling a thread that has exited is undefined and could + // cause Bad Things(tm) to occur. The safety model provided by this class is + // that an instance of this object is expected to live at least as long as + // the thread it is sampling. However, because the sampling is performed + // asynchronously by the SamplingThread, there is no way to guarantee this + // is true without waiting for it to signal that it has finished. + // + // The wait time should, at most, be only as long as it takes to collect one + // sample (~200us) or none at all if sampling has already completed. + ThreadRestrictions::ScopedAllowWait allow_wait; + profiling_inactive_.Wait(); } void StackSamplingProfiler::Start() { @@ -299,19 +761,25 @@ std::unique_ptr<NativeStackSampler> native_sampler = NativeStackSampler::Create(thread_id_, &RecordAnnotations, test_delegate_); + if (!native_sampler) return; - sampling_thread_.reset(new SamplingThread(std::move(native_sampler), params_, - completed_callback_)); - if (!PlatformThread::Create(0, sampling_thread_.get(), - &sampling_thread_handle_)) - sampling_thread_.reset(); + // Wait for profiling to be "inactive", then reset it for the upcoming run. + profiling_inactive_.Wait(); + profiling_inactive_.Reset(); + + DCHECK_EQ(NULL_COLLECTION_ID, collection_id_); + collection_id_ = SamplingThread::GetInstance()->Add( + MakeUnique<SamplingThread::CollectionContext>( + thread_id_, params_, completed_callback_, &profiling_inactive_, + std::move(native_sampler))); + DCHECK_NE(NULL_COLLECTION_ID, collection_id_); } void StackSamplingProfiler::Stop() { - if (sampling_thread_) - sampling_thread_->Stop(); + SamplingThread::GetInstance()->Remove(collection_id_); + collection_id_ = NULL_COLLECTION_ID; } // static @@ -323,11 +791,6 @@ } // static -void StackSamplingProfiler::ResetAnnotationsForTesting() { - subtle::NoBarrier_Store(&process_milestones_, 0u); -} - -// static void StackSamplingProfiler::RecordAnnotations(Sample* sample) { // The code inside this method must not do anything that could acquire a // mutex, including allocating memory (which includes LOG messages) because
diff --git a/base/profiler/stack_sampling_profiler.h b/base/profiler/stack_sampling_profiler.h index b5aa0c5..a5e30e9 100644 --- a/base/profiler/stack_sampling_profiler.h +++ b/base/profiler/stack_sampling_profiler.h
@@ -179,43 +179,84 @@ TimeDelta sampling_interval = TimeDelta::FromMilliseconds(100); }; + // Testing support. These methods are static beause they interact with the + // sampling thread, a singleton used by all StackSamplingProfiler objects. + // These methods can only be called by the same thread that started the + // sampling. + class BASE_EXPORT TestAPI { + public: + // Resets the internal state to that of a fresh start. This is necessary + // so that tests don't inherit state from previous tests. + static void Reset(); + + // Resets internal annotations (like process phase) to initial values. + static void ResetAnnotations(); + + // Returns whether the sampling thread is currently running or not. + static bool IsSamplingThreadRunning(); + + // Disables inherent idle-shutdown behavior. + static void DisableIdleShutdown(); + + // Initiates an idle shutdown task, as though the idle timer had expired, + // causing the thread to exit. There is no "idle" check so this must be + // called only when all sampling tasks have completed. This blocks until + // the task has been executed, though the actual stopping of the thread + // still happens asynchronously. Watch IsSamplingThreadRunning() to know + // when the thread has exited. If |simulate_intervening_start| is true then + // this method will make it appear to the shutdown task that a new profiler + // was started between when the idle-shutdown was initiated and when it + // runs. + static void PerformSamplingThreadIdleShutdown( + bool simulate_intervening_start); + }; + // The callback type used to collect completed profiles. The passed |profiles| - // are move-only. + // are move-only. Other threads, including the UI thread, may block on + // callback completion so this should run as quickly as possible. // - // IMPORTANT NOTE: the callback is invoked on a thread the profiler + // IMPORTANT NOTE: The callback is invoked on a thread the profiler // constructs, rather than on the thread used to construct the profiler and // set the callback, and thus the callback must be callable on any thread. For // threads with message loops that create StackSamplingProfilers, posting a - // task to the message loop with a copy of the profiles is the recommended + // task to the message loop with the moved (i.e. std::move) profiles is the // thread-safe callback implementation. using CompletedCallback = Callback<void(CallStackProfiles)>; - // Creates a profiler that sends completed profiles to |callback|. The second - // constructor is for test purposes. - StackSamplingProfiler(PlatformThreadId thread_id, - const SamplingParams& params, - const CompletedCallback& callback); - StackSamplingProfiler(PlatformThreadId thread_id, - const SamplingParams& params, - const CompletedCallback& callback, - NativeStackSamplerTestDelegate* test_delegate); - // Stops any profiling currently taking place before destroying the profiler. - ~StackSamplingProfiler(); + // Creates a profiler for the CURRENT thread that sends completed profiles + // to |callback|. An optional |test_delegate| can be supplied by tests. + // The caller must ensure that this object gets destroyed before the current + // thread exits. + StackSamplingProfiler( + const SamplingParams& params, + const CompletedCallback& callback, + NativeStackSamplerTestDelegate* test_delegate = nullptr); - // The fire-and-forget interface: starts a profiler and allows it to complete - // without the caller needing to manage the profiler lifetime. May be invoked - // from any thread, but requires that the calling thread has a message loop. - static void StartAndRunAsync(PlatformThreadId thread_id, - const SamplingParams& params, - const CompletedCallback& callback); + // Creates a profiler for ANOTHER thread that sends completed profiles to + // |callback|. An optional |test_delegate| can be supplied by tests. + // + // IMPORTANT: The caller must ensure that the thread being sampled does not + // exit before this object gets destructed or Bad Things(tm) may occur. + StackSamplingProfiler( + PlatformThreadId thread_id, + const SamplingParams& params, + const CompletedCallback& callback, + NativeStackSamplerTestDelegate* test_delegate = nullptr); + + // Stops any profiling currently taking place before destroying the profiler. + // This will block until the callback has been run if profiling has started + // but not already finished. + ~StackSamplingProfiler(); // Initializes the profiler and starts sampling. void Start(); - // Stops the profiler and any ongoing sampling. Calling this function is - // optional; if not invoked profiling terminates when all the profiling bursts - // specified in the SamplingParams are completed or the profiler is destroyed, - // whichever occurs first. + // Stops the profiler and any ongoing sampling. This method will return + // immediately with the callback being run asynchronously. At most one + // more stack sample will be taken after this method returns. Calling this + // function is optional; if not invoked profiling terminates when all the + // profiling bursts specified in the SamplingParams are completed or the + // profiler object is destroyed, whichever occurs first. void Stop(); // Set the current system state that is recorded with each captured stack @@ -225,49 +266,13 @@ // |process_milestones|. The actual meanings of these bits are defined // (globally) by the caller(s). static void SetProcessMilestone(int milestone); - static void ResetAnnotationsForTesting(); private: + friend class TestAPI; + // SamplingThread is a separate thread used to suspend and sample stacks from // the target thread. - class SamplingThread : public PlatformThread::Delegate { - public: - // Samples stacks using |native_sampler|. When complete, invokes - // |completed_callback| with the collected call stack profiles. - // |completed_callback| must be callable on any thread. - SamplingThread(std::unique_ptr<NativeStackSampler> native_sampler, - const SamplingParams& params, - const CompletedCallback& completed_callback); - ~SamplingThread() override; - - // PlatformThread::Delegate: - void ThreadMain() override; - - void Stop(); - - private: - // Collects |profile| from a single burst. If the profiler was stopped - // during collection, sets |was_stopped| and provides the set of samples - // collected up to that point. - void CollectProfile(CallStackProfile* profile, TimeDelta* elapsed_time, - bool* was_stopped); - - // Collects call stack profiles from all bursts, or until the sampling is - // stopped. If stopped before complete, the last profile in - // |call_stack_profiles| may contain a partial burst. - void CollectProfiles(CallStackProfiles* profiles); - - std::unique_ptr<NativeStackSampler> native_sampler_; - const SamplingParams params_; - - // If Stop() is called, it signals this event to force the sampling to - // terminate before all the samples specified in |params_| are collected. - WaitableEvent stop_event_; - - const CompletedCallback completed_callback_; - - DISALLOW_COPY_AND_ASSIGN(SamplingThread); - }; + class SamplingThread; // Adds annotations to a Sample. static void RecordAnnotations(Sample* sample); @@ -284,11 +289,20 @@ const SamplingParams params_; - std::unique_ptr<SamplingThread> sampling_thread_; - PlatformThreadHandle sampling_thread_handle_; - const CompletedCallback completed_callback_; + // This starts "signaled", is reset when sampling begins, and is signaled + // when that sampling is complete and the callback done. + WaitableEvent profiling_inactive_; + + // Object that does the native sampling. This is created during construction + // and later passed to the sampling thread when profiling is started. + std::unique_ptr<NativeStackSampler> native_sampler_; + + // An ID uniquely identifying this collection to the sampling thread. This + // will be an internal "null" value when no collection has been started. + int collection_id_; + // Stored until it can be passed to the NativeStackSampler created in Start(). NativeStackSamplerTestDelegate* const test_delegate_;
diff --git a/base/profiler/stack_sampling_profiler_unittest.cc b/base/profiler/stack_sampling_profiler_unittest.cc index 0b300d5..8b59dff 100644 --- a/base/profiler/stack_sampling_profiler_unittest.cc +++ b/base/profiler/stack_sampling_profiler_unittest.cc
@@ -14,7 +14,6 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/ptr_util.h" -#include "base/message_loop/message_loop.h" #include "base/native_library.h" #include "base/path_service.h" #include "base/profiler/native_stack_sampler.h" @@ -23,8 +22,10 @@ #include "base/scoped_native_library.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "base/synchronization/lock.h" #include "base/synchronization/waitable_event.h" #include "base/threading/platform_thread.h" +#include "base/threading/simple_thread.h" #include "base/time/time.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" @@ -351,29 +352,75 @@ WithTargetThread(function, StackConfiguration(StackConfiguration::NORMAL)); } +struct TestProfilerInfo { + TestProfilerInfo(PlatformThreadId thread_id, + const SamplingParams& params, + NativeStackSamplerTestDelegate* delegate = nullptr) + : completed(WaitableEvent::ResetPolicy::MANUAL, + WaitableEvent::InitialState::NOT_SIGNALED), + profiler(thread_id, + params, + Bind(&SaveProfilesAndSignalEvent, + Unretained(&profiles), + Unretained(&completed)), + delegate) {} + + // The order here is important to ensure objects being referenced don't get + // destructed until after the objects referencing them. + CallStackProfiles profiles; + WaitableEvent completed; + StackSamplingProfiler profiler; + + private: + DISALLOW_COPY_AND_ASSIGN(TestProfilerInfo); +}; + +// Creates multiple profilers based on a vector of parameters. +std::vector<std::unique_ptr<TestProfilerInfo>> CreateProfilers( + PlatformThreadId target_thread_id, + const std::vector<SamplingParams>& params) { + DCHECK(!params.empty()); + + std::vector<std::unique_ptr<TestProfilerInfo>> profilers; + for (size_t i = 0; i < params.size(); ++i) { + profilers.push_back( + MakeUnique<TestProfilerInfo>(target_thread_id, params[i])); + } + + return profilers; +} + // Captures profiles as specified by |params| on the TargetThread, and returns // them in |profiles|. Waits up to |profiler_wait_time| for the profiler to // complete. void CaptureProfiles(const SamplingParams& params, TimeDelta profiler_wait_time, CallStackProfiles* profiles) { - profiles->clear(); - WithTargetThread([¶ms, profiles, profiler_wait_time](PlatformThreadId target_thread_id) { - WaitableEvent sampling_thread_completed( - WaitableEvent::ResetPolicy::MANUAL, - WaitableEvent::InitialState::NOT_SIGNALED); - const StackSamplingProfiler::CompletedCallback callback = - Bind(&SaveProfilesAndSignalEvent, Unretained(profiles), - Unretained(&sampling_thread_completed)); - StackSamplingProfiler profiler(target_thread_id, params, callback); - profiler.Start(); - sampling_thread_completed.TimedWait(profiler_wait_time); - profiler.Stop(); - sampling_thread_completed.Wait(); + TestProfilerInfo info(target_thread_id, params); + info.profiler.Start(); + info.completed.TimedWait(profiler_wait_time); + info.profiler.Stop(); + info.completed.Wait(); + + *profiles = std::move(info.profiles); }); } +// Waits for one of multiple samplings to complete. +size_t WaitForSamplingComplete( + const std::vector<std::unique_ptr<TestProfilerInfo>>& infos) { + // Map unique_ptrs to something that WaitMany can accept. + std::vector<WaitableEvent*> sampling_completed_rawptrs(infos.size()); + std::transform(infos.begin(), infos.end(), sampling_completed_rawptrs.begin(), + [](const std::unique_ptr<TestProfilerInfo>& info) { + return &info.get()->completed; + }); + // Wait for one profiler to finish. + return WaitableEvent::WaitMany(sampling_completed_rawptrs.data(), + sampling_completed_rawptrs.size()); +} + // If this executable was linked with /INCREMENTAL (the default for non-official // debug and release builds on Windows), function addresses do not correspond to // function code itself, but instead to instructions in the Incremental Link @@ -444,9 +491,9 @@ StackCopiedSignaler(WaitableEvent* stack_copied, WaitableEvent* start_stack_walk, bool wait_to_walk_stack) - : stack_copied_(stack_copied), start_stack_walk_(start_stack_walk), - wait_to_walk_stack_(wait_to_walk_stack) { - } + : stack_copied_(stack_copied), + start_stack_walk_(start_stack_walk), + wait_to_walk_stack_(wait_to_walk_stack) {} void OnPreStackWalk() override { stack_copied_->Signal(); @@ -577,6 +624,25 @@ } } +// Provide a suitable (and clean) environment for the tests below. All tests +// must use this class to ensure that proper clean-up is done and thus be +// usable in a later test. +class StackSamplingProfilerTest : public testing::Test { + public: + void SetUp() override { + // The idle-shutdown time is too long for convenient (and accurate) testing. + // That behavior is checked instead by artificially triggering it through + // the TestAPI. + StackSamplingProfiler::TestAPI::DisableIdleShutdown(); + } + + void TearDown() override { + // Be a good citizen and clean up after ourselves. This also re-enables the + // idle-shutdown behavior. + StackSamplingProfiler::TestAPI::Reset(); + } +}; + } // namespace // Checks that the basic expected information is present in a sampled call stack @@ -586,9 +652,7 @@ #else #define MAYBE_Basic DISABLED_Basic #endif -TEST(StackSamplingProfilerTest, MAYBE_Basic) { - StackSamplingProfiler::ResetAnnotationsForTesting(); - +TEST_F(StackSamplingProfilerTest, MAYBE_Basic) { SamplingParams params; params.sampling_interval = TimeDelta::FromMilliseconds(0); params.samples_per_burst = 1; @@ -631,9 +695,7 @@ #else #define MAYBE_Annotations DISABLED_Annotations #endif -TEST(StackSamplingProfilerTest, MAYBE_Annotations) { - StackSamplingProfiler::ResetAnnotationsForTesting(); - +TEST_F(StackSamplingProfilerTest, MAYBE_Annotations) { SamplingParams params; params.sampling_interval = TimeDelta::FromMilliseconds(0); params.samples_per_burst = 1; @@ -667,7 +729,7 @@ #else #define MAYBE_Alloca DISABLED_Alloca #endif -TEST(StackSamplingProfilerTest, MAYBE_Alloca) { +TEST_F(StackSamplingProfilerTest, MAYBE_Alloca) { SamplingParams params; params.sampling_interval = TimeDelta::FromMilliseconds(0); params.samples_per_burst = 1; @@ -720,35 +782,6 @@ << FormatSampleForDiagnosticOutput(sample, profile.modules); } -// Checks that the fire-and-forget interface works. -#if defined(STACK_SAMPLING_PROFILER_SUPPORTED) -#define MAYBE_StartAndRunAsync StartAndRunAsync -#else -#define MAYBE_StartAndRunAsync DISABLED_StartAndRunAsync -#endif -TEST(StackSamplingProfilerTest, MAYBE_StartAndRunAsync) { - // StartAndRunAsync requires the caller to have a message loop. - MessageLoop message_loop; - - SamplingParams params; - params.samples_per_burst = 1; - - CallStackProfiles profiles; - WithTargetThread([¶ms, &profiles](PlatformThreadId target_thread_id) { - WaitableEvent sampling_thread_completed( - WaitableEvent::ResetPolicy::AUTOMATIC, - WaitableEvent::InitialState::NOT_SIGNALED); - const StackSamplingProfiler::CompletedCallback callback = - Bind(&SaveProfilesAndSignalEvent, Unretained(&profiles), - Unretained(&sampling_thread_completed)); - StackSamplingProfiler::StartAndRunAsync(target_thread_id, params, callback); - RunLoop().RunUntilIdle(); - sampling_thread_completed.Wait(); - }); - - ASSERT_EQ(1u, profiles.size()); -} - // Checks that the expected number of profiles and samples are present in the // call stack profiles produced. #if defined(STACK_SAMPLING_PROFILER_SUPPORTED) @@ -756,7 +789,7 @@ #else #define MAYBE_MultipleProfilesAndSamples DISABLED_MultipleProfilesAndSamples #endif -TEST(StackSamplingProfilerTest, MAYBE_MultipleProfilesAndSamples) { +TEST_F(StackSamplingProfilerTest, MAYBE_MultipleProfilesAndSamples) { SamplingParams params; params.burst_interval = params.sampling_interval = TimeDelta::FromMilliseconds(0); @@ -771,6 +804,111 @@ EXPECT_EQ(3u, profiles[1].samples.size()); } +// Checks that a profiler can stop/destruct without ever having started. +#if defined(STACK_SAMPLING_PROFILER_SUPPORTED) +#define MAYBE_StopWithoutStarting StopWithoutStarting +#else +#define MAYBE_StopWithoutStarting DISABLED_StopWithoutStarting +#endif +TEST_F(StackSamplingProfilerTest, MAYBE_StopWithoutStarting) { + WithTargetThread([](PlatformThreadId target_thread_id) { + SamplingParams params; + params.sampling_interval = TimeDelta::FromMilliseconds(0); + params.samples_per_burst = 1; + + CallStackProfiles profiles; + WaitableEvent sampling_completed(WaitableEvent::ResetPolicy::MANUAL, + WaitableEvent::InitialState::NOT_SIGNALED); + const StackSamplingProfiler::CompletedCallback callback = + Bind(&SaveProfilesAndSignalEvent, Unretained(&profiles), + Unretained(&sampling_completed)); + StackSamplingProfiler profiler(target_thread_id, params, callback); + + profiler.Stop(); // Constructed but never started. + EXPECT_FALSE(sampling_completed.IsSignaled()); + }); +} + +// Checks that its okay to stop a profiler before it finishes even when the +// sampling thread continues to run. +#if defined(STACK_SAMPLING_PROFILER_SUPPORTED) +#define MAYBE_StopSafely StopSafely +#else +#define MAYBE_StopSafely DISABLED_StopSafely +#endif +TEST_F(StackSamplingProfilerTest, MAYBE_StopSafely) { + // Test delegate that counts samples. + class SampleRecordedCounter : public NativeStackSamplerTestDelegate { + public: + SampleRecordedCounter() {} + + void OnPreStackWalk() override { + AutoLock lock(lock_); + ++count_; + } + + size_t Get() { + AutoLock lock(lock_); + return count_; + } + + private: + Lock lock_; + size_t count_ = 0; + }; + + WithTargetThread([](PlatformThreadId target_thread_id) { + SamplingParams params[2]; + + // Providing an initial delay makes it more likely that both will be + // scheduled before either starts to run. Once started, samples will + // run ordered by their scheduled, interleaved times regardless of + // whatever interval the thread wakes up. + params[0].initial_delay = TimeDelta::FromMilliseconds(10); + params[0].sampling_interval = TimeDelta::FromMilliseconds(1); + params[0].samples_per_burst = 100000; + + params[1].initial_delay = TimeDelta::FromMilliseconds(10); + params[1].sampling_interval = TimeDelta::FromMilliseconds(1); + params[1].samples_per_burst = 100000; + + SampleRecordedCounter samples_recorded[arraysize(params)]; + + TestProfilerInfo profiler_info0(target_thread_id, params[0], + &samples_recorded[0]); + TestProfilerInfo profiler_info1(target_thread_id, params[1], + &samples_recorded[1]); + + profiler_info0.profiler.Start(); + profiler_info1.profiler.Start(); + + // Wait for both to start accumulating samples. Using a WaitableEvent is + // possible but gets complicated later on because there's no way of knowing + // if 0 or 1 additional sample will be taken after Stop() and thus no way + // of knowing how many Wait() calls to make on it. + while (samples_recorded[0].Get() == 0 || samples_recorded[1].Get() == 0) + PlatformThread::Sleep(TimeDelta::FromMilliseconds(1)); + + // Ensure that the first sampler can be safely stopped while the second + // continues to run. The stopped first profiler will still have a + // PerformCollectionTask pending that will do nothing when executed because + // the collection will have been removed by Stop(). + profiler_info0.profiler.Stop(); + profiler_info0.completed.Wait(); + size_t count0 = samples_recorded[0].Get(); + size_t count1 = samples_recorded[1].Get(); + + // Waiting for the second sampler to collect a couple samples ensures that + // the pending PerformCollectionTask for the first has executed because + // tasks are always ordered by their next scheduled time. + while (samples_recorded[1].Get() < count1 + 2) + PlatformThread::Sleep(TimeDelta::FromMilliseconds(1)); + + // Ensure that the first profiler didn't do anything since it was stopped. + EXPECT_EQ(count0, samples_recorded[0].Get()); + }); +} + // Checks that no call stack profiles are captured if the profiling is stopped // during the initial delay. #if defined(STACK_SAMPLING_PROFILER_SUPPORTED) @@ -778,7 +916,7 @@ #else #define MAYBE_StopDuringInitialDelay DISABLED_StopDuringInitialDelay #endif -TEST(StackSamplingProfilerTest, MAYBE_StopDuringInitialDelay) { +TEST_F(StackSamplingProfilerTest, MAYBE_StopDuringInitialDelay) { SamplingParams params; params.initial_delay = TimeDelta::FromSeconds(60); @@ -795,7 +933,7 @@ #else #define MAYBE_StopDuringInterBurstInterval DISABLED_StopDuringInterBurstInterval #endif -TEST(StackSamplingProfilerTest, MAYBE_StopDuringInterBurstInterval) { +TEST_F(StackSamplingProfilerTest, MAYBE_StopDuringInterBurstInterval) { SamplingParams params; params.sampling_interval = TimeDelta::FromMilliseconds(0); params.burst_interval = TimeDelta::FromSeconds(60); @@ -809,23 +947,51 @@ EXPECT_EQ(1u, profiles[0].samples.size()); } -// Checks that incomplete call stack profiles are captured. +// Checks that tasks can be stopped before completion and incomplete call stack +// profiles are captured. #if defined(STACK_SAMPLING_PROFILER_SUPPORTED) #define MAYBE_StopDuringInterSampleInterval StopDuringInterSampleInterval #else #define MAYBE_StopDuringInterSampleInterval \ DISABLED_StopDuringInterSampleInterval #endif -TEST(StackSamplingProfilerTest, MAYBE_StopDuringInterSampleInterval) { - SamplingParams params; - params.sampling_interval = TimeDelta::FromSeconds(60); - params.samples_per_burst = 2; +TEST_F(StackSamplingProfilerTest, MAYBE_StopDuringInterSampleInterval) { + // Test delegate that counts samples. + class SampleRecordedEvent : public NativeStackSamplerTestDelegate { + public: + SampleRecordedEvent() + : sample_recorded_(WaitableEvent::ResetPolicy::MANUAL, + WaitableEvent::InitialState::NOT_SIGNALED) {} - std::vector<CallStackProfile> profiles; - CaptureProfiles(params, TimeDelta::FromMilliseconds(50), &profiles); + void OnPreStackWalk() override { sample_recorded_.Signal(); } - ASSERT_EQ(1u, profiles.size()); - EXPECT_EQ(1u, profiles[0].samples.size()); + void WaitForSample() { sample_recorded_.Wait(); } + + private: + WaitableEvent sample_recorded_; + }; + + WithTargetThread([](PlatformThreadId target_thread_id) { + SamplingParams params; + + params.sampling_interval = AVeryLongTimeDelta(); + params.samples_per_burst = 2; + + SampleRecordedEvent samples_recorded; + TestProfilerInfo profiler_info(target_thread_id, params, &samples_recorded); + + profiler_info.profiler.Start(); + + // Wait for profiler to start accumulating samples. + samples_recorded.WaitForSample(); + + // Ensure that it can stop safely. + profiler_info.profiler.Stop(); + profiler_info.completed.Wait(); + + ASSERT_EQ(1u, profiler_info.profiles.size()); + EXPECT_EQ(1u, profiler_info.profiles[0].samples.size()); + }); } // Checks that we can destroy the profiler while profiling. @@ -835,7 +1001,7 @@ #define MAYBE_DestroyProfilerWhileProfiling \ DISABLED_DestroyProfilerWhileProfiling #endif -TEST(StackSamplingProfilerTest, MAYBE_DestroyProfilerWhileProfiling) { +TEST_F(StackSamplingProfilerTest, MAYBE_DestroyProfilerWhileProfiling) { SamplingParams params; params.sampling_interval = TimeDelta::FromMilliseconds(10); @@ -859,7 +1025,42 @@ #else #define MAYBE_CanRunMultipleTimes DISABLED_CanRunMultipleTimes #endif -TEST(StackSamplingProfilerTest, MAYBE_CanRunMultipleTimes) { +TEST_F(StackSamplingProfilerTest, MAYBE_CanRunMultipleTimes) { + WithTargetThread([](PlatformThreadId target_thread_id) { + SamplingParams params; + params.sampling_interval = TimeDelta::FromMilliseconds(0); + params.samples_per_burst = 1; + + CallStackProfiles profiles; + WaitableEvent sampling_completed(WaitableEvent::ResetPolicy::MANUAL, + WaitableEvent::InitialState::NOT_SIGNALED); + const StackSamplingProfiler::CompletedCallback callback = + Bind(&SaveProfilesAndSignalEvent, Unretained(&profiles), + Unretained(&sampling_completed)); + StackSamplingProfiler profiler(target_thread_id, params, callback); + + // Just start and stop to execute code paths. + profiler.Start(); + profiler.Stop(); + sampling_completed.Wait(); + + // Ensure a second request will run and not block. + sampling_completed.Reset(); + profiles.clear(); + profiler.Start(); + sampling_completed.Wait(); + profiler.Stop(); + ASSERT_EQ(1u, profiles.size()); + }); +} + +// Checks that the different profilers may be run. +#if defined(STACK_SAMPLING_PROFILER_SUPPORTED) +#define MAYBE_CanRunMultipleProfilers CanRunMultipleProfilers +#else +#define MAYBE_CanRunMultipleProfilers DISABLED_CanRunMultipleProfilers +#endif +TEST_F(StackSamplingProfilerTest, MAYBE_CanRunMultipleProfilers) { SamplingParams params; params.sampling_interval = TimeDelta::FromMilliseconds(0); params.samples_per_burst = 1; @@ -873,60 +1074,282 @@ ASSERT_EQ(1u, profiles.size()); } -// Checks that requests to start profiling while another profile is taking place -// are ignored. +// Checks that a sampler can be started while another is running. #if defined(STACK_SAMPLING_PROFILER_SUPPORTED) -#define MAYBE_ConcurrentProfiling ConcurrentProfiling +#define MAYBE_MultipleStart MultipleStart #else -#define MAYBE_ConcurrentProfiling DISABLED_ConcurrentProfiling +#define MAYBE_MultipleStart DISABLED_MultipleStart #endif -TEST(StackSamplingProfilerTest, MAYBE_ConcurrentProfiling) { +TEST_F(StackSamplingProfilerTest, MAYBE_MultipleStart) { WithTargetThread([](PlatformThreadId target_thread_id) { - SamplingParams params[2]; - params[0].initial_delay = TimeDelta::FromMilliseconds(10); - params[0].sampling_interval = TimeDelta::FromMilliseconds(0); + std::vector<SamplingParams> params(2); + + params[0].initial_delay = AVeryLongTimeDelta(); params[0].samples_per_burst = 1; - params[1].sampling_interval = TimeDelta::FromMilliseconds(0); + params[1].sampling_interval = TimeDelta::FromMilliseconds(1); params[1].samples_per_burst = 1; - CallStackProfiles profiles[2]; - std::vector<std::unique_ptr<WaitableEvent>> sampling_completed(2); - std::vector<std::unique_ptr<StackSamplingProfiler>> profiler(2); - for (int i = 0; i < 2; ++i) { - sampling_completed[i] = - MakeUnique<WaitableEvent>(WaitableEvent::ResetPolicy::AUTOMATIC, - WaitableEvent::InitialState::NOT_SIGNALED); - const StackSamplingProfiler::CompletedCallback callback = - Bind(&SaveProfilesAndSignalEvent, Unretained(&profiles[i]), - Unretained(sampling_completed[i].get())); - profiler[i] = MakeUnique<StackSamplingProfiler>(target_thread_id, - params[i], callback); - } + std::vector<std::unique_ptr<TestProfilerInfo>> profiler_infos = + CreateProfilers(target_thread_id, params); - profiler[0]->Start(); - profiler[1]->Start(); + profiler_infos[0]->profiler.Start(); + profiler_infos[1]->profiler.Start(); + profiler_infos[1]->completed.Wait(); + EXPECT_EQ(1u, profiler_infos[1]->profiles.size()); + }); +} - std::vector<WaitableEvent*> sampling_completed_rawptrs( - sampling_completed.size()); - std::transform( - sampling_completed.begin(), sampling_completed.end(), - sampling_completed_rawptrs.begin(), - [](const std::unique_ptr<WaitableEvent>& elem) { return elem.get(); }); +// Checks that the sampling thread can shut down. +#if defined(STACK_SAMPLING_PROFILER_SUPPORTED) +#define MAYBE_SamplerIdleShutdown SamplerIdleShutdown +#else +#define MAYBE_SamplerIdleShutdown DISABLED_SamplerIdleShutdown +#endif +TEST_F(StackSamplingProfilerTest, MAYBE_SamplerIdleShutdown) { + SamplingParams params; + params.sampling_interval = TimeDelta::FromMilliseconds(0); + params.samples_per_burst = 1; + + std::vector<CallStackProfile> profiles; + CaptureProfiles(params, AVeryLongTimeDelta(), &profiles); + ASSERT_EQ(1u, profiles.size()); + + // Capture thread should still be running at this point. + ASSERT_TRUE(StackSamplingProfiler::TestAPI::IsSamplingThreadRunning()); + + // Initiate an "idle" shutdown and ensure it happens. Idle-shutdown was + // disabled by the test fixture so the test will fail due to a timeout if + // it does not exit. + StackSamplingProfiler::TestAPI::PerformSamplingThreadIdleShutdown(false); + + // While the shutdown has been initiated, the actual exit of the thread still + // happens asynchronously. Watch until the thread actually exits. This test + // will time-out in the case of failure. + while (StackSamplingProfiler::TestAPI::IsSamplingThreadRunning()) + PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(1)); +} + +// Checks that additional requests will restart a stopped profiler. +#if defined(STACK_SAMPLING_PROFILER_SUPPORTED) +#define MAYBE_WillRestartSamplerAfterIdleShutdown \ + WillRestartSamplerAfterIdleShutdown +#else +#define MAYBE_WillRestartSamplerAfterIdleShutdown \ + DISABLED_WillRestartSamplerAfterIdleShutdown +#endif +TEST_F(StackSamplingProfilerTest, MAYBE_WillRestartSamplerAfterIdleShutdown) { + SamplingParams params; + params.sampling_interval = TimeDelta::FromMilliseconds(0); + params.samples_per_burst = 1; + + std::vector<CallStackProfile> profiles; + CaptureProfiles(params, AVeryLongTimeDelta(), &profiles); + ASSERT_EQ(1u, profiles.size()); + + // Capture thread should still be running at this point. + ASSERT_TRUE(StackSamplingProfiler::TestAPI::IsSamplingThreadRunning()); + + // Post a ShutdownTask on the sampling thread which, when executed, will + // mark the thread as EXITING and begin shut down of the thread. + StackSamplingProfiler::TestAPI::PerformSamplingThreadIdleShutdown(false); + + // Ensure another capture will start the sampling thread and run. + profiles.clear(); + CaptureProfiles(params, AVeryLongTimeDelta(), &profiles); + ASSERT_EQ(1u, profiles.size()); + EXPECT_TRUE(StackSamplingProfiler::TestAPI::IsSamplingThreadRunning()); +} + +// Checks that it's safe to stop a task after it's completed and the sampling +// thread has shut-down for being idle. +#if defined(STACK_SAMPLING_PROFILER_SUPPORTED) +#define MAYBE_StopAfterIdleShutdown StopAfterIdleShutdown +#else +#define MAYBE_StopAfterIdleShutdown DISABLED_StopAfterIdleShutdown +#endif +TEST_F(StackSamplingProfilerTest, MAYBE_StopAfterIdleShutdown) { + WithTargetThread([](PlatformThreadId target_thread_id) { + SamplingParams params; + + params.sampling_interval = TimeDelta::FromMilliseconds(1); + params.samples_per_burst = 1; + + TestProfilerInfo profiler_info(target_thread_id, params); + + profiler_info.profiler.Start(); + profiler_info.completed.Wait(); + + // Capture thread should still be running at this point. + ASSERT_TRUE(StackSamplingProfiler::TestAPI::IsSamplingThreadRunning()); + + // Perform an idle shutdown. + StackSamplingProfiler::TestAPI::PerformSamplingThreadIdleShutdown(false); + + // Stop should be safe though its impossible to know at this moment if the + // sampling thread has completely exited or will just "stop soon". + profiler_info.profiler.Stop(); + }); +} + +// Checks that profilers can run both before and after the sampling thread has +// started. +#if defined(STACK_SAMPLING_PROFILER_SUPPORTED) +#define MAYBE_ProfileBeforeAndAfterSamplingThreadRunning \ + ProfileBeforeAndAfterSamplingThreadRunning +#else +#define MAYBE_ProfileBeforeAndAfterSamplingThreadRunning \ + DISABLED_ProfileBeforeAndAfterSamplingThreadRunning +#endif +TEST_F(StackSamplingProfilerTest, + MAYBE_ProfileBeforeAndAfterSamplingThreadRunning) { + WithTargetThread([](PlatformThreadId target_thread_id) { + std::vector<SamplingParams> params(2); + + params[0].initial_delay = AVeryLongTimeDelta(); + params[0].sampling_interval = TimeDelta::FromMilliseconds(1); + params[0].samples_per_burst = 1; + + params[1].initial_delay = TimeDelta::FromMilliseconds(0); + params[1].sampling_interval = TimeDelta::FromMilliseconds(1); + params[1].samples_per_burst = 1; + + std::vector<std::unique_ptr<TestProfilerInfo>> profiler_infos = + CreateProfilers(target_thread_id, params); + + // First profiler is started when there has never been a sampling thread. + EXPECT_FALSE(StackSamplingProfiler::TestAPI::IsSamplingThreadRunning()); + profiler_infos[0]->profiler.Start(); + // Second profiler is started when sampling thread is already running. + EXPECT_TRUE(StackSamplingProfiler::TestAPI::IsSamplingThreadRunning()); + profiler_infos[1]->profiler.Start(); + + // Only the second profiler should finish before test times out. + size_t completed_profiler = WaitForSamplingComplete(profiler_infos); + EXPECT_EQ(1U, completed_profiler); + }); +} + +// Checks that an idle-shutdown task will abort if a new profiler starts +// between when it was posted and when it runs. +#if defined(STACK_SAMPLING_PROFILER_SUPPORTED) +#define MAYBE_IdleShutdownAbort IdleShutdownAbort +#else +#define MAYBE_IdleShutdownAbort DISABLED_IdleShutdownAbort +#endif +TEST_F(StackSamplingProfilerTest, MAYBE_IdleShutdownAbort) { + WithTargetThread([](PlatformThreadId target_thread_id) { + SamplingParams params; + + params.sampling_interval = TimeDelta::FromMilliseconds(1); + params.samples_per_burst = 1; + + TestProfilerInfo profiler_info(target_thread_id, params); + + profiler_info.profiler.Start(); + profiler_info.completed.Wait(); + EXPECT_EQ(1u, profiler_info.profiles.size()); + + // Perform an idle shutdown but simulate that a new capture is started + // before it can actually run. + StackSamplingProfiler::TestAPI::PerformSamplingThreadIdleShutdown(true); + + // Though the shutdown-task has been executed, any actual exit of the + // thread is asynchronous so there is no way to detect that *didn't* exit + // except to wait a reasonable amount of time and then check. Since the + // thread was just running ("perform" blocked until it was), it should + // finish almost immediately and without any waiting for tasks or events. + PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(200)); + EXPECT_TRUE(StackSamplingProfiler::TestAPI::IsSamplingThreadRunning()); + + // Ensure that it's still possible to run another sampler. + TestProfilerInfo another_info(target_thread_id, params); + another_info.profiler.Start(); + another_info.completed.Wait(); + EXPECT_EQ(1u, another_info.profiles.size()); + }); +} + +// Checks that synchronized multiple sampling requests execute in parallel. +#if defined(STACK_SAMPLING_PROFILER_SUPPORTED) +#define MAYBE_ConcurrentProfiling_InSync ConcurrentProfiling_InSync +#else +#define MAYBE_ConcurrentProfiling_InSync DISABLED_ConcurrentProfiling_InSync +#endif +TEST_F(StackSamplingProfilerTest, MAYBE_ConcurrentProfiling_InSync) { + WithTargetThread([](PlatformThreadId target_thread_id) { + std::vector<SamplingParams> params(2); + + // Providing an initial delay makes it more likely that both will be + // scheduled before either starts to run. Once started, samples will + // run ordered by their scheduled, interleaved times regardless of + // whatever interval the thread wakes up. Thus, total execution time + // will be 10ms (delay) + 10x1ms (sampling) + 1/2 timer minimum interval. + params[0].initial_delay = TimeDelta::FromMilliseconds(10); + params[0].sampling_interval = TimeDelta::FromMilliseconds(1); + params[0].samples_per_burst = 9; + + params[1].initial_delay = TimeDelta::FromMilliseconds(11); + params[1].sampling_interval = TimeDelta::FromMilliseconds(1); + params[1].samples_per_burst = 8; + + std::vector<std::unique_ptr<TestProfilerInfo>> profiler_infos = + CreateProfilers(target_thread_id, params); + + profiler_infos[0]->profiler.Start(); + profiler_infos[1]->profiler.Start(); + // Wait for one profiler to finish. - size_t completed_profiler = - WaitableEvent::WaitMany(sampling_completed_rawptrs.data(), 2); - EXPECT_EQ(1u, profiles[completed_profiler].size()); + size_t completed_profiler = WaitForSamplingComplete(profiler_infos); + ASSERT_EQ(1u, profiler_infos[completed_profiler]->profiles.size()); size_t other_profiler = 1 - completed_profiler; - // Give the other profiler a chance to run and observe that it hasn't. - EXPECT_FALSE(sampling_completed[other_profiler]->TimedWait( - TimeDelta::FromMilliseconds(25))); + // Wait for the other profiler to finish. + profiler_infos[other_profiler]->completed.Wait(); + ASSERT_EQ(1u, profiler_infos[other_profiler]->profiles.size()); - // Start the other profiler again and it should run. - profiler[other_profiler]->Start(); - sampling_completed[other_profiler]->Wait(); - EXPECT_EQ(1u, profiles[other_profiler].size()); + // Ensure each got the correct number of samples. + EXPECT_EQ(9u, profiler_infos[0]->profiles[0].samples.size()); + EXPECT_EQ(8u, profiler_infos[1]->profiles[0].samples.size()); + }); +} + +// Checks that several mixed sampling requests execute in parallel. +#if defined(STACK_SAMPLING_PROFILER_SUPPORTED) +#define MAYBE_ConcurrentProfiling_Mixed ConcurrentProfiling_Mixed +#else +#define MAYBE_ConcurrentProfiling_Mixed DISABLED_ConcurrentProfiling_Mixed +#endif +TEST_F(StackSamplingProfilerTest, MAYBE_ConcurrentProfiling_Mixed) { + WithTargetThread([](PlatformThreadId target_thread_id) { + std::vector<SamplingParams> params(3); + + params[0].initial_delay = TimeDelta::FromMilliseconds(8); + params[0].sampling_interval = TimeDelta::FromMilliseconds(4); + params[0].samples_per_burst = 10; + + params[1].initial_delay = TimeDelta::FromMilliseconds(9); + params[1].sampling_interval = TimeDelta::FromMilliseconds(3); + params[1].samples_per_burst = 10; + + params[2].initial_delay = TimeDelta::FromMilliseconds(10); + params[2].sampling_interval = TimeDelta::FromMilliseconds(2); + params[2].samples_per_burst = 10; + + std::vector<std::unique_ptr<TestProfilerInfo>> profiler_infos = + CreateProfilers(target_thread_id, params); + + for (size_t i = 0; i < profiler_infos.size(); ++i) + profiler_infos[i]->profiler.Start(); + + // Wait for one profiler to finish. + size_t completed_profiler = WaitForSamplingComplete(profiler_infos); + EXPECT_EQ(1u, profiler_infos[completed_profiler]->profiles.size()); + // Stop and destroy all profilers, always in the same order. Don't crash. + for (size_t i = 0; i < profiler_infos.size(); ++i) + profiler_infos[i]->profiler.Stop(); + for (size_t i = 0; i < profiler_infos.size(); ++i) + profiler_infos[i].reset(); }); } @@ -937,7 +1360,7 @@ #else #define MAYBE_OtherLibrary DISABLED_OtherLibrary #endif -TEST(StackSamplingProfilerTest, MAYBE_OtherLibrary) { +TEST_F(StackSamplingProfilerTest, MAYBE_OtherLibrary) { SamplingParams params; params.sampling_interval = TimeDelta::FromMilliseconds(0); params.samples_per_burst = 1; @@ -1008,7 +1431,7 @@ #else #define MAYBE_UnloadingLibrary DISABLED_UnloadingLibrary #endif -TEST(StackSamplingProfilerTest, MAYBE_UnloadingLibrary) { +TEST_F(StackSamplingProfilerTest, MAYBE_UnloadingLibrary) { TestLibraryUnload(false); } @@ -1019,8 +1442,153 @@ #else #define MAYBE_UnloadedLibrary DISABLED_UnloadedLibrary #endif -TEST(StackSamplingProfilerTest, MAYBE_UnloadedLibrary) { +TEST_F(StackSamplingProfilerTest, MAYBE_UnloadedLibrary) { TestLibraryUnload(true); } +// Checks that different threads can be sampled in parallel. +#if defined(STACK_SAMPLING_PROFILER_SUPPORTED) +#define MAYBE_MultipleSampledThreads MultipleSampledThreads +#else +#define MAYBE_MultipleSampledThreads DISABLED_MultipleSampledThreads +#endif +TEST_F(StackSamplingProfilerTest, MAYBE_MultipleSampledThreads) { + // Create target threads. The extra parethesis around the StackConfiguration + // call are to avoid the most-vexing-parse problem. + TargetThread target_thread1((StackConfiguration(StackConfiguration::NORMAL))); + TargetThread target_thread2((StackConfiguration(StackConfiguration::NORMAL))); + PlatformThreadHandle target_thread_handle1, target_thread_handle2; + EXPECT_TRUE( + PlatformThread::Create(0, &target_thread1, &target_thread_handle1)); + EXPECT_TRUE( + PlatformThread::Create(0, &target_thread2, &target_thread_handle2)); + target_thread1.WaitForThreadStart(); + target_thread2.WaitForThreadStart(); + + // Providing an initial delay makes it more likely that both will be + // scheduled before either starts to run. Once started, samples will + // run ordered by their scheduled, interleaved times regardless of + // whatever interval the thread wakes up. + SamplingParams params1, params2; + params1.initial_delay = TimeDelta::FromMilliseconds(10); + params1.sampling_interval = TimeDelta::FromMilliseconds(1); + params1.samples_per_burst = 9; + params2.initial_delay = TimeDelta::FromMilliseconds(10); + params2.sampling_interval = TimeDelta::FromMilliseconds(1); + params2.samples_per_burst = 8; + + std::vector<CallStackProfile> profiles1, profiles2; + + WaitableEvent sampling_thread_completed1( + WaitableEvent::ResetPolicy::MANUAL, + WaitableEvent::InitialState::NOT_SIGNALED); + const StackSamplingProfiler::CompletedCallback callback1 = + Bind(&SaveProfilesAndSignalEvent, Unretained(&profiles1), + Unretained(&sampling_thread_completed1)); + StackSamplingProfiler profiler1(target_thread1.id(), params1, callback1); + + WaitableEvent sampling_thread_completed2( + WaitableEvent::ResetPolicy::MANUAL, + WaitableEvent::InitialState::NOT_SIGNALED); + const StackSamplingProfiler::CompletedCallback callback2 = + Bind(&SaveProfilesAndSignalEvent, Unretained(&profiles2), + Unretained(&sampling_thread_completed2)); + StackSamplingProfiler profiler2(target_thread2.id(), params2, callback2); + + // Finally the real work. + profiler1.Start(); + profiler2.Start(); + sampling_thread_completed1.Wait(); + sampling_thread_completed2.Wait(); + ASSERT_EQ(1u, profiles1.size()); + EXPECT_EQ(9u, profiles1[0].samples.size()); + ASSERT_EQ(1u, profiles2.size()); + EXPECT_EQ(8u, profiles2[0].samples.size()); + + target_thread1.SignalThreadToFinish(); + target_thread2.SignalThreadToFinish(); + PlatformThread::Join(target_thread_handle1); + PlatformThread::Join(target_thread_handle2); +} + +// A simple thread that runs a profiler on another thread. +class ProfilerThread : public SimpleThread { + public: + ProfilerThread(const std::string& name, + PlatformThreadId thread_id, + const SamplingParams& params) + : SimpleThread(name, Options()), + run_(WaitableEvent::ResetPolicy::MANUAL, + WaitableEvent::InitialState::NOT_SIGNALED), + completed_(WaitableEvent::ResetPolicy::MANUAL, + WaitableEvent::InitialState::NOT_SIGNALED), + profiler_(thread_id, + params, + Bind(&SaveProfilesAndSignalEvent, + Unretained(&profiles_), + Unretained(&completed_))) {} + + void Run() override { + run_.Wait(); + profiler_.Start(); + } + + void Go() { run_.Signal(); } + + void Wait() { completed_.Wait(); } + + CallStackProfiles& profiles() { return profiles_; } + + private: + WaitableEvent run_; + + CallStackProfiles profiles_; + WaitableEvent completed_; + StackSamplingProfiler profiler_; +}; + +// Checks that different threads can run samplers in parallel. +#if defined(STACK_SAMPLING_PROFILER_SUPPORTED) +#define MAYBE_MultipleProfilerThreads MultipleProfilerThreads +#else +#define MAYBE_MultipleProfilerThreads DISABLED_MultipleProfilerThreads +#endif +TEST_F(StackSamplingProfilerTest, MAYBE_MultipleProfilerThreads) { + WithTargetThread([](PlatformThreadId target_thread_id) { + // Providing an initial delay makes it more likely that both will be + // scheduled before either starts to run. Once started, samples will + // run ordered by their scheduled, interleaved times regardless of + // whatever interval the thread wakes up. + SamplingParams params1, params2; + params1.initial_delay = TimeDelta::FromMilliseconds(10); + params1.sampling_interval = TimeDelta::FromMilliseconds(1); + params1.samples_per_burst = 9; + params2.initial_delay = TimeDelta::FromMilliseconds(10); + params2.sampling_interval = TimeDelta::FromMilliseconds(1); + params2.samples_per_burst = 8; + + // Start the profiler threads and give them a moment to get going. + ProfilerThread profiler_thread1("profiler1", target_thread_id, params1); + ProfilerThread profiler_thread2("profiler2", target_thread_id, params2); + profiler_thread1.Start(); + profiler_thread2.Start(); + PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(10)); + + // This will (approximately) synchronize the two threads. + profiler_thread1.Go(); + profiler_thread2.Go(); + + // Wait for them both to finish and validate collection. + profiler_thread1.Wait(); + profiler_thread2.Wait(); + ASSERT_EQ(1u, profiler_thread1.profiles().size()); + EXPECT_EQ(9u, profiler_thread1.profiles()[0].samples.size()); + ASSERT_EQ(1u, profiler_thread2.profiles().size()); + EXPECT_EQ(8u, profiler_thread2.profiles()[0].samples.size()); + + profiler_thread1.Join(); + profiler_thread2.Join(); + }); +} + } // namespace base
diff --git a/base/task_scheduler/scheduler_single_thread_task_runner_manager.cc b/base/task_scheduler/scheduler_single_thread_task_runner_manager.cc index e2ff1ef..721e1daf 100644 --- a/base/task_scheduler/scheduler_single_thread_task_runner_manager.cc +++ b/base/task_scheduler/scheduler_single_thread_task_runner_manager.cc
@@ -313,18 +313,9 @@ }; SchedulerSingleThreadTaskRunnerManager::SchedulerSingleThreadTaskRunnerManager( - const std::vector<SchedulerWorkerPoolParams>& worker_pool_params_vector, - const TaskScheduler::WorkerPoolIndexForTraitsCallback& - worker_pool_index_for_traits_callback, TaskTracker* task_tracker, DelayedTaskManager* delayed_task_manager) - : worker_pool_params_vector_(worker_pool_params_vector), - worker_pool_index_for_traits_callback_( - worker_pool_index_for_traits_callback), - task_tracker_(task_tracker), - delayed_task_manager_(delayed_task_manager) { - DCHECK_GT(worker_pool_params_vector_.size(), 0U); - DCHECK(worker_pool_index_for_traits_callback_); + : task_tracker_(task_tracker), delayed_task_manager_(delayed_task_manager) { DCHECK(task_tracker_); DCHECK(delayed_task_manager_); } @@ -358,17 +349,21 @@ scoped_refptr<SingleThreadTaskRunner> SchedulerSingleThreadTaskRunnerManager::CreateSingleThreadTaskRunnerWithTraits( + const std::string& name, + ThreadPriority priority_hint, const TaskTraits& traits) { return CreateSingleThreadTaskRunnerWithDelegate<SchedulerWorkerDelegate>( - traits); + name, priority_hint, traits); } #if defined(OS_WIN) scoped_refptr<SingleThreadTaskRunner> SchedulerSingleThreadTaskRunnerManager::CreateCOMSTATaskRunnerWithTraits( + const std::string& name, + ThreadPriority priority_hint, const TaskTraits& traits) { return CreateSingleThreadTaskRunnerWithDelegate<SchedulerWorkerCOMDelegate>( - traits); + name, priority_hint, traits); } #endif // defined(OS_WIN) @@ -392,32 +387,29 @@ template <typename DelegateType> scoped_refptr<SingleThreadTaskRunner> SchedulerSingleThreadTaskRunnerManager:: - CreateSingleThreadTaskRunnerWithDelegate(const TaskTraits& traits) { - size_t index = worker_pool_index_for_traits_callback_.Run(traits); - DCHECK_LT(index, worker_pool_params_vector_.size()); + CreateSingleThreadTaskRunnerWithDelegate(const std::string& name, + ThreadPriority priority_hint, + const TaskTraits& traits) { return new SchedulerSingleThreadTaskRunner( this, traits, - CreateAndRegisterSchedulerWorker<DelegateType>( - worker_pool_params_vector_[index])); + CreateAndRegisterSchedulerWorker<DelegateType>(name, priority_hint)); } template <> std::unique_ptr<SchedulerWorkerDelegate> SchedulerSingleThreadTaskRunnerManager::CreateSchedulerWorkerDelegate< - SchedulerWorkerDelegate>(const SchedulerWorkerPoolParams& params, int id) { - return MakeUnique<SchedulerWorkerDelegate>(StringPrintf( - "TaskSchedulerSingleThreadWorker%d%s", id, params.name().c_str())); + SchedulerWorkerDelegate>(const std::string& name, int id) { + return MakeUnique<SchedulerWorkerDelegate>( + StringPrintf("TaskSchedulerSingleThread%s%d", name.c_str(), id)); } #if defined(OS_WIN) template <> std::unique_ptr<SchedulerWorkerDelegate> SchedulerSingleThreadTaskRunnerManager::CreateSchedulerWorkerDelegate< - SchedulerWorkerCOMDelegate>(const SchedulerWorkerPoolParams& params, - int id) { + SchedulerWorkerCOMDelegate>(const std::string& name, int id) { return MakeUnique<SchedulerWorkerCOMDelegate>( - StringPrintf("TaskSchedulerSingleThreadWorker%d%sCOMSTA", id, - params.name().c_str()), + StringPrintf("TaskSchedulerSingleThreadCOMSTA%s%d", name.c_str(), id), task_tracker_); } #endif // defined(OS_WIN) @@ -425,7 +417,8 @@ template <typename DelegateType> SchedulerWorker* SchedulerSingleThreadTaskRunnerManager::CreateAndRegisterSchedulerWorker( - const SchedulerWorkerPoolParams& params) { + const std::string& name, + ThreadPriority priority_hint) { SchedulerWorker* worker; bool start_worker; @@ -433,8 +426,7 @@ AutoSchedulerLock auto_lock(lock_); int id = next_worker_id_++; workers_.emplace_back(make_scoped_refptr(new SchedulerWorker( - params.priority_hint(), - CreateSchedulerWorkerDelegate<DelegateType>(params, id), + priority_hint, CreateSchedulerWorkerDelegate<DelegateType>(name, id), task_tracker_))); worker = workers_.back().get(); start_worker = started_;
diff --git a/base/task_scheduler/scheduler_single_thread_task_runner_manager.h b/base/task_scheduler/scheduler_single_thread_task_runner_manager.h index c862f19..c6d9d69 100644 --- a/base/task_scheduler/scheduler_single_thread_task_runner_manager.h +++ b/base/task_scheduler/scheduler_single_thread_task_runner_manager.h
@@ -6,6 +6,7 @@ #define BASE_TASK_SCHEDULER_SCHEDULER_SINGLE_THREAD_TASK_RUNNER_MANAGER_H_ #include <memory> +#include <string> #include <vector> #include "base/atomicops.h" @@ -14,8 +15,7 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/task_scheduler/scheduler_lock.h" -#include "base/task_scheduler/scheduler_worker_pool_params.h" -#include "base/task_scheduler/task_scheduler.h" +#include "base/threading/platform_thread.h" #include "build/build_config.h" namespace base { @@ -44,9 +44,6 @@ class BASE_EXPORT SchedulerSingleThreadTaskRunnerManager final { public: SchedulerSingleThreadTaskRunnerManager( - const std::vector<SchedulerWorkerPoolParams>& worker_pool_params_vector, - const TaskScheduler::WorkerPoolIndexForTraitsCallback& - worker_pool_index_for_traits_callback, TaskTracker* task_tracker, DelayedTaskManager* delayed_task_manager); ~SchedulerSingleThreadTaskRunnerManager(); @@ -55,11 +52,23 @@ // be started when SingleThreadTaskRunners are created in the future. void Start(); + // Creates a SingleThreadTaskRunner which runs tasks with |traits| on a + // dedicated thread named "TaskSchedulerSingleThread" + |name| + index. + // |priority_hint| is the preferred thread priority; the actual thread + // priority depends on shutdown state and platform capabilities. scoped_refptr<SingleThreadTaskRunner> CreateSingleThreadTaskRunnerWithTraits( + const std::string& name, + ThreadPriority priority_hint, const TaskTraits& traits); #if defined(OS_WIN) + // Creates a SingleThreadTaskRunner which runs tasks with |traits| on a + // dedicated COM STA thread named "TaskSchedulerSingleThreadCOMSTA" + |name| + + // index. |priority_hint| is the preferred thread priority; the actual thread + // priority depends on shutdown state and platform capabilities. scoped_refptr<SingleThreadTaskRunner> CreateCOMSTATaskRunnerWithTraits( + const std::string& name, + ThreadPriority priority_hint, const TaskTraits& traits); #endif // defined(OS_WIN) @@ -70,22 +79,22 @@ template <typename DelegateType> scoped_refptr<SingleThreadTaskRunner> - CreateSingleThreadTaskRunnerWithDelegate(const TaskTraits& traits); + CreateSingleThreadTaskRunnerWithDelegate(const std::string& name, + ThreadPriority priority_hint, + const TaskTraits& traits); template <typename DelegateType> std::unique_ptr<SchedulerWorkerDelegate> CreateSchedulerWorkerDelegate( - const SchedulerWorkerPoolParams& params, + const std::string& name, int id); template <typename DelegateType> SchedulerWorker* CreateAndRegisterSchedulerWorker( - const SchedulerWorkerPoolParams& params); + const std::string& name, + ThreadPriority priority_hint); void UnregisterSchedulerWorker(SchedulerWorker* worker); - const std::vector<SchedulerWorkerPoolParams> worker_pool_params_vector_; - const TaskScheduler::WorkerPoolIndexForTraitsCallback - worker_pool_index_for_traits_callback_; TaskTracker* const task_tracker_; DelayedTaskManager* const delayed_task_manager_;
diff --git a/base/task_scheduler/scheduler_single_thread_task_runner_manager_unittest.cc b/base/task_scheduler/scheduler_single_thread_task_runner_manager_unittest.cc index 1d6745ac..f7510a0 100644 --- a/base/task_scheduler/scheduler_single_thread_task_runner_manager_unittest.cc +++ b/base/task_scheduler/scheduler_single_thread_task_runner_manager_unittest.cc
@@ -32,32 +32,6 @@ namespace { -enum WorkerPoolType : size_t { - BACKGROUND_WORKER_POOL = 0, - FOREGROUND_WORKER_POOL, -}; - -static size_t GetThreadPoolIndexForTraits(const TaskTraits& traits) { - return traits.priority() == TaskPriority::BACKGROUND ? BACKGROUND_WORKER_POOL - : FOREGROUND_WORKER_POOL; -} - -std::vector<SchedulerWorkerPoolParams> GetParamsVector() { - using StandbyThreadPolicy = SchedulerWorkerPoolParams::StandbyThreadPolicy; - - std::vector<SchedulerWorkerPoolParams> params_vector; - - DCHECK_EQ(BACKGROUND_WORKER_POOL, params_vector.size()); - params_vector.emplace_back("Background", ThreadPriority::BACKGROUND, - StandbyThreadPolicy::LAZY, 1U, TimeDelta::Max()); - - DCHECK_EQ(FOREGROUND_WORKER_POOL, params_vector.size()); - params_vector.emplace_back("Foreground", ThreadPriority::NORMAL, - StandbyThreadPolicy::LAZY, 1U, TimeDelta::Max()); - - return params_vector; -} - class TaskSchedulerSingleThreadTaskRunnerManagerTest : public testing::Test { public: TaskSchedulerSingleThreadTaskRunnerManagerTest() @@ -65,12 +39,10 @@ void SetUp() override { service_thread_.Start(); - delayed_task_manager_ = MakeUnique<DelayedTaskManager>(service_thread_.task_runner()); single_thread_task_runner_manager_ = MakeUnique<SchedulerSingleThreadTaskRunnerManager>( - GetParamsVector(), Bind(&GetThreadPoolIndexForTraits), &task_tracker_, delayed_task_manager_.get()); StartSingleThreadTaskRunnerManagerFromSetUp(); } @@ -122,11 +94,13 @@ scoped_refptr<SingleThreadTaskRunner> task_runner_1 = single_thread_task_runner_manager_ ->CreateSingleThreadTaskRunnerWithTraits( + "A", ThreadPriority::NORMAL, TaskTraits().WithShutdownBehavior( TaskShutdownBehavior::BLOCK_SHUTDOWN)); scoped_refptr<SingleThreadTaskRunner> task_runner_2 = single_thread_task_runner_manager_ ->CreateSingleThreadTaskRunnerWithTraits( + "B", ThreadPriority::NORMAL, TaskTraits().WithShutdownBehavior( TaskShutdownBehavior::BLOCK_SHUTDOWN)); @@ -151,17 +125,13 @@ scoped_refptr<SingleThreadTaskRunner> task_runner_background = single_thread_task_runner_manager_ ->CreateSingleThreadTaskRunnerWithTraits( + "Background", ThreadPriority::BACKGROUND, TaskTraits().WithPriority(TaskPriority::BACKGROUND)); - scoped_refptr<SingleThreadTaskRunner> task_runner_user_visible = + scoped_refptr<SingleThreadTaskRunner> task_runner_normal = single_thread_task_runner_manager_ ->CreateSingleThreadTaskRunnerWithTraits( + "Normal", ThreadPriority::NORMAL, TaskTraits().WithPriority(TaskPriority::USER_VISIBLE)); - scoped_refptr<SingleThreadTaskRunner> task_runner_user_blocking = - single_thread_task_runner_manager_ - ->CreateSingleThreadTaskRunnerWithTraits( - TaskTraits() - .WithPriority(TaskPriority::USER_BLOCKING) - .WithShutdownBehavior(TaskShutdownBehavior::BLOCK_SHUTDOWN)); ThreadPriority thread_priority_background; task_runner_background->PostTask( @@ -173,43 +143,30 @@ FROM_HERE, BindOnce(&WaitableEvent::Signal, Unretained(&waitable_event_background))); - ThreadPriority thread_priority_user_visible; - task_runner_user_visible->PostTask( - FROM_HERE, - BindOnce(&CaptureThreadPriority, &thread_priority_user_visible)); - WaitableEvent waitable_event_user_visible( + ThreadPriority thread_priority_normal; + task_runner_normal->PostTask( + FROM_HERE, BindOnce(&CaptureThreadPriority, &thread_priority_normal)); + WaitableEvent waitable_event_normal( WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); - task_runner_user_visible->PostTask( - FROM_HERE, BindOnce(&WaitableEvent::Signal, - Unretained(&waitable_event_user_visible))); - - ThreadPriority thread_priority_user_blocking; - task_runner_user_blocking->PostTask( + task_runner_normal->PostTask( FROM_HERE, - BindOnce(&CaptureThreadPriority, &thread_priority_user_blocking)); - WaitableEvent waitable_event_user_blocking( - WaitableEvent::ResetPolicy::MANUAL, - WaitableEvent::InitialState::NOT_SIGNALED); - task_runner_user_blocking->PostTask( - FROM_HERE, BindOnce(&WaitableEvent::Signal, - Unretained(&waitable_event_user_blocking))); + BindOnce(&WaitableEvent::Signal, Unretained(&waitable_event_normal))); waitable_event_background.Wait(); - waitable_event_user_visible.Wait(); - waitable_event_user_blocking.Wait(); + waitable_event_normal.Wait(); if (Lock::HandlesMultipleThreadPriorities()) EXPECT_EQ(ThreadPriority::BACKGROUND, thread_priority_background); else EXPECT_EQ(ThreadPriority::NORMAL, thread_priority_background); - EXPECT_EQ(ThreadPriority::NORMAL, thread_priority_user_visible); - EXPECT_EQ(ThreadPriority::NORMAL, thread_priority_user_blocking); + EXPECT_EQ(ThreadPriority::NORMAL, thread_priority_normal); } TEST_F(TaskSchedulerSingleThreadTaskRunnerManagerTest, PostTaskAfterShutdown) { auto task_runner = single_thread_task_runner_manager_ - ->CreateSingleThreadTaskRunnerWithTraits(TaskTraits()); + ->CreateSingleThreadTaskRunnerWithTraits( + "A", ThreadPriority::NORMAL, TaskTraits()); task_tracker_.Shutdown(); EXPECT_FALSE(task_runner->PostTask(FROM_HERE, BindOnce(&ShouldNotRun))); } @@ -222,7 +179,8 @@ WaitableEvent task_ran(WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); auto task_runner = single_thread_task_runner_manager_ - ->CreateSingleThreadTaskRunnerWithTraits(TaskTraits()); + ->CreateSingleThreadTaskRunnerWithTraits( + "A", ThreadPriority::NORMAL, TaskTraits()); EXPECT_TRUE(task_runner->PostDelayedTask( FROM_HERE, BindOnce(&WaitableEvent::Signal, Unretained(&task_ran)), TestTimeouts::tiny_timeout())); @@ -243,11 +201,13 @@ scoped_refptr<SingleThreadTaskRunner> task_runner_1 = single_thread_task_runner_manager_ ->CreateSingleThreadTaskRunnerWithTraits( + "A", ThreadPriority::NORMAL, TaskTraits().WithShutdownBehavior( TaskShutdownBehavior::BLOCK_SHUTDOWN)); scoped_refptr<SingleThreadTaskRunner> task_runner_2 = single_thread_task_runner_manager_ ->CreateSingleThreadTaskRunnerWithTraits( + "B", ThreadPriority::NORMAL, TaskTraits().WithShutdownBehavior( TaskShutdownBehavior::BLOCK_SHUTDOWN)); @@ -331,6 +291,7 @@ { auto task_runner = single_thread_task_runner_manager_ ->CreateSingleThreadTaskRunnerWithTraits( + "A", ThreadPriority::NORMAL, TaskTraits().WithBaseSyncPrimitives()); EXPECT_TRUE(task_runner->PostTask( FROM_HERE, @@ -360,6 +321,7 @@ { auto task_runner = single_thread_task_runner_manager_ ->CreateSingleThreadTaskRunnerWithTraits( + "A", ThreadPriority::NORMAL, TaskTraits().WithBaseSyncPrimitives()); EXPECT_TRUE(task_runner->PostTask( FROM_HERE, @@ -383,11 +345,12 @@ TEST_F(TaskSchedulerSingleThreadTaskRunnerManagerTest, COMSTAInitialized) { scoped_refptr<SingleThreadTaskRunner> com_task_runner = single_thread_task_runner_manager_->CreateCOMSTATaskRunnerWithTraits( + "A", ThreadPriority::NORMAL, TaskTraits().WithShutdownBehavior( TaskShutdownBehavior::BLOCK_SHUTDOWN)); com_task_runner->PostTask( - FROM_HERE, Bind([]() { + FROM_HERE, BindOnce([]() { HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); if (SUCCEEDED(hr)) { ADD_FAILURE() << "COM STA was not initialized on this thread"; @@ -446,6 +409,7 @@ TEST_F(TaskSchedulerSingleThreadTaskRunnerManagerTestWin, PumpsMessages) { scoped_refptr<SingleThreadTaskRunner> com_task_runner = single_thread_task_runner_manager_->CreateCOMSTATaskRunnerWithTraits( + "A", ThreadPriority::NORMAL, TaskTraits().WithShutdownBehavior( TaskShutdownBehavior::BLOCK_SHUTDOWN)); HWND hwnd = nullptr; @@ -454,9 +418,10 @@ // COM callback. com_task_runner->PostTask( FROM_HERE, - Bind([](TaskSchedulerSingleThreadTaskRunnerManagerTestWin* test_harness, - HWND* hwnd) { *hwnd = test_harness->CreateTestWindow(); }, - Unretained(this), &hwnd)); + BindOnce( + [](TaskSchedulerSingleThreadTaskRunnerManagerTestWin* test_harness, + HWND* hwnd) { *hwnd = test_harness->CreateTestWindow(); }, + Unretained(this), &hwnd)); task_tracker_.Flush(); @@ -466,7 +431,7 @@ SendMessage(hwnd, WM_USER, 0, 0); com_task_runner->PostTask( - FROM_HERE, Bind([](HWND hwnd) { ::DestroyWindow(hwnd); }, hwnd)); + FROM_HERE, BindOnce([](HWND hwnd) { ::DestroyWindow(hwnd); }, hwnd)); task_tracker_.Shutdown(); } @@ -497,10 +462,11 @@ WaitableEvent task_running(WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); single_thread_task_runner_manager_ - ->CreateSingleThreadTaskRunnerWithTraits(TaskTraits()) + ->CreateSingleThreadTaskRunnerWithTraits("A", ThreadPriority::NORMAL, + TaskTraits()) ->PostTask( FROM_HERE, - Bind( + BindOnce( [](WaitableEvent* task_running, AtomicFlag* manager_started) { task_running->Signal();
diff --git a/base/task_scheduler/scheduler_worker_pool_impl.cc b/base/task_scheduler/scheduler_worker_pool_impl.cc index d45495413..ad118af 100644 --- a/base/task_scheduler/scheduler_worker_pool_impl.cc +++ b/base/task_scheduler/scheduler_worker_pool_impl.cc
@@ -265,7 +265,7 @@ // highest index is at the bottom of the idle stack. for (int index = params.max_threads() - 1; index >= 0; --index) { workers_[index] = make_scoped_refptr(new SchedulerWorker( - params.priority_hint(), + priority_hint_, MakeUnique<SchedulerWorkerDelegateImpl>( this, re_enqueue_sequence_callback_, index), task_tracker_, params.backward_compatibility(),
diff --git a/base/task_scheduler/task_scheduler.cc b/base/task_scheduler/task_scheduler.cc index 0e621f1..e6181dfb 100644 --- a/base/task_scheduler/task_scheduler.cc +++ b/base/task_scheduler/task_scheduler.cc
@@ -6,7 +6,6 @@ #include <algorithm> -#include "base/bind.h" #include "base/logging.h" #include "base/sys_info.h" #include "base/task_scheduler/scheduler_worker_pool_params.h" @@ -39,7 +38,7 @@ #if !defined(OS_NACL) // static -void TaskScheduler::CreateAndSetSimpleTaskScheduler(const std::string& name) { +void TaskScheduler::CreateAndSetSimpleTaskScheduler(StringPiece name) { using StandbyThreadPolicy = SchedulerWorkerPoolParams::StandbyThreadPolicy; // Values were chosen so that: @@ -66,17 +65,8 @@ } #endif // !defined(OS_NACL) -// static void TaskScheduler::CreateAndSetDefaultTaskScheduler( - const std::vector<SchedulerWorkerPoolParams>& worker_pool_params_vector, - const WorkerPoolIndexForTraitsCallback& - worker_pool_index_for_traits_callback) { - SetInstance(internal::TaskSchedulerImpl::Create( - worker_pool_params_vector, worker_pool_index_for_traits_callback)); -} - -void TaskScheduler::CreateAndSetDefaultTaskScheduler( - const std::string& name, + StringPiece name, const InitParams& init_params) { SetInstance(internal::TaskSchedulerImpl::Create(name, init_params)); }
diff --git a/base/task_scheduler/task_scheduler.h b/base/task_scheduler/task_scheduler.h index d19841f..5525aac3 100644 --- a/base/task_scheduler/task_scheduler.h +++ b/base/task_scheduler/task_scheduler.h
@@ -6,7 +6,6 @@ #define BASE_TASK_SCHEDULER_TASK_SCHEDULER_H_ #include <memory> -#include <string> #include <vector> #include "base/base_export.h" @@ -14,6 +13,7 @@ #include "base/memory/ref_counted.h" #include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" +#include "base/strings/string_piece.h" #include "base/task_runner.h" #include "base/task_scheduler/scheduler_worker_pool_params.h" #include "base/task_scheduler/task_traits.h" @@ -54,12 +54,6 @@ const SchedulerWorkerPoolParams foreground_blocking_worker_pool_params; }; - // Returns the index of the worker pool in which a task with |traits| should - // run. This should be coded in a future-proof way: new traits should - // gracefully map to a default pool. - using WorkerPoolIndexForTraitsCallback = - Callback<size_t(const TaskTraits& traits)>; - // Destroying a TaskScheduler is not allowed in production; it is always // leaked. In tests, it should only be destroyed after JoinForTesting() has // returned. @@ -143,21 +137,9 @@ // label threads and histograms. It should identify the component that calls // this. CHECKs on failure. For tests, prefer base::test::ScopedTaskScheduler // (ensures isolation). - static void CreateAndSetSimpleTaskScheduler(const std::string& name); + static void CreateAndSetSimpleTaskScheduler(StringPiece name); #endif // !defined(OS_NACL) - // Creates and sets a task scheduler with custom worker pools. CHECKs on - // failure. |worker_pool_params_vector| describes the worker pools to create. - // |worker_pool_index_for_traits_callback| returns the index in |worker_pools| - // of the worker pool in which a task with given traits should run. For tests, - // prefer base::test::ScopedTaskScheduler (ensures isolation). - // - // Deprecated. Use the overload below instead. https://crbug.com/690706 - static void CreateAndSetDefaultTaskScheduler( - const std::vector<SchedulerWorkerPoolParams>& worker_pool_params_vector, - const WorkerPoolIndexForTraitsCallback& - worker_pool_index_for_traits_callback); - // Creates and sets a task scheduler using custom params. |name| is used to // label threads and histograms. It should identify the component that creates // the TaskScheduler. |init_params| is used to initialize the worker pools. @@ -166,7 +148,7 @@ // // Note: The names and priority hints in |init_params| are ignored (ref. TODO // to remove them). - static void CreateAndSetDefaultTaskScheduler(const std::string& name, + static void CreateAndSetDefaultTaskScheduler(StringPiece name, const InitParams& init_params); // Registers |task_scheduler| to handle tasks posted through the post_task.h
diff --git a/base/task_scheduler/task_scheduler_impl.cc b/base/task_scheduler/task_scheduler_impl.cc index 6a2732d..d5c59ba7 100644 --- a/base/task_scheduler/task_scheduler_impl.cc +++ b/base/task_scheduler/task_scheduler_impl.cc
@@ -15,11 +15,6 @@ #include "base/task_scheduler/sequence_sort_key.h" #include "base/task_scheduler/task.h" #include "base/task_scheduler/task_tracker.h" -#include "build/build_config.h" - -#if defined(OS_POSIX) && !defined(OS_NACL_SFI) -#include "base/task_scheduler/task_tracker_posix.h" -#endif namespace base { namespace internal { @@ -58,59 +53,15 @@ return is_background ? BACKGROUND : FOREGROUND; } -void AddAugmentedSchedulerWorkerPoolParamsToVector( - EnvironmentType environment_type, - const std::string& task_scheduler_name, - const SchedulerWorkerPoolParams& params, - std::vector<SchedulerWorkerPoolParams>* - scheduler_worker_pool_params_vector) { - DCHECK_EQ(static_cast<size_t>(environment_type), - scheduler_worker_pool_params_vector->size()); - scheduler_worker_pool_params_vector->emplace_back( - task_scheduler_name + kEnvironmentParams[environment_type].name_suffix, - kEnvironmentParams[environment_type].priority_hint, - params.standby_thread_policy(), params.max_threads(), - params.suggested_reclaim_time(), params.backward_compatibility()); -} - } // namespace // static std::unique_ptr<TaskSchedulerImpl> TaskSchedulerImpl::Create( - const std::vector<SchedulerWorkerPoolParams>& worker_pool_params_vector, - const WorkerPoolIndexForTraitsCallback& - worker_pool_index_for_traits_callback) { - std::unique_ptr<TaskSchedulerImpl> scheduler( - new TaskSchedulerImpl(worker_pool_index_for_traits_callback)); - scheduler->Initialize(worker_pool_params_vector); - return scheduler; -} - -// static -std::unique_ptr<TaskSchedulerImpl> TaskSchedulerImpl::Create( - const std::string& name, + StringPiece name, const TaskScheduler::InitParams& init_params) { - // Create a vector of SchedulerWorkerPoolParams using names and priority hints - // derived from |kEnvironmentParams| and other params from |init_params|. - std::vector<SchedulerWorkerPoolParams> worker_pool_params_vector; - AddAugmentedSchedulerWorkerPoolParamsToVector( - BACKGROUND, name, init_params.background_worker_pool_params, - &worker_pool_params_vector); - AddAugmentedSchedulerWorkerPoolParamsToVector( - BACKGROUND_BLOCKING, name, - init_params.background_blocking_worker_pool_params, - &worker_pool_params_vector); - AddAugmentedSchedulerWorkerPoolParamsToVector( - FOREGROUND, name, init_params.foreground_worker_pool_params, - &worker_pool_params_vector); - AddAugmentedSchedulerWorkerPoolParamsToVector( - FOREGROUND_BLOCKING, name, - init_params.foreground_blocking_worker_pool_params, - &worker_pool_params_vector); - DCHECK_EQ(static_cast<size_t>(ENVIRONMENT_COUNT), - worker_pool_params_vector.size()); - - return Create(worker_pool_params_vector, Bind(&GetEnvironmentIndexForTraits)); + auto task_scheduler = WrapUnique(new TaskSchedulerImpl(name)); + task_scheduler->Initialize(init_params); + return task_scheduler; } TaskSchedulerImpl::~TaskSchedulerImpl() { @@ -145,15 +96,21 @@ scoped_refptr<SingleThreadTaskRunner> TaskSchedulerImpl::CreateSingleThreadTaskRunnerWithTraits( const TaskTraits& traits) { + const auto& environment_params = + kEnvironmentParams[GetEnvironmentIndexForTraits(traits)]; return single_thread_task_runner_manager_ - ->CreateSingleThreadTaskRunnerWithTraits(traits); + ->CreateSingleThreadTaskRunnerWithTraits( + name_ + environment_params.name_suffix, + environment_params.priority_hint, traits); } #if defined(OS_WIN) scoped_refptr<SingleThreadTaskRunner> TaskSchedulerImpl::CreateCOMSTATaskRunnerWithTraits(const TaskTraits& traits) { + const auto& environment_params = + kEnvironmentParams[GetEnvironmentIndexForTraits(traits)]; return single_thread_task_runner_manager_->CreateCOMSTATaskRunnerWithTraits( - traits); + environment_params.name_suffix, environment_params.priority_hint, traits); } #endif // defined(OS_WIN) @@ -172,13 +129,11 @@ void TaskSchedulerImpl::Shutdown() { // TODO(fdoray): Increase the priority of BACKGROUND tasks blocking shutdown. - DCHECK(task_tracker_); - task_tracker_->Shutdown(); + task_tracker_.Shutdown(); } void TaskSchedulerImpl::FlushForTesting() { - DCHECK(task_tracker_); - task_tracker_->Flush(); + task_tracker_.Flush(); } void TaskSchedulerImpl::JoinForTesting() { @@ -196,18 +151,11 @@ #endif } -TaskSchedulerImpl::TaskSchedulerImpl(const WorkerPoolIndexForTraitsCallback& - worker_pool_index_for_traits_callback) - : service_thread_("TaskSchedulerServiceThread"), - worker_pool_index_for_traits_callback_( - worker_pool_index_for_traits_callback) { - DCHECK(!worker_pool_index_for_traits_callback_.is_null()); -} +TaskSchedulerImpl::TaskSchedulerImpl(StringPiece name) + : name_(name), service_thread_("TaskSchedulerServiceThread") {} void TaskSchedulerImpl::Initialize( - const std::vector<SchedulerWorkerPoolParams>& worker_pool_params_vector) { - DCHECK(!worker_pool_params_vector.empty()); - + const TaskScheduler::InitParams& init_params) { // Start the service thread. On platforms that support it (POSIX except NaCL // SFI), the service thread runs a MessageLoopForIO which is used to support // FileDescriptorWatcher in the scope in which tasks run. @@ -221,25 +169,20 @@ service_thread_options.timer_slack = TIMER_SLACK_MAXIMUM; CHECK(service_thread_.StartWithOptions(service_thread_options)); - // Instantiate TaskTracker. Needs to happen after starting the service thread - // to get its message_loop(). - task_tracker_ = #if defined(OS_POSIX) && !defined(OS_NACL_SFI) - base::MakeUnique<TaskTrackerPosix>( - static_cast<MessageLoopForIO*>(service_thread_.message_loop())); -#else - base::MakeUnique<TaskTracker>(); + // Needs to happen after starting the service thread to get its + // message_loop(). + task_tracker_.set_watch_file_descriptor_message_loop( + static_cast<MessageLoopForIO*>(service_thread_.message_loop())); #endif - // Instantiate DelayedTaskManager. Needs to happen after starting the service - // thread to get its task_runner(). + // Needs to happen after starting the service thread to get its task_runner(). delayed_task_manager_ = base::MakeUnique<DelayedTaskManager>(service_thread_.task_runner()); single_thread_task_runner_manager_ = MakeUnique<SchedulerSingleThreadTaskRunnerManager>( - worker_pool_params_vector, worker_pool_index_for_traits_callback_, - task_tracker_.get(), delayed_task_manager_.get()); + &task_tracker_, delayed_task_manager_.get()); single_thread_task_runner_manager_->Start(); // Callback invoked by workers to re-enqueue a sequence in the appropriate @@ -248,24 +191,41 @@ re_enqueue_sequence_callback = Bind(&TaskSchedulerImpl::ReEnqueueSequenceCallback, Unretained(this)); + // Order must match the EnvironmentType enum. + const SchedulerWorkerPoolParams* worker_pool_params[] = { + &init_params.background_worker_pool_params, + &init_params.background_blocking_worker_pool_params, + &init_params.foreground_worker_pool_params, + &init_params.foreground_blocking_worker_pool_params}; + + static_assert(arraysize(worker_pools_) == ENVIRONMENT_COUNT, + "The size of |worker_pools_| must match ENVIRONMENT_COUNT."); + static_assert( + arraysize(kEnvironmentParams) == ENVIRONMENT_COUNT, + "The size of |kEnvironmentParams| must match ENVIRONMENT_COUNT."); + static_assert( + arraysize(worker_pool_params) == ENVIRONMENT_COUNT, + "The size of |worker_pool_params| must match ENVIRONMENT_COUNT."); + // Start worker pools. - for (const auto& worker_pool_params : worker_pool_params_vector) { - // Passing pointers to objects owned by |this| to - // SchedulerWorkerPoolImpl::Create() is safe because a TaskSchedulerImpl - // can't be deleted before all its worker pools have been joined. - worker_pools_.push_back(MakeUnique<SchedulerWorkerPoolImpl>( - worker_pool_params.name(), worker_pool_params.priority_hint(), - re_enqueue_sequence_callback, task_tracker_.get(), - delayed_task_manager_.get())); - worker_pools_.back()->Start(worker_pool_params); + for (int environment_type = 0; environment_type < ENVIRONMENT_COUNT; + ++environment_type) { + // Passing pointers to objects owned by |this| to the constructor of + // SchedulerWorkerPoolImpl is safe because a TaskSchedulerImpl can't be + // deleted before all its worker pools have been joined. + worker_pools_[environment_type] = MakeUnique<SchedulerWorkerPoolImpl>( + name_ + kEnvironmentParams[environment_type].name_suffix, + kEnvironmentParams[environment_type].priority_hint, + re_enqueue_sequence_callback, &task_tracker_, + delayed_task_manager_.get()); + worker_pools_[environment_type]->Start( + *worker_pool_params[environment_type]); } } SchedulerWorkerPoolImpl* TaskSchedulerImpl::GetWorkerPoolForTraits( const TaskTraits& traits) const { - const size_t index = worker_pool_index_for_traits_callback_.Run(traits); - DCHECK_LT(index, worker_pools_.size()); - return worker_pools_[index].get(); + return worker_pools_[GetEnvironmentIndexForTraits(traits)].get(); } void TaskSchedulerImpl::ReEnqueueSequenceCallback(
diff --git a/base/task_scheduler/task_scheduler_impl.h b/base/task_scheduler/task_scheduler_impl.h index 1e31888..70da225 100644 --- a/base/task_scheduler/task_scheduler_impl.h +++ b/base/task_scheduler/task_scheduler_impl.h
@@ -13,24 +13,28 @@ #include "base/logging.h" #include "base/macros.h" #include "base/memory/ref_counted.h" +#include "base/strings/string_piece.h" #include "base/synchronization/atomic_flag.h" #include "base/task_scheduler/scheduler_worker_pool_impl.h" #include "base/task_scheduler/sequence.h" #include "base/task_scheduler/task_scheduler.h" +#include "base/task_scheduler/task_tracker.h" #include "base/task_scheduler/task_traits.h" #include "base/threading/thread.h" #include "build/build_config.h" +#if defined(OS_POSIX) && !defined(OS_NACL_SFI) +#include "base/task_scheduler/task_tracker_posix.h" +#endif + namespace base { class HistogramBase; -class SchedulerWorkerPoolParams; namespace internal { class DelayedTaskManager; class SchedulerSingleThreadTaskRunnerManager; -class TaskTracker; // Default TaskScheduler implementation. This class is thread-safe. class BASE_EXPORT TaskSchedulerImpl : public TaskScheduler { @@ -43,20 +47,9 @@ // Note: The names and priority hints in |init_params| are ignored. // https://crbug.com/690706 static std::unique_ptr<TaskSchedulerImpl> Create( - const std::string& name, + StringPiece name, const TaskScheduler::InitParams& init_params); - // Creates and returns an initialized TaskSchedulerImpl. CHECKs on failure. - // |worker_pool_params_vector| describes the worker pools to create. - // |worker_pool_index_for_traits_callback| returns the index in |worker_pools| - // of the worker pool in which a task with given traits should run. - // - // Deprecated. https://crbug.com/690706 - static std::unique_ptr<TaskSchedulerImpl> Create( - const std::vector<SchedulerWorkerPoolParams>& worker_pool_params_vector, - const WorkerPoolIndexForTraitsCallback& - worker_pool_index_for_traits_callback); - ~TaskSchedulerImpl() override; // TaskScheduler: @@ -82,11 +75,9 @@ void JoinForTesting() override; private: - explicit TaskSchedulerImpl(const WorkerPoolIndexForTraitsCallback& - worker_pool_index_for_traits_callback); + explicit TaskSchedulerImpl(StringPiece name); - void Initialize( - const std::vector<SchedulerWorkerPoolParams>& worker_pool_params_vector); + void Initialize(const TaskScheduler::InitParams& init_params); // Returns the worker pool that runs Tasks with |traits|. SchedulerWorkerPoolImpl* GetWorkerPoolForTraits( @@ -96,13 +87,20 @@ // worker pops a Task from it. void ReEnqueueSequenceCallback(scoped_refptr<Sequence> sequence); + const std::string name_; Thread service_thread_; - std::unique_ptr<TaskTracker> task_tracker_; +#if defined(OS_POSIX) && !defined(OS_NACL_SFI) + TaskTrackerPosix task_tracker_; +#else + TaskTracker task_tracker_; +#endif std::unique_ptr<DelayedTaskManager> delayed_task_manager_; std::unique_ptr<SchedulerSingleThreadTaskRunnerManager> single_thread_task_runner_manager_; - const WorkerPoolIndexForTraitsCallback worker_pool_index_for_traits_callback_; - std::vector<std::unique_ptr<SchedulerWorkerPoolImpl>> worker_pools_; + + // There are 4 SchedulerWorkerPoolImpl in this array to match the 4 + // SchedulerWorkerPoolParams in TaskScheduler::InitParams. + std::unique_ptr<SchedulerWorkerPoolImpl> worker_pools_[4]; #if DCHECK_IS_ON() // Set once JoinForTesting() has returned.
diff --git a/base/task_scheduler/task_scheduler_impl_unittest.cc b/base/task_scheduler/task_scheduler_impl_unittest.cc index e0f8869..04ddc6f 100644 --- a/base/task_scheduler/task_scheduler_impl_unittest.cc +++ b/base/task_scheduler/task_scheduler_impl_unittest.cc
@@ -175,23 +175,6 @@ return params; } -enum WorkerPoolType { - BACKGROUND_WORKER_POOL = 0, - BACKGROUND_BLOCKING_WORKER_POOL, - FOREGROUND_WORKER_POOL, - FOREGROUND_BLOCKING_WORKER_POOL, -}; - -size_t GetThreadPoolIndexForTraits(const TaskTraits& traits) { - if (traits.may_block()) { - return traits.priority() == TaskPriority::BACKGROUND - ? BACKGROUND_BLOCKING_WORKER_POOL - : FOREGROUND_BLOCKING_WORKER_POOL; - } - return traits.priority() == TaskPriority::BACKGROUND ? BACKGROUND_WORKER_POOL - : FOREGROUND_WORKER_POOL; -} - class TaskSchedulerImplTest : public testing::TestWithParam<TraitsExecutionModePair> { protected: @@ -200,27 +183,22 @@ void SetUp() override { using StandbyThreadPolicy = SchedulerWorkerPoolParams::StandbyThreadPolicy; - std::vector<SchedulerWorkerPoolParams> params_vector; + constexpr TimeDelta kSuggestedReclaimTime = TimeDelta::FromSeconds(30); + constexpr int kMaxNumBackgroundThreads = 1; + constexpr int kMaxNumBackgroundBlockingThreads = 3; + constexpr int kMaxNumForegroundThreads = 4; + constexpr int kMaxNumForegroundBlockingThreads = 12; - ASSERT_EQ(BACKGROUND_WORKER_POOL, params_vector.size()); - params_vector.emplace_back("Background", ThreadPriority::BACKGROUND, - StandbyThreadPolicy::LAZY, 1U, TimeDelta::Max()); + scheduler_ = TaskSchedulerImpl::Create( + "Test", {{StandbyThreadPolicy::LAZY, kMaxNumBackgroundThreads, + kSuggestedReclaimTime}, + {StandbyThreadPolicy::LAZY, kMaxNumBackgroundBlockingThreads, + kSuggestedReclaimTime}, + {StandbyThreadPolicy::LAZY, kMaxNumForegroundThreads, + kSuggestedReclaimTime}, + {StandbyThreadPolicy::LAZY, kMaxNumForegroundBlockingThreads, + kSuggestedReclaimTime}}); - ASSERT_EQ(BACKGROUND_BLOCKING_WORKER_POOL, params_vector.size()); - params_vector.emplace_back("BackgroundBlocking", ThreadPriority::BACKGROUND, - StandbyThreadPolicy::LAZY, 3U, TimeDelta::Max()); - - ASSERT_EQ(FOREGROUND_WORKER_POOL, params_vector.size()); - params_vector.emplace_back("Foreground", ThreadPriority::NORMAL, - StandbyThreadPolicy::LAZY, 4U, TimeDelta::Max()); - - ASSERT_EQ(FOREGROUND_BLOCKING_WORKER_POOL, params_vector.size()); - params_vector.emplace_back("ForegroundBlocking", ThreadPriority::NORMAL, - StandbyThreadPolicy::LAZY, 12U, - TimeDelta::Max()); - - scheduler_ = TaskSchedulerImpl::Create(params_vector, - Bind(&GetThreadPoolIndexForTraits)); ASSERT_TRUE(scheduler_); }
diff --git a/base/task_scheduler/task_tracker_posix.cc b/base/task_scheduler/task_tracker_posix.cc index 5c54f37..ef73a08a 100644 --- a/base/task_scheduler/task_tracker_posix.cc +++ b/base/task_scheduler/task_tracker_posix.cc
@@ -12,15 +12,11 @@ namespace base { namespace internal { -TaskTrackerPosix::TaskTrackerPosix( - MessageLoopForIO* watch_file_descriptor_message_loop) - : watch_file_descriptor_message_loop_(watch_file_descriptor_message_loop) { - DCHECK(watch_file_descriptor_message_loop_); -} - +TaskTrackerPosix::TaskTrackerPosix() = default; TaskTrackerPosix::~TaskTrackerPosix() = default; void TaskTrackerPosix::PerformRunTask(std::unique_ptr<Task> task) { + DCHECK(watch_file_descriptor_message_loop_); FileDescriptorWatcher file_descriptor_watcher( watch_file_descriptor_message_loop_); TaskTracker::PerformRunTask(std::move(task));
diff --git a/base/task_scheduler/task_tracker_posix.h b/base/task_scheduler/task_tracker_posix.h index f957e4c..53859b2 100644 --- a/base/task_scheduler/task_tracker_posix.h +++ b/base/task_scheduler/task_tracker_posix.h
@@ -21,18 +21,27 @@ // A TaskTracker that instantiates a FileDescriptorWatcher in the scope in which // a task runs. Used on all POSIX platforms except NaCl SFI. +// set_watch_file_descriptor_message_loop() must be called before the +// TaskTracker can run tasks. class BASE_EXPORT TaskTrackerPosix : public TaskTracker { public: - // |watch_file_descriptor_message_loop| is used to setup FileDescriptorWatcher - // in the scope in which a Task runs. - TaskTrackerPosix(MessageLoopForIO* watch_file_descriptor_message_loop); + TaskTrackerPosix(); ~TaskTrackerPosix(); + // Sets the MessageLoopForIO with which to setup FileDescriptorWatcher in the + // scope in which tasks run. Must be called before starting to run tasks. + // External synchronization is required between a call to this and a call to + // RunTask(). + void set_watch_file_descriptor_message_loop( + MessageLoopForIO* watch_file_descriptor_message_loop) { + watch_file_descriptor_message_loop_ = watch_file_descriptor_message_loop; + } + private: // TaskTracker: void PerformRunTask(std::unique_ptr<Task> task) override; - MessageLoopForIO* const watch_file_descriptor_message_loop_; + MessageLoopForIO* watch_file_descriptor_message_loop_ = nullptr; DISALLOW_COPY_AND_ASSIGN(TaskTrackerPosix); };
diff --git a/base/task_scheduler/task_tracker_posix_unittest.cc b/base/task_scheduler/task_tracker_posix_unittest.cc index b654a6d..a6edc69 100644 --- a/base/task_scheduler/task_tracker_posix_unittest.cc +++ b/base/task_scheduler/task_tracker_posix_unittest.cc
@@ -31,7 +31,8 @@ FROM_HERE, Bind([](bool* did_run) { *did_run = true; }, Unretained(&did_run)), TaskTraits(), TimeDelta()); - TaskTrackerPosix tracker(&message_loop); + TaskTrackerPosix tracker; + tracker.set_watch_file_descriptor_message_loop(&message_loop); EXPECT_TRUE(tracker.WillPostTask(task.get())); EXPECT_TRUE(tracker.RunTask(std::move(task), SequenceToken::Create())); @@ -48,7 +49,8 @@ FROM_HERE, Bind(IgnoreResult(&FileDescriptorWatcher::WatchReadable), fds[0], Bind(&DoNothing)), TaskTraits(), TimeDelta()); - TaskTrackerPosix tracker(&message_loop); + TaskTrackerPosix tracker; + tracker.set_watch_file_descriptor_message_loop(&message_loop); EXPECT_TRUE(tracker.WillPostTask(task.get())); EXPECT_TRUE(tracker.RunTask(std::move(task), SequenceToken::Create()));
diff --git a/base/threading/thread_restrictions.h b/base/threading/thread_restrictions.h index 97f3eb6..1b51c46 100644 --- a/base/threading/thread_restrictions.h +++ b/base/threading/thread_restrictions.h
@@ -99,6 +99,7 @@ class SequencedWorkerPool; class SimpleThread; +class StackSamplingProfiler; class Thread; class ThreadTestHelper; @@ -183,6 +184,7 @@ // BEGIN ALLOWED USAGE. friend class android_webview::AwFormDatabaseService; friend class android_webview::CookieManager; + friend class base::StackSamplingProfiler; friend class content::BrowserShutdownProfileDumper; friend class content::BrowserSurfaceViewManager; friend class content::BrowserTestBase;
diff --git a/build/android/AndroidManifest.xml b/build/android/AndroidManifest.xml index 2c469aa0..5439a5a 100644 --- a/build/android/AndroidManifest.xml +++ b/build/android/AndroidManifest.xml
@@ -13,7 +13,7 @@ be kept up to date. --> <manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="dummy.package"> + package="org.dummy"> <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="24" />
diff --git a/build/android/gradle/android.jinja b/build/android/gradle/android.jinja index 197f98f..c817f4f 100644 --- a/build/android/gradle/android.jinja +++ b/build/android/gradle/android.jinja
@@ -42,7 +42,7 @@ compileSdkVersion "{{ compile_sdk_version }}" buildToolsVersion "{{ build_tools_version }}" publishNonDefault true - // Multiple targets use the package name "dummy.package" + // Multiple targets use the package name "org.dummy" enforceUniquePackageName false compileOptions {
diff --git a/build/android/gyp/process_resources.py b/build/android/gyp/process_resources.py index a382308b..9174e095 100755 --- a/build/android/gyp/process_resources.py +++ b/build/android/gyp/process_resources.py
@@ -476,7 +476,7 @@ # - there was already a dependent android_resources() with the same # package (occurs mostly when an apk target and resources target share # an AndroidManifest.xml) - if cur_package != 'dummy.package' and cur_package not in packages: + if cur_package != 'org.dummy' and cur_package not in packages: packages.append(cur_package) r_txt_files.append(r_txt_path)
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/ChromeHomeNewTabPageBase.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/ChromeHomeNewTabPageBase.java index 4515d97..443b5b95 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/ChromeHomeNewTabPageBase.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/ChromeHomeNewTabPageBase.java
@@ -24,6 +24,7 @@ import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.widget.bottomsheet.BottomSheet; import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetMetrics; +import org.chromium.content_public.browser.LoadUrlParams; /** * The base class for the new tab pages displayed in Chrome Home. @@ -90,6 +91,11 @@ mFadingBackgroundView.setEnabled(true); if (!mTab.isClosing()) mShowOverviewOnClose = false; } + + @Override + public void onLoadUrl(Tab tab, LoadUrlParams params, int loadType) { + mBottomSheet.setSheetState(BottomSheet.SHEET_STATE_PEEK, true); + } }; mTab.addObserver(mTabObserver);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkUpdateManager.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkUpdateManager.java index 98a65671..b27cca61 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkUpdateManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkUpdateManager.java
@@ -285,7 +285,11 @@ return true; } - if (isShellApkVersionOutOfDate(info)) return true; + if (isShellApkVersionOutOfDate(info) + && WebApkVersion.CURRENT_SHELL_APK_VERSION + > mStorage.getLastRequestedShellApkVersion()) { + return true; + } return mStorage.shouldCheckForUpdate(); } @@ -363,6 +367,7 @@ if (storage == null) return; recordUpdate(storage, result, relaxUpdates); + storage.updateLastRequestedShellApkVersion(WebApkVersion.CURRENT_SHELL_APK_VERSION); } private static native void nativeUpdateAsync(String id, String startUrl, String scope,
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 0b942331..c8dae5ee 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
@@ -63,6 +63,9 @@ // Whether to check updates less frequently. static final String KEY_RELAX_UPDATES = "relax_updates"; + // The shell Apk version requested in the last update. + static final String KEY_LAST_REQUESTED_SHELL_APK_VERSION = "last_requested_shell_apk_version"; + // Number of milliseconds between checks for whether the WebAPK's Web Manifest has changed. public static final long UPDATE_INTERVAL = TimeUnit.DAYS.toMillis(3L); @@ -74,6 +77,9 @@ // server if the previous update attempt failed. public static final long RETRY_UPDATE_DURATION = TimeUnit.HOURS.toMillis(12L); + // The default shell Apk version of WebAPKs. + static final int DEFAULT_SHELL_APK_VERSION = 1; + // Unset/invalid constants for last used times and URLs. 0 is used as the null last used time as // WebappRegistry assumes that this is always a valid timestamp. static final long LAST_USED_UNSET = 0; @@ -435,6 +441,16 @@ return mPreferences.getInt(KEY_UPDATE_REQUESTED, 0); } + /** Updates the shell Apk version requested in the last update. */ + void updateLastRequestedShellApkVersion(int shellApkVersion) { + mPreferences.edit().putInt(KEY_LAST_REQUESTED_SHELL_APK_VERSION, shellApkVersion).apply(); + } + + /** Returns the shell Apk version requested in last update. */ + int getLastRequestedShellApkVersion() { + return mPreferences.getInt(KEY_LAST_REQUESTED_SHELL_APK_VERSION, DEFAULT_SHELL_APK_VERSION); + } + /** * Returns whether the previous WebAPK update attempt succeeded. Returns true if there has not * been any update attempts. @@ -467,7 +483,7 @@ if (sinceLastCheckDurationMs >= checkUpdatesInterval) return true; long sinceLastUpdateRequestDurationMs = now - getLastWebApkUpdateRequestCompletionTime(); - return sinceLastUpdateRequestDurationMs >= WebappDataStorage.RETRY_UPDATE_DURATION + return sinceLastUpdateRequestDurationMs >= RETRY_UPDATE_DURATION && !didPreviousUpdateSucceed(); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/CopylessPasteTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/CopylessPasteTest.java index fe1956f2..59d08fcb 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/CopylessPasteTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/CopylessPasteTest.java
@@ -10,6 +10,7 @@ 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.base.test.util.Feature; import org.chromium.base.test.util.Restriction; import org.chromium.blink.mojom.document_metadata.Entity; @@ -165,6 +166,7 @@ */ @LargeTest @Feature({"CopylessPaste"}) + @DisabledTest(message = "Flaky: crbug.com/713172") public void testCache() throws InterruptedException, TimeoutException { // The URLs used here should be unique in CopylessPasteTest. String uniqueTag = "#123";
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java index 4358804..1b1acce 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTest.java
@@ -46,7 +46,10 @@ import org.chromium.base.ApplicationStatus; import org.chromium.base.ApplicationStatus.ActivityStateListener; import org.chromium.base.ObserverList.RewindableIterator; +import org.chromium.base.PathUtils; import org.chromium.base.ThreadUtils; +import org.chromium.base.library_loader.LibraryLoader; +import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.DisabledTest; @@ -61,6 +64,7 @@ import org.chromium.chrome.browser.WarmupManager; import org.chromium.chrome.browser.appmenu.AppMenuHandler; import org.chromium.chrome.browser.document.ChromeLauncherActivity; +import org.chromium.chrome.browser.firstrun.FirstRunStatus; import org.chromium.chrome.browser.metrics.PageLoadMetrics; import org.chromium.chrome.browser.prerender.ExternalPrerenderHandler; import org.chromium.chrome.browser.profiles.Profile; @@ -76,6 +80,8 @@ import org.chromium.chrome.test.util.ChromeRestriction; import org.chromium.chrome.test.util.browser.LocationSettingsTestUtil; import org.chromium.chrome.test.util.browser.contextmenu.ContextMenuUtils; +import org.chromium.content.browser.BrowserStartupController; +import org.chromium.content.browser.BrowserStartupController.StartupCallback; import org.chromium.content.browser.test.util.Criteria; import org.chromium.content.browser.test.util.CriteriaHelper; import org.chromium.content.browser.test.util.DOMUtils; @@ -144,10 +150,19 @@ protected void setUp() throws Exception { super.setUp(); + ThreadUtils.runOnUiThreadBlocking(new Runnable() { + @Override + public void run() { + FirstRunStatus.setFirstRunFlowComplete(true); + } + }); + Context appContext = getInstrumentation().getTargetContext().getApplicationContext(); mTestServer = EmbeddedTestServer.createAndStartServer(appContext); mTestPage = mTestServer.getURL(TEST_PAGE); mTestPage2 = mTestServer.getURL(TEST_PAGE_2); + PathUtils.setPrivateDataDirectorySuffix(PRIVATE_DATA_DIRECTORY_SUFFIX); + LibraryLoader.get(LibraryProcessType.PROCESS_BROWSER).ensureInitialized(); mWebServer = TestWebServer.start(); CustomTabsConnection connection = @@ -162,6 +177,13 @@ CustomTabsConnection.getInstance((Application) appContext); connection.setForcePrerender(false); + ThreadUtils.runOnUiThreadBlocking(new Runnable() { + @Override + public void run() { + FirstRunStatus.setFirstRunFlowComplete(false); + } + }); + mTestServer.stopAndDestroyServer(); // finish() is called on a non-UI thread by the testing harness. Must hide the menu @@ -2259,6 +2281,38 @@ assertEquals(mTestPage, tab.getUrl()); } + private CustomTabsConnection warmUpAndWait() { + final Context context = getInstrumentation().getTargetContext().getApplicationContext(); + CustomTabsConnection connection = + CustomTabsTestUtils.setUpConnection((Application) context); + final CallbackHelper startupCallbackHelper = new CallbackHelper(); + assertTrue(connection.warmup(0)); + ThreadUtils.runOnUiThread(new Runnable() { + @Override + public void run() { + BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) + .addStartupCompletedObserver(new StartupCallback() { + @Override + public void onSuccess(boolean alreadyStarted) { + startupCallbackHelper.notifyCalled(); + } + + @Override + public void onFailure() { + fail(); + } + }); + } + }); + + try { + startupCallbackHelper.waitForCallback(0); + } catch (TimeoutException | InterruptedException e) { + fail(); + } + return connection; + } + private ChromeActivity reparentAndVerifyTab() throws InterruptedException { ActivityResult result = null; final ActivityMonitor monitor = getInstrumentation().addMonitor(
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTestBase.java b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTestBase.java index 7b59e2d..92df683 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTestBase.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityTestBase.java
@@ -7,23 +7,14 @@ import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout; import android.app.Activity; -import android.app.Application; -import android.content.Context; import android.content.Intent; import org.chromium.base.ApplicationStatus; -import org.chromium.base.PathUtils; -import org.chromium.base.ThreadUtils; -import org.chromium.base.library_loader.LibraryLoader; -import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.test.util.CallbackHelper; import org.chromium.chrome.browser.DeferredStartupHandler; -import org.chromium.chrome.browser.firstrun.FirstRunStatus; import org.chromium.chrome.browser.tab.EmptyTabObserver; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.test.ChromeActivityTestCaseBase; -import org.chromium.content.browser.BrowserStartupController; -import org.chromium.content.browser.BrowserStartupController.StartupCallback; import org.chromium.content.browser.test.util.Criteria; import org.chromium.content.browser.test.util.CriteriaHelper; @@ -40,40 +31,16 @@ protected static final long STARTUP_TIMEOUT_MS = scaleTimeout(5) * 1000; protected static final long LONG_TIMEOUT_MS = scaleTimeout(10) * 1000; - private static final String PRIVATE_DATA_DIRECTORY_SUFFIX = "chrome"; public CustomTabActivityTestBase() { super(CustomTabActivity.class); } @Override - protected void setUp() throws Exception { - super.setUp(); - ThreadUtils.runOnUiThreadBlocking(new Runnable() { - @Override - public void run() { - FirstRunStatus.setFirstRunFlowComplete(true); - } - }); - PathUtils.setPrivateDataDirectorySuffix(PRIVATE_DATA_DIRECTORY_SUFFIX); - LibraryLoader.get(LibraryProcessType.PROCESS_BROWSER).ensureInitialized(); + public void startMainActivity() throws InterruptedException { } @Override - protected void tearDown() throws Exception { - ThreadUtils.runOnUiThreadBlocking(new Runnable() { - @Override - public void run() { - FirstRunStatus.setFirstRunFlowComplete(false); - } - }); - super.tearDown(); - } - - @Override - public void startMainActivity() throws InterruptedException {} - - @Override protected void startActivityCompletely(Intent intent) { Activity activity = getInstrumentation().startActivitySync(intent); assertNotNull("Main activity did not start", activity); @@ -132,41 +99,4 @@ assertNotNull(tab.getView()); assertTrue(tab.isCurrentlyACustomTab()); } - - /** - * Connects to Custom Tabs, calls warmup() and wait for completion. - * - * @return the connection. - */ - protected CustomTabsConnection warmUpAndWait() { - final Context context = getInstrumentation().getTargetContext().getApplicationContext(); - CustomTabsConnection connection = - CustomTabsTestUtils.setUpConnection((Application) context); - final CallbackHelper startupCallbackHelper = new CallbackHelper(); - assertTrue(connection.warmup(0)); - ThreadUtils.runOnUiThread(new Runnable() { - @Override - public void run() { - BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER) - .addStartupCompletedObserver(new StartupCallback() { - @Override - public void onSuccess(boolean alreadyStarted) { - startupCallbackHelper.notifyCalled(); - } - - @Override - public void onFailure() { - fail(); - } - }); - } - }); - - try { - startupCallbackHelper.waitForCallback(0); - } catch (TimeoutException | InterruptedException e) { - fail(); - } - return connection; - } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabExternalNavigationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabExternalNavigationTest.java index b86be3d..ab7a16ae 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabExternalNavigationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabExternalNavigationTest.java
@@ -15,16 +15,14 @@ import org.chromium.chrome.browser.externalnav.ExternalNavigationParams; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabDelegateFactory; -import org.chromium.content.browser.test.util.Criteria; -import org.chromium.content.browser.test.util.CriteriaHelper; -import org.chromium.content.browser.test.util.DOMUtils; import org.chromium.net.test.EmbeddedTestServer; /** - * Instrumentation tests for external navigation handling of a Custom Tab. + * Instrumentation test for external navigation handling of a Custom Tab. */ @RetryOnFailure public class CustomTabExternalNavigationTest extends CustomTabActivityTestBase { + /** * A dummy activity that claims to handle "customtab://customtabtest". */ @@ -64,14 +62,30 @@ super.tearDown(); } + @Override + public void startMainActivity() throws InterruptedException { + super.startMainActivity(); + startCustomTabActivityWithIntent(CustomTabsTestUtils.createMinimalCustomTabIntent( + getInstrumentation().getTargetContext(), mTestServer.getURL(TEST_PATH))); + Tab tab = getActivity().getActivityTab(); + TabDelegateFactory delegateFactory = tab.getDelegateFactory(); + assertTrue(delegateFactory instanceof CustomTabDelegateFactory); + CustomTabDelegateFactory customTabDelegateFactory = + ((CustomTabDelegateFactory) delegateFactory); + mUrlHandler = customTabDelegateFactory.getExternalNavigationHandler(); + assertTrue(customTabDelegateFactory.getExternalNavigationDelegate() + instanceof CustomTabNavigationDelegate); + mNavigationDelegate = (CustomTabNavigationDelegate) customTabDelegateFactory + .getExternalNavigationDelegate(); + } + /** * For urls with special schemes and hosts, and there is exactly one activity having a matching * intent filter, the framework will make that activity the default handler of the special url. * This test tests whether chrome is able to start the default external handler. */ @SmallTest - public void testExternalActivityStartedForDefaultUrl() throws Exception { - startCustomTabActivity(mTestServer.getURL(TEST_PATH)); + public void testExternalActivityStartedForDefaultUrl() { final String testUrl = "customtab://customtabtest/intent"; ExternalNavigationParams params = new ExternalNavigationParams.Builder(testUrl, false) .build(); @@ -86,8 +100,7 @@ * be shown, even if other activities such as {@link DummyActivityForHttp} claim to handle it. */ @SmallTest - public void testIntentPickerNotShownForNormalUrl() throws Exception { - startCustomTabActivity(mTestServer.getURL(TEST_PATH)); + public void testIntentPickerNotShownForNormalUrl() { final String testUrl = "http://customtabtest.com"; ExternalNavigationParams params = new ExternalNavigationParams.Builder(testUrl, false) .build(); @@ -96,40 +109,4 @@ assertFalse("External activities should not be started to handle the url", mNavigationDelegate.hasExternalActivityStarted()); } - - /** - * Launches a Custom Tab, clicks on an external app scheme link, and check that an external - * activity has been launched. - */ - @SmallTest - public void testExternalApplicationLink() throws Exception { - warmUpAndWait(); - startCustomTabActivity(mTestServer.getURL(TEST_PATH)); - - Tab tab = getActivity().getActivityTab(); - assertTrue(DOMUtils.clickNode(tab.getContentViewCore(), "customtab-external-link")); - - CriteriaHelper.pollUiThread(new Criteria("External Activity not launched.") { - @Override - public boolean isSatisfied() { - return mNavigationDelegate.hasExternalActivityStarted(); - } - }); - } - - private void startCustomTabActivity(String url) throws InterruptedException { - super.startMainActivity(); - startCustomTabActivityWithIntent(CustomTabsTestUtils.createMinimalCustomTabIntent( - getInstrumentation().getTargetContext(), url)); - Tab tab = getActivity().getActivityTab(); - TabDelegateFactory delegateFactory = tab.getDelegateFactory(); - assertTrue(delegateFactory instanceof CustomTabDelegateFactory); - CustomTabDelegateFactory customTabDelegateFactory = - ((CustomTabDelegateFactory) delegateFactory); - mUrlHandler = customTabDelegateFactory.getExternalNavigationHandler(); - assertTrue(customTabDelegateFactory.getExternalNavigationDelegate() - instanceof CustomTabNavigationDelegate); - mNavigationDelegate = (CustomTabNavigationDelegate) - customTabDelegateFactory.getExternalNavigationDelegate(); - } }
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebApkUpdateManagerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebApkUpdateManagerTest.java index cb7d13c..551991aa 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebApkUpdateManagerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/webapps/WebApkUpdateManagerTest.java
@@ -721,4 +721,39 @@ assertTrue(updateManager.updateRequested()); assertEquals(0, storage.getUpdateRequests()); } + + /** + * Tests that a WebAPK update is requested immediately if: + * the Shell APK is out of date, + * AND + * there wasn't a previous request for this ShellAPK version. + */ + @Test + public void testShellApkOutOfDate() { + registerWebApk(defaultManifestData(), WebApkVersion.CURRENT_SHELL_APK_VERSION - 1); + TestWebApkUpdateManager updateManager = new TestWebApkUpdateManager(getStorage()); + + // There have not been any update requests for the current ShellAPK version. A WebAPK update + // should be requested immediately. + updateIfNeeded(updateManager); + assertTrue(updateManager.updateCheckStarted()); + onGotManifestData(updateManager, defaultManifestData()); + assertTrue(updateManager.updateRequested()); + + WebappDataStorage storage = getStorage(); + storage.updateTimeOfLastWebApkUpdateRequestCompletion(); + storage.updateLastRequestedShellApkVersion(WebApkVersion.CURRENT_SHELL_APK_VERSION); + + mClock.advance(1); + updateIfNeeded(updateManager); + assertFalse(updateManager.updateCheckStarted()); + + // A previous update request was made for the current ShellAPK version. A WebAPK update + // should be requested after the regular delay. + mClock.advance(WebappDataStorage.UPDATE_INTERVAL - 1); + updateIfNeeded(updateManager); + assertTrue(updateManager.updateCheckStarted()); + onGotManifestData(updateManager, defaultManifestData()); + assertTrue(updateManager.updateRequested()); + } }
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 5f06bfc..c0d7d0fb 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -1107,6 +1107,10 @@ {"enable-webassembly", flag_descriptions::kEnableWasmName, flag_descriptions::kEnableWasmDescription, kOsAll, FEATURE_VALUE_TYPE(features::kWebAssembly)}, + {"enable-webassembly-streaming", + flag_descriptions::kEnableWasmStreamingName, + flag_descriptions::kEnableWasmStreamingDescription, kOsAll, + FEATURE_VALUE_TYPE(features::kWebAssemblyStreaming)}, {"shared-array-buffer", flag_descriptions::kEnableSharedArrayBufferName, flag_descriptions::kEnableSharedArrayBufferDescription, kOsAll, FEATURE_VALUE_TYPE(features::kSharedArrayBuffer)}, @@ -2351,6 +2355,10 @@ flag_descriptions::kFramebustingName, flag_descriptions::kFramebustingDescription, kOsAll, FEATURE_VALUE_TYPE(features::kFramebustingNeedsSameOriginOrUserGesture)}, + {"vibrate-requires-user-gesture", + flag_descriptions::kVibrateRequiresUserGestureName, + flag_descriptions::kVibrateRequiresUserGestureDescription, kOsAll, + FEATURE_VALUE_TYPE(features::kVibrateRequiresUserGesture)}, {"web-payments", flag_descriptions::kWebPaymentsName, flag_descriptions::kWebPaymentsDescription, kOsDesktop, FEATURE_VALUE_TYPE(features::kWebPayments)},
diff --git a/chrome/browser/browsing_data/autofill_counter_browsertest.cc b/chrome/browser/browsing_data/autofill_counter_browsertest.cc index d85c8896..3db7c8f6 100644 --- a/chrome/browser/browsing_data/autofill_counter_browsertest.cc +++ b/chrome/browser/browsing_data/autofill_counter_browsertest.cc
@@ -114,8 +114,8 @@ void CallbackFromDBThread() { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, - base::Bind(&base::RunLoop::Quit, - base::Unretained(run_loop_.get()))); + base::BindOnce(&base::RunLoop::Quit, + base::Unretained(run_loop_.get()))); } void WaitForDBThread() { @@ -123,8 +123,8 @@ content::BrowserThread::PostTask( content::BrowserThread::DB, FROM_HERE, - base::Bind(&AutofillCounterTest::CallbackFromDBThread, - base::Unretained(this))); + base::BindOnce(&AutofillCounterTest::CallbackFromDBThread, + base::Unretained(this))); run_loop_->Run(); }
diff --git a/chrome/browser/browsing_data/browsing_data_appcache_helper.cc b/chrome/browser/browsing_data/browsing_data_appcache_helper.cc index 88ce531..206021c 100644 --- a/chrome/browser/browsing_data/browsing_data_appcache_helper.cc +++ b/chrome/browser/browsing_data/browsing_data_appcache_helper.cc
@@ -38,7 +38,7 @@ } BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(callback, info_collection)); + base::BindOnce(callback, info_collection)); } } // namespace @@ -55,16 +55,16 @@ BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&BrowsingDataAppCacheHelper::StartFetchingOnIOThread, this, - callback)); + base::BindOnce(&BrowsingDataAppCacheHelper::StartFetchingOnIOThread, this, + callback)); } void BrowsingDataAppCacheHelper::DeleteAppCacheGroup(const GURL& manifest_url) { DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&BrowsingDataAppCacheHelper::DeleteAppCacheGroupOnIOThread, - this, manifest_url)); + base::BindOnce(&BrowsingDataAppCacheHelper::DeleteAppCacheGroupOnIOThread, + this, manifest_url)); } BrowsingDataAppCacheHelper::~BrowsingDataAppCacheHelper() {}
diff --git a/chrome/browser/browsing_data/browsing_data_cache_storage_helper.cc b/chrome/browser/browsing_data/browsing_data_cache_storage_helper.cc index 72483ab9..d5c9e838c 100644 --- a/chrome/browser/browsing_data/browsing_data_cache_storage_helper.cc +++ b/chrome/browser/browsing_data/browsing_data_cache_storage_helper.cc
@@ -32,7 +32,7 @@ } BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(callback, result)); + base::BindOnce(callback, result)); } } // namespace @@ -51,7 +51,7 @@ DCHECK(!callback.is_null()); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind( + base::BindOnce( &BrowsingDataCacheStorageHelper::FetchCacheStorageUsageInfoOnIOThread, this, callback)); } @@ -60,8 +60,9 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&BrowsingDataCacheStorageHelper::DeleteCacheStorageOnIOThread, - this, origin)); + base::BindOnce( + &BrowsingDataCacheStorageHelper::DeleteCacheStorageOnIOThread, this, + origin)); } void BrowsingDataCacheStorageHelper::FetchCacheStorageUsageInfoOnIOThread( @@ -141,7 +142,7 @@ } BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(callback, result)); + base::BindOnce(callback, result)); } void CannedBrowsingDataCacheStorageHelper::DeleteCacheStorage(
diff --git a/chrome/browser/browsing_data/browsing_data_channel_id_helper.cc b/chrome/browser/browsing_data/browsing_data_channel_id_helper.cc index e910a12..1498c985 100644 --- a/chrome/browser/browsing_data/browsing_data_channel_id_helper.cc +++ b/chrome/browser/browsing_data/browsing_data_channel_id_helper.cc
@@ -68,18 +68,17 @@ DCHECK(!callback.is_null()); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&BrowsingDataChannelIDHelperImpl::FetchOnIOThread, this, - callback)); + base::BindOnce(&BrowsingDataChannelIDHelperImpl::FetchOnIOThread, this, + callback)); } void BrowsingDataChannelIDHelperImpl::DeleteChannelID( const std::string& server_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserThread::PostTask( - BrowserThread::IO, - FROM_HERE, - base::Bind( - &BrowsingDataChannelIDHelperImpl::DeleteOnIOThread, this, server_id)); + BrowserThread::IO, FROM_HERE, + base::BindOnce(&BrowsingDataChannelIDHelperImpl::DeleteOnIOThread, this, + server_id)); } void BrowsingDataChannelIDHelperImpl::FetchOnIOThread( @@ -104,7 +103,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(!callback.is_null()); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(callback, channel_id_list)); + base::BindOnce(callback, channel_id_list)); } void BrowsingDataChannelIDHelperImpl::DeleteOnIOThread( @@ -172,8 +171,9 @@ return; // We post a task to emulate async fetching behavior. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&CannedBrowsingDataChannelIDHelper::FinishFetching, - this, callback)); + FROM_HERE, + base::BindOnce(&CannedBrowsingDataChannelIDHelper::FinishFetching, this, + callback)); } void CannedBrowsingDataChannelIDHelper::FinishFetching(
diff --git a/chrome/browser/browsing_data/browsing_data_cookie_helper.cc b/chrome/browser/browsing_data/browsing_data_cookie_helper.cc index 384b20fe..0ae5e6aa 100644 --- a/chrome/browser/browsing_data/browsing_data_cookie_helper.cc +++ b/chrome/browser/browsing_data/browsing_data_cookie_helper.cc
@@ -32,7 +32,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(!callback.is_null()); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(callback, cookies)); + base::BindOnce(callback, cookies)); } } // namespace @@ -51,8 +51,8 @@ DCHECK(!callback.is_null()); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&BrowsingDataCookieHelper::FetchCookiesOnIOThread, this, - callback)); + base::BindOnce(&BrowsingDataCookieHelper::FetchCookiesOnIOThread, this, + callback)); } void BrowsingDataCookieHelper::DeleteCookie( @@ -60,8 +60,8 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&BrowsingDataCookieHelper::DeleteCookieOnIOThread, - this, cookie)); + base::BindOnce(&BrowsingDataCookieHelper::DeleteCookieOnIOThread, this, + cookie)); } void BrowsingDataCookieHelper::FetchCookiesOnIOThread(
diff --git a/chrome/browser/browsing_data/browsing_data_database_helper.cc b/chrome/browser/browsing_data/browsing_data_database_helper.cc index 43b7d0c..5ab4cb20 100644 --- a/chrome/browser/browsing_data/browsing_data_database_helper.cc +++ b/chrome/browser/browsing_data/browsing_data_database_helper.cc
@@ -55,8 +55,8 @@ BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, - base::Bind(&BrowsingDataDatabaseHelper::FetchDatabaseInfoOnFileThread, - this, callback)); + base::BindOnce(&BrowsingDataDatabaseHelper::FetchDatabaseInfoOnFileThread, + this, callback)); } void BrowsingDataDatabaseHelper::DeleteDatabase(const std::string& origin, @@ -64,8 +64,8 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, - base::Bind(&BrowsingDataDatabaseHelper::DeleteDatabaseOnFileThread, this, - origin, name)); + base::BindOnce(&BrowsingDataDatabaseHelper::DeleteDatabaseOnFileThread, + this, origin, name)); } void BrowsingDataDatabaseHelper::FetchDatabaseInfoOnFileThread( @@ -98,7 +98,7 @@ } BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(callback, result)); + base::BindOnce(callback, result)); } void BrowsingDataDatabaseHelper::DeleteDatabaseOnFileThread( @@ -176,8 +176,8 @@ DatabaseInfo(identifier, info.name, info.description, 0, base::Time())); } - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, base::Bind(callback, result)); + BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, + base::BindOnce(callback, result)); } void CannedBrowsingDataDatabaseHelper::DeleteDatabase(
diff --git a/chrome/browser/browsing_data/browsing_data_file_system_helper.cc b/chrome/browser/browsing_data/browsing_data_file_system_helper.cc index fc9e245..d32fe0d0 100644 --- a/chrome/browser/browsing_data/browsing_data_file_system_helper.cc +++ b/chrome/browser/browsing_data/browsing_data_file_system_helper.cc
@@ -76,7 +76,7 @@ DCHECK(!callback.is_null()); file_task_runner()->PostTask( FROM_HERE, - base::Bind( + base::BindOnce( &BrowsingDataFileSystemHelperImpl::FetchFileSystemInfoInFileThread, this, callback)); } @@ -86,7 +86,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); file_task_runner()->PostTask( FROM_HERE, - base::Bind( + base::BindOnce( &BrowsingDataFileSystemHelperImpl::DeleteFileSystemOriginInFileThread, this, origin)); } @@ -131,7 +131,7 @@ result.push_back(iter.second); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(callback, result)); + base::BindOnce(callback, result)); } void BrowsingDataFileSystemHelperImpl::DeleteFileSystemOriginInFileThread( @@ -208,6 +208,6 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(!callback.is_null()); - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, base::Bind(callback, file_system_info_)); + BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, + base::BindOnce(callback, file_system_info_)); }
diff --git a/chrome/browser/browsing_data/browsing_data_indexed_db_helper.cc b/chrome/browser/browsing_data/browsing_data_indexed_db_helper.cc index 2afba3b..11a8323 100644 --- a/chrome/browser/browsing_data/browsing_data_indexed_db_helper.cc +++ b/chrome/browser/browsing_data/browsing_data_indexed_db_helper.cc
@@ -32,7 +32,7 @@ DCHECK(!callback.is_null()); indexed_db_context_->TaskRunner()->PostTask( FROM_HERE, - base::Bind( + base::BindOnce( &BrowsingDataIndexedDBHelper::FetchIndexedDBInfoInIndexedDBThread, this, callback)); } @@ -41,9 +41,8 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); indexed_db_context_->TaskRunner()->PostTask( FROM_HERE, - base::Bind( - &BrowsingDataIndexedDBHelper::DeleteIndexedDBInIndexedDBThread, - this, + base::BindOnce( + &BrowsingDataIndexedDBHelper::DeleteIndexedDBInIndexedDBThread, this, origin)); } @@ -59,7 +58,7 @@ result.push_back(origin); } BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(callback, result)); + base::BindOnce(callback, result)); } void BrowsingDataIndexedDBHelper::DeleteIndexedDBInIndexedDBThread( @@ -127,8 +126,8 @@ result.push_back(info); } - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, base::Bind(callback, result)); + BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, + base::BindOnce(callback, result)); } void CannedBrowsingDataIndexedDBHelper::DeleteIndexedDB(
diff --git a/chrome/browser/browsing_data/browsing_data_local_storage_helper.cc b/chrome/browser/browsing_data/browsing_data_local_storage_helper.cc index 906f4c01..24e6f6c 100644 --- a/chrome/browser/browsing_data/browsing_data_local_storage_helper.cc +++ b/chrome/browser/browsing_data/browsing_data_local_storage_helper.cc
@@ -44,7 +44,7 @@ } BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(callback, result)); + base::BindOnce(callback, result)); } } // namespace @@ -125,8 +125,8 @@ for (const GURL& url : pending_local_storage_info_) result.push_back(LocalStorageInfo(url, 0, base::Time())); - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, base::Bind(callback, result)); + BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, + base::BindOnce(callback, result)); } void CannedBrowsingDataLocalStorageHelper::DeleteOrigin(
diff --git a/chrome/browser/browsing_data/browsing_data_media_license_helper.cc b/chrome/browser/browsing_data/browsing_data_media_license_helper.cc index 653af7ff..389f4baa 100644 --- a/chrome/browser/browsing_data/browsing_data_media_license_helper.cc +++ b/chrome/browser/browsing_data/browsing_data_media_license_helper.cc
@@ -71,18 +71,18 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(!callback.is_null()); file_task_runner()->PostTask( - FROM_HERE, base::Bind(&BrowsingDataMediaLicenseHelperImpl:: - FetchMediaLicenseInfoOnFileTaskRunner, - this, callback)); + FROM_HERE, base::BindOnce(&BrowsingDataMediaLicenseHelperImpl:: + FetchMediaLicenseInfoOnFileTaskRunner, + this, callback)); } void BrowsingDataMediaLicenseHelperImpl::DeleteMediaLicenseOrigin( const GURL& origin) { DCHECK_CURRENTLY_ON(BrowserThread::UI); file_task_runner()->PostTask( - FROM_HERE, base::Bind(&BrowsingDataMediaLicenseHelperImpl:: - DeleteMediaLicenseOriginOnFileTaskRunner, - this, origin)); + FROM_HERE, base::BindOnce(&BrowsingDataMediaLicenseHelperImpl:: + DeleteMediaLicenseOriginOnFileTaskRunner, + this, origin)); } void BrowsingDataMediaLicenseHelperImpl::FetchMediaLicenseInfoOnFileTaskRunner( @@ -112,7 +112,7 @@ } BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(callback, result)); + base::BindOnce(callback, result)); } void BrowsingDataMediaLicenseHelperImpl::
diff --git a/chrome/browser/browsing_data/browsing_data_quota_helper_impl.cc b/chrome/browser/browsing_data/browsing_data_quota_helper_impl.cc index 80b9848..dceb140 100644 --- a/chrome/browser/browsing_data/browsing_data_quota_helper_impl.cc +++ b/chrome/browser/browsing_data/browsing_data_quota_helper_impl.cc
@@ -36,16 +36,16 @@ BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&BrowsingDataQuotaHelperImpl::FetchQuotaInfoOnIOThread, this, - callback)); + base::BindOnce(&BrowsingDataQuotaHelperImpl::FetchQuotaInfoOnIOThread, + this, callback)); } void BrowsingDataQuotaHelperImpl::RevokeHostQuota(const std::string& host) { DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&BrowsingDataQuotaHelperImpl::RevokeHostQuotaOnIOThread, this, - host)); + base::BindOnce(&BrowsingDataQuotaHelperImpl::RevokeHostQuotaOnIOThread, + this, host)); } BrowsingDataQuotaHelperImpl::BrowsingDataQuotaHelperImpl( @@ -159,7 +159,7 @@ } BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(callback, result)); + base::BindOnce(callback, result)); } void BrowsingDataQuotaHelperImpl::RevokeHostQuotaOnIOThread(
diff --git a/chrome/browser/browsing_data/browsing_data_remover_browsertest.cc b/chrome/browser/browsing_data/browsing_data_remover_browsertest.cc index 1fc217c3..d2bce37 100644 --- a/chrome/browser/browsing_data/browsing_data_remover_browsertest.cc +++ b/chrome/browser/browsing_data/browsing_data_remover_browsertest.cc
@@ -162,11 +162,11 @@ void SetUpOnMainThread() override { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&BrowsingDataRemoverTransportSecurityStateBrowserTest:: - SetUpTransportSecurityState, - base::Unretained(this), - base::RetainedRef( - browser()->profile()->GetRequestContext()))); + base::BindOnce( + &BrowsingDataRemoverTransportSecurityStateBrowserTest:: + SetUpTransportSecurityState, + base::Unretained(this), + base::RetainedRef(browser()->profile()->GetRequestContext()))); } void CheckTransportSecurityState( @@ -298,11 +298,12 @@ base::RunLoop run_loop; BrowserThread::PostTaskAndReply( BrowserThread::IO, FROM_HERE, - base::Bind(&BrowsingDataRemoverTransportSecurityStateBrowserTest:: - CheckTransportSecurityState, - base::Unretained(this), - base::RetainedRef(browser()->profile()->GetRequestContext()), - true /* should be cleared */), + base::BindOnce( + &BrowsingDataRemoverTransportSecurityStateBrowserTest:: + CheckTransportSecurityState, + base::Unretained(this), + base::RetainedRef(browser()->profile()->GetRequestContext()), + true /* should be cleared */), run_loop.QuitClosure()); } @@ -314,10 +315,11 @@ base::RunLoop run_loop; BrowserThread::PostTaskAndReply( BrowserThread::IO, FROM_HERE, - base::Bind(&BrowsingDataRemoverTransportSecurityStateBrowserTest:: - CheckTransportSecurityState, - base::Unretained(this), - base::RetainedRef(browser()->profile()->GetRequestContext()), - false /* should not be cleared */), + base::BindOnce( + &BrowsingDataRemoverTransportSecurityStateBrowserTest:: + CheckTransportSecurityState, + base::Unretained(this), + base::RetainedRef(browser()->profile()->GetRequestContext()), + false /* should not be cleared */), run_loop.QuitClosure()); }
diff --git a/chrome/browser/browsing_data/browsing_data_remover_impl.cc b/chrome/browser/browsing_data/browsing_data_remover_impl.cc index d9df6f1..606147bc 100644 --- a/chrome/browser/browsing_data/browsing_data_remover_impl.cc +++ b/chrome/browser/browsing_data/browsing_data_remover_impl.cc
@@ -404,10 +404,10 @@ clear_channel_ids_.Start(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&ClearChannelIDsOnIOThread, - filter_builder.BuildChannelIDFilter(), - delete_begin_, delete_end_, std::move(rq_context), - clear_channel_ids_.GetCompletionCallback())); + base::BindOnce(&ClearChannelIDsOnIOThread, + filter_builder.BuildChannelIDFilter(), delete_begin_, + delete_end_, std::move(rq_context), + clear_channel_ids_.GetCompletionCallback())); } ////////////////////////////////////////////////////////////////////////////// @@ -533,8 +533,8 @@ clear_http_auth_cache_.Start(); BrowserThread::PostTaskAndReply( BrowserThread::IO, FROM_HERE, - base::Bind(&ClearHttpAuthCacheOnIOThread, std::move(request_context), - delete_begin_), + base::BindOnce(&ClearHttpAuthCacheOnIOThread, + std::move(request_context), delete_begin_), clear_http_auth_cache_.GetCompletionCallback()); } @@ -648,7 +648,7 @@ // are scheduled. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, - base::Bind(&BrowsingDataRemoverImpl::RunNextTask, GetWeakPtr())); + base::BindOnce(&BrowsingDataRemoverImpl::RunNextTask, GetWeakPtr())); } void BrowsingDataRemoverImpl::NotifyIfDone() {
diff --git a/chrome/browser/browsing_data/browsing_data_remover_impl_unittest.cc b/chrome/browser/browsing_data/browsing_data_remover_impl_unittest.cc index f7350eaf..6d61086 100644 --- a/chrome/browser/browsing_data/browsing_data_remover_impl_unittest.cc +++ b/chrome/browser/browsing_data/browsing_data_remover_impl_unittest.cc
@@ -176,11 +176,10 @@ const GURL& storage_origin, net::URLRequestContextGetter* rq_context, const base::Closure& callback) override { - BrowserThread::PostTask(BrowserThread::UI, - FROM_HERE, - base::Bind(&TestStoragePartition::AsyncRunCallback, - base::Unretained(this), - callback)); + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::BindOnce(&TestStoragePartition::AsyncRunCallback, + base::Unretained(this), callback)); } void ClearData(uint32_t remove_mask, @@ -199,10 +198,9 @@ storage_partition_removal_data_.origin_matcher = origin_matcher; BrowserThread::PostTask( - BrowserThread::UI, - FROM_HERE, - base::Bind(&TestStoragePartition::AsyncRunCallback, - base::Unretained(this), callback)); + BrowserThread::UI, FROM_HERE, + base::BindOnce(&TestStoragePartition::AsyncRunCallback, + base::Unretained(this), callback)); } void ClearData(uint32_t remove_mask, @@ -221,9 +219,10 @@ storage_partition_removal_data_.origin_matcher = origin_matcher; storage_partition_removal_data_.cookie_matcher = cookie_matcher; - BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(&TestStoragePartition::AsyncRunCallback, - base::Unretained(this), callback)); + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::BindOnce(&TestStoragePartition::AsyncRunCallback, + base::Unretained(this), callback)); } void ClearHttpAndMediaCaches(
diff --git a/chrome/browser/browsing_data/browsing_data_service_worker_helper.cc b/chrome/browser/browsing_data/browsing_data_service_worker_helper.cc index 74dfef3..260a6fb4 100644 --- a/chrome/browser/browsing_data/browsing_data_service_worker_helper.cc +++ b/chrome/browser/browsing_data/browsing_data_service_worker_helper.cc
@@ -33,7 +33,7 @@ } BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(callback, result)); + base::BindOnce(callback, result)); } void EmptySuccessCallback(bool success) {} @@ -52,21 +52,20 @@ const FetchCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(!callback.is_null()); - BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, - base::Bind(&BrowsingDataServiceWorkerHelper:: - FetchServiceWorkerUsageInfoOnIOThread, - this, callback)); + BrowserThread::PostTask( + BrowserThread::IO, FROM_HERE, + base::BindOnce(&BrowsingDataServiceWorkerHelper:: + FetchServiceWorkerUsageInfoOnIOThread, + this, callback)); } void BrowsingDataServiceWorkerHelper::DeleteServiceWorkers(const GURL& origin) { DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserThread::PostTask( - BrowserThread::IO, - FROM_HERE, - base::Bind( + BrowserThread::IO, FROM_HERE, + base::BindOnce( &BrowsingDataServiceWorkerHelper::DeleteServiceWorkersOnIOThread, - this, - origin)); + this, origin)); } void BrowsingDataServiceWorkerHelper::FetchServiceWorkerUsageInfoOnIOThread( @@ -152,8 +151,8 @@ result.push_back(info); } - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, base::Bind(callback, result)); + BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, + base::BindOnce(callback, result)); } void CannedBrowsingDataServiceWorkerHelper::DeleteServiceWorkers(
diff --git a/chrome/browser/browsing_data/cache_counter_browsertest.cc b/chrome/browser/browsing_data/cache_counter_browsertest.cc index 2ac1e74..e2e0f76 100644 --- a/chrome/browser/browsing_data/cache_counter_browsertest.cc +++ b/chrome/browser/browsing_data/cache_counter_browsertest.cc
@@ -82,10 +82,9 @@ case DONE: { entry_->Close(); - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - base::Bind(&CacheCounterTest::Callback, - base::Unretained(this))); + BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, + base::BindOnce(&CacheCounterTest::Callback, + base::Unretained(this))); return; } } @@ -109,9 +108,8 @@ BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&CacheCounterTest::CreateCacheEntryStep, - base::Unretained(this), - net::OK)); + base::BindOnce(&CacheCounterTest::CreateCacheEntryStep, + base::Unretained(this), net::OK)); WaitForIOThread(); }
diff --git a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc index 6f644644..3452790 100644 --- a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc +++ b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc
@@ -485,9 +485,9 @@ clear_hostname_resolution_cache_.Start(); BrowserThread::PostTaskAndReply( BrowserThread::IO, FROM_HERE, - base::Bind(&ClearHostnameResolutionCacheOnIOThread, - g_browser_process->io_thread(), - filter_builder.BuildPluginFilter()), + base::BindOnce(&ClearHostnameResolutionCacheOnIOThread, + g_browser_process->io_thread(), + filter_builder.BuildPluginFilter()), clear_hostname_resolution_cache_.GetCompletionCallback()); } if (profile_->GetNetworkPredictor()) { @@ -495,8 +495,8 @@ clear_network_predictor_.Start(); BrowserThread::PostTaskAndReply( BrowserThread::IO, FROM_HERE, - base::Bind(&ClearNetworkPredictorOnIOThread, - profile_->GetNetworkPredictor()), + base::BindOnce(&ClearNetworkPredictorOnIOThread, + profile_->GetNetworkPredictor()), clear_network_predictor_.GetCompletionCallback()); profile_->GetNetworkPredictor()->ClearPrefsOnUIThread(); } @@ -566,7 +566,7 @@ // The above calls are done on the UI thread but do their work on the DB // thread. So wait for it. BrowserThread::PostTaskAndReply( - BrowserThread::DB, FROM_HERE, base::Bind(&base::DoNothing), + BrowserThread::DB, FROM_HERE, base::BindOnce(&base::DoNothing), clear_autofill_origin_urls_.GetCompletionCallback()); autofill::PersonalDataManager* data_manager = @@ -579,7 +579,7 @@ clear_webrtc_logs_.Start(); BrowserThread::PostTaskAndReply( BrowserThread::FILE, FROM_HERE, - base::Bind( + base::BindOnce( &WebRtcLogUtil::DeleteOldAndRecentWebRtcLogFiles, WebRtcLogList::GetWebRtcLogDirectoryForProfile(profile_->GetPath()), delete_begin_), @@ -675,24 +675,22 @@ if (filter_builder.IsEmptyBlacklist()) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind( + base::BindOnce( &ClearCookiesOnIOThread, delete_begin_, delete_end_, base::RetainedRef(std::move(sb_context)), - UIThreadTrampoline( - base::Bind( - &ChromeBrowsingDataRemoverDelegate::OnClearedCookies, - weak_ptr_factory_.GetWeakPtr())))); + UIThreadTrampoline(base::Bind( + &ChromeBrowsingDataRemoverDelegate::OnClearedCookies, + weak_ptr_factory_.GetWeakPtr())))); } else { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind( + base::BindOnce( &ClearCookiesWithPredicateOnIOThread, delete_begin_, delete_end_, filter_builder.BuildCookieFilter(), base::RetainedRef(std::move(sb_context)), - UIThreadTrampoline( - base::Bind( - &ChromeBrowsingDataRemoverDelegate::OnClearedCookies, - weak_ptr_factory_.GetWeakPtr())))); + UIThreadTrampoline(base::Bind( + &ChromeBrowsingDataRemoverDelegate::OnClearedCookies, + weak_ptr_factory_.GetWeakPtr())))); } } } @@ -750,8 +748,8 @@ clear_http_auth_cache_.Start(); BrowserThread::PostTaskAndReply( BrowserThread::IO, FROM_HERE, - base::Bind(&ClearHttpAuthCacheOnIOThread, std::move(request_context), - delete_begin_), + base::BindOnce(&ClearHttpAuthCacheOnIOThread, + std::move(request_context), delete_begin_), clear_http_auth_cache_.GetCompletionCallback()); } @@ -798,9 +796,9 @@ delete_begin_, delete_end_); // The above calls are done on the UI thread but do their work on the DB // thread. So wait for it. - BrowserThread::PostTaskAndReply( - BrowserThread::DB, FROM_HERE, base::Bind(&base::DoNothing), - clear_form_.GetCompletionCallback()); + BrowserThread::PostTaskAndReply(BrowserThread::DB, FROM_HERE, + base::BindOnce(&base::DoNothing), + clear_form_.GetCompletionCallback()); autofill::PersonalDataManager* data_manager = autofill::PersonalDataManagerFactory::GetForProfile(profile_); @@ -825,14 +823,14 @@ BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&ClearNaClCacheOnIOThread, - UIThreadTrampoline( - clear_nacl_cache_.GetCompletionCallback()))); + base::BindOnce( + &ClearNaClCacheOnIOThread, + UIThreadTrampoline(clear_nacl_cache_.GetCompletionCallback()))); clear_pnacl_cache_.Start(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind( + base::BindOnce( &ClearPnaclCacheOnIOThread, delete_begin_, delete_end_, UIThreadTrampoline(clear_pnacl_cache_.GetCompletionCallback()))); #endif
diff --git a/chrome/browser/browsing_data/site_data_counting_helper.cc b/chrome/browser/browsing_data/site_data_counting_helper.cc index b2908c7..9002e69 100644 --- a/chrome/browser/browsing_data/site_data_counting_helper.cc +++ b/chrome/browser/browsing_data/site_data_counting_helper.cc
@@ -49,8 +49,8 @@ // Count origins with cookies. BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&SiteDataCountingHelper::GetCookiesOnIOThread, - base::Unretained(this), make_scoped_refptr(rq_context))); + base::BindOnce(&SiteDataCountingHelper::GetCookiesOnIOThread, + base::Unretained(this), make_scoped_refptr(rq_context))); storage::QuotaManager* quota_manager = partition->GetQuotaManager(); if (quota_manager) { @@ -66,8 +66,8 @@ tasks_ += 1; BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&storage::QuotaManager::GetOriginsModifiedSince, - quota_manager, type, begin_, origins_callback)); + base::BindOnce(&storage::QuotaManager::GetOriginsModifiedSince, + quota_manager, type, begin_, origins_callback)); } } @@ -110,8 +110,8 @@ tasks_ += 1; BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&SiteDataCountingHelper::GetChannelIDsOnIOThread, - base::Unretained(this), make_scoped_refptr(rq_context))); + base::BindOnce(&SiteDataCountingHelper::GetChannelIDsOnIOThread, + base::Unretained(this), make_scoped_refptr(rq_context))); } void SiteDataCountingHelper::GetOriginsFromHostContentSettignsMap( @@ -142,8 +142,8 @@ } else { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, - base::Bind(&SiteDataCountingHelper::Done, base::Unretained(this), - std::vector<GURL>())); + base::BindOnce(&SiteDataCountingHelper::Done, base::Unretained(this), + std::vector<GURL>())); } } @@ -159,8 +159,8 @@ } } BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(&SiteDataCountingHelper::Done, - base::Unretained(this), origins)); + base::BindOnce(&SiteDataCountingHelper::Done, + base::Unretained(this), origins)); } void SiteDataCountingHelper::GetQuotaOriginsCallback( @@ -169,8 +169,8 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); std::vector<GURL> origins(origin_set.begin(), origin_set.end()); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(&SiteDataCountingHelper::Done, - base::Unretained(this), origins)); + base::BindOnce(&SiteDataCountingHelper::Done, + base::Unretained(this), origins)); } void SiteDataCountingHelper::GetLocalStorageUsageInfoCallback( @@ -228,8 +228,8 @@ } } BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(&SiteDataCountingHelper::Done, - base::Unretained(this), origins)); + base::BindOnce(&SiteDataCountingHelper::Done, + base::Unretained(this), origins)); } void SiteDataCountingHelper::Done(const std::vector<GURL>& origins) { @@ -241,6 +241,6 @@ if (--tasks_ > 0) return; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(completion_callback_, unique_origins_.size())); + FROM_HERE, base::BindOnce(completion_callback_, unique_origins_.size())); base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); }
diff --git a/chrome/browser/browsing_data/site_data_counting_helper_unittest.cc b/chrome/browser/browsing_data/site_data_counting_helper_unittest.cc index b7edb053..6938e5f 100644 --- a/chrome/browser/browsing_data/site_data_counting_helper_unittest.cc +++ b/chrome/browser/browsing_data/site_data_counting_helper_unittest.cc
@@ -57,8 +57,8 @@ return; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, - base::Bind(&SiteDataCountingHelperTest::DoneCallback, - base::Unretained(this))); + base::BindOnce(&SiteDataCountingHelperTest::DoneCallback, + base::Unretained(this))); } void DoneCallback() { @@ -81,9 +81,9 @@ partition->GetURLRequestContext(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&SiteDataCountingHelperTest::CreateCookiesOnIOThread, - base::Unretained(this), make_scoped_refptr(rq_context), - creation_time, urls)); + base::BindOnce(&SiteDataCountingHelperTest::CreateCookiesOnIOThread, + base::Unretained(this), make_scoped_refptr(rq_context), + creation_time, urls)); } void CreateLocalStorage(
diff --git a/chrome/browser/captive_portal/captive_portal_service.cc b/chrome/browser/captive_portal/captive_portal_service.cc index e9bbd46..4b6d636 100644 --- a/chrome/browser/captive_portal/captive_portal_service.cc +++ b/chrome/browser/captive_portal/captive_portal_service.cc
@@ -18,6 +18,7 @@ #include "components/prefs/pref_service.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" +#include "net/traffic_annotation/network_traffic_annotation.h" #if defined(OS_WIN) #include "base/win/windows_version.h" @@ -238,10 +239,39 @@ return; } + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("captive_portal_service", R"( + semantics { + sender: "Captive Portal Service" + description: + "Checks if the system is behind a captive portal. To do so, makes" + "an unlogged, dataless connection to a Google server and checks" + "the response." + trigger: + "It is triggered on multiple cases: It is run on certain SSL " + "errors (ERR_CONNECTION_TIMED_OUT, ERR_SSL_PROTOCOL_ERROR, and all " + "SSL interstitials)." + data: "None." + destination: GOOGLE_OWNED_SERVICE + } + policy { + cookies_allowed: false + setting: + "Users can enable/disable this feature by toggling 'Use a web " + "service to resolve network errors' in Chromium settings under " + "Privacy. This feature is enabled by default." + chrome_policy { + AlternateErrorPagesEnabled { + policy_options {mode: MANDATORY} + AlternateErrorPagesEnabled: false + } + } + })"); captive_portal_detector_.DetectCaptivePortal( - test_url_, base::Bind( - &CaptivePortalService::OnPortalDetectionCompleted, - base::Unretained(this))); + test_url_, + base::Bind(&CaptivePortalService::OnPortalDetectionCompleted, + base::Unretained(this)), + traffic_annotation); } void CaptivePortalService::OnPortalDetectionCompleted(
diff --git a/chrome/browser/chromeos/net/network_portal_detector_impl.cc b/chrome/browser/chromeos/net/network_portal_detector_impl.cc index c3886f6..4b82822b 100644 --- a/chrome/browser/chromeos/net/network_portal_detector_impl.cc +++ b/chrome/browser/chromeos/net/network_portal_detector_impl.cc
@@ -25,6 +25,7 @@ #include "content/public/browser/notification_service.h" #include "content/public/common/content_switches.h" #include "net/http/http_status_code.h" +#include "net/traffic_annotation/network_traffic_annotation.h" #include "third_party/cros_system_api/dbus/service_constants.h" using base::StringPrintf; @@ -446,7 +447,8 @@ captive_portal_detector_->DetectCaptivePortal( portal_test_url_, base::Bind(&NetworkPortalDetectorImpl::OnAttemptCompleted, - weak_factory_.GetWeakPtr())); + weak_factory_.GetWeakPtr()), + NO_TRAFFIC_ANNOTATION_YET); attempt_timeout_.Reset( base::Bind(&NetworkPortalDetectorImpl::OnAttemptTimeout, weak_factory_.GetWeakPtr()));
diff --git a/chrome/browser/chromeos/policy/device_cloud_policy_browsertest.cc b/chrome/browser/chromeos/policy/device_cloud_policy_browsertest.cc index 118d92ea..80fb61b 100644 --- a/chrome/browser/chromeos/policy/device_cloud_policy_browsertest.cc +++ b/chrome/browser/chromeos/policy/device_cloud_policy_browsertest.cc
@@ -32,7 +32,7 @@ #include "chrome/browser/policy/test/local_policy_test_server.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" -#include "chrome/common/chrome_constants.cc" +#include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h"
diff --git a/chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos.cc b/chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos.cc index 882f8e6..b0701037 100644 --- a/chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos.cc +++ b/chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos.cc
@@ -71,7 +71,8 @@ CloudPolicyValidatorBase::TIMESTAMP_FULLY_VALIDATED, CloudPolicyValidatorBase::DM_TOKEN_REQUIRED, CloudPolicyValidatorBase::DEVICE_ID_REQUIRED); - validator.release()->StartValidation( + DeviceCloudPolicyValidator::StartValidation( + std::move(validator), base::Bind(&DeviceCloudPolicyStoreChromeOS::OnPolicyToStoreValidated, weak_factory_.GetWeakPtr())); } @@ -94,7 +95,8 @@ std::unique_ptr<DeviceCloudPolicyValidator> validator( CreateValidator(policy)); validator->ValidateInitialKey(install_attributes_->GetDomain()); - validator.release()->StartValidation( + DeviceCloudPolicyValidator::StartValidation( + std::move(validator), base::Bind(&DeviceCloudPolicyStoreChromeOS::OnPolicyToStoreValidated, weak_factory_.GetWeakPtr())); } @@ -113,8 +115,7 @@ const em::PolicyFetchResponse& policy) { std::unique_ptr<DeviceCloudPolicyValidator> validator( DeviceCloudPolicyValidator::Create( - std::unique_ptr<em::PolicyFetchResponse>( - new em::PolicyFetchResponse(policy)), + base::MakeUnique<em::PolicyFetchResponse>(policy), background_task_runner_)); validator->ValidateDomain(install_attributes_->GetDomain()); validator->ValidatePolicyType(dm_protocol::kChromeDevicePolicyType);
diff --git a/chrome/browser/chromeos/policy/device_local_account_policy_store.cc b/chrome/browser/chromeos/policy/device_local_account_policy_store.cc index 31f42df..7bb6c4b 100644 --- a/chrome/browser/chromeos/policy/device_local_account_policy_store.cc +++ b/chrome/browser/chromeos/policy/device_local_account_policy_store.cc
@@ -212,10 +212,8 @@ validator->ValidateSignature(key->as_string()); if (validate_in_background) { - // The Validator will delete itself once validation is - // complete. - validator.release()->StartValidation( - base::Bind(callback, key->as_string())); + UserCloudPolicyValidator::StartValidation( + std::move(validator), base::Bind(callback, key->as_string())); } else { validator->RunValidation();
diff --git a/chrome/browser/chromeos/policy/enrollment_handler_chromeos.cc b/chrome/browser/chromeos/policy/enrollment_handler_chromeos.cc index a626d90f..23e9cf98 100644 --- a/chrome/browser/chromeos/policy/enrollment_handler_chromeos.cc +++ b/chrome/browser/chromeos/policy/enrollment_handler_chromeos.cc
@@ -10,6 +10,7 @@ #include "base/command_line.h" #include "base/location.h" #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/browser_process.h" @@ -195,8 +196,7 @@ std::unique_ptr<DeviceCloudPolicyValidator> validator( DeviceCloudPolicyValidator::Create( - std::unique_ptr<em::PolicyFetchResponse>( - new em::PolicyFetchResponse(*policy)), + base::MakeUnique<em::PolicyFetchResponse>(*policy), background_task_runner_)); validator->ValidateTimestamp( @@ -221,7 +221,8 @@ // can validate the username on the resulting policy, and use the domain from // that username to validate the key below (http://crbug.com/343074). validator->ValidateInitialKey(domain); - validator.release()->StartValidation( + DeviceCloudPolicyValidator::StartValidation( + std::move(validator), base::Bind(&EnrollmentHandlerChromeOS::HandlePolicyValidationResult, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.cc b/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.cc index f73ec0c..5ede872 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.cc
@@ -14,6 +14,7 @@ #include "base/location.h" #include "base/logging.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/sequenced_task_runner.h" #include "base/stl_util.h" @@ -161,9 +162,9 @@ cached_policy_key_, ExtractDomain(account_id_.GetUserEmail())); } - // Start validation. The Validator will delete itself once validation is - // complete. - validator.release()->StartValidation( + // Start validation. + UserCloudPolicyValidator::StartValidation( + std::move(validator), base::Bind(&UserCloudPolicyStoreChromeOS::OnPolicyToStoreValidated, weak_factory_.GetWeakPtr())); } @@ -245,12 +246,8 @@ void UserCloudPolicyStoreChromeOS::ValidateRetrievedPolicy( std::unique_ptr<em::PolicyFetchResponse> policy) { - // Create and configure a validator for the loaded policy. - std::unique_ptr<UserCloudPolicyValidator> validator = - CreateValidatorForLoad(std::move(policy)); - // Start validation. The Validator will delete itself once validation is - // complete. - validator.release()->StartValidation( + UserCloudPolicyValidator::StartValidation( + CreateValidatorForLoad(std::move(policy)), base::Bind(&UserCloudPolicyStoreChromeOS::OnRetrievedPolicyValidated, weak_factory_.GetWeakPtr())); }
diff --git a/chrome/browser/chromeos/settings/session_manager_operation.cc b/chrome/browser/chromeos/settings/session_manager_operation.cc index ed847589..bdd59b6 100644 --- a/chrome/browser/chromeos/settings/session_manager_operation.cc +++ b/chrome/browser/chromeos/settings/session_manager_operation.cc
@@ -165,9 +165,8 @@ base::SequencedWorkerPool::SKIP_ON_SHUTDOWN); std::unique_ptr<policy::DeviceCloudPolicyValidator> validator = - base::WrapUnique<policy::DeviceCloudPolicyValidator>( - policy::DeviceCloudPolicyValidator::Create(std::move(policy), - background_task_runner)); + policy::DeviceCloudPolicyValidator::Create(std::move(policy), + background_task_runner); if (cloud_validations_) { // Policy auto-generated by session manager doesn't include a timestamp, so @@ -206,8 +205,8 @@ validator->RunValidation(); ReportValidatorStatus(validator.get()); } else { - // The Validator will delete itself once validation is complete. - validator.release()->StartValidation( + policy::DeviceCloudPolicyValidator::StartValidation( + std::move(validator), base::Bind(&SessionManagerOperation::ReportValidatorStatus, weak_factory_.GetWeakPtr())); }
diff --git a/chrome/browser/extensions/extension_crash_recovery_browsertest.cc b/chrome/browser/extensions/extension_crash_recovery_browsertest.cc index e9aedef..29b53ae4 100644 --- a/chrome/browser/extensions/extension_crash_recovery_browsertest.cc +++ b/chrome/browser/extensions/extension_crash_recovery_browsertest.cc
@@ -31,7 +31,7 @@ #include "extensions/browser/process_map.h" #include "extensions/browser/test_extension_registry_observer.h" #include "extensions/common/constants.h" -#include "extensions/test/background_page_watcher.cc" +#include "extensions/test/background_page_watcher.h" #include "ui/message_center/message_center.h" #include "ui/message_center/notification_list.h"
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index b10057ec..dc70967 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -811,10 +811,14 @@ "Enable SharedArrayBuffer support in JavaScript."; const char kEnableWasmName[] = "WebAssembly structured cloning support."; - const char kEnableWasmDescription[] = "Enable web pages to use WebAssembly structured cloning."; +const char kEnableWasmStreamingName[] = + "WebAssembly streaming compile/instantiate support."; +const char kEnableWasmStreamingDescription[] = + "WebAssembly.{compile|instantiate} taking a Response as parameter."; + #if defined(OS_ANDROID) const char kMediaDocumentDownloadButtonName[] = @@ -2513,6 +2517,13 @@ "unless they are same-origin or the iframe is processing a user " "gesture."; +const char kVibrateRequiresUserGestureName[] = + "Requiring user gesture for the Vibration API"; + +const char kVibrateRequiresUserGestureDescription[] = + "Block the Vibration API if no user gesture has been received on " + "the frame or any embedded frame."; + #if defined(OS_ANDROID) const char kEnableVrShellName[] = "Enable Chrome VR.";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index c22a1b7..3edd7a2d 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -510,6 +510,12 @@ // direction in which the handle is dragged. extern const char kTouchSelectionStrategyDirection[]; +// Name of the flag that requires a user gesture for vibrate. +extern const char kVibrateRequiresUserGestureName[]; + +// Description of the flag that requires a user gesture for vibrate. +extern const char kVibrateRequiresUserGestureDescription[]; + // Title for the flag to use the Online Wallet sandbox servers (instead of // production). extern const char kWalletServiceUseSandboxName[]; @@ -896,6 +902,13 @@ // Description for the flag to enable WebAssembly. extern const char kEnableWasmDescription[]; +// Title for the flag to enable WebAssembly streaming compilation/instantiation. +extern const char kEnableWasmStreamingName[]; + +// Description for the flag to enable WebAssembly streaming +// compilation/instantiation. +extern const char kEnableWasmStreamingDescription[]; + #if defined(OS_ANDROID) // Title for the flag to enable the download button on MediaDocument.
diff --git a/chrome/browser/media/webrtc/webrtc_video_quality_browsertest.cc b/chrome/browser/media/webrtc/webrtc_video_quality_browsertest.cc index 5f10376..f7931d25 100644 --- a/chrome/browser/media/webrtc/webrtc_video_quality_browsertest.cc +++ b/chrome/browser/media/webrtc/webrtc_video_quality_browsertest.cc
@@ -344,19 +344,11 @@ IN_PROC_BROWSER_TEST_P(WebRtcVideoQualityBrowserTest, MANUAL_TestVideoQualityVp8) { -// Disable these tests until crbug.com/711400 is addressed. -#if defined(OS_MACOSX) - return; -#endif // defined(OS_MACOSX) TestVideoQuality("VP8"); } IN_PROC_BROWSER_TEST_P(WebRtcVideoQualityBrowserTest, MANUAL_TestVideoQualityVp9) { -// Disable these tests until crbug.com/711400 is addressed. -#if defined(OS_MACOSX) - return; -#endif // defined(OS_MACOSX) TestVideoQuality("VP9"); } @@ -364,10 +356,6 @@ IN_PROC_BROWSER_TEST_P(WebRtcVideoQualityBrowserTest, MANUAL_TestVideoQualityH264) { -// Disable these tests until crbug.com/711400 is addressed. -#if defined(OS_MACOSX) - return; -#endif // defined(OS_MACOSX) // Only run test if run-time feature corresponding to |rtc_use_h264| is on. if (!base::FeatureList::IsEnabled(content::kWebRtcH264WithOpenH264FFmpeg)) { LOG(WARNING) << "Run-time feature WebRTC-H264WithOpenH264FFmpeg disabled. "
diff --git a/chrome/browser/password_manager/native_backend_gnome_x.cc b/chrome/browser/password_manager/native_backend_gnome_x.cc index a51f1d3..9418e71 100644 --- a/chrome/browser/password_manager/native_backend_gnome_x.cc +++ b/chrome/browser/password_manager/native_backend_gnome_x.cc
@@ -494,10 +494,10 @@ bool NativeBackendGnome::RawAddLogin(const PasswordForm& form) { DCHECK_CURRENTLY_ON(BrowserThread::DB); GKRMethod method; - BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(&GKRMethod::AddLogin, - base::Unretained(&method), - form, app_string_.c_str())); + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::BindOnce(&GKRMethod::AddLogin, base::Unretained(&method), form, + app_string_.c_str())); GnomeKeyringResult result = method.WaitResult(); if (result != GNOME_KEYRING_RESULT_OK) { LOG(ERROR) << "Keyring save failed: " @@ -516,10 +516,10 @@ // delete might actually delete the newly-added entry! DCHECK_CURRENTLY_ON(BrowserThread::DB); GKRMethod method; - BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(&GKRMethod::LoginSearch, - base::Unretained(&method), - form, app_string_.c_str())); + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::BindOnce(&GKRMethod::LoginSearch, base::Unretained(&method), form, + app_string_.c_str())); std::vector<std::unique_ptr<PasswordForm>> forms; GnomeKeyringResult result = method.WaitResult(&forms); if (result != GNOME_KEYRING_RESULT_OK && @@ -561,10 +561,10 @@ DCHECK_CURRENTLY_ON(BrowserThread::DB); DCHECK(changes); GKRMethod method; - BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(&GKRMethod::LoginSearch, - base::Unretained(&method), - form, app_string_.c_str())); + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::BindOnce(&GKRMethod::LoginSearch, base::Unretained(&method), form, + app_string_.c_str())); std::vector<std::unique_ptr<PasswordForm>> forms; GnomeKeyringResult result = method.WaitResult(&forms); if (result == GNOME_KEYRING_RESULT_NO_MATCH) @@ -601,10 +601,10 @@ DCHECK_CURRENTLY_ON(BrowserThread::DB); DCHECK(changes); GKRMethod method; - BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(&GKRMethod::RemoveLogin, - base::Unretained(&method), - form, app_string_.c_str())); + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::BindOnce(&GKRMethod::RemoveLogin, base::Unretained(&method), form, + app_string_.c_str())); GnomeKeyringResult result = method.WaitResult(); if (result == GNOME_KEYRING_RESULT_NO_MATCH) return true; @@ -657,10 +657,10 @@ std::vector<std::unique_ptr<PasswordForm>>* forms) { DCHECK_CURRENTLY_ON(BrowserThread::DB); GKRMethod method; - BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(&GKRMethod::GetLogins, - base::Unretained(&method), - form, app_string_.c_str())); + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::BindOnce(&GKRMethod::GetLogins, base::Unretained(&method), form, + app_string_.c_str())); GnomeKeyringResult result = method.WaitResult(forms); if (result == GNOME_KEYRING_RESULT_NO_MATCH) return true; @@ -690,10 +690,10 @@ uint32_t blacklisted_by_user = !autofillable; GKRMethod method; - BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(&GKRMethod::GetLoginsList, - base::Unretained(&method), - blacklisted_by_user, app_string_.c_str())); + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::BindOnce(&GKRMethod::GetLoginsList, base::Unretained(&method), + blacklisted_by_user, app_string_.c_str())); GnomeKeyringResult result = method.WaitResult(forms); if (result == GNOME_KEYRING_RESULT_NO_MATCH) return true; @@ -725,10 +725,10 @@ bool NativeBackendGnome::GetAllLogins( std::vector<std::unique_ptr<PasswordForm>>* forms) { GKRMethod method; - BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - base::Bind(&GKRMethod::GetAllLogins, - base::Unretained(&method), - app_string_.c_str())); + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::BindOnce(&GKRMethod::GetAllLogins, base::Unretained(&method), + app_string_.c_str())); GnomeKeyringResult result = method.WaitResult(forms); if (result == GNOME_KEYRING_RESULT_NO_MATCH) return true;
diff --git a/chrome/browser/password_manager/native_backend_gnome_x_unittest.cc b/chrome/browser/password_manager/native_backend_gnome_x_unittest.cc index e6b63a3..fd20058 100644 --- a/chrome/browser/password_manager/native_backend_gnome_x_unittest.cc +++ b/chrome/browser/password_manager/native_backend_gnome_x_unittest.cc
@@ -438,7 +438,7 @@ // That way we can run both loops and be sure that the UI thread loop will // quit so we can get on with the rest of the test. BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, - base::Bind(&PostQuitTask, &message_loop_)); + base::BindOnce(&PostQuitTask, &message_loop_)); base::RunLoop().Run(); } @@ -528,11 +528,9 @@ backend.Init(); BrowserThread::PostTask( - BrowserThread::DB, - FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), - credentials)); + BrowserThread::DB, FROM_HERE, + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), credentials)); PasswordStore::FormDigest target_form = {scheme, url.spec(), url}; if (scheme != PasswordForm::SCHEME_HTML) { @@ -609,11 +607,9 @@ // Add the PSL-matched copy to saved logins. BrowserThread::PostTask( - BrowserThread::DB, - FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), - m_facebook)); + BrowserThread::DB, FROM_HERE, + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), m_facebook)); RunBothThreads(); EXPECT_EQ(2u, mock_keyring_items.size()); @@ -732,17 +728,13 @@ } BrowserThread::PostTask( - BrowserThread::DB, - FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), - form_google_)); + BrowserThread::DB, FROM_HERE, + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), form_google_)); BrowserThread::PostTask( - BrowserThread::DB, - FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), - form_isc_)); + BrowserThread::DB, FROM_HERE, + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), form_isc_)); PasswordStoreChangeList expected_changes; expected_changes.push_back( @@ -824,8 +816,8 @@ BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), form_google_)); std::vector<std::unique_ptr<PasswordForm>> form_list; BrowserThread::PostTaskAndReplyWithResult( @@ -938,8 +930,8 @@ // First add google login. BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), form_google_)); RunBothThreads(); @@ -975,8 +967,8 @@ BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), form_google_)); RunBothThreads(); @@ -1005,8 +997,8 @@ BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), form_google_)); RunBothThreads(); @@ -1038,8 +1030,8 @@ // First add an unrelated login. BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), form_google_)); RunBothThreads(); @@ -1081,8 +1073,8 @@ // First add an unrelated login. BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), form_google_)); RunBothThreads(); @@ -1114,8 +1106,8 @@ // First add an unrelated login. BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), form_google_)); RunBothThreads(); EXPECT_EQ(1u, mock_keyring_items.size()); @@ -1224,12 +1216,12 @@ BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), form_google_)); BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), form_facebook_)); + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), form_facebook_)); RunBothThreads(); @@ -1277,14 +1269,14 @@ GURL(std::string("http://www.google.com/") + unique_string); BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), form_google_)); form_google_.origin = GURL(std::string("http://www.google.com/") + unique_string_replacement); BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), form_google_)); RunBothThreads(); // Read the raw value back. Change the |unique_string| to @@ -1322,13 +1314,13 @@ BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), form_google_)); BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), form_facebook_)); + base::BindOnce(base::IgnoreResult(&NativeBackendGnome::AddLogin), + base::Unretained(&backend), form_facebook_)); std::vector<std::unique_ptr<PasswordForm>> form_list; BrowserThread::PostTaskAndReplyWithResult(
diff --git a/chrome/browser/password_manager/native_backend_kwallet_x.cc b/chrome/browser/password_manager/native_backend_kwallet_x.cc index 48e1953..db40e28 100644 --- a/chrome/browser/password_manager/native_backend_kwallet_x.cc +++ b/chrome/browser/password_manager/native_backend_kwallet_x.cc
@@ -308,8 +308,8 @@ // destroyed before that occurs, but that's OK. if (kwallet_dbus_.GetSessionBus()) { BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, - base::Bind(&dbus::Bus::ShutdownAndBlock, - kwallet_dbus_.GetSessionBus())); + base::BindOnce(&dbus::Bus::ShutdownAndBlock, + kwallet_dbus_.GetSessionBus())); } } @@ -327,10 +327,10 @@ base::WaitableEvent::InitialState::NOT_SIGNALED); // NativeBackendKWallet isn't reference counted, but we wait for InitWithBus // to finish, so we can safely use base::Unretained here. - BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, - base::Bind(&NativeBackendKWallet::InitOnDBThread, - base::Unretained(this), - optional_bus, &event, &success)); + BrowserThread::PostTask( + BrowserThread::DB, FROM_HERE, + base::BindOnce(&NativeBackendKWallet::InitOnDBThread, + base::Unretained(this), optional_bus, &event, &success)); // This ScopedAllowWait should not be here. http://crbug.com/125331 base::ThreadRestrictions::ScopedAllowWait allow_wait;
diff --git a/chrome/browser/password_manager/native_backend_kwallet_x_unittest.cc b/chrome/browser/password_manager/native_backend_kwallet_x_unittest.cc index 76ac3cb..3cdb043 100644 --- a/chrome/browser/password_manager/native_backend_kwallet_x_unittest.cc +++ b/chrome/browser/password_manager/native_backend_kwallet_x_unittest.cc
@@ -302,7 +302,7 @@ base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, - base::Bind(ThreadDone, &event)); + base::BindOnce(ThreadDone, &event)); event.Wait(); // Some of the tests may post messages to the UI thread, but we don't need // to run those until after the DB thread is finished. So run it here. @@ -439,17 +439,13 @@ } BrowserThread::PostTask( - BrowserThread::DB, - FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), - base::Unretained(&backend), - form_google_)); + BrowserThread::DB, FROM_HERE, + base::BindOnce(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), + base::Unretained(&backend), form_google_)); BrowserThread::PostTask( - BrowserThread::DB, - FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), - base::Unretained(&backend), - form_isc_)); + BrowserThread::DB, FROM_HERE, + base::BindOnce(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), + base::Unretained(&backend), form_isc_)); PasswordStoreChangeList expected_changes; expected_changes.push_back( @@ -737,8 +733,8 @@ BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), + base::Unretained(&backend), form_google_)); RunDBThread(); @@ -776,8 +772,8 @@ BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), + base::Unretained(&backend), form_google_)); std::vector<std::unique_ptr<PasswordForm>> form_list; BrowserThread::PostTaskAndReplyWithResult( @@ -806,8 +802,8 @@ BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), + base::Unretained(&backend), form_google_)); RunDBThread(); @@ -841,8 +837,8 @@ // First add an unrelated login. BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), + base::Unretained(&backend), form_google_)); RunDBThread(); @@ -876,8 +872,8 @@ // First add an unrelated login. BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), + base::Unretained(&backend), form_google_)); RunDBThread(); @@ -1011,12 +1007,12 @@ BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendKWallet::AddLogin), - base::Unretained(&backend), form_isc_)); + base::BindOnce(base::IgnoreResult(&NativeBackendKWallet::AddLogin), + base::Unretained(&backend), form_isc_)); BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendKWallet::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendKWallet::AddLogin), + base::Unretained(&backend), form_google_)); RunDBThread(); @@ -1060,14 +1056,14 @@ GURL(std::string("http://www.google.com/") + unique_string); BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), + base::Unretained(&backend), form_google_)); form_google_.origin = GURL(std::string("http://www.google.com/") + unique_string_replacement); BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), + base::Unretained(&backend), form_google_)); RunDBThread(); // Read the raw value back. Change the |unique_string| to @@ -1119,9 +1115,10 @@ // Verify that nothing is in fact returned, because KWallet fails to respond. std::vector<std::unique_ptr<PasswordForm>> form_list; - BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, - base::Bind(&CheckGetAutofillableLoginsFails, - base::Unretained(&backend), &form_list)); + BrowserThread::PostTask( + BrowserThread::DB, FROM_HERE, + base::BindOnce(&CheckGetAutofillableLoginsFails, + base::Unretained(&backend), &form_list)); RunDBThread(); EXPECT_EQ(0u, form_list.size()); } @@ -1132,12 +1129,12 @@ BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), - base::Unretained(&backend), form_google_)); + base::BindOnce(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), + base::Unretained(&backend), form_google_)); BrowserThread::PostTask( BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), - base::Unretained(&backend), form_isc_)); + base::BindOnce(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), + base::Unretained(&backend), form_isc_)); std::vector<std::unique_ptr<PasswordForm>> form_list; BrowserThread::PostTaskAndReplyWithResult(
diff --git a/chrome/browser/password_manager/password_manager_browsertest.cc b/chrome/browser/password_manager/password_manager_browsertest.cc index 9900a90..cd2e699 100644 --- a/chrome/browser/password_manager/password_manager_browsertest.cc +++ b/chrome/browser/password_manager/password_manager_browsertest.cc
@@ -1556,9 +1556,9 @@ // migration is completed. const auto empty_lambda = []() {}; base::RunLoop run_loop; - content::BrowserThread::PostTaskAndReply(content::BrowserThread::IO, - FROM_HERE, base::Bind(empty_lambda), - run_loop.QuitClosure()); + content::BrowserThread::PostTaskAndReply( + content::BrowserThread::IO, FROM_HERE, base::BindOnce(empty_lambda), + run_loop.QuitClosure()); run_loop.Run(); // Only HTTPS passwords should be present.
diff --git a/chrome/browser/password_manager/password_manager_test_base.cc b/chrome/browser/password_manager/password_manager_test_base.cc index 8e153ee..7b91a84 100644 --- a/chrome/browser/password_manager/password_manager_test_base.cc +++ b/chrome/browser/password_manager/password_manager_test_base.cc
@@ -460,9 +460,9 @@ content::BrowserThread::PostTaskAndReply( content::BrowserThread::IO, FROM_HERE, - base::Bind(&AddHSTSHostImpl, - make_scoped_refptr(browser()->profile()->GetRequestContext()), - host), + base::BindOnce( + &AddHSTSHostImpl, + make_scoped_refptr(browser()->profile()->GetRequestContext()), host), run_loop.QuitClosure()); run_loop.Run();
diff --git a/chrome/browser/predictors/resource_prefetch_predictor_unittest.cc b/chrome/browser/predictors/resource_prefetch_predictor_unittest.cc index d9b6f670..0a517a0 100644 --- a/chrome/browser/predictors/resource_prefetch_predictor_unittest.cc +++ b/chrome/browser/predictors/resource_prefetch_predictor_unittest.cc
@@ -71,7 +71,6 @@ protected: void Start() override { NotifyHeadersComplete(); } - int GetResponseCode() const override { return 200; } void GetResponseInfo(net::HttpResponseInfo* info) override { *info = response_info_; }
diff --git a/chrome/browser/resources/snippets_internals.html b/chrome/browser/resources/snippets_internals.html index 118b8b3e..f7d2bae5b 100644 --- a/chrome/browser/resources/snippets_internals.html +++ b/chrome/browser/resources/snippets_internals.html
@@ -144,6 +144,11 @@ <td>URL <td><a class="url" jsvalues="href:url" jscontent="url"></a> <tr> + <td>URL with favicon + <td> + <a class="url" jsvalues="href:urlWithFavicon" + jscontent="urlWithFavicon"></a> + <tr> <td>Snippet text <td jscontent="snippetText"> <tr>
diff --git a/chrome/browser/safe_browsing/certificate_reporting_service_test_utils.cc b/chrome/browser/safe_browsing/certificate_reporting_service_test_utils.cc index 584a8ec9..998d8903 100644 --- a/chrome/browser/safe_browsing/certificate_reporting_service_test_utils.cc +++ b/chrome/browser/safe_browsing/certificate_reporting_service_test_utils.cc
@@ -186,11 +186,6 @@ return 0; } -int DelayableCertReportURLRequestJob::GetResponseCode() const { - // Report sender ignores responses. Return empty response. - return 200; -} - void DelayableCertReportURLRequestJob::GetResponseInfo( net::HttpResponseInfo* info) { // Report sender ignores responses. Return empty response.
diff --git a/chrome/browser/safe_browsing/certificate_reporting_service_test_utils.h b/chrome/browser/safe_browsing/certificate_reporting_service_test_utils.h index fb2bd9d..4ac99fa 100644 --- a/chrome/browser/safe_browsing/certificate_reporting_service_test_utils.h +++ b/chrome/browser/safe_browsing/certificate_reporting_service_test_utils.h
@@ -116,7 +116,6 @@ // net::URLRequestJob methods: void Start() override; int ReadRawData(net::IOBuffer* buf, int buf_size) override; - int GetResponseCode() const override; void GetResponseInfo(net::HttpResponseInfo* info) override; // Resumes a previously started request that was delayed. If no
diff --git a/chrome/browser/ssl/ssl_browser_tests.cc b/chrome/browser/ssl/ssl_browser_tests.cc index cadbe9d3..ea4f477 100644 --- a/chrome/browser/ssl/ssl_browser_tests.cc +++ b/chrome/browser/ssl/ssl_browser_tests.cc
@@ -2939,8 +2939,6 @@ return bytes_read; } - int GetResponseCode() const override { return 200; } - void GetResponseInfo(net::HttpResponseInfo* info) override { std::string headers; headers.append(
diff --git a/chrome/browser/sync/test/integration/sessions_helper.cc b/chrome/browser/sync/test/integration/sessions_helper.cc index 70d3055..36fb6095 100644 --- a/chrome/browser/sync/test/integration/sessions_helper.cc +++ b/chrome/browser/sync/test/integration/sessions_helper.cc
@@ -37,7 +37,7 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/test/browser_test_utils.cc" +#include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" #include "url/gurl.h"
diff --git a/chrome/browser/ui/sync/tab_contents_synced_tab_delegate_unittest.cc b/chrome/browser/ui/sync/tab_contents_synced_tab_delegate_unittest.cc index 2e59b90..4345fc1b 100644 --- a/chrome/browser/ui/sync/tab_contents_synced_tab_delegate_unittest.cc +++ b/chrome/browser/ui/sync/tab_contents_synced_tab_delegate_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/ui/sync/tab_contents_synced_tab_delegate.cc" +#include "chrome/browser/ui/sync/tab_contents_synced_tab_delegate.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/ui/views/harmony/harmony_layout_provider.cc b/chrome/browser/ui/views/harmony/harmony_layout_provider.cc index 3a9a0d58..35a53b1 100644 --- a/chrome/browser/ui/views/harmony/harmony_layout_provider.cc +++ b/chrome/browser/ui/views/harmony/harmony_layout_provider.cc
@@ -11,6 +11,7 @@ case views::INSETS_PANEL: case views::INSETS_BUBBLE_CONTENTS: return gfx::Insets(kHarmonyLayoutUnit); + case views::INSETS_BUBBLE_TITLE: case views::INSETS_DIALOG_TITLE: { constexpr int top = kHarmonyLayoutUnit; constexpr int side = kHarmonyLayoutUnit;
diff --git a/chrome/browser/ui/views/passwords/manage_passwords_bubble_view.cc b/chrome/browser/ui/views/passwords/manage_passwords_bubble_view.cc index cb65bf6..5f5471b9 100644 --- a/chrome/browser/ui/views/passwords/manage_passwords_bubble_view.cc +++ b/chrome/browser/ui/views/passwords/manage_passwords_bubble_view.cc
@@ -15,7 +15,6 @@ #include "chrome/browser/ui/passwords/password_dialog_prompts.h" #include "chrome/browser/ui/passwords/passwords_model_delegate.h" #include "chrome/browser/ui/views/frame/browser_view.h" -#include "chrome/browser/ui/views/harmony/chrome_layout_provider.h" #include "chrome/browser/ui/views/passwords/credentials_item_view.h" #include "chrome/browser/ui/views/passwords/credentials_selection_view.h" #include "chrome/browser/ui/views/passwords/manage_password_items_view.h" @@ -768,11 +767,6 @@ : ManagePasswordsBubbleModel::USER_ACTION), initially_focused_view_(nullptr) { mouse_handler_.reset(new WebContentMouseHandler(this, this->web_contents())); - // Set title margins to make the title and the content left aligned. - const int side_margin = margins().left(); - set_title_margins(gfx::Insets(ChromeLayoutProvider::Get()->GetDistanceMetric( - DISTANCE_PANEL_CONTENT_MARGIN), - side_margin, 0, side_margin)); } ManagePasswordsBubbleView::~ManagePasswordsBubbleView() {
diff --git a/chrome/browser/ui/views/passwords/manage_passwords_bubble_view_browsertest.cc b/chrome/browser/ui/views/passwords/manage_passwords_bubble_view_browsertest.cc new file mode 100644 index 0000000..f3c3a6f --- /dev/null +++ b/chrome/browser/ui/views/passwords/manage_passwords_bubble_view_browsertest.cc
@@ -0,0 +1,48 @@ +// 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/views/passwords/manage_passwords_bubble_view.h" + +#include "base/macros.h" +#include "chrome/browser/ui/passwords/manage_passwords_test.h" +#include "chrome/browser/ui/test/test_browser_dialog.h" + +class ManagePasswordsBubbleDialogViewTest + : public SupportsTestDialog<ManagePasswordsTest> { + public: + ManagePasswordsBubbleDialogViewTest() {} + ~ManagePasswordsBubbleDialogViewTest() override {} + + void ShowDialog(const std::string& name) override { + if (name == "PendingPasswordBubble") { + SetupPendingPassword(); + } else if (name == "AutomaticPasswordBubble") { + SetupAutomaticPassword(); + } else if (name == "ManagePasswordBubble") { + SetupManagingPasswords(); + ExecuteManagePasswordsCommand(); + } else { + ADD_FAILURE() << "Unknown dialog type"; + return; + } + } + + private: + DISALLOW_COPY_AND_ASSIGN(ManagePasswordsBubbleDialogViewTest); +}; + +IN_PROC_BROWSER_TEST_F(ManagePasswordsBubbleDialogViewTest, + InvokeDialog_PendingPasswordBubble) { + RunDialog(); +} + +IN_PROC_BROWSER_TEST_F(ManagePasswordsBubbleDialogViewTest, + InvokeDialog_AutomaticPasswordBubble) { + RunDialog(); +} + +IN_PROC_BROWSER_TEST_F(ManagePasswordsBubbleDialogViewTest, + InvokeDialog_ManagePasswordBubble) { + RunDialog(); +}
diff --git a/chrome/browser/ui/views/passwords/password_dialog_view_browsertest.cc b/chrome/browser/ui/views/passwords/password_dialog_view_browsertest.cc index c6b8463..7e57353 100644 --- a/chrome/browser/ui/views/passwords/password_dialog_view_browsertest.cc +++ b/chrome/browser/ui/views/passwords/password_dialog_view_browsertest.cc
@@ -9,6 +9,7 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/passwords/manage_passwords_ui_controller.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/browser/ui/test/test_browser_dialog.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/passwords/account_chooser_dialog_view.h" #include "chrome/browser/ui/views/passwords/auto_signin_first_run_dialog_view.h" @@ -137,10 +138,11 @@ return current_autosignin_prompt_; } -class PasswordDialogViewTest : public InProcessBrowserTest { +class PasswordDialogViewTest : public DialogBrowserTest { public: - // InProcessBrowserTest: + // DialogBrowserTest: void SetUpOnMainThread() override; + void ShowDialog(const std::string& name) override; void SetupChooseCredentials( std::vector<std::unique_ptr<autofill::PasswordForm>> local_credentials, @@ -211,7 +213,7 @@ local_credentials.push_back(base::MakeUnique<autofill::PasswordForm>(form)); GURL icon_url("https://google.com/icon.png"); form.icon_url = icon_url; - form.display_name = base::ASCIIToUTF16("Peter Pen"); + form.display_name = base::ASCIIToUTF16("Peter Pan"); form.federation_origin = url::Origin(GURL("https://google.com/federation")); local_credentials.push_back(base::MakeUnique<autofill::PasswordForm>(form)); @@ -247,7 +249,7 @@ local_credentials.push_back(base::MakeUnique<autofill::PasswordForm>(form)); GURL icon_url("https://google.com/icon.png"); form.icon_url = icon_url; - form.display_name = base::ASCIIToUTF16("Peter Pen"); + form.display_name = base::ASCIIToUTF16("Peter Pan"); form.federation_origin = url::Origin(GURL("https://google.com/federation")); local_credentials.push_back(base::MakeUnique<autofill::PasswordForm>(form)); @@ -465,4 +467,29 @@ ASSERT_TRUE(controller()->current_autosignin_prompt()); } +// DialogBrowserTest methods for interactive dialog invocation. +void PasswordDialogViewTest::ShowDialog(const std::string& name) { + GURL origin("https://example.com"); + EXPECT_EQ("PopupAutoSigninPrompt", name); + std::vector<std::unique_ptr<autofill::PasswordForm>> local_credentials; + autofill::PasswordForm form; + form.origin = origin; + form.display_name = base::ASCIIToUTF16("Peter"); + form.username_value = base::ASCIIToUTF16("peter@pan.test"); + form.icon_url = GURL("broken url"); + local_credentials.push_back(base::MakeUnique<autofill::PasswordForm>(form)); + GURL icon_url("https://google.com/icon.png"); + form.icon_url = icon_url; + form.display_name = base::ASCIIToUTF16("Peter Pan"); + form.federation_origin = url::Origin(GURL("https://google.com/federation")); + local_credentials.push_back(base::MakeUnique<autofill::PasswordForm>(form)); + SetupChooseCredentials(std::move(local_credentials), origin); + ASSERT_TRUE(controller()->current_account_chooser()); +} + +IN_PROC_BROWSER_TEST_F(PasswordDialogViewTest, + InvokeDialog_PopupAutoSigninPrompt) { + RunDialog(); +} + } // namespace
diff --git a/chrome/browser/ui/views/session_crashed_bubble_view.h b/chrome/browser/ui/views/session_crashed_bubble_view.h index 7ab7914..40323e7 100644 --- a/chrome/browser/ui/views/session_crashed_bubble_view.h +++ b/chrome/browser/ui/views/session_crashed_bubble_view.h
@@ -37,6 +37,8 @@ bool uma_opted_in_already); private: + friend class SessionCrashedBubbleViewTest; + SessionCrashedBubbleView(views::View* anchor_view, Browser* browser, bool offer_uma_optin);
diff --git a/chrome/browser/ui/views/session_crashed_bubble_view_browsertest.cc b/chrome/browser/ui/views/session_crashed_bubble_view_browsertest.cc new file mode 100644 index 0000000..938c5049 --- /dev/null +++ b/chrome/browser/ui/views/session_crashed_bubble_view_browsertest.cc
@@ -0,0 +1,37 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/views/session_crashed_bubble_view.h" + +#include <string> + +#include "chrome/browser/ui/test/test_browser_dialog.h" +#include "chrome/browser/ui/views/frame/browser_view.h" +#include "chrome/browser/ui/views/toolbar/app_menu_button.h" +#include "chrome/browser/ui/views/toolbar/toolbar_view.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "ui/views/view.h" + +class SessionCrashedBubbleViewTest : public DialogBrowserTest { + public: + SessionCrashedBubbleViewTest() {} + ~SessionCrashedBubbleViewTest() override {} + + void ShowDialog(const std::string& name) override { + views::View* anchor_view = BrowserView::GetBrowserViewForBrowser(browser()) + ->toolbar() + ->app_menu_button(); + SessionCrashedBubbleView* crash_bubble = + new SessionCrashedBubbleView(anchor_view, browser(), false); + views::BubbleDialogDelegateView::CreateBubble(crash_bubble)->Show(); + } + + private: + DISALLOW_COPY_AND_ASSIGN(SessionCrashedBubbleViewTest); +}; + +IN_PROC_BROWSER_TEST_F(SessionCrashedBubbleViewTest, + InvokeDialog_SessionCrashedBubble) { + RunDialog(); +}
diff --git a/chrome/browser/ui/webui/snippets_internals_message_handler.cc b/chrome/browser/ui/webui/snippets_internals_message_handler.cc index 9b77980..3c1b7eee 100644 --- a/chrome/browser/ui/webui/snippets_internals_message_handler.cc +++ b/chrome/browser/ui/webui/snippets_internals_message_handler.cc
@@ -53,6 +53,7 @@ auto entry = base::MakeUnique<base::DictionaryValue>(); entry->SetString("idWithinCategory", suggestion.id().id_within_category()); entry->SetString("url", suggestion.url().spec()); + entry->SetString("urlWithFavicon", suggestion.url_with_favicon().spec()); entry->SetString("title", suggestion.title()); entry->SetString("snippetText", suggestion.snippet_text()); entry->SetString("publishDate",
diff --git a/chrome/renderer/resources/extensions/app_custom_bindings.js b/chrome/renderer/resources/extensions/app_custom_bindings.js index b91705fb9..4d58054b 100644 --- a/chrome/renderer/resources/extensions/app_custom_bindings.js +++ b/chrome/renderer/resources/extensions/app_custom_bindings.js
@@ -4,13 +4,6 @@ // Custom binding for the app API. -var GetAvailability = requireNative('v8_context').GetAvailability; -if (!GetAvailability('app').is_available) { - exports.$set('binding', {}); - exports.$set('onInstallStateResponse', function(){}); - return; -} - var appNatives = requireNative('app'); var process = requireNative('process'); var extensionId = process.GetExtensionId();
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index bc1c20b..64ea782 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -2189,7 +2189,9 @@ "../browser/ui/views/frame/browser_non_client_frame_view_browsertest.cc", "../browser/ui/views/frame/browser_view_browsertest.cc", "../browser/ui/views/location_bar/zoom_bubble_view_browsertest.cc", + "../browser/ui/views/passwords/manage_passwords_bubble_view_browsertest.cc", "../browser/ui/views/passwords/password_dialog_view_browsertest.cc", + "../browser/ui/views/session_crashed_bubble_view_browsertest.cc", "../browser/ui/views/task_manager_view_browsertest.cc", "../browser/ui/views/toolbar/browser_actions_container_browsertest.cc", "../browser/ui/views/translate/translate_bubble_view_browsertest.cc",
diff --git a/chrome/test/data/android/google.html b/chrome/test/data/android/google.html index b51da78..a8a4457e 100644 --- a/chrome/test/data/android/google.html +++ b/chrome/test/data/android/google.html
@@ -26,11 +26,6 @@ <br> <a href="tel:10000000000" id="tel">1-000-000-0000</a> </br> - - -<br> -<a href="customtab://customtabtest/intent" id="customtab-external-link">Dummy External App Link</a> -</br> </body> </html>
diff --git a/components/captive_portal/captive_portal_detector.cc b/components/captive_portal/captive_portal_detector.cc index 04eb56643..6ec4df23 100644 --- a/components/captive_portal/captive_portal_detector.cc +++ b/components/captive_portal/captive_portal_detector.cc
@@ -27,7 +27,8 @@ void CaptivePortalDetector::DetectCaptivePortal( const GURL& url, - const DetectionCallback& detection_callback) { + const DetectionCallback& detection_callback, + const net::NetworkTrafficAnnotationTag& traffic_annotation) { DCHECK(CalledOnValidThread()); DCHECK(!FetchingURL()); DCHECK(detection_callback_.is_null()); @@ -35,7 +36,8 @@ detection_callback_ = detection_callback; // The first 0 means this can use a TestURLFetcherFactory in unit tests. - url_fetcher_ = net::URLFetcher::Create(0, url, net::URLFetcher::GET, this); + url_fetcher_ = net::URLFetcher::Create(0, url, net::URLFetcher::GET, this, + traffic_annotation); url_fetcher_->SetAutomaticallyRetryOn5xx(false); url_fetcher_->SetRequestContext(request_context_.get()); data_use_measurement::DataUseUserData::AttachToFetcher(
diff --git a/components/captive_portal/captive_portal_detector.h b/components/captive_portal/captive_portal_detector.h index 3cf1012..e25cd44 100644 --- a/components/captive_portal/captive_portal_detector.h +++ b/components/captive_portal/captive_portal_detector.h
@@ -15,6 +15,7 @@ #include "base/time/time.h" #include "components/captive_portal/captive_portal_export.h" #include "components/captive_portal/captive_portal_types.h" +#include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_delegate.h" #include "net/url_request/url_request_context_getter.h" @@ -54,7 +55,10 @@ // Triggers a check for a captive portal. After completion, runs the // |callback|. - void DetectCaptivePortal(const GURL& url, const DetectionCallback& callback); + void DetectCaptivePortal( + const GURL& url, + const DetectionCallback& callback, + const net::NetworkTrafficAnnotationTag& traffic_annotation); // Cancels captive portal check. void Cancel();
diff --git a/components/captive_portal/captive_portal_detector_unittest.cc b/components/captive_portal/captive_portal_detector_unittest.cc index 7eaa099f..1f9b169 100644 --- a/components/captive_portal/captive_portal_detector_unittest.cc +++ b/components/captive_portal/captive_portal_detector_unittest.cc
@@ -15,6 +15,7 @@ #include "base/time/time.h" #include "components/captive_portal/captive_portal_testing_utils.h" #include "net/base/net_errors.h" +#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -76,9 +77,11 @@ GURL url(CaptivePortalDetector::kDefaultURL); CaptivePortalClient client(detector()); - detector()->DetectCaptivePortal(url, + detector()->DetectCaptivePortal( + url, base::Bind(&CaptivePortalClient::OnPortalDetectionCompleted, - base::Unretained(&client))); + base::Unretained(&client)), + TRAFFIC_ANNOTATION_FOR_TESTS); ASSERT_TRUE(FetchingURL()); base::RunLoop().RunUntilIdle(); @@ -100,9 +103,11 @@ GURL url(CaptivePortalDetector::kDefaultURL); CaptivePortalClient client(detector()); - detector()->DetectCaptivePortal(url, + detector()->DetectCaptivePortal( + url, base::Bind(&CaptivePortalClient::OnPortalDetectionCompleted, - base::Unretained(&client))); + base::Unretained(&client)), + TRAFFIC_ANNOTATION_FOR_TESTS); ASSERT_TRUE(FetchingURL()); base::RunLoop().RunUntilIdle();
diff --git a/components/component_updater/component_updater_service_unittest.cc b/components/component_updater/component_updater_service_unittest.cc index c4e6199e..d833d200 100644 --- a/components/component_updater/component_updater_service_unittest.cc +++ b/components/component_updater/component_updater_service_unittest.cc
@@ -75,9 +75,11 @@ bool(const std::string& id, CrxUpdateItem* update_item)); MOCK_CONST_METHOD1(IsUpdating, bool(const std::string& id)); MOCK_METHOD0(Stop, void()); - MOCK_METHOD3( - SendUninstallPing, - void(const std::string& id, const base::Version& version, int reason)); + MOCK_METHOD4(SendUninstallPing, + void(const std::string& id, + const base::Version& version, + int reason, + const Callback& callback)); private: ~MockUpdateClient() override;
diff --git a/components/component_updater/default_component_installer_unittest.cc b/components/component_updater/default_component_installer_unittest.cc index 6045332..d9bb6d3 100644 --- a/components/component_updater/default_component_installer_unittest.cc +++ b/components/component_updater/default_component_installer_unittest.cc
@@ -59,9 +59,11 @@ bool(const std::string& id, CrxUpdateItem* update_item)); MOCK_CONST_METHOD1(IsUpdating, bool(const std::string& id)); MOCK_METHOD0(Stop, void()); - MOCK_METHOD3( - SendUninstallPing, - void(const std::string& id, const base::Version& version, int reason)); + MOCK_METHOD4(SendUninstallPing, + void(const std::string& id, + const base::Version& version, + int reason, + const Callback& callback)); private: ~MockUpdateClient() override {}
diff --git a/components/domain_reliability/uploader.cc b/components/domain_reliability/uploader.cc index 19dd56d..d997849 100644 --- a/components/domain_reliability/uploader.cc +++ b/components/domain_reliability/uploader.cc
@@ -16,6 +16,7 @@ #include "net/base/net_errors.h" #include "net/http/http_response_headers.h" #include "net/http/http_util.h" +#include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_delegate.h" #include "net/url_request/url_request_context_getter.h" @@ -83,8 +84,34 @@ return; } - std::unique_ptr<net::URLFetcher> owned_fetcher = - net::URLFetcher::Create(0, upload_url, net::URLFetcher::POST, this); + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("domain_reliability_report_upload", + R"( + semantics { + sender: "Domain Reliability" + description: + "If Chromium has trouble reaching certain Google sites or " + "services, Domain Reliability may report the problems back to " + "Google." + trigger: "Failure to load certain Google sites or services." + data: + "Details of the failed request, including the URL, any IP " + "addresses the browser tried to connect to, error(s) " + "encountered loading the resource, and other connection details." + destination: GOOGLE_OWNED_SERVICE + } + policy { + cookies_allowed: false + setting: + "Users can enable or disable Domain Reliability on desktop, via " + "toggling 'Automatically send usage statistics and crash reports " + "to Google' in Chromium's settings under Privacy. On ChromeOS, " + "the setting is named 'Automatically send diagnostic and usage " + "data to Google'." + policy_exception_justification: "Not implemented." + })"); + std::unique_ptr<net::URLFetcher> owned_fetcher = net::URLFetcher::Create( + 0, upload_url, net::URLFetcher::POST, this, traffic_annotation); net::URLFetcher* fetcher = owned_fetcher.get(); fetcher->SetRequestContext(url_request_context_getter_.get()); fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
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 b914c9b..7a1a045 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,7 +4,6 @@ package org.chromium.components.gcm_driver; -import android.content.Context; import android.os.AsyncTask; import org.chromium.base.Log; @@ -30,29 +29,25 @@ private static GCMDriver sInstance; private long mNativeGCMDriverAndroid; - private final Context mContext; private GoogleCloudMessagingSubscriber mSubscriber; - private GCMDriver(long nativeGCMDriverAndroid, Context context) { + private GCMDriver(long nativeGCMDriverAndroid) { mNativeGCMDriverAndroid = nativeGCMDriverAndroid; - mContext = context; - mSubscriber = new GoogleCloudMessagingV2(context); + mSubscriber = new GoogleCloudMessagingV2(); } /** * Create a GCMDriver object, which is owned by GCMDriverAndroid * on the C++ side. + * @param nativeGCMDriverAndroid The C++ object that owns us. * - * @param nativeGCMDriverAndroid The C++ object that owns us. - * @param context The app context. */ @CalledByNative - private static GCMDriver create(long nativeGCMDriverAndroid, - Context context) { + private static GCMDriver create(long nativeGCMDriverAndroid) { if (sInstance != null) { throw new IllegalStateException("Already instantiated"); } - sInstance = new GCMDriver(nativeGCMDriverAndroid, context); + sInstance = new GCMDriver(nativeGCMDriverAndroid); return sInstance; }
diff --git a/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GoogleCloudMessagingV2.java b/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GoogleCloudMessagingV2.java index 60158dc..1514ab5 100644 --- a/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GoogleCloudMessagingV2.java +++ b/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GoogleCloudMessagingV2.java
@@ -5,7 +5,6 @@ package org.chromium.components.gcm_driver; import android.app.PendingIntent; -import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; @@ -13,6 +12,7 @@ import android.os.Message; import android.os.Messenger; +import org.chromium.base.ContextUtils; import org.chromium.base.PackageUtils; import java.io.IOException; @@ -42,13 +42,10 @@ private static final String EXTRA_SUBTYPE = "subtype"; private static final String EXTRA_SUBSCRIPTION = "subscription"; - private Context mContext; private PendingIntent mAppPendingIntent; private final Object mAppPendingIntentLock = new Object(); - public GoogleCloudMessagingV2(Context context) { - mContext = context; - } + public GoogleCloudMessagingV2() {} @Override public String subscribe(String source, String subtype, @Nullable Bundle data) @@ -134,7 +131,9 @@ if (Looper.getMainLooper() == Looper.myLooper()) { throw new IOException(ERROR_MAIN_THREAD); } - if (PackageUtils.getPackageVersion(mContext, GOOGLE_PLAY_SERVICES_PACKAGE) < 0) { + if (PackageUtils.getPackageVersion( + ContextUtils.getApplicationContext(), GOOGLE_PLAY_SERVICES_PACKAGE) + < 0) { throw new IOException("Google Play Services missing"); } if (data == null) { @@ -156,7 +155,7 @@ setPackageNameExtra(intent); intent.putExtras(data); intent.putExtra(EXTRA_MESSENGER, responseMessenger); - mContext.startService(intent); + ContextUtils.getApplicationContext().startService(intent); try { return responseResult.poll(REGISTER_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { @@ -189,7 +188,7 @@ // Fill in the package, to prevent the intent from being used. target.setPackage("com.google.example.invalidpackage"); mAppPendingIntent = PendingIntent.getBroadcast( - mContext.getApplicationContext(), 0, target, 0); + ContextUtils.getApplicationContext(), 0, target, 0); } } intent.putExtra(INTENT_PARAM_APP, mAppPendingIntent);
diff --git a/components/gcm_driver/gcm_driver_android.cc b/components/gcm_driver/gcm_driver_android.cc index a0fedd5c..b7230f2 100644 --- a/components/gcm_driver/gcm_driver_android.cc +++ b/components/gcm_driver/gcm_driver_android.cc
@@ -7,7 +7,6 @@ #include <stddef.h> #include <stdint.h> -#include "base/android/context_utils.h" #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" @@ -31,10 +30,7 @@ : GCMDriver(store_path, blocking_task_runner), recorder_(this) { JNIEnv* env = AttachCurrentThread(); - java_ref_.Reset( - Java_GCMDriver_create(env, - reinterpret_cast<intptr_t>(this), - base::android::GetApplicationContext())); + java_ref_.Reset(Java_GCMDriver_create(env, reinterpret_cast<intptr_t>(this))); } GCMDriverAndroid::~GCMDriverAndroid() {
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 f819390..d0c91f4 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
@@ -4,12 +4,12 @@ package org.chromium.components.gcm_driver.instance_id; -import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import com.google.android.gms.iid.InstanceID; +import org.chromium.base.ContextUtils; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; @@ -22,7 +22,6 @@ */ @JNINamespace("instance_id") public class InstanceIDBridge { - private final Context mContext; private final String mSubtype; private long mNativeInstanceIDAndroid; /** @@ -33,9 +32,7 @@ private static boolean sBlockOnAsyncTasksForTesting; - private InstanceIDBridge( - long nativeInstanceIDAndroid, Context context, String subtype) { - mContext = context.getApplicationContext(); // Storing activity context would leak activity. + private InstanceIDBridge(long nativeInstanceIDAndroid, String subtype) { mSubtype = subtype; mNativeInstanceIDAndroid = nativeInstanceIDAndroid; } @@ -45,9 +42,8 @@ * share an underlying InstanceIDWithSubtype. */ @CalledByNative - public static InstanceIDBridge create( - long nativeInstanceIDAndroid, Context context, String subtype) { - return new InstanceIDBridge(nativeInstanceIDAndroid, context, subtype); + public static InstanceIDBridge create(long nativeInstanceIDAndroid, String subtype) { + return new InstanceIDBridge(nativeInstanceIDAndroid, subtype); } /** @@ -198,7 +194,8 @@ protected Result doInBackground(Void... params) { synchronized (InstanceIDBridge.this) { if (mInstanceID == null) { - mInstanceID = InstanceIDWithSubtype.getInstance(mContext, mSubtype); + mInstanceID = InstanceIDWithSubtype.getInstance( + ContextUtils.getApplicationContext(), mSubtype); } } return doBackgroundWork();
diff --git a/components/gcm_driver/instance_id/instance_id_android.cc b/components/gcm_driver/instance_id/instance_id_android.cc index e18835b..c284a80 100644 --- a/components/gcm_driver/instance_id/instance_id_android.cc +++ b/components/gcm_driver/instance_id/instance_id_android.cc
@@ -8,7 +8,6 @@ #include <memory> -#include "base/android/context_utils.h" #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" @@ -65,7 +64,6 @@ JNIEnv* env = AttachCurrentThread(); java_ref_.Reset( Java_InstanceIDBridge_create(env, reinterpret_cast<intptr_t>(this), - base::android::GetApplicationContext(), ConvertUTF8ToJavaString(env, subtype))); }
diff --git a/components/minidump_uploader/BUILD.gn b/components/minidump_uploader/BUILD.gn index c017ccd3..cbc33e9 100644 --- a/components/minidump_uploader/BUILD.gn +++ b/components/minidump_uploader/BUILD.gn
@@ -37,5 +37,8 @@ "android/javatests/src/org/chromium/components/minidump_uploader/CrashFileManagerTest.java", "android/javatests/src/org/chromium/components/minidump_uploader/CrashTestCase.java", "android/javatests/src/org/chromium/components/minidump_uploader/MinidumpUploadCallableTest.java", + "android/javatests/src/org/chromium/components/minidump_uploader/MinidumpUploadTestUtility.java", + "android/javatests/src/org/chromium/components/minidump_uploader/TestMinidumpUploaderDelegate.java", + "android/javatests/src/org/chromium/components/minidump_uploader/TestMinidumpUploaderImpl.java", ] }
diff --git a/components/minidump_uploader/android/java/src/org/chromium/components/minidump_uploader/MinidumpUploaderImpl.java b/components/minidump_uploader/android/java/src/org/chromium/components/minidump_uploader/MinidumpUploaderImpl.java index ebf914dc..93307872 100644 --- a/components/minidump_uploader/android/java/src/org/chromium/components/minidump_uploader/MinidumpUploaderImpl.java +++ b/components/minidump_uploader/android/java/src/org/chromium/components/minidump_uploader/MinidumpUploaderImpl.java
@@ -24,7 +24,8 @@ /** * The delegate that performs embedder-specific behavior. */ - private final MinidumpUploaderDelegate mDelegate; + @VisibleForTesting + protected final MinidumpUploaderDelegate mDelegate; /** * Manages the set of pending and failed local minidump files.
diff --git a/components/minidump_uploader/android/javatests/src/org/chromium/components/minidump_uploader/MinidumpUploadTestUtility.java b/components/minidump_uploader/android/javatests/src/org/chromium/components/minidump_uploader/MinidumpUploadTestUtility.java new file mode 100644 index 0000000..4e44806 --- /dev/null +++ b/components/minidump_uploader/android/javatests/src/org/chromium/components/minidump_uploader/MinidumpUploadTestUtility.java
@@ -0,0 +1,87 @@ +// 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. + +package org.chromium.components.minidump_uploader; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout; + +import org.chromium.base.ThreadUtils; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * Utility class for testing the minidump-uploading mechanism. + */ +public class MinidumpUploadTestUtility { + private static final long TIME_OUT_MILLIS = 3000; + + /** + * Utility method for running {@param minidumpUploader}.uploadAllMinidumps on the UI thread to + * avoid breaking any assertions about running on the UI thread. + */ + public static void uploadAllMinidumpsOnUiThread(final MinidumpUploader minidumpUploader, + final MinidumpUploader.UploadsFinishedCallback uploadsFinishedCallback) { + uploadAllMinidumpsOnUiThread( + minidumpUploader, uploadsFinishedCallback, false /* blockUntilJobPosted */); + } + + /** + * Utility method for running {@param minidumpUploader}.uploadAllMinidumps on the UI thread to + * avoid breaking any assertions about running on the UI thread. + * @param blockUntilJobPosted whether to block the current thread until the minidump-uploading + * job has been posted to the UI thread. This can be used to avoid + * some race-conditions (e.g. when waiting for variables that are + * initialized in the uploadAllMinidumps call). + */ + public static void uploadAllMinidumpsOnUiThread(final MinidumpUploader minidumpUploader, + final MinidumpUploader.UploadsFinishedCallback uploadsFinishedCallback, + boolean blockUntilJobPosted) { + final CountDownLatch jobPostedLatch = new CountDownLatch(1); + ThreadUtils.runOnUiThread(new Runnable() { + @Override + public void run() { + minidumpUploader.uploadAllMinidumps(uploadsFinishedCallback); + jobPostedLatch.countDown(); + } + }); + if (blockUntilJobPosted) { + try { + assertTrue( + jobPostedLatch.await(scaleTimeout(TIME_OUT_MILLIS), TimeUnit.MILLISECONDS)); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + } + + /** + * Utility method for uploading minidumps, and waiting for the uploads to finish. + * @param minidumpUploader the implementation to use to upload minidumps. + * @param expectReschedule value used to assert whether the uploads should be rescheduled, + * e.g. when uploading succeeds we should normally not expect to + * reschedule. + */ + public static void uploadMinidumpsSync( + MinidumpUploader minidumpUploader, final boolean expectReschedule) { + final CountDownLatch uploadsFinishedLatch = new CountDownLatch(1); + uploadAllMinidumpsOnUiThread( + minidumpUploader, new MinidumpUploader.UploadsFinishedCallback() { + @Override + public void uploadsFinished(boolean reschedule) { + assertEquals(expectReschedule, reschedule); + uploadsFinishedLatch.countDown(); + } + }); + try { + assertTrue(uploadsFinishedLatch.await( + scaleTimeout(TIME_OUT_MILLIS), TimeUnit.MILLISECONDS)); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } +}
diff --git a/components/minidump_uploader/android/javatests/src/org/chromium/components/minidump_uploader/TestMinidumpUploaderDelegate.java b/components/minidump_uploader/android/javatests/src/org/chromium/components/minidump_uploader/TestMinidumpUploaderDelegate.java new file mode 100644 index 0000000..35b02bc --- /dev/null +++ b/components/minidump_uploader/android/javatests/src/org/chromium/components/minidump_uploader/TestMinidumpUploaderDelegate.java
@@ -0,0 +1,44 @@ +// 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. + +package org.chromium.components.minidump_uploader; + +import org.chromium.components.minidump_uploader.util.CrashReportingPermissionManager; + +import java.io.File; + +/** + * Test-implementation of MinidumpUploaderDelegate. + */ +class TestMinidumpUploaderDelegate implements MinidumpUploaderDelegate { + private CrashReportingPermissionManager mPermissionManager; + private File mCacheDir; + + public TestMinidumpUploaderDelegate( + File cacheDir, CrashReportingPermissionManager permissionManager) { + mCacheDir = cacheDir; + mPermissionManager = permissionManager; + } + + @Override + public File getCrashParentDir() { + return mCacheDir; + } + + @Override + public CrashReportingPermissionManager createCrashReportingPermissionManager() { + return mPermissionManager; + } + + @Override + public void prepareToUploadMinidumps(Runnable startUploads) { + startUploads.run(); + } + + @Override + public void recordUploadSuccess(File minidump) {} + + @Override + public void recordUploadFailure(File minidump) {} +}
diff --git a/components/minidump_uploader/android/javatests/src/org/chromium/components/minidump_uploader/TestMinidumpUploaderImpl.java b/components/minidump_uploader/android/javatests/src/org/chromium/components/minidump_uploader/TestMinidumpUploaderImpl.java new file mode 100644 index 0000000..f08e2036 --- /dev/null +++ b/components/minidump_uploader/android/javatests/src/org/chromium/components/minidump_uploader/TestMinidumpUploaderImpl.java
@@ -0,0 +1,38 @@ +// 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. + +package org.chromium.components.minidump_uploader; + +import org.chromium.components.minidump_uploader.util.CrashReportingPermissionManager; + +import java.io.File; + +/** + * Test-implementation of MinidumpUploaderImpl. + */ +public class TestMinidumpUploaderImpl extends MinidumpUploaderImpl { + public TestMinidumpUploaderImpl( + File cacheDir, CrashReportingPermissionManager permissionManager) { + super(new TestMinidumpUploaderDelegate(cacheDir, permissionManager)); + } + + public TestMinidumpUploaderImpl(MinidumpUploaderDelegate delegate) { + super(delegate); + } + + @Override + public CrashFileManager createCrashFileManager(File crashDir) { + return new CrashFileManager(crashDir) { + @Override + public void cleanOutAllNonFreshMinidumpFiles() {} + }; + } + + @Override + public MinidumpUploadCallable createMinidumpUploadCallable(File minidumpFile, File logfile) { + return new MinidumpUploadCallable(minidumpFile, logfile, + new MinidumpUploadCallableTest.TestHttpURLConnectionFactory(), + mDelegate.createCrashReportingPermissionManager()); + } +}
diff --git a/components/network_session_configurator/network_session_configurator.cc b/components/network_session_configurator/network_session_configurator.cc index 4bb6f77..f7754e8 100644 --- a/components/network_session_configurator/network_session_configurator.cc +++ b/components/network_session_configurator/network_session_configurator.cc
@@ -134,34 +134,6 @@ return net::ParseQuicConnectionOptions(it->second); } -float GetQuicLoadServerInfoTimeoutSrttMultiplier( - const VariationParameters& quic_trial_params) { - double value; - if (base::StringToDouble( - GetVariationParam(quic_trial_params, "load_server_info_time_to_srtt"), - &value)) { - return static_cast<float>(value); - } - return 0.0f; -} - -bool ShouldQuicEnableConnectionRacing( - const VariationParameters& quic_trial_params) { - return base::LowerCaseEqualsASCII( - GetVariationParam(quic_trial_params, "enable_connection_racing"), "true"); -} - -bool ShouldQuicEnableNonBlockingIO( - const VariationParameters& quic_trial_params) { - return base::LowerCaseEqualsASCII( - GetVariationParam(quic_trial_params, "enable_non_blocking_io"), "true"); -} - -bool ShouldQuicDisableDiskCache(const VariationParameters& quic_trial_params) { - return base::LowerCaseEqualsASCII( - GetVariationParam(quic_trial_params, "disable_disk_cache"), "true"); -} - bool ShouldForceHolBlocking(const VariationParameters& quic_trial_params) { return base::LowerCaseEqualsASCII( GetVariationParam(quic_trial_params, "force_hol_blocking"), "true"); @@ -295,18 +267,6 @@ ShouldRetryWithoutAltSvcOnQuicErrors(quic_trial_params); if (params->enable_quic) { - float load_server_info_timeout_srtt_multiplier = - GetQuicLoadServerInfoTimeoutSrttMultiplier(quic_trial_params); - if (load_server_info_timeout_srtt_multiplier != 0) { - params->quic_load_server_info_timeout_srtt_multiplier = - load_server_info_timeout_srtt_multiplier; - } - params->quic_enable_connection_racing = - ShouldQuicEnableConnectionRacing(quic_trial_params); - params->quic_enable_non_blocking_io = - ShouldQuicEnableNonBlockingIO(quic_trial_params); - params->quic_disable_disk_cache = - ShouldQuicDisableDiskCache(quic_trial_params); params->quic_force_hol_blocking = ShouldForceHolBlocking(quic_trial_params); params->quic_connection_options = GetQuicConnectionOptions(quic_trial_params);
diff --git a/components/network_session_configurator/network_session_configurator_unittest.cc b/components/network_session_configurator/network_session_configurator_unittest.cc index 0a52ae01..a4deda3 100644 --- a/components/network_session_configurator/network_session_configurator_unittest.cc +++ b/components/network_session_configurator/network_session_configurator_unittest.cc
@@ -70,11 +70,7 @@ EXPECT_FALSE(params_.retry_without_alt_svc_on_quic_errors); EXPECT_EQ(1350u, params_.quic_max_packet_length); EXPECT_EQ(net::QuicTagVector(), params_.quic_connection_options); - EXPECT_EQ(0.25f, params_.quic_load_server_info_timeout_srtt_multiplier); - EXPECT_FALSE(params_.quic_enable_connection_racing); EXPECT_FALSE(params_.enable_server_push_cancellation); - EXPECT_FALSE(params_.quic_enable_non_blocking_io); - EXPECT_FALSE(params_.quic_disable_disk_cache); EXPECT_FALSE(params_.quic_close_sessions_on_ip_change); EXPECT_EQ(net::kIdleConnectionTimeoutSeconds, params_.quic_idle_connection_timeout_seconds); @@ -339,51 +335,6 @@ EXPECT_EQ(expected_settings, params_.http2_settings); } -TEST_F(NetworkSessionConfiguratorTest, - QuicLoadServerInfoTimeToSmoothedRttFromFieldTrialParams) { - std::map<std::string, std::string> field_trial_params; - field_trial_params["load_server_info_time_to_srtt"] = "0.5"; - variations::AssociateVariationParams("QUIC", "Enabled", field_trial_params); - base::FieldTrialList::CreateFieldTrial("QUIC", "Enabled"); - - ParseFieldTrials(); - - EXPECT_EQ(0.5f, params_.quic_load_server_info_timeout_srtt_multiplier); -} - -TEST_F(NetworkSessionConfiguratorTest, QuicEnableConnectionRacing) { - std::map<std::string, std::string> field_trial_params; - field_trial_params["enable_connection_racing"] = "true"; - variations::AssociateVariationParams("QUIC", "Enabled", field_trial_params); - base::FieldTrialList::CreateFieldTrial("QUIC", "Enabled"); - - ParseFieldTrials(); - - EXPECT_TRUE(params_.quic_enable_connection_racing); -} - -TEST_F(NetworkSessionConfiguratorTest, QuicEnableNonBlockingIO) { - std::map<std::string, std::string> field_trial_params; - field_trial_params["enable_non_blocking_io"] = "true"; - variations::AssociateVariationParams("QUIC", "Enabled", field_trial_params); - base::FieldTrialList::CreateFieldTrial("QUIC", "Enabled"); - - ParseFieldTrials(); - - EXPECT_TRUE(params_.quic_enable_non_blocking_io); -} - -TEST_F(NetworkSessionConfiguratorTest, QuicDisableDiskCache) { - std::map<std::string, std::string> field_trial_params; - field_trial_params["disable_disk_cache"] = "true"; - variations::AssociateVariationParams("QUIC", "Enabled", field_trial_params); - base::FieldTrialList::CreateFieldTrial("QUIC", "Enabled"); - - ParseFieldTrials(); - - EXPECT_TRUE(params_.quic_disable_disk_cache); -} - TEST_F(NetworkSessionConfiguratorTest, TCPFastOpenHttpsEnabled) { base::FieldTrialList::CreateFieldTrial("TCPFastOpen", "HttpsEnabled");
diff --git a/components/ntp_snippets/content_suggestion.h b/components/ntp_snippets/content_suggestion.h index 7879a55..dca3c243 100644 --- a/components/ntp_snippets/content_suggestion.h +++ b/components/ntp_snippets/content_suggestion.h
@@ -112,9 +112,12 @@ // This may be an AMP URL. const GURL& url() const { return url_; } - // The URL of a page that links to a favicon that represents the suggestion. - const GURL& url_with_favicon() const { - return url_with_favicon_.is_valid() ? url_with_favicon_ : url_; + // The URL of the page that links to a favicon that represents the suggestion. + // Path is trimmed for the URL because the current favicon server backend + // prefers it this way. + GURL url_with_favicon() const { + return url_with_favicon_.is_valid() ? url_with_favicon_.GetWithEmptyPath() + : url_.GetWithEmptyPath(); } void set_url_with_favicon(const GURL& url_with_favicon) { url_with_favicon_ = url_with_favicon;
diff --git a/components/ntp_snippets/content_suggestions_service.cc b/components/ntp_snippets/content_suggestions_service.cc index 861a08e..9a5f3fb 100644 --- a/components/ntp_snippets/content_suggestions_service.cc +++ b/components/ntp_snippets/content_suggestions_service.cc
@@ -174,8 +174,7 @@ return; } - const GURL& domain_with_favicon = - position->url_with_favicon().GetWithEmptyPath(); + const GURL& domain_with_favicon = position->url_with_favicon(); // TODO(jkrcal): Create a general wrapper function in LargeIconService that // does handle the get-from-cache-and-fallback-to-google-server functionality
diff --git a/components/policy/core/common/cloud/cloud_policy_validator.cc b/components/policy/core/common/cloud/cloud_policy_validator.cc index ff6008d..3ac136b 100644 --- a/components/policy/core/common/cloud/cloud_policy_validator.cc +++ b/components/policy/core/common/cloud/cloud_policy_validator.cc
@@ -185,13 +185,16 @@ DCHECK(!verification_key_.empty()); } +// static void CloudPolicyValidatorBase::PostValidationTask( + std::unique_ptr<CloudPolicyValidatorBase> validator, const base::Closure& completion_callback) { - background_task_runner_->PostTask( + const auto task_runner = validator->background_task_runner_; + task_runner->PostTask( FROM_HERE, base::Bind(&CloudPolicyValidatorBase::PerformValidation, - base::Passed(std::unique_ptr<CloudPolicyValidatorBase>(this)), - base::ThreadTaskRunnerHandle::Get(), completion_callback)); + base::Passed(&validator), base::ThreadTaskRunnerHandle::Get(), + completion_callback)); } // static
diff --git a/components/policy/core/common/cloud/cloud_policy_validator.h b/components/policy/core/common/cloud/cloud_policy_validator.h index b56af89..bef6e39 100644 --- a/components/policy/core/common/cloud/cloud_policy_validator.h +++ b/components/policy/core/common/cloud/cloud_policy_validator.h
@@ -15,6 +15,7 @@ #include "base/bind.h" #include "base/callback.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/sequenced_task_runner.h" #include "base/time/time.h" @@ -128,7 +129,7 @@ Status status() const { return status_; } bool success() const { return status_ == VALIDATION_OK; } - // The policy objects owned by the validator. These are scoped_ptr + // The policy objects owned by the validator. These are unique_ptr // references, so ownership can be passed on once validation is complete. std::unique_ptr<enterprise_management::PolicyFetchResponse>& policy() { return policy_; @@ -233,9 +234,11 @@ google::protobuf::MessageLite* payload, scoped_refptr<base::SequencedTaskRunner> background_task_runner); - // Posts an asynchronous calls to PerformValidation, which will eventually - // report its result via |completion_callback|. - void PostValidationTask(const base::Closure& completion_callback); + // Posts an asynchronous call to PerformValidation of the passed |validator|, + // which will eventually report its result via |completion_callback|. + static void PostValidationTask( + std::unique_ptr<CloudPolicyValidatorBase> validator, + const base::Closure& completion_callback); private: // Internal flags indicating what to check. @@ -344,32 +347,32 @@ template<typename PayloadProto> class POLICY_EXPORT CloudPolicyValidator : public CloudPolicyValidatorBase { public: - typedef base::Callback<void(CloudPolicyValidator<PayloadProto>*)> - CompletionCallback; + using CompletionCallback = base::Callback<void(CloudPolicyValidator*)>; virtual ~CloudPolicyValidator() {} // Creates a new validator. // |background_task_runner| is optional; if RunValidation() is used directly // and StartValidation() is not used then it can be nullptr. - static CloudPolicyValidator<PayloadProto>* Create( + static std::unique_ptr<CloudPolicyValidator> Create( std::unique_ptr<enterprise_management::PolicyFetchResponse> policy_response, scoped_refptr<base::SequencedTaskRunner> background_task_runner) { - return new CloudPolicyValidator( - std::move(policy_response), - std::unique_ptr<PayloadProto>(new PayloadProto()), - background_task_runner); + return base::WrapUnique<CloudPolicyValidator>(new CloudPolicyValidator( + std::move(policy_response), base::MakeUnique<PayloadProto>(), + background_task_runner)); } std::unique_ptr<PayloadProto>& payload() { return payload_; } - // Kicks off asynchronous validation. |completion_callback| is invoked when - // done. From this point on, the validator manages its own lifetime - this - // allows callers to provide a WeakPtr in the callback without leaking the - // validator. - void StartValidation(const CompletionCallback& completion_callback) { - PostValidationTask(base::Bind(completion_callback, this)); + // Kicks off asynchronous validation through |validator|. + // |completion_callback| is invoked when done. + static void StartValidation(std::unique_ptr<CloudPolicyValidator> validator, + const CompletionCallback& completion_callback) { + CloudPolicyValidator* const validator_ptr = validator.release(); + PostValidationTask( + base::WrapUnique<CloudPolicyValidatorBase>(validator_ptr), + base::Bind(completion_callback, validator_ptr)); } private: @@ -388,12 +391,12 @@ DISALLOW_COPY_AND_ASSIGN(CloudPolicyValidator); }; -typedef CloudPolicyValidator<enterprise_management::CloudPolicySettings> - UserCloudPolicyValidator; +using UserCloudPolicyValidator = + CloudPolicyValidator<enterprise_management::CloudPolicySettings>; #if !defined(OS_ANDROID) && !defined(OS_IOS) -typedef CloudPolicyValidator<enterprise_management::ExternalPolicyData> - ComponentCloudPolicyValidator; +using ComponentCloudPolicyValidator = + CloudPolicyValidator<enterprise_management::ExternalPolicyData>; #endif } // namespace policy
diff --git a/components/policy/core/common/cloud/cloud_policy_validator_unittest.cc b/components/policy/core/common/cloud/cloud_policy_validator_unittest.cc index c3112952..c61675fc 100644 --- a/components/policy/core/common/cloud/cloud_policy_validator_unittest.cc +++ b/components/policy/core/common/cloud/cloud_policy_validator_unittest.cc
@@ -72,7 +72,8 @@ // Run validation and check the result. EXPECT_CALL(*this, ValidationCompletion(validator.get())).WillOnce( check_action); - validator.release()->StartValidation( + UserCloudPolicyValidator::StartValidation( + std::move(validator), base::Bind(&CloudPolicyValidatorTest::ValidationCompletion, base::Unretained(this))); base::RunLoop().RunUntilIdle(); @@ -84,8 +85,9 @@ std::string public_key = PolicyBuilder::GetPublicTestKeyAsString(); EXPECT_FALSE(public_key.empty()); - UserCloudPolicyValidator* validator = UserCloudPolicyValidator::Create( - std::move(policy_response), base::ThreadTaskRunnerHandle::Get()); + std::unique_ptr<UserCloudPolicyValidator> validator = + UserCloudPolicyValidator::Create(std::move(policy_response), + base::ThreadTaskRunnerHandle::Get()); validator->ValidateTimestamp(timestamp_, timestamp_, timestamp_option_); validator->ValidateUsername(PolicyBuilder::kFakeUsername, true); @@ -104,7 +106,7 @@ } else { validator->ValidateSignature(public_key); } - return base::WrapUnique(validator); + return validator; }
diff --git a/components/policy/core/common/cloud/user_cloud_policy_store.cc b/components/policy/core/common/cloud/user_cloud_policy_store.cc index 9307530d..47917bca 100644 --- a/components/policy/core/common/cloud/user_cloud_policy_store.cc +++ b/components/policy/core/common/cloud/user_cloud_policy_store.cc
@@ -408,9 +408,8 @@ } if (validate_in_background) { - // Start validation in the background. The Validator will free itself once - // validation is complete. - validator.release()->StartValidation(callback); + // Start validation in the background. + UserCloudPolicyValidator::StartValidation(std::move(validator), callback); } else { // Run validation immediately and invoke the callback with the results. validator->RunValidation();
diff --git a/components/policy/core/common/cloud/user_cloud_policy_store_base.cc b/components/policy/core/common/cloud/user_cloud_policy_store_base.cc index 46dffc2..bca28896 100644 --- a/components/policy/core/common/cloud/user_cloud_policy_store_base.cc +++ b/components/policy/core/common/cloud/user_cloud_policy_store_base.cc
@@ -31,8 +31,9 @@ std::unique_ptr<enterprise_management::PolicyFetchResponse> policy, CloudPolicyValidatorBase::ValidateTimestampOption timestamp_option) { // Configure the validator. - UserCloudPolicyValidator* validator = UserCloudPolicyValidator::Create( - std::move(policy), background_task_runner_); + std::unique_ptr<UserCloudPolicyValidator> validator = + UserCloudPolicyValidator::Create(std::move(policy), + background_task_runner_); validator->ValidatePolicyType(dm_protocol::kChromeUserPolicyType); validator->ValidateAgainstCurrentPolicy( policy_.get(), @@ -40,7 +41,7 @@ CloudPolicyValidatorBase::DM_TOKEN_REQUIRED, CloudPolicyValidatorBase::DEVICE_ID_REQUIRED); validator->ValidatePayload(); - return std::unique_ptr<UserCloudPolicyValidator>(validator); + return validator; } void UserCloudPolicyStoreBase::InstallPolicy(
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index 8ec19048e..adfd6a8 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -47,23 +47,27 @@ # TODO(fhorschig|tnagel): Revisit policy tags after reviews. # # Policy group descriptions, policy captions and similar texts are localized -# strings taken from the <message> nodes of the .grd file. Their name -# attributes are generated from the JSON keys. +# strings taken from the <message> nodes of the .grd file. Their name attributes +# are generated from the JSON keys. # Each item (policy or group) may have the following messages: # - description: # Describes the item it applies to. # - caption # A short, one-line summary of the item it applies to. This can appear # both in policy or group listings or on title bars of policy-setting -# windows. +# windows. (The caption should not end with a punctuation mark.) # - label (Optional, defaults to caption if not specified.) # A short, one-line summary of the item it applies to. The difference # from caption is that label always appears next to the entry field # where the value of the policy can be entered. 'main' policies on # Windows ignore this. Policies on Mac are using this instead of caption. # -# Non-translateable strings should be tagged using <ph name="..."></ph> as -# described in https://www.chromium.org/developers/tools-we-use-in-chromium/grit/grit-users-guide +# As a reference for translators, non-translateable strings must be tagged using +# <ph name="..."></ph> as described in [1]. As these tags are pruned before +# generating the comments for .proto files, paragraphs containing such tags +# should not be line-wrapped (use one long line per paragraph instead) to allow +# for correct re-flowing of the text. +# [1] https://www.chromium.org/developers/tools-we-use-in-chromium/grit/grit-users-guide. # # Generated grd names: # Each name has two parts: the second part is either CAPTION, DESC or LABEL, @@ -733,10 +737,7 @@ 'caption': '''Configure remote access options''', 'desc': '''Configure remote access options in Chrome Remote Desktop host. - Chrome Remote Desktop host is a native service that runs on the target - machine that a user can connect to using Chrome Remote Desktop - application. The native service is packaged and executed separately from - the <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> browser. + Chrome Remote Desktop host is a native service that runs on the target machine that a user can connect to using Chrome Remote Desktop application. The native service is packaged and executed separately from the <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> browser. These policies are ignored unless the Chrome Remote Desktop host is installed.''', @@ -1299,17 +1300,12 @@ 'caption': '''Enable saving passwords to the password manager''', 'tags': [], 'desc': ''' - If this setting is enabled, users can have <ph - name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> memorize passwords - and provide them automatically the next time they log in to a site. + If this setting is enabled, users can have <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> memorize passwords and provide them automatically the next time they log in to a site. If this settings is disabled, users cannot save new passwords but they may still use passwords that have been saved previously. - If this policy is enabled or disabled, users cannot change or override - it in <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph>. If this - policy is unset, password saving is allowed (but can be turned off by - the user).''', + If this policy is enabled or disabled, users cannot change or override it in <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph>. If this policy is unset, password saving is allowed (but can be turned off by the user).''', 'arc_support': 'This policy has no effect on Android apps.', }, { @@ -1521,7 +1517,7 @@ }, 'example_value': True, 'id': 358, - 'caption': '''Enable the creation of roaming copies for <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> profile data.''', + 'caption': '''Enable the creation of roaming copies for <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> profile data''', 'tags': ['local-data-access'], 'desc': '''Enables the creation of roaming copies for <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> profile data. @@ -3846,7 +3842,7 @@ }, 'example_value': False, 'id': 253, - 'caption': '''Allow user-level Native Messaging hosts (installed without admin permissions).''', + 'caption': '''Allow user-level Native Messaging hosts (installed without admin permissions)''', 'tags': [], 'desc': '''Enables user-level installation of Native Messaging hosts. @@ -5924,7 +5920,7 @@ 'schema': { 'type': 'boolean' }, 'tags': [], 'supported_on': ['chrome_os:54-'], - 'caption': '''Treat external storage devices as read-only.''', + 'caption': '''Treat external storage devices as read-only''', 'desc': '''When this policy is set to true, users cannot write anything to external storage devices. If this setting is set to false or not configured, then users can create and modify files of external storage devices which are physically writable. @@ -7891,17 +7887,7 @@ 'tags': [], 'desc': '''Configures a list of managed bookmarks. - The policy consists of a list of bookmarks whereas each bookmark is a - dictionary containing the keys <ph name="NAME">"name"</ph> and <ph - name="URL_LABEL">"url"</ph> which hold the bookmark's name and its target. A - subfolder may be configured by defining a bookmark without an <ph - name="URL_LABEL">"url"</ph> key but with an additional <ph - name="CHILDREN">"children"</ph> key which itself contains a list of - bookmarks as defined above (some of which may be folders again). <ph - name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> amends incomplete URLs - as if they were submitted via the Omnibox, for example <ph - name="GOOGLE_COM">"google.com"</ph> becomes <ph - name="HTTPS_GOOGLE_COM">"https://google.com/"</ph>. + The policy consists of a list of bookmarks whereas each bookmark is a dictionary containing the keys <ph name="NAME">"name"</ph> and <ph name="URL_LABEL">"url"</ph> which hold the bookmark's name and its target. A subfolder may be configured by defining a bookmark without an <ph name="URL_LABEL">"url"</ph> key but with an additional <ph name="CHILDREN">"children"</ph> key which itself contains a list of bookmarks as defined above (some of which may be folders again). <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> amends incomplete URLs as if they were submitted via the Omnibox, for example <ph name="GOOGLE_COM">"google.com"</ph> becomes <ph name="HTTPS_GOOGLE_COM">"https://google.com/"</ph>. These bookmarks are placed in a "Managed bookmarks" folder that can't be modified by the user, but the user can choose to hide it from the bookmark bar. Managed bookmarks are not synced to the user account and can't be modified by extensions. @@ -8183,7 +8169,7 @@ }, 'example_value': False, 'id': 346, - 'caption': '''Enables force sign in for <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph>.''', + 'caption': '''Enables force sign in for <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph>''', 'tags': [], 'desc': '''If this policy is set to true, user has to sign in to <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> with their profile before using the browser. And the default value of BrowserGuestModeEnabled will be set to false. @@ -8581,7 +8567,7 @@ 'type': 'main', 'schema': { 'type': 'boolean' }, 'id': 303, - 'caption': 'Enable showing the welcome page on the first browser launch following OS upgrade.', + 'caption': 'Enable showing the welcome page on the first browser launch following OS upgrade', 'tags': [], 'desc': '''Enable showing the welcome page on the first browser launch following OS upgrade. @@ -8625,7 +8611,7 @@ }, 'example_value': True, 'id': 307, - 'caption': '''Make Unified Desktop available and turn on by default.''', + 'caption': '''Make Unified Desktop available and turn on by default''', 'tags': [], 'desc': '''If this policy is set to true, Unified Desktop is allowed and enabled by default, which allows applications to span multiple displays. @@ -8876,11 +8862,7 @@ When this policy is set to false, the device will not attempt to contact the Quirks Server to download configuration files. - If this policy is true or not configured then - <ph name="PRODUCT_OS_NAME">$2<ex>Google Chrome OS</ex></ph> will - automatically contact the Quirks Server and download configuration files, - if available, and store them on the device. Such files might, for - example, be used to improve display quality of attached monitors.''', + If this policy is true or not configured then <ph name="PRODUCT_OS_NAME">$2<ex>Google Chrome OS</ex></ph> will automatically contact the Quirks Server and download configuration files, if available, and store them on the device. Such files might, for example, be used to improve display quality of attached monitors.''', }, { 'name': 'SystemTimezoneAutomaticDetection', @@ -8893,27 +8875,27 @@ { 'name': 'TimezoneAutomaticDetectionUsersDecide', 'value': 0, - 'caption': '''Let users decide.''', + 'caption': '''Let users decide''', }, { 'name': 'TimezoneAutomaticDetectionDisabled', 'value': 1, - 'caption': '''Never auto-detect timezone.''', + 'caption': '''Never auto-detect timezone''', }, { 'name': 'TimezoneAutomaticDetectionIPOnly', 'value': 2, - 'caption': '''Always use coarse timezone detection.''', + 'caption': '''Always use coarse timezone detection''', }, { 'name': 'TimezoneAutomaticDetectionSendWiFiAccessPoints', 'value': 3, - 'caption': '''Always send WiFi access-points to server while resolving timezone.''', + 'caption': '''Always send WiFi access-points to server while resolving timezone''', }, { 'name': 'TimezoneAutomaticDetectionSendAllLocationInfo', 'value': 4, - 'caption': '''Always send any available location signals to the server while resolving timezone.''', + 'caption': '''Always send any available location signals to the server while resolving timezone''', }, ], 'supported_on': ['chrome_os:53-'], @@ -9044,28 +9026,11 @@ implicitly, without user interaction, including any additional permissions requested by future versions of the app. - If an app that previously had been force-installed is removed from - this list, it is automatically uninstalled by <ph name="PRODUCT_NAME">$1<ex>Google - Chrome</ex></ph>. + If an app that previously had been force-installed is removed from this list, it is automatically uninstalled by <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph>. - Each list item of the policy is a string that contains an extension ID - and an "update" URL separated by a semicolon (<ph - name="SEMICOLON">;</ph>). The extension ID is the 32-letter string - found e.g. on <ph - name="CHROME_EXTENSIONS_LINK">chrome://extensions</ph> when in - developer mode. The "update" URL should point to an Update Manifest - XML document as described at <ph - name="LINK_TO_EXTENSION_DOC1">https://developer.chrome.com/extensions/autoupdate</ph>. Note - that the "update" URL set in this policy is only used for the initial - installation; subsequent updates of the extension employ the update - URL indicated in the extension's manifest. + Each list item of the policy is a string that contains an extension ID and an "update" URL separated by a semicolon (<ph name="SEMICOLON">;</ph>). The extension ID is the 32-letter string found e.g. on <ph name="CHROME_EXTENSIONS_LINK">chrome://extensions</ph> when in developer mode. The "update" URL should point to an Update Manifest XML document as described at <ph name="LINK_TO_EXTENSION_DOC1">https://developer.chrome.com/extensions/autoupdate</ph>. Note that the "update" URL set in this policy is only used for the initial installation; subsequent updates of the extension employ the update URL indicated in the extension's manifest. - For example, <ph - name="EXTENSION_POLICY_EXAMPLE">gbchcmhmhahfdphkhkmpfmihenigjmpp;https://clients2.google.com/service/update2/crx</ph> - installs the <ph name="EXTENSION_POLICY_EXAMPLE_EXTENSION_NAME">Chrome - Remote Desktop</ph> app from the standard Chrome Web Store "update" - URL. For more information about hosting extensions, see: <ph - name="LINK_TO_EXTENSION_DOC2">https://developer.chrome.com/extensions/hosting</ph>.''', + For example, <ph name="EXTENSION_POLICY_EXAMPLE">gbchcmhmhahfdphkhkmpfmihenigjmpp;https://clients2.google.com/service/update2/crx</ph> installs the <ph name="EXTENSION_POLICY_EXAMPLE_EXTENSION_NAME">Chrome Remote Desktop</ph> app from the standard Chrome Web Store "update" URL. For more information about hosting extensions, see: <ph name="LINK_TO_EXTENSION_DOC2">https://developer.chrome.com/extensions/hosting</ph>.''', }, { 'name': 'AllowScreenLock', @@ -9130,9 +9095,7 @@ 'id': 331, 'caption': '''Define domains allowed to access Google Apps''', 'tags': ['filtering'], - 'desc': '''Enables <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph>'s - restricted log in feature in Google Apps and prevents users from - changing this setting. + 'desc': '''Enables <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph>'s restricted log in feature in Google Apps and prevents users from changing this setting. If you define this setting, the user will only be able to access Google Apps (such as Gmail) using accounts from the specified domains. @@ -9341,7 +9304,7 @@ }, 'example_value': True, 'id': 342, - 'caption': '''Enables component updates in <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph>.''', + 'caption': '''Enables component updates in <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph>''', 'tags': [], 'desc': '''Enables component updates for all components in <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> when not set or set to True. @@ -9397,23 +9360,9 @@ This policy allows administrators to provide printer configurations for their users. - <ph name="PRINTER_DISPLAY_NAME">display_name</ph> and <ph - name="PRINTER_DESCRIPTION">description</ph> are free form strings that - can be customized for ease of printer selection. <ph - name="PRINTER_MANUFACTURER">manufacturer</ph> and <ph - name="PRINTER_MODEL">model</ph> serve to ease printer identification by - end users. They represent the manufcaturer and model of the printer. <ph - name="PRINTER_URI">uri</ph> should be an address reachable - from a client computer including the <ph name="URI_SCHEME">scheme</ph>, - <ph name="URI_PORT">port</ph>, and <ph name="URI_QUEUE">queue</ph>. <ph - name="PRINTER_UUID">uuid</ph> is optional. If provided, it is used to - help deduplicate <ph name="ZEROCONF_DISCOVERY">zeroconf</ph> printers. + <ph name="PRINTER_DISPLAY_NAME">display_name</ph> and <ph name="PRINTER_DESCRIPTION">description</ph> are free form strings that can be customized for ease of printer selection. <ph name="PRINTER_MANUFACTURER">manufacturer</ph> and <ph name="PRINTER_MODEL">model</ph> serve to ease printer identification by end users. They represent the manufacturer and model of the printer. <ph name="PRINTER_URI">uri</ph> should be an address reachable from a client computer including the <ph name="URI_SCHEME">scheme</ph>, <ph name="URI_PORT">port</ph>, and <ph name="URI_QUEUE">queue</ph>. <ph name="PRINTER_UUID">uuid</ph> is optional. If provided, it is used to help deduplicate <ph name="ZEROCONF_DISCOVERY">zeroconf</ph> printers. - <ph name="PRINTER_EFFECTIVE_MODEL">effective_model</ph> must match one of - the strings which represent a <ph name="PRODUCT_NAME">$2<ex>Google Chrome - OS</ex></ph> supported printer. The string will be used to identify and - install the appropriate PPD for the printer. More information can be - found at https://support.google.com/chrome?p=noncloudprint. + <ph name="PRINTER_EFFECTIVE_MODEL">effective_model</ph> must match one of the strings which represent a <ph name="PRODUCT_NAME">$2<ex>Google Chrome OS</ex></ph> supported printer. The string will be used to identify and install the appropriate PPD for the printer. More information can be found at https://support.google.com/chrome?p=noncloudprint. Printer setup is completed upon the first use of a printer. PPDs are not downloaded until the printer is used. After that time, frequently used @@ -9451,7 +9400,7 @@ 'example_value': ['PIN'], 'default_for_enterprise_users': [], 'id': 352, - 'caption': '''Configure allowed quick unlock modes.''', + 'caption': '''Configure allowed quick unlock modes''', 'tags': [], 'desc': '''A whitelist controlling which quick unlock modes the user can configure and use to unlock the lock screen. @@ -9472,22 +9421,22 @@ { 'name': 'SixHours', 'value': 0, - 'caption': '''Password entry is required every six hours.''', + 'caption': '''Password entry is required every six hours''', }, { 'name': 'TweleveHours', 'value': 1, - 'caption': '''Password entry is required every twelve hours.''', + 'caption': '''Password entry is required every twelve hours''', }, { 'name': 'Day', 'value': 2, - 'caption': '''Password entry is required every day (24 hours).''', + 'caption': '''Password entry is required every day (24 hours)''', }, { 'name': 'Week', 'value': 3, - 'caption': '''Password entry is required every week (168 hours).''', + 'caption': '''Password entry is required every week (168 hours)''', }, ], 'supported_on': ['chrome_os:57-'], @@ -9497,7 +9446,7 @@ }, 'example_value': 2, 'id': 353, - 'caption': '''Sets how often user has to enter password to use quick unlock.''', + 'caption': '''Sets how often user has to enter password to use quick unlock''', 'tags': [], 'desc': '''This setting controls how often the lock screen will request the password to be entered in order to continue using quick unlock. Each time the lock screen is entered, if the last password entry was more than this setting, the quick unlock will not be available on entering the lock screen. Should the user stay on the lock screen past this period of time, a password will be requested next time the user enters the wrong code, or re-enters the lock screen, whichever comes first. @@ -9516,7 +9465,7 @@ }, 'example_value': 6, 'id': 354, - 'caption': '''Sets the minimum length of the lock screen PIN.''', + 'caption': '''Sets the minimum length of the lock screen PIN''', 'tags': [], 'desc': '''This setting controls the minimum PIN length. @@ -9535,7 +9484,7 @@ }, 'example_value': 0, 'id': 355, - 'caption': '''Sets the maximum length of the lock screen PIN.''', + 'caption': '''Sets the maximum length of the lock screen PIN''', 'tags': [], 'desc': '''This setting controls the maximum PIN length. @@ -9556,7 +9505,7 @@ }, 'example_value': False, 'id': 356, - 'caption': '''Enables users to set weak PINs for the lock screen PIN.''', + 'caption': '''Enables users to set weak PINs for the lock screen PIN''', 'tags': [], 'desc': '''If false, users will be unable to set PINs which are weak and easy to guess.
diff --git a/components/safe_browsing_db/android/java/src/org/chromium/components/safe_browsing/SafeBrowsingApiBridge.java b/components/safe_browsing_db/android/java/src/org/chromium/components/safe_browsing/SafeBrowsingApiBridge.java index 1785899..de39ea2 100644 --- a/components/safe_browsing_db/android/java/src/org/chromium/components/safe_browsing/SafeBrowsingApiBridge.java +++ b/components/safe_browsing_db/android/java/src/org/chromium/components/safe_browsing/SafeBrowsingApiBridge.java
@@ -4,8 +4,7 @@ package org.chromium.components.safe_browsing; -import android.content.Context; - +import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; @@ -38,7 +37,7 @@ * @return the handler if it's usable, or null if the API is not supported. */ @CalledByNative - private static SafeBrowsingApiHandler create(Context context) { + private static SafeBrowsingApiHandler create() { SafeBrowsingApiHandler handler; try { handler = sHandler.newInstance(); @@ -46,12 +45,13 @@ Log.e(TAG, "Failed to init handler: " + e.getMessage()); return null; } - boolean initSuccesssful = handler.init(context, new SafeBrowsingApiHandler.Observer() { - @Override - public void onUrlCheckDone(long callbackId, int resultStatus, String metadata) { - nativeOnUrlCheckDone(callbackId, resultStatus, metadata); - } - }); + boolean initSuccesssful = handler.init( + ContextUtils.getApplicationContext(), new SafeBrowsingApiHandler.Observer() { + @Override + public void onUrlCheckDone(long callbackId, int resultStatus, String metadata) { + nativeOnUrlCheckDone(callbackId, resultStatus, metadata); + } + }); return initSuccesssful ? handler : null; }
diff --git a/components/safe_browsing_db/android/safe_browsing_api_handler_bridge.cc b/components/safe_browsing_db/android/safe_browsing_api_handler_bridge.cc index a4dd994..ae37100 100644 --- a/components/safe_browsing_db/android/safe_browsing_api_handler_bridge.cc +++ b/components/safe_browsing_db/android/safe_browsing_api_handler_bridge.cc
@@ -7,7 +7,6 @@ #include <memory> #include <string> -#include "base/android/context_utils.h" #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" @@ -19,7 +18,6 @@ using base::android::AttachCurrentThread; using base::android::ConvertJavaStringToUTF8; using base::android::ConvertUTF8ToJavaString; -using base::android::GetApplicationContext; using base::android::JavaParamRef; using base::android::ScopedJavaLocalRef; using base::android::ToJavaIntArray; @@ -140,8 +138,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!checked_api_support_) { DVLOG(1) << "Checking API support."; - j_api_handler_ = Java_SafeBrowsingApiBridge_create(AttachCurrentThread(), - GetApplicationContext()); + j_api_handler_ = Java_SafeBrowsingApiBridge_create(AttachCurrentThread()); checked_api_support_ = true; } return j_api_handler_.obj() != nullptr;
diff --git a/components/update_client/update_client.cc b/components/update_client/update_client.cc index 3dc567d..e495392 100644 --- a/components/update_client/update_client.cc +++ b/components/update_client/update_client.cc
@@ -234,7 +234,8 @@ void UpdateClientImpl::SendUninstallPing(const std::string& id, const base::Version& version, - int reason) { + int reason, + const Callback& callback) { DCHECK(thread_checker_.CalledOnValidThread()); // The implementation of PingManager::SendPing contains a self-deleting @@ -247,6 +248,9 @@ item.extra_code1 = reason; ping_manager_->SendPing(&item); + + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::Bind(callback, Error::NONE)); } scoped_refptr<UpdateClient> UpdateClientFactory(
diff --git a/components/update_client/update_client.h b/components/update_client/update_client.h index cdcd956f..412a4d9 100644 --- a/components/update_client/update_client.h +++ b/components/update_client/update_client.h
@@ -328,7 +328,8 @@ // of this class. virtual void SendUninstallPing(const std::string& id, const base::Version& version, - int reason) = 0; + int reason, + const Callback& callback) = 0; // Returns status details about a CRX update. The function returns true in // case of success and false in case of errors, such as |id| was
diff --git a/components/update_client/update_client_internal.h b/components/update_client/update_client_internal.h index 2f675a8..83cdd10 100644 --- a/components/update_client/update_client_internal.h +++ b/components/update_client/update_client_internal.h
@@ -49,7 +49,8 @@ void Stop() override; void SendUninstallPing(const std::string& id, const base::Version& version, - int reason) override; + int reason, + const Callback& callback) override; private: ~UpdateClientImpl() override;
diff --git a/components/update_client/update_client_unittest.cc b/components/update_client/update_client_unittest.cc index dd8302e..20eb9c7f 100644 --- a/components/update_client/update_client_unittest.cc +++ b/components/update_client/update_client_unittest.cc
@@ -2233,6 +2233,13 @@ } TEST_F(UpdateClientTest, SendUninstallPing) { + class CompletionCallbackFake { + public: + static void Callback(const base::Closure& quit_closure, Error error) { + quit_closure.Run(); + } + }; + class FakeUpdateChecker : public UpdateChecker { public: static std::unique_ptr<UpdateChecker> Create( @@ -2286,8 +2293,11 @@ config(), std::move(ping_manager), &FakeUpdateChecker::Create, &FakeCrxDownloader::Create)); - update_client->SendUninstallPing("jebgalgnebhfojomionfpkfelancnnkf", - base::Version("1.0"), 10); + update_client->SendUninstallPing( + "jebgalgnebhfojomionfpkfelancnnkf", base::Version("1.0"), 10, + base::Bind(&CompletionCallbackFake::Callback, quit_closure())); + + RunThreads(); } TEST_F(UpdateClientTest, RetryAfter) {
diff --git a/components/variations/android/java/src/org/chromium/components/variations/firstrun/VariationsSeedBridge.java b/components/variations/android/java/src/org/chromium/components/variations/firstrun/VariationsSeedBridge.java index cbd1beb..93500c6 100644 --- a/components/variations/android/java/src/org/chromium/components/variations/firstrun/VariationsSeedBridge.java +++ b/components/variations/android/java/src/org/chromium/components/variations/firstrun/VariationsSeedBridge.java
@@ -4,7 +4,6 @@ package org.chromium.components.variations.firstrun; -import android.content.Context; import android.util.Base64; import org.chromium.base.ContextUtils; @@ -29,7 +28,7 @@ protected static final String VARIATIONS_FIRST_RUN_SEED_NATIVE_STORED = "variations_seed_native_stored"; - protected static String getVariationsFirstRunSeedPref(Context context, String prefName) { + protected static String getVariationsFirstRunSeedPref(String prefName) { return ContextUtils.getAppSharedPreferences().getString(prefName, ""); } @@ -38,8 +37,8 @@ * CalledByNative attribute is used by unit tests code to set test data. */ @CalledByNative - public static void setVariationsFirstRunSeed(Context context, byte[] rawSeed, String signature, - String country, String date, boolean isGzipCompressed) { + public static void setVariationsFirstRunSeed(byte[] rawSeed, String signature, String country, + String date, boolean isGzipCompressed) { ContextUtils.getAppSharedPreferences() .edit() .putString(VARIATIONS_FIRST_RUN_SEED_BASE64, @@ -52,7 +51,7 @@ } @CalledByNative - private static void clearFirstRunPrefs(Context context) { + private static void clearFirstRunPrefs() { ContextUtils.getAppSharedPreferences() .edit() .remove(VARIATIONS_FIRST_RUN_SEED_BASE64) @@ -66,7 +65,7 @@ /** * Returns the status of the variations first run fetch: was it successful or not. */ - public static boolean hasJavaPref(Context context) { + public static boolean hasJavaPref() { return !ContextUtils.getAppSharedPreferences() .getString(VARIATIONS_FIRST_RUN_SEED_BASE64, "") .isEmpty(); @@ -75,13 +74,13 @@ /** * Returns the status of the variations seed storing on the C++ side: was it successful or not. */ - public static boolean hasNativePref(Context context) { + public static boolean hasNativePref() { return ContextUtils.getAppSharedPreferences().getBoolean( VARIATIONS_FIRST_RUN_SEED_NATIVE_STORED, false); } @CalledByNative - private static void markVariationsSeedAsStored(Context context) { + private static void markVariationsSeedAsStored() { ContextUtils.getAppSharedPreferences() .edit() .putBoolean(VARIATIONS_FIRST_RUN_SEED_NATIVE_STORED, true) @@ -89,29 +88,28 @@ } @CalledByNative - private static byte[] getVariationsFirstRunSeedData(Context context) { + private static byte[] getVariationsFirstRunSeedData() { return Base64.decode( - getVariationsFirstRunSeedPref(context, VARIATIONS_FIRST_RUN_SEED_BASE64), - Base64.NO_WRAP); + getVariationsFirstRunSeedPref(VARIATIONS_FIRST_RUN_SEED_BASE64), Base64.NO_WRAP); } @CalledByNative - private static String getVariationsFirstRunSeedSignature(Context context) { - return getVariationsFirstRunSeedPref(context, VARIATIONS_FIRST_RUN_SEED_SIGNATURE); + private static String getVariationsFirstRunSeedSignature() { + return getVariationsFirstRunSeedPref(VARIATIONS_FIRST_RUN_SEED_SIGNATURE); } @CalledByNative - private static String getVariationsFirstRunSeedCountry(Context context) { - return getVariationsFirstRunSeedPref(context, VARIATIONS_FIRST_RUN_SEED_COUNTRY); + private static String getVariationsFirstRunSeedCountry() { + return getVariationsFirstRunSeedPref(VARIATIONS_FIRST_RUN_SEED_COUNTRY); } @CalledByNative - private static String getVariationsFirstRunSeedDate(Context context) { - return getVariationsFirstRunSeedPref(context, VARIATIONS_FIRST_RUN_SEED_DATE); + private static String getVariationsFirstRunSeedDate() { + return getVariationsFirstRunSeedPref(VARIATIONS_FIRST_RUN_SEED_DATE); } @CalledByNative - private static boolean getVariationsFirstRunSeedIsGzipCompressed(Context context) { + private static boolean getVariationsFirstRunSeedIsGzipCompressed() { return ContextUtils.getAppSharedPreferences().getBoolean( VARIATIONS_FIRST_RUN_SEED_IS_GZIP_COMPRESSED, false); }
diff --git a/components/variations/android/java/src/org/chromium/components/variations/firstrun/VariationsSeedFetcher.java b/components/variations/android/java/src/org/chromium/components/variations/firstrun/VariationsSeedFetcher.java index 3c69677..b02c6f1 100644 --- a/components/variations/android/java/src/org/chromium/components/variations/firstrun/VariationsSeedFetcher.java +++ b/components/variations/android/java/src/org/chromium/components/variations/firstrun/VariationsSeedFetcher.java
@@ -103,7 +103,7 @@ // Note that VariationsSeedBridge.hasNativePref() is a pure Java function, reading an // Android preference that is set when the seed is fetched by the native code. if (prefs.getBoolean(VARIATIONS_INITIALIZED_PREF, false) - || VariationsSeedBridge.hasNativePref(context)) { + || VariationsSeedBridge.hasNativePref()) { return; } downloadContent(context, restrictMode); @@ -155,7 +155,7 @@ String date = getHeaderFieldOrEmpty(connection, "Date"); boolean isGzipCompressed = getHeaderFieldOrEmpty(connection, "IM").equals("gzip"); VariationsSeedBridge.setVariationsFirstRunSeed( - context, rawSeed, signature, country, date, isGzipCompressed); + rawSeed, signature, country, date, isGzipCompressed); recordSeedFetchTime(SystemClock.elapsedRealtime() - startTimeMillis); } catch (SocketTimeoutException e) { recordFetchResultOrCode(SEED_FETCH_RESULT_TIMEOUT);
diff --git a/components/variations/android/junit/src/org/chromium/components/variations/firstrun/VariationsSeedFetcherTest.java b/components/variations/android/junit/src/org/chromium/components/variations/firstrun/VariationsSeedFetcherTest.java index 5cad3a2b..5415c9f 100644 --- a/components/variations/android/junit/src/org/chromium/components/variations/firstrun/VariationsSeedFetcherTest.java +++ b/components/variations/android/junit/src/org/chromium/components/variations/firstrun/VariationsSeedFetcherTest.java
@@ -116,7 +116,7 @@ mFetcher.fetchSeed(""); assertTrue(mPrefs.getBoolean(VariationsSeedFetcher.VARIATIONS_INITIALIZED_PREF, false)); - assertFalse(VariationsSeedBridge.hasJavaPref(ContextUtils.getApplicationContext())); + assertFalse(VariationsSeedBridge.hasJavaPref()); } /** @@ -129,6 +129,6 @@ mFetcher.fetchSeed(""); assertTrue(mPrefs.getBoolean(VariationsSeedFetcher.VARIATIONS_INITIALIZED_PREF, false)); - assertFalse(VariationsSeedBridge.hasJavaPref(ContextUtils.getApplicationContext())); + assertFalse(VariationsSeedBridge.hasJavaPref()); } }
diff --git a/components/variations/android/variations_seed_bridge.cc b/components/variations/android/variations_seed_bridge.cc index f5b73e9..6b7bd84 100644 --- a/components/variations/android/variations_seed_bridge.cc +++ b/components/variations/android/variations_seed_bridge.cc
@@ -8,7 +8,6 @@ #include <stdint.h> #include <vector> -#include "base/android/context_utils.h" #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" @@ -18,7 +17,6 @@ using base::android::AttachCurrentThread; using base::android::ConvertJavaStringToUTF8; using base::android::ConvertUTF8ToJavaString; -using base::android::GetApplicationContext; using base::android::ScopedJavaLocalRef; namespace { @@ -50,20 +48,15 @@ bool* is_gzip_compressed) { JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jbyteArray> j_seed_data = - Java_VariationsSeedBridge_getVariationsFirstRunSeedData( - env, GetApplicationContext()); + Java_VariationsSeedBridge_getVariationsFirstRunSeedData(env); ScopedJavaLocalRef<jstring> j_seed_signature = - Java_VariationsSeedBridge_getVariationsFirstRunSeedSignature( - env, GetApplicationContext()); + Java_VariationsSeedBridge_getVariationsFirstRunSeedSignature(env); ScopedJavaLocalRef<jstring> j_seed_country = - Java_VariationsSeedBridge_getVariationsFirstRunSeedCountry( - env, GetApplicationContext()); + Java_VariationsSeedBridge_getVariationsFirstRunSeedCountry(env); ScopedJavaLocalRef<jstring> j_response_date = - Java_VariationsSeedBridge_getVariationsFirstRunSeedDate( - env, GetApplicationContext()); + Java_VariationsSeedBridge_getVariationsFirstRunSeedDate(env); jboolean j_is_gzip_compressed = - Java_VariationsSeedBridge_getVariationsFirstRunSeedIsGzipCompressed( - env, GetApplicationContext()); + Java_VariationsSeedBridge_getVariationsFirstRunSeedIsGzipCompressed(env); *seed_data = JavaByteArrayToString(env, j_seed_data.obj()); *seed_signature = ConvertJavaStringToUTF8(j_seed_signature); *seed_country = ConvertJavaStringToUTF8(j_seed_country); @@ -73,13 +66,12 @@ void ClearJavaFirstRunPrefs() { JNIEnv* env = AttachCurrentThread(); - Java_VariationsSeedBridge_clearFirstRunPrefs(env, GetApplicationContext()); + Java_VariationsSeedBridge_clearFirstRunPrefs(env); } void MarkVariationsSeedAsStored() { JNIEnv* env = AttachCurrentThread(); - Java_VariationsSeedBridge_markVariationsSeedAsStored(env, - GetApplicationContext()); + Java_VariationsSeedBridge_markVariationsSeedAsStored(env); } void SetJavaFirstRunPrefsForTesting(const std::string& seed_data, @@ -89,7 +81,7 @@ bool is_gzip_compressed) { JNIEnv* env = AttachCurrentThread(); Java_VariationsSeedBridge_setVariationsFirstRunSeed( - env, GetApplicationContext(), StringToJavaByteArray(env, seed_data), + env, StringToJavaByteArray(env, seed_data), ConvertUTF8ToJavaString(env, seed_signature), ConvertUTF8ToJavaString(env, seed_country), ConvertUTF8ToJavaString(env, response_date),
diff --git a/components/viz/frame_sinks/mojo_frame_sink_manager.h b/components/viz/frame_sinks/mojo_frame_sink_manager.h index 5a9d461..5fb8fa60 100644 --- a/components/viz/frame_sinks/mojo_frame_sink_manager.h +++ b/components/viz/frame_sinks/mojo_frame_sink_manager.h
@@ -46,7 +46,7 @@ cc::SurfaceManager* surface_manager() { return &manager_; } - // cc::mojom::MojoFrameSinkManager implementation: + // cc::mojom::FrameSinkManager implementation: void CreateRootCompositorFrameSink( const cc::FrameSinkId& frame_sink_id, gpu::SurfaceHandle surface_handle,
diff --git a/content/browser/renderer_host/input/passthrough_touch_event_queue.cc b/content/browser/renderer_host/input/passthrough_touch_event_queue.cc index ae2131f..b9cc039 100644 --- a/content/browser/renderer_host/input/passthrough_touch_event_queue.cc +++ b/content/browser/renderer_host/input/passthrough_touch_event_queue.cc
@@ -24,6 +24,10 @@ namespace content { namespace { +// A sanity check on touches received to ensure that touch movement outside +// the platform slop region will cause scrolling. +const double kMaxConceivablePlatformSlopRegionLengthDipsSquared = 60. * 60.; + // Compare all properties of touch points to determine the state. bool HasPointChanged(const WebTouchPoint& point_1, const WebTouchPoint& point_2) { @@ -42,6 +46,59 @@ } // namespace +// Provides touchmove slop suppression for a touch sequence until a +// (unprevented) touch will trigger immediate scrolling. +class TouchMoveSlopSuppressor { + public: + TouchMoveSlopSuppressor() : suppressing_touchmoves_(false) {} + + bool FilterEvent(const WebTouchEvent& event) { + if (WebTouchEventTraits::IsTouchSequenceStart(event)) { + suppressing_touchmoves_ = true; + touch_start_location_ = gfx::PointF(event.touches[0].position); + } + + if (event.GetType() == WebInputEvent::kTouchEnd || + event.GetType() == WebInputEvent::kTouchCancel) + suppressing_touchmoves_ = false; + + if (event.GetType() != WebInputEvent::kTouchMove) + return false; + + if (suppressing_touchmoves_) { + if (event.touches_length > 1) { + suppressing_touchmoves_ = false; + } else if (event.moved_beyond_slop_region) { + suppressing_touchmoves_ = false; + } else { + // No sane slop region should be larger than 60 DIPs. + DCHECK_LT( + (gfx::PointF(event.touches[0].position) - touch_start_location_) + .LengthSquared(), + kMaxConceivablePlatformSlopRegionLengthDipsSquared); + } + } + + return suppressing_touchmoves_; + } + + void ConfirmTouchEvent(InputEventAckState ack_result) { + if (ack_result == INPUT_EVENT_ACK_STATE_CONSUMED) + suppressing_touchmoves_ = false; + } + + bool suppressing_touchmoves() const { return suppressing_touchmoves_; } + + private: + bool suppressing_touchmoves_; + + // Sanity check that the upstream touch provider is properly reporting whether + // the touch sequence will cause scrolling. + gfx::PointF touch_start_location_; + + DISALLOW_COPY_AND_ASSIGN(TouchMoveSlopSuppressor); +}; + PassthroughTouchEventQueue::TouchEventWithLatencyInfoAndAckState:: TouchEventWithLatencyInfoAndAckState(const TouchEventWithLatencyInfo& event) : TouchEventWithLatencyInfo(event), @@ -59,6 +116,7 @@ has_handlers_(true), maybe_has_handler_for_current_sequence_(false), drop_remaining_touches_in_sequence_(false), + touchmove_slop_suppressor_(new TouchMoveSlopSuppressor), send_touch_events_async_(false), processing_acks_(false) { if (config.touch_ack_timeout_supported) { @@ -121,6 +179,8 @@ timeout_handler_->ConfirmTouchEvent(unique_touch_event_id, ack_result)) return; + touchmove_slop_suppressor_->ConfirmTouchEvent(ack_result); + auto touch_event_iter = outstanding_touches_.begin(); while (touch_event_iter != outstanding_touches_.end()) { if (unique_touch_event_id == touch_event_iter->event.unique_touch_event_id) @@ -303,6 +363,9 @@ if (timeout_handler_ && timeout_handler_->FilterEvent(event)) return ACK_WITH_NO_CONSUMER_EXISTS; + if (touchmove_slop_suppressor_->FilterEvent(event)) + return ACK_WITH_NOT_CONSUMED; + if (drop_remaining_touches_in_sequence_ && event.GetType() != WebInputEvent::kTouchCancel) { return ACK_WITH_NO_CONSUMER_EXISTS;
diff --git a/content/browser/renderer_host/input/passthrough_touch_event_queue.h b/content/browser/renderer_host/input/passthrough_touch_event_queue.h index cae55abf..d38ee425 100644 --- a/content/browser/renderer_host/input/passthrough_touch_event_queue.h +++ b/content/browser/renderer_host/input/passthrough_touch_event_queue.h
@@ -12,6 +12,7 @@ namespace content { class TouchTimeoutHandler; +class TouchMoveSlopSuppressor; // A queue that processes a touch-event and forwards it on to the // renderer process immediately. This class assumes that queueing will @@ -115,6 +116,10 @@ // cancelled after a touch timeout. bool drop_remaining_touches_in_sequence_; + // Suppresses TouchMove's within a slop region when a sequence has not yet + // been preventDefaulted. + std::unique_ptr<TouchMoveSlopSuppressor> touchmove_slop_suppressor_; + // Optional handler for timed-out touch event acks. std::unique_ptr<TouchTimeoutHandler> timeout_handler_;
diff --git a/content/browser/renderer_host/input/passthrough_touch_event_queue_unittest.cc b/content/browser/renderer_host/input/passthrough_touch_event_queue_unittest.cc index 2bed8a6df..6e3d0c1 100644 --- a/content/browser/renderer_host/input/passthrough_touch_event_queue_unittest.cc +++ b/content/browser/renderer_host/input/passthrough_touch_event_queue_unittest.cc
@@ -1290,37 +1290,32 @@ // TouchMove's movedBeyondSlopRegion within the slop region is set to false. MoveTouchPoint(0, 0, kHalfSlopLengthDips); - EXPECT_EQ(1U, queued_event_count()); - SendTouchEventAck(INPUT_EVENT_ACK_STATE_NOT_CONSUMED); - EXPECT_EQ(1U, GetAndResetSentEventCount()); + EXPECT_EQ(0U, queued_event_count()); + EXPECT_EQ(0U, GetAndResetSentEventCount()); EXPECT_EQ(1U, GetAndResetAckedEventCount()); EXPECT_FALSE(acked_event().moved_beyond_slop_region); MoveTouchPoint(0, kHalfSlopLengthDips, 0); - EXPECT_EQ(1U, queued_event_count()); - SendTouchEventAck(INPUT_EVENT_ACK_STATE_NOT_CONSUMED); - EXPECT_EQ(1U, GetAndResetSentEventCount()); + EXPECT_EQ(0U, queued_event_count()); + EXPECT_EQ(0U, GetAndResetSentEventCount()); EXPECT_EQ(1U, GetAndResetAckedEventCount()); EXPECT_FALSE(acked_event().moved_beyond_slop_region); MoveTouchPoint(0, -kHalfSlopLengthDips, 0); - EXPECT_EQ(1U, queued_event_count()); - SendTouchEventAck(INPUT_EVENT_ACK_STATE_NOT_CONSUMED); - EXPECT_EQ(1U, GetAndResetSentEventCount()); + EXPECT_EQ(0U, queued_event_count()); + EXPECT_EQ(0U, GetAndResetSentEventCount()); EXPECT_EQ(1U, GetAndResetAckedEventCount()); EXPECT_FALSE(acked_event().moved_beyond_slop_region); MoveTouchPoint(0, -kSlopLengthDips, 0); - EXPECT_EQ(1U, queued_event_count()); - SendTouchEventAck(INPUT_EVENT_ACK_STATE_NOT_CONSUMED); - EXPECT_EQ(1U, GetAndResetSentEventCount()); + EXPECT_EQ(0U, queued_event_count()); + EXPECT_EQ(0U, GetAndResetSentEventCount()); EXPECT_EQ(1U, GetAndResetAckedEventCount()); EXPECT_FALSE(acked_event().moved_beyond_slop_region); MoveTouchPoint(0, 0, kSlopLengthDips); - EXPECT_EQ(1U, queued_event_count()); - SendTouchEventAck(INPUT_EVENT_ACK_STATE_NOT_CONSUMED); - EXPECT_EQ(1U, GetAndResetSentEventCount()); + EXPECT_EQ(0U, queued_event_count()); + EXPECT_EQ(0U, GetAndResetSentEventCount()); EXPECT_EQ(1U, GetAndResetAckedEventCount()); EXPECT_FALSE(acked_event().moved_beyond_slop_region); @@ -1335,7 +1330,6 @@ EXPECT_EQ(0U, GetAndResetAckedEventCount()); SendTouchEventAck(INPUT_EVENT_ACK_STATE_NOT_CONSUMED); EXPECT_EQ(1U, GetAndResetAckedEventCount()); - EXPECT_TRUE(acked_event().moved_beyond_slop_region); } // Tests that even very small TouchMove's movedBeyondSlopRegion is set to true
diff --git a/content/browser/renderer_host/media/audio_input_sync_writer.cc b/content/browser/renderer_host/media/audio_input_sync_writer.cc index c72b1cd..b1767aff 100644 --- a/content/browser/renderer_host/media/audio_input_sync_writer.cc +++ b/content/browser/renderer_host/media/audio_input_sync_writer.cc
@@ -5,6 +5,7 @@ #include "content/browser/renderer_host/media/audio_input_sync_writer.h" #include <algorithm> +#include <utility> #include "base/format_macros.h" #include "base/metrics/histogram_macros.h" @@ -47,6 +48,7 @@ write_count_(0), write_to_fifo_count_(0), write_error_count_(0), + had_socket_error_(false), trailing_write_to_fifo_count_(0), trailing_write_error_count_(0) { DCHECK_GT(shared_memory_segment_count, 0); @@ -328,13 +330,20 @@ bool AudioInputSyncWriter::SignalDataWrittenAndUpdateCounters() { if (socket_->Send(¤t_segment_id_, sizeof(current_segment_id_)) != sizeof(current_segment_id_)) { - const std::string error_message = "AISW: No room in socket buffer."; - LOG(WARNING) << error_message; - AddToNativeLog(error_message); - TRACE_EVENT_INSTANT0("audio", - "AudioInputSyncWriter: No room in socket buffer", - TRACE_EVENT_SCOPE_THREAD); + // Ensure we don't log consecutive errors as this can lead to a large + // amount of logs. + if (!had_socket_error_) { + had_socket_error_ = true; + const std::string error_message = "AISW: No room in socket buffer."; + PLOG(WARNING) << error_message; + AddToNativeLog(error_message); + TRACE_EVENT_INSTANT0("audio", + "AudioInputSyncWriter: No room in socket buffer", + TRACE_EVENT_SCOPE_THREAD); + } return false; + } else { + had_socket_error_ = false; } if (++current_segment_id_ >= shared_memory_segment_count_)
diff --git a/content/browser/renderer_host/media/audio_input_sync_writer.h b/content/browser/renderer_host/media/audio_input_sync_writer.h index 880e49c..a65f9008 100644 --- a/content/browser/renderer_host/media/audio_input_sync_writer.h +++ b/content/browser/renderer_host/media/audio_input_sync_writer.h
@@ -10,6 +10,7 @@ #include <deque> #include <memory> +#include <string> #include <vector> #include "base/gtest_prod_util.h" @@ -142,6 +143,10 @@ // the fifo or the socket buffer being full. size_t write_error_count_; + // Denotes that the most recent socket error has been logged. Used to avoid + // log spam. + bool had_socket_error_; + // Counts the fifo writes and errors we get during renderer process teardown // so that we can account for that (subtract) when we calculate the overall // counts.
diff --git a/content/browser/renderer_host/media/audio_sync_reader.cc b/content/browser/renderer_host/media/audio_sync_reader.cc index be6afd9..18ac79d0 100644 --- a/content/browser/renderer_host/media/audio_sync_reader.cc +++ b/content/browser/renderer_host/media/audio_sync_reader.cc
@@ -53,6 +53,7 @@ : shared_memory_(std::move(shared_memory)), mute_audio_(base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kMuteAudio)), + had_socket_error_(false), socket_(std::move(socket)), foreign_socket_(std::move(foreign_socket)), packet_size_(shared_memory_->requested_size()), @@ -176,12 +177,18 @@ size_t sent_bytes = socket_->Send(&control_signal, sizeof(control_signal)); if (sent_bytes != sizeof(control_signal)) { - const std::string error_message = "ASR: No room in socket buffer."; - LOG(WARNING) << error_message; - MediaStreamManager::SendMessageToNativeLog(error_message); - TRACE_EVENT_INSTANT0("audio", - "AudioSyncReader: No room in socket buffer", - TRACE_EVENT_SCOPE_THREAD); + // Ensure we don't log consecutive errors as this can lead to a large + // amount of logs. + if (!had_socket_error_) { + had_socket_error_ = true; + const std::string error_message = "ASR: No room in socket buffer."; + PLOG(WARNING) << error_message; + MediaStreamManager::SendMessageToNativeLog(error_message); + TRACE_EVENT_INSTANT0("audio", "AudioSyncReader: No room in socket buffer", + TRACE_EVENT_SCOPE_THREAD); + } + } else { + had_socket_error_ = false; } ++buffer_index_; }
diff --git a/content/browser/renderer_host/media/audio_sync_reader.h b/content/browser/renderer_host/media/audio_sync_reader.h index 9cccff15..a82f592 100644 --- a/content/browser/renderer_host/media/audio_sync_reader.h +++ b/content/browser/renderer_host/media/audio_sync_reader.h
@@ -67,6 +67,10 @@ // during automated testing. const bool mute_audio_; + // Denotes that the most recent socket error has been logged. Used to avoid + // log spam. + bool had_socket_error_; + // Socket for transmitting audio data. std::unique_ptr<base::CancelableSyncSocket> socket_;
diff --git a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc index e800151..ea4ca38 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc
@@ -1693,7 +1693,7 @@ EXPECT_TRUE(press.synchronous_handling_disabled()); EXPECT_EQ(ui::MotionEvent::ACTION_DOWN, pointer_state().GetAction()); EXPECT_EQ(1U, pointer_state().GetPointerCount()); - EXPECT_EQ(3U, GetSentMessageCountAndResetSink()); + EXPECT_EQ(2U, GetSentMessageCountAndResetSink()); widget_host_->OnMessageReceived(ViewHostMsg_HasTouchEventHandlers(0, false));
diff --git a/content/browser/renderer_host/render_widget_host_view_base.cc b/content/browser/renderer_host/render_widget_host_view_base.cc index 4dd0e59..8c862b6 100644 --- a/content/browser/renderer_host/render_widget_host_view_base.cc +++ b/content/browser/renderer_host/render_widget_host_view_base.cc
@@ -138,7 +138,6 @@ } bool RenderWidgetHostViewBase::IsInVR() const { - NOTIMPLEMENTED(); return false; }
diff --git a/content/browser/streams/stream_url_request_job.cc b/content/browser/streams/stream_url_request_job.cc index f6ea712..b9714b1 100644 --- a/content/browser/streams/stream_url_request_job.cc +++ b/content/browser/streams/stream_url_request_job.cc
@@ -138,13 +138,6 @@ *info = *response_info_; } -int StreamURLRequestJob::GetResponseCode() const { - if (!response_info_) - return -1; - - return response_info_->headers->response_code(); -} - int64_t StreamURLRequestJob::GetTotalReceivedBytes() const { int64_t total_received_bytes = 0; if (response_info_)
diff --git a/content/browser/streams/stream_url_request_job.h b/content/browser/streams/stream_url_request_job.h index 741af05..2eafa5f9 100644 --- a/content/browser/streams/stream_url_request_job.h +++ b/content/browser/streams/stream_url_request_job.h
@@ -33,7 +33,6 @@ int ReadRawData(net::IOBuffer* buf, int buf_size) override; bool GetMimeType(std::string* mime_type) const override; void GetResponseInfo(net::HttpResponseInfo* info) override; - int GetResponseCode() const override; int64_t GetTotalReceivedBytes() const override; protected:
diff --git a/content/child/runtime_features.cc b/content/child/runtime_features.cc index 668dc0fe0..d0a3c95 100644 --- a/content/child/runtime_features.cc +++ b/content/child/runtime_features.cc
@@ -111,11 +111,8 @@ if (!base::FeatureList::IsEnabled(features::kNotificationContentImage)) WebRuntimeFeatures::EnableNotificationContentImage(false); - // For the time being, wasm serialization is separately controlled - // by this flag. WebAssembly APIs and compilation is now enabled - // unconditionally in V8. - if (base::FeatureList::IsEnabled(features::kWebAssembly)) - WebRuntimeFeatures::EnableWebAssemblySerialization(true); + WebRuntimeFeatures::EnableWebAssemblyStreaming( + base::FeatureList::IsEnabled(features::kWebAssemblyStreaming)); WebRuntimeFeatures::EnableSharedArrayBuffer( base::FeatureList::IsEnabled(features::kSharedArrayBuffer)); @@ -304,6 +301,10 @@ base::FeatureList::IsEnabled( features::kFramebustingNeedsSameOriginOrUserGesture)); + WebRuntimeFeatures::EnableFeatureFromString( + "VibrateRequiresUserGesture", + base::FeatureList::IsEnabled(features::kVibrateRequiresUserGesture)); + if (command_line.HasSwitch(switches::kDisableBackgroundTimerThrottling)) WebRuntimeFeatures::EnableTimerThrottlingForBackgroundTabs(false);
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index 1436426c..b8443f8 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -226,14 +226,22 @@ const base::Feature kTouchpadAndWheelScrollLatching{ "TouchpadAndWheelScrollLatching", base::FEATURE_DISABLED_BY_DEFAULT}; +// Controls whether vibrate requires user gesture. +const base::Feature kVibrateRequiresUserGesture{ + "VibrateRequiresUserGesture", base::FEATURE_DISABLED_BY_DEFAULT}; + // Enables VR UI. const base::Feature kVrShell{"VrShell", base::FEATURE_DISABLED_BY_DEFAULT}; -// Enable WebAssembly. +// Enable WebAssembly structured cloning. // http://webassembly.org/ const base::Feature kWebAssembly{"WebAssembly", base::FEATURE_DISABLED_BY_DEFAULT}; +// Enable WebAssembly streamed compilation. +const base::Feature kWebAssemblyStreaming{"WebAssemblyStreaming", + base::FEATURE_DISABLED_BY_DEFAULT}; + // If WebGL Image Chromium is allowed, this feature controls whether it is // enabled. const base::Feature kWebGLImageChromium{"WebGLImageChromium",
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index 80e7807..a01873c 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -60,8 +60,10 @@ CONTENT_EXPORT extern const base::Feature kTimerThrottlingForHiddenFrames; CONTENT_EXPORT extern const base::Feature kTokenBinding; CONTENT_EXPORT extern const base::Feature kTouchpadAndWheelScrollLatching; +CONTENT_EXPORT extern const base::Feature kVibrateRequiresUserGesture; CONTENT_EXPORT extern const base::Feature kVrShell; CONTENT_EXPORT extern const base::Feature kWebAssembly; +CONTENT_EXPORT extern const base::Feature kWebAssemblyStreaming; CONTENT_EXPORT extern const base::Feature kWebGLImageChromium; CONTENT_EXPORT extern const base::Feature kWebPayments; CONTENT_EXPORT extern const base::Feature kWebRtcEcdsaDefault;
diff --git a/content/shell/browser/shell_devtools_bindings.cc b/content/shell/browser/shell_devtools_bindings.cc index 250273d6..77bfc75 100644 --- a/content/shell/browser/shell_devtools_bindings.cc +++ b/content/shell/browser/shell_devtools_bindings.cc
@@ -28,6 +28,7 @@ #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/http/http_response_headers.h" +#include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_response_writer.h" @@ -222,8 +223,35 @@ return; } + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation( + "devtools_handle_front_end_messages", R"( + semantics { + sender: "Developer Tools" + description: + "When user opens Developer Tools, the browser may fetch " + "additional resources from the network to enrich the debugging " + "experience (e.g. source map resources)." + trigger: "User opens Developer Tools to debug a web page." + data: "Any resources requested by Developer Tools." + destination: OTHER + } + policy { + cookies_allowed: true + cookies_store: "user" + setting: + "It's not possible to disable this feature from settings." + chrome_policy { + DeveloperToolsDisabled { + policy_options {mode: MANDATORY} + DeveloperToolsDisabled: true + } + } + })"); net::URLFetcher* fetcher = - net::URLFetcher::Create(gurl, net::URLFetcher::GET, this).release(); + net::URLFetcher::Create(gurl, net::URLFetcher::GET, this, + traffic_annotation) + .release(); pending_requests_[fetcher] = request_id; fetcher->SetRequestContext(BrowserContext::GetDefaultStoragePartition( web_contents()->GetBrowserContext())
diff --git a/device/vr/BUILD.gn b/device/vr/BUILD.gn index 97903c48..6afccbc 100644 --- a/device/vr/BUILD.gn +++ b/device/vr/BUILD.gn
@@ -46,7 +46,6 @@ "vr_device_provider.h", "vr_display_impl.cc", "vr_display_impl.h", - "vr_export.h", "vr_math.cc", "vr_math.h", "vr_service_impl.cc",
diff --git a/docs/ios/build_instructions.md b/docs/ios/build_instructions.md index db1844c..9aa2539 100644 --- a/docs/ios/build_instructions.md +++ b/docs/ios/build_instructions.md
@@ -142,6 +142,7 @@ - `${prefix}.chrome.ios.herebedragons` - `${prefix}.chrome.ios.herebedragons.ShareExtension` - `${prefix}.chrome.ios.herebedragons.TodayExtension` +- `${prefix}.chrome.ios.herebedragons.SearchTodayExtension` All these certificates need to have the "App Groups" (`com.apple.security.application-groups`) capability enabled for
diff --git a/extensions/browser/updater/update_service.cc b/extensions/browser/updater/update_service.cc index 8946a16b..92b5efe 100644 --- a/extensions/browser/updater/update_service.cc +++ b/extensions/browser/updater/update_service.cc
@@ -18,6 +18,8 @@ void UpdateCheckCompleteCallback(update_client::Error error) {} +void SendUninstallPingCompleteCallback(update_client::Error error) {} + void InstallUpdateCallback(content::BrowserContext* context, const std::string& extension_id, const base::FilePath& temp_dir) { @@ -46,7 +48,8 @@ void UpdateService::SendUninstallPing(const std::string& id, const base::Version& version, int reason) { - update_client_->SendUninstallPing(id, version, reason); + update_client_->SendUninstallPing( + id, version, reason, base::Bind(&SendUninstallPingCompleteCallback)); } void UpdateService::StartUpdateCheck(
diff --git a/extensions/browser/updater/update_service_unittest.cc b/extensions/browser/updater/update_service_unittest.cc index 3c03909..d75329c 100644 --- a/extensions/browser/updater/update_service_unittest.cc +++ b/extensions/browser/updater/update_service_unittest.cc
@@ -65,7 +65,8 @@ void Stop() override {} void SendUninstallPing(const std::string& id, const base::Version& version, - int reason) override { + int reason, + const update_client::Callback& callback) override { uninstall_pings_.emplace_back(id, version, reason); }
diff --git a/extensions/renderer/event_emitter.cc b/extensions/renderer/event_emitter.cc index 79b1e82..ccd4303 100644 --- a/extensions/renderer/event_emitter.cc +++ b/extensions/renderer/event_emitter.cc
@@ -130,11 +130,7 @@ v8::HandleScope handle_scope(arguments->isolate()); v8::Local<v8::Context> context = arguments->isolate()->GetCurrentContext(); - std::vector<v8::Local<v8::Value>> v8_args; - if (arguments->Length() > 0) { - // Converting to v8::Values should never fail. - CHECK(arguments->GetRemaining(&v8_args)); - } + std::vector<v8::Local<v8::Value>> v8_args = arguments->GetAll(); Fire(context, &v8_args, nullptr); }
diff --git a/gin/arguments.cc b/gin/arguments.cc index 600a811..4d01c0e4 100644 --- a/gin/arguments.cc +++ b/gin/arguments.cc
@@ -32,6 +32,19 @@ return (*info_)[next_]; } +std::vector<v8::Local<v8::Value>> Arguments::GetAll() const { + std::vector<v8::Local<v8::Value>> result; + int length = info_->Length(); + if (length == 0) + return result; + + result.reserve(length); + for (int i = 0; i < length; ++i) + result.push_back((*info_)[i]); + + return result; +} + v8::Local<v8::Context> Arguments::GetHolderCreationContext() { return info_->Holder()->CreationContext(); }
diff --git a/gin/arguments.h b/gin/arguments.h index 99a5d16d..c0a7bc2 100644 --- a/gin/arguments.h +++ b/gin/arguments.h
@@ -81,6 +81,11 @@ // dereferencing the handle. v8::Local<v8::Value> PeekNext() const; + // Returns all arguments. Since this doesn't require any conversion, it + // cannot fail. This does not rely on or modify the current position in the + // array used by Get/PeekNext(). + std::vector<v8::Local<v8::Value>> GetAll() const; + void ThrowError() const; void ThrowTypeError(const std::string& message) const;
diff --git a/gin/arguments_unittest.cc b/gin/arguments_unittest.cc index d2b5136..3a262c7 100644 --- a/gin/arguments_unittest.cc +++ b/gin/arguments_unittest.cc
@@ -64,4 +64,67 @@ } } +TEST_F(ArgumentsTest, TestGetAll) { + v8::Isolate* isolate = instance_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Local<v8::Context> context = context_.Get(instance_->isolate()); + + using V8List = std::vector<v8::Local<v8::Value>>; + + V8List list1 = { + gin::ConvertToV8(isolate, 1), gin::StringToV8(isolate, "some string"), + gin::ConvertToV8(context, std::vector<double>({2.0, 3.0})) + .ToLocalChecked(), + }; + bool called1 = false; + + V8List list2 = { + gin::StringToV8(isolate, "some other string"), + gin::ConvertToV8(isolate, 42), + }; + bool called2 = false; + + V8List list3; // Empty list. + bool called3 = false; + + auto check_arguments = [](V8List* expected, bool* called, + gin::Arguments* arguments) { + *called = true; + V8List actual = arguments->GetAll(); + ASSERT_EQ(expected->size(), actual.size()); + for (size_t i = 0; i < expected->size(); ++i) + EXPECT_EQ(expected->at(i), actual[i]) << i; + }; + + // Create an object that will compare GetHolderCreationContext() with + // |creation_context|. + v8::Local<v8::ObjectTemplate> object_template = + ObjectTemplateBuilder(isolate) + .SetMethod("check1", base::Bind(check_arguments, &list1, &called1)) + .SetMethod("check2", base::Bind(check_arguments, &list2, &called2)) + .SetMethod("check3", base::Bind(check_arguments, &list3, &called3)) + .Build(); + + v8::Local<v8::Object> object = + object_template->NewInstance(context).ToLocalChecked(); + + auto do_check = [object, context](V8List& args, base::StringPiece key) { + v8::Local<v8::Value> val; + ASSERT_TRUE( + object->Get(context, gin::StringToSymbol(context->GetIsolate(), key)) + .ToLocal(&val)); + ASSERT_TRUE(val->IsFunction()); + val.As<v8::Function>() + ->Call(context, object, static_cast<int>(args.size()), args.data()) + .ToLocalChecked(); + }; + + do_check(list1, "check1"); + EXPECT_TRUE(called1); + do_check(list2, "check2"); + EXPECT_TRUE(called2); + do_check(list3, "check3"); + EXPECT_TRUE(called3); +} + } // namespace gin
diff --git a/ios/BUILD.gn b/ios/BUILD.gn index 7ba2d563..bb776b6f 100644 --- a/ios/BUILD.gn +++ b/ios/BUILD.gn
@@ -40,9 +40,9 @@ deps = [ # List all the targets that need to be build on iOS by default. "//ios/chrome/app:chrome", + "//ios/chrome/search_widget_extension", "//ios/chrome/share_extension", "//ios/chrome/today_extension", - "//ios/chrome/widget_extension", "//ios/clean/chrome/app:chrome_clean_skeleton", "//ios/showcase", "//ios/web/shell:ios_web_shell",
diff --git a/ios/build/chrome_build.gni b/ios/build/chrome_build.gni index 30ff8fb..d4a6e6b 100644 --- a/ios/build/chrome_build.gni +++ b/ios/build/chrome_build.gni
@@ -9,7 +9,7 @@ declare_args() { # Enable today extension. ios_enable_today_extension = true - ios_enable_widget_extension = false + ios_enable_search_widget_extension = true # Enable share extension. ios_enable_share_extension = true @@ -29,8 +29,6 @@ # entitlements. ios_egtests_entitlements_additions = [] } -assert(!(ios_enable_today_extension && ios_enable_widget_extension), - "Both today extensions cannot be enabled simultaneously.") # Configure whether breakpad support is enabled. breakpad_enabled = is_official_build && is_chrome_branded
diff --git a/ios/chrome/app/BUILD.gn b/ios/chrome/app/BUILD.gn index 3704c77..4e36ae06 100644 --- a/ios/chrome/app/BUILD.gn +++ b/ios/chrome/app/BUILD.gn
@@ -274,8 +274,8 @@ if (ios_enable_today_extension) { deps += [ ":today_extension_bundle" ] } - if (ios_enable_widget_extension) { - deps += [ ":widget_extension_bundle" ] + if (ios_enable_search_widget_extension) { + deps += [ ":search_widget_extension_bundle" ] } if (ios_enable_share_extension) { deps += [ ":share_extension_bundle" ] @@ -314,22 +314,16 @@ } } - if (ios_enable_widget_extension) { - bundle_data("widget_extension_bundle") { + if (ios_enable_search_widget_extension) { + bundle_data("search_widget_extension_bundle") { public_deps = [ - "//ios/chrome/widget_extension", + "//ios/chrome/search_widget_extension", ] sources = [ - "$root_out_dir/widget_extension.appex", + "$root_out_dir/search_widget_extension.appex", ] - - # The output is renamed today_extension.appex so that signing in canary - # works and clobbering is not necessary when switching between this - # extension and the today extension. - # TODO(crbug.com/682230) : Rename this when widget gets its own - # mobileprovision. outputs = [ - "{{bundle_plugins_dir}}/today_extension.appex", + "{{bundle_plugins_dir}}/{{source_file_part}}", ] } }
diff --git a/ios/chrome/browser/crash_report/crash_restore_helper.mm b/ios/chrome/browser/crash_report/crash_restore_helper.mm index a2e23b5..12b96763 100644 --- a/ios/chrome/browser/crash_report/crash_restore_helper.mm +++ b/ios/chrome/browser/crash_report/crash_restore_helper.mm
@@ -20,6 +20,7 @@ #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #import "ios/chrome/browser/crash_report/breakpad_helper.h" #include "ios/chrome/browser/sessions/ios_chrome_tab_restore_service_factory.h" +#import "ios/chrome/browser/sessions/session_ios.h" #import "ios/chrome/browser/sessions/session_service_ios.h" #import "ios/chrome/browser/sessions/session_window_ios.h" #import "ios/chrome/browser/tabs/tab.h" @@ -259,13 +260,15 @@ DCHECK(!_sessionRestored); _sessionRestored = YES; _infoBarBridge.reset(); - SessionWindowIOS* sessionWindow = [[SessionServiceIOS sharedService] - loadSessionWindowFromPath:[self sessionBackupPath]]; - if (sessionWindow) { - breakpad_helper::WillStartCrashRestoration(); - return [_tabModel restoreSessionWindow:sessionWindow]; - } - return NO; + + SessionIOS* session = [[SessionServiceIOS sharedService] + loadSessionFromPath:[self sessionBackupPath]]; + if (!session) + return NO; + + DCHECK_EQ(session.sessionWindows.count, 1u); + breakpad_helper::WillStartCrashRestoration(); + return [_tabModel restoreSessionWindow:session.sessionWindows[0]]; } - (void)infoBarRemoved:(infobars::InfoBar*)infobar { @@ -281,12 +284,14 @@ // the recently closed tabs. _sessionRestored = YES; - SessionWindowIOS* window = [[SessionServiceIOS sharedService] - loadSessionWindowFromPath:[self sessionBackupPath]]; - DCHECK(window); - NSArray* sessions = window.sessions; + SessionIOS* session = [[SessionServiceIOS sharedService] + loadSessionFromPath:[self sessionBackupPath]]; + DCHECK_EQ(session.sessionWindows.count, 1u); + + NSArray<CRWSessionStorage*>* sessions = session.sessionWindows[0].sessions; if (!sessions.count) return; + sessions::TabRestoreService* const tabRestoreService = IOSChromeTabRestoreServiceFactory::GetForBrowserState(_browserState); tabRestoreService->LoadTabsFromLastSession();
diff --git a/ios/chrome/browser/passwords/password_controller_unittest.mm b/ios/chrome/browser/passwords/password_controller_unittest.mm index 9a6ddbd..db1e759 100644 --- a/ios/chrome/browser/passwords/password_controller_unittest.mm +++ b/ios/chrome/browser/passwords/password_controller_unittest.mm
@@ -728,69 +728,54 @@ "<form name=\"f6'\">" "<input id=\"un6'\" type='text' name=\"u6'\">" "<input id=\"pw6'\" type='password' name=\"p6'\">" - "</form>"; - -// A script that resets all text fields. -static NSString* kClearInputFieldsScript = - @"var inputs = document.getElementsByTagName('input');" - "for(var i = 0; i < inputs.length; i++){" - " inputs[i].value = '';" - "}"; - -// A script that we run after autofilling forms. It returns -// ids and values of all non-empty fields. -static NSString* kInputFieldValueVerificationScript = - @"var result='';" - "var inputs = document.getElementsByTagName('input');" - "for(var i = 0; i < inputs.length; i++){" - " var input = inputs[i];" - " if (input.value) {" - " result += input.id + '=' + input.value +';';" - " }" - "}; result"; - -// Test html content and expected result for __gCrWeb.hasPasswordField call. -struct TestDataForPasswordFormDetection { - NSString* page_content; - BOOL contains_password; -}; - -// Tests that the existence of (or the lack of) a password field in the page is -// detected correctly. -TEST_F(PasswordControllerTest, HasPasswordField) { - TestDataForPasswordFormDetection test_data[] = { - // Form without a password field. - {@"<form><input type='text' name='password'></form>", NO}, - // Form with a password field. - {@"<form><input type='password' name='password'></form>", YES}}; - for (size_t i = 0; i < arraysize(test_data); i++) { - TestDataForPasswordFormDetection& data = test_data[i]; - LoadHtml(data.page_content); - id result = ExecuteJavaScript(@"__gCrWeb.hasPasswordField()"); - EXPECT_NSEQ(@(data.contains_password), result) - << " in test " << i << ": " - << base::SysNSStringToUTF8(data.page_content); - } -} - -// Tests that the existence a password field in a nested iframe/ is detected -// correctly. -TEST_F(PasswordControllerTest, HasPasswordFieldinFrame) { - TestDataForPasswordFormDetection data = { - // Form with a password field in a nested iframe. - @"<iframe name='pf'></iframe>" + "</form>" + "<iframe name='pf'></iframe>" "<script>" " var doc = frames['pf'].document.open();" - " doc.write('<form><input type=\\'password\\'></form>');" + // Add a form inside iframe. It should also be matched and autofilled. + " doc.write('<form><input id=\\'un7\\' type=\\'text\\' name=\\'u4\\'>');" + " doc.write('<input id=\\'pw7\\' type=\\'password\\' name=\\'p4\\'>');" + " doc.write('</form>');" + // Add a non-password form inside iframe. It should not be matched. + " doc.write('<form><input id=\\'un8\\' type=\\'text\\' name=\\'u4\\'>');" + " doc.write('<input id=\\'pw8\\' type=\\'text\\' name=\\'p4\\'>');" + " doc.write('</form>');" " doc.close();" - "</script>", - YES - }; - LoadHtml(data.page_content); - id result = ExecuteJavaScript(@"__gCrWeb.hasPasswordField()"); - EXPECT_NSEQ(@(data.contains_password), result) - << base::SysNSStringToUTF8(data.page_content); -} + "</script>"; + +// A script that resets all text fields, including those in iframes. +static NSString* kClearInputFieldsScript = + @"function clearInputFields(win) {" + " var inputs = win.document.getElementsByTagName('input');" + " for (var i = 0; i < inputs.length; i++) {" + " inputs[i].value = '';" + " }" + " var frames = win.frames;" + " for (var i = 0; i < frames.length; i++) {" + " clearInputFields(frames[i]);" + " }" + "}" + "clearInputFields(window);"; + +// A script that runs after autofilling forms. It returns ids and values of all +// non-empty fields, including those in iframes. +static NSString* kInputFieldValueVerificationScript = + @"function findAllInputs(win) {" + " var result = '';" + " var inputs = win.document.getElementsByTagName('input');" + " for (var i = 0; i < inputs.length; i++) {" + " var input = inputs[i];" + " if (input.value) {" + " result += input.id + '=' + input.value + ';';" + " }" + " }" + " var frames = win.frames;" + " for (var i = 0; i < frames.length; i++) {" + " result += findAllInputs(frames[i]);" + " }" + " return result;" + "};" + "var result = findAllInputs(window); result"; struct FillPasswordFormTestData { const std::string origin; @@ -807,12 +792,6 @@ TEST_F(PasswordControllerTest, FillPasswordForm) { LoadHtml(kHtmlWithMultiplePasswordForms); - // TODO(crbug.com/614092): can we remove this assertion? This call is the only - // reason why hasPasswordField is a public API on gCrWeb. If the page does - // not contain a password field, shouldn't one of the expectations of the - // remaining tests also fail? - EXPECT_NSEQ(@YES, ExecuteJavaScript(@"__gCrWeb.hasPasswordField()")); - const std::string base_url = BaseUrl(); // clang-format off FillPasswordFormTestData test_data[] = { @@ -827,7 +806,8 @@ YES, @"un0=test_user;pw0=test_password;" }, - // Multiple forms match: they should all be autofilled. + // Multiple forms match (including one in iframe): they should all be + // autofilled. { base_url, base_url, @@ -837,6 +817,7 @@ "test_password", YES, @"un4=test_user;pw4=test_password;un5=test_user;pw5=test_password;" + "un7=test_user;pw7=test_password;" }, // The form matches despite a different action: the only difference // is a query and reference. @@ -990,7 +971,6 @@ BOOL PasswordControllerTest::BasicFormFill(NSString* html) { LoadHtml(html); - EXPECT_NSEQ(@YES, ExecuteJavaScript(@"__gCrWeb.hasPasswordField()")); const std::string base_url = BaseUrl(); PasswordFormFillData form_data; SetPasswordFormFillData(form_data, base_url, base_url, "u0", "test_user",
diff --git a/ios/chrome/browser/passwords/resources/password_controller.js b/ios/chrome/browser/passwords/resources/password_controller.js index c04af67c..506896d 100644 --- a/ios/chrome/browser/passwords/resources/password_controller.js +++ b/ios/chrome/browser/passwords/resources/password_controller.js
@@ -34,20 +34,6 @@ return __gCrWeb.stringify(formDataList); }; - /** - * Returns true if the top window or any frames inside contain an input field - * of type 'password'. This method is only used for unit tests and are only - * kept for legacy reasons. Prefer to use the private - * {@code hasPasswordField_} within this file. - * @return {boolean} Whether a password field exists. - * - * TODO(crbug.com/614092): investigate if this method can be completely - * removed from the gCrWeb public interface. - */ - __gCrWeb['hasPasswordField'] = function() { - return hasPasswordField_(window); - }; - /** Returns true if the supplied window or any frames inside contain an input * field of type 'password'. * @private
diff --git a/ios/chrome/browser/sessions/BUILD.gn b/ios/chrome/browser/sessions/BUILD.gn index fee17d05..c99eaecb 100644 --- a/ios/chrome/browser/sessions/BUILD.gn +++ b/ios/chrome/browser/sessions/BUILD.gn
@@ -11,6 +11,8 @@ "ios_chrome_tab_restore_service_client.mm", "ios_chrome_tab_restore_service_factory.cc", "ios_chrome_tab_restore_service_factory.h", + "session_ios.h", + "session_ios.mm", "session_service_ios.h", "session_service_ios.mm", "session_window_ios.h",
diff --git a/ios/chrome/browser/sessions/session_ios.h b/ios/chrome/browser/sessions/session_ios.h new file mode 100644 index 0000000..e7098a8 --- /dev/null +++ b/ios/chrome/browser/sessions/session_ios.h
@@ -0,0 +1,24 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_BROWSER_SESSIONS_SESSION_IOS_H_ +#define IOS_CHROME_BROWSER_SESSIONS_SESSION_IOS_H_ + +#import <Foundation/Foundation.h> + +@class SessionWindowIOS; + +// Encapsulates everything required to save a session. A session is a set of +// one or more session windows that share the same browser state. +@interface SessionIOS : NSObject<NSCoding> + +- (instancetype)initWithWindows:(NSArray<SessionWindowIOS*>*)sessionWindows + NS_DESIGNATED_INITIALIZER; + +// The serialized SessionWindowIOS objects. May be empty but never nil. +@property(nonatomic, readonly) NSArray<SessionWindowIOS*>* sessionWindows; + +@end + +#endif // IOS_CHROME_BROWSER_SESSIONS_SESSION_IOS_H_
diff --git a/ios/chrome/browser/sessions/session_ios.mm b/ios/chrome/browser/sessions/session_ios.mm new file mode 100644 index 0000000..3620c731 --- /dev/null +++ b/ios/chrome/browser/sessions/session_ios.mm
@@ -0,0 +1,52 @@ +// 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 "ios/chrome/browser/sessions/session_ios.h" + +#import "base/mac/foundation_util.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +namespace { +// Serialization keys +NSString* const kSessionWindowsKey = @"sessionWindows"; +} // namespace + +@implementation SessionIOS + +@synthesize sessionWindows = _sessionWindows; + +#pragma mark - Public interface. + +- (instancetype)initWithWindows:(NSArray<SessionWindowIOS*>*)sessionWindows { + DCHECK(sessionWindows); + if ((self = [super init])) { + _sessionWindows = sessionWindows; + } + return self; +} + +#pragma mark - NSObject + +- (instancetype)init { + return [self initWithWindows:@[]]; +} + +#pragma mark - NSCoding + +- (instancetype)initWithCoder:(NSCoder*)aDecoder { + NSArray<SessionWindowIOS*>* sessionWindows = + base::mac::ObjCCast<NSArray<SessionWindowIOS*>>( + [aDecoder decodeObjectForKey:kSessionWindowsKey]); + + return [self initWithWindows:(sessionWindows ? sessionWindows : @[])]; +} + +- (void)encodeWithCoder:(NSCoder*)aCoder { + [aCoder encodeObject:_sessionWindows forKey:kSessionWindowsKey]; +} + +@end
diff --git a/ios/chrome/browser/sessions/session_service_ios.h b/ios/chrome/browser/sessions/session_service_ios.h index ae3b99d6..c37bd8b 100644 --- a/ios/chrome/browser/sessions/session_service_ios.h +++ b/ios/chrome/browser/sessions/session_service_ios.h
@@ -9,7 +9,7 @@ #include "base/sequenced_task_runner.h" -@class SessionWindowIOS; +@class SessionIOS; // A singleton service for saving the current session. Can either save on a // delay or immediately. Saving is always performed on a separate thread. @@ -24,22 +24,22 @@ (const scoped_refptr<base::SequencedTaskRunner>&)taskRunner NS_DESIGNATED_INITIALIZER; -// Saves the session represented by |sessionWindow| to |directory| on disk. If -// |immediately| is NO, the save is done after a delay. If another call is -// pending, this one is ignored. If YES, the save is done now, cancelling any -// pending calls. Either way, the save is done on a separate thread to avoid -// blocking the UI thread. -- (void)saveSessionWindow:(SessionWindowIOS*)sessionWindow - directory:(NSString*)directory - immediately:(BOOL)immediately; +// Saves the session represented by |session| to |directory|. If |immediately| +// is NO, the save is done after a delay. If another call is pending, this one +// is ignored. If YES, the save is done now, cancelling any pending calls. +// Either way, the save is done on a separate thread to avoid blocking the UI +// thread. +- (void)saveSession:(SessionIOS*)sessionWindow + directory:(NSString*)directory + immediately:(BOOL)immediately; -// Loads the session window from default session file in |directory| on the -// main thread. Returns nil in case of errors. -- (SessionWindowIOS*)loadSessionWindowFromDirectory:(NSString*)directory; +// Loads the session from default session file in |directory| on the main +// thread. Returns nil in case of errors. +- (SessionIOS*)loadSessionFromDirectory:(NSString*)directory; -// Loads the session window from |sessionPath| on the main thread. Returns nil -// in case of errors. -- (SessionWindowIOS*)loadSessionWindowFromPath:(NSString*)sessionPath; +// Loads the session from |sessionPath| on the main thread. Returns nil in case +// of errors. +- (SessionIOS*)loadSessionFromPath:(NSString*)sessionPath; // Schedules deletion of the file containing the last session in |directory|. - (void)deleteLastSessionFileInDirectory:(NSString*)directory;
diff --git a/ios/chrome/browser/sessions/session_service_ios.mm b/ios/chrome/browser/sessions/session_service_ios.mm index 320d999..c2f1be5 100644 --- a/ios/chrome/browser/sessions/session_service_ios.mm +++ b/ios/chrome/browser/sessions/session_service_ios.mm
@@ -8,14 +8,17 @@ #include "base/critical_closure.h" #include "base/files/file_path.h" +#include "base/format_macros.h" #include "base/location.h" #include "base/logging.h" #import "base/mac/bind_objc_block.h" +#import "base/mac/foundation_util.h" #include "base/memory/ref_counted.h" #include "base/sequenced_task_runner.h" #include "base/strings/sys_string_conversions.h" #include "base/threading/sequenced_worker_pool.h" #include "base/threading/thread_restrictions.h" +#import "ios/chrome/browser/sessions/session_ios.h" #import "ios/chrome/browser/sessions/session_window_ios.h" #import "ios/web/public/crw_navigation_item_storage.h" #import "ios/web/public/crw_session_certificate_policy_cache_storage.h" @@ -72,9 +75,8 @@ // The SequencedTaskRunner on which File IO operations are performed. scoped_refptr<base::SequencedTaskRunner> _taskRunner; - // Maps session path to the pending session window for the delayed save - // behaviour. - NSMutableDictionary<NSString*, SessionWindowIOS*>* _pendingSessionWindows; + // Maps session path to the pending session for the delayed save behaviour. + NSMutableDictionary<NSString*, SessionIOS*>* _pendingSessions; } #pragma mark - NSObject overrides @@ -101,19 +103,18 @@ DCHECK(taskRunner); self = [super init]; if (self) { - _pendingSessionWindows = [NSMutableDictionary dictionary]; + _pendingSessions = [NSMutableDictionary dictionary]; _taskRunner = taskRunner; } return self; } -- (void)saveSessionWindow:(SessionWindowIOS*)sessionWindow - directory:(NSString*)directory - immediately:(BOOL)immediately { +- (void)saveSession:(SessionIOS*)session + directory:(NSString*)directory + immediately:(BOOL)immediately { NSString* sessionPath = [[self class] sessionPathForDirectory:directory]; - BOOL hadPendingSession = - [_pendingSessionWindows objectForKey:sessionPath] != nil; - [_pendingSessionWindows setObject:sessionWindow forKey:sessionPath]; + BOOL hadPendingSession = [_pendingSessions objectForKey:sessionPath] != nil; + [_pendingSessions setObject:session forKey:sessionPath]; if (immediately) { [NSObject cancelPreviousPerformRequestsWithTarget:self]; [self performSaveToPathInBackground:sessionPath]; @@ -126,12 +127,13 @@ } } -- (SessionWindowIOS*)loadSessionWindowFromDirectory:(NSString*)directory { +- (SessionIOS*)loadSessionFromDirectory:(NSString*)directory { NSString* sessionPath = [[self class] sessionPathForDirectory:directory]; - return [self loadSessionWindowFromPath:sessionPath]; + return [self loadSessionFromPath:sessionPath]; } -- (SessionWindowIOS*)loadSessionWindowFromPath:(NSString*)sessionPath { +- (SessionIOS*)loadSessionFromPath:(NSString*)sessionPath { + NSObject<NSCoding>* rootObject = nil; @try { NSData* data = [NSData dataWithContentsOfFile:sessionPath]; if (!data) @@ -142,13 +144,25 @@ // Register compatibility aliases to support legacy saved sessions. [unarchiver cr_registerCompatibilityAliases]; - return [unarchiver decodeObjectForKey:kRootObjectKey]; + rootObject = [unarchiver decodeObjectForKey:kRootObjectKey]; } @catch (NSException* exception) { NOTREACHED() << "Error loading session file: " << base::SysNSStringToUTF8(sessionPath) << ": " << base::SysNSStringToUTF8([exception reason]); - return nil; } + + if (!rootObject) + return nil; + + // Support for legacy saved session that contained a single SessionWindowIOS + // object as the root object (pre-M-59). + if ([rootObject isKindOfClass:[SessionWindowIOS class]]) { + return [[SessionIOS alloc] initWithWindows:@[ + base::mac::ObjCCastStrict<SessionWindowIOS>(rootObject) + ]]; + } + + return base::mac::ObjCCastStrict<SessionIOS>(rootObject); } - (void)deleteLastSessionFileInDirectory:(NSString*)directory { @@ -177,17 +191,15 @@ // Do the work of saving on a background thread. - (void)performSaveToPathInBackground:(NSString*)sessionPath { DCHECK(sessionPath); - DCHECK([_pendingSessionWindows objectForKey:sessionPath] != nil); + DCHECK([_pendingSessions objectForKey:sessionPath] != nil); // Serialize to NSData on the main thread to avoid accessing potentially // non-threadsafe objects on a background thread. - SessionWindowIOS* sessionWindow = - [_pendingSessionWindows objectForKey:sessionPath]; - [_pendingSessionWindows removeObjectForKey:sessionPath]; + SessionIOS* session = [_pendingSessions objectForKey:sessionPath]; + [_pendingSessions removeObjectForKey:sessionPath]; @try { - NSData* sessionData = - [NSKeyedArchiver archivedDataWithRootObject:sessionWindow]; + NSData* sessionData = [NSKeyedArchiver archivedDataWithRootObject:session]; _taskRunner->PostTask( FROM_HERE, base::MakeCriticalClosure(base::BindBlockArc(^{ [self performSaveSessionData:sessionData sessionPath:sessionPath];
diff --git a/ios/chrome/browser/sessions/session_service_ios_unittest.mm b/ios/chrome/browser/sessions/session_service_ios_unittest.mm index 9ce7914..91e2132 100644 --- a/ios/chrome/browser/sessions/session_service_ios_unittest.mm +++ b/ios/chrome/browser/sessions/session_service_ios_unittest.mm
@@ -15,6 +15,7 @@ #include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "ios/chrome/browser/chrome_paths.h" +#import "ios/chrome/browser/sessions/session_ios.h" #import "ios/chrome/browser/sessions/session_service_ios.h" #import "ios/chrome/browser/sessions/session_window_ios.h" #import "ios/web/public/crw_session_storage.h" @@ -68,15 +69,21 @@ return base::SysUTF8ToNSString(session_path.AsUTF8Unsafe()); } - // Create a SessionWindowIOS with |tab_count| tabs. - SessionWindowIOS* CreateSessionWindow(NSUInteger tab_count) { - NSMutableArray<CRWSessionStorage*>* tabs = [NSMutableArray array]; - while (tabs.count < tab_count) { - [tabs addObject:[[CRWSessionStorage alloc] init]]; + // Create a SessionIOS corresponding to |window_count| windows each with + // |tab_count| tabs. + SessionIOS* CreateSession(NSUInteger window_count, NSUInteger tab_count) { + NSMutableArray<SessionWindowIOS*>* windows = [NSMutableArray array]; + while (windows.count < window_count) { + NSMutableArray<CRWSessionStorage*>* tabs = [NSMutableArray array]; + while (tabs.count < tab_count) { + [tabs addObject:[[CRWSessionStorage alloc] init]]; + } + [windows addObject:[[SessionWindowIOS alloc] + initWithSessions:[tabs copy] + selectedIndex:(tabs.count ? tabs.count - 1 + : NSNotFound)]]; } - return [[SessionWindowIOS alloc] - initWithSessions:[tabs copy] - selectedIndex:(tabs.count ? tabs.count - 1 : NSNotFound)]; + return [[SessionIOS alloc] initWithWindows:[windows copy]]; } SessionServiceIOS* session_service() { return session_service_; } @@ -97,12 +104,12 @@ [SessionServiceIOS sessionPathForDirectory:@""]); } -TEST_F(SessionServiceTest, SaveSessionWindowToDirectory) { - [session_service() saveSessionWindow:CreateSessionWindow(0u) - directory:directory() - immediately:YES]; +TEST_F(SessionServiceTest, SaveSessionWindowToPath) { + [session_service() saveSession:CreateSession(0u, 0u) + directory:directory() + immediately:YES]; - // Even if immediately is YES, the file is created by a task on the task + // Even if |immediately| is YES, the file is created by a task on the task // runner passed to SessionServiceIOS initializer (which is the current // thread task runner during test). Wait for the task to complete. base::RunLoop().RunUntilIdle(); @@ -111,17 +118,17 @@ EXPECT_TRUE([file_manager removeItemAtPath:directory() error:nullptr]); } -TEST_F(SessionServiceTest, SaveSessionWindowToExistingDirectory) { +TEST_F(SessionServiceTest, SaveSessionWindowToPathDirectoryExists) { ASSERT_TRUE([[NSFileManager defaultManager] createDirectoryAtPath:directory() withIntermediateDirectories:YES attributes:nil error:nullptr]); - [session_service() saveSessionWindow:CreateSessionWindow(0u) - directory:directory() - immediately:YES]; + [session_service() saveSession:CreateSession(0u, 0u) + directory:directory() + immediately:YES]; - // Even if immediately is YES, the file is created by a task on the task + // Even if |immediately| is YES, the file is created by a task on the task // runner passed to SessionServiceIOS initializer (which is the current // thread task runner during test). Wait for the task to complete. base::RunLoop().RunUntilIdle(); @@ -130,34 +137,37 @@ EXPECT_TRUE([file_manager removeItemAtPath:directory() error:nullptr]); } -TEST_F(SessionServiceTest, LoadSessionWindowFromDirectoryNoFile) { - SessionWindowIOS* session_window = - [session_service() loadSessionWindowFromDirectory:directory()]; - EXPECT_TRUE(session_window == nil); +TEST_F(SessionServiceTest, LoadSessionFromDirectoryNoFile) { + SessionIOS* session = + [session_service() loadSessionFromDirectory:directory()]; + EXPECT_TRUE(session == nil); } -TEST_F(SessionServiceTest, LoadSessionWindowFromDirectory) { - [session_service() saveSessionWindow:CreateSessionWindow(1u) - directory:directory() - immediately:YES]; +TEST_F(SessionServiceTest, LoadSessionFromDirectory) { + [session_service() saveSession:CreateSession(2u, 1u) + directory:directory() + immediately:YES]; - // Even if immediately is YES, the file is created by a task on the task + // Even if |immediately| is YES, the file is created by a task on the task // runner passed to SessionServiceIOS initializer (which is the current // thread task runner during test). Wait for the task to complete. base::RunLoop().RunUntilIdle(); - SessionWindowIOS* session_window = - [session_service() loadSessionWindowFromDirectory:directory()]; - EXPECT_EQ(1u, session_window.sessions.count); - EXPECT_EQ(0u, session_window.selectedIndex); + SessionIOS* session = + [session_service() loadSessionFromDirectory:directory()]; + EXPECT_EQ(2u, session.sessionWindows.count); + for (SessionWindowIOS* sessionWindow in session.sessionWindows) { + EXPECT_EQ(1u, sessionWindow.sessions.count); + EXPECT_EQ(0u, sessionWindow.selectedIndex); + } } -TEST_F(SessionServiceTest, LoadSessionWindowFromPath) { - [session_service() saveSessionWindow:CreateSessionWindow(1u) - directory:directory() - immediately:YES]; +TEST_F(SessionServiceTest, LoadSessionFromPath) { + [session_service() saveSession:CreateSession(2u, 1u) + directory:directory() + immediately:YES]; - // Even if immediately is YES, the file is created by a task on the task + // Even if |immediately| is YES, the file is created by a task on the task // runner passed to SessionServiceIOS initializer (which is the current // thread task runner during test). Wait for the task to complete. base::RunLoop().RunUntilIdle(); @@ -172,19 +182,20 @@ toPath:renamed_path error:nil]); - SessionWindowIOS* session_window = - [session_service() loadSessionWindowFromPath:renamed_path]; - EXPECT_EQ(1u, session_window.sessions.count); - EXPECT_EQ(0u, session_window.selectedIndex); + SessionIOS* session = [session_service() loadSessionFromPath:renamed_path]; + EXPECT_EQ(2u, session.sessionWindows.count); + for (SessionWindowIOS* sessionWindow in session.sessionWindows) { + EXPECT_EQ(1u, sessionWindow.sessions.count); + EXPECT_EQ(0u, sessionWindow.selectedIndex); + } } -TEST_F(SessionServiceTest, LoadCorruptedSessionWindow) { +TEST_F(SessionServiceTest, LoadCorruptedSession) { NSString* session_path = SessionPathForTestData(FILE_PATH_LITERAL("corrupted.plist")); ASSERT_NSNE(nil, session_path); - SessionWindowIOS* session_window = - [session_service() loadSessionWindowFromPath:session_path]; - EXPECT_TRUE(session_window == nil); + SessionIOS* session = [session_service() loadSessionFromPath:session_path]; + EXPECT_TRUE(session == nil); } // TODO(crbug.com/661633): remove this once M67 has shipped (i.e. once more @@ -193,9 +204,8 @@ NSString* session_path = SessionPathForTestData(FILE_PATH_LITERAL("session_m57.plist")); ASSERT_NSNE(nil, session_path); - SessionWindowIOS* session_window = - [session_service() loadSessionWindowFromPath:session_path]; - EXPECT_TRUE(session_window != nil); + SessionIOS* session = [session_service() loadSessionFromPath:session_path]; + EXPECT_EQ(1u, session.sessionWindows.count); } // TODO(crbug.com/661633): remove this once M68 has shipped (i.e. once more @@ -204,9 +214,8 @@ NSString* session_path = SessionPathForTestData(FILE_PATH_LITERAL("session_m58.plist")); ASSERT_NSNE(nil, session_path); - SessionWindowIOS* session_window = - [session_service() loadSessionWindowFromPath:session_path]; - EXPECT_TRUE(session_window != nil); + SessionIOS* session = [session_service() loadSessionFromPath:session_path]; + EXPECT_EQ(1u, session.sessionWindows.count); } } // anonymous namespace
diff --git a/ios/chrome/browser/sessions/session_window_ios.h b/ios/chrome/browser/sessions/session_window_ios.h index 1b67058..d1fbe507 100644 --- a/ios/chrome/browser/sessions/session_window_ios.h +++ b/ios/chrome/browser/sessions/session_window_ios.h
@@ -9,8 +9,7 @@ @class CRWSessionStorage; -// Encapsulates everything required to save a session "window". For iOS, there -// will only be one window at a time. +// Encapsulates everything required to save a session "window". @interface SessionWindowIOS : NSObject<NSCoding> // Initializes SessionsWindowIOS using the parameters are initial values for @@ -20,7 +19,7 @@ selectedIndex:(NSUInteger)selectedIndex NS_DESIGNATED_INITIALIZER; -// The serialized session objects. +// The serialized session objects. May be empty but never nil. @property(nonatomic, readonly) NSArray<CRWSessionStorage*>* sessions; // The currently selected session. NSNotFound if the sessionWindow contains
diff --git a/ios/chrome/browser/sessions/test_session_service.mm b/ios/chrome/browser/sessions/test_session_service.mm index cd25667..34f61ed 100644 --- a/ios/chrome/browser/sessions/test_session_service.mm +++ b/ios/chrome/browser/sessions/test_session_service.mm
@@ -19,11 +19,11 @@ return [super initWithTaskRunner:base::ThreadTaskRunnerHandle::Get()]; } -- (void)saveSessionWindow:(SessionWindowIOS*)sessionWindow - directory:(NSString*)directory - immediately:(BOOL)immediately { +- (void)saveSession:(SessionIOS*)session + directory:(NSString*)directory + immediately:(BOOL)immediately { NSString* sessionPath = [[self class] sessionPathForDirectory:directory]; - NSData* data = [NSKeyedArchiver archivedDataWithRootObject:sessionWindow]; + NSData* data = [NSKeyedArchiver archivedDataWithRootObject:session]; if (self.performIO) [self performSaveSessionData:data sessionPath:sessionPath]; }
diff --git a/ios/chrome/browser/ssl/ios_ssl_error_handler.mm b/ios/chrome/browser/ssl/ios_ssl_error_handler.mm index 4b28441..a6bc31d 100644 --- a/ios/chrome/browser/ssl/ios_ssl_error_handler.mm +++ b/ios/chrome/browser/ssl/ios_ssl_error_handler.mm
@@ -15,6 +15,7 @@ #include "ios/web/public/browser_state.h" #import "ios/web/public/web_state/web_state.h" #include "net/ssl/ssl_info.h" +#include "net/traffic_annotation/network_traffic_annotation.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -83,7 +84,8 @@ UMA_HISTOGRAM_ENUMERATION(kSessionDetectionResultHistogram, static_cast<int>(status), static_cast<int>(CaptivePortalStatus::COUNT)); - })); + }), + NO_TRAFFIC_ANNOTATION_YET); } // static
diff --git a/ios/chrome/browser/tabs/tab_model.mm b/ios/chrome/browser/tabs/tab_model.mm index f88d2ea..050cdcf 100644 --- a/ios/chrome/browser/tabs/tab_model.mm +++ b/ios/chrome/browser/tabs/tab_model.mm
@@ -26,6 +26,7 @@ #import "ios/chrome/browser/metrics/tab_usage_recorder.h" #import "ios/chrome/browser/metrics/tab_usage_recorder_web_state_list_observer.h" #include "ios/chrome/browser/sessions/ios_chrome_tab_restore_service_factory.h" +#import "ios/chrome/browser/sessions/session_ios.h" #import "ios/chrome/browser/sessions/session_service_ios.h" #import "ios/chrome/browser/sessions/session_window_ios.h" #import "ios/chrome/browser/snapshots/snapshot_cache.h" @@ -169,7 +170,7 @@ } // Session window for the contents of the tab model. -@property(nonatomic, readonly) SessionWindowIOS* windowForSavingSession; +@property(nonatomic, readonly) SessionIOS* sessionForSaving; // Helper method that posts a notification with the given name with |tab| // in the userInfo dictionary under the kTabModelTabKey. @@ -392,9 +393,9 @@ return; NSString* statePath = base::SysUTF8ToNSString(_browserState->GetStatePath().AsUTF8Unsafe()); - [_sessionService saveSessionWindow:self.windowForSavingSession - directory:statePath - immediately:immediately]; + [_sessionService saveSession:self.sessionForSaving + directory:statePath + immediately:immediately]; } - (Tab*)tabAtIndex:(NSUInteger)index { @@ -690,7 +691,7 @@ #pragma mark - Private methods -- (SessionWindowIOS*)windowForSavingSession { +- (SessionIOS*)sessionForSaving { // Background tabs will already have their state preserved, but not the // fg tab. Do it now. [self.currentTab recordStateInHistory]; @@ -699,9 +700,10 @@ // be done on a separate thread. // TODO(crbug.com/661986): This could get expensive especially since this // window may never be saved (if another call comes in before the delay). - return [[[SessionWindowIOS alloc] + SessionWindowIOS* sessionWindow = [[[SessionWindowIOS alloc] initWithSessions:SerializeWebStateList(_webStateList.get()) selectedIndex:[self indexOfTab:self.currentTab]] autorelease]; + return [[SessionIOS alloc] initWithWindows:@[ sessionWindow ]]; } - (void)postNotificationName:(NSString*)notificationName withTab:(Tab*)tab {
diff --git a/ios/chrome/browser/tabs/tab_model_unittest.mm b/ios/chrome/browser/tabs/tab_model_unittest.mm index a2ca74e..5ce94521 100644 --- a/ios/chrome/browser/tabs/tab_model_unittest.mm +++ b/ios/chrome/browser/tabs/tab_model_unittest.mm
@@ -14,6 +14,7 @@ #include "ios/chrome/browser/chrome_url_constants.h" #include "ios/chrome/browser/infobars/infobar_manager_impl.h" #include "ios/chrome/browser/sessions/ios_chrome_session_tab_helper.h" +#import "ios/chrome/browser/sessions/session_ios.h" #import "ios/chrome/browser/sessions/session_window_ios.h" #import "ios/chrome/browser/sessions/test_session_service.h" #import "ios/chrome/browser/tabs/legacy_tab_helper.h" @@ -1150,8 +1151,10 @@ NSString* state_path = base::SysUTF8ToNSString( chrome_browser_state_->GetStatePath().AsUTF8Unsafe()); - SessionWindowIOS* session_window = - [test_session_service loadSessionWindowFromDirectory:state_path]; + SessionIOS* session = + [test_session_service loadSessionFromDirectory:state_path]; + ASSERT_EQ(1u, session.sessionWindows.count); + SessionWindowIOS* session_window = session.sessionWindows[0]; // Create tab model from saved session. SetTabModel(CreateTabModel(test_session_service.get(), session_window));
diff --git a/ios/chrome/browser/test/perf_test_with_bvc_ios.mm b/ios/chrome/browser/test/perf_test_with_bvc_ios.mm index 146c521a..d8a056c 100644 --- a/ios/chrome/browser/test/perf_test_with_bvc_ios.mm +++ b/ios/chrome/browser/test/perf_test_with_bvc_ios.mm
@@ -14,6 +14,7 @@ #include "ios/chrome/browser/bookmarks/bookmark_model_factory.h" #include "ios/chrome/browser/browser_state/test_chrome_browser_state_manager.h" #include "ios/chrome/browser/search_engines/template_url_service_factory.h" +#import "ios/chrome/browser/sessions/session_ios.h" #import "ios/chrome/browser/sessions/session_service_ios.h" #import "ios/chrome/browser/sessions/session_window_ios.h" #import "ios/chrome/browser/tabs/tab_model.h" @@ -118,17 +119,18 @@ // Use the session to create a window which will contain the tab models. NSString* state_path = base::SysUTF8ToNSString( chrome_browser_state_->GetStatePath().AsUTF8Unsafe()); - SessionWindowIOS* session_window = [[SessionServiceIOS sharedService] - loadSessionWindowFromDirectory:state_path]; + SessionIOS* session = + [[SessionServiceIOS sharedService] loadSessionFromDirectory:state_path]; + DCHECK_EQ(session.sessionWindows.count, 1u); // Tab models. The off-the-record (OTR) tab model is required for the stack // view controller, which is created in OpenStackView(). tab_model_.reset([[TabModel alloc] - initWithSessionWindow:session_window + initWithSessionWindow:session.sessionWindows[0] sessionService:[SessionServiceIOS sharedService] browserState:chrome_browser_state_.get()]); otr_tab_model_.reset([[TabModel alloc] - initWithSessionWindow:session_window + initWithSessionWindow:session.sessionWindows[0] sessionService:[SessionServiceIOS sharedService] browserState:chrome_browser_state_ ->GetOffTheRecordChromeBrowserState()]);
diff --git a/ios/chrome/browser/ui/main/browser_view_wrangler.mm b/ios/chrome/browser/ui/main/browser_view_wrangler.mm index 537fa72..ef7f08f 100644 --- a/ios/chrome/browser/ui/main/browser_view_wrangler.mm +++ b/ios/chrome/browser/ui/main/browser_view_wrangler.mm
@@ -14,6 +14,7 @@ #include "ios/chrome/browser/crash_report/crash_report_helper.h" #import "ios/chrome/browser/device_sharing/device_sharing_manager.h" #import "ios/chrome/browser/physical_web/start_physical_web_discovery.h" +#import "ios/chrome/browser/sessions/session_ios.h" #import "ios/chrome/browser/sessions/session_service_ios.h" #import "ios/chrome/browser/sessions/session_window_ios.h" #import "ios/chrome/browser/tabs/tab.h" @@ -300,8 +301,12 @@ // Load existing saved tab model state. NSString* statePath = base::SysUTF8ToNSString(browserState->GetStatePath().AsUTF8Unsafe()); - sessionWindow = [[SessionServiceIOS sharedService] - loadSessionWindowFromDirectory:statePath]; + SessionIOS* session = + [[SessionServiceIOS sharedService] loadSessionFromDirectory:statePath]; + if (session) { + DCHECK_EQ(session.sessionWindows.count, 1u); + sessionWindow = session.sessionWindows[0]; + } } // Create tab model from saved session (nil is ok).
diff --git a/ios/chrome/browser/ui/side_swipe/BUILD.gn b/ios/chrome/browser/ui/side_swipe/BUILD.gn index ce315af..eb8e097 100644 --- a/ios/chrome/browser/ui/side_swipe/BUILD.gn +++ b/ios/chrome/browser/ui/side_swipe/BUILD.gn
@@ -17,6 +17,7 @@ } source_set("side_swipe") { + configs += [ "//build/config/compiler:enable_arc" ] sources = [ "card_side_swipe_view.h", "card_side_swipe_view.mm",
diff --git a/ios/chrome/browser/ui/side_swipe/card_side_swipe_view.h b/ios/chrome/browser/ui/side_swipe/card_side_swipe_view.h index 6b068749..8b9714bf 100644 --- a/ios/chrome/browser/ui/side_swipe/card_side_swipe_view.h +++ b/ios/chrome/browser/ui/side_swipe/card_side_swipe_view.h
@@ -42,7 +42,7 @@ base::scoped_nsobject<UIImageView> backgroundView_; } -@property(nonatomic, assign) id<SideSwipeControllerDelegate> delegate; +@property(nonatomic, weak) id<SideSwipeControllerDelegate> delegate; @property(nonatomic, assign) CGFloat topMargin; - (id)initWithFrame:(CGRect)frame
diff --git a/ios/chrome/browser/ui/side_swipe/card_side_swipe_view.mm b/ios/chrome/browser/ui/side_swipe/card_side_swipe_view.mm index ddfdaf9..8bff8e2 100644 --- a/ios/chrome/browser/ui/side_swipe/card_side_swipe_view.mm +++ b/ios/chrome/browser/ui/side_swipe/card_side_swipe_view.mm
@@ -25,6 +25,10 @@ #import "ios/web/web_state/ui/crw_web_controller.h" #include "url/gurl.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + using base::UserMetricsAction; namespace { @@ -144,8 +148,7 @@ currentPoint_ = CGPointZero; topMargin_ = topMargin; - base::scoped_nsobject<UIView> background( - [[UIView alloc] initWithFrame:CGRectZero]); + UIView* background = [[UIView alloc] initWithFrame:CGRectZero]; [self addSubview:background]; [background setTranslatesAutoresizingMaskIntoConstraints:NO];
diff --git a/ios/chrome/browser/ui/side_swipe/history_side_swipe_provider.mm b/ios/chrome/browser/ui/side_swipe/history_side_swipe_provider.mm index d23979a6..a86e19f 100644 --- a/ios/chrome/browser/ui/side_swipe/history_side_swipe_provider.mm +++ b/ios/chrome/browser/ui/side_swipe/history_side_swipe_provider.mm
@@ -4,9 +4,15 @@ #import "ios/chrome/browser/ui/side_swipe/history_side_swipe_provider.h" +#include "ios/chrome/browser/tabs/tab.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + @interface HistorySideSwipeProvider () { // Keep a reference to detach before deallocing. - TabModel* _tabModel; // weak + __weak TabModel* _tabModel; // weak } @end
diff --git a/ios/chrome/browser/ui/side_swipe/side_swipe_controller.h b/ios/chrome/browser/ui/side_swipe/side_swipe_controller.h index 81f4fdf4..0a13aae 100644 --- a/ios/chrome/browser/ui/side_swipe/side_swipe_controller.h +++ b/ios/chrome/browser/ui/side_swipe/side_swipe_controller.h
@@ -78,8 +78,8 @@ : NSObject<CRWSwipeRecognizerProvider, UIGestureRecognizerDelegate> @property(nonatomic, assign) BOOL inSwipe; -@property(nonatomic, assign) id<SideSwipeControllerDelegate> swipeDelegate; -@property(nonatomic, assign) id<TabSnapshottingDelegate> snapshotDelegate; +@property(nonatomic, weak) id<SideSwipeControllerDelegate> swipeDelegate; +@property(nonatomic, weak) id<TabSnapshottingDelegate> snapshotDelegate; // Initializer. - (id)initWithTabModel:(TabModel*)model
diff --git a/ios/chrome/browser/ui/side_swipe/side_swipe_controller.mm b/ios/chrome/browser/ui/side_swipe/side_swipe_controller.mm index b95f771..fd0ad6f 100644 --- a/ios/chrome/browser/ui/side_swipe/side_swipe_controller.mm +++ b/ios/chrome/browser/ui/side_swipe/side_swipe_controller.mm
@@ -6,7 +6,6 @@ #include <memory> -#import "base/ios/weak_nsobject.h" #include "components/reading_list/core/reading_list_model.h" #import "ios/chrome/browser/browser_state/chrome_browser_state.h" #import "ios/chrome/browser/infobars/infobar_container_view.h" @@ -24,6 +23,10 @@ #import "ios/web/public/web_state/web_state_observer_bridge.h" #import "ios/web/web_state/ui/crw_web_controller.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace ios_internal { NSString* const kSideSwipeWillStartNotification = @"kSideSwipeWillStartNotification"; @@ -50,21 +53,21 @@ UIGestureRecognizerDelegate> { @private - base::WeakNSObject<TabModel> model_; + __weak TabModel* model_; // Side swipe view for tab navigation. - base::scoped_nsobject<CardSideSwipeView> tabSideSwipeView_; + CardSideSwipeView* tabSideSwipeView_; // Side swipe view for page navigation. - base::scoped_nsobject<SideSwipeNavigationView> pageSideSwipeView_; + SideSwipeNavigationView* pageSideSwipeView_; // YES if the user is currently swiping. BOOL inSwipe_; // Swipe gesture recognizer. - base::scoped_nsobject<SideSwipeGestureRecognizer> swipeGestureRecognizer_; + SideSwipeGestureRecognizer* swipeGestureRecognizer_; - base::scoped_nsobject<SideSwipeGestureRecognizer> panGestureRecognizer_; + SideSwipeGestureRecognizer* panGestureRecognizer_; // Used in iPad side swipe gesture, tracks the starting tab index. NSUInteger startingTabIndex_; @@ -76,16 +79,15 @@ std::unique_ptr<web::WebStateObserverBridge> webStateObserverBridge_; // Curtain over web view while waiting for it to load. - base::scoped_nsobject<UIView> curtain_; + UIView* curtain_; // Provides forward/back action for history entries. - base::scoped_nsobject<HistorySideSwipeProvider> historySideSwipeProvider_; + HistorySideSwipeProvider* historySideSwipeProvider_; // Provides forward action for reading list. - base::scoped_nsobject<ReadingListSideSwipeProvider> - readingListSideSwipeProvider_; + ReadingListSideSwipeProvider* readingListSideSwipeProvider_; - base::WeakNSProtocol<id<SideSwipeContentProvider>> currentContentProvider_; + __weak id<SideSwipeContentProvider> currentContentProvider_; } // Load grey snapshots for the next |kIpadGreySwipeTabCount| tabs in @@ -117,27 +119,26 @@ DCHECK(model); self = [super init]; if (self) { - model_.reset(model); + model_ = model; [model_ addObserver:self]; - historySideSwipeProvider_.reset( - [[HistorySideSwipeProvider alloc] initWithTabModel:model_]); + historySideSwipeProvider_ = + [[HistorySideSwipeProvider alloc] initWithTabModel:model_]; - readingListSideSwipeProvider_.reset([[ReadingListSideSwipeProvider alloc] + readingListSideSwipeProvider_ = [[ReadingListSideSwipeProvider alloc] initWithReadingList:ReadingListModelFactory::GetForBrowserState( - browserState)]); + browserState)]; } return self; } - (void)dealloc { [model_ removeObserver:self]; - [super dealloc]; } - (void)addHorizontalGesturesToView:(UIView*)view { - swipeGestureRecognizer_.reset([[SideSwipeGestureRecognizer alloc] + swipeGestureRecognizer_ = [[SideSwipeGestureRecognizer alloc] initWithTarget:self - action:@selector(handleSwipe:)]); + action:@selector(handleSwipe:)]; [swipeGestureRecognizer_ setMaximumNumberOfTouches:1]; [swipeGestureRecognizer_ setDelegate:self]; [swipeGestureRecognizer_ setSwipeEdge:kSwipeEdge]; @@ -145,9 +146,9 @@ // Add a second gesture recognizer to handle swiping on the toolbar to change // tabs. - panGestureRecognizer_.reset([[SideSwipeGestureRecognizer alloc] - initWithTarget:self - action:@selector(handlePan:)]); + panGestureRecognizer_ = + [[SideSwipeGestureRecognizer alloc] initWithTarget:self + action:@selector(handlePan:)]; [panGestureRecognizer_ setMaximumNumberOfTouches:1]; [panGestureRecognizer_ setSwipeThreshold:48]; [panGestureRecognizer_ setDelegate:self]; @@ -155,7 +156,7 @@ } - (NSSet*)swipeRecognizers { - return [NSSet setWithObjects:swipeGestureRecognizer_.get(), nil]; + return [NSSet setWithObjects:swipeGestureRecognizer_, nil]; } - (void)setEnabled:(BOOL)enabled { @@ -252,14 +253,14 @@ index = index + dx; } [[SnapshotCache sharedInstance] createGreyCache:sessionIDs]; - for (Tab* tab in model_.get()) { + for (Tab* tab in model_) { tab.useGreyImageCache = YES; } } - (void)deleteGreyCache { [[SnapshotCache sharedInstance] removeGreyCache]; - for (Tab* tab in model_.get()) { + for (Tab* tab in model_) { tab.useGreyImageCache = NO; } } @@ -385,7 +386,7 @@ [swipeDelegate_ updateAccessoryViewsForSideSwipeWithVisibility:NO]; BOOL goBack = IsSwipingBack(gesture.direction); - currentContentProvider_.reset([self contentProviderForGesture:goBack]); + currentContentProvider_ = [self contentProviderForGesture:goBack]; BOOL canNavigate = currentContentProvider_ != nil; CGRect gestureBounds = gesture.view.bounds; @@ -396,19 +397,19 @@ CGRectGetWidth(gestureBounds), CGRectGetHeight(gestureBounds) - headerHeight); - pageSideSwipeView_.reset([[SideSwipeNavigationView alloc] + pageSideSwipeView_ = [[SideSwipeNavigationView alloc] initWithFrame:navigationFrame withDirection:gesture.direction canNavigate:canNavigate image:[currentContentProvider_ paneIcon] - rotateForward:[currentContentProvider_ rotateForwardIcon]]); + rotateForward:[currentContentProvider_ rotateForwardIcon]]; [pageSideSwipeView_ setTargetView:[swipeDelegate_ contentView]]; [gesture.view insertSubview:pageSideSwipeView_ belowSubview:[[swipeDelegate_ toolbarController] view]]; } - base::WeakNSObject<Tab> weakCurrentTab([model_ currentTab]); + __weak Tab* weakCurrentTab = [model_ currentTab]; [pageSideSwipeView_ handleHorizontalPan:gesture onOverThresholdCompletion:^{ BOOL wantsBack = IsSwipingBack(gesture.direction); @@ -454,10 +455,9 @@ [tabSideSwipeView_ setFrame:frame]; [tabSideSwipeView_ setTopMargin:headerHeight]; } else { - tabSideSwipeView_.reset([[CardSideSwipeView alloc] - initWithFrame:frame - topMargin:headerHeight - model:model_]); + tabSideSwipeView_ = [[CardSideSwipeView alloc] initWithFrame:frame + topMargin:headerHeight + model:model_]; [tabSideSwipeView_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight]; [tabSideSwipeView_ setDelegate:swipeDelegate_]; @@ -490,8 +490,8 @@ - (void)addCurtainWithCompletionHandler:(ProceduralBlock)completionHandler { if (!curtain_) { - curtain_.reset( - [[UIView alloc] initWithFrame:[swipeDelegate_ contentView].bounds]); + curtain_ = + [[UIView alloc] initWithFrame:[swipeDelegate_ contentView].bounds]; [curtain_ setBackgroundColor:[UIColor whiteColor]]; } [[swipeDelegate_ contentView] addSubview:curtain_]; @@ -500,7 +500,7 @@ // long it can take a web view to clear the previous page image, and what // feels like to 'too long' to see the curtain. [self performSelector:@selector(dismissCurtainWithCompletionHandler:) - withObject:[[completionHandler copy] autorelease] + withObject:[completionHandler copy] afterDelay:3]; } @@ -514,7 +514,7 @@ [NSObject cancelPreviousPerformRequestsWithTarget:self]; webStateObserverBridge_.reset(); [curtain_ removeFromSuperview]; - curtain_.reset(); + curtain_ = nil; completionHandler(); }
diff --git a/ios/chrome/browser/ui/side_swipe/side_swipe_navigation_view.h b/ios/chrome/browser/ui/side_swipe/side_swipe_navigation_view.h index b18f2a3..c8a4e2b 100644 --- a/ios/chrome/browser/ui/side_swipe/side_swipe_navigation_view.h +++ b/ios/chrome/browser/ui/side_swipe/side_swipe_navigation_view.h
@@ -13,7 +13,7 @@ // is dragged from side to side. @interface SideSwipeNavigationView : UIView -@property(nonatomic, assign) UIView* targetView; +@property(nonatomic, weak) UIView* targetView; // Initialize with direction. - (instancetype)initWithFrame:(CGRect)frame
diff --git a/ios/chrome/browser/ui/side_swipe/side_swipe_navigation_view.mm b/ios/chrome/browser/ui/side_swipe/side_swipe_navigation_view.mm index ca4fa6d2..83beea7e 100644 --- a/ios/chrome/browser/ui/side_swipe/side_swipe_navigation_view.mm +++ b/ios/chrome/browser/ui/side_swipe/side_swipe_navigation_view.mm
@@ -7,8 +7,7 @@ #include <cmath> #include "base/logging.h" -#include "base/mac/objc_property_releaser.h" -#include "base/mac/scoped_nsobject.h" + #include "base/metrics/user_metrics.h" #include "base/metrics/user_metrics_action.h" #import "ios/chrome/browser/ui/side_swipe/side_swipe_util.h" @@ -17,6 +16,10 @@ #import "ios/chrome/browser/ui/uikit_ui_util.h" #import "ios/chrome/common/material_timing.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + namespace { enum class SwipeType { CHANGE_TABS, NAVIGATION }; @@ -71,7 +74,7 @@ BOOL thresholdTriggered_; // The back or forward sprite image. - base::scoped_nsobject<UIImageView> arrowView_; + UIImageView* arrowView_; // The selection bubble. CAShapeLayer* selectionCircleLayer_; @@ -83,8 +86,6 @@ // If |YES| arrowView_ is directionnal and must be rotated 180 degreed for the // forward panes. BOOL rotateForward_; - - base::mac::ObjCPropertyReleaser _propertyReleaser_SideSwipeNavigationView; } // Returns a newly allocated and configured selection circle shape. - (CAShapeLayer*)newSelectionCircleLayer; @@ -104,8 +105,6 @@ rotateForward:(BOOL)rotateForward { self = [super initWithFrame:frame]; if (self) { - _propertyReleaser_SideSwipeNavigationView.Init( - self, [SideSwipeNavigationView class]); self.backgroundColor = [UIColor colorWithWhite:90.0 / 256 alpha:1.0]; canNavigate_ = canNavigate; @@ -113,7 +112,7 @@ if (canNavigate) { image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; const CGRect imageSize = CGRectMake(0, 0, 24, 24); - arrowView_.reset([[UIImageView alloc] initWithImage:image]); + arrowView_ = [[UIImageView alloc] initWithImage:image]; [arrowView_ setTintColor:[UIColor whiteColor]]; selectionCircleLayer_ = [self newSelectionCircleLayer]; [arrowView_ setFrame:imageSize]; @@ -123,8 +122,7 @@ [UIImage imageNamed:@"side_swipe_navigation_content_shadow"]; CGRect borderFrame = CGRectMake(0, 0, shadowImage.size.width, self.frame.size.height); - base::scoped_nsobject<UIImageView> border( - [[UIImageView alloc] initWithFrame:borderFrame]); + UIImageView* border = [[UIImageView alloc] initWithFrame:borderFrame]; [border setImage:shadowImage]; [self addSubview:border]; if (direction == UISwipeGestureRecognizerDirectionRight) {
diff --git a/ios/chrome/browser/ui/side_swipe/side_swipe_util.mm b/ios/chrome/browser/ui/side_swipe/side_swipe_util.mm index f8a2a0d..7a8455e3 100644 --- a/ios/chrome/browser/ui/side_swipe/side_swipe_util.mm +++ b/ios/chrome/browser/ui/side_swipe/side_swipe_util.mm
@@ -8,6 +8,10 @@ #include "ios/chrome/browser/ui/rtl_geometry.h" +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + BOOL IsSwipingBack(UISwipeGestureRecognizerDirection direction) { if (UseRTLLayout()) return direction == UISwipeGestureRecognizerDirectionLeft;
diff --git a/ios/chrome/widget_extension/BUILD.gn b/ios/chrome/search_widget_extension/BUILD.gn similarity index 71% rename from ios/chrome/widget_extension/BUILD.gn rename to ios/chrome/search_widget_extension/BUILD.gn index 31fed23e..80a585f 100644 --- a/ios/chrome/widget_extension/BUILD.gn +++ b/ios/chrome/search_widget_extension/BUILD.gn
@@ -14,17 +14,17 @@ compile_plist("entitlements") { format = "xml1" substitutions = [ "IOS_BUNDLE_ID_PREFIX=$ios_app_bundle_id_prefix" ] - output_name = "$target_gen_dir/today_extension.appex.entitlements" + output_name = "$target_gen_dir/search_widget_extension.appex.entitlements" plist_templates = - [ "entitlements/external/widget_extension.appex.entitlements" ] + [ "entitlements/external/search_widget_extension.appex.entitlements" ] } -ios_appex_bundle("widget_extension") { +ios_appex_bundle("search_widget_extension") { sources = [ - "widget_view.h", - "widget_view.mm", - "widget_view_controller.h", - "widget_view_controller.mm", + "search_widget_view.h", + "search_widget_view.mm", + "search_widget_view_controller.h", + "search_widget_view_controller.mm", ] deps = [ @@ -52,11 +52,7 @@ extra_substitutions = [ "CHROME_CHANNEL_SCHEME=$url_channel_scheme", "CHROMIUM_SHORT_NAME=$chromium_short_name", - - # The widget_extension and today_extension are using the same provisioning - # profile during development work. - # TODO(crbug.com/682238) : Request provisioning profile if widget is kept. - "WIDGET_EXTENSION_BUNDLE_ID=$chromium_bundle_id.TodayExtension", + "WIDGET_EXTENSION_BUNDLE_ID=$chromium_bundle_id.SearchTodayExtension", ] configs += [ "//build/config/compiler:enable_arc" ]
diff --git a/ios/chrome/widget_extension/DEPS b/ios/chrome/search_widget_extension/DEPS similarity index 100% rename from ios/chrome/widget_extension/DEPS rename to ios/chrome/search_widget_extension/DEPS
diff --git a/ios/chrome/widget_extension/Info.plist b/ios/chrome/search_widget_extension/Info.plist similarity index 88% rename from ios/chrome/widget_extension/Info.plist rename to ios/chrome/search_widget_extension/Info.plist index 915460e2..6b05ac1 100644 --- a/ios/chrome/widget_extension/Info.plist +++ b/ios/chrome/search_widget_extension/Info.plist
@@ -7,13 +7,13 @@ <key>CFBundleDisplayName</key> <string>${CHROMIUM_SHORT_NAME}</string> <key>CFBundleExecutable</key> - <string>widget_extension</string> + <string>search_widget_extension</string> <key>CFBundleIdentifier</key> <string>${IOS_BUNDLE_ID_PREFIX}.${WIDGET_EXTENSION_BUNDLE_ID}</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> - <string>widget_extension</string> + <string>search_widget_extension</string> <key>CFBundlePackageType</key> <string>XPC!</string> <key>CFBundleShortVersionString</key> @@ -25,7 +25,7 @@ <key>NSExtension</key> <dict> <key>NSExtensionPrincipalClass</key> - <string>WidgetViewController</string> + <string>SearchWidgetViewController</string> <key>NSExtensionPointIdentifier</key> <string>com.apple.widget-extension</string> </dict>
diff --git a/ios/chrome/widget_extension/OWNERS b/ios/chrome/search_widget_extension/OWNERS similarity index 100% rename from ios/chrome/widget_extension/OWNERS rename to ios/chrome/search_widget_extension/OWNERS
diff --git a/ios/chrome/widget_extension/entitlements/external/widget_extension.appex.entitlements b/ios/chrome/search_widget_extension/entitlements/external/search_widget_extension.appex.entitlements similarity index 100% rename from ios/chrome/widget_extension/entitlements/external/widget_extension.appex.entitlements rename to ios/chrome/search_widget_extension/entitlements/external/search_widget_extension.appex.entitlements
diff --git a/ios/chrome/widget_extension/widget_view.h b/ios/chrome/search_widget_extension/search_widget_view.h similarity index 67% rename from ios/chrome/widget_extension/widget_view.h rename to ios/chrome/search_widget_extension/search_widget_view.h index 6b6bd57..d9f145c 100644 --- a/ios/chrome/widget_extension/widget_view.h +++ b/ios/chrome/search_widget_extension/search_widget_view.h
@@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef IOS_CHROME_WIDGET_EXTENSION_WIDGET_VIEW_H_ -#define IOS_CHROME_WIDGET_EXTENSION_WIDGET_VIEW_H_ +#ifndef IOS_CHROME_SEARCH_WIDGET_EXTENSION_SEARCH_WIDGET_VIEW_H_ +#define IOS_CHROME_SEARCH_WIDGET_EXTENSION_SEARCH_WIDGET_VIEW_H_ #import <UIKit/UIKit.h> -// Protocol to be implemented by targets for user actions coming from the widget -// view. -@protocol WidgetViewActionTarget +// Protocol to be implemented by targets for user actions coming from the search +// widget view. +@protocol SearchWidgetViewActionTarget // Called when the user taps the Search button. - (void)openSearch:(id)sender; @@ -24,13 +24,13 @@ @end -// View for the widget. Shows a blinking cursor for a fake omnibox and calls the -// target when tapped. -@interface WidgetView : UIView +// View for the search widget. Shows a blinking cursor for a fake omnibox and +// calls the target when tapped. +@interface SearchWidgetView : UIView // Designated initializer, creates the widget view with a |target| for user // actions. -- (instancetype)initWithActionTarget:(id<WidgetViewActionTarget>)target +- (instancetype)initWithActionTarget:(id<SearchWidgetViewActionTarget>)target NS_DESIGNATED_INITIALIZER; - (instancetype)initWithFrame:(CGRect)frame NS_UNAVAILABLE; - (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE; @@ -40,4 +40,4 @@ @end -#endif // IOS_CHROME_WIDGET_EXTENSION_WIDGET_VIEW_H_ +#endif // IOS_CHROME_SEARCH_WIDGET_EXTENSION_SEARCH_WIDGET_VIEW_H_
diff --git a/ios/chrome/widget_extension/widget_view.mm b/ios/chrome/search_widget_extension/search_widget_view.mm similarity index 91% rename from ios/chrome/widget_extension/widget_view.mm rename to ios/chrome/search_widget_extension/search_widget_view.mm index d078fe0..42a7f89 100644 --- a/ios/chrome/widget_extension/widget_view.mm +++ b/ios/chrome/search_widget_extension/search_widget_view.mm
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#import "ios/chrome/widget_extension/widget_view.h" +#import "ios/chrome/search_widget_extension/search_widget_view.h" #include "base/logging.h" @@ -21,8 +21,8 @@ } // namespace -@interface WidgetView () { - __weak id<WidgetViewActionTarget> _target; +@interface SearchWidgetView () { + __weak id<SearchWidgetViewActionTarget> _target; } @property(nonatomic, copy) NSString* copiedURL; @@ -35,14 +35,14 @@ @end -@implementation WidgetView +@implementation SearchWidgetView @synthesize copiedURL = _copiedURL; @synthesize copiedURLLabel = _copiedURLLabel; @synthesize cursor = _cursor; -- (instancetype)initWithActionTarget:(id<WidgetViewActionTarget>)target { +- (instancetype)initWithActionTarget:(id<SearchWidgetViewActionTarget>)target { self = [super initWithFrame:CGRectZero]; if (self) { DCHECK(target);
diff --git a/ios/chrome/search_widget_extension/search_widget_view_controller.h b/ios/chrome/search_widget_extension/search_widget_view_controller.h new file mode 100644 index 0000000..938e2b12 --- /dev/null +++ b/ios/chrome/search_widget_extension/search_widget_view_controller.h
@@ -0,0 +1,15 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_SEARCH_WIDGET_EXTENSION_SEARCH_WIDGET_VIEW_CONTROLLER_H_ +#define IOS_CHROME_SEARCH_WIDGET_EXTENSION_SEARCH_WIDGET_VIEW_CONTROLLER_H_ + +#import <NotificationCenter/NotificationCenter.h> +#import <UIKit/UIKit.h> + +@interface SearchWidgetViewController : UIViewController<NCWidgetProviding> + +@end + +#endif // IOS_CHROME_SEARCH_WIDGET_EXTENSION_SEARCH_WIDGET_VIEW_CONTROLLER_H_
diff --git a/ios/chrome/widget_extension/widget_view_controller.mm b/ios/chrome/search_widget_extension/search_widget_view_controller.mm similarity index 92% rename from ios/chrome/widget_extension/widget_view_controller.mm rename to ios/chrome/search_widget_extension/search_widget_view_controller.mm index 141cc23..12e8838f 100644 --- a/ios/chrome/widget_extension/widget_view_controller.mm +++ b/ios/chrome/search_widget_extension/search_widget_view_controller.mm
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#import "ios/chrome/widget_extension/widget_view_controller.h" +#import "ios/chrome/search_widget_extension/search_widget_view_controller.h" #import <NotificationCenter/NotificationCenter.h> @@ -11,7 +11,7 @@ #include "base/strings/sys_string_conversions.h" #include "components/open_from_clipboard/clipboard_recent_content_impl_ios.h" #include "ios/chrome/common/app_group/app_group_constants.h" -#import "ios/chrome/widget_extension/widget_view.h" +#import "ios/chrome/search_widget_extension/search_widget_view.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -25,8 +25,8 @@ NSString* const kXCallbackURLHost = @"x-callback-url"; } // namespace -@interface WidgetViewController ()<WidgetViewActionTarget> -@property(nonatomic, weak) WidgetView* widgetView; +@interface SearchWidgetViewController ()<SearchWidgetViewActionTarget> +@property(nonatomic, weak) SearchWidgetView* widgetView; @property(nonatomic, strong) NSURL* copiedURL; @property(nonatomic, strong) ClipboardRecentContentImplIOS* clipboardRecentContent; @@ -45,7 +45,7 @@ @end -@implementation WidgetViewController +@implementation SearchWidgetViewController @synthesize widgetView = _widgetView; @synthesize copiedURL = _copiedURL; @@ -70,7 +70,8 @@ // A local variable is necessary here as the property is declared weak and the // object would be deallocated before being retained by the addSubview call. - WidgetView* widgetView = [[WidgetView alloc] initWithActionTarget:self]; + SearchWidgetView* widgetView = + [[SearchWidgetView alloc] initWithActionTarget:self]; self.widgetView = widgetView; [self.view addSubview:self.widgetView]; @@ -172,9 +173,10 @@ [[NSUserDefaults alloc] initWithSuiteName:app_group::ApplicationGroup()]; NSString* defaultsKey = base::SysUTF8ToNSString(app_group::kChromeAppGroupCommandPreference); - [sharedDefaults setObject:[WidgetViewController dictForCommand:command - parameter:parameter] - forKey:defaultsKey]; + [sharedDefaults + setObject:[SearchWidgetViewController dictForCommand:command + parameter:parameter] + forKey:defaultsKey]; [sharedDefaults synchronize]; NSString* scheme = base::mac::ObjCCast<NSString>([[NSBundle mainBundle]
diff --git a/ios/chrome/widget_extension/widget_view_controller.h b/ios/chrome/widget_extension/widget_view_controller.h deleted file mode 100644 index 6026622..0000000 --- a/ios/chrome/widget_extension/widget_view_controller.h +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_CHROME_WIDGET_EXTENSION_WIDGET_VIEW_CONTROLLER_H_ -#define IOS_CHROME_WIDGET_EXTENSION_WIDGET_VIEW_CONTROLLER_H_ - -#import <NotificationCenter/NotificationCenter.h> -#import <UIKit/UIKit.h> - -@interface WidgetViewController : UIViewController<NCWidgetProviding> - -@end - -#endif // IOS_CHROME_WIDGET_EXTENSION_WIDGET_VIEW_CONTROLLER_H_
diff --git a/ios/clean/chrome/browser/ui/find_in_page/find_in_page_mediator.mm b/ios/clean/chrome/browser/ui/find_in_page/find_in_page_mediator.mm index c5f7900..645e739f 100644 --- a/ios/clean/chrome/browser/ui/find_in_page/find_in_page_mediator.mm +++ b/ios/clean/chrome/browser/ui/find_in_page/find_in_page_mediator.mm
@@ -5,6 +5,7 @@ #import "ios/clean/chrome/browser/ui/find_in_page/find_in_page_mediator.h" #include "base/memory/ptr_util.h" +#include "base/scoped_observer.h" #import "ios/chrome/browser/find_in_page/find_in_page_model.h" #import "ios/chrome/browser/find_in_page/find_tab_helper.h" #include "ios/chrome/browser/web_state_list/web_state_list.h" @@ -36,6 +37,8 @@ // Observes the WebStateList so that this mediator can update the UI when the // active WebState changes. std::unique_ptr<WebStateListObserverBridge> _webStateListObserver; + std::unique_ptr<ScopedObserver<WebStateList, WebStateListObserverBridge>> + _scopedWebStateListObserver; } @synthesize dispatcher = _dispatcher; @@ -55,15 +58,14 @@ _dispatcher = dispatcher; _webStateListObserver = base::MakeUnique<WebStateListObserverBridge>(self); - _webStateList->AddObserver(_webStateListObserver.get()); + _scopedWebStateListObserver = base::MakeUnique< + ScopedObserver<WebStateList, WebStateListObserverBridge>>( + _webStateListObserver.get()); + _scopedWebStateListObserver->Add(_webStateList); } return self; } -- (void)dealloc { - _webStateList->RemoveObserver(_webStateListObserver.get()); -} - - (void)stopFinding { web::WebState* webState = self.webStateList->GetActiveWebState(); FindTabHelper* helper = FindTabHelper::FromWebState(webState);
diff --git a/mojo/public/cpp/bindings/array_traits_wtf_vector.h b/mojo/public/cpp/bindings/array_traits_wtf_vector.h index d95cd2e..1780c81 100644 --- a/mojo/public/cpp/bindings/array_traits_wtf_vector.h +++ b/mojo/public/cpp/bindings/array_traits_wtf_vector.h
@@ -21,7 +21,7 @@ static void SetToNull(WTF::Vector<U>* output) { // WTF::Vector<> doesn't support null state. Set it to empty instead. - output->Clear(); + output->clear(); } static size_t GetSize(const WTF::Vector<U>& input) { return input.size(); }
diff --git a/net/BUILD.gn b/net/BUILD.gn index 1c06639..0c33989d 100644 --- a/net/BUILD.gn +++ b/net/BUILD.gn
@@ -788,8 +788,6 @@ "http/bidirectional_stream_request_info.h", "http/des.cc", "http/des.h", - "http/disk_cache_based_quic_server_info.cc", - "http/disk_cache_based_quic_server_info.h", "http/failing_http_transaction_factory.cc", "http/failing_http_transaction_factory.h", "http/http_auth.cc", @@ -4325,7 +4323,6 @@ "ftp/ftp_util_unittest.cc", "http/bidirectional_stream_unittest.cc", "http/des_unittest.cc", - "http/disk_cache_based_quic_server_info_unittest.cc", "http/http_auth_cache_unittest.cc", "http/http_auth_challenge_tokenizer_unittest.cc", "http/http_auth_controller_unittest.cc",
diff --git a/net/http/disk_cache_based_quic_server_info.cc b/net/http/disk_cache_based_quic_server_info.cc deleted file mode 100644 index b149fc9..0000000 --- a/net/http/disk_cache_based_quic_server_info.cc +++ /dev/null
@@ -1,450 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "net/http/disk_cache_based_quic_server_info.h" - -#include "base/bind.h" -#include "base/callback.h" -#include "base/callback_helpers.h" -#include "base/logging.h" -#include "base/metrics/histogram_macros.h" -#include "base/stl_util.h" -#include "base/trace_event/memory_usage_estimator.h" -#include "net/base/completion_callback.h" -#include "net/base/io_buffer.h" -#include "net/base/net_errors.h" -#include "net/http/http_cache.h" -#include "net/http/http_network_session.h" -#include "net/quic/core/quic_server_id.h" - -namespace net { - -// Some APIs inside disk_cache take a handle that the caller must keep alive -// until the API has finished its asynchronous execution. -// -// Unfortunately, DiskCacheBasedQuicServerInfo may be deleted before the -// operation completes causing a use-after-free. -// -// This data shim struct is meant to provide a location for the disk_cache -// APIs to write into even if the originating DiskCacheBasedQuicServerInfo -// object has been deleted. The lifetime for instances of this struct -// should be bound to the CompletionCallback that is passed to the disk_cache -// API. We do this by binding an instance of this struct to an unused -// parameter for OnIOComplete() using base::Owned(). -// -// This is a hack. A better fix is to make it so that the disk_cache APIs -// take a Callback to a mutator for setting the output value rather than -// writing into a raw handle. Then the caller can just pass in a Callback -// bound to WeakPtr for itself. This callback would correctly "no-op" itself -// when the DiskCacheBasedQuicServerInfo object is deleted. -// -// TODO(ajwong): Change disk_cache's API to return results via Callback. -struct DiskCacheBasedQuicServerInfo::CacheOperationDataShim { - CacheOperationDataShim() : backend(NULL), entry(NULL) {} - - disk_cache::Backend* backend; - disk_cache::Entry* entry; -}; - -DiskCacheBasedQuicServerInfo::DiskCacheBasedQuicServerInfo( - const QuicServerId& server_id, - HttpCache* http_cache) - : QuicServerInfo(server_id), - data_shim_(new CacheOperationDataShim()), - state_(GET_BACKEND), - ready_(false), - found_entry_(false), - server_id_(server_id), - http_cache_(http_cache), - backend_(NULL), - entry_(NULL), - last_failure_(NO_FAILURE), - weak_factory_(this) { - io_callback_ = - base::Bind(&DiskCacheBasedQuicServerInfo::OnIOComplete, - weak_factory_.GetWeakPtr(), - base::Owned(data_shim_)); // Ownership assigned. -} - -DiskCacheBasedQuicServerInfo::~DiskCacheBasedQuicServerInfo() { - DCHECK(wait_for_ready_callback_.is_null()); - if (entry_) - entry_->Close(); -} - -void DiskCacheBasedQuicServerInfo::Start() { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(GET_BACKEND, state_); - DCHECK_EQ(last_failure_, NO_FAILURE); - RecordQuicServerInfoStatus(QUIC_SERVER_INFO_START); - load_start_time_ = base::TimeTicks::Now(); - DoLoop(OK); -} - -int DiskCacheBasedQuicServerInfo::WaitForDataReady( - const CompletionCallback& callback) { - DCHECK(CalledOnValidThread()); - DCHECK_NE(GET_BACKEND, state_); - wait_for_data_start_time_ = base::TimeTicks::Now(); - - RecordQuicServerInfoStatus(QUIC_SERVER_INFO_WAIT_FOR_DATA_READY); - if (ready_) { - wait_for_data_end_time_ = base::TimeTicks::Now(); - RecordLastFailure(); - return OK; - } - - if (!callback.is_null()) { - // Prevent a new callback for WaitForDataReady overwriting an existing - // pending callback (|wait_for_ready_callback_|). - if (!wait_for_ready_callback_.is_null()) { - RecordQuicServerInfoFailure(WAIT_FOR_DATA_READY_INVALID_ARGUMENT_FAILURE); - return ERR_INVALID_ARGUMENT; - } - wait_for_ready_callback_ = callback; - } - - return ERR_IO_PENDING; -} - -void DiskCacheBasedQuicServerInfo::ResetWaitForDataReadyCallback() { - DCHECK(CalledOnValidThread()); - wait_for_ready_callback_.Reset(); -} - -void DiskCacheBasedQuicServerInfo::CancelWaitForDataReadyCallback() { - DCHECK(CalledOnValidThread()); - - RecordQuicServerInfoStatus(QUIC_SERVER_INFO_WAIT_FOR_DATA_READY_CANCEL); - if (!wait_for_ready_callback_.is_null()) { - RecordLastFailure(); - wait_for_ready_callback_.Reset(); - } -} - -bool DiskCacheBasedQuicServerInfo::IsDataReady() { - return ready_; -} - -bool DiskCacheBasedQuicServerInfo::IsReadyToPersist() { - // The data can be persisted if it has been loaded from the disk cache - // and there are no pending writes. - RecordQuicServerInfoStatus(QUIC_SERVER_INFO_READY_TO_PERSIST); - if (ready_ && new_data_.empty()) - return true; - RecordQuicServerInfoFailure(READY_TO_PERSIST_FAILURE); - return false; -} - -void DiskCacheBasedQuicServerInfo::Persist() { - DCHECK(CalledOnValidThread()); - if (!IsReadyToPersist()) { - // Handle updates while a write is pending or if we haven't loaded from disk - // cache. Save the data to be written into a temporary buffer and then - // persist that data when we are ready to persist. - pending_write_data_ = Serialize(); - return; - } - PersistInternal(); -} - -void DiskCacheBasedQuicServerInfo::PersistInternal() { - DCHECK(CalledOnValidThread()); - DCHECK_NE(GET_BACKEND, state_); - DCHECK(new_data_.empty()); - CHECK(ready_); - DCHECK(wait_for_ready_callback_.is_null()); - - if (pending_write_data_.empty()) { - new_data_ = Serialize(); - } else { - new_data_ = pending_write_data_; - base::STLClearObject(&pending_write_data_); - } - - RecordQuicServerInfoStatus(QUIC_SERVER_INFO_PERSIST); - if (!backend_) { - RecordQuicServerInfoFailure(PERSIST_NO_BACKEND_FAILURE); - return; - } - - state_ = CREATE_OR_OPEN; - DoLoop(OK); -} - -void DiskCacheBasedQuicServerInfo::OnExternalCacheHit() { - DCHECK(CalledOnValidThread()); - DCHECK_NE(GET_BACKEND, state_); - - RecordQuicServerInfoStatus(QUIC_SERVER_INFO_EXTERNAL_CACHE_HIT); - if (!backend_) { - RecordQuicServerInfoFailure(PERSIST_NO_BACKEND_FAILURE); - return; - } - - backend_->OnExternalCacheHit(key()); -} - -size_t DiskCacheBasedQuicServerInfo::EstimateMemoryUsage() const { - return base::trace_event::EstimateMemoryUsage(new_data_) + - base::trace_event::EstimateMemoryUsage(pending_write_data_) + - base::trace_event::EstimateMemoryUsage(server_id_) + - (read_buffer_ == nullptr ? 0 : read_buffer_->size()) + - (write_buffer_ == nullptr ? 0 : write_buffer_->size()) + - base::trace_event::EstimateMemoryUsage(data_); -} - -std::string DiskCacheBasedQuicServerInfo::key() const { - return "quicserverinfo:" + server_id_.ToString(); -} - -void DiskCacheBasedQuicServerInfo::OnIOComplete(CacheOperationDataShim* unused, - int rv) { - DCHECK_NE(NONE, state_); - rv = DoLoop(rv); - if (rv == ERR_IO_PENDING) - return; - - base::WeakPtr<DiskCacheBasedQuicServerInfo> weak_this = - weak_factory_.GetWeakPtr(); - - if (!wait_for_ready_callback_.is_null()) { - wait_for_data_end_time_ = base::TimeTicks::Now(); - RecordLastFailure(); - base::ResetAndReturn(&wait_for_ready_callback_).Run(rv); - } - // |wait_for_ready_callback_| could delete the object if there is an error. - // Check if |weak_this| still exists before accessing it. - if (weak_this.get() && ready_ && !pending_write_data_.empty()) { - DCHECK_EQ(NONE, state_); - PersistInternal(); - } -} - -int DiskCacheBasedQuicServerInfo::DoLoop(int rv) { - do { - switch (state_) { - case GET_BACKEND: - rv = DoGetBackend(); - break; - case GET_BACKEND_COMPLETE: - rv = DoGetBackendComplete(rv); - break; - case OPEN: - rv = DoOpen(); - break; - case OPEN_COMPLETE: - rv = DoOpenComplete(rv); - break; - case READ: - rv = DoRead(); - break; - case READ_COMPLETE: - rv = DoReadComplete(rv); - break; - case WAIT_FOR_DATA_READY_DONE: - rv = DoWaitForDataReadyDone(); - break; - case CREATE_OR_OPEN: - rv = DoCreateOrOpen(); - break; - case CREATE_OR_OPEN_COMPLETE: - rv = DoCreateOrOpenComplete(rv); - break; - case WRITE: - rv = DoWrite(); - break; - case WRITE_COMPLETE: - rv = DoWriteComplete(rv); - break; - case SET_DONE: - rv = DoSetDone(); - break; - default: - rv = OK; - NOTREACHED(); - } - } while (rv != ERR_IO_PENDING && state_ != NONE); - - return rv; -} - -int DiskCacheBasedQuicServerInfo::DoGetBackendComplete(int rv) { - if (rv == OK) { - backend_ = data_shim_->backend; - state_ = OPEN; - } else { - RecordQuicServerInfoFailure(GET_BACKEND_FAILURE); - state_ = WAIT_FOR_DATA_READY_DONE; - } - return OK; -} - -int DiskCacheBasedQuicServerInfo::DoOpenComplete(int rv) { - if (rv == OK) { - entry_ = data_shim_->entry; - state_ = READ; - found_entry_ = true; - } else { - RecordQuicServerInfoFailure(OPEN_FAILURE); - state_ = WAIT_FOR_DATA_READY_DONE; - } - - return OK; -} - -int DiskCacheBasedQuicServerInfo::DoReadComplete(int rv) { - if (rv > 0) - data_.assign(read_buffer_->data(), rv); - else if (rv < 0) - RecordQuicServerInfoFailure(READ_FAILURE); - - read_buffer_ = nullptr; - state_ = WAIT_FOR_DATA_READY_DONE; - return OK; -} - -int DiskCacheBasedQuicServerInfo::DoWriteComplete(int rv) { - if (rv < 0) - RecordQuicServerInfoFailure(WRITE_FAILURE); - write_buffer_ = nullptr; - state_ = SET_DONE; - return OK; -} - -int DiskCacheBasedQuicServerInfo::DoCreateOrOpenComplete(int rv) { - if (rv != OK) { - RecordQuicServerInfoFailure(CREATE_OR_OPEN_FAILURE); - state_ = SET_DONE; - } else { - if (!entry_) { - entry_ = data_shim_->entry; - found_entry_ = true; - } - DCHECK(entry_); - state_ = WRITE; - } - return OK; -} - -int DiskCacheBasedQuicServerInfo::DoGetBackend() { - state_ = GET_BACKEND_COMPLETE; - return http_cache_->GetBackend(&data_shim_->backend, io_callback_); -} - -int DiskCacheBasedQuicServerInfo::DoOpen() { - state_ = OPEN_COMPLETE; - return backend_->OpenEntry(key(), &data_shim_->entry, io_callback_); -} - -int DiskCacheBasedQuicServerInfo::DoRead() { - const int32_t size = entry_->GetDataSize(0 /* index */); - if (!size) { - state_ = WAIT_FOR_DATA_READY_DONE; - return OK; - } - - read_buffer_ = new IOBufferWithSize(size); - state_ = READ_COMPLETE; - return entry_->ReadData( - 0 /* index */, 0 /* offset */, read_buffer_.get(), size, io_callback_); -} - -int DiskCacheBasedQuicServerInfo::DoWrite() { - write_buffer_ = new IOBufferWithSize(new_data_.size()); - memcpy(write_buffer_->data(), new_data_.data(), new_data_.size()); - state_ = WRITE_COMPLETE; - - return entry_->WriteData(0 /* index */, - 0 /* offset */, - write_buffer_.get(), - new_data_.size(), - io_callback_, - true /* truncate */); -} - -int DiskCacheBasedQuicServerInfo::DoCreateOrOpen() { - state_ = CREATE_OR_OPEN_COMPLETE; - if (entry_) - return OK; - - if (found_entry_) { - return backend_->OpenEntry(key(), &data_shim_->entry, io_callback_); - } - - return backend_->CreateEntry(key(), &data_shim_->entry, io_callback_); -} - -int DiskCacheBasedQuicServerInfo::DoWaitForDataReadyDone() { - DCHECK(!ready_); - state_ = NONE; - ready_ = true; - // We close the entry because, if we shutdown before ::Persist is called, - // then we might leak a cache reference, which causes a DCHECK on shutdown. - if (entry_) - entry_->Close(); - entry_ = NULL; - - RecordQuicServerInfoStatus(QUIC_SERVER_INFO_PARSE); - if (!Parse(data_)) { - if (data_.empty()) - RecordQuicServerInfoFailure(PARSE_NO_DATA_FAILURE); - else - RecordQuicServerInfoFailure(PARSE_FAILURE); - } - - UMA_HISTOGRAM_TIMES("Net.QuicServerInfo.DiskCacheLoadTime", - base::TimeTicks::Now() - load_start_time_); - return OK; -} - -int DiskCacheBasedQuicServerInfo::DoSetDone() { - if (entry_) - entry_->Close(); - entry_ = NULL; - base::STLClearObject(&new_data_); - state_ = NONE; - return OK; -} - -void DiskCacheBasedQuicServerInfo::RecordQuicServerInfoStatus( - QuicServerInfoAPICall call) { - if (!backend_) { - UMA_HISTOGRAM_ENUMERATION("Net.QuicDiskCache.APICall.NoBackend", call, - QUIC_SERVER_INFO_NUM_OF_API_CALLS); - } else if (backend_->GetCacheType() == MEMORY_CACHE) { - UMA_HISTOGRAM_ENUMERATION("Net.QuicDiskCache.APICall.MemoryCache", call, - QUIC_SERVER_INFO_NUM_OF_API_CALLS); - } else { - UMA_HISTOGRAM_ENUMERATION("Net.QuicDiskCache.APICall.DiskCache", call, - QUIC_SERVER_INFO_NUM_OF_API_CALLS); - } -} - -void DiskCacheBasedQuicServerInfo::RecordLastFailure() { - if (last_failure_ != NO_FAILURE) { - UMA_HISTOGRAM_ENUMERATION( - "Net.QuicDiskCache.FailureReason.WaitForDataReady", - last_failure_, NUM_OF_FAILURES); - } - last_failure_ = NO_FAILURE; -} - -void DiskCacheBasedQuicServerInfo::RecordQuicServerInfoFailure( - FailureReason failure) { - last_failure_ = failure; - - if (!backend_) { - UMA_HISTOGRAM_ENUMERATION("Net.QuicDiskCache.FailureReason.NoBackend", - failure, NUM_OF_FAILURES); - } else if (backend_->GetCacheType() == MEMORY_CACHE) { - UMA_HISTOGRAM_ENUMERATION("Net.QuicDiskCache.FailureReason.MemoryCache", - failure, NUM_OF_FAILURES); - } else { - UMA_HISTOGRAM_ENUMERATION("Net.QuicDiskCache.FailureReason.DiskCache", - failure, NUM_OF_FAILURES); - } -} - -} // namespace net
diff --git a/net/http/disk_cache_based_quic_server_info.h b/net/http/disk_cache_based_quic_server_info.h deleted file mode 100644 index 2396f8c..0000000 --- a/net/http/disk_cache_based_quic_server_info.h +++ /dev/null
@@ -1,135 +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 NET_HTTP_DISK_CACHE_BASED_QUIC_SERVER_INFO_H_ -#define NET_HTTP_DISK_CACHE_BASED_QUIC_SERVER_INFO_H_ - -#include <string> - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/threading/non_thread_safe.h" -#include "base/time/time.h" -#include "net/base/completion_callback.h" -#include "net/base/net_export.h" -#include "net/disk_cache/disk_cache.h" -#include "net/quic/chromium/quic_server_info.h" - -namespace net { - -class HttpCache; -class IOBufferWithSize; -class QuicServerId; - -// DiskCacheBasedQuicServerInfo fetches information about a QUIC server from -// our standard disk cache. Since the information is defined to be -// non-sensitive, it's ok for us to keep it on disk. -class NET_EXPORT_PRIVATE DiskCacheBasedQuicServerInfo - : public QuicServerInfo, - public NON_EXPORTED_BASE(base::NonThreadSafe) { - public: - DiskCacheBasedQuicServerInfo(const QuicServerId& server_id, - HttpCache* http_cache); - ~DiskCacheBasedQuicServerInfo() override; - - // QuicServerInfo implementation. - void Start() override; - int WaitForDataReady(const CompletionCallback& callback) override; - void ResetWaitForDataReadyCallback() override; - void CancelWaitForDataReadyCallback() override; - bool IsDataReady() override; - bool IsReadyToPersist() override; - void Persist() override; - void OnExternalCacheHit() override; - size_t EstimateMemoryUsage() const override; - - private: - struct CacheOperationDataShim; - - enum State { - GET_BACKEND, - GET_BACKEND_COMPLETE, - OPEN, - OPEN_COMPLETE, - READ, - READ_COMPLETE, - WAIT_FOR_DATA_READY_DONE, - CREATE_OR_OPEN, - CREATE_OR_OPEN_COMPLETE, - WRITE, - WRITE_COMPLETE, - SET_DONE, - NONE, - }; - - // Persists |pending_write_data_| if it is not empty, otherwise serializes the - // data and pesists it. - void PersistInternal(); - - std::string key() const; - - // The |unused| parameter is a small hack so that we can have the - // CacheOperationDataShim object owned by the Callback that is created for - // this method. See comment above CacheOperationDataShim for details. - void OnIOComplete(CacheOperationDataShim* unused, int rv); - - int DoLoop(int rv); - - int DoGetBackendComplete(int rv); - int DoOpenComplete(int rv); - int DoReadComplete(int rv); - int DoWriteComplete(int rv); - int DoCreateOrOpenComplete(int rv); - - int DoGetBackend(); - int DoOpen(); - int DoRead(); - int DoWrite(); - int DoCreateOrOpen(); - - // DoWaitForDataReadyDone is the terminal state of the read operation. - int DoWaitForDataReadyDone(); - - // DoSetDone is the terminal state of the write operation. - int DoSetDone(); - - // Tracks in a histogram the number of times data read/parse/write API calls - // of QuicServerInfo to and from disk cache is called. - void RecordQuicServerInfoStatus(QuicServerInfoAPICall call); - - // Tracks in a histogram the failure reasons to read/load/write of - // QuicServerInfo to and from disk cache. It also saves the |failure| in - // |last_failure_|. - void RecordQuicServerInfoFailure(FailureReason failure); - - // Tracks in a histogram if |last_failure_| is not NO_FAILURE. - void RecordLastFailure(); - - CacheOperationDataShim* data_shim_; // Owned by |io_callback_|. - CompletionCallback io_callback_; - State state_; - bool ready_; - bool found_entry_; // Controls the behavior of DoCreateOrOpen. - std::string new_data_; - std::string pending_write_data_; - const QuicServerId server_id_; - HttpCache* const http_cache_; - disk_cache::Backend* backend_; - disk_cache::Entry* entry_; - CompletionCallback wait_for_ready_callback_; - scoped_refptr<IOBufferWithSize> read_buffer_; - scoped_refptr<IOBufferWithSize> write_buffer_; - std::string data_; - base::TimeTicks load_start_time_; - FailureReason last_failure_; - - base::WeakPtrFactory<DiskCacheBasedQuicServerInfo> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(DiskCacheBasedQuicServerInfo); -}; - -} // namespace net - -#endif // NET_HTTP_DISK_CACHE_BASED_QUIC_SERVER_INFO_H_
diff --git a/net/http/disk_cache_based_quic_server_info_unittest.cc b/net/http/disk_cache_based_quic_server_info_unittest.cc deleted file mode 100644 index 55f5835..0000000 --- a/net/http/disk_cache_based_quic_server_info_unittest.cc +++ /dev/null
@@ -1,721 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "net/http/disk_cache_based_quic_server_info.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "base/run_loop.h" -#include "net/base/net_errors.h" -#include "net/http/mock_http_cache.h" -#include "net/quic/chromium/quic_server_info.h" -#include "net/quic/core/quic_server_id.h" -#include "net/test/gtest_util.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using net::test::IsError; -using net::test::IsOk; - -using std::string; - -namespace net { -namespace { - -// This is an empty transaction, needed to register the URL and the test mode. -const MockTransaction kHostInfoTransaction1 = { - "quicserverinfo:https://www.google.com:443", - "", - base::Time(), - "", - LOAD_NORMAL, - "", - "", - base::Time(), - "", - TEST_MODE_NORMAL, - nullptr, - nullptr, - nullptr, - 0, - 0, - OK, -}; - -const MockTransaction kHostInfoTransaction2 = { - "quicserverinfo:https://www.google.com:80", - "", - base::Time(), - "", - LOAD_NORMAL, - "", - "", - base::Time(), - "", - TEST_MODE_NORMAL, - nullptr, - nullptr, - nullptr, - 0, - 0, - OK, -}; - -class DeleteCacheCompletionCallback : public TestCompletionCallbackBase { - public: - explicit DeleteCacheCompletionCallback(QuicServerInfo* server_info) - : server_info_(server_info), - callback_(base::Bind(&DeleteCacheCompletionCallback::OnComplete, - base::Unretained(this))) {} - - const CompletionCallback& callback() const { return callback_; } - - private: - void OnComplete(int result) { - delete server_info_; - SetResult(result); - } - - QuicServerInfo* server_info_; - CompletionCallback callback_; - - DISALLOW_COPY_AND_ASSIGN(DeleteCacheCompletionCallback); -}; - -} // namespace - -// Tests that we can delete a DiskCacheBasedQuicServerInfo object in a -// completion callback for DiskCacheBasedQuicServerInfo::WaitForDataReady. -TEST(DiskCacheBasedQuicServerInfo, DeleteInCallback) { - // Use the blocking mock backend factory to force asynchronous completion - // of quic_server_info->WaitForDataReady(), so that the callback will run. - MockBlockingBackendFactory* factory = new MockBlockingBackendFactory(); - MockHttpCache cache(base::WrapUnique(factory), true); - QuicServerId server_id("www.verisign.com", 443, PRIVACY_MODE_DISABLED); - std::unique_ptr<QuicServerInfo> quic_server_info( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - quic_server_info->Start(); - TestCompletionCallback callback; - int rv = quic_server_info->WaitForDataReady(callback.callback()); - EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); - // Now complete the backend creation and let the callback run. - factory->FinishCreation(); - EXPECT_THAT(callback.GetResult(rv), IsOk()); -} - -// Tests the basic logic of storing, retrieving and updating data. -TEST(DiskCacheBasedQuicServerInfo, Update) { - MockHttpCache cache(true); - AddMockTransaction(&kHostInfoTransaction1); - TestCompletionCallback callback; - - QuicServerId server_id("www.google.com", 443, PRIVACY_MODE_DISABLED); - std::unique_ptr<QuicServerInfo> quic_server_info( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - quic_server_info->Start(); - int rv = quic_server_info->WaitForDataReady(callback.callback()); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - - QuicServerInfo::State* state = quic_server_info->mutable_state(); - EXPECT_TRUE(state->certs.empty()); - const string server_config_a = "server_config_a"; - const string source_address_token_a = "source_address_token_a"; - const string cert_sct_a = "cert_sct_a"; - const string chlo_hash_a = "chlo_hash_a"; - const string server_config_sig_a = "server_config_sig_a"; - const string cert_a = "cert_a"; - const string cert_b = "cert_b"; - - state->server_config = server_config_a; - state->source_address_token = source_address_token_a; - state->cert_sct = cert_sct_a; - state->chlo_hash = chlo_hash_a; - state->server_config_sig = server_config_sig_a; - state->certs.push_back(cert_a); - quic_server_info->Persist(); - - // Wait until Persist() does the work. - base::RunLoop().RunUntilIdle(); - - // Open the stored QuicServerInfo. - quic_server_info.reset( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - quic_server_info->Start(); - rv = quic_server_info->WaitForDataReady(callback.callback()); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - - // And now update the data. - state = quic_server_info->mutable_state(); - state->certs.push_back(cert_b); - - // Fail instead of DCHECKing double creates. - cache.disk_cache()->set_double_create_check(false); - quic_server_info->Persist(); - base::RunLoop().RunUntilIdle(); - - // Verify that the state was updated. - quic_server_info.reset( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - quic_server_info->Start(); - rv = quic_server_info->WaitForDataReady(callback.callback()); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - EXPECT_TRUE(quic_server_info->IsDataReady()); - - const QuicServerInfo::State& state1 = quic_server_info->state(); - EXPECT_EQ(server_config_a, state1.server_config); - EXPECT_EQ(source_address_token_a, state1.source_address_token); - EXPECT_EQ(cert_sct_a, state1.cert_sct); - EXPECT_EQ(chlo_hash_a, state1.chlo_hash); - EXPECT_EQ(server_config_sig_a, state1.server_config_sig); - EXPECT_EQ(2U, state1.certs.size()); - EXPECT_EQ(cert_a, state1.certs[0]); - EXPECT_EQ(cert_b, state1.certs[1]); - - RemoveMockTransaction(&kHostInfoTransaction1); -} - -// Test that demonstrates different info is returned when the ports differ. -TEST(DiskCacheBasedQuicServerInfo, UpdateDifferentPorts) { - MockHttpCache cache(true); - AddMockTransaction(&kHostInfoTransaction1); - AddMockTransaction(&kHostInfoTransaction2); - TestCompletionCallback callback; - - // Persist data for port 443. - QuicServerId server_id1("www.google.com", 443, PRIVACY_MODE_DISABLED); - std::unique_ptr<QuicServerInfo> quic_server_info1( - new DiskCacheBasedQuicServerInfo(server_id1, cache.http_cache())); - quic_server_info1->Start(); - int rv = quic_server_info1->WaitForDataReady(callback.callback()); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - - QuicServerInfo::State* state1 = quic_server_info1->mutable_state(); - EXPECT_TRUE(state1->certs.empty()); - const string server_config_a = "server_config_a"; - const string source_address_token_a = "source_address_token_a"; - const string cert_sct_a = "cert_sct_a"; - const string chlo_hash_a = "chlo_hash_a"; - const string server_config_sig_a = "server_config_sig_a"; - const string cert_a = "cert_a"; - - state1->server_config = server_config_a; - state1->source_address_token = source_address_token_a; - state1->cert_sct = cert_sct_a; - state1->chlo_hash = chlo_hash_a; - state1->server_config_sig = server_config_sig_a; - state1->certs.push_back(cert_a); - quic_server_info1->Persist(); - - // Wait until Persist() does the work. - base::RunLoop().RunUntilIdle(); - - // Persist data for port 80. - QuicServerId server_id2("www.google.com", 80, PRIVACY_MODE_DISABLED); - std::unique_ptr<QuicServerInfo> quic_server_info2( - new DiskCacheBasedQuicServerInfo(server_id2, cache.http_cache())); - quic_server_info2->Start(); - rv = quic_server_info2->WaitForDataReady(callback.callback()); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - - QuicServerInfo::State* state2 = quic_server_info2->mutable_state(); - EXPECT_TRUE(state2->certs.empty()); - const string server_config_b = "server_config_b"; - const string source_address_token_b = "source_address_token_b"; - const string cert_sct_b = "cert_sct_b"; - const string chlo_hash_b = "chlo_hash_b"; - const string server_config_sig_b = "server_config_sig_b"; - const string cert_b = "cert_b"; - - state2->server_config = server_config_b; - state2->source_address_token = source_address_token_b; - state2->cert_sct = cert_sct_b; - state2->chlo_hash = chlo_hash_b; - state2->server_config_sig = server_config_sig_b; - state2->certs.push_back(cert_b); - quic_server_info2->Persist(); - - // Wait until Persist() does the work. - base::RunLoop().RunUntilIdle(); - - // Verify the stored QuicServerInfo for port 443. - std::unique_ptr<QuicServerInfo> quic_server_info( - new DiskCacheBasedQuicServerInfo(server_id1, cache.http_cache())); - quic_server_info->Start(); - rv = quic_server_info->WaitForDataReady(callback.callback()); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - EXPECT_TRUE(quic_server_info->IsDataReady()); - - const QuicServerInfo::State& state_a = quic_server_info->state(); - EXPECT_EQ(server_config_a, state_a.server_config); - EXPECT_EQ(source_address_token_a, state_a.source_address_token); - EXPECT_EQ(cert_sct_a, state_a.cert_sct); - EXPECT_EQ(chlo_hash_a, state_a.chlo_hash); - EXPECT_EQ(server_config_sig_a, state_a.server_config_sig); - EXPECT_EQ(1U, state_a.certs.size()); - EXPECT_EQ(cert_a, state_a.certs[0]); - - // Verify the stored QuicServerInfo for port 80. - quic_server_info.reset( - new DiskCacheBasedQuicServerInfo(server_id2, cache.http_cache())); - quic_server_info->Start(); - rv = quic_server_info->WaitForDataReady(callback.callback()); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - EXPECT_TRUE(quic_server_info->IsDataReady()); - - const QuicServerInfo::State& state_b = quic_server_info->state(); - EXPECT_EQ(server_config_b, state_b.server_config); - EXPECT_EQ(source_address_token_b, state_b.source_address_token); - EXPECT_EQ(cert_sct_b, state_b.cert_sct); - EXPECT_EQ(chlo_hash_b, state_b.chlo_hash); - EXPECT_EQ(server_config_sig_b, state_b.server_config_sig); - EXPECT_EQ(1U, state_b.certs.size()); - EXPECT_EQ(cert_b, state_b.certs[0]); - - RemoveMockTransaction(&kHostInfoTransaction2); - RemoveMockTransaction(&kHostInfoTransaction1); -} - -// Test IsReadyToPersist when there is a pending write. -TEST(DiskCacheBasedQuicServerInfo, IsReadyToPersist) { - MockHttpCache cache(true); - AddMockTransaction(&kHostInfoTransaction1); - TestCompletionCallback callback; - - QuicServerId server_id("www.google.com", 443, PRIVACY_MODE_DISABLED); - std::unique_ptr<QuicServerInfo> quic_server_info( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - EXPECT_FALSE(quic_server_info->IsDataReady()); - quic_server_info->Start(); - int rv = quic_server_info->WaitForDataReady(callback.callback()); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - EXPECT_TRUE(quic_server_info->IsDataReady()); - - QuicServerInfo::State* state = quic_server_info->mutable_state(); - EXPECT_TRUE(state->certs.empty()); - const string server_config_a = "server_config_a"; - const string source_address_token_a = "source_address_token_a"; - const string cert_sct_a = "cert_sct_a"; - const string chlo_hash_a = "chlo_hash_a"; - const string server_config_sig_a = "server_config_sig_a"; - const string cert_a = "cert_a"; - - state->server_config = server_config_a; - state->source_address_token = source_address_token_a; - state->cert_sct = cert_sct_a; - state->chlo_hash = chlo_hash_a; - state->server_config_sig = server_config_sig_a; - state->certs.push_back(cert_a); - EXPECT_TRUE(quic_server_info->IsReadyToPersist()); - quic_server_info->Persist(); - - // Once we call Persist, IsReadyToPersist should return false until Persist - // has completed. - EXPECT_FALSE(quic_server_info->IsReadyToPersist()); - - // Wait until Persist() does the work. - base::RunLoop().RunUntilIdle(); - - EXPECT_TRUE(quic_server_info->IsReadyToPersist()); - - // Verify that the state was updated. - quic_server_info.reset( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - quic_server_info->Start(); - rv = quic_server_info->WaitForDataReady(callback.callback()); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - EXPECT_TRUE(quic_server_info->IsDataReady()); - - const QuicServerInfo::State& state1 = quic_server_info->state(); - EXPECT_EQ(server_config_a, state1.server_config); - EXPECT_EQ(source_address_token_a, state1.source_address_token); - EXPECT_EQ(cert_sct_a, state1.cert_sct); - EXPECT_EQ(chlo_hash_a, state1.chlo_hash); - EXPECT_EQ(server_config_sig_a, state1.server_config_sig); - EXPECT_EQ(1U, state1.certs.size()); - EXPECT_EQ(cert_a, state1.certs[0]); - - RemoveMockTransaction(&kHostInfoTransaction1); -} - -// Test multiple calls to Persist. -TEST(DiskCacheBasedQuicServerInfo, MultiplePersist) { - MockHttpCache cache(true); - AddMockTransaction(&kHostInfoTransaction1); - TestCompletionCallback callback; - - QuicServerId server_id("www.google.com", 443, PRIVACY_MODE_DISABLED); - std::unique_ptr<QuicServerInfo> quic_server_info( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - EXPECT_FALSE(quic_server_info->IsDataReady()); - quic_server_info->Start(); - int rv = quic_server_info->WaitForDataReady(callback.callback()); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - EXPECT_TRUE(quic_server_info->IsDataReady()); - - // Persist data once. - QuicServerInfo::State* state = quic_server_info->mutable_state(); - EXPECT_TRUE(state->certs.empty()); - const string server_config_init = "server_config_init"; - const string source_address_token_init = "source_address_token_init"; - const string cert_sct_init = "cert_sct_init"; - const string chlo_hash_init = "chlo_hash_init"; - const string server_config_sig_init = "server_config_sig_init"; - const string cert_init = "cert_init"; - - state->server_config = server_config_init; - state->source_address_token = source_address_token_init; - state->cert_sct = cert_sct_init; - state->chlo_hash = chlo_hash_init; - state->server_config_sig = server_config_sig_init; - state->certs.push_back(cert_init); - EXPECT_TRUE(quic_server_info->IsReadyToPersist()); - quic_server_info->Persist(); - - // Once we call Persist, IsReadyToPersist should return false until Persist - // has completed. - EXPECT_FALSE(quic_server_info->IsReadyToPersist()); - - // Wait until Persist() does the work. - base::RunLoop().RunUntilIdle(); - - EXPECT_TRUE(quic_server_info->IsReadyToPersist()); - - // Persist one more time using the same |quic_server_info| object and without - // doing another Start() and WaitForDataReady. - const string server_config_a = "server_config_a"; - const string source_address_token_a = "source_address_token_a"; - const string cert_sct_a = "cert_sct_a"; - const string chlo_hash_a = "chlo_hash_a"; - const string server_config_sig_a = "server_config_sig_a"; - const string cert_a = "cert_a"; - - state->server_config = server_config_a; - state->source_address_token = source_address_token_a; - state->cert_sct = cert_sct_a; - state->chlo_hash = chlo_hash_a; - state->server_config_sig = server_config_sig_a; - state->certs.push_back(cert_a); - EXPECT_TRUE(quic_server_info->IsReadyToPersist()); - quic_server_info->Persist(); - - // Once we call Persist, IsReadyToPersist should return false until Persist - // has completed. - EXPECT_FALSE(quic_server_info->IsReadyToPersist()); - - // Wait until Persist() does the work. - base::RunLoop().RunUntilIdle(); - - EXPECT_TRUE(quic_server_info->IsReadyToPersist()); - - // Verify that the state was updated. - quic_server_info.reset( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - quic_server_info->Start(); - rv = quic_server_info->WaitForDataReady(callback.callback()); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - EXPECT_TRUE(quic_server_info->IsDataReady()); - - const QuicServerInfo::State& state1 = quic_server_info->state(); - EXPECT_EQ(server_config_a, state1.server_config); - EXPECT_EQ(source_address_token_a, state1.source_address_token); - EXPECT_EQ(cert_sct_a, state1.cert_sct); - EXPECT_EQ(chlo_hash_a, state1.chlo_hash); - EXPECT_EQ(server_config_sig_a, state1.server_config_sig); - EXPECT_EQ(1U, state1.certs.size()); - EXPECT_EQ(cert_a, state1.certs[0]); - - RemoveMockTransaction(&kHostInfoTransaction1); -} - -TEST(DiskCacheBasedQuicServerInfo, CancelWaitForDataReady) { - MockBlockingBackendFactory* factory = new MockBlockingBackendFactory(); - MockHttpCache cache(base::WrapUnique(factory), true); - TestCompletionCallback callback; - QuicServerId server_id("www.google.com", 443, PRIVACY_MODE_DISABLED); - std::unique_ptr<QuicServerInfo> quic_server_info( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - EXPECT_FALSE(quic_server_info->IsDataReady()); - quic_server_info->Start(); - int rv = quic_server_info->WaitForDataReady(callback.callback()); - EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); - // Now cancel the callback. - quic_server_info->CancelWaitForDataReadyCallback(); - EXPECT_FALSE(quic_server_info->IsDataReady()); - // Now complete the backend creation and let the callback run. - factory->FinishCreation(); - EXPECT_TRUE(quic_server_info->IsDataReady()); -} - -TEST(DiskCacheBasedQuicServerInfo, CancelWaitForDataReadyButDataIsReady) { - MockHttpCache cache(true); - AddMockTransaction(&kHostInfoTransaction1); - TestCompletionCallback callback; - - QuicServerId server_id("www.google.com", 443, PRIVACY_MODE_DISABLED); - std::unique_ptr<QuicServerInfo> quic_server_info( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - EXPECT_FALSE(quic_server_info->IsDataReady()); - quic_server_info->Start(); - int rv = quic_server_info->WaitForDataReady(callback.callback()); - quic_server_info->CancelWaitForDataReadyCallback(); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - EXPECT_TRUE(quic_server_info->IsDataReady()); - RemoveMockTransaction(&kHostInfoTransaction1); -} - -TEST(DiskCacheBasedQuicServerInfo, CancelWaitForDataReadyAfterDeleteCache) { - std::unique_ptr<QuicServerInfo> quic_server_info; - { - MockHttpCache cache(true); - AddMockTransaction(&kHostInfoTransaction1); - TestCompletionCallback callback; - - QuicServerId server_id("www.google.com", 443, PRIVACY_MODE_DISABLED); - quic_server_info.reset( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - EXPECT_FALSE(quic_server_info->IsDataReady()); - quic_server_info->Start(); - int rv = quic_server_info->WaitForDataReady(callback.callback()); - quic_server_info->CancelWaitForDataReadyCallback(); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - EXPECT_TRUE(quic_server_info->IsDataReady()); - RemoveMockTransaction(&kHostInfoTransaction1); - } - // Cancel the callback after Cache is deleted. - quic_server_info->ResetWaitForDataReadyCallback(); -} - -// Test Start() followed by Persist() without calling WaitForDataReady. -TEST(DiskCacheBasedQuicServerInfo, StartAndPersist) { - MockHttpCache cache(true); - AddMockTransaction(&kHostInfoTransaction1); - - QuicServerId server_id("www.google.com", 443, PRIVACY_MODE_DISABLED); - std::unique_ptr<QuicServerInfo> quic_server_info( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - EXPECT_FALSE(quic_server_info->IsDataReady()); - quic_server_info->Start(); - // Wait until Start() does the work. - base::RunLoop().RunUntilIdle(); - - EXPECT_TRUE(quic_server_info->IsDataReady()); - - QuicServerInfo::State* state = quic_server_info->mutable_state(); - EXPECT_TRUE(state->certs.empty()); - const string server_config_a = "server_config_a"; - const string source_address_token_a = "source_address_token_a"; - const string cert_sct_a = "cert_sct_a"; - const string chlo_hash_a = "chlo_hash_a"; - const string server_config_sig_a = "server_config_sig_a"; - const string cert_a = "cert_a"; - - state->server_config = server_config_a; - state->source_address_token = source_address_token_a; - state->cert_sct = cert_sct_a; - state->chlo_hash = chlo_hash_a; - state->server_config_sig = server_config_sig_a; - state->certs.push_back(cert_a); - EXPECT_TRUE(quic_server_info->IsReadyToPersist()); - quic_server_info->Persist(); - quic_server_info->OnExternalCacheHit(); - - // Once we call Persist, IsReadyToPersist should return false until Persist - // has completed. - EXPECT_FALSE(quic_server_info->IsReadyToPersist()); - - // Wait until Persist() does the work. - base::RunLoop().RunUntilIdle(); - - EXPECT_TRUE(quic_server_info->IsReadyToPersist()); - - // Verify that the state was updated. - quic_server_info.reset( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - quic_server_info->Start(); - TestCompletionCallback callback; - int rv = quic_server_info->WaitForDataReady(callback.callback()); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - EXPECT_TRUE(quic_server_info->IsDataReady()); - - const QuicServerInfo::State& state1 = quic_server_info->state(); - EXPECT_EQ(server_config_a, state1.server_config); - EXPECT_EQ(source_address_token_a, state1.source_address_token); - EXPECT_EQ(cert_sct_a, state1.cert_sct); - EXPECT_EQ(chlo_hash_a, state1.chlo_hash); - EXPECT_EQ(server_config_sig_a, state1.server_config_sig); - EXPECT_EQ(1U, state1.certs.size()); - EXPECT_EQ(cert_a, state1.certs[0]); - - RemoveMockTransaction(&kHostInfoTransaction1); -} - -// Test Persisting data when we are not ready to persist and then verify it -// persists the data when Start() finishes. -TEST(DiskCacheBasedQuicServerInfo, PersistWhenNotReadyToPersist) { - MockBlockingBackendFactory* factory = new MockBlockingBackendFactory(); - MockHttpCache cache(base::WrapUnique(factory), true); - AddMockTransaction(&kHostInfoTransaction1); - TestCompletionCallback callback; - - QuicServerId server_id("www.google.com", 443, PRIVACY_MODE_DISABLED); - std::unique_ptr<QuicServerInfo> quic_server_info( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - EXPECT_FALSE(quic_server_info->IsDataReady()); - // We do a Start(), but don't call WaitForDataReady(). Because we haven't - // created the backend, we will wait and data wouldn't be ready. - quic_server_info->Start(); - EXPECT_FALSE(quic_server_info->IsDataReady()); - - // Persist data once, even though the backend is not ready. - QuicServerInfo::State* state = quic_server_info->mutable_state(); - EXPECT_TRUE(state->certs.empty()); - const string server_config_init = "server_config_init"; - const string source_address_token_init = "source_address_token_init"; - const string cert_sct_init = "cert_sct_init"; - const string chlo_hash_init = "chlo_hash_init"; - const string server_config_sig_init = "server_config_sig_init"; - const string cert_init = "cert_init"; - - state->server_config = server_config_init; - state->source_address_token = source_address_token_init; - state->cert_sct = cert_sct_init; - state->chlo_hash = chlo_hash_init; - state->server_config_sig = server_config_sig_init; - state->certs.push_back(cert_init); - EXPECT_FALSE(quic_server_info->IsReadyToPersist()); - quic_server_info->Persist(); - EXPECT_FALSE(quic_server_info->IsReadyToPersist()); - - // Now complete the backend creation and let the callback run. - factory->FinishCreation(); - EXPECT_TRUE(quic_server_info->IsDataReady()); - - // Wait until Persist() does the work. - base::RunLoop().RunUntilIdle(); - - // Verify that the state was updated. - quic_server_info.reset( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - quic_server_info->Start(); - int rv = quic_server_info->WaitForDataReady(callback.callback()); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - EXPECT_TRUE(quic_server_info->IsDataReady()); - - const QuicServerInfo::State& state1 = quic_server_info->state(); - EXPECT_EQ(server_config_init, state1.server_config); - EXPECT_EQ(source_address_token_init, state1.source_address_token); - EXPECT_EQ(cert_sct_init, state1.cert_sct); - EXPECT_EQ(chlo_hash_init, state1.chlo_hash); - EXPECT_EQ(server_config_sig_init, state1.server_config_sig); - EXPECT_EQ(1U, state1.certs.size()); - EXPECT_EQ(cert_init, state1.certs[0]); - RemoveMockTransaction(&kHostInfoTransaction1); -} - -// Test multiple calls to Persist without waiting for the data to be written. -TEST(DiskCacheBasedQuicServerInfo, MultiplePersistsWithoutWaiting) { - MockHttpCache cache(true); - AddMockTransaction(&kHostInfoTransaction1); - TestCompletionCallback callback; - - QuicServerId server_id("www.google.com", 443, PRIVACY_MODE_DISABLED); - std::unique_ptr<QuicServerInfo> quic_server_info( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - EXPECT_FALSE(quic_server_info->IsDataReady()); - quic_server_info->Start(); - int rv = quic_server_info->WaitForDataReady(callback.callback()); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - EXPECT_TRUE(quic_server_info->IsDataReady()); - - // Persist data once. - QuicServerInfo::State* state = quic_server_info->mutable_state(); - EXPECT_TRUE(state->certs.empty()); - const string server_config_init = "server_config_init"; - const string source_address_token_init = "source_address_token_init"; - const string cert_sct_init = "cert_sct_init"; - const string chlo_hash_init = "chlo_hash_init"; - const string server_config_sig_init = "server_config_sig_init"; - const string cert_init = "cert_init"; - - state->server_config = server_config_init; - state->source_address_token = source_address_token_init; - state->cert_sct = cert_sct_init; - state->chlo_hash = chlo_hash_init; - state->server_config_sig = server_config_sig_init; - state->certs.push_back(cert_init); - EXPECT_TRUE(quic_server_info->IsReadyToPersist()); - quic_server_info->Persist(); - - // Once we call Persist, IsReadyToPersist should return false until Persist - // has completed. - EXPECT_FALSE(quic_server_info->IsReadyToPersist()); - - // Persist one more time using the same |quic_server_info| object and without - // doing another Start() and WaitForDataReady. - const string server_config_a = "server_config_a"; - const string source_address_token_a = "source_address_token_a"; - const string cert_sct_a = "cert_sct_a"; - const string chlo_hash_a = "chlo_hash_a"; - const string server_config_sig_a = "server_config_sig_a"; - const string cert_a = "cert_a"; - - state->server_config = server_config_a; - state->source_address_token = source_address_token_a; - state->cert_sct = cert_sct_a; - state->chlo_hash = chlo_hash_a; - state->server_config_sig = server_config_sig_a; - state->certs.push_back(cert_a); - EXPECT_FALSE(quic_server_info->IsReadyToPersist()); - quic_server_info->Persist(); - - // Wait until Persist() does the work. - base::RunLoop().RunUntilIdle(); - - EXPECT_TRUE(quic_server_info->IsReadyToPersist()); - - // Verify that the state was updated. - quic_server_info.reset( - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache())); - quic_server_info->Start(); - rv = quic_server_info->WaitForDataReady(callback.callback()); - EXPECT_THAT(callback.GetResult(rv), IsOk()); - EXPECT_TRUE(quic_server_info->IsDataReady()); - - // Verify the second time persisted data is persisted. - const QuicServerInfo::State& state1 = quic_server_info->state(); - EXPECT_EQ(server_config_a, state1.server_config); - EXPECT_EQ(source_address_token_a, state1.source_address_token); - EXPECT_EQ(cert_sct_a, state1.cert_sct); - EXPECT_EQ(chlo_hash_a, state1.chlo_hash); - EXPECT_EQ(server_config_sig_a, state1.server_config_sig); - EXPECT_EQ(1U, state1.certs.size()); - EXPECT_EQ(cert_a, state1.certs[0]); - - RemoveMockTransaction(&kHostInfoTransaction1); -} - -// crbug.com/439209: test deletion of QuicServerInfo object in the callback -// doesn't crash. -TEST(DiskCacheBasedQuicServerInfo, DeleteServerInfoInCallback) { - // Use the blocking mock backend factory to force asynchronous completion - // of quic_server_info->WaitForDataReady(), so that the callback will run. - MockBlockingBackendFactory* factory = new MockBlockingBackendFactory(); - MockHttpCache cache(base::WrapUnique(factory), true); - QuicServerId server_id("www.verisign.com", 443, PRIVACY_MODE_DISABLED); - QuicServerInfo* quic_server_info = - new DiskCacheBasedQuicServerInfo(server_id, cache.http_cache()); - // |cb| takes owndership and deletes |quic_server_info| when it is called. - DeleteCacheCompletionCallback cb(quic_server_info); - quic_server_info->Start(); - int rv = quic_server_info->WaitForDataReady(cb.callback()); - EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); - // Now complete the backend creation and let the callback run. - factory->FinishCreation(); - EXPECT_THAT(cb.GetResult(rv), IsOk()); -} - -} // namespace net
diff --git a/net/http/http_cache.cc b/net/http/http_cache.cc index 93d39cc..968cffa 100644 --- a/net/http/http_cache.cc +++ b/net/http/http_cache.cc
@@ -37,7 +37,6 @@ #include "net/base/net_errors.h" #include "net/base/upload_data_stream.h" #include "net/disk_cache/disk_cache.h" -#include "net/http/disk_cache_based_quic_server_info.h" #include "net/http/http_cache_lookup_manager.h" #include "net/http/http_cache_transaction.h" #include "net/http/http_network_layer.h" @@ -303,24 +302,6 @@ } //----------------------------------------------------------------------------- - -class HttpCache::QuicServerInfoFactoryAdaptor : public QuicServerInfoFactory { - public: - explicit QuicServerInfoFactoryAdaptor(HttpCache* http_cache) - : http_cache_(http_cache) { - } - - std::unique_ptr<QuicServerInfo> GetForServer( - const QuicServerId& server_id) override { - return base::MakeUnique<DiskCacheBasedQuicServerInfo>(server_id, - http_cache_); - } - - private: - HttpCache* const http_cache_; -}; - -//----------------------------------------------------------------------------- HttpCache::HttpCache(HttpNetworkSession* session, std::unique_ptr<BackendFactory> backend_factory, bool is_main_cache) @@ -353,12 +334,6 @@ session->SetServerPushDelegate( base::MakeUnique<HttpCacheLookupManager>(this)); - - if (!session->quic_stream_factory()->has_quic_server_info_factory()) { - // QuicStreamFactory takes ownership of QuicServerInfoFactoryAdaptor. - session->quic_stream_factory()->set_quic_server_info_factory( - new QuicServerInfoFactoryAdaptor(this)); - } } HttpCache::~HttpCache() {
diff --git a/net/http/http_network_session.cc b/net/http/http_network_session.cc index 9fdfc05..a654327 100644 --- a/net/http/http_network_session.cc +++ b/net/http/http_network_session.cc
@@ -123,10 +123,6 @@ enable_quic(false), mark_quic_broken_when_network_blackholes(false), retry_without_alt_svc_on_quic_errors(false), - quic_load_server_info_timeout_srtt_multiplier(0.25f), - quic_enable_connection_racing(false), - quic_enable_non_blocking_io(false), - quic_disable_disk_cache(false), quic_max_server_configs_stored_in_properties(0u), quic_clock(nullptr), quic_random(nullptr), @@ -190,11 +186,7 @@ params.quic_max_packet_length, params.quic_user_agent_id, params.quic_supported_versions, - params.quic_load_server_info_timeout_srtt_multiplier, - params.quic_enable_connection_racing, - params.quic_enable_non_blocking_io, - params.quic_disable_disk_cache, - params.quic_max_server_configs_stored_in_properties, + params.quic_max_server_configs_stored_in_properties > 0, params.quic_close_sessions_on_ip_change, params.mark_quic_broken_when_network_blackholes, params.quic_idle_connection_timeout_seconds, @@ -326,11 +318,6 @@ } dict->Set("origins_to_force_quic_on", std::move(origins_to_force_quic_on)); - dict->SetDouble("load_server_info_timeout_srtt_multiplier", - params_.quic_load_server_info_timeout_srtt_multiplier); - dict->SetBoolean("enable_connection_racing", - params_.quic_enable_connection_racing); - dict->SetBoolean("disable_disk_cache", params_.quic_disable_disk_cache); dict->SetInteger("max_server_configs_stored_in_properties", params_.quic_max_server_configs_stored_in_properties); dict->SetInteger("idle_connection_timeout_seconds",
diff --git a/net/http/http_network_session.h b/net/http/http_network_session.h index f9115f46..27725eec 100644 --- a/net/http/http_network_session.h +++ b/net/http/http_network_session.h
@@ -122,17 +122,6 @@ // Retry requests which fail with QUIC_PROTOCOL_ERROR, and mark QUIC // broken if the retry succeeds. bool retry_without_alt_svc_on_quic_errors; - // If not zero, the task to load QUIC server configs from the disk cache - // will timeout after this value multiplied by the smoothed RTT for the - // server. - float quic_load_server_info_timeout_srtt_multiplier; - // Causes QUIC to race reading the server config from disk with - // sending an inchoate CHLO. - bool quic_enable_connection_racing; - // Use non-blocking IO for UDP sockets. - bool quic_enable_non_blocking_io; - // Disables using the disk cache to store QUIC server configs. - bool quic_disable_disk_cache; // Maximum number of server configs that are to be stored in // HttpServerProperties, instead of the disk cache. size_t quic_max_server_configs_stored_in_properties;
diff --git a/net/log/net_log_event_type_list.h b/net/log/net_log_event_type_list.h index b3325d7..b7b9d5c 100644 --- a/net/log/net_log_event_type_list.h +++ b/net/log/net_log_event_type_list.h
@@ -586,6 +586,24 @@ // } EVENT_TYPE(SSL_NSS_ERROR) +// An SSL connection sent or received an alert. +// The following parameters are attached: +// { +// "hex_encoded_bytes": <The exact bytes sent, as a hexadecimal string> +// } +EVENT_TYPE(SSL_ALERT_RECEIVED) +EVENT_TYPE(SSL_ALERT_SENT) + +// An SSL connection sent or received a handshake message. +// The following parameters are attached: +// { +// "type": <The type of the handshake message, as an integer> +// "hex_encoded_bytes": <The exact bytes sent, as a hexadecimal string. May +// be elided in some cases> +// } +EVENT_TYPE(SSL_HANDSHAKE_MESSAGE_RECEIVED) +EVENT_TYPE(SSL_HANDSHAKE_MESSAGE_SENT) + // The specified number of bytes were sent on the socket. Depending on the // source of the event, may be logged either once the data is sent, or when it // is queued to be sent.
diff --git a/net/quic/chromium/properties_based_quic_server_info.cc b/net/quic/chromium/properties_based_quic_server_info.cc index e90331fd7..54d1b6da 100644 --- a/net/quic/chromium/properties_based_quic_server_info.cc +++ b/net/quic/chromium/properties_based_quic_server_info.cc
@@ -14,13 +14,6 @@ namespace { -void RecordQuicServerInfoStatus( - net::QuicServerInfo::QuicServerInfoAPICall call) { - UMA_HISTOGRAM_ENUMERATION( - "Net.QuicDiskCache.APICall.PropertiesBasedCache", call, - net::QuicServerInfo::QUIC_SERVER_INFO_NUM_OF_API_CALLS); -} - void RecordQuicServerInfoFailure(net::QuicServerInfo::FailureReason failure) { UMA_HISTOGRAM_ENUMERATION( "Net.QuicDiskCache.FailureReason.PropertiesBasedCache", failure, @@ -41,74 +34,33 @@ PropertiesBasedQuicServerInfo::~PropertiesBasedQuicServerInfo() {} -void PropertiesBasedQuicServerInfo::Start() { - RecordQuicServerInfoStatus(QUIC_SERVER_INFO_START); -} - -int PropertiesBasedQuicServerInfo::WaitForDataReady( - const CompletionCallback& callback) { - RecordQuicServerInfoStatus(QUIC_SERVER_INFO_WAIT_FOR_DATA_READY); +bool PropertiesBasedQuicServerInfo::Load() { const string* data = http_server_properties_->GetQuicServerInfo(server_id_); string decoded; if (!data) { RecordQuicServerInfoFailure(PARSE_NO_DATA_FAILURE); - return ERR_FAILED; + return false; } if (!base::Base64Decode(*data, &decoded)) { RecordQuicServerInfoFailure(PARSE_DATA_DECODE_FAILURE); - return ERR_FAILED; + return false; } - RecordQuicServerInfoStatus(QUIC_SERVER_INFO_PARSE); if (!Parse(decoded)) { RecordQuicServerInfoFailure(PARSE_FAILURE); - return ERR_FAILED; + return false; } - return OK; -} - -void PropertiesBasedQuicServerInfo::ResetWaitForDataReadyCallback() { - RecordQuicServerInfoStatus(QUIC_SERVER_INFO_RESET_WAIT_FOR_DATA_READY); -} - -void PropertiesBasedQuicServerInfo::CancelWaitForDataReadyCallback() { - RecordQuicServerInfoStatus(QUIC_SERVER_INFO_WAIT_FOR_DATA_READY_CANCEL); -} - -bool PropertiesBasedQuicServerInfo::IsDataReady() { return true; } -bool PropertiesBasedQuicServerInfo::IsReadyToPersist() { - RecordQuicServerInfoStatus(QUIC_SERVER_INFO_READY_TO_PERSIST); - return true; -} void PropertiesBasedQuicServerInfo::Persist() { - RecordQuicServerInfoStatus(QUIC_SERVER_INFO_PERSIST); string encoded; base::Base64Encode(Serialize(), &encoded); http_server_properties_->SetQuicServerInfo(server_id_, encoded); } -void PropertiesBasedQuicServerInfo::OnExternalCacheHit() { - RecordQuicServerInfoStatus(QUIC_SERVER_INFO_EXTERNAL_CACHE_HIT); -} - size_t PropertiesBasedQuicServerInfo::EstimateMemoryUsage() const { return 0; } -PropertiesBasedQuicServerInfoFactory::PropertiesBasedQuicServerInfoFactory( - HttpServerProperties* http_server_properties) - : http_server_properties_(http_server_properties) {} - -PropertiesBasedQuicServerInfoFactory::~PropertiesBasedQuicServerInfoFactory() {} - -std::unique_ptr<QuicServerInfo> -PropertiesBasedQuicServerInfoFactory::GetForServer( - const QuicServerId& server_id) { - return base::MakeUnique<PropertiesBasedQuicServerInfo>( - server_id, http_server_properties_); -} - } // namespace net
diff --git a/net/quic/chromium/properties_based_quic_server_info.h b/net/quic/chromium/properties_based_quic_server_info.h index 35ebb9b7..df85a9d8 100644 --- a/net/quic/chromium/properties_based_quic_server_info.h +++ b/net/quic/chromium/properties_based_quic_server_info.h
@@ -30,14 +30,8 @@ ~PropertiesBasedQuicServerInfo() override; // QuicServerInfo implementation. - void Start() override; - int WaitForDataReady(const CompletionCallback& callback) override; - void ResetWaitForDataReadyCallback() override; - void CancelWaitForDataReadyCallback() override; - bool IsDataReady() override; - bool IsReadyToPersist() override; + bool Load() override; void Persist() override; - void OnExternalCacheHit() override; size_t EstimateMemoryUsage() const override; private: @@ -46,22 +40,6 @@ DISALLOW_COPY_AND_ASSIGN(PropertiesBasedQuicServerInfo); }; -class QUIC_EXPORT_PRIVATE PropertiesBasedQuicServerInfoFactory - : public QuicServerInfoFactory { - public: - explicit PropertiesBasedQuicServerInfoFactory( - HttpServerProperties* http_server_properties); - ~PropertiesBasedQuicServerInfoFactory() override; - - std::unique_ptr<QuicServerInfo> GetForServer( - const QuicServerId& server_id) override; - - private: - HttpServerProperties* http_server_properties_; - - DISALLOW_COPY_AND_ASSIGN(PropertiesBasedQuicServerInfoFactory); -}; - } // namespace net #endif // NET_QUIC_CHROMIUM_PROPERTIES_BASED_QUIC_SERVER_INFO_H_
diff --git a/net/quic/chromium/properties_based_quic_server_info_test.cc b/net/quic/chromium/properties_based_quic_server_info_test.cc index aba7c635..c4cc0638 100644 --- a/net/quic/chromium/properties_based_quic_server_info_test.cc +++ b/net/quic/chromium/properties_based_quic_server_info_test.cc
@@ -34,8 +34,6 @@ // Initialize |server_info_| object and persist it. void InitializeAndPersist() { - server_info_.Start(); - EXPECT_TRUE(server_info_.IsDataReady()); QuicServerInfo::State* state = server_info_.mutable_state(); EXPECT_TRUE(state->certs.empty()); @@ -45,11 +43,7 @@ state->cert_sct = kCertSCTA; state->chlo_hash = kChloHashA; state->certs.push_back(kCertA); - EXPECT_TRUE(server_info_.IsReadyToPersist()); server_info_.Persist(); - EXPECT_TRUE(server_info_.IsReadyToPersist()); - EXPECT_TRUE(server_info_.IsDataReady()); - server_info_.OnExternalCacheHit(); } // Verify the data that is persisted in InitializeAndPersist(). @@ -75,10 +69,7 @@ // Read the persisted data and verify we have read the data correctly. PropertiesBasedQuicServerInfo server_info1(server_id_, &http_server_properties_); - server_info1.Start(); - EXPECT_THAT(server_info1.WaitForDataReady(callback_), - IsOk()); // Read the data. - EXPECT_TRUE(server_info1.IsDataReady()); + EXPECT_TRUE(server_info1.Load()); // Verify the data. const QuicServerInfo::State& state1 = server_info1.state(); @@ -88,16 +79,12 @@ // Update the data, by adding another cert. QuicServerInfo::State* state2 = server_info1.mutable_state(); state2->certs.push_back(kCertB); - EXPECT_TRUE(server_info_.IsReadyToPersist()); server_info1.Persist(); // Read the persisted data and verify we have read the data correctly. PropertiesBasedQuicServerInfo server_info2(server_id_, &http_server_properties_); - server_info2.Start(); - EXPECT_THAT(server_info2.WaitForDataReady(callback_), - IsOk()); // Read the data. - EXPECT_TRUE(server_info1.IsDataReady()); + EXPECT_TRUE(server_info2.Load()); // Verify updated data. const QuicServerInfo::State& state3 = server_info2.state();
diff --git a/net/quic/chromium/quic_chromium_client_session.cc b/net/quic/chromium/quic_chromium_client_session.cc index 27818a5c..6913eb5 100644 --- a/net/quic/chromium/quic_chromium_client_session.cc +++ b/net/quic/chromium/quic_chromium_client_session.cc
@@ -375,24 +375,8 @@ round_trip_handshakes, 1, 3, 4); } } + const QuicConnectionStats stats = connection()->GetStats(); - if (server_info_ && stats.min_rtt_us > 0) { - base::TimeTicks wait_for_data_start_time = - server_info_->wait_for_data_start_time(); - base::TimeTicks wait_for_data_end_time = - server_info_->wait_for_data_end_time(); - if (!wait_for_data_start_time.is_null() && - !wait_for_data_end_time.is_null()) { - base::TimeDelta wait_time = - wait_for_data_end_time - wait_for_data_start_time; - const base::HistogramBase::Sample kMaxWaitToRtt = 1000; - base::HistogramBase::Sample wait_to_rtt = - static_cast<base::HistogramBase::Sample>( - 100 * wait_time.InMicroseconds() / stats.min_rtt_us); - UMA_HISTOGRAM_CUSTOM_COUNTS("Net.QuicServerInfo.WaitForDataReadyToRtt", - wait_to_rtt, 1, kMaxWaitToRtt, 50); - } - } // The MTU used by QUIC is limited to a fairly small set of predefined values // (initial values and MTU discovery values), but does not fare well when @@ -862,21 +846,6 @@ UMA_HISTOGRAM_TIMES( "Net.QuicSession.HandshakeConfirmedTime", connect_timing_.connect_end - connect_timing_.connect_start); - - if (server_info_) { - // TODO(rtenneti): Should we delete this histogram? - // Track how long it has taken to finish handshake once we start waiting - // for reading of QUIC server information from disk cache. We could use - // this data to compare total time taken if we were to cancel the disk - // cache read vs waiting for the read to complete. - base::TimeTicks wait_for_data_start_time = - server_info_->wait_for_data_start_time(); - if (!wait_for_data_start_time.is_null()) { - UMA_HISTOGRAM_TIMES( - "Net.QuicServerInfo.WaitForDataReady.HandshakeConfirmedTime", - base::TimeTicks::Now() - wait_for_data_start_time); - } - } // Track how long it has taken to finish handshake after we have finished // DNS host resolution. if (!connect_timing_.dns_end.is_null()) { @@ -891,8 +860,6 @@ ++it; observer->OnCryptoHandshakeConfirmed(); } - if (server_info_) - server_info_->OnExternalCacheHit(); } QuicSpdySession::OnCryptoHandshakeEvent(event); }
diff --git a/net/quic/chromium/quic_server_info.cc b/net/quic/chromium/quic_server_info.cc index 23f4cf8a..3e53fa5 100644 --- a/net/quic/chromium/quic_server_info.cc +++ b/net/quic/chromium/quic_server_info.cc
@@ -146,6 +146,4 @@ return string(reinterpret_cast<const char*>(p.data()), p.size()); } -QuicServerInfoFactory::~QuicServerInfoFactory() {} - } // namespace net
diff --git a/net/quic/chromium/quic_server_info.h b/net/quic/chromium/quic_server_info.h index eab5366..a818576 100644 --- a/net/quic/chromium/quic_server_info.h +++ b/net/quic/chromium/quic_server_info.h
@@ -24,20 +24,6 @@ // crypto config. class QUIC_EXPORT_PRIVATE QuicServerInfo { public: - // Enum to track number of times data read/parse/write API calls of - // QuicServerInfo to and from disk cache is called. - enum QuicServerInfoAPICall { - QUIC_SERVER_INFO_START = 0, - QUIC_SERVER_INFO_WAIT_FOR_DATA_READY = 1, - QUIC_SERVER_INFO_PARSE = 2, - QUIC_SERVER_INFO_WAIT_FOR_DATA_READY_CANCEL = 3, - QUIC_SERVER_INFO_READY_TO_PERSIST = 4, - QUIC_SERVER_INFO_PERSIST = 5, - QUIC_SERVER_INFO_EXTERNAL_CACHE_HIT = 6, - QUIC_SERVER_INFO_RESET_WAIT_FOR_DATA_READY = 7, - QUIC_SERVER_INFO_NUM_OF_API_CALLS = 8, - }; - // Enum to track failure reasons to read/load/write of QuicServerInfo to // and from disk cache. enum FailureReason { @@ -59,49 +45,13 @@ explicit QuicServerInfo(const QuicServerId& server_id); virtual ~QuicServerInfo(); - // Start will commence the lookup. This must be called before any other - // methods. By opportunistically calling this early, it may be possible to - // overlap this object's lookup and reduce latency. - virtual void Start() = 0; + // Fetches the server config from the backing store, and returns true + // if the server config was found. + virtual bool Load() = 0; - // WaitForDataReady returns OK if the fetch of the requested data has - // completed. Otherwise it returns ERR_IO_PENDING and will call |callback| on - // the current thread when ready. - // - // Only a single callback can be outstanding at a given time and, in the - // event that WaitForDataReady returns OK, it's the caller's responsibility - // to delete |callback|. - // - // |callback| may be NULL, in which case ERR_IO_PENDING may still be returned - // but, obviously, a callback will never be made. - virtual int WaitForDataReady(const CompletionCallback& callback) = 0; - - // Reset's WaitForDataReady callback. This method shouldn't have any side - // effects (could be called even if HttpCache doesn't exist). - virtual void ResetWaitForDataReadyCallback() = 0; - - // Cancel's WaitForDataReady callback. |callback| passed in WaitForDataReady - // will not be called. - virtual void CancelWaitForDataReadyCallback() = 0; - - // Returns true if data is loaded from disk cache and ready (WaitForDataReady - // doesn't have a pending callback). - virtual bool IsDataReady() = 0; - - // Returns true if the object is ready to persist data, in other words, if - // data is loaded from disk cache and ready and there are no pending writes. - virtual bool IsReadyToPersist() = 0; - - // Persist allows for the server information to be updated for future users. - // This is a fire and forget operation: the caller may drop its reference - // from this object and the store operation will still complete. This can - // only be called once WaitForDataReady has returned OK or called its - // callback. + // Persist allows for the server information to be updated for future uses. virtual void Persist() = 0; - // Called whenever an external cache reuses quic server config. - virtual void OnExternalCacheHit() = 0; - // Returns the size of dynamically allocated memory in bytes. virtual size_t EstimateMemoryUsage() const = 0; @@ -129,14 +79,6 @@ const State& state() const; State* mutable_state(); - base::TimeTicks wait_for_data_start_time() const { - return wait_for_data_start_time_; - } - - base::TimeTicks wait_for_data_end_time() const { - return wait_for_data_end_time_; - } - protected: // Parse parses pickled data and fills out the public member fields of this // object. It returns true iff the parse was successful. The public member @@ -146,10 +88,6 @@ State state_; - // Time when WaitForDataReady was called and when it has finished. - base::TimeTicks wait_for_data_start_time_; - base::TimeTicks wait_for_data_end_time_; - // This is the QUIC server (hostname, port, is_https, privacy_mode) tuple for // which we restore the crypto_config. const QuicServerId server_id_; @@ -164,20 +102,6 @@ DISALLOW_COPY_AND_ASSIGN(QuicServerInfo); }; -class QUIC_EXPORT_PRIVATE QuicServerInfoFactory { - public: - QuicServerInfoFactory() {} - virtual ~QuicServerInfoFactory(); - - // GetForServer returns a fresh, allocated QuicServerInfo for the given - // |server_id| or NULL on failure. - virtual std::unique_ptr<QuicServerInfo> GetForServer( - const QuicServerId& server_id) = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(QuicServerInfoFactory); -}; - } // namespace net #endif // NET_QUIC_CHROMIUM_QUIC_SERVER_INFO_H_
diff --git a/net/quic/chromium/quic_stream_factory.cc b/net/quic/chromium/quic_stream_factory.cc index ff9a91a..5616476 100644 --- a/net/quic/chromium/quic_stream_factory.cc +++ b/net/quic/chromium/quic_stream_factory.cc
@@ -331,16 +331,8 @@ const QuicSessionKey& key, bool was_alternative_service_recently_broken, int cert_verify_flags, - std::unique_ptr<QuicServerInfo> server_info, const NetLogWithSource& net_log); - // Creates a new job to handle the resumption of for connecting an - // existing session. - Job(QuicStreamFactory* factory, - HostResolver* host_resolver, - QuicChromiumClientSession* session, - const QuicSessionKey& key); - ~Job(); int Run(const CompletionCallback& callback); @@ -348,19 +340,13 @@ int DoLoop(int rv); int DoResolveHost(); int DoResolveHostComplete(int rv); - int DoLoadServerInfo(); - int DoLoadServerInfoComplete(int rv); int DoConnect(); int DoConnectComplete(int rv); void OnIOComplete(int rv); - void RunAuxilaryJob(); - void Cancel(); - void CancelWaitForDataReadyCallback(); - const QuicSessionKey& key() const { return key_; } const NetLogWithSource& net_log() const { return net_log_; } @@ -375,8 +361,6 @@ STATE_NONE, STATE_RESOLVE_HOST, STATE_RESOLVE_HOST_COMPLETE, - STATE_LOAD_SERVER_INFO, - STATE_LOAD_SERVER_INFO_COMPLETE, STATE_CONNECT, STATE_CONNECT_COMPLETE, }; @@ -388,8 +372,6 @@ const QuicSessionKey key_; const int cert_verify_flags_; const bool was_alternative_service_recently_broken_; - std::unique_ptr<QuicServerInfo> server_info_; - bool started_another_job_; const NetLogWithSource net_log_; int num_sent_client_hellos_; QuicChromiumClientSession* session_; @@ -406,7 +388,6 @@ const QuicSessionKey& key, bool was_alternative_service_recently_broken, int cert_verify_flags, - std::unique_ptr<QuicServerInfo> server_info, const NetLogWithSource& net_log) : io_state_(STATE_RESOLVE_HOST), factory_(factory), @@ -415,8 +396,6 @@ cert_verify_flags_(cert_verify_flags), was_alternative_service_recently_broken_( was_alternative_service_recently_broken), - server_info_(std::move(server_info)), - started_another_job_(false), net_log_( NetLogWithSource::Make(net_log.net_log(), NetLogSourceType::QUIC_STREAM_FACTORY_JOB)), @@ -438,10 +417,6 @@ QuicStreamFactory::Job::~Job() { net_log_.EndEvent(NetLogEventType::QUIC_STREAM_FACTORY_JOB); DCHECK(callback_.is_null()); - - // If disk cache has a pending WaitForDataReadyCallback, cancel that callback. - if (server_info_) - server_info_->ResetWaitForDataReadyCallback(); } int QuicStreamFactory::Job::Run(const CompletionCallback& callback) { @@ -465,13 +440,6 @@ case STATE_RESOLVE_HOST_COMPLETE: rv = DoResolveHostComplete(rv); break; - case STATE_LOAD_SERVER_INFO: - CHECK_EQ(OK, rv); - rv = DoLoadServerInfo(); - break; - case STATE_LOAD_SERVER_INFO_COMPLETE: - rv = DoLoadServerInfoComplete(rv); - break; case STATE_CONNECT: CHECK_EQ(OK, rv); rv = DoConnect(); @@ -493,13 +461,6 @@ base::ResetAndReturn(&callback_).Run(rv); } -void QuicStreamFactory::Job::RunAuxilaryJob() { - int rv = Run(base::Bind(&QuicStreamFactory::OnJobComplete, - base::Unretained(factory_), this)); - if (rv != ERR_IO_PENDING) - factory_->OnJobComplete(this, rv); -} - void QuicStreamFactory::Job::Cancel() { callback_.Reset(); if (session_) @@ -508,24 +469,12 @@ ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); } -void QuicStreamFactory::Job::CancelWaitForDataReadyCallback() { - // If we are waiting for WaitForDataReadyCallback, then cancel the callback. - if (io_state_ != STATE_LOAD_SERVER_INFO_COMPLETE) - return; - server_info_->CancelWaitForDataReadyCallback(); - OnIOComplete(OK); -} - size_t QuicStreamFactory::Job::EstimateMemoryUsage() const { - return base::trace_event::EstimateMemoryUsage(key_) + - base::trace_event::EstimateMemoryUsage(server_info_); + return base::trace_event::EstimateMemoryUsage(key_); } int QuicStreamFactory::Job::DoResolveHost() { dns_resolution_start_time_ = base::TimeTicks::Now(); - // Start loading the data now, and wait for it after we resolve the host. - if (server_info_) - server_info_->Start(); io_state_ = STATE_RESOLVE_HOST_COMPLETE; return host_resolver_->Resolve( @@ -547,71 +496,6 @@ if (factory_->OnResolution(key_, address_list_)) return OK; - if (server_info_) - io_state_ = STATE_LOAD_SERVER_INFO; - else - io_state_ = STATE_CONNECT; - return OK; -} - -int QuicStreamFactory::Job::DoLoadServerInfo() { - net_log_.BeginEvent( - NetLogEventType::QUIC_STREAM_FACTORY_JOB_LOAD_SERVER_INFO); - - io_state_ = STATE_LOAD_SERVER_INFO_COMPLETE; - - DCHECK(server_info_); - - // To mitigate the effects of disk cache taking too long to load QUIC server - // information, set up a timer to cancel WaitForDataReady's callback. - if (factory_->load_server_info_timeout_srtt_multiplier_ > 0) { - const int kMaxLoadServerInfoTimeoutMs = 50; - // Wait for DiskCache a maximum of 50ms. - int64_t load_server_info_timeout_ms = - std::min(static_cast<int>( - (factory_->load_server_info_timeout_srtt_multiplier_ * - factory_->GetServerNetworkStatsSmoothedRttInMicroseconds( - key_.server_id())) / - 1000), - kMaxLoadServerInfoTimeoutMs); - if (load_server_info_timeout_ms > 0) { - factory_->task_runner_->PostDelayedTask( - FROM_HERE, - base::Bind(&QuicStreamFactory::Job::CancelWaitForDataReadyCallback, - GetWeakPtr()), - base::TimeDelta::FromMilliseconds(load_server_info_timeout_ms)); - } - } - - int rv = server_info_->WaitForDataReady( - base::Bind(&QuicStreamFactory::Job::OnIOComplete, GetWeakPtr())); - if (rv == ERR_IO_PENDING && factory_->enable_connection_racing()) { - // If we are waiting to load server config from the disk cache, then start - // another job. - started_another_job_ = true; - factory_->CreateAuxilaryJob(key_, cert_verify_flags_, net_log_); - } - return rv; -} - -int QuicStreamFactory::Job::DoLoadServerInfoComplete(int rv) { - net_log_.EndEvent(NetLogEventType::QUIC_STREAM_FACTORY_JOB_LOAD_SERVER_INFO); - UMA_HISTOGRAM_TIMES("Net.QuicServerInfo.DiskCacheWaitForDataReadyTime", - base::TimeTicks::Now() - dns_resolution_end_time_); - - if (rv != OK) - server_info_.reset(); - - if (started_another_job_ && - (!server_info_ || server_info_->state().server_config.empty() || - !factory_->CryptoConfigCacheIsEmpty(key_.server_id()))) { - // If we have started another job and if we didn't load the server config - // from the disk cache or if we have received a new server config from the - // server, then cancel the current job. - io_state_ = STATE_NONE; - return ERR_CONNECTION_CLOSED; - } - io_state_ = STATE_CONNECT; return OK; } @@ -625,10 +509,10 @@ NetLogEventType::QUIC_STREAM_FACTORY_JOB_CONNECT, NetLog::BoolCallback("require_confirmation", require_confirmation)); - int rv = factory_->CreateSession( - key_, cert_verify_flags_, std::move(server_info_), require_confirmation, - address_list_, dns_resolution_start_time_, dns_resolution_end_time_, - net_log_, &session_); + int rv = + factory_->CreateSession(key_, cert_verify_flags_, require_confirmation, + address_list_, dns_resolution_start_time_, + dns_resolution_end_time_, net_log_, &session_); if (rv != OK) { DCHECK(rv != ERR_IO_PENDING); DCHECK(!session_); @@ -771,11 +655,7 @@ size_t max_packet_length, const std::string& user_agent_id, const QuicVersionVector& supported_versions, - float load_server_info_timeout_srtt_multiplier, - bool enable_connection_racing, - bool enable_non_blocking_io, - bool disable_disk_cache, - int max_server_configs_stored_in_properties, + bool store_server_configs_in_properties, bool close_sessions_on_ip_change, bool mark_quic_broken_when_network_blackholes, int idle_connection_timeout_seconds, @@ -813,13 +693,9 @@ transport_security_state, cert_transparency_verifier))), supported_versions_(supported_versions), - load_server_info_timeout_srtt_multiplier_( - load_server_info_timeout_srtt_multiplier), - enable_connection_racing_(enable_connection_racing), - enable_non_blocking_io_(enable_non_blocking_io), - disable_disk_cache_(disable_disk_cache), mark_quic_broken_when_network_blackholes_( mark_quic_broken_when_network_blackholes), + store_server_configs_in_properties_(store_server_configs_in_properties), ping_timeout_(QuicTime::Delta::FromSeconds(kPingTimeoutSecs)), reduced_ping_timeout_( QuicTime::Delta::FromSeconds(reduced_ping_timeout_seconds)), @@ -838,7 +714,6 @@ do_not_fragment_(do_not_fragment), estimate_initial_rtt(estimate_initial_rtt), check_persisted_supports_quic_(true), - has_initialized_data_(false), num_push_streams_created_(0), task_runner_(nullptr), ssl_config_service_(ssl_config_service), @@ -866,13 +741,6 @@ has_aes_hardware_support); if (has_aes_hardware_support) crypto_config_.PreferAesGcm(); - // When disk cache is used to store the server configs, HttpCache code calls - // |set_quic_server_info_factory| if |quic_server_info_factory_| wasn't - // created. - if (max_server_configs_stored_in_properties > 0) { - quic_server_info_factory_.reset( - new PropertiesBasedQuicServerInfoFactory(http_server_properties_)); - } // migrate_sessions_early should only be set to true if // migrate_sessions_on_network_change is set to true. @@ -930,11 +798,6 @@ return base::TimeDelta::FromMicroseconds(srtt); } -void QuicStreamFactory::set_quic_server_info_factory( - QuicServerInfoFactory* quic_server_info_factory) { - quic_server_info_factory_.reset(quic_server_info_factory); -} - void QuicStreamFactory::DumpMemoryStats( base::trace_event::ProcessMemoryDump* pmd, const std::string& parent_absolute_name) const { @@ -1069,25 +932,12 @@ if (!task_runner_) task_runner_ = base::ThreadTaskRunnerHandle::Get().get(); - std::unique_ptr<QuicServerInfo> quic_server_info; - if (quic_server_info_factory_.get()) { - bool load_from_disk_cache = !disable_disk_cache_; - MaybeInitialize(); - if (!base::ContainsKey(quic_supported_servers_at_startup_, destination)) { - // If there is no entry for QUIC, consider that as a new server and - // don't wait for Cache thread to load the data for that server. - load_from_disk_cache = false; - } - if (load_from_disk_cache && CryptoConfigCacheIsEmpty(server_id)) - quic_server_info = quic_server_info_factory_->GetForServer(server_id); - } - ignore_result(StartCertVerifyJob(server_id, cert_verify_flags, net_log)); QuicSessionKey key(destination, server_id); std::unique_ptr<Job> job = base::MakeUnique<Job>( this, host_resolver_, key, WasQuicRecentlyBroken(server_id), - cert_verify_flags, std::move(quic_server_info), net_log); + cert_verify_flags, net_log); int rv = job->Run(base::Bind(&QuicStreamFactory::OnJobComplete, base::Unretained(this), job.get())); if (rv == ERR_IO_PENDING) { @@ -1133,18 +983,6 @@ EstimateServerIdMemoryUsage(server_id_); } -void QuicStreamFactory::CreateAuxilaryJob(const QuicSessionKey& key, - int cert_verify_flags, - const NetLogWithSource& net_log) { - Job* aux_job = - new Job(this, host_resolver_, key, WasQuicRecentlyBroken(key.server_id()), - cert_verify_flags, nullptr, net_log); - active_jobs_[key.server_id()][aux_job] = base::WrapUnique(aux_job); - task_runner_->PostTask(FROM_HERE, - base::Bind(&QuicStreamFactory::Job::RunAuxilaryJob, - aux_job->GetWeakPtr())); -} - bool QuicStreamFactory::OnResolution(const QuicSessionKey& key, const AddressList& address_list) { const QuicServerId& server_id(key.server_id()); @@ -1584,8 +1422,7 @@ int QuicStreamFactory::ConfigureSocket(DatagramClientSocket* socket, IPEndPoint addr, NetworkHandle network) { - if (enable_non_blocking_io_) - socket->UseNonBlockingIO(); + socket->UseNonBlockingIO(); int rv; if (migrate_sessions_on_network_change_) { @@ -1643,7 +1480,6 @@ int QuicStreamFactory::CreateSession( const QuicSessionKey& key, int cert_verify_flags, - std::unique_ptr<QuicServerInfo> server_info, bool require_confirmation, const AddressList& address_list, base::TimeTicks dns_resolution_start_time, @@ -1672,7 +1508,13 @@ alarm_factory_.reset(new QuicChromiumAlarmFactory( base::ThreadTaskRunnerHandle::Get().get(), clock_)); } + QuicConnectionId connection_id = random_generator_->RandUint64(); + std::unique_ptr<QuicServerInfo> server_info; + if (store_server_configs_in_properties_) { + server_info = base::MakeUnique<PropertiesBasedQuicServerInfo>( + server_id, http_server_properties_); + } InitializeCachedStateInCryptoConfig(server_id, server_info, &connection_id); QuicChromiumPacketWriter* writer = new QuicChromiumPacketWriter(socket.get()); @@ -1694,14 +1536,6 @@ if (force_hol_blocking_) config.SetForceHolBlocking(); - if (quic_server_info_factory_.get() && !server_info) { - // Start the disk cache loading so that we can persist the newer QUIC server - // information and/or inform the disk cache that we have reused - // |server_info|. - server_info = quic_server_info_factory_->GetForServer(server_id); - server_info->Start(); - } - // Use the factory to create a new socket performance watcher, and pass the // ownership to QuicChromiumClientSession. std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher; @@ -1844,20 +1678,9 @@ if (!cached->IsEmpty()) return; - // |server_info| will be NULL, if a non-empty server config already exists in - // the memory cache. - if (!server_info) + if (!server_info || !server_info->Load()) return; - // TODO(rtenneti): Delete the following histogram after collecting stats. - // If the AlternativeServiceMap contained an entry for this host, check if - // the disk cache contained an entry for it. - if (base::ContainsKey(quic_supported_servers_at_startup_, - server_id.host_port_pair())) { - UMA_HISTOGRAM_BOOLEAN("Net.QuicServerInfo.ExpectConfigMissingFromDiskCache", - server_info->state().server_config.empty()); - } - cached->Initialize(server_info->state().server_config, server_info->state().source_address_token, server_info->state().certs, server_info->state().cert_sct, @@ -1866,60 +1689,6 @@ QuicWallTime::Zero()); } -void QuicStreamFactory::MaybeInitialize() { - // We don't initialize data from HttpServerProperties in the constructor - // because HttpServerProperties has not yet initialized. We're guaranteed - // HttpServerProperties has been initialized by the first time a request is - // made. - if (has_initialized_data_) - return; - - has_initialized_data_ = true; - - // Query the proxy delegate for the default alternative proxy server. - ProxyServer default_alternative_proxy_server = - proxy_delegate_ ? proxy_delegate_->GetDefaultAlternativeProxy() - : ProxyServer(); - if (default_alternative_proxy_server.is_quic()) { - quic_supported_servers_at_startup_.insert( - default_alternative_proxy_server.host_port_pair()); - } - - for (const std::pair<const url::SchemeHostPort, AlternativeServiceInfoVector>& - key_value : http_server_properties_->alternative_service_map()) { - HostPortPair host_port_pair(key_value.first.host(), key_value.first.port()); - for (const AlternativeServiceInfo& alternative_service_info : - key_value.second) { - if (alternative_service_info.alternative_service.protocol == kProtoQUIC) { - quic_supported_servers_at_startup_.insert(host_port_pair); - break; - } - } - } - - if (http_server_properties_->max_server_configs_stored_in_properties() == 0) - return; - // Create a temporary QuicServerInfo object to deserialize and to populate the - // in-memory crypto server config cache in the MRU order. - std::unique_ptr<QuicServerInfo> server_info; - CompletionCallback callback; - // Get the list of servers to be deserialized first because WaitForDataReady - // touches quic_server_info_map. - const QuicServerInfoMap& quic_server_info_map = - http_server_properties_->quic_server_info_map(); - std::vector<QuicServerId> server_list; - for (const auto& key_value : quic_server_info_map) - server_list.push_back(key_value.first); - for (auto it = server_list.rbegin(); it != server_list.rend(); ++it) { - const QuicServerId& server_id = *it; - server_info = quic_server_info_factory_->GetForServer(server_id); - if (server_info->WaitForDataReady(callback) == OK) { - DVLOG(1) << "Initialized server config for: " << server_id.ToString(); - InitializeCachedStateInCryptoConfig(server_id, server_info, nullptr); - } - } -} - void QuicStreamFactory::ProcessGoingAwaySession( QuicChromiumClientSession* session, const QuicServerId& server_id,
diff --git a/net/quic/chromium/quic_stream_factory.h b/net/quic/chromium/quic_stream_factory.h index f0addeac..f1533d7e 100644 --- a/net/quic/chromium/quic_stream_factory.h +++ b/net/quic/chromium/quic_stream_factory.h
@@ -66,7 +66,6 @@ class QuicCryptoClientStreamFactory; class QuicRandom; class QuicServerInfo; -class QuicServerInfoFactory; class QuicStreamFactory; class SocketPerformanceWatcherFactory; class TransportSecurityState; @@ -208,11 +207,7 @@ size_t max_packet_length, const std::string& user_agent_id, const QuicVersionVector& supported_versions, - float load_server_info_timeout_srtt_multiplier, - bool enable_connection_racing, - bool enable_non_blocking_io, - bool disable_disk_cache, - int max_server_configs_stored_in_properties, + bool store_server_configs_in_properties, bool close_sessions_on_ip_change, bool mark_quic_broken_when_network_blackholes, int idle_connection_timeout_seconds, @@ -368,26 +363,10 @@ QuicAlarmFactory* alarm_factory() { return alarm_factory_.get(); } - bool has_quic_server_info_factory() const { - return quic_server_info_factory_.get() != nullptr; - } - - QuicServerInfoFactory* quic_server_info_factory() const { - return quic_server_info_factory_.get(); - } - - void set_quic_server_info_factory( - QuicServerInfoFactory* quic_server_info_factory); - void set_server_push_delegate(ServerPushDelegate* push_delegate) { push_delegate_ = push_delegate; } - bool enable_connection_racing() const { return enable_connection_racing_; } - void set_enable_connection_racing(bool enable_connection_racing) { - enable_connection_racing_ = enable_connection_racing; - } - bool migrate_sessions_on_network_change() const { return migrate_sessions_on_network_change_; } @@ -420,12 +399,6 @@ typedef std::map<QuicServerId, std::unique_ptr<CertVerifierJob>> CertVerifierJobMap; - // Creates a job which doesn't wait for server config to be loaded from the - // disk cache. This job is started via a PostTask. - void CreateAuxilaryJob(const QuicSessionKey& key, - int cert_verify_flags, - const NetLogWithSource& net_log); - // Returns a newly created QuicHttpStream owned by the caller. std::unique_ptr<QuicHttpStream> CreateFromSession( QuicChromiumClientSession* session); @@ -438,7 +411,6 @@ bool HasActiveCertVerifierJob(const QuicServerId& server_id) const; int CreateSession(const QuicSessionKey& key, int cert_verify_flags, - std::unique_ptr<QuicServerInfo> quic_server_info, bool require_confirmation, const AddressList& address_list, base::TimeTicks dns_resolution_start_time, @@ -484,11 +456,6 @@ const std::unique_ptr<QuicServerInfo>& server_info, QuicConnectionId* connection_id); - // Initialize |quic_supported_servers_at_startup_| with the list of servers - // that supported QUIC at start up and also initialize in-memory cache of - // QuicServerInfo objects from HttpServerProperties. - void MaybeInitialize(); - void ProcessGoingAwaySession(QuicChromiumClientSession* session, const QuicServerId& server_id, bool was_session_active); @@ -513,7 +480,6 @@ ProxyDelegate* proxy_delegate_; TransportSecurityState* transport_security_state_; CTVerifier* cert_transparency_verifier_; - std::unique_ptr<QuicServerInfoFactory> quic_server_info_factory_; QuicCryptoClientStreamFactory* quic_crypto_client_stream_factory_; QuicRandom* random_generator_; // Unowned. QuicClock* clock_; // Unowned. @@ -558,27 +524,13 @@ const QuicVersionVector supported_versions_; - // Specifies the ratio between time to load QUIC server information from disk - // cache to 'smoothed RTT'. This ratio is used to calculate the timeout in - // milliseconds to wait for loading of QUIC server information. If we don't - // want to timeout, set |load_server_info_timeout_srtt_multiplier_| to 0. - float load_server_info_timeout_srtt_multiplier_; - - // Set if we want to race connections - one connection that sends - // INCHOATE_HELLO and another connection that sends CHLO after loading server - // config from the disk cache. - bool enable_connection_racing_; - - // Set if experimental non-blocking IO should be used on windows sockets. - bool enable_non_blocking_io_; - - // Set if we do not want to load server config from the disk cache. - bool disable_disk_cache_; - // True if QUIC should be marked as broken when a connection blackholes after // the handshake is confirmed. bool mark_quic_broken_when_network_blackholes_; + // Set if QUIC server configs should be stored in HttpServerProperties. + bool store_server_configs_in_properties_; + // PING timeout for connections. QuicTime::Delta ping_timeout_; QuicTime::Delta reduced_ping_timeout_; @@ -619,8 +571,6 @@ // Local address of socket that was created in CreateSession. IPEndPoint local_address_; bool check_persisted_supports_quic_; - bool has_initialized_data_; - std::set<HostPortPair> quic_supported_servers_at_startup_; NetworkConnection network_connection_;
diff --git a/net/quic/chromium/quic_stream_factory_peer.cc b/net/quic/chromium/quic_stream_factory_peer.cc index ff050436..d5f4b5c 100644 --- a/net/quic/chromium/quic_stream_factory_peer.cc +++ b/net/quic/chromium/quic_stream_factory_peer.cc
@@ -119,20 +119,6 @@ return it->second.size(); } -void QuicStreamFactoryPeer::MaybeInitialize(QuicStreamFactory* factory) { - factory->MaybeInitialize(); -} - -bool QuicStreamFactoryPeer::HasInitializedData(QuicStreamFactory* factory) { - return factory->has_initialized_data_; -} - -bool QuicStreamFactoryPeer::SupportsQuicAtStartUp(QuicStreamFactory* factory, - HostPortPair host_port_pair) { - return base::ContainsKey(factory->quic_supported_servers_at_startup_, - host_port_pair); -} - bool QuicStreamFactoryPeer::CryptoConfigCacheIsEmpty( QuicStreamFactory* factory, const QuicServerId& quic_server_id) {
diff --git a/net/quic/chromium/quic_stream_factory_peer.h b/net/quic/chromium/quic_stream_factory_peer.h index d9b8d1d..c2d3be9e 100644 --- a/net/quic/chromium/quic_stream_factory_peer.h +++ b/net/quic/chromium/quic_stream_factory_peer.h
@@ -79,13 +79,6 @@ static size_t GetNumberOfActiveJobs(QuicStreamFactory* factory, const QuicServerId& server_id); - static void MaybeInitialize(QuicStreamFactory* factory); - - static bool HasInitializedData(QuicStreamFactory* factory); - - static bool SupportsQuicAtStartUp(QuicStreamFactory* factory, - HostPortPair host_port_pair); - static bool CryptoConfigCacheIsEmpty(QuicStreamFactory* factory, const QuicServerId& quic_server_id);
diff --git a/net/quic/chromium/quic_stream_factory_test.cc b/net/quic/chromium/quic_stream_factory_test.cc index f3acc60..c5f5a85 100644 --- a/net/quic/chromium/quic_stream_factory_test.cc +++ b/net/quic/chromium/quic_stream_factory_test.cc
@@ -101,23 +101,18 @@ // and enable_connection_racting. struct TestParams { friend std::ostream& operator<<(std::ostream& os, const TestParams& p) { - os << "{ version: " << QuicVersionToString(p.version) - << ", enable_connection_racing: " - << (p.enable_connection_racing ? "true" : "false") << " }"; + os << "{ version: " << QuicVersionToString(p.version) << " }"; return os; } QuicVersion version; - bool enable_connection_racing; }; std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; QuicVersionVector all_supported_versions = AllSupportedVersions(); - for (const QuicVersion version : all_supported_versions) { - params.push_back(TestParams{version, false}); - params.push_back(TestParams{version, true}); - } + for (const auto& version : all_supported_versions) + params.push_back(TestParams{version}); return params; } @@ -127,8 +122,6 @@ friend std::ostream& operator<<(std::ostream& os, const PoolingTestParams& p) { os << "{ version: " << QuicVersionToString(p.version) - << ", enable_connection_racing: " - << (p.enable_connection_racing ? "true" : "false") << ", destination_type: "; switch (p.destination_type) { case SAME_AS_FIRST: @@ -146,7 +139,6 @@ } QuicVersion version; - bool enable_connection_racing; DestinationType destination_type; }; @@ -154,12 +146,9 @@ std::vector<PoolingTestParams> params; QuicVersionVector all_supported_versions = AllSupportedVersions(); for (const QuicVersion version : all_supported_versions) { - params.push_back(PoolingTestParams{version, false, SAME_AS_FIRST}); - params.push_back(PoolingTestParams{version, false, SAME_AS_SECOND}); - params.push_back(PoolingTestParams{version, false, DIFFERENT}); - params.push_back(PoolingTestParams{version, true, SAME_AS_FIRST}); - params.push_back(PoolingTestParams{version, true, SAME_AS_SECOND}); - params.push_back(PoolingTestParams{version, true, DIFFERENT}); + params.push_back(PoolingTestParams{version, SAME_AS_FIRST}); + params.push_back(PoolingTestParams{version, SAME_AS_SECOND}); + params.push_back(PoolingTestParams{version, DIFFERENT}); } return params; } @@ -173,50 +162,9 @@ } }; -class MockQuicServerInfo : public QuicServerInfo { - public: - explicit MockQuicServerInfo(const QuicServerId& server_id) - : QuicServerInfo(server_id) {} - ~MockQuicServerInfo() override {} - - void Start() override {} - - int WaitForDataReady(const CompletionCallback& callback) override { - return ERR_IO_PENDING; - } - - void ResetWaitForDataReadyCallback() override {} - - void CancelWaitForDataReadyCallback() override {} - - bool IsDataReady() override { return false; } - - bool IsReadyToPersist() override { return false; } - - void Persist() override {} - - void OnExternalCacheHit() override {} - - size_t EstimateMemoryUsage() const override { - NOTREACHED(); - return 0; - } -}; - -class MockQuicServerInfoFactory : public QuicServerInfoFactory { - public: - MockQuicServerInfoFactory() {} - ~MockQuicServerInfoFactory() override {} - - std::unique_ptr<QuicServerInfo> GetForServer( - const QuicServerId& server_id) override { - return base::MakeUnique<MockQuicServerInfo>(server_id); - } -}; - class QuicStreamFactoryTestBase { protected: - QuicStreamFactoryTestBase(QuicVersion version, bool enable_connection_racing) + explicit QuicStreamFactoryTestBase(QuicVersion version) : ssl_config_service_(new MockSSLConfigService), random_generator_(0), runner_(new TestTaskRunner(&clock_)), @@ -243,10 +191,7 @@ url3_(kServer3Url), url4_(kServer4Url), privacy_mode_(PRIVACY_MODE_DISABLED), - load_server_info_timeout_srtt_multiplier_(0.0f), - enable_connection_racing_(enable_connection_racing), - enable_non_blocking_io_(true), - disable_disk_cache_(false), + store_server_configs_in_properties_(false), close_sessions_on_ip_change_(false), idle_connection_timeout_seconds_(kIdleConnectionTimeoutSeconds), reduced_ping_timeout_seconds_(kPingTimeoutSecs), @@ -271,10 +216,7 @@ /*SocketPerformanceWatcherFactory*/ nullptr, &crypto_client_stream_factory_, &random_generator_, &clock_, kDefaultMaxPacketSize, string(), SupportedVersions(version_), - load_server_info_timeout_srtt_multiplier_, enable_connection_racing_, - enable_non_blocking_io_, disable_disk_cache_, - /*max_server_configs_stored_in_properties*/ 0, - close_sessions_on_ip_change_, + store_server_configs_in_properties_, close_sessions_on_ip_change_, /*mark_quic_broken_when_network_blackholes*/ false, idle_connection_timeout_seconds_, reduced_ping_timeout_seconds_, packet_reader_yield_after_duration_milliseconds_, @@ -283,9 +225,6 @@ /*do_not_fragment*/ true, estimate_initial_rtt_, QuicTagVector(), /*enable_token_binding*/ false)); factory_->set_require_confirmation(false); - EXPECT_FALSE(factory_->has_quic_server_info_factory()); - factory_->set_quic_server_info_factory(new MockQuicServerInfoFactory()); - EXPECT_TRUE(factory_->has_quic_server_info_factory()); } void InitializeConnectionMigrationTest( @@ -541,10 +480,14 @@ // a non proxy server that support alternative services is added to the // HttpServerProperties map. void VerifyInitialization(bool proxy_delegate_provides_quic_supported_proxy) { + store_server_configs_in_properties_ = true; idle_connection_timeout_seconds_ = 500; Initialize(); ProofVerifyDetailsChromium verify_details = DefaultProofVerifyDetails(); crypto_client_stream_factory_.AddProofVerifyDetails(&verify_details); + crypto_client_stream_factory_.AddProofVerifyDetails(&verify_details); + crypto_client_stream_factory_.set_handshake_mode( + MockCryptoClientStream::ZERO_RTT); const QuicConfig* config = QuicStreamFactoryPeer::GetConfig(factory_.get()); EXPECT_EQ(500, config->IdleNetworkTimeout().ToSeconds()); @@ -584,14 +527,11 @@ http_server_properties_.SetMaxServerConfigsStoredInProperties( kMaxQuicServersToPersist); - QuicServerId quic_server_id(kDefaultServerHostName, 80, + QuicServerId quic_server_id(kDefaultServerHostName, 443, PRIVACY_MODE_DISABLED); - QuicServerInfoFactory* quic_server_info_factory = - new PropertiesBasedQuicServerInfoFactory(&http_server_properties_); - factory_->set_quic_server_info_factory(quic_server_info_factory); - - std::unique_ptr<QuicServerInfo> quic_server_info( - quic_server_info_factory->GetForServer(quic_server_id)); + std::unique_ptr<QuicServerInfo> quic_server_info = + base::MakeUnique<PropertiesBasedQuicServerInfo>( + quic_server_id, &http_server_properties_); // Update quic_server_info's server_config and persist it. QuicServerInfo::State* state = quic_server_info->mutable_state(); @@ -627,10 +567,10 @@ quic_server_info->Persist(); - QuicServerId quic_server_id2(kServer2HostName, 80, PRIVACY_MODE_DISABLED); - std::unique_ptr<QuicServerInfo> quic_server_info2( - quic_server_info_factory->GetForServer(quic_server_id2)); - + QuicServerId quic_server_id2(kServer2HostName, 443, PRIVACY_MODE_DISABLED); + std::unique_ptr<QuicServerInfo> quic_server_info2 = + base::MakeUnique<PropertiesBasedQuicServerInfo>( + quic_server_id2, &http_server_properties_); // Update quic_server_info2's server_config and persist it. QuicServerInfo::State* state2 = quic_server_info2->mutable_state(); @@ -667,9 +607,6 @@ quic_server_info2->Persist(); - QuicStreamFactoryPeer::MaybeInitialize(factory_.get()); - EXPECT_TRUE(QuicStreamFactoryPeer::HasInitializedData(factory_.get())); - // Verify the MRU order is maintained. const QuicServerInfoMap& quic_server_info_map = http_server_properties_.quic_server_info_map(); @@ -680,8 +617,21 @@ ++quic_server_info_map_it; EXPECT_EQ(quic_server_info_map_it->first, quic_server_id); - EXPECT_TRUE(QuicStreamFactoryPeer::SupportsQuicAtStartUp(factory_.get(), - host_port_pair_)); + host_resolver_.rules()->AddIPLiteralRule(host_port_pair_.host(), + "192.168.0.1", ""); + + // Create a session and verify that the cached state is loaded. + MockQuicData socket_data; + socket_data.AddRead(SYNCHRONOUS, ERR_IO_PENDING); + socket_data.AddSocketDataToFactory(&socket_factory_); + + QuicStreamRequest request(factory_.get(), &http_server_properties_); + EXPECT_EQ(ERR_IO_PENDING, + request.Request(quic_server_id.host_port_pair(), privacy_mode_, + /*cert_verify_flags=*/0, url_, "GET", net_log_, + callback_.callback())); + EXPECT_THAT(callback_.WaitForResult(), IsOk()); + EXPECT_FALSE(QuicStreamFactoryPeer::CryptoConfigCacheIsEmpty( factory_.get(), quic_server_id)); QuicCryptoClientConfig* crypto_config = @@ -698,8 +648,24 @@ ASSERT_EQ(1U, cached->certs().size()); EXPECT_EQ(test_cert, cached->certs()[0]); - EXPECT_TRUE(QuicStreamFactoryPeer::SupportsQuicAtStartUp(factory_.get(), - host_port_pair2)); + EXPECT_TRUE(socket_data.AllWriteDataConsumed()); + + // Create a session and verify that the cached state is loaded. + MockQuicData socket_data2; + socket_data2.AddRead(SYNCHRONOUS, ERR_IO_PENDING); + socket_data2.AddSocketDataToFactory(&socket_factory_); + + host_resolver_.rules()->AddIPLiteralRule(host_port_pair_.host(), + "192.168.0.2", ""); + + QuicStreamRequest request2(factory_.get(), &http_server_properties_); + EXPECT_EQ(ERR_IO_PENDING, + request2.Request(quic_server_id2.host_port_pair(), privacy_mode_, + /*cert_verify_flags=*/0, + GURL("https://mail.example.org/"), "GET", + net_log_, callback_.callback())); + EXPECT_THAT(callback_.WaitForResult(), IsOk()); + EXPECT_FALSE(QuicStreamFactoryPeer::CryptoConfigCacheIsEmpty( factory_.get(), quic_server_id2)); QuicCryptoClientConfig::CachedState* cached2 = @@ -769,10 +735,7 @@ TestCompletionCallback callback_; // Variables to configure QuicStreamFactory. - double load_server_info_timeout_srtt_multiplier_; - bool enable_connection_racing_; - bool enable_non_blocking_io_; - bool disable_disk_cache_; + bool store_server_configs_in_properties_; bool close_sessions_on_ip_change_; int idle_connection_timeout_seconds_; int reduced_ping_timeout_seconds_; @@ -788,9 +751,7 @@ class QuicStreamFactoryTest : public QuicStreamFactoryTestBase, public ::testing::TestWithParam<TestParams> { protected: - QuicStreamFactoryTest() - : QuicStreamFactoryTestBase(GetParam().version, - GetParam().enable_connection_racing) {} + QuicStreamFactoryTest() : QuicStreamFactoryTestBase(GetParam().version) {} }; INSTANTIATE_TEST_CASE_P(Version, @@ -4417,62 +4378,7 @@ } } -TEST_P(QuicStreamFactoryTest, RacingConnections) { - disable_disk_cache_ = false; - Initialize(); - ProofVerifyDetailsChromium verify_details = DefaultProofVerifyDetails(); - crypto_client_stream_factory_.AddProofVerifyDetails(&verify_details); - - if (!enable_connection_racing_) - return; - - QuicStreamFactoryPeer::SetTaskRunner(factory_.get(), runner_.get()); - - MockQuicData socket_data; - socket_data.AddRead(SYNCHRONOUS, ERR_IO_PENDING); - socket_data.AddSocketDataToFactory(&socket_factory_); - - MockQuicData socket_data2; - socket_data2.AddRead(SYNCHRONOUS, ERR_IO_PENDING); - socket_data2.AddSocketDataToFactory(&socket_factory_); - - const AlternativeService alternative_service1( - kProtoQUIC, host_port_pair_.host(), host_port_pair_.port()); - AlternativeServiceInfoVector alternative_service_info_vector; - base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1); - alternative_service_info_vector.push_back( - AlternativeServiceInfo(alternative_service1, expiration)); - - http_server_properties_.SetAlternativeServices( - url::SchemeHostPort(url_), alternative_service_info_vector); - - crypto_client_stream_factory_.set_handshake_mode( - MockCryptoClientStream::ZERO_RTT); - host_resolver_.set_synchronous_mode(true); - host_resolver_.rules()->AddIPLiteralRule(host_port_pair_.host(), - "192.168.0.1", ""); - - QuicStreamRequest request(factory_.get(), &http_server_properties_); - QuicServerId server_id(host_port_pair_, privacy_mode_); - EXPECT_EQ(ERR_IO_PENDING, - request.Request(host_port_pair_, privacy_mode_, - /*cert_verify_flags=*/0, url_, "GET", net_log_, - callback_.callback())); - EXPECT_EQ(2u, QuicStreamFactoryPeer::GetNumberOfActiveJobs(factory_.get(), - server_id)); - - runner_->RunNextTask(); - - std::unique_ptr<QuicHttpStream> stream = request.CreateStream(); - EXPECT_TRUE(stream.get()); - EXPECT_TRUE(socket_data.AllReadDataConsumed()); - EXPECT_TRUE(socket_data.AllWriteDataConsumed()); - EXPECT_EQ(0u, QuicStreamFactoryPeer::GetNumberOfActiveJobs(factory_.get(), - server_id)); -} - TEST_P(QuicStreamFactoryTest, EnableNotLoadFromDiskCache) { - disable_disk_cache_ = true; Initialize(); ProofVerifyDetailsChromium verify_details = DefaultProofVerifyDetails(); crypto_client_stream_factory_.AddProofVerifyDetails(&verify_details); @@ -4506,7 +4412,6 @@ TEST_P(QuicStreamFactoryTest, ReducePingTimeoutOnConnectionTimeOutOpenStreams) { reduced_ping_timeout_seconds_ = 10; - disable_disk_cache_ = true; Initialize(); ProofVerifyDetailsChromium verify_details = DefaultProofVerifyDetails(); crypto_client_stream_factory_.AddProofVerifyDetails(&verify_details); @@ -4598,50 +4503,6 @@ EXPECT_TRUE(socket_data2.AllWriteDataConsumed()); } -TEST_P(QuicStreamFactoryTest, DelayTcpRace) { - Initialize(); - ProofVerifyDetailsChromium verify_details = DefaultProofVerifyDetails(); - crypto_client_stream_factory_.AddProofVerifyDetails(&verify_details); - MockQuicData socket_data; - socket_data.AddRead(SYNCHRONOUS, ERR_IO_PENDING); - socket_data.AddWrite( - ConstructSettingsPacket(1, SETTINGS_MAX_HEADER_LIST_SIZE, - kDefaultMaxUncompressedHeaderSize, nullptr)); - socket_data.AddSocketDataToFactory(&socket_factory_); - - ServerNetworkStats stats1; - stats1.srtt = base::TimeDelta::FromMicroseconds(10); - http_server_properties_.SetServerNetworkStats(url::SchemeHostPort(url_), - stats1); - - crypto_client_stream_factory_.set_handshake_mode( - MockCryptoClientStream::COLD_START); - host_resolver_.set_synchronous_mode(true); - host_resolver_.rules()->AddIPLiteralRule(host_port_pair_.host(), - "192.168.0.1", ""); - - QuicStreamRequest request(factory_.get(), &http_server_properties_); - EXPECT_EQ(ERR_IO_PENDING, - request.Request(host_port_pair_, privacy_mode_, - /*cert_verify_flags=*/0, url_, "POST", net_log_, - callback_.callback())); - - // Verify delay is one RTT and that server supports QUIC. - EXPECT_EQ(base::TimeDelta::FromMicroseconds(15), - request.GetTimeDelayForWaitingJob()); - - // Confirm the handshake and verify that the stream is created. - crypto_client_stream_factory_.last_stream()->SendOnCryptoHandshakeEvent( - QuicSession::HANDSHAKE_CONFIRMED); - - EXPECT_THAT(callback_.WaitForResult(), IsOk()); - - std::unique_ptr<QuicHttpStream> stream = request.CreateStream(); - EXPECT_TRUE(stream.get()); - EXPECT_TRUE(socket_data.AllReadDataConsumed()); - EXPECT_TRUE(socket_data.AllWriteDataConsumed()); -} - // Verifies that the QUIC stream factory is initialized correctly. TEST_P(QuicStreamFactoryTest, MaybeInitialize) { VerifyInitialization(false); @@ -4993,8 +4854,7 @@ public ::testing::TestWithParam<PoolingTestParams> { protected: QuicStreamFactoryWithDestinationTest() - : QuicStreamFactoryTestBase(GetParam().version, - GetParam().enable_connection_racing), + : QuicStreamFactoryTestBase(GetParam().version), destination_type_(GetParam().destination_type), hanging_read_(SYNCHRONOUS, ERR_IO_PENDING, 0) {}
diff --git a/net/socket/ssl_client_socket_impl.cc b/net/socket/ssl_client_socket_impl.cc index 3b29d41..a5f1bbc 100644 --- a/net/socket/ssl_client_socket_impl.cc +++ b/net/socket/ssl_client_socket_impl.cc
@@ -255,6 +255,43 @@ } #endif +std::unique_ptr<base::Value> NetLogSSLAlertCallback( + const void* bytes, + size_t len, + NetLogCaptureMode capture_mode) { + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + dict->SetString("hex_encoded_bytes", base::HexEncode(bytes, len)); + return std::move(dict); +} + +std::unique_ptr<base::Value> NetLogSSLMessageCallback( + bool is_write, + const void* bytes, + size_t len, + NetLogCaptureMode capture_mode) { + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + if (len == 0) { + NOTREACHED(); + return std::move(dict); + } + + // The handshake message type is the first byte. Include it so elided messages + // still report their type. + uint8_t type = reinterpret_cast<const uint8_t*>(bytes)[0]; + dict->SetInteger("type", type); + + // Elide client certificate messages unless logging socket bytes. The client + // certificate does not contain information needed to impersonate the user + // (that's the private key which isn't sent over the wire), but it may contain + // information on the user's identity. + if (!is_write || type != SSL3_MT_CERTIFICATE || + capture_mode.include_socket_bytes()) { + dict->SetString("hex_encoded_bytes", base::HexEncode(bytes, len)); + } + + return std::move(dict); +} + } // namespace class SSLClientSocketImpl::SSLContext { @@ -315,6 +352,8 @@ // Deduplicate all certificates minted from the SSL_CTX in memory. SSL_CTX_set0_buffer_pool(ssl_ctx_.get(), x509_util::GetBufferPool()); + SSL_CTX_set_msg_callback(ssl_ctx_.get(), MessageCallback); + if (!SSL_CTX_add_client_custom_ext(ssl_ctx_.get(), kTbExtNum, &TokenBindingAddCallback, &TokenBindingFreeCallback, nullptr, @@ -405,6 +444,17 @@ } #endif + static void MessageCallback(int is_write, + int version, + int content_type, + const void* buf, + size_t len, + SSL* ssl, + void* arg) { + SSLClientSocketImpl* socket = GetInstance()->GetClientSocketFromSSL(ssl); + return socket->MessageCallback(is_write, content_type, buf, len); + } + // This is the index used with SSL_get_ex_data to retrieve the owner // SSLClientSocketImpl object from an SSL instance. int ssl_socket_data_index_; @@ -1812,6 +1862,27 @@ RetryAllOperations(); } +void SSLClientSocketImpl::MessageCallback(int is_write, + int content_type, + const void* buf, + size_t len) { + switch (content_type) { + case SSL3_RT_ALERT: + net_log_.AddEvent(is_write ? NetLogEventType::SSL_ALERT_SENT + : NetLogEventType::SSL_ALERT_RECEIVED, + base::Bind(&NetLogSSLAlertCallback, buf, len)); + break; + case SSL3_RT_HANDSHAKE: + net_log_.AddEvent( + is_write ? NetLogEventType::SSL_HANDSHAKE_MESSAGE_SENT + : NetLogEventType::SSL_HANDSHAKE_MESSAGE_RECEIVED, + base::Bind(&NetLogSSLMessageCallback, !!is_write, buf, len)); + break; + default: + return; + } +} + int SSLClientSocketImpl::TokenBindingAdd(const uint8_t** out, size_t* out_len, int* out_alert_value) {
diff --git a/net/socket/ssl_client_socket_impl.h b/net/socket/ssl_client_socket_impl.h index 019c1c5..5eda482 100644 --- a/net/socket/ssl_client_socket_impl.h +++ b/net/socket/ssl_client_socket_impl.h
@@ -215,6 +215,12 @@ void OnPrivateKeyComplete(Error error, const std::vector<uint8_t>& signature); + // Called whenever BoringSSL processes a protocol message. + void MessageCallback(int is_write, + int content_type, + const void* buf, + size_t len); + int TokenBindingAdd(const uint8_t** out, size_t* out_len, int* out_alert_value);
diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc index 1eb9711..7282a0e5 100644 --- a/net/url_request/url_request_unittest.cc +++ b/net/url_request/url_request_unittest.cc
@@ -7868,127 +7868,6 @@ EXPECT_EQ(LOW, job_priority); } -TEST_F(URLRequestTest, QuicServerInfoFactoryTest) { - HttpNetworkSession::Params params; - - MockClientSocketFactory socket_factory; - MockCryptoClientStreamFactory crypto_client_stream_factory; - MockHostResolver host_resolver; - MockCertVerifier cert_verifier; - CTPolicyEnforcer ct_policy_enforcer; - TransportSecurityState transport_security_state; - std::unique_ptr<CTVerifier> cert_transparency_verifier( - new MultiLogCTVerifier()); - std::unique_ptr<ProxyService> proxy_service = ProxyService::CreateDirect(); - scoped_refptr<SSLConfigServiceDefaults> ssl_config_service( - new SSLConfigServiceDefaults); - HttpServerPropertiesImpl http_server_properties; - // Set up the quic stream factory. - params.enable_quic = true; - params.client_socket_factory = &socket_factory; - params.quic_crypto_client_stream_factory = &crypto_client_stream_factory; - params.host_resolver = &host_resolver; - params.cert_verifier = &cert_verifier; - params.ct_policy_enforcer = &ct_policy_enforcer; - params.transport_security_state = &transport_security_state; - params.cert_transparency_verifier = cert_transparency_verifier.get(); - - params.proxy_service = proxy_service.get(); - params.ssl_config_service = ssl_config_service.get(); - params.http_server_properties = &http_server_properties; - - HttpNetworkSession session(params); - DCHECK(session.quic_stream_factory()); - - std::unique_ptr<HttpNetworkLayer> network_layer1( - new HttpNetworkLayer(&session)); - - HttpCache main_cache(std::move(network_layer1), - HttpCache::DefaultBackend::InMemory(0), - true /* is_main_cache */); - - EXPECT_TRUE(session.quic_stream_factory()->has_quic_server_info_factory()); - - default_context_.set_http_transaction_factory(&main_cache); - - QuicServerInfoFactory* quic_server_info_factory = - session.quic_stream_factory()->quic_server_info_factory(); - DCHECK(quic_server_info_factory); - - QuicServerId server_id("www.google.com", 443, PRIVACY_MODE_DISABLED); - const string server_config_a = "server_config_a"; - const string source_address_token_a = "source_address_token_a"; - const string cert_sct_a = "cert_sct_a"; - const string chlo_hash_a = "chlo_hash_a"; - const string server_config_sig_a = "server_config_sig_a"; - const string cert_a = "cert_a"; - const string cert_b = "cert_b"; - - { - // Store a QuicServerInfo to the quic server info factory. - TestCompletionCallback cb; - std::unique_ptr<QuicServerInfo> quic_server_info = - quic_server_info_factory->GetForServer(server_id); - quic_server_info->Start(); - int rv = quic_server_info->WaitForDataReady(cb.callback()); - EXPECT_THAT(cb.GetResult(rv), IsOk()); - - QuicServerInfo::State* state = quic_server_info->mutable_state(); - EXPECT_TRUE(state->certs.empty()); - - state->server_config = server_config_a; - state->source_address_token = source_address_token_a; - state->cert_sct = cert_sct_a; - state->chlo_hash = chlo_hash_a; - state->server_config_sig = server_config_sig_a; - state->certs.push_back(cert_a); - quic_server_info->Persist(); - base::RunLoop().RunUntilIdle(); - } - - // Retrieve the QuicServerInfo from the quic server info factory and verify - // the data is correct. - { - TestCompletionCallback cb; - std::unique_ptr<QuicServerInfo> quic_server_info = - quic_server_info_factory->GetForServer(server_id); - quic_server_info->Start(); - int rv = quic_server_info->WaitForDataReady(cb.callback()); - EXPECT_THAT(cb.GetResult(rv), IsOk()); - - QuicServerInfo::State* state = quic_server_info->mutable_state(); - EXPECT_TRUE(quic_server_info->IsDataReady()); - EXPECT_EQ(server_config_a, state->server_config); - EXPECT_EQ(source_address_token_a, state->source_address_token); - EXPECT_EQ(cert_sct_a, state->cert_sct); - EXPECT_EQ(chlo_hash_a, state->chlo_hash); - EXPECT_EQ(server_config_sig_a, state->server_config_sig); - EXPECT_EQ(1U, state->certs.size()); - EXPECT_EQ(cert_a, state->certs[0]); - - // Update the data. - state->certs.push_back(cert_b); - quic_server_info->Persist(); - base::RunLoop().RunUntilIdle(); - } - - { - // Verify data has been successfully updated. - TestCompletionCallback cb; - std::unique_ptr<QuicServerInfo> quic_server_info = - quic_server_info_factory->GetForServer(server_id); - quic_server_info->Start(); - int rv = quic_server_info->WaitForDataReady(cb.callback()); - EXPECT_THAT(cb.GetResult(rv), IsOk()); - - QuicServerInfo::State* state = quic_server_info->mutable_state(); - EXPECT_TRUE(quic_server_info->IsDataReady()); - EXPECT_EQ(2U, state->certs.size()); - EXPECT_EQ(cert_a, state->certs[0]); - EXPECT_EQ(cert_b, state->certs[1]); - } -} - // Check that creating a network request while entering/exiting suspend mode // fails as it should. This is the only case where an HttpTransactionFactory // does not return an HttpTransaction.
diff --git a/storage/browser/fileapi/file_system_url_request_job.cc b/storage/browser/fileapi/file_system_url_request_job.cc index 30fb47d..b68a43a 100644 --- a/storage/browser/fileapi/file_system_url_request_job.cc +++ b/storage/browser/fileapi/file_system_url_request_job.cc
@@ -143,12 +143,6 @@ *info = *response_info_; } -int FileSystemURLRequestJob::GetResponseCode() const { - if (response_info_) - return 200; - return URLRequestJob::GetResponseCode(); -} - void FileSystemURLRequestJob::StartAsync() { if (!request_) return;
diff --git a/storage/browser/fileapi/file_system_url_request_job.h b/storage/browser/fileapi/file_system_url_request_job.h index 59b286ab..7ed1042 100644 --- a/storage/browser/fileapi/file_system_url_request_job.h +++ b/storage/browser/fileapi/file_system_url_request_job.h
@@ -45,7 +45,6 @@ bool IsRedirectResponse(GURL* location, int* http_status_code) override; void SetExtraRequestHeaders(const net::HttpRequestHeaders& headers) override; void GetResponseInfo(net::HttpResponseInfo* info) override; - int GetResponseCode() const override; // FilterContext methods (via URLRequestJob): bool GetMimeType(std::string* mime_type) const override;
diff --git a/storage/browser/fileapi/file_writer_delegate_unittest.cc b/storage/browser/fileapi/file_writer_delegate_unittest.cc index 3a87993..39deadf9 100644 --- a/storage/browser/fileapi/file_writer_delegate_unittest.cc +++ b/storage/browser/fileapi/file_writer_delegate_unittest.cc
@@ -19,6 +19,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "net/base/io_buffer.h" #include "net/base/request_priority.h" +#include "net/http/http_response_headers.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_job.h" @@ -202,6 +203,14 @@ int GetResponseCode() const override { return 200; } + void GetResponseInfo(net::HttpResponseInfo* info) override { + const char kStatus[] = "HTTP/1.1 200 OK\0"; + const size_t kStatusLen = arraysize(kStatus); + + info->headers = + new net::HttpResponseHeaders(std::string(kStatus, kStatusLen)); + } + protected: ~FileWriterDelegateTestJob() override {}
diff --git a/third_party/WebKit/LayoutTests/NeverFixTests b/third_party/WebKit/LayoutTests/NeverFixTests index af54bb9..a804504 100644 --- a/third_party/WebKit/LayoutTests/NeverFixTests +++ b/third_party/WebKit/LayoutTests/NeverFixTests
@@ -216,9 +216,11 @@ # Only Windows supports Symbol CMAP encoded fonts. crbug.com/627953 [ Android Linux Mac ] fast/text/symbol-cmap.html [ WontFix ] -# wasm tests. Currently under virtual/enable_wasm +# wasm tests. Currently under virtual/enable_wasm or virtual/enable_wasm_streaming crbug.com/642912 http/tests/wasm/ [ WontFix ] crbug.com/642912 virtual/mojo-loading/http/tests/wasm/ [ WontFix ] +crbug.com/712970 http/tests/wasm_streaming/ [ WontFix ] +crbug.com/712970 virtual/mojo-loading/http/tests/wasm_streaming/ [ WontFix ] # These tests require audio codecs which are generally not available; # these tests can still be run manually with --skiped=ignore.
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index 6218cd8..f700691b 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -1826,21 +1826,14 @@ # ====== New tests from wpt-importer added here ====== crbug.com/626703 external/wpt/XMLHttpRequest/getresponseheader-chunked-trailer.htm [ Failure ] -crbug.com/626703 external/wpt/XMLHttpRequest/anonymous-mode-unsupported.htm [ Failure ] -crbug.com/626703 external/wpt/XMLHttpRequest/open-after-setrequestheader.htm [ Failure ] -crbug.com/626703 external/wpt/XMLHttpRequest/open-referer.htm [ Failure ] crbug.com/626703 external/wpt/XMLHttpRequest/open-url-redirected-worker-origin.htm [ Failure ] crbug.com/626703 external/wpt/XMLHttpRequest/open-url-worker-origin.htm [ Failure ] crbug.com/626703 external/wpt/XMLHttpRequest/preserve-ua-header-on-redirect.htm [ Failure ] -crbug.com/626703 external/wpt/XMLHttpRequest/send-accept-language.htm [ Failure ] crbug.com/626703 external/wpt/XMLHttpRequest/send-entity-body-document.htm [ Failure ] crbug.com/626703 external/wpt/XMLHttpRequest/setrequestheader-allow-empty-value.htm [ Failure ] crbug.com/626703 external/wpt/XMLHttpRequest/setrequestheader-allow-whitespace-in-value.htm [ Failure ] -crbug.com/626703 external/wpt/XMLHttpRequest/setrequestheader-case-insensitive.htm [ Failure ] crbug.com/626703 external/wpt/XMLHttpRequest/setrequestheader-content-type.htm [ Failure ] crbug.com/626703 external/wpt/XMLHttpRequest/setrequestheader-header-allowed.htm [ Failure ] -crbug.com/626703 external/wpt/XMLHttpRequest/setrequestheader-header-forbidden.htm [ Failure ] -crbug.com/626703 external/wpt/XMLHttpRequest/setrequestheader-open-setrequestheader.htm [ Failure ] crbug.com/626703 external/wpt/html/webappapis/system-state-and-capabilities/the-navigator-object/NavigatorID.html [ Failure ] crbug.com/626703 external/wpt/XMLHttpRequest/abort-after-stop.htm [ Timeout ] crbug.com/626703 external/wpt/XMLHttpRequest/event-readystatechange-loaded.htm [ Failure Timeout ] @@ -2697,8 +2690,6 @@ crbug.com/706091 [ Linux ] virtual/wheelscrolllatching/fast/events/wheel/wheel-scroll-latching-on-scrollbar.html [ Failure Pass ] -crbug.com/700788 virtual/enable_wasm/http/tests/wasm/wasm_local_iframe_test.html [ Failure ] - # Sheriff failures 2017-04-03 # Should be [ Crash Pass ], but this has a commented out [ Skip ] expectation # for Mac earlier in the file, so just skip it everywhere. @@ -2710,3 +2701,16 @@ crbug.com/713049 images/color-profile-reflection.html [ Failure Pass ] crbug.com/713049 virtual/gpu-rasterization/images/color-profile-reflection.html [ Failure Pass ] crbug.com/713050 tables/mozilla/bugs/bug113424.html [ Failure Pass ] + +crbug.com/708934 fast/backgrounds/background-image-relative-url-in-iframe.html [ Failure Pass ] + +# Skip tests for vibrate with feature policy +crbug.com/710850 http/tests/feature-policy/vibrate-enabledforall.php [ Skip ] +crbug.com/710850 http/tests/feature-policy/vibrate-enabledforself.php [ Skip ] +crbug.com/710850 http/tests/feature-policy/vibrate-disabled.php [ Skip ] +crbug.com/710850 virtual/feature-policy/http/tests/feature-policy/vibrate-enabledforall.php [ Skip ] +crbug.com/710850 virtual/feature-policy/http/tests/feature-policy/vibrate-enabledforself.php [ Skip ] +crbug.com/710850 virtual/feature-policy/http/tests/feature-policy/vibrate-disabled.php [ Skip ] +crbug.com/710850 virtual/mojo-loading/http/tests/feature-policy/vibrate-enabledforall.php [ Skip ] +crbug.com/710850 virtual/mojo-loading/http/tests/feature-policy/vibrate-enabledforself.php [ Skip ] +crbug.com/710850 virtual/mojo-loading/http/tests/feature-policy/vibrate-disabled.php [ Skip ]
diff --git a/third_party/WebKit/LayoutTests/VirtualTestSuites b/third_party/WebKit/LayoutTests/VirtualTestSuites index 14cf539..53dda9c 100644 --- a/third_party/WebKit/LayoutTests/VirtualTestSuites +++ b/third_party/WebKit/LayoutTests/VirtualTestSuites
@@ -423,6 +423,11 @@ "args": ["--enable-features=WebAssembly"] }, { + "prefix": "enable_wasm_streaming", + "base": "http/tests/wasm_streaming", + "args": ["--enable-features=WebAssemblyStreaming"] + }, + { "prefix": "enable_asmjs", "base": "http/tests/asmjs", "args": ["--enable-features=AsmJsToWebAssembly"]
diff --git a/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/getallresponseheaders-cl-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/getallresponseheaders-cl-expected.txt index 9bc0ecc..67a8da89 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/getallresponseheaders-cl-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/XMLHttpRequest/getallresponseheaders-cl-expected.txt
@@ -1,6 +1,6 @@ This is a testharness.js-based test. FAIL Casing of known headers assert_equals: expected "content-length: 0\r\n" but got "CONTENT-LENGTH: 0\r\n" -FAIL Casing of known headers 1 assert_regexp_match: expected object "/content-TYPE/" but got "" -FAIL Casing of known headers 2 assert_regexp_match: expected object "/THIS-is-A-test: 1, 2/" but got "" +PASS Casing of known headers 1 +PASS Casing of known headers 2 Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/fast/events/pointerevents/multi-pointer-event-in-slop-region-expected.txt b/third_party/WebKit/LayoutTests/fast/events/pointerevents/multi-pointer-event-in-slop-region-expected.txt new file mode 100644 index 0000000..cd80199 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/events/pointerevents/multi-pointer-event-in-slop-region-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL Tests that TouchMoves are not suppressed if a secondary pointer is present during any movement. assert_equals: expected 3 but got 2 +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/fast/events/pointerevents/pointer-event-in-slop-region-expected.txt b/third_party/WebKit/LayoutTests/fast/events/pointerevents/pointer-event-in-slop-region-expected.txt new file mode 100644 index 0000000..b61ad5a --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/events/pointerevents/pointer-event-in-slop-region-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL Tests that TouchMoves are suppressed if within the slop suppression region. assert_equals: expected 7 but got 3 +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/http/tests/feature-policy/resources/feature-policy-vibrate-disabled.html b/third_party/WebKit/LayoutTests/http/tests/feature-policy/resources/feature-policy-vibrate-disabled.html index 4fdb34b..2fab1c8 100644 --- a/third_party/WebKit/LayoutTests/http/tests/feature-policy/resources/feature-policy-vibrate-disabled.html +++ b/third_party/WebKit/LayoutTests/http/tests/feature-policy/resources/feature-policy-vibrate-disabled.html
@@ -3,9 +3,23 @@ <title>Feature-Policy Vibrate Disabled</title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> -</head> +<script src="/js-test-resources/user-gesture-utils.js"></script> <script> - test(function() { + +function startTest(event) { + // Simulates a user click for vibrate to be allowed. + var element = document.getElementById("test"); + simulateUserClick(element.offsetLeft + event.data.x + 2, element.offsetTop + event.data.y + 2); +} + +function testVibrate() { + test(function () { assert_false(navigator.vibrate(200)); }, 'No iframe may call navigator.vibrate when disabled.'); +} + +window.addEventListener("message", startTest, true); </script> +<body> +<button id="test" onclick="testVibrate();">Click to vibrate</button> +
diff --git a/third_party/WebKit/LayoutTests/http/tests/feature-policy/resources/feature-policy-vibrate-enabled.html b/third_party/WebKit/LayoutTests/http/tests/feature-policy/resources/feature-policy-vibrate-enabled.html index 81d5769..3c7aeb03 100644 --- a/third_party/WebKit/LayoutTests/http/tests/feature-policy/resources/feature-policy-vibrate-enabled.html +++ b/third_party/WebKit/LayoutTests/http/tests/feature-policy/resources/feature-policy-vibrate-enabled.html
@@ -1,11 +1,26 @@ <!DOCTYPE html> <head> - <title>Feature-Policy Vibrate Enabled</title> - <script src="/resources/testharness.js"></script> - <script src="/resources/testharnessreport.js"></script> -</head> +<title>Feature-Policy Vibrate Enabled</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/js-test-resources/user-gesture-utils.js"></script> <script> - test(function() { - assert_true(navigator.vibrate(200)); + +function startTest(event) { + // Simulates a user click for vibrate to be allowed. + var element = document.getElementById("test"); + simulateUserClick(element.offsetLeft + event.data.x + 2, element.offsetTop + event.data.y + 2); +} + +function testVibrate() { + test(function () { + assert_true(navigator.vibrate(200)); }, 'Any iframe may call navigator.vibrate when enabled.'); +} + +window.addEventListener("message", startTest, false); </script> +<body> +<button id="test" onclick="testVibrate();">Click to vibrate</button> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/feature-policy/vibrate-disabled-expected.txt b/third_party/WebKit/LayoutTests/http/tests/feature-policy/vibrate-disabled-expected.txt index f89cc9f..9962515 100644 --- a/third_party/WebKit/LayoutTests/http/tests/feature-policy/vibrate-disabled-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/feature-policy/vibrate-disabled-expected.txt
@@ -1,3 +1,4 @@ +CONSOLE ERROR: line 9: Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet: https://www.chromestatus.com/feature/5644273861001216. --------
diff --git a/third_party/WebKit/LayoutTests/http/tests/feature-policy/vibrate-enabledforall.php b/third_party/WebKit/LayoutTests/http/tests/feature-policy/vibrate-enabledforall.php index 471f7b0..50c03732 100644 --- a/third_party/WebKit/LayoutTests/http/tests/feature-policy/vibrate-enabledforall.php +++ b/third_party/WebKit/LayoutTests/http/tests/feature-policy/vibrate-enabledforall.php
@@ -15,13 +15,22 @@ <script src="../../resources/testharness.js"></script> <script src="../../resources/testharnessreport.js"></script> <script> - if (window.testRunner) { - testRunner.dumpAsText(); - testRunner.dumpChildFramesAsText(); +if (window.testRunner) { + testRunner.dumpAsText(); + testRunner.dumpChildFramesAsText(); +} + +function loaded() { + var iframes = document.getElementsByTagName('iframe'); + for (var i = 0; i < iframes.length; ++i) { // < 1; ++i) { // + var iframe = iframes[i]; + // The iframe uses eventSender to emulate a user navigatation, which requires absolute coordinates. + iframe.contentWindow.postMessage({x: iframe.offsetLeft, y: iframe.offsetTop}, "*"); } +} </script> </head> -<body> +<body onload="loaded();"> <iframe id="f1" src="resources/feature-policy-vibrate-enabled.html"></iframe> <iframe id="f2" src="http://localhost:8000/feature-policy/resources/feature-policy-vibrate-enabled.html"></iframe> </body>
diff --git a/third_party/WebKit/LayoutTests/http/tests/feature-policy/vibrate-enabledforself.php b/third_party/WebKit/LayoutTests/http/tests/feature-policy/vibrate-enabledforself.php index caa422d..b9abda90 100644 --- a/third_party/WebKit/LayoutTests/http/tests/feature-policy/vibrate-enabledforself.php +++ b/third_party/WebKit/LayoutTests/http/tests/feature-policy/vibrate-enabledforself.php
@@ -15,13 +15,22 @@ <script src="../../resources/testharness.js"></script> <script src="../../resources/testharnessreport.js"></script> <script> - if (window.testRunner) { - testRunner.dumpAsText(); - testRunner.dumpChildFramesAsText(); +if (window.testRunner) { + testRunner.dumpAsText(); + testRunner.dumpChildFramesAsText(); +} + +function loaded() { + var iframes = document.getElementsByTagName('iframe'); + for (var i = 0; i < iframes.length; ++i) { + var iframe = iframes[i]; + // The iframe uses eventSender to emulate a user navigatation, which requires absolute coordinates. + iframe.contentWindow.postMessage({x: iframe.offsetLeft, y: iframe.offsetTop}, "*"); } +} </script> </head> -<body> +<body onload="loaded();"> <iframe id="f1" src="resources/feature-policy-vibrate-enabled.html"></iframe> <iframe id="f2" src="http://localhost:8000/feature-policy/resources/feature-policy-vibrate-disabled.html"></iframe> </body>
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/resources/same-origin-iframe-for-vibrate-allowed.html b/third_party/WebKit/LayoutTests/http/tests/security/resources/same-origin-iframe-for-vibrate-allowed.html deleted file mode 100644 index d5b3f8f5..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/security/resources/same-origin-iframe-for-vibrate-allowed.html +++ /dev/null
@@ -1,14 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <script src="/resources/testharness.js"></script> - <script src="/resources/testharnessreport.js"></script> -</head> -<body> - <script> - test(function () { - assert_true(navigator.vibrate(200)); - }, "A same-origin iframe may call navigator.vibrate."); - </script> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_same_origin_iframe_allowed.html b/third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_same_origin_iframe_allowed.html deleted file mode 100644 index bef01c5..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_same_origin_iframe_allowed.html +++ /dev/null
@@ -1,15 +0,0 @@ -<!DOCTYPE html> -<html> - <head> - <title>Vibrate in same-origin iframe is allowed.</title> - <script src="/resources/testharness.js"></script> - <script src="/resources/testharnessreport.js"></script> - <script> - if (window.testRunner) { - testRunner.dumpAsText(); - testRunner.dumpChildFramesAsText(); - } - </script> - </head> - <iframe id="iframe" src="resources/same-origin-iframe-for-vibrate-allowed.html"></iframe> -</html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/resources/cross-origin-iframe-for-vibrate-blocked.html b/third_party/WebKit/LayoutTests/http/tests/security/vibration/resources/vibrate-in-cross-origin-iframe-blocked.html similarity index 100% rename from third_party/WebKit/LayoutTests/http/tests/security/resources/cross-origin-iframe-for-vibrate-blocked.html rename to third_party/WebKit/LayoutTests/http/tests/security/vibration/resources/vibrate-in-cross-origin-iframe-blocked.html
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/resources/cross-origin-iframe-for-vibrate-with-user-gesture-allowed.html b/third_party/WebKit/LayoutTests/http/tests/security/vibration/resources/vibrate-in-iframe-with-user-gesture-allowed.html similarity index 64% rename from third_party/WebKit/LayoutTests/http/tests/security/resources/cross-origin-iframe-for-vibrate-with-user-gesture-allowed.html rename to third_party/WebKit/LayoutTests/http/tests/security/vibration/resources/vibrate-in-iframe-with-user-gesture-allowed.html index 2e17ce2a..f7917352 100644 --- a/third_party/WebKit/LayoutTests/http/tests/security/resources/cross-origin-iframe-for-vibrate-with-user-gesture-allowed.html +++ b/third_party/WebKit/LayoutTests/http/tests/security/vibration/resources/vibrate-in-iframe-with-user-gesture-allowed.html
@@ -1,13 +1,10 @@ <html> <head> + <title>Testing vibrate 3 times in an iframe</title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> + <script src="/js-test-resources/user-gesture-utils.js"></script> <script> - var test = async_test( - "Testing vibrate 3 times in a x-origin iframe: " + - " 1. blocked before user gesture;" + - " 2. succeed during the click event;" + - " 3. succeed after user click."); function loaded() { document.getElementsByTagName('h4')[0].innerHTML = document.domain; @@ -15,34 +12,30 @@ function startTest(event) { - // A manual click should navigate. + // A manual click should enable vibrate. if (window.eventSender) { - var button = document.getElementById("b"); - eventSender.mouseMoveTo(button.offsetLeft + event.data.x + 2, button.offsetTop + event.data.y + 2); - test.step(function() { + test(function() { assert_false( navigator.vibrate(200), "1. Blocked vibrate before user gesture."); }); - - eventSender.mouseDown(); - eventSender.mouseUp(); + var element = document.getElementById("b"); + simulateUserClick(element.offsetLeft + event.data.x + 2, element.offsetTop + event.data.y + 2); } } function performTestAfterClick() { - test.step(function () { + test(function () { assert_true( navigator.vibrate(200), "3. Vibrate after user gesture succeeded."); }); - test.done(); } function performTestWithClick() { - test.step(function () { + test(function () { assert_true( navigator.vibrate(200), "2. Vibrate triggered by user gesture succeeded."); @@ -58,3 +51,4 @@ <button id="b" onclick="performTestWithClick();">Perform Test</button> </body> </html> +
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/vibration/resources/vibrate-in-same-origin-iframe-with-user-gesture-allowed.html b/third_party/WebKit/LayoutTests/http/tests/security/vibration/resources/vibrate-in-same-origin-iframe-with-user-gesture-allowed.html new file mode 100644 index 0000000..9203138 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/security/vibration/resources/vibrate-in-same-origin-iframe-with-user-gesture-allowed.html
@@ -0,0 +1,54 @@ +<html> +<head> + <title>Testing vibrate 3 times in an iframe</title> + <script src="/resources/testharness.js"></script> + <script src="/resources/testharnessreport.js"></script> + <script src="/js-test-resources/user-gesture-utils.js"></script> + <script> + function loaded() + { + document.getElementsByTagName('h4')[0].innerHTML = document.domain; + } + + function startTest(event) + { + // A manual click should enable vibrate. + if (window.eventSender) { + test(function() { + assert_true( + navigator.vibrate(200), + "1. Vibrate w/o user gesture is deprecated and will be blocked in M60."); + }); + var element = document.getElementById("b"); + simulateUserClick(element.offsetLeft + event.data.x + 2, element.offsetTop + event.data.y + 2); + } + } + + function performTestAfterClick() + { + test(function () { + assert_true( + navigator.vibrate(200), + "3. Vibrate after user gesture succeeded."); + }); + } + + function performTestWithClick() + { + test(function () { + assert_true( + navigator.vibrate(200), + "2. Vibrate triggered by user gesture succeeded."); + }); + window.requestAnimationFrame(performTestAfterClick); + } + + window.addEventListener("message", startTest, false); + </script> +</head> +<body onload="loaded();"> + <h4>DOMAIN</h4> + <button id="b" onclick="performTestWithClick();">Perform Test</button> +</body> +</html> +
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/vibration/resources/vibrate-with-user-gesture-allowed.html b/third_party/WebKit/LayoutTests/http/tests/security/vibration/resources/vibrate-with-user-gesture-allowed.html new file mode 100644 index 0000000..a011f34 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/security/vibration/resources/vibrate-with-user-gesture-allowed.html
@@ -0,0 +1,27 @@ +<!DOCTYPE html> +<html> +<head> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/js-test-resources/user-gesture-utils.js"></script> +<script> + +function startTest(event) { + // Simulates a user click for vibrate to be allowed. + var element = document.getElementById("test"); + simulateUserClick(element.offsetLeft + event.data.x + 2, element.offsetTop + event.data.y + 2); +} + +function testVibrate() { + test(function () { + assert_true(navigator.vibrate(200)); + }, "An iframe may call navigator.vibrate with user gesture."); +} + +window.addEventListener("message", startTest, false); +</script> +</head> +<body> +<button id="test" onclick="testVibrate();">Click to vibrate</button> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_cross_origin_iframe_blocked-expected.txt b/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-cross-origin-iframe-blocked-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_cross_origin_iframe_blocked-expected.txt rename to third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-cross-origin-iframe-blocked-expected.txt
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_cross_origin_iframe_blocked.html b/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-cross-origin-iframe-blocked.html similarity index 74% rename from third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_cross_origin_iframe_blocked.html rename to third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-cross-origin-iframe-blocked.html index 9296c33..ac39ba1 100644 --- a/third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_cross_origin_iframe_blocked.html +++ b/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-cross-origin-iframe-blocked.html
@@ -11,5 +11,5 @@ } </script> </head> - <iframe id="iframe" src="http://localhost:8000/security/resources/cross-origin-iframe-for-vibrate-blocked.html"></iframe> + <iframe id="iframe" src="http://localhost:8000/security/vibration/resources/vibrate-in-cross-origin-iframe-blocked.html"></iframe> </html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_cross_origin_iframe_with_user_gesture_allowed-expected.txt b/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-cross-origin-iframe-with-user-gesture-allowed-expected.txt similarity index 62% rename from third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_cross_origin_iframe_with_user_gesture_allowed-expected.txt rename to third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-cross-origin-iframe-with-user-gesture-allowed-expected.txt index 9c2c093..361942f 100644 --- a/third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_cross_origin_iframe_with_user_gesture_allowed-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-cross-origin-iframe-with-user-gesture-allowed-expected.txt
@@ -1,4 +1,4 @@ -CONSOLE ERROR: line 24: Blocked call to navigator.vibrate inside a cross-origin iframe because the frame has never been activated by the user: https://www.chromestatus.com/feature/5682658461876224. +CONSOLE ERROR: line 19: Blocked call to navigator.vibrate inside a cross-origin iframe because the frame has never been activated by the user: https://www.chromestatus.com/feature/5682658461876224. This tests that a cross-origin iframe with user gesture can vibrate. 127.0.0.1 @@ -9,6 +9,6 @@ Frame: '<!--framePath //<!--frame0-->-->' -------- This is a testharness.js-based test. -PASS Testing vibrate 3 times in a x-origin iframe: 1. blocked before user gesture; 2. succeed during the click event; 3. succeed after user click. +PASS Testing vibrate 3 times in an iframe Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_cross_origin_iframe_with_user_gesture_allowed.html b/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-cross-origin-iframe-with-user-gesture-allowed.html similarity index 87% rename from third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_cross_origin_iframe_with_user_gesture_allowed.html rename to third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-cross-origin-iframe-with-user-gesture-allowed.html index a1649540..0ce69d7 100644 --- a/third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_cross_origin_iframe_with_user_gesture_allowed.html +++ b/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-cross-origin-iframe-with-user-gesture-allowed.html
@@ -22,6 +22,6 @@ <body onload="loaded();"> <p>This tests that a cross-origin iframe with user gesture can vibrate.</p> <h4>DOMAIN</h4> - <iframe id="i" src="http://localhost:8000/security/resources/cross-origin-iframe-for-vibrate-with-user-gesture-allowed.html"></iframe> + <iframe id="i" src="http://localhost:8000/security/vibration/resources/vibrate-in-iframe-with-user-gesture-allowed.html"></iframe> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-same-origin-iframe-with-user-gesture-allowed-expected.txt b/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-same-origin-iframe-with-user-gesture-allowed-expected.txt new file mode 100644 index 0000000..a6eed96 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-same-origin-iframe-with-user-gesture-allowed-expected.txt
@@ -0,0 +1,14 @@ +CONSOLE WARNING: line 19: A call to navigator.vibrate without user tap on the frame or any embedded frame is deprecated and will be removed in M60, around August 2017. See https://www.chromestatus.com/features/5644273861001216 for more details. +This tests that a same-origin iframe with user gesture can vibrate. + +127.0.0.1 + + + +-------- +Frame: '<!--framePath //<!--frame0-->-->' +-------- +This is a testharness.js-based test. +PASS Testing vibrate 3 times in an iframe +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_cross_origin_iframe_with_user_gesture_allowed.html b/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-same-origin-iframe-with-user-gesture-allowed.html similarity index 65% copy from third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_cross_origin_iframe_with_user_gesture_allowed.html copy to third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-same-origin-iframe-with-user-gesture-allowed.html index a1649540..7e8f2f3 100644 --- a/third_party/WebKit/LayoutTests/http/tests/security/vibrate_in_cross_origin_iframe_with_user_gesture_allowed.html +++ b/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-in-same-origin-iframe-with-user-gesture-allowed.html
@@ -1,7 +1,7 @@ <!DOCTYPE html> <html> <head> - <title>Vibrate in cross-origin iframe with user gesture is allowed.</title> + <title>Vibrate in same-origin iframe with user gesture is allowed.</title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script> @@ -14,14 +14,13 @@ document.getElementsByTagName('h4')[0].innerHTML = document.domain; var iframe = document.getElementById("i"); // The iframe uses eventSender to emulate a user navigatation, which requires absolute coordinates. - // Because the iframe is cross-origin, it can't get the offsets itself, so leak them. frames[0].postMessage({x: iframe.offsetLeft, y: iframe.offsetTop}, "*"); } </script> </head> <body onload="loaded();"> - <p>This tests that a cross-origin iframe with user gesture can vibrate.</p> + <p>This tests that a same-origin iframe with user gesture can vibrate.</p> <h4>DOMAIN</h4> - <iframe id="i" src="http://localhost:8000/security/resources/cross-origin-iframe-for-vibrate-with-user-gesture-allowed.html"></iframe> + <iframe id="i" src="resources/vibrate-in-same-origin-iframe-with-user-gesture-allowed.html"></iframe> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-on-top-page-before-during-after-user-gesture-expected.txt b/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-on-top-page-before-during-after-user-gesture-expected.txt new file mode 100644 index 0000000..81c2455 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-on-top-page-before-during-after-user-gesture-expected.txt
@@ -0,0 +1,5 @@ +CONSOLE WARNING: line 12: A call to navigator.vibrate without user tap on the frame or any embedded frame is deprecated and will be removed in M60, around August 2017. See https://www.chromestatus.com/features/5644273861001216 for more details. +This is a testharness.js-based test. +PASS Testing vibrate 3 times on the top page +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-on-top-page-before-during-after-user-gesture.html b/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-on-top-page-before-during-after-user-gesture.html new file mode 100644 index 0000000..ac9056df --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/security/vibration/vibrate-on-top-page-before-during-after-user-gesture.html
@@ -0,0 +1,45 @@ +<html> +<head> + <title>Testing vibrate 3 times on the top page</title> + <script src="/resources/testharness.js"></script> + <script src="/resources/testharnessreport.js"></script> + <script src="/js-test-resources/user-gesture-utils.js"></script> + <script> + function startTest() + { + test(function() { + assert_true( + navigator.vibrate(200), + "1. Vibrate w/o user gesture is deprecated and will be blocked in M60."); + }); + + // A manual click should enable vibrate. + var element = document.getElementById("test"); + simulateUserClick(element.offsetLeft + 2, element.offsetTop + 2); + performTestWithClick(); + } + + function performTestWithClick() + { + test(function () { + assert_true( + navigator.vibrate(200), + "2. Vibrate triggered by user gesture succeeded."); + }); + window.requestAnimationFrame(performTestAfterClick); + } + + function performTestAfterClick() + { + test(function () { + assert_true( + navigator.vibrate(200), + "3. Vibrate after user gesture succeeded."); + }); + } + </script> +</head> +<body onload="startTest();"> + <button id="test">Click to vibrate</button> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/wasm/resources/frame.html b/third_party/WebKit/LayoutTests/http/tests/wasm/resources/frame.html index 937206d6..2f2b3ac9 100644 --- a/third_party/WebKit/LayoutTests/http/tests/wasm/resources/frame.html +++ b/third_party/WebKit/LayoutTests/http/tests/wasm/resources/frame.html
@@ -1,18 +1,18 @@ <script> - function listener(event) { - var mod = event.data; - try { - var i = new WebAssembly.Instance(mod); - var ans = i.exports.increment(42); - event.source.postMessage(ans, "*"); - } catch (e) { - event.source.postMessage(e, "*"); - } +function listener(event) { + var mod = event.data; + try { + var i = new WebAssembly.Instance(mod); + var ans = i.exports.increment(42); + event.source.postMessage(ans, event.origin); + } catch (e) { + event.source.postMessage(e, event.origin); } +} - if (window.addEventListener){ - addEventListener("message", listener, false) - } else { - attachEvent("onmessage", listener) - } +if (window.addEventListener){ + addEventListener("message", listener, false) +} else { + attachEvent("onmessage", listener) +} </script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/wasm/wasm_local_iframe_test.html b/third_party/WebKit/LayoutTests/http/tests/wasm/wasm_local_iframe_test.html index 66f7885..fa1ab0c 100644 --- a/third_party/WebKit/LayoutTests/http/tests/wasm/wasm_local_iframe_test.html +++ b/third_party/WebKit/LayoutTests/http/tests/wasm/wasm_local_iframe_test.html
@@ -10,7 +10,7 @@ var ans = await new Promise((resolve, reject) => { var iframe = document.getElementById("iframe").contentWindow; iframe.postMessage(mod, '*'); - iframe.onmessage = event => resolve(event.data); + window.addEventListener("message", (reply) => resolve(reply.data), false); }); assert_equals(ans, 43); }, "send wasm module to iframe");
diff --git a/third_party/WebKit/LayoutTests/http/tests/wasm/wasm_response_apis.html b/third_party/WebKit/LayoutTests/http/tests/wasm_streaming/wasm_response_apis.html similarity index 100% rename from third_party/WebKit/LayoutTests/http/tests/wasm/wasm_response_apis.html rename to third_party/WebKit/LayoutTests/http/tests/wasm_streaming/wasm_response_apis.html
diff --git a/third_party/WebKit/LayoutTests/http/tests/wasm/wasm_response_apis.js b/third_party/WebKit/LayoutTests/http/tests/wasm_streaming/wasm_response_apis.js similarity index 88% rename from third_party/WebKit/LayoutTests/http/tests/wasm/wasm_response_apis.js rename to third_party/WebKit/LayoutTests/http/tests/wasm_streaming/wasm_response_apis.js index dc2ebcb..e8b8f921 100644 --- a/third_party/WebKit/LayoutTests/http/tests/wasm/wasm_response_apis.js +++ b/third_party/WebKit/LayoutTests/http/tests/wasm_streaming/wasm_response_apis.js
@@ -2,16 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +const incrementer_url = '../wasm/incrementer.wasm'; function TestStreamedCompile() { - return fetch('incrementer.wasm') + return fetch(incrementer_url) .then(WebAssembly.compile) .then(m => new WebAssembly.Instance(m)) .then(i => assert_equals(5, i.exports.increment(4))); } function TestShortFormStreamedCompile() { - return WebAssembly.compile(fetch('incrementer.wasm')) + return WebAssembly.compile(fetch(incrementer_url)) .then(m => new WebAssembly.Instance(m)) .then(i => assert_equals(5, i.exports.increment(4))); } @@ -29,7 +30,7 @@ } function FromArrayBuffer() { - return fetch('incrementer.wasm') + return fetch(incrementer_url) .then(r => r.arrayBuffer()) .then(arr => new Response(arr)) .then(WebAssembly.compile)
diff --git a/third_party/WebKit/LayoutTests/resources/user-gesture-utils.js b/third_party/WebKit/LayoutTests/resources/user-gesture-utils.js new file mode 100644 index 0000000..35defbb --- /dev/null +++ b/third_party/WebKit/LayoutTests/resources/user-gesture-utils.js
@@ -0,0 +1,13 @@ +/** + * Simulates a user click on coordinates [x], [y]. + * For example, for vibrate to be allowed: + * https://www.chromestatus.com/feature/5644273861001216. + */ +function simulateUserClick(x, y) { + if (window.eventSender) { + eventSender.mouseMoveTo(x, y); + eventSender.mouseDown(); + eventSender.mouseUp(); + } +} +
diff --git a/third_party/WebKit/LayoutTests/vibration/cancel-vibration-during-pattern-vibrating.html b/third_party/WebKit/LayoutTests/vibration/cancel-vibration-during-pattern-vibrating.html index d41c4054..812306e 100644 --- a/third_party/WebKit/LayoutTests/vibration/cancel-vibration-during-pattern-vibrating.html +++ b/third_party/WebKit/LayoutTests/vibration/cancel-vibration-during-pattern-vibrating.html
@@ -1,11 +1,18 @@ <html> <head> <script src="../resources/js-test.js"></script> +<script src="../resources/user-gesture-utils.js"></script> +<script src="vibration-utils.js"></script> </head> <body> +<h4 id="test"></h4> <script> description('Tests the cancelVibration during pattern vibration is working.'); +// Simulates a user click for vibrate to be allowed. +var element = document.getElementById("test"); +simulateUserClick(element.offsetLeft + 2, element.offsetTop + 2); + function vibrate(pattern) { navigator.vibrate(pattern); shouldBeTrue('internals.isVibrating(navigator)'); @@ -60,4 +67,4 @@ } </script> </body> -</html> \ No newline at end of file +</html>
diff --git a/third_party/WebKit/LayoutTests/vibration/resources/vibrate-from-iframe.html b/third_party/WebKit/LayoutTests/vibration/resources/vibrate-from-iframe.html index 4bcf5f58..a7f70d6 100644 --- a/third_party/WebKit/LayoutTests/vibration/resources/vibrate-from-iframe.html +++ b/third_party/WebKit/LayoutTests/vibration/resources/vibrate-from-iframe.html
@@ -1,7 +1,32 @@ <!DOCTYPE html> +<head> +<title>Test vibrate with user gesture in same-origin iframe</title> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="../../resources/user-gesture-utils.js"></script> <script> 'use strict'; -navigator.vibrate(1234); +function startTest() { + if (window.eventSender) { + var iframes = window.parent.document.getElementsByTagName('iframe'); + // The last iframe. + var iframe = iframes[iframes.length-1]; + // Simulates a user click for vibrate to be allowed. + var element = document.getElementById("test"); + simulateUserClick(element.offsetLeft + iframe.offsetLeft + 2, element.offsetTop + iframe.offsetTop + 2); + } +} +function testVibrate() { + test(function () { + assert_true(navigator.vibrate(200)); + }, "An iframe may call navigator.vibrate with user gesture."); +} </script> +</head> +<body onload="startTest();"> +<button id="test" onclick="testVibrate();">Click to vibrate</button> +</body> +</html> +
diff --git a/third_party/WebKit/LayoutTests/vibration/vibration-durations.html b/third_party/WebKit/LayoutTests/vibration/vibration-durations.html index b83f4a1..49a5791 100644 --- a/third_party/WebKit/LayoutTests/vibration/vibration-durations.html +++ b/third_party/WebKit/LayoutTests/vibration/vibration-durations.html
@@ -1,12 +1,23 @@ <html> <head> <script src="../resources/js-test.js"></script> +<script src="../resources/user-gesture-utils.js"></script> <script src="vibration-utils.js"></script> </head> <body> +<h4 id="test"></h4> <script> description('Tests for how durations are handled in the Vibration API.'); +if (window.testRunner) { + testRunner.dumpAsText(); + testRunner.dumpChildFramesAsText(); +} + +// Simulates a user click for vibrate to be allowed. +var element = document.getElementById("test"); +simulateUserClick(element.offsetLeft + 2, element.offsetTop + 2); + // Empty pattern is empty. Does not start a vibration. shouldBeTrue("navigator.vibrate([])"); shouldBeTrue("areArraysEqual(internals.pendingVibrationPattern(navigator), [])");
diff --git a/third_party/WebKit/LayoutTests/vibration/vibration-exceptions.html b/third_party/WebKit/LayoutTests/vibration/vibration-exceptions.html index ee16c08..ff0d57021 100644 --- a/third_party/WebKit/LayoutTests/vibration/vibration-exceptions.html +++ b/third_party/WebKit/LayoutTests/vibration/vibration-exceptions.html
@@ -1,12 +1,18 @@ <html> <head> <script src="../resources/js-test.js"></script> +<script src="../resources/user-gesture-utils.js"></script> <script src="vibration-utils.js"></script> </head> <body> +<h4 id="test"></h4> <script> description('Tests that bad input throws exceptions in the Vibration API.'); +// Simulates a user click for vibrate to be allowed. +var element = document.getElementById("test"); +simulateUserClick(element.offsetLeft + 2, element.offsetTop + 2); + shouldThrow("navigator.vibrate()"); shouldBe("navigator.vibrate(1, 2)", "true"); shouldBe("navigator.vibrate([1], [2])", "true");
diff --git a/third_party/WebKit/LayoutTests/vibration/vibration-iframe-expected.txt b/third_party/WebKit/LayoutTests/vibration/vibration-iframe-expected.txt index 154b228..8b13789 100644 --- a/third_party/WebKit/LayoutTests/vibration/vibration-iframe-expected.txt +++ b/third_party/WebKit/LayoutTests/vibration/vibration-iframe-expected.txt
@@ -1,8 +1 @@ -CONSOLE ERROR: line 301: Uncaught TypeError: Cannot read property 'then' of undefined -CONSOLE ERROR: line 301: Uncaught TypeError: Cannot read property 'then' of undefined -This is a testharness.js-based test. -Harness Error. harness_status.status = 1 , harness_status.message = Uncaught TypeError: Cannot read property 'then' of undefined -PASS Iframe reload cancels vibration started by it before. -PASS Iframe destroy cancels vibration started by it before. -Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/vibration/vibration-page-visibility.html b/third_party/WebKit/LayoutTests/vibration/vibration-page-visibility.html index 88afbbef..e79d93c 100644 --- a/third_party/WebKit/LayoutTests/vibration/vibration-page-visibility.html +++ b/third_party/WebKit/LayoutTests/vibration/vibration-page-visibility.html
@@ -1,8 +1,14 @@ <!DOCTYPE html> +<h4 id="test"></h4> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> +<script src="../resources/user-gesture-utils.js"></script> +<script src="vibration-utils.js"></script> <script> 'use strict'; +// Simulates a user click for vibrate to be allowed. +var element = document.getElementById("test"); +simulateUserClick(element.offsetLeft + 2, element.offsetTop + 2); test(() => { // Initially the page is hidden and no vibration can be started.
diff --git a/third_party/WebKit/LayoutTests/vibration/vibration-patterns.html b/third_party/WebKit/LayoutTests/vibration/vibration-patterns.html index ca254ea8..75aa0f5 100644 --- a/third_party/WebKit/LayoutTests/vibration/vibration-patterns.html +++ b/third_party/WebKit/LayoutTests/vibration/vibration-patterns.html
@@ -1,12 +1,18 @@ <html> <head> <script src="../resources/js-test.js"></script> +<script src="../resources/user-gesture-utils.js"></script> <script src="vibration-utils.js"></script> </head> <body> +<h4 id="test"></h4> <script> description('Tests for how patterns are handled in the Vibration API.'); +// Simulates a user click for vibrate to be allowed. +var element = document.getElementById("test"); +simulateUserClick(element.offsetLeft + 2, element.offsetTop + 2); + // A trailing pause is discarded from a pattern i.e. patterns of even // non-zero length are truncated by 1. shouldBeTrue("navigator.vibrate(newPattern(1, 4))");
diff --git a/third_party/WebKit/LayoutTests/vibration/vibration.html b/third_party/WebKit/LayoutTests/vibration/vibration.html index 1dfcde4..46e7afc8 100644 --- a/third_party/WebKit/LayoutTests/vibration/vibration.html +++ b/third_party/WebKit/LayoutTests/vibration/vibration.html
@@ -2,7 +2,10 @@ <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> <script src="../resources/mojo-helpers.js"></script> +<script src="../resources/user-gesture-utils.js"></script> <script src="resources/vibration-helpers.js"></script> +<script src="vibration-utils.js"></script> +<h4 id="test"></h4> <script> 'use strict'; @@ -10,6 +13,10 @@ if (!window.testRunner) debug('This test cannot be run without the TestRunner'); +// Simulates a user click for vibrate to be allowed. +var element = document.getElementById("test"); +simulateUserClick(element.offsetLeft + 2, element.offsetTop + 2); + vibration_test(vibration => { assert_true(vibration instanceof Object); assert_true(vibration.mockVibrationManager instanceof Object);
diff --git a/third_party/WebKit/LayoutTests/virtual/enable_wasm_streaming/README.txt b/third_party/WebKit/LayoutTests/virtual/enable_wasm_streaming/README.txt new file mode 100644 index 0000000..d6444f1 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/enable_wasm_streaming/README.txt
@@ -0,0 +1 @@ +Tests that depend on --enable-features=WebAssemblyStreaming
diff --git a/third_party/WebKit/LayoutTests/virtual/enable_wasm_streaming/http/tests/wasm_streaming/README.txt b/third_party/WebKit/LayoutTests/virtual/enable_wasm_streaming/http/tests/wasm_streaming/README.txt new file mode 100644 index 0000000..d6444f1 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/enable_wasm_streaming/http/tests/wasm_streaming/README.txt
@@ -0,0 +1 @@ +Tests that depend on --enable-features=WebAssemblyStreaming
diff --git a/third_party/WebKit/Source/bindings/core/v8/DOMWrapperWorldTest.cpp b/third_party/WebKit/Source/bindings/core/v8/DOMWrapperWorldTest.cpp index 547b38d..90492eb 100644 --- a/third_party/WebKit/Source/bindings/core/v8/DOMWrapperWorldTest.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/DOMWrapperWorldTest.cpp
@@ -63,7 +63,7 @@ Vector<RefPtr<DOMWrapperWorld>> worlds = CreateWorlds(thread->GetIsolate()); DOMWrapperWorld::AllWorldsInCurrentThread(retrieved_worlds); EXPECT_EQ(worlds.size(), retrieved_worlds.size()); - retrieved_worlds.Clear(); + retrieved_worlds.clear(); // Dispose of the last world. worlds.pop_back(); @@ -75,7 +75,7 @@ if (world->IsWorkerWorld()) world->Dispose(); } - worlds.Clear(); + worlds.clear(); thread->Shutdown(); main_thread_task_runner->PostTask(BLINK_FROM_HERE, @@ -91,7 +91,7 @@ DOMWrapperWorld::AllWorldsInCurrentThread(retrieved_worlds); EXPECT_EQ(1u, retrieved_worlds.size()); EXPECT_TRUE(retrieved_worlds[0]->IsMainWorld()); - retrieved_worlds.Clear(); + retrieved_worlds.clear(); // Create isolated worlds and verify them. V8TestingScope scope; @@ -104,11 +104,11 @@ // Create other worlds and verify them. Vector<RefPtr<DOMWrapperWorld>> worlds = CreateWorlds(scope.GetIsolate()); EXPECT_TRUE(DOMWrapperWorld::NonMainWorldsExistInMainThread()); - retrieved_worlds.Clear(); + retrieved_worlds.clear(); DOMWrapperWorld::AllWorldsInCurrentThread(retrieved_worlds); EXPECT_EQ(isolated_worlds.size() + worlds.size() + 1, retrieved_worlds.size()); - retrieved_worlds.Clear(); + retrieved_worlds.clear(); // Start a worker thread and create worlds on that. std::unique_ptr<WorkerBackingThread> thread = @@ -126,21 +126,21 @@ DOMWrapperWorld::AllWorldsInCurrentThread(retrieved_worlds); EXPECT_EQ(isolated_worlds.size() + worlds.size() + 1, retrieved_worlds.size()); - retrieved_worlds.Clear(); + retrieved_worlds.clear(); // Dispose of the isolated worlds. - isolated_worlds.Clear(); + isolated_worlds.clear(); EXPECT_TRUE(DOMWrapperWorld::NonMainWorldsExistInMainThread()); DOMWrapperWorld::AllWorldsInCurrentThread(retrieved_worlds); EXPECT_EQ(worlds.size() + 1, retrieved_worlds.size()); - retrieved_worlds.Clear(); + retrieved_worlds.clear(); // Dispose of the other worlds. for (RefPtr<DOMWrapperWorld>& world : worlds) { if (world->IsWorkerWorld()) world->Dispose(); } - worlds.Clear(); + worlds.clear(); EXPECT_FALSE(DOMWrapperWorld::NonMainWorldsExistInMainThread()); DOMWrapperWorld::AllWorldsInCurrentThread(retrieved_worlds); EXPECT_EQ(1u, retrieved_worlds.size());
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptPromise.cpp b/third_party/WebKit/Source/bindings/core/v8/ScriptPromise.cpp index 088561f..405c749 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptPromise.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptPromise.cpp
@@ -153,7 +153,7 @@ void MarkPromiseSettled() { DCHECK(!is_settled_); is_settled_ = true; - values_.Clear(); + values_.clear(); } size_t number_of_pending_promises_;
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptPromisePropertyBase.cpp b/third_party/WebKit/Source/bindings/core/v8/ScriptPromisePropertyBase.cpp index c41f73c..3d19054 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptPromisePropertyBase.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptPromisePropertyBase.cpp
@@ -165,7 +165,7 @@ PromiseSymbol().Set(wrapper, v8::Undefined(isolate_)); } } - wrappers_.Clear(); + wrappers_.clear(); } void ScriptPromisePropertyBase::CheckThis() {
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptWrappableVisitor.cpp b/third_party/WebKit/Source/bindings/core/v8/ScriptWrappableVisitor.cpp index 4b9ee0f..a46ffa2 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptWrappableVisitor.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptWrappableVisitor.cpp
@@ -90,7 +90,7 @@ header->UnmarkWrapperHeader(); } - headers_to_unmark_.Clear(); + headers_to_unmark_.clear(); marking_deque_.Clear(); verifier_deque_.Clear(); should_cleanup_ = false;
diff --git a/third_party/WebKit/Source/bindings/core/v8/TraceWrapperMember.h b/third_party/WebKit/Source/bindings/core/v8/TraceWrapperMember.h index f62fd0161..79833c33 100644 --- a/third_party/WebKit/Source/bindings/core/v8/TraceWrapperMember.h +++ b/third_party/WebKit/Source/bindings/core/v8/TraceWrapperMember.h
@@ -103,12 +103,12 @@ for (auto item : a) { temp.push_back(TraceWrapperMember<T>(parent_for_b, item.Get())); } - a.Clear(); + a.clear(); a.ReserveCapacity(b.size()); for (auto item : b) { a.push_back(TraceWrapperMember<T>(parent_for_a, item.Get())); } - b.Clear(); + b.clear(); b.ReserveCapacity(temp.size()); for (auto item : temp) { b.push_back(TraceWrapperMember<T>(parent_for_b, item.Get())); @@ -130,12 +130,12 @@ for (auto item : a) { temp.push_back(TraceWrapperMember<T>(item.Parent(), item.Get())); } - a.Clear(); + a.clear(); a.ReserveCapacity(b.size()); for (auto item : b) { a.push_back(TraceWrapperMember<T>(parent_for_a, item.Get())); } - b.Clear(); + b.clear(); b.ReserveCapacity(temp.size()); for (auto item : temp) { b.push_back(item.Get());
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8PerIsolateData.cpp b/third_party/WebKit/Source/bindings/core/v8/V8PerIsolateData.cpp index dcb8c84..6874a66 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8PerIsolateData.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8PerIsolateData.cpp
@@ -283,7 +283,7 @@ } void V8PerIsolateData::ClearEndOfScopeTasks() { - end_of_scope_tasks_.Clear(); + end_of_scope_tasks_.clear(); } void V8PerIsolateData::SetThreadDebugger(
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8PersistentValueVector.h b/third_party/WebKit/Source/bindings/core/v8/V8PersistentValueVector.h index a6924dae..71e1bf0 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8PersistentValueVector.h +++ b/third_party/WebKit/Source/bindings/core/v8/V8PersistentValueVector.h
@@ -54,7 +54,7 @@ static void ReserveCapacity(Impl* impl, size_t capacity) { impl->ReserveCapacity(capacity); } - static void Clear(Impl* impl) { impl->Clear(); } + static void Clear(Impl* impl) { impl->clear(); } }; template <class ValueType>
diff --git a/third_party/WebKit/Source/bindings/modules/v8/wasm/WasmResponseExtensions.cpp b/third_party/WebKit/Source/bindings/modules/v8/wasm/WasmResponseExtensions.cpp index 790a428..cff5a92 100644 --- a/third_party/WebKit/Source/bindings/modules/v8/wasm/WasmResponseExtensions.cpp +++ b/third_party/WebKit/Source/bindings/modules/v8/wasm/WasmResponseExtensions.cpp
@@ -224,7 +224,9 @@ } // namespace void WasmResponseExtensions::Initialize(v8::Isolate* isolate) { - isolate->SetWasmCompileCallback(WasmCompileOverload); + if (RuntimeEnabledFeatures::webAssemblyStreamingEnabled()) { + isolate->SetWasmCompileCallback(WasmCompileOverload); + } } } // namespace blink
diff --git a/third_party/WebKit/Source/bindings/templates/callback_interface.cpp.tmpl b/third_party/WebKit/Source/bindings/templates/callback_interface.cpp.tmpl index e308643..c417aaa 100644 --- a/third_party/WebKit/Source/bindings/templates/callback_interface.cpp.tmpl +++ b/third_party/WebKit/Source/bindings/templates/callback_interface.cpp.tmpl
@@ -26,8 +26,8 @@ if method.idl_type == 'boolean' else 'return' %}{# void #} ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - DCHECK(!executionContext->IsContextSuspended()); - if (!executionContext || executionContext->IsContextDestroyed()) + if (!executionContext || executionContext->IsContextSuspended() || + executionContext->IsContextDestroyed()) {{return_default}}; if (!m_scriptState->ContextIsValid()) {{return_default}};
diff --git a/third_party/WebKit/Source/bindings/templates/methods.cpp.tmpl b/third_party/WebKit/Source/bindings/templates/methods.cpp.tmpl index 7145333..a113986 100644 --- a/third_party/WebKit/Source/bindings/templates/methods.cpp.tmpl +++ b/third_party/WebKit/Source/bindings/templates/methods.cpp.tmpl
@@ -448,9 +448,9 @@ // so that the serializer can consider the array buffers as // non-transferable and serialize them into the message. ArrayBufferArray transferableArrayBuffers = transferables.array_buffers; - transferables.array_buffers.Clear(); + transferables.array_buffers.clear(); ImageBitmapArray transferableImageBitmaps = transferables.image_bitmaps; - transferables.image_bitmaps.Clear(); + transferables.image_bitmaps.clear(); SerializedScriptValue::SerializeOptions options; options.transferables = &transferables; message = SerializedScriptValue::Serialize(info.GetIsolate(), info[0], options, exceptionState);
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackInterface.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackInterface.cpp index 69ea2fa..7435cec9 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackInterface.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackInterface.cpp
@@ -37,8 +37,8 @@ void V8TestCallbackInterface::voidMethod() { ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - DCHECK(!executionContext->IsContextSuspended()); - if (!executionContext || executionContext->IsContextDestroyed()) + if (!executionContext || executionContext->IsContextSuspended() || + executionContext->IsContextDestroyed()) return; if (!m_scriptState->ContextIsValid()) return; @@ -59,8 +59,8 @@ bool V8TestCallbackInterface::booleanMethod() { ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - DCHECK(!executionContext->IsContextSuspended()); - if (!executionContext || executionContext->IsContextDestroyed()) + if (!executionContext || executionContext->IsContextSuspended() || + executionContext->IsContextDestroyed()) return true; if (!m_scriptState->ContextIsValid()) return true; @@ -84,8 +84,8 @@ void V8TestCallbackInterface::voidMethodBooleanArg(bool boolArg) { ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - DCHECK(!executionContext->IsContextSuspended()); - if (!executionContext || executionContext->IsContextDestroyed()) + if (!executionContext || executionContext->IsContextSuspended() || + executionContext->IsContextDestroyed()) return; if (!m_scriptState->ContextIsValid()) return; @@ -107,8 +107,8 @@ void V8TestCallbackInterface::voidMethodSequenceArg(const HeapVector<Member<TestInterfaceEmpty>>& sequenceArg) { ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - DCHECK(!executionContext->IsContextSuspended()); - if (!executionContext || executionContext->IsContextDestroyed()) + if (!executionContext || executionContext->IsContextSuspended() || + executionContext->IsContextDestroyed()) return; if (!m_scriptState->ContextIsValid()) return; @@ -130,8 +130,8 @@ void V8TestCallbackInterface::voidMethodFloatArg(float floatArg) { ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - DCHECK(!executionContext->IsContextSuspended()); - if (!executionContext || executionContext->IsContextDestroyed()) + if (!executionContext || executionContext->IsContextSuspended() || + executionContext->IsContextDestroyed()) return; if (!m_scriptState->ContextIsValid()) return; @@ -153,8 +153,8 @@ void V8TestCallbackInterface::voidMethodTestInterfaceEmptyArg(TestInterfaceEmpty* testInterfaceEmptyArg) { ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - DCHECK(!executionContext->IsContextSuspended()); - if (!executionContext || executionContext->IsContextDestroyed()) + if (!executionContext || executionContext->IsContextSuspended() || + executionContext->IsContextDestroyed()) return; if (!m_scriptState->ContextIsValid()) return; @@ -176,8 +176,8 @@ void V8TestCallbackInterface::voidMethodTestInterfaceEmptyStringArg(TestInterfaceEmpty* testInterfaceEmptyArg, const String& stringArg) { ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - DCHECK(!executionContext->IsContextSuspended()); - if (!executionContext || executionContext->IsContextDestroyed()) + if (!executionContext || executionContext->IsContextSuspended() || + executionContext->IsContextDestroyed()) return; if (!m_scriptState->ContextIsValid()) return; @@ -200,8 +200,8 @@ void V8TestCallbackInterface::callbackWithThisValueVoidMethodStringArg(ScriptValue thisValue, const String& stringArg) { ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - DCHECK(!executionContext->IsContextSuspended()); - if (!executionContext || executionContext->IsContextDestroyed()) + if (!executionContext || executionContext->IsContextSuspended() || + executionContext->IsContextDestroyed()) return; if (!m_scriptState->ContextIsValid()) return;
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestObject.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestObject.cpp index a641196..ee95987 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestObject.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestObject.cpp
@@ -8258,9 +8258,9 @@ // so that the serializer can consider the array buffers as // non-transferable and serialize them into the message. ArrayBufferArray transferableArrayBuffers = transferables.array_buffers; - transferables.array_buffers.Clear(); + transferables.array_buffers.clear(); ImageBitmapArray transferableImageBitmaps = transferables.image_bitmaps; - transferables.image_bitmaps.Clear(); + transferables.image_bitmaps.clear(); SerializedScriptValue::SerializeOptions options; options.transferables = &transferables; message = SerializedScriptValue::Serialize(info.GetIsolate(), info[0], options, exceptionState);
diff --git a/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.cpp.tmpl b/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.cpp.tmpl index 2eac3550..07ef096 100644 --- a/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.cpp.tmpl +++ b/third_party/WebKit/Source/build/scripts/templates/StyleBuilderFunctions.cpp.tmpl
@@ -99,7 +99,7 @@ {% set vector = attribute + "List()" %} {{declare_initial_function(property_id)}} { CSS{{animation}}Data& data = state.Style()->Access{{animation}}s(); - data.{{vector}}.Clear(); + data.{{vector}}.clear(); data.{{vector}}.push_back(CSS{{animation}}Data::Initial{{attribute}}()); } @@ -113,7 +113,7 @@ {{declare_value_function(property_id)}} { CSS{{animation}}Data& data = state.Style()->Access{{animation}}s(); - data.{{vector}}.Clear(); + data.{{vector}}.clear(); for (auto& listValue : ToCSSValueList(value)) data.{{vector}}.push_back(CSSToStyleMap::MapAnimation{{attribute}}(*listValue)); }
diff --git a/third_party/WebKit/Source/core/animation/ImageListPropertyFunctions.h b/third_party/WebKit/Source/core/animation/ImageListPropertyFunctions.h index 3af020d..fb7a8f8de 100644 --- a/third_party/WebKit/Source/core/animation/ImageListPropertyFunctions.h +++ b/third_party/WebKit/Source/core/animation/ImageListPropertyFunctions.h
@@ -16,7 +16,7 @@ class ImageListPropertyFunctions { public: static void GetInitialImageList(CSSPropertyID, StyleImageList& result) { - result.Clear(); + result.clear(); } static void GetImageList(CSSPropertyID property, @@ -35,7 +35,7 @@ return; } - result.Clear(); + result.clear(); while (fill_layer) { result.push_back(fill_layer->GetImage()); fill_layer = fill_layer->Next();
diff --git a/third_party/WebKit/Source/core/animation/InertEffect.cpp b/third_party/WebKit/Source/core/animation/InertEffect.cpp index ccab3725..d25aee2f 100644 --- a/third_party/WebKit/Source/core/animation/InertEffect.cpp +++ b/third_party/WebKit/Source/core/animation/InertEffect.cpp
@@ -53,7 +53,7 @@ void InertEffect::Sample(Vector<RefPtr<Interpolation>>& result) const { UpdateInheritedTime(inherited_time_, kTimingUpdateOnDemand); if (!IsInEffect()) { - result.Clear(); + result.clear(); return; }
diff --git a/third_party/WebKit/Source/core/animation/InterpolationEffect.h b/third_party/WebKit/Source/core/animation/InterpolationEffect.h index e142b49..176ed8a9 100644 --- a/third_party/WebKit/Source/core/animation/InterpolationEffect.h +++ b/third_party/WebKit/Source/core/animation/InterpolationEffect.h
@@ -27,7 +27,7 @@ void Clear() { is_populated_ = false; - interpolations_.Clear(); + interpolations_.clear(); } void GetActiveInterpolations(double fraction,
diff --git a/third_party/WebKit/Source/core/animation/InvalidatableInterpolation.cpp b/third_party/WebKit/Source/core/animation/InvalidatableInterpolation.cpp index 78d6d2c2..9a3569e5 100644 --- a/third_party/WebKit/Source/core/animation/InvalidatableInterpolation.cpp +++ b/third_party/WebKit/Source/core/animation/InvalidatableInterpolation.cpp
@@ -117,7 +117,7 @@ void InvalidatableInterpolation::ClearConversionCache() const { is_conversion_cached_ = false; cached_pair_conversion_.reset(); - conversion_checkers_.Clear(); + conversion_checkers_.clear(); cached_value_.reset(); }
diff --git a/third_party/WebKit/Source/core/animation/KeyframeEffectReadOnly.cpp b/third_party/WebKit/Source/core/animation/KeyframeEffectReadOnly.cpp index 48cb0bae..b1e8454 100644 --- a/third_party/WebKit/Source/core/animation/KeyframeEffectReadOnly.cpp +++ b/third_party/WebKit/Source/core/animation/KeyframeEffectReadOnly.cpp
@@ -321,7 +321,7 @@ CompositorAnimations::CancelAnimationOnCompositor(*target_, *GetAnimation(), compositor_animation_id); } - compositor_animation_ids_.Clear(); + compositor_animation_ids_.clear(); return true; }
diff --git a/third_party/WebKit/Source/core/animation/SampledEffect.cpp b/third_party/WebKit/Source/core/animation/SampledEffect.cpp index f4bf7d6..b6e30133 100644 --- a/third_party/WebKit/Source/core/animation/SampledEffect.cpp +++ b/third_party/WebKit/Source/core/animation/SampledEffect.cpp
@@ -13,7 +13,7 @@ void SampledEffect::Clear() { effect_ = nullptr; - interpolations_.Clear(); + interpolations_.clear(); } bool SampledEffect::WillNeverChange() const {
diff --git a/third_party/WebKit/Source/core/animation/css/CSSAnimationUpdate.h b/third_party/WebKit/Source/core/animation/css/CSSAnimationUpdate.h index 2854d0b..c406856 100644 --- a/third_party/WebKit/Source/core/animation/css/CSSAnimationUpdate.h +++ b/third_party/WebKit/Source/core/animation/css/CSSAnimationUpdate.h
@@ -119,17 +119,17 @@ } void Clear() { - new_animations_.Clear(); - animations_with_updates_.Clear(); + new_animations_.clear(); + animations_with_updates_.clear(); new_transitions_.Clear(); active_interpolations_for_animations_.Clear(); active_interpolations_for_custom_transitions_.Clear(); active_interpolations_for_standard_transitions_.Clear(); - cancelled_animation_indices_.Clear(); - animation_indices_with_pause_toggled_.Clear(); + cancelled_animation_indices_.clear(); + animation_indices_with_pause_toggled_.clear(); cancelled_transitions_.Clear(); finished_transitions_.Clear(); - updated_compositor_keyframes_.Clear(); + updated_compositor_keyframes_.clear(); } void StartAnimation(const AtomicString& animation_name,
diff --git a/third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp b/third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp index 3dacad96..a837bd2c 100644 --- a/third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp +++ b/third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp
@@ -930,7 +930,7 @@ entry.value.animation->Update(kTimingUpdateOnDemand); } - running_animations_.Clear(); + running_animations_.clear(); transitions_.Clear(); ClearPendingUpdate(); }
diff --git a/third_party/WebKit/Source/core/clipboard/DataObject.cpp b/third_party/WebKit/Source/core/clipboard/DataObject.cpp index 0c578e2..3a28e5b0 100644 --- a/third_party/WebKit/Source/core/clipboard/DataObject.cpp +++ b/third_party/WebKit/Source/core/clipboard/DataObject.cpp
@@ -91,7 +91,7 @@ } void DataObject::ClearAll() { - item_list_.Clear(); + item_list_.clear(); } DataObjectItem* DataObject::Add(const String& data, const String& type) {
diff --git a/third_party/WebKit/Source/core/css/CSSSelectorList.cpp b/third_party/WebKit/Source/core/css/CSSSelectorList.cpp index 0375db27..cd0c10f 100644 --- a/third_party/WebKit/Source/core/css/CSSSelectorList.cpp +++ b/third_party/WebKit/Source/core/css/CSSSelectorList.cpp
@@ -89,7 +89,7 @@ } DCHECK_EQ(flattened_size, array_index); list.selector_array_[array_index - 1].SetLastInSelectorList(); - selector_vector.Clear(); + selector_vector.clear(); return list; }
diff --git a/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp b/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp index 7a125fe..5e4232d 100644 --- a/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp +++ b/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp
@@ -212,8 +212,8 @@ } bool CSSStyleSheet::MatchesMediaQueries(const MediaQueryEvaluator& evaluator) { - viewport_dependent_media_query_results_.Clear(); - device_dependent_media_query_results_.Clear(); + viewport_dependent_media_query_results_.clear(); + device_dependent_media_query_results_.clear(); if (!media_queries_) return true; @@ -433,7 +433,7 @@ } void CSSStyleSheet::SetText(const String& text) { - child_rule_cssom_wrappers_.Clear(); + child_rule_cssom_wrappers_.clear(); CSSStyleSheet::RuleMutationScope mutation_scope(this); contents_->ClearRules();
diff --git a/third_party/WebKit/Source/core/css/CSSSyntaxDescriptor.cpp b/third_party/WebKit/Source/core/css/CSSSyntaxDescriptor.cpp index 1c835708..d96dfaf 100644 --- a/third_party/WebKit/Source/core/css/CSSSyntaxDescriptor.cpp +++ b/third_party/WebKit/Source/core/css/CSSSyntaxDescriptor.cpp
@@ -117,7 +117,7 @@ } if (!success) { - syntax_components_.Clear(); + syntax_components_.clear(); return; } @@ -128,7 +128,7 @@ } while (ConsumeCharacterAndWhitespace(input, '|', offset)); if (offset != input.length()) - syntax_components_.Clear(); + syntax_components_.clear(); } const CSSValue* ConsumeSingleType(const CSSSyntaxComponent& syntax,
diff --git a/third_party/WebKit/Source/core/css/ElementRuleCollector.cpp b/third_party/WebKit/Source/core/css/ElementRuleCollector.cpp index 34ecd4a..9e177d7 100644 --- a/third_party/WebKit/Source/core/css/ElementRuleCollector.cpp +++ b/third_party/WebKit/Source/core/css/ElementRuleCollector.cpp
@@ -79,7 +79,7 @@ } void ElementRuleCollector::ClearMatchedRules() { - matched_rules_.Clear(); + matched_rules_.clear(); } inline StyleRuleList* ElementRuleCollector::EnsureStyleRuleList() {
diff --git a/third_party/WebKit/Source/core/css/FontFaceSet.cpp b/third_party/WebKit/Source/core/css/FontFaceSet.cpp index 336455b..be76c77 100644 --- a/third_party/WebKit/Source/core/css/FontFaceSet.cpp +++ b/third_party/WebKit/Source/core/css/FontFaceSet.cpp
@@ -362,11 +362,11 @@ FontFaceSetLoadEvent* error_event = nullptr; done_event = FontFaceSetLoadEvent::CreateForFontFaces( EventTypeNames::loadingdone, loaded_fonts_); - loaded_fonts_.Clear(); + loaded_fonts_.clear(); if (!failed_fonts_.IsEmpty()) { error_event = FontFaceSetLoadEvent::CreateForFontFaces( EventTypeNames::loadingerror, failed_fonts_); - failed_fonts_.Clear(); + failed_fonts_.clear(); } is_loading_ = false; DispatchEvent(done_event);
diff --git a/third_party/WebKit/Source/core/css/RuleFeature.cpp b/third_party/WebKit/Source/core/css/RuleFeature.cpp index c1a366a..d1979af 100644 --- a/third_party/WebKit/Source/core/css/RuleFeature.cpp +++ b/third_party/WebKit/Source/core/css/RuleFeature.cpp
@@ -970,8 +970,8 @@ void RuleFeatureSet::Clear() { CHECK(is_alive_); - sibling_rules_.Clear(); - uncommon_attribute_rules_.Clear(); + sibling_rules_.clear(); + uncommon_attribute_rules_.clear(); metadata_.Clear(); class_invalidation_sets_.Clear(); attribute_invalidation_sets_.Clear(); @@ -979,8 +979,8 @@ pseudo_invalidation_sets_.Clear(); universal_sibling_invalidation_set_.Clear(); nth_invalidation_set_.Clear(); - viewport_dependent_media_query_results_.Clear(); - device_dependent_media_query_results_.Clear(); + viewport_dependent_media_query_results_.clear(); + device_dependent_media_query_results_.clear(); } void RuleFeatureSet::CollectInvalidationSetsForClass(
diff --git a/third_party/WebKit/Source/core/css/RuleFeatureSetTest.cpp b/third_party/WebKit/Source/core/css/RuleFeatureSetTest.cpp index afcdc2d..eede973 100644 --- a/third_party/WebKit/Source/core/css/RuleFeatureSetTest.cpp +++ b/third_party/WebKit/Source/core/css/RuleFeatureSetTest.cpp
@@ -439,7 +439,7 @@ EXPECT_EQ(RuleFeatureSet::kSelectorMayMatch, CollectFeatures(".a .b")); - invalidation_lists.descendants.Clear(); + invalidation_lists.descendants.clear(); CollectInvalidationSetsForClass(invalidation_lists, "a"); ExpectClassesInvalidation("b", "c", invalidation_lists.descendants); }
diff --git a/third_party/WebKit/Source/core/css/StylePropertySet.cpp b/third_party/WebKit/Source/core/css/StylePropertySet.cpp index cfed37c7..f1ea500 100644 --- a/third_party/WebKit/Source/core/css/StylePropertySet.cpp +++ b/third_party/WebKit/Source/core/css/StylePropertySet.cpp
@@ -384,7 +384,7 @@ void MutableStylePropertySet::ParseDeclarationList( const String& style_declaration, StyleSheetContents* context_style_sheet) { - property_vector_.Clear(); + property_vector_.clear(); CSSParserContext* context; if (context_style_sheet) { @@ -443,7 +443,7 @@ } void MutableStylePropertySet::Clear() { - property_vector_.Clear(); + property_vector_.clear(); } inline bool ContainsId(const CSSPropertyID* set,
diff --git a/third_party/WebKit/Source/core/css/StyleSheetContents.cpp b/third_party/WebKit/Source/core/css/StyleSheetContents.cpp index fed816f..4be8e11 100644 --- a/third_party/WebKit/Source/core/css/StyleSheetContents.cpp +++ b/third_party/WebKit/Source/core/css/StyleSheetContents.cpp
@@ -223,9 +223,9 @@ DCHECK_EQ(import_rules_.at(i)->ParentStyleSheet(), this); import_rules_[i]->ClearParentStyleSheet(); } - import_rules_.Clear(); - namespace_rules_.Clear(); - child_rules_.Clear(); + import_rules_.clear(); + namespace_rules_.clear(); + child_rules_.clear(); } bool StyleSheetContents::WrapperInsertRule(StyleRuleBase* rule,
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserImpl.cpp b/third_party/WebKit/Source/core/css/parser/CSSParserImpl.cpp index d35ae85..3d358ff7 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSParserImpl.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSParserImpl.cpp
@@ -147,7 +147,7 @@ ImmutableStylePropertySet* result = ImmutableStylePropertySet::Create( results.Data() + unused_entries, results.size() - unused_entries, mode); - parsed_properties.Clear(); + parsed_properties.clear(); return result; } @@ -331,7 +331,7 @@ DCHECK(parsed_properties_.IsEmpty()); ConsumeDeclaration(range, StyleRule::kStyle); bool result = !parsed_properties_.IsEmpty(); - parsed_properties_.Clear(); + parsed_properties_.clear(); return result; }
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.cpp b/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.cpp index dcc0609..f44719cb 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.cpp
@@ -1273,7 +1273,7 @@ } else { if (!AddCSSPaintArgument(argument_tokens, &variable_data)) return nullptr; - argument_tokens.Clear(); + argument_tokens.clear(); if (!ConsumeCommaIncludingWhitespace(args)) return nullptr; }
diff --git a/third_party/WebKit/Source/core/css/parser/MediaQueryParser.cpp b/third_party/WebKit/Source/core/css/parser/MediaQueryParser.cpp index 6dfbe9d1..96a40f2 100644 --- a/third_party/WebKit/Source/core/css/parser/MediaQueryParser.cpp +++ b/third_party/WebKit/Source/core/css/parser/MediaQueryParser.cpp
@@ -253,8 +253,8 @@ media_type_ = MediaTypeNames::all; media_type_set_ = false; media_feature_ = String(); - value_list_.Clear(); - expressions_.Clear(); + value_list_.clear(); + expressions_.clear(); } MediaQuery* MediaQueryData::TakeMediaQuery() { @@ -269,7 +269,7 @@ MediaQueryExp::CreateIfValid(media_feature_, value_list_); bool is_valid = !!expression; expressions_.push_back(expression); - value_list_.Clear(); + value_list_.clear(); return is_valid; }
diff --git a/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp b/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp index 3222854..f8ed4f59 100644 --- a/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp +++ b/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp
@@ -49,7 +49,7 @@ } void CachedMatchedProperties::Clear() { - matched_properties.Clear(); + matched_properties.clear(); computed_style = nullptr; parent_computed_style = nullptr; }
diff --git a/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp b/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp index 113d59b9..56922e0 100644 --- a/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp +++ b/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp
@@ -128,9 +128,9 @@ } void ScopedStyleResolver::ResetAuthorStyle() { - author_style_sheets_.Clear(); - viewport_dependent_media_query_results_.Clear(); - device_dependent_media_query_results_.Clear(); + author_style_sheets_.clear(); + viewport_dependent_media_query_results_.clear(); + device_dependent_media_query_results_.clear(); keyframes_rule_map_.Clear(); tree_boundary_crossing_rule_set_ = nullptr; has_deep_or_shadow_selector_ = false;
diff --git a/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp b/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp index b962b37..c3614055b 100644 --- a/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp +++ b/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp
@@ -58,8 +58,8 @@ } void ViewportStyleResolver::Reset() { - viewport_dependent_media_query_results_.Clear(); - device_dependent_media_query_results_.Clear(); + viewport_dependent_media_query_results_.clear(); + device_dependent_media_query_results_.clear(); property_set_ = nullptr; has_author_style_ = false; has_viewport_units_ = false;
diff --git a/third_party/WebKit/Source/core/dom/CSSSelectorWatch.cpp b/third_party/WebKit/Source/core/dom/CSSSelectorWatch.cpp index 6c8dd8b..4bde989 100644 --- a/third_party/WebKit/Source/core/dom/CSSSelectorWatch.cpp +++ b/third_party/WebKit/Source/core/dom/CSSSelectorWatch.cpp
@@ -146,7 +146,7 @@ } void CSSSelectorWatch::WatchCSSSelectors(const Vector<String>& selectors) { - watched_callback_selectors_.Clear(); + watched_callback_selectors_.clear(); StylePropertySet* callback_property_set = ImmutableStylePropertySet::Create(nullptr, 0, kUASheetMode);
diff --git a/third_party/WebKit/Source/core/dom/CSSSelectorWatchTest.cpp b/third_party/WebKit/Source/core/dom/CSSSelectorWatchTest.cpp index 21530d9..7dd6823 100644 --- a/third_party/WebKit/Source/core/dom/CSSSelectorWatchTest.cpp +++ b/third_party/WebKit/Source/core/dom/CSSSelectorWatchTest.cpp
@@ -58,7 +58,7 @@ GetDocument().View()->UpdateAllLifecyclePhases(); - selectors.Clear(); + selectors.clear(); selectors.push_back(".b"); selectors.push_back(".c"); selectors.push_back("#nomatch");
diff --git a/third_party/WebKit/Source/core/dom/DOMStringList.h b/third_party/WebKit/Source/core/dom/DOMStringList.h index c21cd4d..a5bd6054 100644 --- a/third_party/WebKit/Source/core/dom/DOMStringList.h +++ b/third_party/WebKit/Source/core/dom/DOMStringList.h
@@ -45,7 +45,7 @@ static DOMStringList* Create() { return new DOMStringList(); } bool IsEmpty() const { return strings_.IsEmpty(); } - void Clear() { strings_.Clear(); } + void clear() { strings_.clear(); } void Append(const String& string) { strings_.push_back(string); } void Sort();
diff --git a/third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp b/third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp index 96afb95..cbe849e 100644 --- a/third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp +++ b/third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp
@@ -88,7 +88,7 @@ DCHECK(entry->count); entry->element = nullptr; entry->count++; - entry->ordered_list.Clear(); + entry->ordered_list.clear(); } void DocumentOrderedMap::Remove(const AtomicString& key, Element* element) { @@ -112,7 +112,7 @@ entry->ordered_list.size() > 1 ? entry->ordered_list[1] : nullptr; } entry->count--; - entry->ordered_list.Clear(); + entry->ordered_list.clear(); } }
diff --git a/third_party/WebKit/Source/core/dom/ExecutionContext.cpp b/third_party/WebKit/Source/core/dom/ExecutionContext.cpp index 66d65e8..4778d3d 100644 --- a/third_party/WebKit/Source/core/dom/ExecutionContext.cpp +++ b/third_party/WebKit/Source/core/dom/ExecutionContext.cpp
@@ -125,7 +125,7 @@ return; for (ErrorEvent* e : pending_exceptions_) ExceptionThrown(e); - pending_exceptions_.Clear(); + pending_exceptions_.clear(); } bool ExecutionContext::DispatchErrorEventInternal(
diff --git a/third_party/WebKit/Source/core/dom/FrameRequestCallbackCollection.cpp b/third_party/WebKit/Source/core/dom/FrameRequestCallbackCollection.cpp index fa5d8a88..9c8c1d88 100644 --- a/third_party/WebKit/Source/core/dom/FrameRequestCallbackCollection.cpp +++ b/third_party/WebKit/Source/core/dom/FrameRequestCallbackCollection.cpp
@@ -78,7 +78,7 @@ } } - callbacks_to_invoke_.Clear(); + callbacks_to_invoke_.clear(); } DEFINE_TRACE(FrameRequestCallbackCollection) {
diff --git a/third_party/WebKit/Source/core/dom/Fullscreen.cpp b/third_party/WebKit/Source/core/dom/Fullscreen.cpp index f61650b9..7df6c27 100644 --- a/third_party/WebKit/Source/core/dom/Fullscreen.cpp +++ b/third_party/WebKit/Source/core/dom/Fullscreen.cpp
@@ -358,7 +358,7 @@ full_screen_layout_object_->Destroy(); current_full_screen_element_ = nullptr; - fullscreen_element_stack_.Clear(); + fullscreen_element_stack_.clear(); } // https://fullscreen.spec.whatwg.org/#dom-element-requestfullscreen @@ -849,7 +849,7 @@ if (fullscreen_element_stack_.IsEmpty()) return; - fullscreen_element_stack_.Clear(); + fullscreen_element_stack_.clear(); SetNeedsPaintPropertyUpdate(GetDocument()); }
diff --git a/third_party/WebKit/Source/core/dom/IntersectionObserver.cpp b/third_party/WebKit/Source/core/dom/IntersectionObserver.cpp index d64351d..aa1cc50 100644 --- a/third_party/WebKit/Source/core/dom/IntersectionObserver.cpp +++ b/third_party/WebKit/Source/core/dom/IntersectionObserver.cpp
@@ -281,7 +281,7 @@ for (auto& observation : observations_) observation->Disconnect(); observations_.clear(); - entries_.Clear(); + entries_.clear(); } HeapVector<Member<IntersectionObserverEntry>> IntersectionObserver::takeRecords(
diff --git a/third_party/WebKit/Source/core/dom/ModuleMapTest.cpp b/third_party/WebKit/Source/core/dom/ModuleMapTest.cpp index 87adbf2..eb3f00f3 100644 --- a/third_party/WebKit/Source/core/dom/ModuleMapTest.cpp +++ b/third_party/WebKit/Source/core/dom/ModuleMapTest.cpp
@@ -140,7 +140,7 @@ WrapPersistent(test_request->client.Get()), WrapPersistent(module_script))); } - test_requests_.Clear(); + test_requests_.clear(); } class ModuleMapTest : public testing::Test {
diff --git a/third_party/WebKit/Source/core/dom/MutationObserver.cpp b/third_party/WebKit/Source/core/dom/MutationObserver.cpp index 2ef6493..fce9101 100644 --- a/third_party/WebKit/Source/core/dom/MutationObserver.cpp +++ b/third_party/WebKit/Source/core/dom/MutationObserver.cpp
@@ -143,7 +143,7 @@ void MutationObserver::disconnect() { CancelInspectorAsyncTasks(); - records_.Clear(); + records_.clear(); MutationObserverRegistrationSet registrations(registrations_); for (auto& registration : registrations) { // The registration may be already unregistered while iteration.
diff --git a/third_party/WebKit/Source/core/dom/ResizeObserver.cpp b/third_party/WebKit/Source/core/dom/ResizeObserver.cpp index 437d429..80d45a0 100644 --- a/third_party/WebKit/Source/core/dom/ResizeObserver.cpp +++ b/third_party/WebKit/Source/core/dom/ResizeObserver.cpp
@@ -105,7 +105,7 @@ } void ResizeObserver::ClearObservations() { - active_observations_.Clear(); + active_observations_.clear(); skipped_observations_ = false; }
diff --git a/third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp b/third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp index cf19595..c1f5deb 100644 --- a/third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp +++ b/third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp
@@ -36,8 +36,8 @@ StyleSheetCollection::StyleSheetCollection() {} void StyleSheetCollection::Dispose() { - style_sheets_for_style_sheet_list_.Clear(); - active_author_style_sheets_.Clear(); + style_sheets_for_style_sheet_list_.clear(); + active_author_style_sheets_.clear(); } void StyleSheetCollection::Swap(StyleSheetCollection& other) {
diff --git a/third_party/WebKit/Source/core/dom/TaskRunnerHelper.cpp b/third_party/WebKit/Source/core/dom/TaskRunnerHelper.cpp index 1a1cd88..3cd58de 100644 --- a/third_party/WebKit/Source/core/dom/TaskRunnerHelper.cpp +++ b/third_party/WebKit/Source/core/dom/TaskRunnerHelper.cpp
@@ -29,24 +29,24 @@ // TODO(nhiroki): Throttle them again after we're convinced that it's safe // or provide a mechanism that web pages can opt-out it if throttling is not // desirable. - case TaskType::kDOMManipulation: case TaskType::kDatabaseAccess: - case TaskType::kFileReading: - case TaskType::kHistoryTraversal: - case TaskType::kPerformanceTimeline: - case TaskType::kPostedMessage: - case TaskType::kRemoteEvent: - case TaskType::kSensor: - case TaskType::kUnshippedPortMessage: - case TaskType::kWebSocket: return frame ? frame->FrameScheduler()->SuspendableTaskRunner() : Platform::Current()->CurrentThread()->GetWebTaskRunner(); + case TaskType::kDOMManipulation: case TaskType::kUserInteraction: + case TaskType::kHistoryTraversal: case TaskType::kEmbed: case TaskType::kMediaElementEvent: case TaskType::kCanvasBlobSerialization: + case TaskType::kRemoteEvent: + case TaskType::kWebSocket: case TaskType::kMicrotask: + case TaskType::kPostedMessage: + case TaskType::kUnshippedPortMessage: + case TaskType::kFileReading: case TaskType::kPresentation: + case TaskType::kSensor: + case TaskType::kPerformanceTimeline: case TaskType::kWebGL: case TaskType::kUnspecedTimer: case TaskType::kMiscPlatformAPI:
diff --git a/third_party/WebKit/Source/core/dom/URLSearchParams.cpp b/third_party/WebKit/Source/core/dom/URLSearchParams.cpp index 358727d..d6c21711 100644 --- a/third_party/WebKit/Source/core/dom/URLSearchParams.cpp +++ b/third_party/WebKit/Source/core/dom/URLSearchParams.cpp
@@ -119,7 +119,7 @@ } void URLSearchParams::SetInput(const String& query_string) { - params_.Clear(); + params_.clear(); size_t start = 0; size_t query_string_length = query_string.length();
diff --git a/third_party/WebKit/Source/core/dom/custom/CustomElementReactionStack.cpp b/third_party/WebKit/Source/core/dom/custom/CustomElementReactionStack.cpp index 2c3f1f8..6f27f84 100644 --- a/third_party/WebKit/Source/core/dom/custom/CustomElementReactionStack.cpp +++ b/third_party/WebKit/Source/core/dom/custom/CustomElementReactionStack.cpp
@@ -110,7 +110,7 @@ void CustomElementReactionStack::InvokeBackupQueue() { DCHECK(IsMainThread()); InvokeReactions(*backup_queue_); - backup_queue_->Clear(); + backup_queue_->clear(); } CustomElementReactionStack& CustomElementReactionStack::Current() {
diff --git a/third_party/WebKit/Source/core/dom/custom/CustomElementRegistryTest.cpp b/third_party/WebKit/Source/core/dom/custom/CustomElementRegistryTest.cpp index 81643b5..22e59cd 100644 --- a/third_party/WebKit/Source/core/dom/custom/CustomElementRegistryTest.cpp +++ b/third_party/WebKit/Source/core/dom/custom/CustomElementRegistryTest.cpp
@@ -216,8 +216,8 @@ HeapVector<Member<Adopted>> adopted_; void Clear() { - logs_.Clear(); - attribute_changed_.Clear(); + logs_.clear(); + attribute_changed_.clear(); } bool RunConstructor(Element* element) override {
diff --git a/third_party/WebKit/Source/core/dom/custom/V0CustomElementMicrotaskDispatcher.cpp b/third_party/WebKit/Source/core/dom/custom/V0CustomElementMicrotaskDispatcher.cpp index c99b31f..41bb53e9 100644 --- a/third_party/WebKit/Source/core/dom/custom/V0CustomElementMicrotaskDispatcher.cpp +++ b/third_party/WebKit/Source/core/dom/custom/V0CustomElementMicrotaskDispatcher.cpp
@@ -69,7 +69,7 @@ element->ProcessInElementQueue(kMicrotaskQueueId); } - elements_.Clear(); + elements_.clear(); V0CustomElementScheduler::MicrotaskDispatcherDidFinish(); phase_ = kQuiescent; }
diff --git a/third_party/WebKit/Source/core/dom/shadow/DistributedNodes.h b/third_party/WebKit/Source/core/dom/shadow/DistributedNodes.h index fb518cd6..566013ba 100644 --- a/third_party/WebKit/Source/core/dom/shadow/DistributedNodes.h +++ b/third_party/WebKit/Source/core/dom/shadow/DistributedNodes.h
@@ -52,7 +52,7 @@ void Append(Node*); void Clear() { - nodes_.Clear(); + nodes_.clear(); indices_.Clear(); } void ShrinkToFit() { nodes_.ShrinkToFit(); }
diff --git a/third_party/WebKit/Source/core/dom/shadow/ElementShadowV0.cpp b/third_party/WebKit/Source/core/dom/shadow/ElementShadowV0.cpp index 062bd930..da6e80d 100644 --- a/third_party/WebKit/Source/core/dom/shadow/ElementShadowV0.cpp +++ b/third_party/WebKit/Source/core/dom/shadow/ElementShadowV0.cpp
@@ -57,8 +57,8 @@ inline void DistributionPool::Clear() { DetachNonDistributedNodes(); - nodes_.Clear(); - distributed_.Clear(); + nodes_.clear(); + distributed_.clear(); } inline void DistributionPool::PopulateChildren(const ContainerNode& parent) {
diff --git a/third_party/WebKit/Source/core/dom/shadow/ShadowRootRareDataV0.h b/third_party/WebKit/Source/core/dom/shadow/ShadowRootRareDataV0.h index d98e96f..0f5a415 100644 --- a/third_party/WebKit/Source/core/dom/shadow/ShadowRootRareDataV0.h +++ b/third_party/WebKit/Source/core/dom/shadow/ShadowRootRareDataV0.h
@@ -71,7 +71,7 @@ descendant_insertion_points_.Swap(list); } void ClearDescendantInsertionPoints() { - descendant_insertion_points_.Clear(); + descendant_insertion_points_.clear(); } void SetYoungerShadowRoot(ShadowRoot& younger_shadow_root) {
diff --git a/third_party/WebKit/Source/core/dom/shadow/SlotAssignment.cpp b/third_party/WebKit/Source/core/dom/shadow/SlotAssignment.cpp index c119789..76b9ef8 100644 --- a/third_party/WebKit/Source/core/dom/shadow/SlotAssignment.cpp +++ b/third_party/WebKit/Source/core/dom/shadow/SlotAssignment.cpp
@@ -160,7 +160,7 @@ void SlotAssignment::CollectSlots() { DCHECK(needs_collect_slots_); - slots_.Clear(); + slots_.clear(); slots_.ReserveCapacity(slot_count_); for (HTMLSlotElement& slot :
diff --git a/third_party/WebKit/Source/core/editing/VisibleUnits.cpp b/third_party/WebKit/Source/core/editing/VisibleUnits.cpp index 23e78e5a..f3dc53a 100644 --- a/third_party/WebKit/Source/core/editing/VisibleUnits.cpp +++ b/third_party/WebKit/Source/core/editing/VisibleUnits.cpp
@@ -454,7 +454,7 @@ const RootInlineBox* root) { if (root_inline_box_ != root) { root_inline_box_ = root; - leaf_boxes_.Clear(); + leaf_boxes_.clear(); root->CollectLeafBoxesInLogicalOrder(leaf_boxes_); } return leaf_boxes_; @@ -574,7 +574,7 @@ visible_position, text_box, previous_box_in_different_block, leaf_boxes); int len = 0; - string.Clear(); + string.clear(); if (previous_box) { previous_box_length = previous_box->Len(); previous_box->GetLineLayoutItem().GetText().AppendTo( @@ -602,7 +602,7 @@ visible_position, text_box, next_box_in_different_block, leaf_boxes); int len = 0; - string.Clear(); + string.clear(); text_box->GetLineLayoutItem().GetText().AppendTo(string, text_box->Start(), text_box->Len()); len += text_box->Len();
diff --git a/third_party/WebKit/Source/core/editing/commands/InsertParagraphSeparatorCommand.cpp b/third_party/WebKit/Source/core/editing/commands/InsertParagraphSeparatorCommand.cpp index e2345c60..589c5f7 100644 --- a/third_party/WebKit/Source/core/editing/commands/InsertParagraphSeparatorCommand.cpp +++ b/third_party/WebKit/Source/core/editing/commands/InsertParagraphSeparatorCommand.cpp
@@ -136,7 +136,7 @@ const Node* insertion_node, Element* outer_block, HeapVector<Member<Element>>& ancestors) { - ancestors.Clear(); + ancestors.clear(); // Build up list of ancestors elements between the insertion node and the // outer block.
diff --git a/third_party/WebKit/Source/core/editing/iterators/TextIterator.cpp b/third_party/WebKit/Source/core/editing/iterators/TextIterator.cpp index af8da33f..d3bcf4e 100644 --- a/third_party/WebKit/Source/core/editing/iterators/TextIterator.cpp +++ b/third_party/WebKit/Source/core/editing/iterators/TextIterator.cpp
@@ -640,7 +640,7 @@ // Used when text boxes are out of order (Hebrew/Arabic w/ embeded LTR text) if (layout_object->ContainsReversedText()) { - sorted_text_boxes_.Clear(); + sorted_text_boxes_.clear(); for (InlineTextBox* text_box = layout_object->FirstTextBox(); text_box; text_box = text_box->NextTextBox()) { sorted_text_boxes_.push_back(text_box); @@ -832,7 +832,7 @@ LayoutObject* first_letter = pseudo_layout_object->SlowFirstChild(); - sorted_text_boxes_.Clear(); + sorted_text_boxes_.clear(); remaining_text_box_ = text_box_; CHECK(first_letter && first_letter->IsText()); first_letter_text_ = ToLayoutText(first_letter);
diff --git a/third_party/WebKit/Source/core/editing/markers/DocumentMarkerController.cpp b/third_party/WebKit/Source/core/editing/markers/DocumentMarkerController.cpp index 7230632..6773d52d 100644 --- a/third_party/WebKit/Source/core/editing/markers/DocumentMarkerController.cpp +++ b/third_party/WebKit/Source/core/editing/markers/DocumentMarkerController.cpp
@@ -673,7 +673,7 @@ continue; } if (marker_types.Contains((*list->begin())->GetType())) { - list->Clear(); + list->clear(); list.Clear(); ++empty_lists_count; needs_repainting = true;
diff --git a/third_party/WebKit/Source/core/events/EventListenerMap.cpp b/third_party/WebKit/Source/core/events/EventListenerMap.cpp index 6e4e3e0..cf54cc80 100644 --- a/third_party/WebKit/Source/core/events/EventListenerMap.cpp +++ b/third_party/WebKit/Source/core/events/EventListenerMap.cpp
@@ -80,7 +80,7 @@ void EventListenerMap::Clear() { CheckNoActiveIterators(); - entries_.Clear(); + entries_.clear(); } Vector<AtomicString> EventListenerMap::EventTypes() const {
diff --git a/third_party/WebKit/Source/core/events/EventPath.cpp b/third_party/WebKit/Source/core/events/EventPath.cpp index c67501f2..ee57ba46b 100644 --- a/third_party/WebKit/Source/core/events/EventPath.cpp +++ b/third_party/WebKit/Source/core/events/EventPath.cpp
@@ -69,8 +69,8 @@ node_ = &node; event_ = event; window_event_context_ = nullptr; - node_event_contexts_.Clear(); - tree_scope_event_contexts_.Clear(); + node_event_contexts_.clear(); + tree_scope_event_contexts_.clear(); Initialize(); }
diff --git a/third_party/WebKit/Source/core/events/EventPath.h b/third_party/WebKit/Source/core/events/EventPath.h index f4cb5c1..b4656da 100644 --- a/third_party/WebKit/Source/core/events/EventPath.h +++ b/third_party/WebKit/Source/core/events/EventPath.h
@@ -85,8 +85,8 @@ DECLARE_TRACE(); void Clear() { - node_event_contexts_.Clear(); - tree_scope_event_contexts_.Clear(); + node_event_contexts_.clear(); + tree_scope_event_contexts_.clear(); } private:
diff --git a/third_party/WebKit/Source/core/events/EventSender.h b/third_party/WebKit/Source/core/events/EventSender.h index 17b3cbc..a26ae98 100644 --- a/third_party/WebKit/Source/core/events/EventSender.h +++ b/third_party/WebKit/Source/core/events/EventSender.h
@@ -112,7 +112,7 @@ sender->DispatchPendingEvent(this); } } - dispatching_list_.Clear(); + dispatching_list_.clear(); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/events/GenericEventQueue.cpp b/third_party/WebKit/Source/core/events/GenericEventQueue.cpp index 82e5ece..1e46007 100644 --- a/third_party/WebKit/Source/core/events/GenericEventQueue.cpp +++ b/third_party/WebKit/Source/core/events/GenericEventQueue.cpp
@@ -122,7 +122,7 @@ EventTarget* target = event->target() ? event->target() : owner_.Get(); probe::AsyncTaskCanceled(target->GetExecutionContext(), event); } - pending_events_.Clear(); + pending_events_.clear(); } bool GenericEventQueue::HasPendingEvents() const {
diff --git a/third_party/WebKit/Source/core/events/InputEvent.cpp b/third_party/WebKit/Source/core/events/InputEvent.cpp index e3db512..e84ee6d 100644 --- a/third_party/WebKit/Source/core/events/InputEvent.cpp +++ b/third_party/WebKit/Source/core/events/InputEvent.cpp
@@ -220,7 +220,7 @@ // Authors should explicitly call |getTargetRanges()|->|toRange()| if they // want to keep a copy of |Range|. See Editing TF meeting notes: // https://docs.google.com/document/d/1hCj6QX77NYIVY0RWrMHT1Yra6t8_Qu8PopaWLG0AM58/edit?usp=sharing - Event().ranges_.Clear(); + Event().ranges_.clear(); return result; }
diff --git a/third_party/WebKit/Source/core/fileapi/FileList.h b/third_party/WebKit/Source/core/fileapi/FileList.h index a3e2f83..22ee455 100644 --- a/third_party/WebKit/Source/core/fileapi/FileList.h +++ b/third_party/WebKit/Source/core/fileapi/FileList.h
@@ -45,7 +45,7 @@ File* item(unsigned index) const; bool IsEmpty() const { return files_.IsEmpty(); } - void Clear() { files_.Clear(); } + void clear() { files_.clear(); } void Append(File* file) { files_.push_back(file); } Vector<String> PathsForUserVisibleFiles() const;
diff --git a/third_party/WebKit/Source/core/frame/Deprecation.cpp b/third_party/WebKit/Source/core/frame/Deprecation.cpp index 44d4438..89546cd 100644 --- a/third_party/WebKit/Source/core/frame/Deprecation.cpp +++ b/third_party/WebKit/Source/core/frame/Deprecation.cpp
@@ -415,6 +415,12 @@ return willBeRemoved("indexedDB.webkitGetDatabaseNames()", M60, "5725741740195840"); + case UseCounter::kVibrateWithoutUserGesture: + return willBeRemoved( + "A call to navigator.vibrate without user tap on the frame or any " + "embedded frame", + M60, "5644273861001216"); + case UseCounter::kChildSrcAllowedWorkerThatScriptSrcBlocked: return replacedWillBeRemoved("The 'child-src' directive", "the 'script-src' directive for Workers",
diff --git a/third_party/WebKit/Source/core/frame/HostsUsingFeatures.cpp b/third_party/WebKit/Source/core/frame/HostsUsingFeatures.cpp index 7297599..7bbdbf4 100644 --- a/third_party/WebKit/Source/core/frame/HostsUsingFeatures.cpp +++ b/third_party/WebKit/Source/core/frame/HostsUsingFeatures.cpp
@@ -72,7 +72,7 @@ void HostsUsingFeatures::Clear() { value_by_name_.Clear(); - url_and_values_.Clear(); + url_and_values_.clear(); } void HostsUsingFeatures::DocumentDetached(Document& document) { @@ -93,7 +93,7 @@ if (!url_and_values_.IsEmpty()) { RecordHostToRappor(); RecordETLDPlus1ToRappor(); - url_and_values_.Clear(); + url_and_values_.clear(); } if (!value_by_name_.IsEmpty()) RecordNamesToRappor();
diff --git a/third_party/WebKit/Source/core/frame/SmartClip.cpp b/third_party/WebKit/Source/core/frame/SmartClip.cpp index 486190a..caa41f5e 100644 --- a/third_party/WebKit/Source/core/frame/SmartClip.cpp +++ b/third_party/WebKit/Source/core/frame/SmartClip.cpp
@@ -87,7 +87,7 @@ CollectOverlappingChildNodes(best_node, crop_rect_in_viewport, hit_nodes); if (hit_nodes.IsEmpty() || hit_nodes.size() == best_node->CountChildren()) { - hit_nodes.Clear(); + hit_nodes.clear(); hit_nodes.push_back(best_node); }
diff --git a/third_party/WebKit/Source/core/frame/SubresourceIntegrity.cpp b/third_party/WebKit/Source/core/frame/SubresourceIntegrity.cpp index 37db8f0..7816a2ba 100644 --- a/third_party/WebKit/Source/core/frame/SubresourceIntegrity.cpp +++ b/third_party/WebKit/Source/core/frame/SubresourceIntegrity.cpp
@@ -190,7 +190,7 @@ if (metadata.Algorithm() != strongest_algorithm) continue; - digest.Clear(); + digest.clear(); bool digest_success = ComputeDigest(metadata.Algorithm(), content, size, digest); @@ -210,7 +210,7 @@ } } - digest.Clear(); + digest.clear(); if (ComputeDigest(kHashAlgorithmSha256, content, size, digest)) { // This message exposes the digest of the resource to the console. // Because this is only to the console, that's okay for now, but we
diff --git a/third_party/WebKit/Source/core/frame/UseCounter.h b/third_party/WebKit/Source/core/frame/UseCounter.h index c82c64a7..3b79e72 100644 --- a/third_party/WebKit/Source/core/frame/UseCounter.h +++ b/third_party/WebKit/Source/core/frame/UseCounter.h
@@ -1578,6 +1578,7 @@ kRequestMIDIAccessIframeWithSysExOption = 1963, kGamepadAxes = 1964, kGamepadButtons = 1965, + kVibrateWithoutUserGesture = 1966, // Add new features immediately above this line. Don't change assigned // numbers of any item, and don't reuse removed slots.
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp index b520fa7..001432da 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp
@@ -177,7 +177,7 @@ for (const auto& console_message : console_messages_) execution_context_->AddConsoleMessage(console_message); - console_messages_.Clear(); + console_messages_.clear(); for (const auto& policy : policies_) { UseCounter::Count(*document, GetUseCounterType(policy->HeaderType()));
diff --git a/third_party/WebKit/Source/core/html/HTMLFormElement.cpp b/third_party/WebKit/Source/core/html/HTMLFormElement.cpp index a232557c..a67b64b 100644 --- a/third_party/WebKit/Source/core/html/HTMLFormElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLFormElement.cpp
@@ -541,14 +541,14 @@ void HTMLFormElement::Associate(ListedElement& e) { listed_elements_are_dirty_ = true; - listed_elements_.Clear(); + listed_elements_.clear(); if (ToHTMLElement(e).FastHasAttribute(formAttr)) has_elements_associated_by_form_attribute_ = true; } void HTMLFormElement::Disassociate(ListedElement& e) { listed_elements_are_dirty_ = true; - listed_elements_.Clear(); + listed_elements_.clear(); RemoveFromPastNamesMap(ToHTMLElement(e)); } @@ -563,12 +563,12 @@ void HTMLFormElement::Associate(HTMLImageElement& e) { image_elements_are_dirty_ = true; - image_elements_.Clear(); + image_elements_.clear(); } void HTMLFormElement::Disassociate(HTMLImageElement& e) { image_elements_are_dirty_ = true; - image_elements_.Clear(); + image_elements_.clear(); RemoveFromPastNamesMap(e); } @@ -586,7 +586,7 @@ void HTMLFormElement::CollectListedElements( Node& root, ListedElement::List& elements) const { - elements.Clear(); + elements.clear(); for (HTMLElement& element : Traversal<HTMLElement>::StartsAfter(root)) { ListedElement* listed_element = 0; if (element.IsFormControlElement()) @@ -620,7 +620,7 @@ void HTMLFormElement::CollectImageElements( Node& root, HeapVector<Member<HTMLImageElement>>& elements) { - elements.Clear(); + elements.clear(); for (HTMLImageElement& image : Traversal<HTMLImageElement>::StartsAfter(root)) { if (image.formOwner() == this)
diff --git a/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp b/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp index d3e0fc4..afe41b3 100644 --- a/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp
@@ -1020,7 +1020,7 @@ // HTMLMediaElement::textTracksAreReady will need "... the text tracks whose // mode was not in the disabled state when the element's resource selection // algorithm last started". - text_tracks_when_resource_selection_began_.Clear(); + text_tracks_when_resource_selection_began_.clear(); if (text_tracks_) { for (unsigned i = 0; i < text_tracks_->length(); ++i) { TextTrack* track = text_tracks_->AnonymousIndexedGetter(i); @@ -4067,7 +4067,7 @@ return; play_promise_resolve_list_.AppendVector(play_promise_resolvers_); - play_promise_resolvers_.Clear(); + play_promise_resolvers_.clear(); if (play_promise_resolve_task_handle_.IsActive()) return; @@ -4093,7 +4093,7 @@ return; play_promise_reject_list_.AppendVector(play_promise_resolvers_); - play_promise_resolvers_.Clear(); + play_promise_resolvers_.clear(); if (play_promise_reject_task_handle_.IsActive()) return; @@ -4118,7 +4118,7 @@ for (auto& resolver : play_promise_resolve_list_) resolver->Resolve(); - play_promise_resolve_list_.Clear(); + play_promise_resolve_list_.clear(); } void HTMLMediaElement::RejectScheduledPlayPromises() { @@ -4140,7 +4140,7 @@ void HTMLMediaElement::RejectPlayPromises(ExceptionCode code, const String& message) { play_promise_reject_list_.AppendVector(play_promise_resolvers_); - play_promise_resolvers_.Clear(); + play_promise_resolvers_.clear(); RejectPlayPromisesInternal(code, message); } @@ -4151,7 +4151,7 @@ for (auto& resolver : play_promise_reject_list_) resolver->Reject(DOMException::Create(code, message)); - play_promise_reject_list_.Clear(); + play_promise_reject_list_.clear(); } EnumerationHistogram& HTMLMediaElement::ShowControlsHistogram() const {
diff --git a/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp b/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp index 25638b62..7e64174 100644 --- a/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp
@@ -573,7 +573,7 @@ return; } - last_on_change_selection_.Clear(); + last_on_change_selection_.clear(); for (auto& element : GetListItems()) last_on_change_selection_.push_back( isHTMLOptionElement(*element) && @@ -940,7 +940,7 @@ ResetToDefaultSelection(); } SetNeedsValidityCheck(); - last_on_change_selection_.Clear(); + last_on_change_selection_.clear(); } void HTMLSelectElement::OptionRemoved(HTMLOptionElement& option) { @@ -962,19 +962,19 @@ if (option.Selected()) SetAutofilled(false); SetNeedsValidityCheck(); - last_on_change_selection_.Clear(); + last_on_change_selection_.clear(); } void HTMLSelectElement::OptGroupInsertedOrRemoved( HTMLOptGroupElement& optgroup) { SetRecalcListItems(); SetNeedsValidityCheck(); - last_on_change_selection_.Clear(); + last_on_change_selection_.clear(); } void HTMLSelectElement::HrInsertedOrRemoved(HTMLHRElement& hr) { SetRecalcListItems(); - last_on_change_selection_.Clear(); + last_on_change_selection_.clear(); } // TODO(tkent): This function is not efficient. It contains multiple O(N) @@ -1072,7 +1072,7 @@ // made. This matches other browsers' behavior. if (UsesMenuList()) DispatchInputAndChangeEventForMenuList(); - last_on_change_selection_.Clear(); + last_on_change_selection_.clear(); if (PopupIsVisible()) HidePopup(); HTMLFormControlElementWithState::DispatchBlurEvent(new_focused_element, type,
diff --git a/third_party/WebKit/Source/core/html/HTMLSlotElement.cpp b/third_party/WebKit/Source/core/html/HTMLSlotElement.cpp index c86f05d4..bf89d354e 100644 --- a/third_party/WebKit/Source/core/html/HTMLSlotElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLSlotElement.cpp
@@ -140,8 +140,8 @@ void HTMLSlotElement::ClearDistribution() { // TODO(hayato): Figure out when to call // lazyReattachDistributedNodesIfNeeded() - assigned_nodes_.Clear(); - distributed_nodes_.Clear(); + assigned_nodes_.clear(); + distributed_nodes_.clear(); distributed_indices_.Clear(); } @@ -314,7 +314,7 @@ node->LazyReattachIfAttached(); probe::didPerformSlotDistribution(this); } - old_distributed_nodes_.Clear(); + old_distributed_nodes_.clear(); } void HTMLSlotElement::DidSlotChange(SlotChangeType slot_change_type) {
diff --git a/third_party/WebKit/Source/core/html/PublicURLManager.cpp b/third_party/WebKit/Source/core/html/PublicURLManager.cpp index 211f833..193ea3a 100644 --- a/third_party/WebKit/Source/core/html/PublicURLManager.cpp +++ b/third_party/WebKit/Source/core/html/PublicURLManager.cpp
@@ -88,7 +88,7 @@ } for (const auto& url : urls_to_remove) registered_urls.erase(url); - urls_to_remove.Clear(); + urls_to_remove.clear(); } }
diff --git a/third_party/WebKit/Source/core/html/forms/FileInputType.cpp b/third_party/WebKit/Source/core/html/forms/FileInputType.cpp index 3a55246..f0e05452 100644 --- a/third_party/WebKit/Source/core/html/forms/FileInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/FileInputType.cpp
@@ -199,7 +199,7 @@ if (!value_changed) return; - file_list_->Clear(); + file_list_->clear(); GetElement().SetNeedsStyleRecalc( kSubtreeStyleChange, StyleChangeReasonForTracing::Create(StyleChangeReason::kControlValue));
diff --git a/third_party/WebKit/Source/core/html/forms/FileInputTypeTest.cpp b/third_party/WebKit/Source/core/html/forms/FileInputTypeTest.cpp index 7607ed2..89bc50c 100644 --- a/third_party/WebKit/Source/core/html/forms/FileInputTypeTest.cpp +++ b/third_party/WebKit/Source/core/html/forms/FileInputTypeTest.cpp
@@ -90,7 +90,7 @@ EXPECT_EQ(String("/native/path"), file_input->Files()->item(0)->GetPath()); // Try to upload multiple files without multipleAttr - paths.Clear(); + paths.clear(); paths.push_back("/native/path1"); paths.push_back("/native/path2"); file_input->SetFilesFromPaths(paths); @@ -99,7 +99,7 @@ // Try to upload multiple files with multipleAttr input->SetBooleanAttribute(HTMLNames::multipleAttr, true); - paths.Clear(); + paths.clear(); paths.push_back("/native/real/path1"); paths.push_back("/native/real/path2"); file_input->SetFilesFromPaths(paths);
diff --git a/third_party/WebKit/Source/core/html/forms/FormController.cpp b/third_party/WebKit/Source/core/html/forms/FormController.cpp index 6f8b2517..10b380e0 100644 --- a/third_party/WebKit/Source/core/html/forms/FormController.cpp +++ b/third_party/WebKit/Source/core/html/forms/FormController.cpp
@@ -450,7 +450,7 @@ } bool has_only_signature = state_vector.size() == 1; if (has_only_signature) - state_vector.Clear(); + state_vector.clear(); return state_vector; }
diff --git a/third_party/WebKit/Source/core/html/forms/RangeInputType.cpp b/third_party/WebKit/Source/core/html/forms/RangeInputType.cpp index fd44566..e2436956 100644 --- a/third_party/WebKit/Source/core/html/forms/RangeInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/RangeInputType.cpp
@@ -356,7 +356,7 @@ void RangeInputType::UpdateTickMarkValues() { if (!tick_mark_values_dirty_) return; - tick_mark_values_.Clear(); + tick_mark_values_.clear(); tick_mark_values_dirty_ = false; HTMLDataListElement* data_list = GetElement().DataList(); if (!data_list)
diff --git a/third_party/WebKit/Source/core/html/imports/HTMLImportTreeRoot.cpp b/third_party/WebKit/Source/core/html/imports/HTMLImportTreeRoot.cpp index 8f0104fd..ed535ae 100644 --- a/third_party/WebKit/Source/core/html/imports/HTMLImportTreeRoot.cpp +++ b/third_party/WebKit/Source/core/html/imports/HTMLImportTreeRoot.cpp
@@ -30,7 +30,7 @@ void HTMLImportTreeRoot::Dispose() { for (const auto& import_child : imports_) import_child->Dispose(); - imports_.Clear(); + imports_.clear(); document_ = nullptr; recalc_timer_.Stop(); }
diff --git a/third_party/WebKit/Source/core/html/imports/HTMLImportsController.cpp b/third_party/WebKit/Source/core/html/imports/HTMLImportsController.cpp index 6585f8f..fac6a5be 100644 --- a/third_party/WebKit/Source/core/html/imports/HTMLImportsController.cpp +++ b/third_party/WebKit/Source/core/html/imports/HTMLImportsController.cpp
@@ -54,7 +54,7 @@ for (const auto& loader : loaders_) loader->Dispose(); - loaders_.Clear(); + loaders_.clear(); } static bool MakesCycle(HTMLImport* parent, const KURL& url) {
diff --git a/third_party/WebKit/Source/core/html/media/MediaFragmentURIParser.cpp b/third_party/WebKit/Source/core/html/media/MediaFragmentURIParser.cpp index b8164ab..716ae58a 100644 --- a/third_party/WebKit/Source/core/html/media/MediaFragmentURIParser.cpp +++ b/third_party/WebKit/Source/core/html/media/MediaFragmentURIParser.cpp
@@ -183,7 +183,7 @@ // previous occurrences (valid or invalid) SHOULD be ignored by the UA. } } - fragments_.Clear(); + fragments_.clear(); } bool MediaFragmentURIParser::ParseNPTFragment(const LChar* time_string,
diff --git a/third_party/WebKit/Source/core/html/parser/AtomicHTMLToken.h b/third_party/WebKit/Source/core/html/parser/AtomicHTMLToken.h index fa4d8f6..47f5614 100644 --- a/third_party/WebKit/Source/core/html/parser/AtomicHTMLToken.h +++ b/third_party/WebKit/Source/core/html/parser/AtomicHTMLToken.h
@@ -220,7 +220,7 @@ if (!size) return; - attributes_.Clear(); + attributes_.clear(); attributes_.ReserveInitialCapacity(size); for (const auto& attribute : attributes) { if (attribute.NameAsVector().IsEmpty())
diff --git a/third_party/WebKit/Source/core/html/parser/BackgroundHTMLInputStream.cpp b/third_party/WebKit/Source/core/html/parser/BackgroundHTMLInputStream.cpp index fe3cb4f..2208bb4 100644 --- a/third_party/WebKit/Source/core/html/parser/BackgroundHTMLInputStream.cpp +++ b/third_party/WebKit/Source/core/html/parser/BackgroundHTMLInputStream.cpp
@@ -108,8 +108,8 @@ DCHECK_EQ(current_.IsClosed(), is_closed); - segments_.Clear(); - checkpoints_.Clear(); + segments_.clear(); + checkpoints_.clear(); first_valid_checkpoint_index_ = 0; first_valid_segment_index_ = 0;
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp b/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp index 195bb02..817664c 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp
@@ -468,7 +468,7 @@ speculations_.Clear(); pending_csp_meta_token_ = nullptr; - queued_preloads_.Clear(); + queued_preloads_.clear(); std::unique_ptr<BackgroundHTMLParser::Checkpoint> checkpoint = WTF::WrapUnique(new BackgroundHTMLParser::Checkpoint); @@ -1280,7 +1280,7 @@ EvaluateAndPreloadScriptForDocumentWrite(script_source); } - queued_document_write_scripts_.Clear(); + queued_document_write_scripts_.clear(); } void HTMLDocumentParser::EvaluateAndPreloadScriptForDocumentWrite(
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLEntityParser.cpp b/third_party/WebKit/Source/core/html/parser/HTMLEntityParser.cpp index 532585c..1dc461dc5 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLEntityParser.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLEntityParser.cpp
@@ -128,7 +128,7 @@ // source back to the point at which we had consumed an // actual entity. UnconsumeCharacters(source, consumed_characters); - consumed_characters.Clear(); + consumed_characters.clear(); const HTMLEntityTableEntry* most_recent = entity_search.MostRecentMatch(); const int length = most_recent->length; const LChar* reference = HTMLEntityTable::EntityString(*most_recent);
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp b/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp index 67f8516..ac9f576 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp
@@ -607,7 +607,7 @@ in_script_ = checkpoint.in_script; css_scanner_.Reset(); - checkpoints_.Clear(); + checkpoints_.clear(); } void TokenPreloadScanner::Scan(const HTMLToken& token,
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLToken.h b/third_party/WebKit/Source/core/html/parser/HTMLToken.h index 42e800d..0476960 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLToken.h +++ b/third_party/WebKit/Source/core/html/parser/HTMLToken.h
@@ -125,7 +125,7 @@ void AppendToValue(UChar c) { value_.push_back(c); } void AppendToValue(const String& value) { value.AppendTo(value_); } - void ClearValue() { value_.Clear(); } + void ClearValue() { value_.clear(); } const Range& NameRange() const { return name_range_; } const Range& ValueRange() const { return value_range_; } @@ -239,13 +239,13 @@ void SetPublicIdentifierToEmptyString() { DCHECK_EQ(type_, DOCTYPE); doctype_data_->has_public_identifier_ = true; - doctype_data_->public_identifier_.Clear(); + doctype_data_->public_identifier_.clear(); } void SetSystemIdentifierToEmptyString() { DCHECK_EQ(type_, DOCTYPE); doctype_data_->has_system_identifier_ = true; - doctype_data_->system_identifier_.Clear(); + doctype_data_->system_identifier_.clear(); } void AppendToPublicIdentifier(UChar character) { @@ -284,7 +284,7 @@ type_ = kStartTag; self_closing_ = false; current_attribute_ = 0; - attributes_.Clear(); + attributes_.clear(); data_.push_back(character); or_all_data_ |= character; @@ -295,7 +295,7 @@ type_ = kEndTag; self_closing_ = false; current_attribute_ = 0; - attributes_.Clear(); + attributes_.clear(); data_.push_back(character); } @@ -305,7 +305,7 @@ type_ = kEndTag; self_closing_ = false; current_attribute_ = 0; - attributes_.Clear(); + attributes_.clear(); data_.AppendVector(characters); } @@ -433,7 +433,7 @@ // Only for XSSAuditor void EraseCharacters() { DCHECK_EQ(type_, kCharacter); - data_.Clear(); + data_.clear(); or_all_data_ = 0; }
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLTokenizer.cpp b/third_party/WebKit/Source/core/html/parser/HTMLTokenizer.cpp index 535e149..ec8889f 100644 --- a/third_party/WebKit/Source/core/html/parser/HTMLTokenizer.cpp +++ b/third_party/WebKit/Source/core/html/parser/HTMLTokenizer.cpp
@@ -105,9 +105,9 @@ if (token_->GetType() == HTMLToken::kCharacter) return true; token_->BeginEndTag(buffered_end_tag_name_); - buffered_end_tag_name_.Clear(); - appropriate_end_tag_name_.Clear(); - temporary_buffer_.Clear(); + buffered_end_tag_name_.clear(); + appropriate_end_tag_name_.clear(); + temporary_buffer_.clear(); return false; } @@ -140,9 +140,9 @@ // FIXME: This should call flushBufferedEndTag(). // We started an end tag during our last iteration. token_->BeginEndTag(buffered_end_tag_name_); - buffered_end_tag_name_.Clear(); - appropriate_end_tag_name_.Clear(); - temporary_buffer_.Clear(); + buffered_end_tag_name_.clear(); + appropriate_end_tag_name_.clear(); + temporary_buffer_.clear(); if (state_ == HTMLTokenizer::kDataState) { // We're back in the data state, so we must be done with the tag. return true; @@ -262,11 +262,11 @@ HTML_BEGIN_STATE(kEndTagOpenState) { if (IsASCIIUpper(cc)) { token_->BeginEndTag(static_cast<LChar>(ToLowerCase(cc))); - appropriate_end_tag_name_.Clear(); + appropriate_end_tag_name_.clear(); HTML_ADVANCE_TO(kTagNameState); } else if (IsASCIILower(cc)) { token_->BeginEndTag(static_cast<LChar>(cc)); - appropriate_end_tag_name_.Clear(); + appropriate_end_tag_name_.clear(); HTML_ADVANCE_TO(kTagNameState); } else if (cc == '>') { ParseError(); @@ -305,7 +305,7 @@ HTML_BEGIN_STATE(kRCDATALessThanSignState) { if (cc == '/') { - temporary_buffer_.Clear(); + temporary_buffer_.clear(); DCHECK(buffered_end_tag_name_.IsEmpty()); HTML_ADVANCE_TO(kRCDATAEndTagOpenState); } else { @@ -361,8 +361,8 @@ BufferCharacter('<'); BufferCharacter('/'); token_->AppendToCharacter(temporary_buffer_); - buffered_end_tag_name_.Clear(); - temporary_buffer_.Clear(); + buffered_end_tag_name_.clear(); + temporary_buffer_.clear(); HTML_RECONSUME_IN(kRCDATAState); } } @@ -370,7 +370,7 @@ HTML_BEGIN_STATE(kRAWTEXTLessThanSignState) { if (cc == '/') { - temporary_buffer_.Clear(); + temporary_buffer_.clear(); DCHECK(buffered_end_tag_name_.IsEmpty()); HTML_ADVANCE_TO(kRAWTEXTEndTagOpenState); } else { @@ -426,8 +426,8 @@ BufferCharacter('<'); BufferCharacter('/'); token_->AppendToCharacter(temporary_buffer_); - buffered_end_tag_name_.Clear(); - temporary_buffer_.Clear(); + buffered_end_tag_name_.clear(); + temporary_buffer_.clear(); HTML_RECONSUME_IN(kRAWTEXTState); } } @@ -435,7 +435,7 @@ HTML_BEGIN_STATE(kScriptDataLessThanSignState) { if (cc == '/') { - temporary_buffer_.Clear(); + temporary_buffer_.clear(); DCHECK(buffered_end_tag_name_.IsEmpty()); HTML_ADVANCE_TO(kScriptDataEndTagOpenState); } else if (cc == '!') { @@ -495,8 +495,8 @@ BufferCharacter('<'); BufferCharacter('/'); token_->AppendToCharacter(temporary_buffer_); - buffered_end_tag_name_.Clear(); - temporary_buffer_.Clear(); + buffered_end_tag_name_.clear(); + temporary_buffer_.clear(); HTML_RECONSUME_IN(kScriptDataState); } } @@ -573,19 +573,19 @@ HTML_BEGIN_STATE(kScriptDataEscapedLessThanSignState) { if (cc == '/') { - temporary_buffer_.Clear(); + temporary_buffer_.clear(); DCHECK(buffered_end_tag_name_.IsEmpty()); HTML_ADVANCE_TO(kScriptDataEscapedEndTagOpenState); } else if (IsASCIIUpper(cc)) { BufferCharacter('<'); BufferCharacter(cc); - temporary_buffer_.Clear(); + temporary_buffer_.clear(); temporary_buffer_.push_back(ToLowerCase(cc)); HTML_ADVANCE_TO(kScriptDataDoubleEscapeStartState); } else if (IsASCIILower(cc)) { BufferCharacter('<'); BufferCharacter(cc); - temporary_buffer_.Clear(); + temporary_buffer_.clear(); temporary_buffer_.push_back(static_cast<LChar>(cc)); HTML_ADVANCE_TO(kScriptDataDoubleEscapeStartState); } else { @@ -641,8 +641,8 @@ BufferCharacter('<'); BufferCharacter('/'); token_->AppendToCharacter(temporary_buffer_); - buffered_end_tag_name_.Clear(); - temporary_buffer_.Clear(); + buffered_end_tag_name_.clear(); + temporary_buffer_.clear(); HTML_RECONSUME_IN(kScriptDataEscapedState); } } @@ -725,7 +725,7 @@ HTML_BEGIN_STATE(kScriptDataDoubleEscapedLessThanSignState) { if (cc == '/') { BufferCharacter(cc); - temporary_buffer_.Clear(); + temporary_buffer_.clear(); HTML_ADVANCE_TO(kScriptDataDoubleEscapeEndState); } else HTML_RECONSUME_IN(kScriptDataDoubleEscapedState);
diff --git a/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp b/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp index 96ce30b..023819f 100644 --- a/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp +++ b/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp
@@ -490,7 +490,7 @@ data_for_decode, length_for_decode, WTF::kDoNotFlush, content_type_ == kXMLContent && !use_lenient_xml_decoding_, saw_error_); - buffer_.Clear(); + buffer_.clear(); return result; } @@ -514,7 +514,7 @@ String result = codec_->Decode( buffer_.Data(), buffer_.size(), WTF::kFetchEOF, content_type_ == kXMLContent && !use_lenient_xml_decoding_, saw_error_); - buffer_.Clear(); + buffer_.clear(); codec_.reset(); checked_for_bom_ = false; // Skip BOM again when re-decoding. return result;
diff --git a/third_party/WebKit/Source/core/html/parser/TokenizedChunkQueue.cpp b/third_party/WebKit/Source/core/html/parser/TokenizedChunkQueue.cpp index fe0e9b1..1289fff 100644 --- a/third_party/WebKit/Source/core/html/parser/TokenizedChunkQueue.cpp +++ b/third_party/WebKit/Source/core/html/parser/TokenizedChunkQueue.cpp
@@ -30,7 +30,7 @@ void TokenizedChunkQueue::Clear() { pending_token_count_ = 0; - pending_chunks_.Clear(); + pending_chunks_.clear(); } void TokenizedChunkQueue::TakeAll(
diff --git a/third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp b/third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp index 72144e6..43076f5 100644 --- a/third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp +++ b/third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp
@@ -110,7 +110,7 @@ } void TextTrackCueList::Clear() { - list_.Clear(); + list_.clear(); } void TextTrackCueList::InvalidateCueIndex(size_t index) {
diff --git a/third_party/WebKit/Source/core/html/track/TextTrackList.cpp b/third_party/WebKit/Source/core/html/track/TextTrackList.cpp index 52baf4e..67f6238 100644 --- a/third_party/WebKit/Source/core/html/track/TextTrackList.cpp +++ b/third_party/WebKit/Source/core/html/track/TextTrackList.cpp
@@ -219,7 +219,7 @@ for (const auto& track : inband_tracks_) { track->SetTrackList(0); } - inband_tracks_.Clear(); + inband_tracks_.clear(); } bool TextTrackList::Contains(TextTrack* track) const {
diff --git a/third_party/WebKit/Source/core/html/track/TrackListBase.h b/third_party/WebKit/Source/core/html/track/TrackListBase.h index e14e09a..767974c 100644 --- a/third_party/WebKit/Source/core/html/track/TrackListBase.h +++ b/third_party/WebKit/Source/core/html/track/TrackListBase.h
@@ -72,7 +72,7 @@ for (const auto& track : tracks_) track->SetMediaElement(0); - tracks_.Clear(); + tracks_.clear(); } void ScheduleChangeEvent() {
diff --git a/third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp b/third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp index 5f749ee..0dc2f1b 100644 --- a/third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp +++ b/third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp
@@ -347,7 +347,7 @@ current_node_ = fragment; VTTTokenizer tokenizer(cue_text); - language_stack_.Clear(); + language_stack_.clear(); while (tokenizer.NextToken(token_)) ConstructTreeFromToken(GetDocument());
diff --git a/third_party/WebKit/Source/core/inspector/DOMPatchSupport.cpp b/third_party/WebKit/Source/core/inspector/DOMPatchSupport.cpp index d5d052d1..5cd10dbd 100644 --- a/third_party/WebKit/Source/core/inspector/DOMPatchSupport.cpp +++ b/third_party/WebKit/Source/core/inspector/DOMPatchSupport.cpp
@@ -485,7 +485,7 @@ digest->attrs_sha1_ = Base64Encode(reinterpret_cast<const char*>(digest_result.Data()), 10); AddStringToDigestor(digestor.get(), digest->attrs_sha1_); - digest_result.Clear(); + digest_result.clear(); } } FinishDigestor(digestor.get(), digest_result);
diff --git a/third_party/WebKit/Source/core/inspector/DevToolsHost.cpp b/third_party/WebKit/Source/core/inspector/DevToolsHost.cpp index 8ab6314..541f0969 100644 --- a/third_party/WebKit/Source/core/inspector/DevToolsHost.cpp +++ b/third_party/WebKit/Source/core/inspector/DevToolsHost.cpp
@@ -85,7 +85,7 @@ devtools_host_->ClearMenuProvider(); devtools_host_ = nullptr; } - items_.Clear(); + items_.clear(); } void PopulateContextMenu(ContextMenu* menu) override {
diff --git a/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp index 991ca68..8d76427 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp
@@ -171,12 +171,12 @@ } else { if (colors.size() > 1) { // Gradient on gradient is too complicated, bail out - colors.Clear(); + colors.clear(); return; } Color existing_color = colors.front(); - colors.Clear(); + colors.clear(); for (auto stop_color : stop_colors) { found_non_transparent_color = found_non_transparent_color || (stop_color.Alpha() != 0); @@ -204,7 +204,7 @@ if (!style_image->IsGeneratedImage()) { // Make no assertions about the colors in non-generated images - colors.Clear(); + colors.clear(); found_opaque_color = false; return; } @@ -247,7 +247,7 @@ isHTMLImageElement(element) || isHTMLObjectElement(element) || isHTMLPictureElement(element) || element->IsSVGElement() || isHTMLVideoElement(element)) { - colors.Clear(); + colors.clear(); found_opaque_color = false; continue; } @@ -267,7 +267,7 @@ colors.push_back(background_color); } else { if (!background_color.HasAlpha()) { - colors.Clear(); + colors.clear(); colors.push_back(background_color); found_opaque_color = true; } else { @@ -285,7 +285,7 @@ bool contains = found_top_element || element->BoundingBox().Contains(rect); if (!contains && found_non_transparent_color) { // Only return colors if some opaque element covers up this one. - colors.Clear(); + colors.clear(); found_opaque_color = false; } } @@ -380,7 +380,7 @@ } static void ConstructDeletedValue(Vector<String>& vec, bool) { - vec.Clear(); + vec.clear(); vec.push_back(String(WTF::kHashTableDeletedValue)); }
diff --git a/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp index 48d33253..a9a2e62 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp
@@ -288,7 +288,7 @@ } void InspectorDOMAgent::ReleaseDanglingNodes() { - dangling_node_to_id_maps_.Clear(); + dangling_node_to_id_maps_.clear(); } int InspectorDOMAgent::Bind(Node* node, NodeToIdMap* nodes_map) {
diff --git a/third_party/WebKit/Source/core/inspector/InspectorHistory.cpp b/third_party/WebKit/Source/core/inspector/InspectorHistory.cpp index 3be2c29d3..23598d3 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorHistory.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorHistory.cpp
@@ -139,7 +139,7 @@ void InspectorHistory::Reset() { after_last_action_index_ = 0; - history_.Clear(); + history_.clear(); } DEFINE_TRACE(InspectorHistory) {
diff --git a/third_party/WebKit/Source/core/inspector/InspectorResourceContentLoader.cpp b/third_party/WebKit/Source/core/inspector/InspectorResourceContentLoader.cpp index 4844b95..4eed7c1b 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorResourceContentLoader.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorResourceContentLoader.cpp
@@ -209,7 +209,7 @@ pending_resource_clients_.swap(pending_resource_clients); for (const auto& client : pending_resource_clients) client->loader_ = nullptr; - resources_.Clear(); + resources_.clear(); // Make sure all callbacks are called to prevent infinite waiting time. CheckDone(); all_requests_started_ = false;
diff --git a/third_party/WebKit/Source/core/inspector/InspectorSession.cpp b/third_party/WebKit/Source/core/inspector/InspectorSession.cpp index 640f9db..95d25f3 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorSession.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorSession.cpp
@@ -70,7 +70,7 @@ inspector_backend_dispatcher_.reset(); for (size_t i = agents_.size(); i > 0; i--) agents_[i - 1]->Dispose(); - agents_.Clear(); + agents_.clear(); v8_session_.reset(); } @@ -183,7 +183,7 @@ client_->SendProtocolMessage(session_id_, 0, notification_queue_[i]->Serialize(), String()); } - notification_queue_.Clear(); + notification_queue_.clear(); } DEFINE_TRACE(InspectorSession) {
diff --git a/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp b/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp index 73380245..973f911 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp
@@ -1407,7 +1407,7 @@ CSSStyleSheet::Create(style_sheet, *page_style_sheet_->ownerNode()); } - parsed_flat_rules_.Clear(); + parsed_flat_rules_.clear(); CollectFlatRules(source_data_sheet, &parsed_flat_rules_); source_data_ = new CSSRuleSourceDataList(); @@ -1789,7 +1789,7 @@ rule_to_source_data_.Clear(); source_data_to_rule_.Clear(); - cssom_flat_rules_.Clear(); + cssom_flat_rules_.clear(); CSSRuleVector& cssom_rules = cssom_flat_rules_; CollectFlatRules(page_style_sheet_.Get(), &cssom_rules);
diff --git a/third_party/WebKit/Source/core/layout/DepthOrderedLayoutObjectList.cpp b/third_party/WebKit/Source/core/layout/DepthOrderedLayoutObjectList.cpp index 95820529..f414d09 100644 --- a/third_party/WebKit/Source/core/layout/DepthOrderedLayoutObjectList.cpp +++ b/third_party/WebKit/Source/core/layout/DepthOrderedLayoutObjectList.cpp
@@ -39,7 +39,7 @@ void DepthOrderedLayoutObjectList::Add(LayoutObject& object) { DCHECK(!object.GetFrameView()->IsInPerformLayout()); data_->objects_.insert(&object); - data_->ordered_objects_.Clear(); + data_->ordered_objects_.clear(); } void DepthOrderedLayoutObjectList::Remove(LayoutObject& object) { @@ -48,12 +48,12 @@ return; DCHECK(!object.GetFrameView()->IsInPerformLayout()); data_->objects_.erase(it); - data_->ordered_objects_.Clear(); + data_->ordered_objects_.clear(); } void DepthOrderedLayoutObjectList::Clear() { data_->objects_.Clear(); - data_->ordered_objects_.Clear(); + data_->ordered_objects_.clear(); } unsigned DepthOrderedLayoutObjectList::LayoutObjectWithDepth::DetermineDepth(
diff --git a/third_party/WebKit/Source/core/layout/FlexibleBoxAlgorithm.cpp b/third_party/WebKit/Source/core/layout/FlexibleBoxAlgorithm.cpp index 3c286ad..76b90233 100644 --- a/third_party/WebKit/Source/core/layout/FlexibleBoxAlgorithm.cpp +++ b/third_party/WebKit/Source/core/layout/FlexibleBoxAlgorithm.cpp
@@ -63,7 +63,7 @@ double& total_flex_shrink, double& total_weighted_flex_shrink, LayoutUnit& sum_hypothetical_main_size) { - line_items.Clear(); + line_items.clear(); sum_flex_base_size = LayoutUnit(); total_flex_grow = total_flex_shrink = total_weighted_flex_shrink = 0; sum_hypothetical_main_size = LayoutUnit();
diff --git a/third_party/WebKit/Source/core/layout/HitTestCache.cpp b/third_party/WebKit/Source/core/layout/HitTestCache.cpp index af964ae1..8be999f 100644 --- a/third_party/WebKit/Source/core/layout/HitTestCache.cpp +++ b/third_party/WebKit/Source/core/layout/HitTestCache.cpp
@@ -70,7 +70,7 @@ void HitTestCache::Clear() { update_index_ = 0; - items_.Clear(); + items_.clear(); } DEFINE_TRACE(HitTestCache) {
diff --git a/third_party/WebKit/Source/core/layout/LayoutTable.cpp b/third_party/WebKit/Source/core/layout/LayoutTable.cpp index 1f2289c..4d51fd4 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTable.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTable.cpp
@@ -774,7 +774,7 @@ } void LayoutTable::InvalidateCollapsedBorders() { - collapsed_borders_.Clear(); + collapsed_borders_.clear(); if (!CollapseBorders()) return; @@ -790,7 +790,7 @@ if (collapsed_borders_valid_ || !CollapseBorders()) return; collapsed_borders_valid_ = true; - collapsed_borders_.Clear(); + collapsed_borders_.clear(); for (LayoutObject* section = FirstChild(); section; section = section->NextSibling()) { if (!section->IsTableSection())
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableSection.cpp b/third_party/WebKit/Source/core/layout/LayoutTableSection.cpp index 95efd6a..49cbfa6 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTableSection.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTableSection.cpp
@@ -1691,7 +1691,7 @@ c_col_ = 0; c_row_ = 0; - grid_.Clear(); + grid_.clear(); for (LayoutTableRow* row = FirstRow(); row; row = row->NextRow()) { unsigned insertion_row = c_row_;
diff --git a/third_party/WebKit/Source/core/layout/LayoutText.cpp b/third_party/WebKit/Source/core/layout/LayoutText.cpp index f9b04a00..497a705 100644 --- a/third_party/WebKit/Source/core/layout/LayoutText.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutText.cpp
@@ -400,7 +400,7 @@ } if (!has_checked_box_in_range) { has_checked_box_in_range = true; - rects.Clear(); + rects.clear(); } rects.push_back(LocalToAbsoluteQuad(r).EnclosingBoundingBox()); } else if ((box->Start() <= start && start <= box->end()) || @@ -410,7 +410,7 @@ if (!rect.IsZero()) { if (!has_checked_box_in_range) { has_checked_box_in_range = true; - rects.Clear(); + rects.clear(); } rects.push_back(LocalToAbsoluteQuad(rect).EnclosingBoundingBox()); } @@ -529,7 +529,7 @@ } if (!has_checked_box_in_range) { has_checked_box_in_range = true; - quads.Clear(); + quads.clear(); } quads.push_back(LocalToAbsoluteQuad(FloatRect(r))); } else if ((box->Start() <= start && start <= box->end()) || @@ -539,7 +539,7 @@ if (!rect.IsZero()) { if (!has_checked_box_in_range) { has_checked_box_in_range = true; - quads.Clear(); + quads.clear(); } quads.push_back(LocalToAbsoluteQuad(rect)); }
diff --git a/third_party/WebKit/Source/core/layout/TextAutosizer.cpp b/third_party/WebKit/Source/core/layout/TextAutosizer.cpp index 4af1f5c..a4cec13 100644 --- a/third_party/WebKit/Source/core/layout/TextAutosizer.cpp +++ b/third_party/WebKit/Source/core/layout/TextAutosizer.cpp
@@ -286,7 +286,7 @@ // Clear the cluster stack and the supercluster map to avoid stale pointers. // Speculative fix for http://crbug.com/369485. first_block_to_begin_layout_ = nullptr; - cluster_stack_.Clear(); + cluster_stack_.clear(); } } @@ -386,8 +386,8 @@ if (block == first_block_to_begin_layout_) { first_block_to_begin_layout_ = nullptr; - cluster_stack_.Clear(); - styles_retained_during_layout_.Clear(); + cluster_stack_.clear(); + styles_retained_during_layout_.clear(); #if DCHECK_IS_ON() blocks_that_have_begun_layout_.Clear(); #endif
diff --git a/third_party/WebKit/Source/core/layout/line/LineBreaker.cpp b/third_party/WebKit/Source/core/layout/line/LineBreaker.cpp index 92e44a1..c7d5abb9 100644 --- a/third_party/WebKit/Source/core/layout/line/LineBreaker.cpp +++ b/third_party/WebKit/Source/core/layout/line/LineBreaker.cpp
@@ -53,7 +53,7 @@ } void LineBreaker::Reset() { - positioned_objects_.Clear(); + positioned_objects_.clear(); hyphenated_ = false; clear_ = EClear::kNone; }
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.cc index a6cd187..21633c7 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.cc
@@ -108,7 +108,7 @@ line_box->MoveChildrenInBlockDirection( baseline_shift, child.fragment_start, child.fragment_end); } - box->pending_descendants.Clear(); + box->pending_descendants.clear(); } const ComputedStyle& style = *box->style;
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_node.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_node.cc index d765129..8cd19d8 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_node.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_node.cc
@@ -53,7 +53,7 @@ void NGInlineNode::InvalidatePrepareLayout() { text_content_ = String(); - items_.Clear(); + items_.clear(); } void NGInlineNode::PrepareLayout() { @@ -421,7 +421,7 @@ baseline + max_with_leading.descent); bidi_runs.DeleteRuns(); - fragments_for_bidi_runs.Clear(); + fragments_for_bidi_runs.clear(); } }
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_node_test.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_node_test.cc index 0ed7bb1f..dd482de7 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_node_test.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_node_test.cc
@@ -45,7 +45,7 @@ void ClearText() { text_content_ = String(); - items_.Clear(); + items_.clear(); } void SegmentText() {
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_layout_inline_items_builder_test.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_layout_inline_items_builder_test.cc index 7fdc308..97df728 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_layout_inline_items_builder_test.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_layout_inline_items_builder_test.cc
@@ -28,7 +28,7 @@ } const String& TestAppend(const String inputs[], int size) { - items_.Clear(); + items_.clear(); NGLayoutInlineItemsBuilder builder(&items_); for (int i = 0; i < size; i++) builder.Append(inputs[i], style_.Get());
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_exclusion.cc b/third_party/WebKit/Source/core/layout/ng/ng_exclusion.cc index 9d1ecd23..06855c1b 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_exclusion.cc +++ b/third_party/WebKit/Source/core/layout/ng/ng_exclusion.cc
@@ -67,7 +67,7 @@ } inline NGExclusions& NGExclusions::operator=(const NGExclusions& other) { - storage.Clear(); + storage.clear(); last_left_float = nullptr; last_right_float = nullptr; for (const auto& exclusion : other.storage)
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_floats_utils.cc b/third_party/WebKit/Source/core/layout/ng/ng_floats_utils.cc index 2f77bb3..93dd925e 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_floats_utils.cc +++ b/third_party/WebKit/Source/core/layout/ng/ng_floats_utils.cc
@@ -177,7 +177,7 @@ NGLogicalOffset offset = PositionFloat(floating_object.Get(), space); builder->AddFloatingObject(floating_object, offset); } - builder->MutableUnpositionedFloats().Clear(); + builder->MutableUnpositionedFloats().clear(); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_fragment_builder.cc b/third_party/WebKit/Source/core/layout/ng/ng_fragment_builder.cc index 938169c..6061bdd 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_fragment_builder.cc +++ b/third_party/WebKit/Source/core/layout/ng/ng_fragment_builder.cc
@@ -168,7 +168,7 @@ descendant_positions->push_back(builder_relative_position); } out_of_flow_descendant_candidates_.clear(); - out_of_flow_candidate_placements_.Clear(); + out_of_flow_candidate_placements_.clear(); } NGFragmentBuilder& NGFragmentBuilder::AddOutOfFlowDescendant(
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_out_of_flow_layout_part.cc b/third_party/WebKit/Source/core/layout/ng/ng_out_of_flow_layout_part.cc index 7e02192..10d7c750 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_out_of_flow_layout_part.cc +++ b/third_party/WebKit/Source/core/layout/ng/ng_out_of_flow_layout_part.cc
@@ -90,7 +90,7 @@ // Sweep any descendants that might have been added. // This happens when an absolute container has a fixed child. out_of_flow_candidates.clear(); - out_of_flow_candidate_positions.Clear(); + out_of_flow_candidate_positions.clear(); container_builder_->GetAndClearOutOfFlowDescendantCandidates( &out_of_flow_candidates, &out_of_flow_candidate_positions); }
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGInlineText.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGInlineText.cpp index 6e92fef..6ed711c 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGInlineText.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGInlineText.cpp
@@ -333,7 +333,7 @@ void LayoutSVGInlineText::UpdateMetricsList( bool& last_character_was_white_space) { - metrics_.Clear(); + metrics_.clear(); if (!TextLength()) return;
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGPath.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGPath.cpp index 1eaa594..eb9cf300 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGPath.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGPath.cpp
@@ -127,7 +127,7 @@ } void LayoutSVGPath::ProcessMarkerPositions() { - marker_positions_.Clear(); + marker_positions_.clear(); if (!ShouldGenerateMarkerPositions()) return;
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGText.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGText.cpp index 51bc388..bea009f5 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGText.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGText.cpp
@@ -72,7 +72,7 @@ } void LayoutSVGText::WillBeDestroyed() { - descendant_text_nodes_.Clear(); + descendant_text_nodes_.clear(); LayoutSVGBlock::WillBeDestroyed(); } @@ -104,7 +104,7 @@ void LayoutSVGText::InvalidatePositioningValues( LayoutInvalidationReasonForTracing reason) { - descendant_text_nodes_.Clear(); + descendant_text_nodes_.clear(); SetNeedsPositioningValuesUpdate(); SetNeedsLayoutAndFullPaintInvalidation(reason); } @@ -208,7 +208,7 @@ // When the x/y/dx/dy/rotate lists change, we need to recompute the layout // attributes. if (needs_positioning_values_update_) { - descendant_text_nodes_.Clear(); + descendant_text_nodes_.clear(); CollectDescendantTextNodes(*this, descendant_text_nodes_); SVGTextLayoutAttributesBuilder(*this).BuildLayoutAttributes();
diff --git a/third_party/WebKit/Source/core/layout/svg/SVGLayoutSupport.cpp b/third_party/WebKit/Source/core/layout/svg/SVGLayoutSupport.cpp index f2a02b8..9dcbe1b1 100644 --- a/third_party/WebKit/Source/core/layout/svg/SVGLayoutSupport.cpp +++ b/third_party/WebKit/Source/core/layout/svg/SVGLayoutSupport.cpp
@@ -605,7 +605,7 @@ float distance = DistanceToChildLayoutObject(child, point); if (distance >= closest_text.candidate_distance) continue; - candidates.Clear(); + candidates.clear(); closest_text.candidate_layout_object = child; closest_text.candidate_distance = distance; continue;
diff --git a/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngine.cpp b/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngine.cpp index 6415f321..e5822be 100644 --- a/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngine.cpp +++ b/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngine.cpp
@@ -293,7 +293,7 @@ SVGTextChunkBuilder chunk_layout_builder; chunk_layout_builder.ProcessTextChunks(line_layout_boxes_); - line_layout_boxes_.Clear(); + line_layout_boxes_.clear(); } const LayoutSVGInlineText* SVGTextLayoutEngine::NextLogicalTextNode() {
diff --git a/third_party/WebKit/Source/core/layout/svg/line/SVGInlineTextBox.h b/third_party/WebKit/Source/core/layout/svg/line/SVGInlineTextBox.h index 046271d..c1a5603 100644 --- a/third_party/WebKit/Source/core/layout/svg/line/SVGInlineTextBox.h +++ b/third_party/WebKit/Source/core/layout/svg/line/SVGInlineTextBox.h
@@ -54,7 +54,7 @@ // Calculate the bounding rect of all text fragments. LayoutRect CalculateBoundaries() const; - void ClearTextFragments() { text_fragments_.Clear(); } + void ClearTextFragments() { text_fragments_.clear(); } Vector<SVGTextFragment>& TextFragments() { return text_fragments_; } const Vector<SVGTextFragment>& TextFragments() const { return text_fragments_;
diff --git a/third_party/WebKit/Source/core/loader/DocumentLoader.cpp b/third_party/WebKit/Source/core/loader/DocumentLoader.cpp index ad68e74b..e3a8c51 100644 --- a/third_party/WebKit/Source/core/loader/DocumentLoader.cpp +++ b/third_party/WebKit/Source/core/loader/DocumentLoader.cpp
@@ -743,7 +743,7 @@ } void DocumentLoader::ClearRedirectChain() { - redirect_chain_.Clear(); + redirect_chain_.clear(); } void DocumentLoader::AppendRedirect(const KURL& url) {
diff --git a/third_party/WebKit/Source/core/loader/HistoryItem.cpp b/third_party/WebKit/Source/core/loader/HistoryItem.cpp index 81d2c8a..3756e2c5 100644 --- a/third_party/WebKit/Source/core/loader/HistoryItem.cpp +++ b/third_party/WebKit/Source/core/loader/HistoryItem.cpp
@@ -125,7 +125,7 @@ void HistoryItem::ClearDocumentState() { document_state_.Clear(); - document_state_vector_.Clear(); + document_state_vector_.clear(); } void HistoryItem::SetStateObject(PassRefPtr<SerializedScriptValue> object) {
diff --git a/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.cpp b/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.cpp index 030818c..54aa2d7 100644 --- a/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.cpp +++ b/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.cpp
@@ -264,7 +264,7 @@ deferred.error_url, deferred.error_status, deferred.error_message); } - deferred_events_.Clear(); + deferred_events_.clear(); defers_events_ = false; }
diff --git a/third_party/WebKit/Source/core/loader/resource/MultipartImageResourceParser.cpp b/third_party/WebKit/Source/core/loader/resource/MultipartImageResourceParser.cpp index ee2ac621..fdb74323 100644 --- a/third_party/WebKit/Source/core/loader/resource/MultipartImageResourceParser.cpp +++ b/third_party/WebKit/Source/core/loader/resource/MultipartImageResourceParser.cpp
@@ -86,7 +86,7 @@ '-' == data_[boundary_end_position]) { // This was the last boundary so we can stop processing. saw_last_boundary_ = true; - data_.Clear(); + data_.clear(); return; } @@ -120,7 +120,7 @@ // it to the client. if (!is_parsing_headers_ && !data_.IsEmpty()) client_->MultipartDataReceived(data_.Data(), data_.size()); - data_.Clear(); + data_.clear(); saw_last_boundary_ = true; }
diff --git a/third_party/WebKit/Source/core/page/CustomContextMenuProvider.cpp b/third_party/WebKit/Source/core/page/CustomContextMenuProvider.cpp index 2a80d465..bbfe4bc 100644 --- a/third_party/WebKit/Source/core/page/CustomContextMenuProvider.cpp +++ b/third_party/WebKit/Source/core/page/CustomContextMenuProvider.cpp
@@ -47,7 +47,7 @@ } void CustomContextMenuProvider::ContextMenuCleared() { - menu_items_.Clear(); + menu_items_.clear(); subject_element_ = nullptr; }
diff --git a/third_party/WebKit/Source/core/page/PrintContext.cpp b/third_party/WebKit/Source/core/page/PrintContext.cpp index ef2fec61..4e2d3cec 100644 --- a/third_party/WebKit/Source/core/page/PrintContext.cpp +++ b/third_party/WebKit/Source/core/page/PrintContext.cpp
@@ -54,7 +54,7 @@ float footer_height, float user_scale_factor, float& out_page_height) { - page_rects_.Clear(); + page_rects_.clear(); out_page_height = 0; if (!frame_->GetDocument() || !frame_->View() || @@ -89,7 +89,7 @@ void PrintContext::ComputePageRectsWithPageSize( const FloatSize& page_size_in_pixels) { - page_rects_.Clear(); + page_rects_.clear(); ComputePageRectsWithPageSizeInternal(page_size_in_pixels); }
diff --git a/third_party/WebKit/Source/core/page/TouchDisambiguation.cpp b/third_party/WebKit/Source/core/page/TouchDisambiguation.cpp index b7c6cb6..9603450 100644 --- a/third_party/WebKit/Source/core/page/TouchDisambiguation.cpp +++ b/third_party/WebKit/Source/core/page/TouchDisambiguation.cpp
@@ -90,7 +90,7 @@ LocalFrame* main_frame, Vector<IntRect>& good_targets, HeapVector<Member<Node>>& highlight_nodes) { - good_targets.Clear(); + good_targets.clear(); int touch_point_padding = ceil(std::max(touch_box_in_root_frame.Width(), touch_box_in_root_frame.Height()) *
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp b/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp index 66dfe99..4e4ff7a 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp
@@ -2074,7 +2074,7 @@ scrollable_area->SetNeedsRelayout(false); } - needs_relayout_->Clear(); + needs_relayout_->clear(); } layout_scope_ = nullptr; }
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerStackingNode.cpp b/third_party/WebKit/Source/core/paint/PaintLayerStackingNode.cpp index 3ec4267..8fd0e51 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerStackingNode.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerStackingNode.cpp
@@ -105,9 +105,9 @@ #endif if (pos_z_order_list_) - pos_z_order_list_->Clear(); + pos_z_order_list_->clear(); if (neg_z_order_list_) - neg_z_order_list_->Clear(); + neg_z_order_list_->clear(); z_order_lists_dirty_ = true; if (!GetLayoutObject().DocumentBeingDestroyed())
diff --git a/third_party/WebKit/Source/core/style/FilterOperations.h b/third_party/WebKit/Source/core/style/FilterOperations.h index e3a4b29a..755c3e7 100644 --- a/third_party/WebKit/Source/core/style/FilterOperations.h +++ b/third_party/WebKit/Source/core/style/FilterOperations.h
@@ -46,7 +46,7 @@ bool operator==(const FilterOperations&) const; bool operator!=(const FilterOperations& o) const { return !(*this == o); } - void Clear() { operations_.Clear(); } + void clear() { operations_.clear(); } typedef HeapVector<Member<FilterOperation>> FilterOperationVector;
diff --git a/third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp b/third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp index b124a47..9fe18d32 100644 --- a/third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp
@@ -49,7 +49,7 @@ // space before and after semicolon separators, is allowed and will be // ignored. // http://www.w3.org/TR/SVG11/animate.html#ValuesAttribute - result.Clear(); + result.clear(); Vector<String> parse_list; value.Split(';', true, parse_list); unsigned last = parse_list.size() - 1; @@ -66,14 +66,14 @@ return true; fail: - result.Clear(); + result.clear(); return false; } static bool ParseKeyTimes(const String& string, Vector<float>& result, bool verify_order) { - result.Clear(); + result.clear(); Vector<String> parse_list; string.Split(';', true, parse_list); for (unsigned n = 0; n < parse_list.size(); ++n) { @@ -94,7 +94,7 @@ } return true; fail: - result.Clear(); + result.clear(); return false; } @@ -137,7 +137,7 @@ static bool ParseKeySplines(const String& string, Vector<gfx::CubicBezier>& result) { - result.Clear(); + result.clear(); if (string.IsEmpty()) return true; bool parsed = true; @@ -146,7 +146,7 @@ else parsed = ParseKeySplinesInternal<UChar>(string, result); if (!parsed) { - result.Clear(); + result.clear(); return false; } return true; @@ -342,7 +342,7 @@ // FIXME, webkit.org/b/109010: m_keyTimes should not be modified in this // function. - key_times_.Clear(); + key_times_.clear(); Vector<float> key_times_for_paced; float total_distance = 0;
diff --git a/third_party/WebKit/Source/core/svg/SVGPathByteStream.h b/third_party/WebKit/Source/core/svg/SVGPathByteStream.h index 9937ba7..e07de52 100644 --- a/third_party/WebKit/Source/core/svg/SVGPathByteStream.h +++ b/third_party/WebKit/Source/core/svg/SVGPathByteStream.h
@@ -53,7 +53,7 @@ void Append(const unsigned char* data, size_t data_size) { data_.Append(data, data_size); } - void Clear() { data_.Clear(); } + void clear() { data_.clear(); } void ReserveInitialCapacity(size_t size) { data_.ReserveInitialCapacity(size); }
diff --git a/third_party/WebKit/Source/core/svg/SVGPathUtilities.cpp b/third_party/WebKit/Source/core/svg/SVGPathUtilities.cpp index 5a02fd0..e9383dc 100644 --- a/third_party/WebKit/Source/core/svg/SVGPathUtilities.cpp +++ b/third_party/WebKit/Source/core/svg/SVGPathUtilities.cpp
@@ -58,7 +58,7 @@ SVGParsingError BuildByteStreamFromString(const String& d, SVGPathByteStream& result) { - result.Clear(); + result.clear(); if (d.IsEmpty()) return SVGParseStatus::kNoError;
diff --git a/third_party/WebKit/Source/core/svg/SVGStringList.cpp b/third_party/WebKit/Source/core/svg/SVGStringList.cpp index 39f5a96..394fb7b 100644 --- a/third_party/WebKit/Source/core/svg/SVGStringList.cpp +++ b/third_party/WebKit/Source/core/svg/SVGStringList.cpp
@@ -34,7 +34,7 @@ SVGStringList::~SVGStringList() {} void SVGStringList::Initialize(const String& item) { - values_.Clear(); + values_.clear(); values_.push_back(item); } @@ -99,7 +99,7 @@ SVGParsingError SVGStringList::SetValueAsString(const String& data) { // FIXME: Add more error checking and reporting. - values_.Clear(); + values_.clear(); if (data.IsEmpty()) return SVGParseStatus::kNoError;
diff --git a/third_party/WebKit/Source/core/svg/SVGStringList.h b/third_party/WebKit/Source/core/svg/SVGStringList.h index 3da2f9b..fd00d72 100644 --- a/third_party/WebKit/Source/core/svg/SVGStringList.h +++ b/third_party/WebKit/Source/core/svg/SVGStringList.h
@@ -67,7 +67,7 @@ // SVGStringList DOM Spec implementation. These are only to be called from // SVGStringListTearOff: unsigned long length() { return values_.size(); } - void Clear() { values_.Clear(); } + void clear() { values_.clear(); } void Initialize(const String&); String GetItem(size_t, ExceptionState&); void InsertItemBefore(const String&, size_t);
diff --git a/third_party/WebKit/Source/core/svg/SVGStringListTearOff.h b/third_party/WebKit/Source/core/svg/SVGStringListTearOff.h index 818abdd..46c86068 100644 --- a/third_party/WebKit/Source/core/svg/SVGStringListTearOff.h +++ b/third_party/WebKit/Source/core/svg/SVGStringListTearOff.h
@@ -61,7 +61,7 @@ ThrowReadOnly(exception_state); return; } - Target()->Clear(); + Target()->clear(); CommitChange(); }
diff --git a/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp b/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp index 8a7c6fd..8d45636 100644 --- a/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp +++ b/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp
@@ -238,7 +238,7 @@ void SVGSMILElement::ClearConditions() { DisconnectSyncBaseConditions(); DisconnectEventBaseConditions(); - conditions_.Clear(); + conditions_.clear(); } void SVGSMILElement::BuildPendingResource() {
diff --git a/third_party/WebKit/Source/core/svg/properties/SVGListPropertyHelper.h b/third_party/WebKit/Source/core/svg/properties/SVGListPropertyHelper.h index d6ddf42c..072979f7 100644 --- a/third_party/WebKit/Source/core/svg/properties/SVGListPropertyHelper.h +++ b/third_party/WebKit/Source/core/svg/properties/SVGListPropertyHelper.h
@@ -179,7 +179,7 @@ (*it)->SetOwnerList(nullptr); } - values_.Clear(); + values_.clear(); } template <typename Derived, typename ItemProperty>
diff --git a/third_party/WebKit/Source/core/timing/PerformanceBase.cpp b/third_party/WebKit/Source/core/timing/PerformanceBase.cpp index 89b35e61..1f5902d 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceBase.cpp +++ b/third_party/WebKit/Source/core/timing/PerformanceBase.cpp
@@ -207,7 +207,7 @@ } void PerformanceBase::clearResourceTimings() { - resource_timing_buffer_.Clear(); + resource_timing_buffer_.clear(); } void PerformanceBase::setResourceTimingBufferSize(unsigned size) { @@ -217,7 +217,7 @@ } void PerformanceBase::clearFrameTimings() { - frame_timing_buffer_.Clear(); + frame_timing_buffer_.clear(); } void PerformanceBase::setFrameTimingBufferSize(unsigned size) {
diff --git a/third_party/WebKit/Source/core/timing/PerformanceObserver.cpp b/third_party/WebKit/Source/core/timing/PerformanceObserver.cpp index ac49c2c2..1db78d24 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceObserver.cpp +++ b/third_party/WebKit/Source/core/timing/PerformanceObserver.cpp
@@ -65,7 +65,7 @@ if (performance_) { performance_->UnregisterPerformanceObserver(*this); } - performance_entries_.Clear(); + performance_entries_.clear(); is_registered_ = false; }
diff --git a/third_party/WebKit/Source/core/workers/InProcessWorkerMessagingProxy.cpp b/third_party/WebKit/Source/core/workers/InProcessWorkerMessagingProxy.cpp index bc0a6f1..2b7f52cd 100644 --- a/third_party/WebKit/Source/core/workers/InProcessWorkerMessagingProxy.cpp +++ b/third_party/WebKit/Source/core/workers/InProcessWorkerMessagingProxy.cpp
@@ -199,7 +199,7 @@ CrossThreadUnretained(GetWorkerThread())); GetWorkerThread()->PostTask(BLINK_FROM_HERE, std::move(task)); } - queued_early_tasks_.Clear(); + queued_early_tasks_.clear(); } void InProcessWorkerMessagingProxy::ParentObjectDestroyed() {
diff --git a/third_party/WebKit/Source/core/xml/XPathNodeSet.h b/third_party/WebKit/Source/core/xml/XPathNodeSet.h index e2cdf75d..be9d412 100644 --- a/third_party/WebKit/Source/core/xml/XPathNodeSet.h +++ b/third_party/WebKit/Source/core/xml/XPathNodeSet.h
@@ -52,7 +52,7 @@ void ReserveCapacity(size_t new_capacity) { nodes_.ReserveCapacity(new_capacity); } - void Clear() { nodes_.Clear(); } + void clear() { nodes_.clear(); } void Swap(NodeSet& other) { std::swap(is_sorted_, other.is_sorted_); std::swap(subtrees_are_disjoint_, other.subtrees_are_disjoint_);
diff --git a/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp b/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp index 8b03338..99a71764 100644 --- a/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp +++ b/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp
@@ -315,7 +315,7 @@ leaf_text_node_ = nullptr; if (current_node_stack_.size()) { // Aborted parsing. - current_node_stack_.Clear(); + current_node_stack_.clear(); } } @@ -367,7 +367,7 @@ leaf_text_node_->appendData( ToString(buffered_text_.Data(), buffered_text_.size())); - buffered_text_.Clear(); + buffered_text_.clear(); leaf_text_node_ = nullptr; // Mutation event handlers executed by appendData() might detach this parser.
diff --git a/third_party/WebKit/Source/modules/accessibility/AXLayoutObject.cpp b/third_party/WebKit/Source/modules/accessibility/AXLayoutObject.cpp index c4065f5..ce2fc51 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXLayoutObject.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXLayoutObject.cpp
@@ -1178,7 +1178,7 @@ if (layout_object_->GetFrame()) return String(); - ASSERT_NOT_REACHED(); + NOTREACHED(); } if (IsTextControl())
diff --git a/third_party/WebKit/Source/modules/accessibility/AXNodeObject.cpp b/third_party/WebKit/Source/modules/accessibility/AXNodeObject.cpp index 71d0042..ba43089 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXNodeObject.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXNodeObject.cpp
@@ -1800,7 +1800,7 @@ current = current->Parent(); } - ASSERT_NOT_REACHED(); + NOTREACHED(); return nullptr; } @@ -2760,7 +2760,7 @@ local_related_objects.push_back(new NameSourceRelatedObject( figcaption_ax_object, text_alternative)); *related_objects = local_related_objects; - local_related_objects.Clear(); + local_related_objects.clear(); } if (name_sources) { @@ -2821,7 +2821,7 @@ local_related_objects.push_back( new NameSourceRelatedObject(caption_ax_object, text_alternative)); *related_objects = local_related_objects; - local_related_objects.Clear(); + local_related_objects.clear(); } if (name_sources) { @@ -2878,7 +2878,7 @@ local_related_objects.push_back( new NameSourceRelatedObject(title_ax_object, text_alternative)); *related_objects = local_related_objects; - local_related_objects.Clear(); + local_related_objects.clear(); } } if (name_sources) { @@ -2912,7 +2912,7 @@ local_related_objects.push_back( new NameSourceRelatedObject(legend_ax_object, text_alternative)); *related_objects = local_related_objects; - local_related_objects.Clear(); + local_related_objects.clear(); } if (name_sources) { @@ -2970,7 +2970,7 @@ local_related_objects.push_back( new NameSourceRelatedObject(title_ax_object, text_alternative)); *related_objects = local_related_objects; - local_related_objects.Clear(); + local_related_objects.clear(); } if (name_sources) { @@ -2995,7 +2995,7 @@ String result = Description(name_from, description_from, nullptr, &related_objects); if (description_objects) { - description_objects->Clear(); + description_objects->clear(); for (size_t i = 0; i < related_objects.size(); i++) description_objects->push_back(related_objects[i]->object); }
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObject.cpp b/third_party/WebKit/Source/modules/accessibility/AXObject.cpp index 325ba70..c775e18 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXObject.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXObject.cpp
@@ -762,7 +762,7 @@ text = CollapseWhitespace(text); if (name_objects) { - name_objects->Clear(); + name_objects->clear(); for (size_t i = 0; i < related_objects.size(); i++) name_objects->push_back(related_objects[i]->object); } @@ -1211,7 +1211,7 @@ for (const auto& child : children_) child->DetachFromParent(); - children_.Clear(); + children_.clear(); have_children_ = false; }
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.cpp b/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.cpp index 1966982a..c3d401c 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.cpp
@@ -651,7 +651,7 @@ ChildrenChanged(obj->ParentObject()); } - notifications_to_post_.Clear(); + notifications_to_post_.clear(); } void AXObjectCacheImpl::PostNotification(LayoutObject* layout_object,
diff --git a/third_party/WebKit/Source/modules/accessibility/AXTable.cpp b/third_party/WebKit/Source/modules/accessibility/AXTable.cpp index fcabff0..d50e4d1 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXTable.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXTable.cpp
@@ -355,8 +355,8 @@ void AXTable::ClearChildren() { AXLayoutObject::ClearChildren(); - rows_.Clear(); - columns_.Clear(); + rows_.clear(); + columns_.clear(); if (header_container_) { header_container_->DetachFromParent();
diff --git a/third_party/WebKit/Source/modules/accessibility/InspectorAccessibilityAgent.cpp b/third_party/WebKit/Source/modules/accessibility/InspectorAccessibilityAgent.cpp index dca7729..418ac16c 100644 --- a/third_party/WebKit/Source/modules/accessibility/InspectorAccessibilityAgent.cpp +++ b/third_party/WebKit/Source/modules/accessibility/InspectorAccessibilityAgent.cpp
@@ -417,13 +417,13 @@ properties.addItem(CreateRelatedNodeListProperty( AXRelationshipAttributesEnum::Describedby, results, aria_describedbyAttr, ax_object)); - results.Clear(); + results.clear(); ax_object.AriaOwnsElements(results); if (!results.IsEmpty()) properties.addItem(CreateRelatedNodeListProperty( AXRelationshipAttributesEnum::Owns, results, aria_ownsAttr, ax_object)); - results.Clear(); + results.clear(); } std::unique_ptr<AXValue> CreateRoleNameValue(AccessibilityRole role) {
diff --git a/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.cpp b/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.cpp index 45d141a..33e3291 100644 --- a/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.cpp +++ b/third_party/WebKit/Source/modules/accessibility/InspectorTypeBuilderHelper.cpp
@@ -55,7 +55,7 @@ case kAXUninteresting: return "uninteresting"; } - ASSERT_NOT_REACHED(); + NOTREACHED(); return ""; }
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp index 594c44d4..25d0c375 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp
@@ -554,7 +554,7 @@ void CanvasRenderingContext2D::ClearFilterReferences() { filter_operations_.RemoveClient(this); - filter_operations_.Clear(); + filter_operations_.clear(); } void CanvasRenderingContext2D::UpdateFilterReferences(
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeyStatusMap.cpp b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeyStatusMap.cpp index b1b5fba..d1dd838c 100644 --- a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeyStatusMap.cpp +++ b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeyStatusMap.cpp
@@ -103,7 +103,7 @@ }; void MediaKeyStatusMap::Clear() { - entries_.Clear(); + entries_.clear(); } void MediaKeyStatusMap::AddEntry(WebData key_id, const String& status) {
diff --git a/third_party/WebKit/Source/modules/eventsource/EventSourceParser.cpp b/third_party/WebKit/Source/modules/eventsource/EventSourceParser.cpp index 59f3a62..e9552c4 100644 --- a/third_party/WebKit/Source/modules/eventsource/EventSourceParser.cpp +++ b/third_party/WebKit/Source/modules/eventsource/EventSourceParser.cpp
@@ -38,7 +38,7 @@ is_recognizing_bom_ = false; if (memcmp(line.Data(), kBOM, sizeof(kBOM)) == 0) { start = i; - line_.Clear(); + line_.clear(); continue; } } @@ -52,7 +52,7 @@ if (bytes[i] == '\r' || bytes[i] == '\n') { line_.Append(&bytes[start], i - start); ParseLine(); - line_.Clear(); + line_.clear(); start = i + 1; is_recognizing_crlf_ = bytes[i] == '\r'; is_recognizing_bom_ = false; @@ -73,7 +73,7 @@ client_->OnMessageEvent( event_type_.IsEmpty() ? EventTypeNames::message : event_type_, data, last_event_id_); - data_.Clear(); + data_.clear(); } event_type_ = g_null_atom; return;
diff --git a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp index 438e3b9..e385915 100644 --- a/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp +++ b/third_party/WebKit/Source/modules/fetch/DataConsumerHandleTestUtil.cpp
@@ -282,7 +282,7 @@ } std::unique_ptr<HandleReadResult> result = WTF::MakeUnique<HandleReadResult>(r, data_); - data_.Clear(); + data_.clear(); Platform::Current()->CurrentThread()->GetWebTaskRunner()->PostTask( BLINK_FROM_HERE, WTF::Bind(&HandleReader::RunOnFinishedReading, WTF::Unretained(this), @@ -322,7 +322,7 @@ } std::unique_ptr<HandleReadResult> result = WTF::MakeUnique<HandleReadResult>(r, data_); - data_.Clear(); + data_.clear(); Platform::Current()->CurrentThread()->GetWebTaskRunner()->PostTask( BLINK_FROM_HERE, WTF::Bind(&HandleTwoPhaseReader::RunOnFinishedReading,
diff --git a/third_party/WebKit/Source/modules/fetch/FetchHeaderList.cpp b/third_party/WebKit/Source/modules/fetch/FetchHeaderList.cpp index 42111cf..22da9b04 100644 --- a/third_party/WebKit/Source/modules/fetch/FetchHeaderList.cpp +++ b/third_party/WebKit/Source/modules/fetch/FetchHeaderList.cpp
@@ -110,7 +110,7 @@ // This is going to be removed: see crbug.com/645492. void FetchHeaderList::GetAll(const String& name, Vector<String>& result) const { - result.Clear(); + result.clear(); auto range = header_list_.equal_range(name); for (auto header = range.first; header != range.second; ++header) { result.push_back(header->second);
diff --git a/third_party/WebKit/Source/modules/fetch/FormDataBytesConsumer.cpp b/third_party/WebKit/Source/modules/fetch/FormDataBytesConsumer.cpp index 245def42..c7ab8cd 100644 --- a/third_party/WebKit/Source/modules/fetch/FormDataBytesConsumer.cpp +++ b/third_party/WebKit/Source/modules/fetch/FormDataBytesConsumer.cpp
@@ -82,7 +82,7 @@ void Cancel() override { state_ = PublicState::kClosed; form_data_ = nullptr; - flatten_form_data_.Clear(); + flatten_form_data_.clear(); flatten_form_data_offset_ = 0; } PublicState GetPublicState() const override { return state_; }
diff --git a/third_party/WebKit/Source/modules/filesystem/DirectoryReader.cpp b/third_party/WebKit/Source/modules/filesystem/DirectoryReader.cpp index 4ef55e4..e46b840 100644 --- a/third_party/WebKit/Source/modules/filesystem/DirectoryReader.cpp +++ b/third_party/WebKit/Source/modules/filesystem/DirectoryReader.cpp
@@ -109,7 +109,7 @@ WrapPersistent(entries_callback), PersistentHeapVector<Member<Entry>>(entries_))); } - entries_.Clear(); + entries_.clear(); return; }
diff --git a/third_party/WebKit/Source/modules/indexeddb/IDBRequest.cpp b/third_party/WebKit/Source/modules/indexeddb/IDBRequest.cpp index 1c27879..bea4fbb 100644 --- a/third_party/WebKit/Source/modules/indexeddb/IDBRequest.cpp +++ b/third_party/WebKit/Source/modules/indexeddb/IDBRequest.cpp
@@ -159,7 +159,7 @@ bool removed = event_queue->CancelEvent(enqueued_events_[i].Get()); DCHECK(removed); } - enqueued_events_.Clear(); + enqueued_events_.clear(); error_.Clear(); result_.Clear(); @@ -397,7 +397,7 @@ } } - enqueued_events_.Clear(); + enqueued_events_.clear(); if (source_) source_->ContextWillBeDestroyed(); if (result_)
diff --git a/third_party/WebKit/Source/modules/indexeddb/IDBTransaction.cpp b/third_party/WebKit/Source/modules/indexeddb/IDBTransaction.cpp index b2e99e8..c581c0e 100644 --- a/third_party/WebKit/Source/modules/indexeddb/IDBTransaction.cpp +++ b/third_party/WebKit/Source/modules/indexeddb/IDBTransaction.cpp
@@ -616,8 +616,8 @@ } old_store_metadata_.Clear(); - deleted_indexes_.Clear(); - deleted_object_stores_.Clear(); + deleted_indexes_.clear(); + deleted_object_stores_.clear(); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/mediasource/SourceBuffer.cpp b/third_party/WebKit/Source/modules/mediasource/SourceBuffer.cpp index 3d525518..1d5aa21e 100644 --- a/third_party/WebKit/Source/modules/mediasource/SourceBuffer.cpp +++ b/third_party/WebKit/Source/modules/mediasource/SourceBuffer.cpp
@@ -541,7 +541,7 @@ // 4.1. Abort the buffer append and stream append loop algorithms if they are // running. append_buffer_async_part_runner_->Stop(); - pending_append_data_.Clear(); + pending_append_data_.clear(); pending_append_data_offset_ = 0; // 4.2. Set the updating attribute to false. @@ -1218,7 +1218,7 @@ web_source_buffer_->Append(append_data, append_size, ×tamp_offset_); if (!append_success) { - pending_append_data_.Clear(); + pending_append_data_.clear(); pending_append_data_offset_ = 0; AppendError(); } else { @@ -1233,7 +1233,7 @@ // 3. Set the updating attribute to false. updating_ = false; - pending_append_data_.Clear(); + pending_append_data_.clear(); pending_append_data_offset_ = 0; // 4. Queue a task to fire a simple event named update at this SourceBuffer
diff --git a/third_party/WebKit/Source/modules/mediasource/SourceBufferList.cpp b/third_party/WebKit/Source/modules/mediasource/SourceBufferList.cpp index a582e319..edd2228 100644 --- a/third_party/WebKit/Source/modules/mediasource/SourceBufferList.cpp +++ b/third_party/WebKit/Source/modules/mediasource/SourceBufferList.cpp
@@ -61,7 +61,7 @@ } void SourceBufferList::Clear() { - list_.Clear(); + list_.clear(); ScheduleEvent(EventTypeNames::removesourcebuffer); }
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaStream.cpp b/third_party/WebKit/Source/modules/mediastream/MediaStream.cpp index 2b52b45..cbe9a36 100644 --- a/third_party/WebKit/Source/modules/mediastream/MediaStream.cpp +++ b/third_party/WebKit/Source/modules/mediastream/MediaStream.cpp
@@ -416,7 +416,7 @@ for (; it != events.end(); ++it) DispatchEvent((*it).Release()); - events.Clear(); + events.clear(); } URLRegistry& MediaStream::Registry() const {
diff --git a/third_party/WebKit/Source/modules/payments/PaymentRequest.cpp b/third_party/WebKit/Source/modules/payments/PaymentRequest.cpp index 996611e9..e517e71e 100644 --- a/third_party/WebKit/Source/modules/payments/PaymentRequest.cpp +++ b/third_party/WebKit/Source/modules/payments/PaymentRequest.cpp
@@ -196,7 +196,7 @@ if (unique_ids.Contains(option.id())) { // Clear |output| instead of throwing an exception. - output.Clear(); + output.clear(); return; }
diff --git a/third_party/WebKit/Source/modules/peerconnection/RTCDataChannel.cpp b/third_party/WebKit/Source/modules/peerconnection/RTCDataChannel.cpp index fcecd8e..59de81cc 100644 --- a/third_party/WebKit/Source/modules/peerconnection/RTCDataChannel.cpp +++ b/third_party/WebKit/Source/modules/peerconnection/RTCDataChannel.cpp
@@ -372,7 +372,7 @@ for (; it != events.end(); ++it) DispatchEvent((*it).Release()); - events.Clear(); + events.clear(); } DEFINE_TRACE(RTCDataChannel) {
diff --git a/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp b/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp index dd52150..ce87c6f 100644 --- a/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp +++ b/third_party/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp
@@ -1534,7 +1534,7 @@ } } - events.Clear(); + events.clear(); } void RTCPeerConnection::RecordRapporMetrics() {
diff --git a/third_party/WebKit/Source/modules/peerconnection/RTCRtpReceiver.cpp b/third_party/WebKit/Source/modules/peerconnection/RTCRtpReceiver.cpp index 3f57b445..2318256 100644 --- a/third_party/WebKit/Source/modules/peerconnection/RTCRtpReceiver.cpp +++ b/third_party/WebKit/Source/modules/peerconnection/RTCRtpReceiver.cpp
@@ -31,7 +31,7 @@ void RTCRtpReceiver::UpdateSourcesIfNeeded() { if (!contributing_sources_needs_updating_) return; - contributing_sources_.Clear(); + contributing_sources_.clear(); for (const std::unique_ptr<WebRTCRtpContributingSource>& web_contributing_source : receiver_->GetSources()) { if (web_contributing_source->SourceType() ==
diff --git a/third_party/WebKit/Source/modules/plugins/PluginOcclusionSupport.cpp b/third_party/WebKit/Source/modules/plugins/PluginOcclusionSupport.cpp index 137c778..745a0ef 100644 --- a/third_party/WebKit/Source/modules/plugins/PluginOcclusionSupport.cpp +++ b/third_party/WebKit/Source/modules/plugins/PluginOcclusionSupport.cpp
@@ -48,7 +48,7 @@ static void GetObjectStack(const LayoutObject* ro, Vector<const LayoutObject*>* ro_stack) { - ro_stack->Clear(); + ro_stack->clear(); while (ro) { ro_stack->push_back(ro); ro = ro->Parent();
diff --git a/third_party/WebKit/Source/modules/sensor/SensorProxy.cpp b/third_party/WebKit/Source/modules/sensor/SensorProxy.cpp index d5f7e3a..b9066464 100644 --- a/third_party/WebKit/Source/modules/sensor/SensorProxy.cpp +++ b/third_party/WebKit/Source/modules/sensor/SensorProxy.cpp
@@ -167,7 +167,7 @@ void SensorProxy::HandleSensorError() { state_ = kUninitialized; - frequencies_used_.Clear(); + frequencies_used_.clear(); reading_ = device::SensorReading(); // The m_sensor.reset() will release all callbacks and its bound parameters,
diff --git a/third_party/WebKit/Source/modules/speech/SpeechRecognition.cpp b/third_party/WebKit/Source/modules/speech/SpeechRecognition.cpp index 827a541..7d8a9cb 100644 --- a/third_party/WebKit/Source/modules/speech/SpeechRecognition.cpp +++ b/third_party/WebKit/Source/modules/speech/SpeechRecognition.cpp
@@ -53,7 +53,7 @@ return; } - final_results_.Clear(); + final_results_.clear(); controller_->Start(this, grammars_, lang_, continuous_, interim_results_, max_alternatives_, audio_track_); started_ = true;
diff --git a/third_party/WebKit/Source/modules/speech/SpeechSynthesis.cpp b/third_party/WebKit/Source/modules/speech/SpeechSynthesis.cpp index a6c620f..fd97662a3 100644 --- a/third_party/WebKit/Source/modules/speech/SpeechSynthesis.cpp +++ b/third_party/WebKit/Source/modules/speech/SpeechSynthesis.cpp
@@ -47,7 +47,7 @@ } void SpeechSynthesis::VoicesDidChange() { - voice_list_.Clear(); + voice_list_.clear(); if (GetExecutionContext()) DispatchEvent(Event::Create(EventTypeNames::voiceschanged)); }
diff --git a/third_party/WebKit/Source/modules/speech/testing/PlatformSpeechSynthesizerMock.cpp b/third_party/WebKit/Source/modules/speech/testing/PlatformSpeechSynthesizerMock.cpp index 7eb0e6c4..f3e85e2b 100644 --- a/third_party/WebKit/Source/modules/speech/testing/PlatformSpeechSynthesizerMock.cpp +++ b/third_party/WebKit/Source/modules/speech/testing/PlatformSpeechSynthesizerMock.cpp
@@ -76,7 +76,7 @@ } void PlatformSpeechSynthesizerMock::InitializeVoiceList() { - voice_list_.Clear(); + voice_list_.clear(); voice_list_.push_back(PlatformSpeechSynthesisVoice::Create( String("mock.voice.bruce"), String("bruce"), String("en-US"), true, true));
diff --git a/third_party/WebKit/Source/modules/vibration/NavigatorVibration.cpp b/third_party/WebKit/Source/modules/vibration/NavigatorVibration.cpp index 0ab176f..0321257 100644 --- a/third_party/WebKit/Source/modules/vibration/NavigatorVibration.cpp +++ b/third_party/WebKit/Source/modules/vibration/NavigatorVibration.cpp
@@ -20,10 +20,13 @@ #include "modules/vibration/NavigatorVibration.h" #include "core/dom/Document.h" +#include "core/frame/Deprecation.h" +#include "core/frame/FrameConsole.h" #include "core/frame/LocalDOMWindow.h" #include "core/frame/LocalFrame.h" #include "core/frame/Navigator.h" #include "core/frame/UseCounter.h" +#include "core/inspector/ConsoleMessage.h" #include "core/page/Page.h" #include "modules/vibration/VibrationController.h" #include "platform/Histogram.h" @@ -89,13 +92,31 @@ return false; } - if (!RuntimeEnabledFeatures::featurePolicyEnabled() && - frame->IsCrossOriginSubframe() && !frame->HasReceivedUserGesture()) { - frame->DomWindow()->PrintErrorMessage( - "Blocked call to navigator.vibrate inside a cross-origin iframe " - "because the frame has never been activated by the user: " - "https://www.chromestatus.com/feature/5682658461876224."); - return false; + if (!frame->HasReceivedUserGesture()) { + String message; + MessageLevel level = kErrorMessageLevel; + if (frame->IsCrossOriginSubframe()) { + message = + "Blocked call to navigator.vibrate inside a cross-origin " + "iframe because the frame has never been activated by the user: " + "https://www.chromestatus.com/feature/5682658461876224."; + } else if (RuntimeEnabledFeatures::vibrateRequiresUserGestureEnabled()) { + // The actual blocking is targeting M60. + message = + "Blocked call to navigator.vibrate because user hasn't tapped " + "on the frame or any embedded frame yet: " + "https://www.chromestatus.com/feature/5644273861001216."; + } else { // Just shows the deprecation message in M59. + level = kWarningMessageLevel; + Deprecation::CountDeprecation(frame, + UseCounter::kVibrateWithoutUserGesture); + } + + if (level == kErrorMessageLevel) { + frame->DomWindow()->GetFrameConsole()->AddMessage( + ConsoleMessage::Create(kInterventionMessageSource, level, message)); + return false; + } } return NavigatorVibration::From(navigator).Controller(*frame)->Vibrate(
diff --git a/third_party/WebKit/Source/modules/vibration/VibrationController.cpp b/third_party/WebKit/Source/modules/vibration/VibrationController.cpp index d655810..dab6a738 100644 --- a/third_party/WebKit/Source/modules/vibration/VibrationController.cpp +++ b/third_party/WebKit/Source/modules/vibration/VibrationController.cpp
@@ -102,7 +102,7 @@ return true; if (pattern_.size() == 1 && !pattern_[0]) { - pattern_.Clear(); + pattern_.clear(); return true; } @@ -158,7 +158,7 @@ } void VibrationController::Cancel() { - pattern_.Clear(); + pattern_.clear(); timer_do_vibrate_.Stop(); if (is_running_ && !is_calling_cancel_ && vibration_manager_) {
diff --git a/third_party/WebKit/Source/modules/vr/VRController.cpp b/third_party/WebKit/Source/modules/vr/VRController.cpp index cbbcda1..f8a3877 100644 --- a/third_party/WebKit/Source/modules/vr/VRController.cpp +++ b/third_party/WebKit/Source/modules/vr/VRController.cpp
@@ -110,7 +110,7 @@ for (const auto& display : displays_) display->Dispose(); - displays_.Clear(); + displays_.clear(); // Ensure that any outstanding getDisplays promises are resolved. OnGetDisplays();
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioParamTimeline.cpp b/third_party/WebKit/Source/modules/webaudio/AudioParamTimeline.cpp index 2e89cce3b..ab637d1 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioParamTimeline.cpp +++ b/third_party/WebKit/Source/modules/webaudio/AudioParamTimeline.cpp
@@ -1127,7 +1127,7 @@ // value. FillWithDefault(values, default_value, number_of_values, 0); smoothed_value_ = default_value; - events_.Clear(); + events_.clear(); return true; }
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioWorkletGlobalScope.cpp b/third_party/WebKit/Source/modules/webaudio/AudioWorkletGlobalScope.cpp index f93e04a0..e42afbd 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioWorkletGlobalScope.cpp +++ b/third_party/WebKit/Source/modules/webaudio/AudioWorkletGlobalScope.cpp
@@ -44,7 +44,7 @@ void AudioWorkletGlobalScope::Dispose() { DCHECK(IsContextThread()); processor_definition_map_.Clear(); - processor_instances_.Clear(); + processor_instances_.clear(); ThreadedWorkletGlobalScope::Dispose(); }
diff --git a/third_party/WebKit/Source/modules/webaudio/BaseAudioContext.cpp b/third_party/WebKit/Source/modules/webaudio/BaseAudioContext.cpp index d58dd559..114f3d7 100644 --- a/third_party/WebKit/Source/modules/webaudio/BaseAudioContext.cpp +++ b/third_party/WebKit/Source/modules/webaudio/BaseAudioContext.cpp
@@ -688,7 +688,7 @@ } } } - finished_source_handlers_.Clear(); + finished_source_handlers_.clear(); return did_remove; } @@ -705,7 +705,7 @@ for (auto& source_node : active_source_nodes_) source_node->Handler().BreakConnection(); - active_source_nodes_.Clear(); + active_source_nodes_.clear(); } void BaseAudioContext::HandleStoppableSourceNodes() { @@ -793,7 +793,7 @@ } } - resume_resolvers_.Clear(); + resume_resolvers_.clear(); is_resolving_resume_promises_ = false; } @@ -863,7 +863,7 @@ resolver->Reject(DOMException::Create(kInvalidStateError, "Audio context is going away")); } - resume_resolvers_.Clear(); + resume_resolvers_.clear(); is_resolving_resume_promises_ = false; RejectPendingDecodeAudioDataResolvers();
diff --git a/third_party/WebKit/Source/modules/webaudio/DeferredTaskHandler.cpp b/third_party/WebKit/Source/modules/webaudio/DeferredTaskHandler.cpp index eee6e54..0603919 100644 --- a/third_party/WebKit/Source/modules/webaudio/DeferredTaskHandler.cpp +++ b/third_party/WebKit/Source/modules/webaudio/DeferredTaskHandler.cpp
@@ -86,7 +86,7 @@ for (unsigned i = 0; i < deferred_break_connection_list_.size(); ++i) deferred_break_connection_list_[i]->BreakConnectionWithLock(); - deferred_break_connection_list_.Clear(); + deferred_break_connection_list_.clear(); } void DeferredTaskHandler::MarkSummingJunctionDirty( @@ -265,7 +265,7 @@ if (rendering_orphan_handlers_.IsEmpty()) return; deletable_orphan_handlers_.AppendVector(rendering_orphan_handlers_); - rendering_orphan_handlers_.Clear(); + rendering_orphan_handlers_.clear(); Platform::Current()->MainThread()->GetWebTaskRunner()->PostTask( BLINK_FROM_HERE, CrossThreadBind(&DeferredTaskHandler::DeleteHandlersOnMainThread, @@ -275,14 +275,14 @@ void DeferredTaskHandler::DeleteHandlersOnMainThread() { DCHECK(IsMainThread()); AutoLocker locker(*this); - deletable_orphan_handlers_.Clear(); + deletable_orphan_handlers_.clear(); } void DeferredTaskHandler::ClearHandlersToBeDeleted() { DCHECK(IsMainThread()); AutoLocker locker(*this); - rendering_orphan_handlers_.Clear(); - deletable_orphan_handlers_.Clear(); + rendering_orphan_handlers_.clear(); + deletable_orphan_handlers_.clear(); } void DeferredTaskHandler::SetAudioThreadToCurrentThread() {
diff --git a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp index 3d554f9a..c0ae1b65 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp
@@ -219,20 +219,20 @@ GLint num_combined_texture_image_units = 0; ContextGL()->GetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &num_combined_texture_image_units); - sampler_units_.Clear(); + sampler_units_.clear(); sampler_units_.Resize(num_combined_texture_image_units); max_transform_feedback_separate_attribs_ = 0; ContextGL()->GetIntegerv(GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS, &max_transform_feedback_separate_attribs_); - bound_indexed_transform_feedback_buffers_.Clear(); + bound_indexed_transform_feedback_buffers_.clear(); bound_indexed_transform_feedback_buffers_.Resize( max_transform_feedback_separate_attribs_); GLint max_uniform_buffer_bindings = 0; ContextGL()->GetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, &max_uniform_buffer_bindings); - bound_indexed_uniform_buffers_.Clear(); + bound_indexed_uniform_buffers_.clear(); bound_indexed_uniform_buffers_.Resize(max_uniform_buffer_bindings); max_bound_uniform_buffer_index_ = 0;
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp index 8216a1f..f4be992 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp
@@ -1174,7 +1174,7 @@ GLint num_combined_texture_image_units = 0; ContextGL()->GetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &num_combined_texture_image_units); - texture_units_.Clear(); + texture_units_.clear(); texture_units_.Resize(num_combined_texture_image_units); GLint num_vertex_attribs = 0; @@ -1298,7 +1298,7 @@ } void WebGLRenderingContextBase::RemoveAllCompressedTextureFormats() { - compressed_texture_formats_.Clear(); + compressed_texture_formats_.clear(); } // Helper function for V8 bindings to identify what version of WebGL a @@ -7562,7 +7562,7 @@ WrapWeakPersistent(this))); GetDrawingBuffer()->Bind(GL_FRAMEBUFFER); - lost_context_errors_.Clear(); + lost_context_errors_.clear(); context_lost_mode_ = kNotLostContext; auto_recovery_method_ = kManual; restore_allowed_ = false;
diff --git a/third_party/WebKit/Source/modules/webmidi/MIDIAccess.cpp b/third_party/WebKit/Source/modules/webmidi/MIDIAccess.cpp index c78139f5..9429e72 100644 --- a/third_party/WebKit/Source/modules/webmidi/MIDIAccess.cpp +++ b/third_party/WebKit/Source/modules/webmidi/MIDIAccess.cpp
@@ -115,7 +115,7 @@ } if (inputs.size() != ids.size()) { // There is id duplication that violates the spec. - inputs.Clear(); + inputs.clear(); } return new MIDIInputMap(inputs); } @@ -132,7 +132,7 @@ } if (outputs.size() != ids.size()) { // There is id duplication that violates the spec. - outputs.Clear(); + outputs.clear(); } return new MIDIOutputMap(outputs); }
diff --git a/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannel.cpp b/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannel.cpp index 40965e76..6be8c03 100644 --- a/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannel.cpp +++ b/third_party/WebKit/Source/modules/websockets/DocumentWebSocketChannel.cpp
@@ -605,7 +605,7 @@ ? g_empty_string : String::FromUTF8(receiving_message_data_.Data(), receiving_message_data_.size()); - receiving_message_data_.Clear(); + receiving_message_data_.clear(); if (message.IsNull()) { FailAsError("Could not decode a text frame as UTF-8."); // failAsError may delete this object.
diff --git a/third_party/WebKit/Source/platform/ContextMenuItem.cpp b/third_party/WebKit/Source/platform/ContextMenuItem.cpp index 8721bce..b04d1ad 100644 --- a/third_party/WebKit/Source/platform/ContextMenuItem.cpp +++ b/third_party/WebKit/Source/platform/ContextMenuItem.cpp
@@ -77,7 +77,7 @@ sub_menu_items_ = sub_menu->Items(); } else { type_ = kActionType; - sub_menu_items_.Clear(); + sub_menu_items_.clear(); } }
diff --git a/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.json5 b/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.json5 index ce58ba9b..002e02b 100644 --- a/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.json5 +++ b/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.json5
@@ -948,6 +948,10 @@ name: "V8IdleTasks", }, { + name: "VibrateRequiresUserGesture", + status: "experimental", + }, + { name: "VideoFullscreenDetection", }, { @@ -974,9 +978,9 @@ status: "experimental", }, { - name: "WebAssemblySerialization", - status: "test", - }, + name: "WebAssemblyStreaming", + status: "experimental", + }, { name: "WebAuth", status: "experimental",
diff --git a/third_party/WebKit/Source/platform/SharedBuffer.cpp b/third_party/WebKit/Source/platform/SharedBuffer.cpp index 9fd75a0..357969f6 100644 --- a/third_party/WebKit/Source/platform/SharedBuffer.cpp +++ b/third_party/WebKit/Source/platform/SharedBuffer.cpp
@@ -135,9 +135,9 @@ for (size_t i = 0; i < segments_.size(); ++i) FreeSegment(segments_[i]); - segments_.Clear(); + segments_.clear(); size_ = 0; - buffer_.Clear(); + buffer_.clear(); } PassRefPtr<SharedBuffer> SharedBuffer::Copy() const { @@ -168,7 +168,7 @@ bytes_left -= bytes_to_copy; FreeSegment(segments_[i]); } - segments_.Clear(); + segments_.clear(); } }
diff --git a/third_party/WebKit/Source/platform/SharedBufferChunkReader.cpp b/third_party/WebKit/Source/platform/SharedBufferChunkReader.cpp index d82b71d..358278e34 100644 --- a/third_party/WebKit/Source/platform/SharedBufferChunkReader.cpp +++ b/third_party/WebKit/Source/platform/SharedBufferChunkReader.cpp
@@ -64,7 +64,7 @@ } void SharedBufferChunkReader::SetSeparator(const char* separator) { - separator_.Clear(); + separator_.clear(); separator_.Append(separator, strlen(separator)); } @@ -73,7 +73,7 @@ if (reached_end_of_file_) return false; - chunk.Clear(); + chunk.clear(); while (true) { while (segment_index_ < segment_length_) { char current_character = segment_[segment_index_++]; @@ -123,7 +123,7 @@ size_t SharedBufferChunkReader::Peek(Vector<char>& data, size_t requested_size) { - data.Clear(); + data.clear(); if (requested_size <= segment_length_ - segment_index_) { data.Append(segment_ + segment_index_, requested_size); return requested_size;
diff --git a/third_party/WebKit/Source/platform/TimerTest.cpp b/third_party/WebKit/Source/platform/TimerTest.cpp index 47075a0..cdbfaca 100644 --- a/third_party/WebKit/Source/platform/TimerTest.cpp +++ b/third_party/WebKit/Source/platform/TimerTest.cpp
@@ -28,7 +28,7 @@ class TimerTest : public testing::Test { public: void SetUp() override { - run_times_.Clear(); + run_times_.clear(); platform_->AdvanceClockSeconds(10.0); start_time_ = MonotonicallyIncreasingTime(); }
diff --git a/third_party/WebKit/Source/platform/WebVectorTest.cpp b/third_party/WebKit/Source/platform/WebVectorTest.cpp index adc8733..a6d1a48e 100644 --- a/third_party/WebKit/Source/platform/WebVectorTest.cpp +++ b/third_party/WebKit/Source/platform/WebVectorTest.cpp
@@ -30,7 +30,7 @@ EXPECT_EQ(input[i], output[i]); // Use begin()/end() const_iterators directly. - output.Clear(); + output.clear(); for (WebVector<int>::const_iterator it = const_web_vector.begin(); it != const_web_vector.end(); ++it) output.push_back(*it); @@ -39,7 +39,7 @@ EXPECT_EQ(input[i], output[i]); // Use range-based for loop. - output.Clear(); + output.clear(); for (int x : web_vector) output.push_back(x); ASSERT_EQ(input.size(), output.size());
diff --git a/third_party/WebKit/Source/platform/audio/AudioDSPKernelProcessor.cpp b/third_party/WebKit/Source/platform/audio/AudioDSPKernelProcessor.cpp index 1cde247..63d81a30 100644 --- a/third_party/WebKit/Source/platform/audio/AudioDSPKernelProcessor.cpp +++ b/third_party/WebKit/Source/platform/audio/AudioDSPKernelProcessor.cpp
@@ -59,7 +59,7 @@ return; MutexLocker locker(process_lock_); - kernels_.Clear(); + kernels_.clear(); initialized_ = false; }
diff --git a/third_party/WebKit/Source/platform/audio/DynamicsCompressorKernel.cpp b/third_party/WebKit/Source/platform/audio/DynamicsCompressorKernel.cpp index cc48b59..ce9bd1c0 100644 --- a/third_party/WebKit/Source/platform/audio/DynamicsCompressorKernel.cpp +++ b/third_party/WebKit/Source/platform/audio/DynamicsCompressorKernel.cpp
@@ -73,7 +73,7 @@ if (pre_delay_buffers_.size() == number_of_channels) return; - pre_delay_buffers_.Clear(); + pre_delay_buffers_.clear(); for (unsigned i = 0; i < number_of_channels; ++i) { pre_delay_buffers_.push_back( WTF::MakeUnique<AudioFloatArray>(kMaxPreDelayFrames));
diff --git a/third_party/WebKit/Source/platform/feature_policy/FeaturePolicyTest.cpp b/third_party/WebKit/Source/platform/feature_policy/FeaturePolicyTest.cpp index c57bc38..ff42573 100644 --- a/third_party/WebKit/Source/platform/feature_policy/FeaturePolicyTest.cpp +++ b/third_party/WebKit/Source/platform/feature_policy/FeaturePolicyTest.cpp
@@ -51,7 +51,7 @@ TEST_F(FeaturePolicyTest, ParseValidPolicy) { Vector<String> messages; for (const char* policy_string : kValidPolicies) { - messages.Clear(); + messages.clear(); ParseFeaturePolicy(policy_string, origin_a_.Get(), &messages); EXPECT_EQ(0UL, messages.size()); } @@ -60,7 +60,7 @@ TEST_F(FeaturePolicyTest, ParseInvalidPolicy) { Vector<String> messages; for (const char* policy_string : kInvalidPolicies) { - messages.Clear(); + messages.clear(); ParseFeaturePolicy(policy_string, origin_a_.Get(), &messages); EXPECT_NE(0UL, messages.size()); }
diff --git a/third_party/WebKit/Source/platform/fonts/FontDataCache.cpp b/third_party/WebKit/Source/platform/fonts/FontDataCache.cpp index 1416f1c..724d256 100644 --- a/third_party/WebKit/Source/platform/fonts/FontDataCache.cpp +++ b/third_party/WebKit/Source/platform/fonts/FontDataCache.cpp
@@ -163,7 +163,7 @@ bool did_work = font_data_to_delete.size(); - font_data_to_delete.Clear(); + font_data_to_delete.clear(); is_purging = false;
diff --git a/third_party/WebKit/Source/platform/fonts/FontFallbackList.cpp b/third_party/WebKit/Source/platform/fonts/FontFallbackList.cpp index a4f337d..2aea90a7 100644 --- a/third_party/WebKit/Source/platform/fonts/FontFallbackList.cpp +++ b/third_party/WebKit/Source/platform/fonts/FontFallbackList.cpp
@@ -49,7 +49,7 @@ void FontFallbackList::Invalidate(FontSelector* font_selector) { ReleaseFontData(); - font_list_.Clear(); + font_list_.clear(); cached_primary_simple_font_data_ = 0; family_index_ = 0; has_loading_fallback_ = false;
diff --git a/third_party/WebKit/Source/platform/fonts/ScriptRunIterator.cpp b/third_party/WebKit/Source/platform/fonts/ScriptRunIterator.cpp index 1b7ccf1..1e1a6f2 100644 --- a/third_party/WebKit/Source/platform/fonts/ScriptRunIterator.cpp +++ b/third_party/WebKit/Source/platform/fonts/ScriptRunIterator.cpp
@@ -39,7 +39,7 @@ if (U_FAILURE(status)) { DLOG(ERROR) << "Could not get icu script data: " << status << " for 0x" << std::hex << ch; - dst.Clear(); + dst.clear(); return; } @@ -128,7 +128,7 @@ DCHECK(data); if (ahead_pos_ < length_) { - current_set_.Clear(); + current_set_.clear(); // Priming the m_currentSet with USCRIPT_COMMON here so that the first // resolution between m_currentSet and m_nextSet in mergeSets() leads to // chosing the script of the first consumed character. @@ -171,7 +171,7 @@ limit = length_; script = ResolveCurrentScript(); - current_set_.Clear(); + current_set_.clear(); return true; } @@ -193,7 +193,7 @@ if (it->ch == target) { // Have a match, use open paren's resolved script. UScriptCode script = it->script; - next_set_.Clear(); + next_set_.clear(); next_set_.push_back(script); // And pop stack to this point.
diff --git a/third_party/WebKit/Source/platform/fonts/ScriptRunIteratorTest.cpp b/third_party/WebKit/Source/platform/fonts/ScriptRunIteratorTest.cpp index 3a79c70..f06441c4 100644 --- a/third_party/WebKit/Source/platform/fonts/ScriptRunIteratorTest.cpp +++ b/third_party/WebKit/Source/platform/fonts/ScriptRunIteratorTest.cpp
@@ -41,7 +41,7 @@ DCHECK_LT(ch, kMockCharLimit); int code = ch - kMockCharMin; - dst.Clear(); + dst.clear(); switch (code & kCodeSpecialMask) { case kCodeSpecialCommon: dst.push_back(USCRIPT_COMMON);
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.cpp b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.cpp index ea99800..406eaf57 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.cpp
@@ -307,7 +307,7 @@ if (!holes_queue.size()) return false; - hint.Clear(); + hint.clear(); size_t num_chars_added = 0; for (auto it = holes_queue.begin(); it != holes_queue.end(); ++it) {
diff --git a/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridge.cpp b/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridge.cpp index eaf8e1bd..ae69049 100644 --- a/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridge.cpp +++ b/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridge.cpp
@@ -360,7 +360,7 @@ for (const auto& it : image_info_cache_) { DeleteCHROMIUMImage(it); } - image_info_cache_.Clear(); + image_info_cache_.clear(); } #endif // USE_IOSURFACE_FOR_2D_CANVAS
diff --git a/third_party/WebKit/Source/platform/graphics/ContiguousContainer.cpp b/third_party/WebKit/Source/platform/graphics/ContiguousContainer.cpp index 960e780..89924c7 100644 --- a/third_party/WebKit/Source/platform/graphics/ContiguousContainer.cpp +++ b/third_party/WebKit/Source/platform/graphics/ContiguousContainer.cpp
@@ -146,8 +146,8 @@ } void ContiguousContainerBase::Clear() { - elements_.Clear(); - buffers_.Clear(); + elements_.clear(); + buffers_.clear(); end_index_ = 0; }
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsLayer.cpp b/third_party/WebKit/Source/platform/graphics/GraphicsLayer.cpp index 60f4aad..de81bab 100644 --- a/third_party/WebKit/Source/platform/graphics/GraphicsLayer.cpp +++ b/third_party/WebKit/Source/platform/graphics/GraphicsLayer.cpp
@@ -125,7 +125,7 @@ GraphicsLayer::~GraphicsLayer() { for (size_t i = 0; i < link_highlights_.size(); ++i) link_highlights_[i]->ClearCurrentGraphicsLayer(); - link_highlights_.Clear(); + link_highlights_.clear(); #if DCHECK_IS_ON() if (client_) @@ -482,7 +482,7 @@ return; if (RuntimeEnabledFeatures::paintUnderInvalidationCheckingEnabled()) - tracking->tracked_raster_invalidations.Clear(); + tracking->tracked_raster_invalidations.clear(); else GetRasterInvalidationTrackingMap().Remove(this); }
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsLayerDebugInfo.cpp b/third_party/WebKit/Source/platform/graphics/GraphicsLayerDebugInfo.cpp index 26c119f..cccc616 100644 --- a/third_party/WebKit/Source/platform/graphics/GraphicsLayerDebugInfo.cpp +++ b/third_party/WebKit/Source/platform/graphics/GraphicsLayerDebugInfo.cpp
@@ -103,7 +103,7 @@ } void GraphicsLayerDebugInfo::ClearAnnotatedInvalidateRects() { - previous_invalidations_.Clear(); + previous_invalidations_.clear(); previous_invalidations_.Swap(invalidations_); }
diff --git a/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositor.cpp b/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositor.cpp index 99ccb59..16583632 100644 --- a/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositor.cpp +++ b/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositor.cpp
@@ -70,7 +70,7 @@ void AddPaintChunkDebugData(std::unique_ptr<JSONArray> json) { paint_chunk_debug_data_.push_back(std::move(json)); } - void ClearPaintChunkDebugData() { paint_chunk_debug_data_.Clear(); } + void ClearPaintChunkDebugData() { paint_chunk_debug_data_.clear(); } // cc::ContentLayerClient gfx::Rect PaintableRegion() override { return paintable_region_; } @@ -91,7 +91,7 @@ return; if (RuntimeEnabledFeatures::paintUnderInvalidationCheckingEnabled()) - tracking->tracked_raster_invalidations.Clear(); + tracking->tracked_raster_invalidations.clear(); else CcLayersRasterInvalidationTrackingMap().Remove(cc_picture_layer_.get()); } @@ -644,7 +644,7 @@ if (extra_data_for_testing_enabled_) extra_data_for_testing_->content_layers.push_back(layer); } - content_layer_clients_.Clear(); + content_layer_clients_.clear(); content_layer_clients_.Swap(new_content_layer_clients); // Mark the property trees as having been rebuilt.
diff --git a/third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.cpp b/third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.cpp index e4d34d37..97ce92b 100644 --- a/third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.cpp +++ b/third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.cpp
@@ -947,7 +947,7 @@ // Free all mailboxes, because they are now of the wrong size. Only the // first call in this loop has any effect. recycled_color_buffer_queue_.Clear(); - recycled_bitmaps_.Clear(); + recycled_bitmaps_.clear(); if (adjusted_size.IsEmpty()) return false;
diff --git a/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperClipCache.cpp b/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperClipCache.cpp index 7029946..acc0d47 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperClipCache.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperClipCache.cpp
@@ -22,7 +22,7 @@ void GeometryMapperClipCache::InvalidateCacheIfNeeded() { if (cache_generation_ != g_clip_cache_generation) { - clip_cache_.Clear(); + clip_cache_.clear(); cache_generation_ = g_clip_cache_generation; } }
diff --git a/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperTransformCache.cpp b/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperTransformCache.cpp index 8570aec..c94c50a5 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperTransformCache.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperTransformCache.cpp
@@ -20,7 +20,7 @@ void GeometryMapperTransformCache::InvalidateCacheIfNeeded() { if (cache_generation_ != g_transform_cache_generation) { - transform_cache_.Clear(); + transform_cache_.clear(); cache_generation_ = g_transform_cache_generation; } }
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintArtifact.cpp b/third_party/WebKit/Source/platform/graphics/paint/PaintArtifact.cpp index 16c48d2b..f9818a5 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintArtifact.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintArtifact.cpp
@@ -79,7 +79,7 @@ void PaintArtifact::Reset() { display_item_list_.Clear(); - paint_chunks_.Clear(); + paint_chunks_.clear(); } size_t PaintArtifact::ApproximateUnsharedMemoryUsage() const {
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.cpp b/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.cpp index ee83372..43f5760a 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintChunker.cpp
@@ -95,8 +95,8 @@ } void PaintChunker::Clear() { - chunks_.Clear(); - chunk_behavior_.Clear(); + chunks_.clear(); + chunk_behavior_.clear(); current_chunk_id_ = WTF::kNullopt; current_properties_ = PaintChunkProperties(); } @@ -104,7 +104,7 @@ Vector<PaintChunk> PaintChunker::ReleasePaintChunks() { Vector<PaintChunk> chunks; chunks.Swap(chunks_); - chunk_behavior_.Clear(); + chunk_behavior_.clear(); current_chunk_id_ = WTF::kNullopt; current_properties_ = PaintChunkProperties(); return chunks;
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintController.cpp b/third_party/WebKit/Source/platform/graphics/paint/PaintController.cpp index 8a89c97..6ce4fa0 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintController.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintController.cpp
@@ -597,7 +597,7 @@ ResetCurrentListIndices(); out_of_order_item_indices_.Clear(); out_of_order_chunk_indices_.Clear(); - items_moved_into_new_list_.Clear(); + items_moved_into_new_list_.clear(); if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) { for (const auto& chunk : current_paint_artifact_.PaintChunks()) {
diff --git a/third_party/WebKit/Source/platform/heap/HeapTest.cpp b/third_party/WebKit/Source/platform/heap/HeapTest.cpp index 45c819f..429115d 100644 --- a/third_party/WebKit/Source/platform/heap/HeapTest.cpp +++ b/third_party/WebKit/Source/platform/heap/HeapTest.cpp
@@ -1524,7 +1524,7 @@ // Check that vector_ hasn't shrunk. EXPECT_LT(31ul, vector_.Capacity()); // Just releasing the backing is allowed. - vector_.Clear(); + vector_.clear(); EXPECT_EQ(0ul, vector_.Capacity()); // Remove elemets so that map_ will try to shrink.
diff --git a/third_party/WebKit/Source/platform/heap/ThreadState.h b/third_party/WebKit/Source/platform/heap/ThreadState.h index 11218d6..acf753d 100644 --- a/third_party/WebKit/Source/platform/heap/ThreadState.h +++ b/third_party/WebKit/Source/platform/heap/ThreadState.h
@@ -566,7 +566,7 @@ ~ThreadState(); void ClearSafePointScopeMarker() { - safe_point_stack_copy_.Clear(); + safe_point_stack_copy_.clear(); safe_point_scope_marker_ = nullptr; }
diff --git a/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoder.cpp b/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoder.cpp index 669289ee6..a9e858a 100644 --- a/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoder.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoder.cpp
@@ -90,8 +90,8 @@ } bool ICOImageDecoder::SetFailed() { - bmp_readers_.Clear(); - png_decoders_.Clear(); + bmp_readers_.clear(); + png_decoders_.clear(); return ImageDecoder::SetFailed(); }
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.h b/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.h index 6c87b9e6..eae8f9b2 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.h +++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceResponse.h
@@ -303,7 +303,7 @@ const Vector<char>& MultipartBoundary() const { return multipart_boundary_; } void SetMultipartBoundary(const char* bytes, size_t size) { - multipart_boundary_.Clear(); + multipart_boundary_.clear(); multipart_boundary_.Append(bytes, size); }
diff --git a/third_party/WebKit/Source/platform/mhtml/MHTMLFuzzer.cpp b/third_party/WebKit/Source/platform/mhtml/MHTMLFuzzer.cpp index c36a760f..30e8f7a 100644 --- a/third_party/WebKit/Source/platform/mhtml/MHTMLFuzzer.cpp +++ b/third_party/WebKit/Source/platform/mhtml/MHTMLFuzzer.cpp
@@ -17,7 +17,7 @@ MHTMLParser mhtml_parser(SharedBuffer::Create(data, size)); HeapVector<Member<ArchiveResource>> mhtml_archives = mhtml_parser.ParseArchive(); - mhtml_archives.Clear(); + mhtml_archives.clear(); ThreadState::Current()->CollectAllGarbage(); return 0;
diff --git a/third_party/WebKit/Source/platform/mhtml/MHTMLParser.cpp b/third_party/WebKit/Source/platform/mhtml/MHTMLParser.cpp index 9b858394..18ff0323 100644 --- a/third_party/WebKit/Source/platform/mhtml/MHTMLParser.cpp +++ b/third_party/WebKit/Source/platform/mhtml/MHTMLParser.cpp
@@ -212,7 +212,7 @@ MIMEHeader* header = MIMEHeader::ParseHeader(&line_reader_); HeapVector<Member<ArchiveResource>> resources; if (!ParseArchiveWithHeader(header, resources)) - resources.Clear(); + resources.clear(); return resources; }
diff --git a/third_party/WebKit/Source/platform/network/EncodedFormData.cpp b/third_party/WebKit/Source/platform/network/EncodedFormData.cpp index 0c929b1..1afe49bc 100644 --- a/third_party/WebKit/Source/platform/network/EncodedFormData.cpp +++ b/third_party/WebKit/Source/platform/network/EncodedFormData.cpp
@@ -150,7 +150,7 @@ void EncodedFormData::Flatten(Vector<char>& data) const { // Concatenate all the byte arrays, but omit any files. - data.Clear(); + data.clear(); size_t n = elements_.size(); for (size_t i = 0; i < n; ++i) { const FormDataElement& e = elements_[i];
diff --git a/third_party/WebKit/Source/platform/network/NetworkStateNotifier.cpp b/third_party/WebKit/Source/platform/network/NetworkStateNotifier.cpp index b99fc08..65da95c1 100644 --- a/third_party/WebKit/Source/platform/network/NetworkStateNotifier.cpp +++ b/third_party/WebKit/Source/platform/network/NetworkStateNotifier.cpp
@@ -251,7 +251,7 @@ for (size_t i = 0; i < list->zeroed_observers.size(); ++i) list->observers.erase(list->zeroed_observers[i]); - list->zeroed_observers.Clear(); + list->zeroed_observers.clear(); if (list->observers.IsEmpty()) { MutexLocker locker(mutex_);
diff --git a/third_party/WebKit/Source/platform/text/BidiResolver.h b/third_party/WebKit/Source/platform/text/BidiResolver.h index cee4142c..adfb4c32 100644 --- a/third_party/WebKit/Source/platform/text/BidiResolver.h +++ b/third_party/WebKit/Source/platform/text/BidiResolver.h
@@ -640,7 +640,7 @@ SetContext(to_context); - current_explicit_embedding_sequence_.Clear(); + current_explicit_embedding_sequence_.clear(); return from_level != to_level; }
diff --git a/third_party/WebKit/Source/platform/text/QuotedPrintable.cpp b/third_party/WebKit/Source/platform/text/QuotedPrintable.cpp index eae09cc..e0d32a3 100644 --- a/third_party/WebKit/Source/platform/text/QuotedPrintable.cpp +++ b/third_party/WebKit/Source/platform/text/QuotedPrintable.cpp
@@ -61,7 +61,7 @@ void QuotedPrintableEncode(const char* input, size_t input_length, Vector<char>& out) { - out.Clear(); + out.clear(); out.ReserveCapacity(input_length); size_t current_line_length = 0; for (size_t i = 0; i < input_length; ++i) { @@ -129,7 +129,7 @@ void QuotedPrintableDecode(const char* data, size_t data_length, Vector<char>& out) { - out.Clear(); + out.clear(); if (!data_length) return;
diff --git a/third_party/WebKit/Source/platform/transforms/TransformOperations.h b/third_party/WebKit/Source/platform/transforms/TransformOperations.h index d3f6ce2..393f9c83 100644 --- a/third_party/WebKit/Source/platform/transforms/TransformOperations.h +++ b/third_party/WebKit/Source/platform/transforms/TransformOperations.h
@@ -72,7 +72,7 @@ bool OperationsMatch(const TransformOperations&) const; - void Clear() { operations_.Clear(); } + void clear() { operations_.clear(); } Vector<RefPtr<TransformOperation>>& Operations() { return operations_; } const Vector<RefPtr<TransformOperation>>& Operations() const {
diff --git a/third_party/WebKit/Source/platform/wtf/Vector.h b/third_party/WebKit/Source/platform/wtf/Vector.h index 3742c06f..b780f28 100644 --- a/third_party/WebKit/Source/platform/wtf/Vector.h +++ b/third_party/WebKit/Source/platform/wtf/Vector.h
@@ -1091,7 +1091,7 @@ // Remove all the elements. This function actually releases the backing // buffer, thus any iterators will get invalidated (including begin()). - void Clear() { ShrinkCapacity(0); } + void clear() { ShrinkCapacity(0); } // Insertion to the back. All of these functions except uncheckedAppend() may // cause a reallocation. @@ -1357,7 +1357,7 @@ if (size() > other.size()) { Shrink(other.size()); } else if (other.size() > Capacity()) { - Clear(); + clear(); ReserveCapacity(other.size()); DCHECK(begin()); } @@ -1386,7 +1386,7 @@ if (size() > other.size()) { Shrink(other.size()); } else if (other.size() > Capacity()) { - Clear(); + clear(); ReserveCapacity(other.size()); DCHECK(begin()); } @@ -1429,7 +1429,7 @@ if (size() > elements.size()) { Shrink(elements.size()); } else if (elements.size() > Capacity()) { - Clear(); + clear(); ReserveCapacity(elements.size()); DCHECK(begin()); } @@ -1479,7 +1479,7 @@ if (size() > new_size) { Shrink(new_size); } else if (new_size > Capacity()) { - Clear(); + clear(); ReserveCapacity(new_size); DCHECK(begin()); }
diff --git a/third_party/WebKit/Source/platform/wtf/VectorTest.cpp b/third_party/WebKit/Source/platform/wtf/VectorTest.cpp index e248143..ebb93c8 100644 --- a/third_party/WebKit/Source/platform/wtf/VectorTest.cpp +++ b/third_party/WebKit/Source/platform/wtf/VectorTest.cpp
@@ -218,7 +218,7 @@ EXPECT_EQ(count, copy_vector.size()); EXPECT_EQ(0u, vector.size()); - copy_vector.Clear(); + copy_vector.clear(); EXPECT_EQ(count, static_cast<size_t>(destruct_number)); } @@ -492,8 +492,8 @@ for (unsigned i = 0; i < 13; i++) { for (unsigned j = 0; j < 13; j++) { - vector.Clear(); - vector2.Clear(); + vector.clear(); + vector2.clear(); EXPECT_EQ(0u, LivenessCounter::live_); for (unsigned k = 0; k < j; k++) @@ -541,8 +541,8 @@ for (unsigned size = 0; size < 13; size++) { for (unsigned size2 = 0; size2 < 13; size2++) { - vector.Clear(); - vector2.Clear(); + vector.clear(); + vector2.clear(); for (unsigned i = 0; i < size; i++) vector.push_back(i); for (unsigned i = 0; i < size2; i++)
diff --git a/third_party/WebKit/Source/platform/wtf/text/Base64.cpp b/third_party/WebKit/Source/platform/wtf/text/Base64.cpp index e03f115..947fdf1 100644 --- a/third_party/WebKit/Source/platform/wtf/text/Base64.cpp +++ b/third_party/WebKit/Source/platform/wtf/text/Base64.cpp
@@ -62,7 +62,7 @@ unsigned len, Vector<char>& out, Base64EncodePolicy policy) { - out.Clear(); + out.clear(); if (!len) return; @@ -129,7 +129,7 @@ Vector<char>& out, CharacterMatchFunctionPtr should_ignore_character, Base64DecodePolicy policy) { - out.Clear(); + out.clear(); // If the input string is pathologically large, just return nothing. if (in.size() > UINT_MAX) @@ -146,7 +146,7 @@ Vector<char>& out, CharacterMatchFunctionPtr should_ignore_character, Base64DecodePolicy policy) { - out.Clear(); + out.clear(); if (!length) return true;
diff --git a/third_party/WebKit/Source/platform/wtf/text/WTFString.cpp b/third_party/WebKit/Source/platform/wtf/text/WTFString.cpp index e2b6693..a4532bd 100644 --- a/third_party/WebKit/Source/platform/wtf/text/WTFString.cpp +++ b/third_party/WebKit/Source/platform/wtf/text/WTFString.cpp
@@ -523,7 +523,7 @@ void String::Split(const StringView& separator, bool allow_empty_entries, Vector<String>& result) const { - result.Clear(); + result.clear(); unsigned start_pos = 0; size_t end_pos; @@ -539,7 +539,7 @@ void String::Split(UChar separator, bool allow_empty_entries, Vector<String>& result) const { - result.Clear(); + result.clear(); unsigned start_pos = 0; size_t end_pos;
diff --git a/third_party/WebKit/Source/web/TextFinder.cpp b/third_party/WebKit/Source/web/TextFinder.cpp index 905d4bd..b0c1985 100644 --- a/third_party/WebKit/Source/web/TextFinder.cpp +++ b/third_party/WebKit/Source/web/TextFinder.cpp
@@ -522,7 +522,7 @@ if (!find_matches_cache_.IsEmpty()) ++find_match_markers_version_; - find_matches_cache_.Clear(); + find_matches_cache_.clear(); find_match_rects_are_valid_ = false; }
diff --git a/third_party/WebKit/Source/web/WebRuntimeFeatures.cpp b/third_party/WebKit/Source/web/WebRuntimeFeatures.cpp index dd795437..6b7ac6a 100644 --- a/third_party/WebKit/Source/web/WebRuntimeFeatures.cpp +++ b/third_party/WebKit/Source/web/WebRuntimeFeatures.cpp
@@ -43,8 +43,8 @@ RuntimeEnabledFeatures::setWebBluetoothEnabled(enable); } -void WebRuntimeFeatures::EnableWebAssemblySerialization(bool enable) { - RuntimeEnabledFeatures::setWebAssemblySerializationEnabled(enable); +void WebRuntimeFeatures::EnableWebAssemblyStreaming(bool enable) { + RuntimeEnabledFeatures::setWebAssemblyStreamingEnabled(enable); } void WebRuntimeFeatures::EnableWebUsb(bool enable) {
diff --git a/third_party/WebKit/Source/web/WebViewImpl.cpp b/third_party/WebKit/Source/web/WebViewImpl.cpp index af54f9e9..1b96494 100644 --- a/third_party/WebKit/Source/web/WebViewImpl.cpp +++ b/third_party/WebKit/Source/web/WebViewImpl.cpp
@@ -1513,7 +1513,7 @@ // Always clear any existing highlight when this is invoked, even if we // don't get a new target to highlight. - link_highlights_.Clear(); + link_highlights_.clear(); for (size_t i = 0; i < highlight_nodes.size(); ++i) { Node* node = highlight_nodes[i]; @@ -2548,7 +2548,7 @@ void WebViewImpl::WillCloseLayerTreeView() { if (link_highlights_timeline_) { - link_highlights_.Clear(); + link_highlights_.clear(); DetachCompositorAnimationTimeline(link_highlights_timeline_.get()); link_highlights_timeline_.reset(); } @@ -3651,7 +3651,7 @@ GetPage()->GetVisualViewport().MainFrameDidChangeSize(); // Make sure link highlight from previous page is cleared. - link_highlights_.Clear(); + link_highlights_.clear(); EndActiveFlingAnimation(); }
diff --git a/third_party/WebKit/Source/web/tests/ActivityLoggerTest.cpp b/third_party/WebKit/Source/web/tests/ActivityLoggerTest.cpp index 68c96d5..d9af06d 100644 --- a/third_party/WebKit/Source/web/tests/ActivityLoggerTest.cpp +++ b/third_party/WebKit/Source/web/tests/ActivityLoggerTest.cpp
@@ -54,7 +54,7 @@ logged_activities_.push_back(activity_string); } - void Clear() { logged_activities_.Clear(); } + void clear() { logged_activities_.clear(); } bool VerifyActivities(const Vector<String>& expected) const { EXPECT_EQ(expected.size(), logged_activities_.size()); for (size_t i = 0; i < std::min(expected.size(), logged_activities_.size());
diff --git a/third_party/WebKit/Source/web/tests/AnimationSimTest.cpp b/third_party/WebKit/Source/web/tests/AnimationSimTest.cpp index 29d3010..7806501 100644 --- a/third_party/WebKit/Source/web/tests/AnimationSimTest.cpp +++ b/third_party/WebKit/Source/web/tests/AnimationSimTest.cpp
@@ -84,7 +84,7 @@ keyframe->SetCSSPropertyValue("--x", GetDocument().GetPropertyRegistry(), "100%", GetDocument().ElementSheet().Contents()); - keyframes.Clear(); + keyframes.clear(); keyframes.push_back(keyframe.Release()); timing = Timing::Defaults(); timing.iteration_duration = 1; // Seconds.
diff --git a/third_party/WebKit/Source/web/tests/PrerenderingTest.cpp b/third_party/WebKit/Source/web/tests/PrerenderingTest.cpp index cd7c21a..bdd3b44 100644 --- a/third_party/WebKit/Source/web/tests/PrerenderingTest.cpp +++ b/third_party/WebKit/Source/web/tests/PrerenderingTest.cpp
@@ -101,9 +101,9 @@ ~TestPrerenderingSupport() override { Shutdown(); } void Clear() { - added_prerenders_.Clear(); - canceled_prerenders_.Clear(); - abandoned_prerenders_.Clear(); + added_prerenders_.clear(); + canceled_prerenders_.clear(); + abandoned_prerenders_.clear(); } size_t TotalCount() const {
diff --git a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp index 9a40225f..321d99f 100644 --- a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp +++ b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp
@@ -4454,8 +4454,8 @@ ~ContextLifetimeTestWebFrameClient() override { Reset(); } void Reset() { - create_notifications.Clear(); - release_notifications.Clear(); + create_notifications.clear(); + release_notifications.clear(); } Vector<std::unique_ptr<Notification>> create_notifications;
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/WPTHeads b/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/WPTHeads index f605e61..e99854c 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/WPTHeads +++ b/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/WPTHeads
@@ -2,5 +2,5 @@ ./ tools 0075ffdc61f71b078fc4fd7c75cbe3273b838d6d ./tools html5lib 7cce65bbaa78411f98b8b37eeefc9db03c580097 ./tools six 3b6173c833d217ab0186c355804f5925cbcfca47 -./tools wptserve 071c51e26a57300979ad53313970d7247979f6d3 +./tools wptserve c7bf515d74c16320455f68b61c113a9012743ff1 ./tools/lint 08a039c29ebe850edfd38aa650b9e5477e200bd2
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/checkout.sh b/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/checkout.sh index ad14bf7..8c03fe5 100755 --- a/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/checkout.sh +++ b/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/checkout.sh
@@ -22,7 +22,7 @@ cd $TARGET_DIR && git checkout $WPT_HEAD echo "WPTHead: " `git rev-parse HEAD` - # Starting from the 2nd line of WPTWhiteList, we read and checkout submodules. + # Starting from the 2nd line of WPTHeads, we read and checkout submodules. tail -n+2 $DIR/WPTHeads | while read dir submodule commit; do cd $TARGET_DIR/$dir && \ git submodule update --init $submodule && \
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/README.md b/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/README.md index c0c88e2c..30a7dcc 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/README.md +++ b/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/README.md
@@ -1,4 +1,6 @@ wptserve ======== -Web server designed for use with web-platform-tests +Web server designed for use with web-platform-tests. + +[wptserve.readthedocs.io](http://wptserve.readthedocs.io/en/latest/index.html)
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/handlers.py b/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/handlers.py index c40321d..9cc1f73 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/handlers.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/handlers.py
@@ -2,8 +2,8 @@ import json import os import traceback -import urllib -import urlparse + +from six.moves.urllib.parse import parse_qs, quote, unquote, urljoin from .constants import content_types from .pipes import Pipeline, template @@ -30,7 +30,7 @@ if base_path is None: base_path = request.doc_root - path = urllib.unquote(request.url_parts.path) + path = unquote(request.url_parts.path) if path.startswith(url_base): path = path[len(url_base):] @@ -85,11 +85,11 @@ # statically defined ones if base_path != "/": - link = urlparse.urljoin(base_path, "..") + link = urljoin(base_path, "..") yield ("""<li class="dir"><a href="%(link)s">%(name)s</a></li>""" % {"link": link, "name": ".."}) for item in sorted(os.listdir(path)): - link = cgi.escape(urllib.quote(item)) + link = cgi.escape(quote(item)) if os.path.isdir(os.path.join(path, item)): link += "/" class_ = "dir" @@ -128,7 +128,7 @@ byte_ranges = None data = self.get_data(response, path, byte_ranges) response.content = data - query = urlparse.parse_qs(request.url_parts.query) + query = parse_qs(request.url_parts.query) pipeline = None if "pipe" in query:
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/pipes.py b/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/pipes.py index 41f7dd33..95108ba 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/pipes.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/pipes.py
@@ -8,10 +8,7 @@ def resolve_content(response): - rv = "".join(item for item in response.iter_content(read_file=True)) - if type(rv) == unicode: - rv = rv.encode(response.encoding) - return rv + return b"".join(item for item in response.iter_content(read_file=True)) class Pipeline(object):
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/request.py b/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/request.py index 6b8a7ce..4476634 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/request.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/request.py
@@ -3,7 +3,8 @@ import Cookie import StringIO import tempfile -import urlparse + +from six.moves.urllib.parse import parse_qsl, urlsplit from . import stash from .utils import HTTPException @@ -186,14 +187,6 @@ Absolute URL for the request. - .. attribute:: headers - - List of request headers. - - .. attribute:: raw_input - - File-like object representing the body of the request. - .. attribute:: url_parts Parts of the requested URL as obtained by urlparse.urlsplit(path) @@ -207,10 +200,18 @@ RequestHeaders object providing a dictionary-like representation of the request headers. + .. attribute:: raw_headers. + + Dictionary of non-normalized request headers. + .. attribute:: body Request body as a string + .. attribute:: raw_input + + File-like object representing the body of the request. + .. attribute:: GET MultiDict representing the parameters supplied with the request. @@ -265,9 +266,9 @@ host, port, self.request_path) - self.url_parts = urlparse.urlsplit(self.url) + self.url_parts = urlsplit(self.url) - self._raw_headers = request_handler.headers + self.raw_headers = request_handler.headers self.request_line = request_handler.raw_requestline @@ -290,7 +291,7 @@ @property def GET(self): if self._GET is None: - params = urlparse.parse_qsl(self.url_parts.query, keep_blank_values=True) + params = parse_qsl(self.url_parts.query, keep_blank_values=True) self._GET = MultiDict() for key, value in params: self._GET.add(key, value) @@ -325,7 +326,7 @@ @property def headers(self): if self._headers is None: - self._headers = RequestHeaders(self._raw_headers) + self._headers = RequestHeaders(self.raw_headers) return self._headers @property
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/server.py b/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/server.py index 31929ef..0ab512c 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/server.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/wpt/wpt/tools/wptserve/wptserve/server.py
@@ -9,7 +9,8 @@ import time import traceback import types -import urlparse + +from six.moves.urllib.parse import urlsplit, urlunsplit from . import routes as default_routes from .logger import get_logger @@ -89,7 +90,7 @@ :param request_handler: BaseHTTPRequestHandler for which to rewrite the request. """ - split_url = urlparse.urlsplit(request_handler.path) + split_url = urlsplit(request_handler.path) if split_url.path in self.rules: methods, destination = self.rules[split_url.path] if "*" in methods or request_handler.command in methods: @@ -97,7 +98,7 @@ (request_handler.path, destination)) new_url = list(split_url) new_url[2] = destination - new_url = urlparse.urlunsplit(new_url) + new_url = urlunsplit(new_url) request_handler.path = new_url @@ -456,6 +457,6 @@ if not self.started: return None - return urlparse.urlunsplit(("http" if not self.use_ssl else "https", - "%s:%s" % (self.host, self.port), - path, query, fragment)) + return urlunsplit(("http" if not self.use_ssl else "https", + "%s:%s" % (self.host, self.port), + path, query, fragment))
diff --git a/third_party/WebKit/public/web/WebRuntimeFeatures.h b/third_party/WebKit/public/web/WebRuntimeFeatures.h index d93a026e..966c1cd 100644 --- a/third_party/WebKit/public/web/WebRuntimeFeatures.h +++ b/third_party/WebKit/public/web/WebRuntimeFeatures.h
@@ -124,7 +124,7 @@ BLINK_EXPORT static void EnableTouchEventFeatureDetection(bool); BLINK_EXPORT static void EnableTouchpadAndWheelScrollLatching(bool); BLINK_EXPORT static void EnableV8IdleTasks(bool); - BLINK_EXPORT static void EnableWebAssemblySerialization(bool); + BLINK_EXPORT static void EnableWebAssemblyStreaming(bool); BLINK_EXPORT static void EnableWebBluetooth(bool); BLINK_EXPORT static void EnableWebFontsInterventionV2With2G(bool); BLINK_EXPORT static void EnableWebFontsInterventionV2With3G(bool);
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 881ea0b3..5c644c8 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -96821,6 +96821,7 @@ <int value="1963" label="RequestMIDIAccessIframeWithSysExOption"/> <int value="1964" label="GamepadAxes"/> <int value="1965" label="GamepadButtons"/> + <int value="1966" label="VibrateWithoutUserGesture"/> </enum> <enum name="FetchRequestMode" type="int"> @@ -102909,6 +102910,7 @@ <int value="-891856063" label="MidiManagerAndroid:enabled"/> <int value="-885601782" label="enable-contextual-search"/> <int value="-884864731" label="WebPaymentsSingleAppUiSkip:enabled"/> + <int value="-881054479" label="WebAssemblyStreaming:disabled"/> <int value="-876148583" label="ArcBootCompletedBroadcast:disabled"/> <int value="-867087281" label="enable-virtual-keyboard"/> <int value="-864266073" label="cros-regions-mode"/> @@ -103249,6 +103251,7 @@ <int value="581118445" label="enable-eol-notification"/> <int value="581355159" label="ContentSuggestionsCategoryRanker:disabled"/> <int value="584541349" label="ContextualSearchSingleActions:disabled"/> + <int value="586021329" label="VibrateRequiresUserGesture:enabled"/> <int value="592050831" label="disable-slimming-paint"/> <int value="593707592" label="disable-network-portal-notification"/> <int value="596106994" label="CustomFeedbackUi:enabled"/> @@ -103284,6 +103287,7 @@ <int value="690185633" label="NonValidatingReloadOnNormalReload:disabled"/> <int value="691020108" label="NTPCondensedTileLayout:disabled"/> <int value="693012666" label="QuickUnlockPin:disabled"/> + <int value="696600628" label="VibrateRequiresUserGesture:disabled"/> <int value="709850261" label="disable-touch-editing"/> <int value="711424932" label="enable-cloud-print-xps"/> <int value="715617684" label="OriginTrials:disabled"/> @@ -103311,6 +103315,7 @@ <int value="820650704" label="disable-ntp-popular-sites"/> <int value="821192723" label="show-fps-counter"/> <int value="824961931" label="use-simple-cache-backend"/> + <int value="832142463" label="WebAssemblyStreaming:enabled"/> <int value="834033186" label="enable-data-reduction-proxy-dev"/> <int value="834326277" label="enable-answers-in-suggest"/> <int value="835018878" label="disable-quic"/>
diff --git a/tools/resource_prefetch_predictor/README.md b/tools/resource_prefetch_predictor/README.md index 77ff51ff..e4f2409 100644 --- a/tools/resource_prefetch_predictor/README.md +++ b/tools/resource_prefetch_predictor/README.md
@@ -12,7 +12,4 @@ # Installation * Install an updated protobuf library: `pip install --user protobuf` -* Generated protocol buffers in the path: Assuming that the build directory is -`out/Release` and chromium's `src/` is `$CHROMIUM_SRC`, `export -PYTHONPATH=$PYTHONPATH:${CHROMIUM_SRC}/out/Release/pyproto/chrome/browser/predictors/` * SQLite from the Android SDK is recent enough, make sure that `${CHROMIUM_SRC}/third_party/android_tools/sdk/platform-tools` is in the path.
diff --git a/tools/resource_prefetch_predictor/prefetch_predictor_tool.py b/tools/resource_prefetch_predictor/prefetch_predictor_tool.py index 9680c65..436e0216 100755 --- a/tools/resource_prefetch_predictor/prefetch_predictor_tool.py +++ b/tools/resource_prefetch_predictor/prefetch_predictor_tool.py
@@ -12,16 +12,17 @@ """ import argparse +import datetime import sqlite3 import os - -from resource_prefetch_predictor_pb2 import (PrefetchData, ResourceData) +import sys class Entry(object): """Represents an entry in the predictor database.""" def __init__( self, primary_key, proto_buffer): + from resource_prefetch_predictor_pb2 import (PrefetchData, ResourceData) self.primary_key = primary_key self.prefetch_data = PrefetchData() self.prefetch_data.ParseFromString(proto_buffer) @@ -36,6 +37,7 @@ Return: The resource score (int). """ + from resource_prefetch_predictor_pb2 import (PrefetchData, ResourceData) priority_multiplier = 1 type_multiplier = 1 @@ -78,6 +80,32 @@ continue self._PrettyPrintResource(resource) +def DumpOriginDatabaseRow(domain, primary_key, proto): + from resource_prefetch_predictor_pb2 import OriginData + entry = OriginData() + entry.ParseFromString(proto) + # For the offset, see kWindowsEpochDeltaMicroseconds in + # base/time/time_posix.cc. + last_visit_timestamp = int(entry.last_visit_time / 1e6 - 11644473600) + formatted_last_visit_time = datetime.datetime.utcfromtimestamp( + last_visit_timestamp).strftime('%Y-%m-%d %H:%M:%S') + print '''host: %s +last_visit_time: %s +origins:''' % (entry.host, formatted_last_visit_time) + for origin_stat in entry.origins: + print ''' origin: %s + number_of_hits: %d + number_of_misses: %d + consecutive_misses: %d + average_position: %f + always_access_network: %s + accessed_network: %s +''' % (origin_stat.origin, origin_stat.number_of_hits, + origin_stat.number_of_misses, origin_stat.consecutive_misses, + origin_stat.average_position, origin_stat.always_access_network, + origin_stat.accessed_network) + + # The version of python sqlite3 library we have in Ubuntu 14.04 LTS doesn't # support views but command line util does. # TODO(alexilin): get rid of this when python sqlite3 adds view support. @@ -88,22 +116,42 @@ subprocess.call(['sqlite3', tmpfile, 'DROP VIEW MmapStatus']) return tmpfile -def DatabaseStats(filename, domain): +def DatabaseStats(filename, host): + query_template = 'SELECT key, proto from %s' connection = sqlite3.connect(filename) c = connection.cursor() - query = ('SELECT key, proto FROM resource_prefetch_predictor_host') + print 'HOST DATABASE' + query = query_template % 'resource_prefetch_predictor_host' entries = [Entry.FromRow(row) for row in c.execute(query)] for x in entries: - if domain is None or x.primary_key == domain: + if host is None or x.primary_key == host: x.PrettyPrintCandidates() + print '\n\nORIGIN DATABASE' + query = query_template % 'resource_prefetch_predictor_origin' + rows = [row for row in c.execute(query) + if host is None or row.primary_key == host] + for row in rows: + DumpOriginDatabaseRow(host, *row) + + +def _AddProtocolBuffersPath(build_dir): + assert os.path.isdir(build_dir) + proto_dir = os.path.join( + build_dir, os.path.join('pyproto', 'chrome', 'browser', 'predictors')) + sys.path.append(proto_dir) + def main(): parser = argparse.ArgumentParser() parser.add_argument('-f', dest='database_filename', required=True, help='Path to the database') parser.add_argument('-d', dest='domain', default=None, help='Domain') + parser.add_argument('--build-dir', dest='build_dir', required=True, + help='Path to the build directory.') args = parser.parse_args() + _AddProtocolBuffersPath(args.build_dir) + try: database_copy = CreateCompatibleDatabaseCopy(args.database_filename) DatabaseStats(database_copy, args.domain)
diff --git a/ui/arc/notification/arc_custom_notification_view.cc b/ui/arc/notification/arc_custom_notification_view.cc index 671ead9..a09ecb3 100644 --- a/ui/arc/notification/arc_custom_notification_view.cc +++ b/ui/arc/notification/arc_custom_notification_view.cc
@@ -209,9 +209,12 @@ ArcCustomNotificationView::ControlButton::ControlButton( ArcCustomNotificationView* owner) : message_center::PaddedButton(owner), owner_(owner) { - if (!owner_->item_) { + if (owner_->item_) { set_background(views::Background::CreateSolidBackground( GetControlButtonBackgroundColor(owner_->item_->shown_contents()))); + } else { + set_background(views::Background::CreateSolidBackground( + message_center::kControlButtonBackgroundColor)); } }
diff --git a/ui/platform_window/stub/stub_window.cc b/ui/platform_window/stub/stub_window.cc index b54ada3..7e28c11 100644 --- a/ui/platform_window/stub/stub_window.cc +++ b/ui/platform_window/stub/stub_window.cc
@@ -10,8 +10,9 @@ namespace ui { StubWindow::StubWindow(PlatformWindowDelegate* delegate, - bool use_default_accelerated_widget) - : delegate_(delegate) { + bool use_default_accelerated_widget, + const gfx::Rect& bounds) + : delegate_(delegate), bounds_(bounds) { DCHECK(delegate); if (use_default_accelerated_widget) delegate_->OnAcceleratedWidgetAvailable(gfx::kNullAcceleratedWidget, 1.f);
diff --git a/ui/platform_window/stub/stub_window.h b/ui/platform_window/stub/stub_window.h index 4b8d29e..080e945c 100644 --- a/ui/platform_window/stub/stub_window.h +++ b/ui/platform_window/stub/stub_window.h
@@ -17,8 +17,9 @@ class STUB_WINDOW_EXPORT StubWindow : NON_EXPORTED_BASE(public PlatformWindow) { public: - StubWindow(PlatformWindowDelegate* delegate, - bool use_default_accelerated_widget = true); + explicit StubWindow(PlatformWindowDelegate* delegate, + bool use_default_accelerated_widget = true, + const gfx::Rect& bounds = gfx::Rect()); ~StubWindow() override; private:
diff --git a/ui/views/bubble/bubble_dialog_delegate.cc b/ui/views/bubble/bubble_dialog_delegate.cc index 3278b6f..0f23909 100644 --- a/ui/views/bubble/bubble_dialog_delegate.cc +++ b/ui/views/bubble/bubble_dialog_delegate.cc
@@ -217,7 +217,7 @@ parent_window_(NULL) { LayoutProvider* provider = LayoutProvider::Get(); margins_ = provider->GetInsetsMetric(INSETS_BUBBLE_CONTENTS); - title_margins_ = provider->GetInsetsMetric(INSETS_DIALOG_TITLE); + title_margins_ = provider->GetInsetsMetric(INSETS_BUBBLE_TITLE); if (anchor_view) SetAnchorView(anchor_view); UpdateColorsFromTheme(GetNativeTheme());
diff --git a/ui/views/layout/layout_provider.cc b/ui/views/layout/layout_provider.cc index 926916d1..208b9aa7 100644 --- a/ui/views/layout/layout_provider.cc +++ b/ui/views/layout/layout_provider.cc
@@ -33,14 +33,17 @@ gfx::Insets LayoutProvider::GetInsetsMetric(int metric) const { DCHECK_LT(metric, VIEWS_INSETS_MAX); switch (metric) { + case InsetsMetric::INSETS_BUBBLE_CONTENTS: + return gfx::Insets(kPanelVertMargin, kPanelHorizMargin); + case InsetsMetric::INSETS_BUBBLE_TITLE: + return gfx::Insets(kPanelVertMargin, kPanelHorizMargin, 0, + kPanelHorizMargin); case InsetsMetric::INSETS_DIALOG_BUTTON: return gfx::Insets(0, kButtonHEdgeMarginNew, kButtonVEdgeMarginNew, kButtonHEdgeMarginNew); case InsetsMetric::INSETS_DIALOG_TITLE: return gfx::Insets(kPanelVertMargin, kButtonHEdgeMarginNew, 0, kButtonHEdgeMarginNew); - case InsetsMetric::INSETS_BUBBLE_CONTENTS: - return gfx::Insets(kPanelVertMargin, kPanelHorizMargin); case InsetsMetric::INSETS_PANEL: return gfx::Insets(kPanelVertMargin, kButtonHEdgeMarginNew); case InsetsMetric::INSETS_VECTOR_IMAGE_BUTTON:
diff --git a/ui/views/layout/layout_provider.h b/ui/views/layout/layout_provider.h index f00238f..197586b 100644 --- a/ui/views/layout/layout_provider.h +++ b/ui/views/layout/layout_provider.h
@@ -21,6 +21,8 @@ // The margins around the contents area of a bubble (popover)-style dialog. INSETS_BUBBLE_CONTENTS = VIEWS_INSETS_START, + // The margins around the title of a bubble (popover)-style dialog. + INSETS_BUBBLE_TITLE, // The margins around the button row of a dialog. INSETS_DIALOG_BUTTON, // The margins around the icon/title of a dialog.