diff --git a/BUILD.gn b/BUILD.gn index 2e769ee5..88fc91a 100644 --- a/BUILD.gn +++ b/BUILD.gn
@@ -78,6 +78,16 @@ ] } +# TODO(GYP): This target exists for compatibility with GYP for the builders. +# For now, this builds everything. We should decide if we want to build less. +group("chromium_builder_tests") { + testonly = true + + deps = [ + ":All", + ] +} + # The "both_gn_and_gyp" target should reflect every target that is built # in both the GN and GYP builds, and ideally it should match the # "both_gn_and_gyp" target in build/gn_migration.gypi line-for-line.
diff --git a/DEPS b/DEPS index c4afc11..296612b0 100644 --- a/DEPS +++ b/DEPS
@@ -39,11 +39,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': 'cb232e8b1b9f2d7831ad90815df5934ecafab1d4', + 'skia_revision': 'bde57ed11b8a6bd6da6043189e000c58bf146422', # 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': '9d4557a76e28adc1df468e1405079a8f90ff60bb', + 'v8_revision': '35f367373553f4ecc260aec67c1cee8f0020b0f2', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -51,7 +51,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '6684007a77572f3616fc453138b0ef5f7d42d038', + 'angle_revision': 'ae2d0a0e865545fbc5f55bf2014d00bb8f4669c9', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling build tools # and whatever else without interference from each other. @@ -83,7 +83,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling NaCl # and whatever else without interference from each other. - 'nacl_revision': '864091e4b8875e8562b193bbdf5f8d95015d5ab9', + 'nacl_revision': '44a5a1eee2ce76d15bb0169472b177f61497040d', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling dEQP # 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': '94d724b18fcef3f8ab81ae9b0dd85466db68815d', + 'catapult_revision': '7ea5228763e4cd9d39e4c39c14d4ad1fdb5bc4ac', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -216,7 +216,7 @@ Var('chromium_git') + '/native_client/src/third_party/scons-2.0.1.git' + '@' + '1c1550e17fc26355d08627fbdec13d8291227067', 'src/third_party/webrtc': - Var('chromium_git') + '/external/webrtc/trunk/webrtc.git' + '@' + '780d506ddf7bcba4a3dc04cfe2240c1ae80880f2', # commit position 12384 + Var('chromium_git') + '/external/webrtc/trunk/webrtc.git' + '@' + 'cc6714b1ec7b4f6c7f0c37338aaca193b503c9cb', # commit position 12409 'src/third_party/openmax_dl': Var('chromium_git') + '/external/webrtc/deps/third_party/openmax.git' + '@' + Var('openmax_dl_revision'),
diff --git a/PRESUBMIT.py b/PRESUBMIT.py index 7d32ad53..ca87ae7d 100644 --- a/PRESUBMIT.py +++ b/PRESUBMIT.py
@@ -373,7 +373,7 @@ files.append(f) if len(files): - return [ output_api.PresubmitError( + return [output_api.PresubmitError( 'Do not #include <iostream> in header files, since it inserts static ' 'initialization into every file including the header. Instead, ' '#include <ostream>. See http://crbug.com/94794', @@ -479,6 +479,20 @@ 'been modified and the associated histogram name has no match in either ' '%s or the modifications of it:' % (histograms_xml_path), problems)] +def _CheckFlakyTestUsage(input_api, output_api): + """Check that FlakyTest annotation is our own instead of the android one""" + pattern = input_api.re.compile(r'import android.test.FlakyTest;') + files = [] + for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile): + if f.LocalPath().endswith('Test.java'): + if pattern.search(input_api.ReadFile(f)): + files.append(f) + if len(files): + return [output_api.PresubmitError( + 'Use org.chromium.base.test.util.FlakyTest instead of ' + 'android.test.FlakyTest', + files)] + return [] def _CheckNoNewWStrings(input_api, output_api): """Checks to make sure we don't introduce use of wstrings.""" @@ -1655,7 +1669,7 @@ break if files: - return [ output_api.PresubmitError( + return [output_api.PresubmitError( 'Found base::Singleton<T> in the following header files.\n' + 'Please move them to an appropriate source file so that the ' + 'template gets instantiated in a single compilation unit.', @@ -1796,6 +1810,7 @@ results.extend(_CheckNoAbbreviationInPngFileName(input_api, output_api)) results.extend(_CheckForInvalidOSMacros(input_api, output_api)) results.extend(_CheckForInvalidIfDefinedMacros(input_api, output_api)) + results.extend(_CheckFlakyTestUsage(input_api, output_api)) # TODO(danakj): Remove this when base/move.h is removed. results.extend(_CheckForUsingPass(input_api, output_api)) results.extend(_CheckAddedDepsHaveTargetApprovals(input_api, output_api))
diff --git a/android_webview/glue/BUILD.gn b/android_webview/glue/BUILD.gn index 59302f7..ac732bd 100644 --- a/android_webview/glue/BUILD.gn +++ b/android_webview/glue/BUILD.gn
@@ -7,12 +7,29 @@ import("generate_resource_rewriter.gni") import("glue.gni") -webview_framework_ijar = - "$root_out_dir/lib.java/webview/frameworks.interface.jar" +# There are two copies of this file: one upstream and one downstream, +# all targets defined in this file will finally generate two targets. +# is_upstream could be used to differentiate those two targets, see +# 'glue' target for details. +is_upstream = rebase_path(".", "//android_webview/glue") == "." -generate_interface_jar("framework_ijar") { - input_jar = webview_framework_jar - output_jar = webview_framework_ijar +webview_framework_ijar = "frameworks.interface.jar" +webview_public_framework_ijar = "frameworks.public.interface.jar" + +# Mark webview_framework_ijar is used, otherwise it isn't used if there +# is no internal code. +assert(webview_framework_ijar != "") + +if (defined(webview_internal_framework_jar)) { + generate_interface_jar("framework_ijar") { + input_jar = webview_internal_framework_jar + output_jar = "$target_out_dir/$webview_framework_ijar" + } +} + +generate_interface_jar("public_framework_ijar") { + input_jar = webview_public_framework_jar + output_jar = "$target_out_dir/$webview_public_framework_ijar" } generate_resource_rewriter("glue_resource_rewriter") { @@ -21,35 +38,41 @@ package_name = "com.android.webview.chromium" } -if (!defined(use_webview_internal_framework) || - !use_webview_internal_framework) { - android_library("glue") { - # Change deps? please modify glue_library_deps variable. - deps = glue_library_deps - srcjar_deps = [ ":glue_resource_rewriter" ] +android_library("glue") { + # Change deps? please modify glue_library_deps variable. + deps = glue_library_deps + srcjar_deps = [ ":glue_resource_rewriter" ] - alternative_android_sdk_ijar = webview_framework_ijar - alternative_android_sdk_ijar_dep = "//android_webview/glue:framework_ijar" - - java_files = [ - "java/src/com/android/webview/chromium/ContentSettingsAdapter.java", - "java/src/com/android/webview/chromium/CookieManagerAdapter.java", - "java/src/com/android/webview/chromium/DrawGLFunctor.java", - "java/src/com/android/webview/chromium/GeolocationPermissionsAdapter.java", - "java/src/com/android/webview/chromium/GraphicsUtils.java", - "java/src/com/android/webview/chromium/LicenseActivity.java", - "java/src/com/android/webview/chromium/LicenseContentProvider.java", - "java/src/com/android/webview/chromium/ResourcesContextWrapperFactory.java", - "java/src/com/android/webview/chromium/WebBackForwardListChromium.java", - "java/src/com/android/webview/chromium/WebHistoryItemChromium.java", - "java/src/com/android/webview/chromium/WebIconDatabaseAdapter.java", - "java/src/com/android/webview/chromium/WebMessagePortAdapter.java", - "java/src/com/android/webview/chromium/WebStorageAdapter.java", - "java/src/com/android/webview/chromium/WebViewChromiumFactoryProvider.java", - "java/src/com/android/webview/chromium/WebViewChromium.java", - "java/src/com/android/webview/chromium/WebViewContentsClientAdapter.java", - "java/src/com/android/webview/chromium/WebViewDatabaseAdapter.java", - "java/src/com/android/webview/chromium/WebViewDelegateFactory.java", - ] + # Always build upstream or downstream target with public or internal + # framework jar respectively. + if (is_upstream) { + alternative_android_sdk_ijar_dep = ":public_framework_ijar" + _ijar = webview_public_framework_ijar + } else { + assert(defined(webview_internal_framework_jar)) + alternative_android_sdk_ijar_dep = ":framework_ijar" + _ijar = webview_framework_ijar } + _ijar_dir = get_label_info(alternative_android_sdk_ijar_dep, "target_out_dir") + alternative_android_sdk_ijar = "$_ijar_dir/$_ijar" + java_files = [ + "java/src/com/android/webview/chromium/ContentSettingsAdapter.java", + "java/src/com/android/webview/chromium/CookieManagerAdapter.java", + "java/src/com/android/webview/chromium/DrawGLFunctor.java", + "java/src/com/android/webview/chromium/GeolocationPermissionsAdapter.java", + "java/src/com/android/webview/chromium/GraphicsUtils.java", + "java/src/com/android/webview/chromium/LicenseActivity.java", + "java/src/com/android/webview/chromium/LicenseContentProvider.java", + "java/src/com/android/webview/chromium/ResourcesContextWrapperFactory.java", + "java/src/com/android/webview/chromium/WebBackForwardListChromium.java", + "java/src/com/android/webview/chromium/WebHistoryItemChromium.java", + "java/src/com/android/webview/chromium/WebIconDatabaseAdapter.java", + "java/src/com/android/webview/chromium/WebMessagePortAdapter.java", + "java/src/com/android/webview/chromium/WebStorageAdapter.java", + "java/src/com/android/webview/chromium/WebViewChromiumFactoryProvider.java", + "java/src/com/android/webview/chromium/WebViewChromium.java", + "java/src/com/android/webview/chromium/WebViewContentsClientAdapter.java", + "java/src/com/android/webview/chromium/WebViewDatabaseAdapter.java", + "java/src/com/android/webview/chromium/WebViewDelegateFactory.java", + ] }
diff --git a/android_webview/glue/java/src/com/android/webview/chromium/DrawGLFunctor.java b/android_webview/glue/java/src/com/android/webview/chromium/DrawGLFunctor.java index b12cb04..597313b 100644 --- a/android_webview/glue/java/src/com/android/webview/chromium/DrawGLFunctor.java +++ b/android_webview/glue/java/src/com/android/webview/chromium/DrawGLFunctor.java
@@ -5,6 +5,7 @@ package com.android.webview.chromium; import android.graphics.Canvas; +import android.os.Build; import android.view.View; import com.android.webview.chromium.WebViewDelegateFactory.WebViewDelegate; @@ -52,7 +53,10 @@ } } - public boolean requestDrawGL(Canvas canvas, View containerView, boolean waitForCompletion) { + private static final boolean sSupportFunctorReleasedCallback = + (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) || "N".equals(Build.VERSION.CODENAME); + public boolean requestDrawGL(Canvas canvas, View containerView, boolean waitForCompletion, + Runnable releasedCallback) { if (mDestroyRunnable.mNativeDrawGLFunctor == 0) { throw new RuntimeException("requested DrawGL on already destroyed DrawGLFunctor"); } @@ -69,15 +73,27 @@ mContainerView = containerView; if (canvas == null) { + assert releasedCallback == null; mWebViewDelegate.invokeDrawGlFunctor( containerView, mDestroyRunnable.mNativeDrawGLFunctor, waitForCompletion); return true; } - mWebViewDelegate.callDrawGlFunction(canvas, mDestroyRunnable.mNativeDrawGLFunctor); + if (sSupportFunctorReleasedCallback) { + assert releasedCallback != null; + mWebViewDelegate.callDrawGlFunction( + canvas, mDestroyRunnable.mNativeDrawGLFunctor, releasedCallback); + } else { + assert releasedCallback == null; + mWebViewDelegate.callDrawGlFunction(canvas, mDestroyRunnable.mNativeDrawGLFunctor); + } return true; } + public static boolean supportsDrawGLFunctorReleasedCallback() { + return sSupportFunctorReleasedCallback; + } + public static void setChromiumAwDrawGLFunction(long functionPointer) { nativeSetChromiumAwDrawGLFunction(functionPointer); }
diff --git a/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromium.java b/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromium.java index 4769a4e..49bc09a 100644 --- a/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromium.java +++ b/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromium.java
@@ -2248,17 +2248,19 @@ // AwContents.NativeGLDelegate implementation -------------------------------------- private class WebViewNativeGLDelegate implements AwContents.NativeGLDelegate { @Override - public boolean setDrawGLFunctionDetachedCallback(View view, Runnable callback) { - return false; // Not supported yet. + public boolean supportsDrawGLFunctorReleasedCallback() { + return DrawGLFunctor.supportsDrawGLFunctorReleasedCallback(); } @Override - public boolean requestDrawGL(Canvas canvas, boolean waitForCompletion, View containerView) { + public boolean requestDrawGL(Canvas canvas, boolean waitForCompletion, View containerView, + Runnable releasedCallback) { if (mGLfunctor == null) { mGLfunctor = new DrawGLFunctor( mAwContents.getAwDrawGLViewContext(), mFactory.getWebViewDelegate()); } - return mGLfunctor.requestDrawGL(canvas, containerView, waitForCompletion); + return mGLfunctor.requestDrawGL( + canvas, containerView, waitForCompletion, releasedCallback); } @Override
diff --git a/android_webview/glue/java/src/com/android/webview/chromium/WebViewDelegateFactory.java b/android_webview/glue/java/src/com/android/webview/chromium/WebViewDelegateFactory.java index 56e797ff..6a8ff972 100644 --- a/android_webview/glue/java/src/com/android/webview/chromium/WebViewDelegateFactory.java +++ b/android_webview/glue/java/src/com/android/webview/chromium/WebViewDelegateFactory.java
@@ -59,9 +59,15 @@ void invokeDrawGlFunctor( View containerView, long nativeDrawGLFunctor, boolean waitForCompletion); - /** @see android.webkit.WebViewDelegate#callDrawGlFunction */ + /** @see android.webkit.WebViewDelegate#callDrawGlFunction. Available API level 23 and + * below. + */ void callDrawGlFunction(Canvas canvas, long nativeDrawGLFunctor); + /** @see android.webkit.WebViewDelegate#callDrawGlFunction. Available above API level 23 + * only. */ + void callDrawGlFunction(Canvas canvas, long nativeDrawGLFunctor, Runnable releasedRunnable); + /** @see android.webkit.WebViewDelegate#detachDrawGlFunctor */ void detachDrawGlFunctor(View containerView, long nativeDrawGLFunctor); @@ -144,6 +150,12 @@ } @Override + public void callDrawGlFunction( + Canvas canvas, long nativeDrawGLFunctor, Runnable releasedRunnable) { + throw new RuntimeException("Call not supported"); + } + + @Override public void detachDrawGlFunctor(View containerView, long nativeDrawGLFunctor) { mDelegate.detachDrawGlFunctor(containerView, nativeDrawGLFunctor); } @@ -305,6 +317,12 @@ } @Override + public void callDrawGlFunction( + Canvas canvas, long nativeDrawGLFunctor, Runnable releasedRunnable) { + throw new RuntimeException("Call not supported"); + } + + @Override public void detachDrawGlFunctor(View containerView, long nativeDrawGLFunctor) { try { Object viewRootImpl = mGetViewRootImplMethod.invoke(containerView);
diff --git a/android_webview/java/src/org/chromium/android_webview/AwContents.java b/android_webview/java/src/org/chromium/android_webview/AwContents.java index 6c350aef..98935fb 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwContents.java +++ b/android_webview/java/src/org/chromium/android_webview/AwContents.java
@@ -169,13 +169,7 @@ * native GL rendering. */ public interface NativeGLDelegate { - /** - * Set the callback for when the getAwDrawGLFunction objects is safe to be deleted - * for this view. The callback forms a lifecycle between requestDrawGL (with canvas). - * - * @return false if not supported and this is a no-op; true otherwise. - */ - boolean setDrawGLFunctionDetachedCallback(View view, Runnable callback); + boolean supportsDrawGLFunctorReleasedCallback(); /** * Requests a callback on the native DrawGL method (see getAwDrawGLFunction) @@ -189,7 +183,8 @@ * @return false indicates the GL draw request was not accepted, and the caller * should fallback to the SW path. */ - boolean requestDrawGL(Canvas canvas, boolean waitForCompletion, View containerView); + boolean requestDrawGL(Canvas canvas, boolean waitForCompletion, View containerView, + Runnable releasedRunnable); /** * Detaches the GLFunctor from the view tree. @@ -252,8 +247,6 @@ // This can be accessed on any thread after construction. See AwContentsIoThreadClient. private final AwSettings mSettings; private final ScrollAccessibilityHelper mScrollAccessibilityHelper; - private final boolean mSupportsFunctorDetachedCallback; - private boolean mFunctorDetachedCallbackPending; private boolean mIsPaused; private boolean mIsViewVisible; @@ -329,17 +322,18 @@ // Hold onto a reference to the window (via its wrapper), so that it is not destroyed // until we are done here. private final WindowAndroidWrapper mWindowAndroid; - private final AwGLFunctor mAwGLFunctor; + private final Runnable mAwGLFunctorDestroyRunnable; private DestroyRunnable(long nativeAwContents, WindowAndroidWrapper windowAndroid, AwGLFunctor awGLFunctor) { mNativeAwContents = nativeAwContents; mWindowAndroid = windowAndroid; - mAwGLFunctor = awGLFunctor; + mAwGLFunctorDestroyRunnable = awGLFunctor.getDestroyRunnable(); } @Override public void run() { nativeDestroy(mNativeAwContents); + mAwGLFunctorDestroyRunnable.run(); } } @@ -765,13 +759,6 @@ setNewAwContents(nativeInit(mBrowserContext)); - mSupportsFunctorDetachedCallback = - mNativeGLDelegate.setDrawGLFunctionDetachedCallback(mContainerView, new Runnable() { - @Override - public void run() { - onFunctorDetached(); - } - }); onContainerViewChanged(); } @@ -990,10 +977,7 @@ mContentViewCore = createAndInitializeContentViewCore(mContainerView, mContext, mInternalAccessAdapter, webContents, new AwGestureStateListener(), mContentViewClient, mZoomControls, mWindowAndroid.getWindowAndroid()); - mAwGLFunctor = new AwGLFunctor(); - if (mIsAttachedToWindow) { - mAwGLFunctor.onAttachedToWindow(mNativeGLDelegate, mContainerView); - } + mAwGLFunctor = new AwGLFunctor(mNativeGLDelegate, mContainerView); nativeSetAwGLFunctor(mNativeAwContents, mAwGLFunctor.getNativeAwGLFunctor()); nativeSetJavaPeers(mNativeAwContents, this, mWebContentsDelegate, mContentsClientBridge, mIoThreadClient, mInterceptNavigationDelegate); @@ -1113,7 +1097,7 @@ // hardware resources. if (mIsAttachedToWindow) { Log.w(TAG, "WebView.destroy() called while WebView is still attached to window."); - mAwGLFunctor.onDetachedFromWindow(); + mAwGLFunctor.deleteHardwareRenderer(); nativeOnDetachedFromWindow(mNativeAwContents); } mIsDestroyed = true; @@ -1142,10 +1126,6 @@ mCleanupReference.cleanupNow(); mCleanupReference = null; - if (!mFunctorDetachedCallbackPending) { - mAwGLFunctor.destroy(); - mAwGLFunctor = null; - } } assert mContentViewCore == null; @@ -2344,16 +2324,6 @@ mAwViewMethods.onDetachedFromWindow(); } - // Note short term fix. This is only called for the original container view, not the - // FullScreenView. - public void onFunctorDetached() { - mFunctorDetachedCallbackPending = false; - if (isDestroyed(NO_WARN) && mAwGLFunctor != null) { - mAwGLFunctor.destroy(); - mAwGLFunctor = null; - } - } - /** * @see android.view.View#onWindowFocusChanged() */ @@ -2948,9 +2918,7 @@ canvas.isHardwareAccelerated(), scrollX, scrollY, globalVisibleRect.left, globalVisibleRect.top, globalVisibleRect.right, globalVisibleRect.bottom); if (did_draw && canvas.isHardwareAccelerated() && !FORCE_AUXILIARY_BITMAP_RENDERING) { - did_draw = mNativeGLDelegate.requestDrawGL(canvas, false, mContainerView); - mFunctorDetachedCallbackPending |= - (mSupportsFunctorDetachedCallback && did_draw && !isFullScreen()); + did_draw = mAwGLFunctor.requestDrawGLForCanvas(canvas); } if (did_draw) { int scrollXDiff = mContainerView.getScrollX() - scrollX; @@ -3098,7 +3066,6 @@ mContentViewCore.onAttachedToWindow(); nativeOnAttachedToWindow(mNativeAwContents, mContainerView.getWidth(), mContainerView.getHeight()); - mAwGLFunctor.onAttachedToWindow(mNativeGLDelegate, mContainerView); updateHardwareAcceleratedFeaturesToggle(); postUpdateContentViewCoreVisibility(); @@ -3119,7 +3086,7 @@ } mIsAttachedToWindow = false; hideAutofillPopup(); - mAwGLFunctor.onDetachedFromWindow(); + mAwGLFunctor.deleteHardwareRenderer(); nativeOnDetachedFromWindow(mNativeAwContents); mContentViewCore.onDetachedFromWindow();
diff --git a/android_webview/java/src/org/chromium/android_webview/AwGLFunctor.java b/android_webview/java/src/org/chromium/android_webview/AwGLFunctor.java index caba8d8..4f37589 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwGLFunctor.java +++ b/android_webview/java/src/org/chromium/android_webview/AwGLFunctor.java
@@ -4,12 +4,11 @@ package org.chromium.android_webview; +import android.graphics.Canvas; import android.view.ViewGroup; -import org.chromium.base.Log; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; -import org.chromium.content.common.CleanupReference; /** * Manages state associated with the Android render thread and the draw functor @@ -20,8 +19,6 @@ */ @JNINamespace("android_webview") class AwGLFunctor { - private static final String TAG = "AwGLFunctor"; - private static final class DestroyRunnable implements Runnable { private final long mNativeAwGLFunctor; @@ -34,35 +31,27 @@ } } - private long mNativeAwGLFunctor; - private CleanupReference mCleanupReference; - private AwContents.NativeGLDelegate mNativeGLDelegate; - private ViewGroup mContainerView; + private final long mNativeAwGLFunctor; + private final DestroyRunnable mDestroyRunnable; + private final AwContents.NativeGLDelegate mNativeGLDelegate; + private final ViewGroup mContainerView; + private final Runnable mFunctorReleasedCallback; - public AwGLFunctor() { + public AwGLFunctor(AwContents.NativeGLDelegate nativeGLDelegate, ViewGroup containerView) { mNativeAwGLFunctor = nativeCreate(this); - mCleanupReference = new CleanupReference(this, new DestroyRunnable(mNativeAwGLFunctor)); - } - - public void onAttachedToWindow( - AwContents.NativeGLDelegate nativeGLDelegate, ViewGroup containerView) { + mDestroyRunnable = new DestroyRunnable(mNativeAwGLFunctor); mNativeGLDelegate = nativeGLDelegate; mContainerView = containerView; - } - - public void onDetachedFromWindow() { - deleteHardwareRenderer(); - mNativeGLDelegate = null; - mContainerView = null; - } - - public void destroy() { - if (mCleanupReference != null) { - mNativeGLDelegate = null; - mContainerView = null; - mCleanupReference.cleanupNow(); - mCleanupReference = null; - mNativeAwGLFunctor = 0; + if (mNativeGLDelegate.supportsDrawGLFunctorReleasedCallback()) { + mFunctorReleasedCallback = new Runnable() { + @Override + public void run() { + // Deliberate no-op. This Runnable is holding a strong reference back to the + // AwGLFunctor, which serves its purpose for now. + } + }; + } else { + mFunctorReleasedCallback = null; } } @@ -71,35 +60,34 @@ } public long getNativeAwGLFunctor() { - assert mNativeAwGLFunctor != 0; return mNativeAwGLFunctor; } + public Runnable getDestroyRunnable() { + return mDestroyRunnable; + } + + public boolean requestDrawGLForCanvas(Canvas canvas) { + return mNativeGLDelegate.requestDrawGL( + canvas, false, mContainerView, mFunctorReleasedCallback); + } + @CalledByNative private boolean requestDrawGL(boolean waitForCompletion) { - if (mNativeGLDelegate == null) { - return false; - } - return mNativeGLDelegate.requestDrawGL(null, waitForCompletion, mContainerView); + return mNativeGLDelegate.requestDrawGL(null, waitForCompletion, mContainerView, null); } @CalledByNative private void detachFunctorFromView() { - if (mNativeGLDelegate != null) { - mNativeGLDelegate.detachGLFunctor(); - mContainerView.invalidate(); - } else { - Log.w(TAG, "Unable to detach functor from view. Already detached."); - } + mNativeGLDelegate.detachGLFunctor(); + mContainerView.invalidate(); } public void deleteHardwareRenderer() { - assert mNativeAwGLFunctor != 0; nativeDeleteHardwareRenderer(mNativeAwGLFunctor); } public long getAwDrawGLViewContext() { - assert mNativeAwGLFunctor != 0; return nativeGetAwDrawGLViewContext(mNativeAwGLFunctor); }
diff --git a/android_webview/test/shell/src/org/chromium/android_webview/test/AwTestContainerView.java b/android_webview/test/shell/src/org/chromium/android_webview/test/AwTestContainerView.java index b17033d..13e0fe20 100644 --- a/android_webview/test/shell/src/org/chromium/android_webview/test/AwTestContainerView.java +++ b/android_webview/test/shell/src/org/chromium/android_webview/test/AwTestContainerView.java
@@ -417,13 +417,14 @@ private class NativeGLDelegate implements AwContents.NativeGLDelegate { @Override - public boolean setDrawGLFunctionDetachedCallback(View view, Runnable callback) { + public boolean supportsDrawGLFunctorReleasedCallback() { return false; } @Override - public boolean requestDrawGL(Canvas canvas, boolean waitForCompletion, - View containerview) { + public boolean requestDrawGL(Canvas canvas, boolean waitForCompletion, View containerview, + Runnable releasedRunnable) { + assert releasedRunnable == null; if (!isBackedByHardwareView()) return false; mHardwareView.requestRender(canvas, waitForCompletion); return true;
diff --git a/ash/app_list/app_list_presenter_delegate.cc b/ash/app_list/app_list_presenter_delegate.cc index bbc4c8f3b..7c79ec5 100644 --- a/ash/app_list/app_list_presenter_delegate.cc +++ b/ash/app_list/app_list_presenter_delegate.cc
@@ -51,11 +51,12 @@ gfx::Vector2d GetAnchorPositionOffsetToShelf(const gfx::Rect& button_bounds, views::Widget* widget) { DCHECK(Shell::HasInstance()); - ShelfAlignment shelf_alignment = Shell::GetInstance()->GetShelfAlignment( - widget->GetNativeView()->GetRootWindow()); + ShelfAlignment shelf_alignment = + Shelf::ForWindow(widget->GetNativeView()->GetRootWindow())->alignment(); gfx::Point anchor(button_bounds.CenterPoint()); switch (shelf_alignment) { case SHELF_ALIGNMENT_BOTTOM: + case SHELF_ALIGNMENT_BOTTOM_LOCKED: if (base::i18n::IsRTL()) { int screen_width = widget->GetWorkAreaBoundsInScreen().width(); return gfx::Vector2d( @@ -253,18 +254,10 @@ ->GetShelfLayoutManager() ->UpdateAutoHideState(); - ShelfAlignment shelf_alignment = - Shell::GetInstance()->GetShelfAlignment(root_window); - switch (shelf_alignment) { - case SHELF_ALIGNMENT_BOTTOM: - return gfx::Vector2d(0, kAnimationOffset); - case SHELF_ALIGNMENT_LEFT: - return gfx::Vector2d(-kAnimationOffset, 0); - case SHELF_ALIGNMENT_RIGHT: - return gfx::Vector2d(kAnimationOffset, 0); - } - NOTREACHED(); - return gfx::Vector2d(); + return Shelf::ForWindow(root_window) + ->SelectValueForShelfAlignment(gfx::Vector2d(0, kAnimationOffset), + gfx::Vector2d(-kAnimationOffset, 0), + gfx::Vector2d(kAnimationOffset, 0)); } ////////////////////////////////////////////////////////////////////////////////
diff --git a/ash/ash.gyp b/ash/ash.gyp index 49f8358..e2caf98 100644 --- a/ash/ash.gyp +++ b/ash/ash.gyp
@@ -247,6 +247,8 @@ 'shelf/shelf_layout_manager.cc', 'shelf/shelf_layout_manager.h', 'shelf/shelf_layout_manager_observer.h', + 'shelf/shelf_locking_manager.cc', + 'shelf/shelf_locking_manager.h', 'shelf/shelf_menu_model.h', 'shelf/shelf_model.cc', 'shelf/shelf_model.h', @@ -736,7 +738,6 @@ 'test/shelf_button_pressed_metric_tracker_test_api.h', 'test/shelf_item_delegate_manager_test_api.cc', 'test/shelf_item_delegate_manager_test_api.h', - 'test/shelf_test_api.cc', 'test/shelf_test_api.h', 'test/shelf_view_test_api.cc', 'test/shelf_view_test_api.h',
diff --git a/ash/content/keyboard_overlay/keyboard_overlay_delegate_unittest.cc b/ash/content/keyboard_overlay/keyboard_overlay_delegate_unittest.cc index 32afe08..8b6871c 100644 --- a/ash/content/keyboard_overlay/keyboard_overlay_delegate_unittest.cc +++ b/ash/content/keyboard_overlay/keyboard_overlay_delegate_unittest.cc
@@ -63,6 +63,7 @@ KeyboardOverlayDelegateTest, testing::Values(SHELF_ALIGNMENT_BOTTOM, SHELF_ALIGNMENT_LEFT, - SHELF_ALIGNMENT_RIGHT)); + SHELF_ALIGNMENT_RIGHT, + SHELF_ALIGNMENT_BOTTOM_LOCKED)); } // namespace ash
diff --git a/ash/mus/shelf_delegate_mus.cc b/ash/mus/shelf_delegate_mus.cc index 3e53ad87..310ed9a 100644 --- a/ash/mus/shelf_delegate_mus.cc +++ b/ash/mus/shelf_delegate_mus.cc
@@ -135,7 +135,7 @@ void ShelfDelegateMus::OnShelfAlignmentChanged(Shelf* shelf) { SetShelfPreferredSizes(shelf); mash::shelf::mojom::Alignment alignment = - static_cast<mash::shelf::mojom::Alignment>(shelf->GetAlignment()); + static_cast<mash::shelf::mojom::Alignment>(shelf->alignment()); shelf_layout_->SetAlignment(alignment); observers_.ForAllPtrs( @@ -191,7 +191,7 @@ // Notify the observer of the current state. Shelf* shelf = Shelf::ForPrimaryDisplay(); observer_ptr->OnAlignmentChanged( - static_cast<mash::shelf::mojom::Alignment>(shelf->GetAlignment())); + static_cast<mash::shelf::mojom::Alignment>(shelf->alignment())); observer_ptr->OnAutoHideBehaviorChanged( static_cast<mash::shelf::mojom::AutoHideBehavior>( shelf->auto_hide_behavior()));
diff --git a/ash/shelf/shelf.cc b/ash/shelf/shelf.cc index 8d96506..0609d6d 100644 --- a/ash/shelf/shelf.cc +++ b/ash/shelf/shelf.cc
@@ -42,12 +42,10 @@ Shelf::Shelf(ShelfModel* shelf_model, ShelfDelegate* shelf_delegate, ShelfWidget* shelf_widget) - : shelf_view_(nullptr), - alignment_(SHELF_ALIGNMENT_BOTTOM), - auto_hide_behavior_(SHELF_AUTO_HIDE_BEHAVIOR_NEVER), - delegate_(shelf_delegate), - shelf_widget_(shelf_widget) { - shelf_view_ = new ShelfView(shelf_model, delegate_, this); + : delegate_(shelf_delegate), + shelf_widget_(shelf_widget), + shelf_view_(new ShelfView(shelf_model, delegate_, this)), + shelf_locking_manager_(this) { shelf_view_->Init(); shelf_widget_->GetContentsView()->AddChildView(shelf_view_); shelf_widget_->GetNativeView()->SetName(kNativeViewName); @@ -81,14 +79,8 @@ // ShelfLayoutManager will resize the shelf. } -ShelfAlignment Shelf::GetAlignment() const { - // Bottom alignment is forced when the screen is locked or a user gets added. - bool locked = shelf_widget_->shelf_layout_manager()->IsAlignmentLocked(); - return locked ? SHELF_ALIGNMENT_BOTTOM : alignment_; -} - bool Shelf::IsHorizontalAlignment() const { - return alignment_ == SHELF_ALIGNMENT_BOTTOM; + return ash::IsHorizontalAlignment(alignment_); } void Shelf::SetAutoHideBehavior(ShelfAutoHideBehavior auto_hide_behavior) {
diff --git a/ash/shelf/shelf.h b/ash/shelf/shelf.h index b602e93..30c8296 100644 --- a/ash/shelf/shelf.h +++ b/ash/shelf/shelf.h
@@ -7,6 +7,7 @@ #include "ash/ash_export.h" #include "ash/shelf/shelf_constants.h" +#include "ash/shelf/shelf_locking_manager.h" #include "ash/shelf/shelf_types.h" #include "ash/shelf/shelf_widget.h" #include "base/macros.h" @@ -56,12 +57,9 @@ static Shelf* ForWindow(const aura::Window* window); void SetAlignment(ShelfAlignment alignment); - ShelfAlignment GetAlignment() const; + ShelfAlignment alignment() const { return alignment_; } bool IsHorizontalAlignment() const; - // TODO(msw): Remove this accessor, kept temporarily to simplify changes. - ShelfAlignment alignment() const { return GetAlignment(); } - // Sets the ShelfAutoHideBehavior. See enum description for details. void SetAutoHideBehavior(ShelfAutoHideBehavior auto_hide_behavior); ShelfAutoHideBehavior auto_hide_behavior() const { @@ -76,6 +74,7 @@ T SelectValueForShelfAlignment(T bottom, T left, T right) const { switch (alignment_) { case SHELF_ALIGNMENT_BOTTOM: + case SHELF_ALIGNMENT_BOTTOM_LOCKED: return bottom; case SHELF_ALIGNMENT_LEFT: return left; @@ -143,15 +142,13 @@ private: friend class test::ShelfTestAPI; - // ShelfView used to display icons. - ShelfView* shelf_view_; - - ShelfAlignment alignment_; - ShelfAutoHideBehavior auto_hide_behavior_; - ShelfDelegate* delegate_; - ShelfWidget* shelf_widget_; + ShelfView* shelf_view_; + ShelfLockingManager shelf_locking_manager_; + + ShelfAlignment alignment_ = SHELF_ALIGNMENT_BOTTOM; + ShelfAutoHideBehavior auto_hide_behavior_ = SHELF_AUTO_HIDE_BEHAVIOR_NEVER; DISALLOW_COPY_AND_ASSIGN(Shelf); };
diff --git a/ash/shelf/shelf_bezel_event_filter.cc b/ash/shelf/shelf_bezel_event_filter.cc index 39f8101..3d6ab47 100644 --- a/ash/shelf/shelf_bezel_event_filter.cc +++ b/ash/shelf/shelf_bezel_event_filter.cc
@@ -51,24 +51,11 @@ } } -bool ShelfBezelEventFilter::IsShelfOnBezel( - const gfx::Rect& screen, - const gfx::Point& point) const{ - switch (shelf_->GetAlignment()) { - case SHELF_ALIGNMENT_BOTTOM: - if (point.y() >= screen.bottom()) - return true; - break; - case SHELF_ALIGNMENT_LEFT: - if (point.x() <= screen.x()) - return true; - break; - case SHELF_ALIGNMENT_RIGHT: - if (point.x() >= screen.right()) - return true; - break; - } - return false; +bool ShelfBezelEventFilter::IsShelfOnBezel(const gfx::Rect& screen, + const gfx::Point& point) const { + return shelf_->SelectValueForShelfAlignment(point.y() >= screen.bottom(), + point.x() <= screen.x(), + point.x() >= screen.right()); } } // namespace ash
diff --git a/ash/shelf/shelf_button.cc b/ash/shelf/shelf_button.cc index 7a805bd..328fe51 100644 --- a/ash/shelf/shelf_button.cc +++ b/ash/shelf/shelf_button.cc
@@ -180,7 +180,7 @@ double animation = animating_ ? ShelfButtonAnimation::GetInstance()->GetAnimation() : 1.0; double scale = .35 + .65 * animation; - if (shelf_->alignment() == SHELF_ALIGNMENT_BOTTOM) { + if (shelf_->IsHorizontalAlignment()) { int width = base_bounds_.width() * scale; bounds.set_width(std::min(width, kIconSize)); int x_offset = (base_bounds_.width() - bounds.width()) / 2; @@ -485,19 +485,16 @@ bar_id = IDR_ASH_SHELF_UNDERLINE_RUNNING; if (bar_id != 0) { - ResourceBundle& rb = ResourceBundle::GetSharedInstance(); - const gfx::ImageSkia* image = rb.GetImageNamed(bar_id).ToImageSkia(); - Shelf* shelf = shelf_view_->shelf(); - if (shelf->alignment() == SHELF_ALIGNMENT_BOTTOM) { - bar_->SetImage(*image); - } else { - bar_->SetImage(gfx::ImageSkiaOperations::CreateRotatedImage( - *image, shelf->SelectValueForShelfAlignment( - SkBitmapOperations::ROTATION_90_CW, - SkBitmapOperations::ROTATION_90_CW, - SkBitmapOperations::ROTATION_270_CW))); + ResourceBundle* rb = &ResourceBundle::GetSharedInstance(); + gfx::ImageSkia image = *rb->GetImageNamed(bar_id).ToImageSkia(); + if (!shelf->IsHorizontalAlignment()) { + image = gfx::ImageSkiaOperations::CreateRotatedImage( + image, shelf->alignment() == SHELF_ALIGNMENT_LEFT + ? SkBitmapOperations::ROTATION_90_CW + : SkBitmapOperations::ROTATION_270_CW); } + bar_->SetImage(image); bar_->SetHorizontalAlignment(shelf->SelectValueForShelfAlignment( views::ImageView::CENTER, views::ImageView::LEADING, views::ImageView::TRAILING));
diff --git a/ash/shelf/shelf_layout_manager.cc b/ash/shelf/shelf_layout_manager.cc index 5d1bf38..d37901b8 100644 --- a/ash/shelf/shelf_layout_manager.cc +++ b/ash/shelf/shelf_layout_manager.cc
@@ -19,6 +19,7 @@ #include "ash/shelf/shelf_bezel_event_filter.h" #include "ash/shelf/shelf_constants.h" #include "ash/shelf/shelf_layout_manager_observer.h" +#include "ash/shelf/shelf_util.h" #include "ash/shelf/shelf_widget.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" @@ -387,6 +388,7 @@ bool correct_direction = false; switch (GetAlignment()) { case SHELF_ALIGNMENT_BOTTOM: + case SHELF_ALIGNMENT_BOTTOM_LOCKED: case SHELF_ALIGNMENT_RIGHT: correct_direction = gesture_drag_amount_ < 0; break; @@ -491,26 +493,7 @@ } bool ShelfLayoutManager::IsHorizontalAlignment() const { - return GetAlignment() == SHELF_ALIGNMENT_BOTTOM; -} - -bool ShelfLayoutManager::IsAlignmentLocked() const { - if (state_.is_screen_locked) - return true; - // The session state becomes active at the start of transitioning to a user - // session, however the session is considered blocked until the full UI is - // ready. Exit early to allow for proper layout. - SessionStateDelegate* session_state_delegate = - Shell::GetInstance()->session_state_delegate(); - if (session_state_delegate->GetSessionState() == - SessionStateDelegate::SESSION_STATE_ACTIVE) { - return false; - } - if (session_state_delegate->IsUserSessionBlocked() || - state_.is_adding_user_screen) { - return true; - } - return false; + return ash::IsHorizontalAlignment(GetAlignment()); } void ShelfLayoutManager::SetChromeVoxPanelHeight(int height) { @@ -852,7 +835,7 @@ int shelf_height = target_bounds->shelf_bounds_in_root.height() - translate; shelf_height = std::max(shelf_height, kAutoHideSize); target_bounds->shelf_bounds_in_root.set_height(shelf_height); - if (GetAlignment() == SHELF_ALIGNMENT_BOTTOM) { + if (IsHorizontalAlignment()) { target_bounds->shelf_bounds_in_root.set_y( available_bounds.bottom() - shelf_height); } @@ -1008,7 +991,7 @@ ShelfAlignment alignment = GetAlignment(); shelf_region.Inset( alignment == SHELF_ALIGNMENT_RIGHT ? -kNotificationBubbleGapHeight : 0, - alignment == SHELF_ALIGNMENT_BOTTOM ? -kNotificationBubbleGapHeight : 0, + IsHorizontalAlignment() ? -kNotificationBubbleGapHeight : 0, alignment == SHELF_ALIGNMENT_LEFT ? -kNotificationBubbleGapHeight : 0, 0); } @@ -1118,9 +1101,6 @@ void ShelfLayoutManager::UpdateShelfVisibilityAfterLoginUIChange() { UpdateVisibilityState(); LayoutShelf(); - // The shelf alignment may have changed when it was unlocked. - Shell::GetInstance()->OnShelfAlignmentChanged( - shelf_->GetNativeWindow()->GetRootWindow()); } } // namespace ash
diff --git a/ash/shelf/shelf_layout_manager.h b/ash/shelf/shelf_layout_manager.h index e8e696ad..3689d017 100644 --- a/ash/shelf/shelf_layout_manager.h +++ b/ash/shelf/shelf_layout_manager.h
@@ -191,6 +191,7 @@ T SelectValueForShelfAlignment(T bottom, T left, T right) const { switch (GetAlignment()) { case SHELF_ALIGNMENT_BOTTOM: + case SHELF_ALIGNMENT_BOTTOM_LOCKED: return bottom; case SHELF_ALIGNMENT_LEFT: return left; @@ -209,11 +210,6 @@ // Is the shelf's alignment horizontal? bool IsHorizontalAlignment() const; - // Returns true when the alignment is locked. This can be caused by the screen - // being locked, or when adding a user. Returns false when transitioning to a - // user session, and while the session is active. - bool IsAlignmentLocked() const; - // Set the height of the ChromeVox panel, which takes away space from the // available work area from the top of the screen. void SetChromeVoxPanelHeight(int height);
diff --git a/ash/shelf/shelf_layout_manager_unittest.cc b/ash/shelf/shelf_layout_manager_unittest.cc index 1f97dcb..99412ee3 100644 --- a/ash/shelf/shelf_layout_manager_unittest.cc +++ b/ash/shelf/shelf_layout_manager_unittest.cc
@@ -14,6 +14,7 @@ #include "ash/session/session_state_delegate.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_layout_manager_observer.h" +#include "ash/shelf/shelf_locking_manager.h" #include "ash/shelf/shelf_view.h" #include "ash/shelf/shelf_widget.h" #include "ash/shell.h" @@ -381,10 +382,14 @@ // Open the add user screen if |show| is true, otherwise end it. void ShowAddUserScreen(bool show) { SetUserAddingScreenRunning(show); - ShelfLayoutManager* manager = GetShelfWidget()->shelf_layout_manager(); - manager->SessionStateChanged( - show ? SessionStateDelegate::SESSION_STATE_LOGIN_SECONDARY : - SessionStateDelegate::SESSION_STATE_ACTIVE); + + const SessionStateDelegate::SessionState state = + show ? SessionStateDelegate::SESSION_STATE_LOGIN_SECONDARY + : SessionStateDelegate::SESSION_STATE_ACTIVE; + GetShelfWidget()->shelf_layout_manager()->SessionStateChanged(state); + test::ShelfTestAPI(GetShelfWidget()->shelf()) + .shelf_locking_manager() + ->SessionStateChanged(state); } private: @@ -764,7 +769,7 @@ manager->SetAlignment(SHELF_ALIGNMENT_LEFT); EXPECT_EQ(SHELF_ALIGNMENT_LEFT, manager->GetAlignment()); LockScreen(); - EXPECT_EQ(SHELF_ALIGNMENT_BOTTOM, manager->GetAlignment()); + EXPECT_EQ(SHELF_ALIGNMENT_BOTTOM_LOCKED, manager->GetAlignment()); UnlockScreen(); EXPECT_EQ(SHELF_ALIGNMENT_LEFT, manager->GetAlignment()); } @@ -775,7 +780,7 @@ manager->SetAlignment(SHELF_ALIGNMENT_LEFT); EXPECT_EQ(SHELF_ALIGNMENT_LEFT, manager->GetAlignment()); ShowAddUserScreen(true); - EXPECT_EQ(SHELF_ALIGNMENT_BOTTOM, manager->GetAlignment()); + EXPECT_EQ(SHELF_ALIGNMENT_BOTTOM_LOCKED, manager->GetAlignment()); ShowAddUserScreen(false); EXPECT_EQ(SHELF_ALIGNMENT_LEFT, manager->GetAlignment()); }
diff --git a/ash/shelf/shelf_locking_manager.cc b/ash/shelf/shelf_locking_manager.cc new file mode 100644 index 0000000..d291da6 --- /dev/null +++ b/ash/shelf/shelf_locking_manager.cc
@@ -0,0 +1,62 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/shelf/shelf_locking_manager.h" + +#include "ash/session/session_state_delegate.h" +#include "ash/shelf/shelf.h" +#include "ash/shell.h" +#include "ash/wm/lock_state_controller.h" + +namespace ash { + +ShelfLockingManager::ShelfLockingManager(Shelf* shelf) : shelf_(shelf) { + Shell* shell = Shell::GetInstance(); + shell->lock_state_controller()->AddObserver(this); + SessionStateDelegate* delegate = shell->session_state_delegate(); + session_locked_ = + delegate->GetSessionState() != SessionStateDelegate::SESSION_STATE_ACTIVE; + screen_locked_ = delegate->IsScreenLocked(); + delegate->AddSessionStateObserver(this); + shell->AddShellObserver(this); +} + +ShelfLockingManager::~ShelfLockingManager() { + Shell* shell = Shell::GetInstance(); + shell->lock_state_controller()->RemoveObserver(this); + shell->session_state_delegate()->RemoveSessionStateObserver(this); + shell->RemoveShellObserver(this); +} + +void ShelfLockingManager::OnLockStateChanged(bool locked) { + screen_locked_ = locked; + UpdateLockedState(); +} + +void ShelfLockingManager::SessionStateChanged( + SessionStateDelegate::SessionState state) { + session_locked_ = state != SessionStateDelegate::SESSION_STATE_ACTIVE; + UpdateLockedState(); +} + +void ShelfLockingManager::OnLockStateEvent(EventType event) { + // This is only called when locking the screen; there is no unlock event here. + // It's also called when the screen lock animation begins and should help the + // shelf appear locked much earlier than ShellObserver::OnLockStateChanged. + screen_locked_ = true; + UpdateLockedState(); +} + +void ShelfLockingManager::UpdateLockedState() { + const bool should_be_locked = screen_locked_ || session_locked_; + const ShelfAlignment alignment = shelf_->alignment(); + if (should_be_locked && alignment != SHELF_ALIGNMENT_BOTTOM_LOCKED) { + stored_alignment_ = alignment; + shelf_->SetAlignment(SHELF_ALIGNMENT_BOTTOM_LOCKED); + } else if (!should_be_locked && alignment == SHELF_ALIGNMENT_BOTTOM_LOCKED) { + shelf_->SetAlignment(stored_alignment_); + } +} + +} // namespace ash
diff --git a/ash/shelf/shelf_locking_manager.h b/ash/shelf/shelf_locking_manager.h new file mode 100644 index 0000000..73878e2 --- /dev/null +++ b/ash/shelf/shelf_locking_manager.h
@@ -0,0 +1,49 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_SHELF_SHELF_LOCKING_MANAGER_H_ +#define ASH_SHELF_SHELF_LOCKING_MANAGER_H_ + +#include "ash/ash_export.h" +#include "ash/session/session_state_observer.h" +#include "ash/shelf/shelf_types.h" +#include "ash/shell_observer.h" +#include "ash/wm/lock_state_observer.h" + +namespace ash { + +class Shelf; + +// ShelfLockingManager observes screen and session events to [un]lock the shelf. +class ASH_EXPORT ShelfLockingManager : public ShellObserver, + public SessionStateObserver, + public LockStateObserver { + public: + explicit ShelfLockingManager(Shelf* shelf); + ~ShelfLockingManager() override; + + // ShellObserver: + void OnLockStateChanged(bool locked) override; + + // SessionStateObserver: + void SessionStateChanged(SessionStateDelegate::SessionState state) override; + + // LockStateObserver: + void OnLockStateEvent(EventType event) override; + + private: + // Update the shelf state for session and screen lock changes. + void UpdateLockedState(); + + Shelf* shelf_; + bool session_locked_ = false; + bool screen_locked_ = false; + ShelfAlignment stored_alignment_ = SHELF_ALIGNMENT_BOTTOM; + + DISALLOW_COPY_AND_ASSIGN(ShelfLockingManager); +}; + +} // namespace ash + +#endif // ASH_SHELF_SHELF_LOCKING_MANAGER_H_
diff --git a/ash/shelf/shelf_types.h b/ash/shelf/shelf_types.h index 6540f11..f74279f7 100644 --- a/ash/shelf/shelf_types.h +++ b/ash/shelf/shelf_types.h
@@ -12,6 +12,9 @@ SHELF_ALIGNMENT_LEFT, SHELF_ALIGNMENT_RIGHT, // Top has never been supported. + + // The locked alignment is set temporarily and not saved to preferences. + SHELF_ALIGNMENT_BOTTOM_LOCKED, }; enum ShelfAutoHideBehavior {
diff --git a/ash/shelf/shelf_util.cc b/ash/shelf/shelf_util.cc index 70fa02b..b87d668 100644 --- a/ash/shelf/shelf_util.cc +++ b/ash/shelf/shelf_util.cc
@@ -58,4 +58,9 @@ return window->GetProperty(kShelfItemDetailsKey); } +bool IsHorizontalAlignment(ShelfAlignment alignment) { + return alignment == SHELF_ALIGNMENT_BOTTOM || + alignment == SHELF_ALIGNMENT_BOTTOM_LOCKED; +} + } // namespace ash
diff --git a/ash/shelf/shelf_util.h b/ash/shelf/shelf_util.h index 799e59f..65b893d 100644 --- a/ash/shelf/shelf_util.h +++ b/ash/shelf/shelf_util.h
@@ -7,6 +7,7 @@ #include "ash/ash_export.h" #include "ash/shelf/shelf_item_types.h" +#include "ash/shelf/shelf_types.h" #include "base/strings/string16.h" #include "ui/aura/window.h" @@ -54,6 +55,9 @@ ASH_EXPORT const ShelfItemDetails* GetShelfItemDetailsForWindow( aura::Window* window); +// Returns true if the shelf |alignment| is horizontal. +ASH_EXPORT bool IsHorizontalAlignment(ShelfAlignment alignment); + } // namespace ash #endif // ASH_SHELF_SHELF_UTIL_H_
diff --git a/ash/shelf/shelf_view_unittest.cc b/ash/shelf/shelf_view_unittest.cc index afb5117..0a0bd97 100644 --- a/ash/shelf/shelf_view_unittest.cc +++ b/ash/shelf/shelf_view_unittest.cc
@@ -302,7 +302,7 @@ void SetUp() override { AshTestBase::SetUp(); - test::ShellTestApi test_api(Shell::GetInstance()); + ShellTestApi test_api(Shell::GetInstance()); model_ = test_api.shelf_model(); Shelf* shelf = Shelf::ForPrimaryDisplay(); shelf_view_ = ShelfTestAPI(shelf).shelf_view(); @@ -575,8 +575,8 @@ ASSERT_TRUE(test_api_->overflow_bubble() && test_api_->overflow_bubble()->IsShowing()); - ash::test::ShelfViewTestAPI test_api_for_overflow( - test_api_->overflow_bubble()->shelf_view()); + ShelfViewTestAPI test_api_for_overflow( + test_api_->overflow_bubble()->shelf_view()); int total_item_count = model_->item_count(); @@ -664,12 +664,11 @@ void ReplaceShelfDelegate() { // Replace ShelfDelegate. - test::ShellTestApi shell_test_api(Shell::GetInstance()); + ShellTestApi shell_test_api(Shell::GetInstance()); shell_test_api.SetShelfDelegate(NULL); shelf_delegate_ = new TestShelfDelegateForShelfView(); shell_test_api.SetShelfDelegate(shelf_delegate_); - test::ShelfTestAPI(Shelf::ForPrimaryDisplay()) - .SetShelfDelegate(shelf_delegate_); + ShelfTestAPI(Shelf::ForPrimaryDisplay()).set_delegate(shelf_delegate_); test_api_->SetShelfDelegate(shelf_delegate_); } @@ -962,9 +961,8 @@ // Test that any two successive visible icons never overlap in all shelf // alignment types. const ShelfAlignment kAlignments[] = { - SHELF_ALIGNMENT_LEFT, - SHELF_ALIGNMENT_RIGHT, - SHELF_ALIGNMENT_BOTTOM + SHELF_ALIGNMENT_LEFT, SHELF_ALIGNMENT_RIGHT, SHELF_ALIGNMENT_BOTTOM, + SHELF_ALIGNMENT_BOTTOM_LOCKED, }; for (ShelfAlignment alignment : kAlignments) { @@ -987,12 +985,15 @@ // Making sure the overflow bubble arrow correctly tracks with shelf position. TEST_F(ShelfViewTest, OverflowArrowForShelfPosition) { const ShelfAlignment kAlignments[] = { - SHELF_ALIGNMENT_BOTTOM, SHELF_ALIGNMENT_LEFT, SHELF_ALIGNMENT_RIGHT}; + SHELF_ALIGNMENT_BOTTOM, SHELF_ALIGNMENT_LEFT, SHELF_ALIGNMENT_RIGHT, + SHELF_ALIGNMENT_BOTTOM_LOCKED, + }; // These must match what is expected for each alignment above. const views::BubbleBorder::Arrow kArrows[] = { views::BubbleBorder::BOTTOM_LEFT, views::BubbleBorder::LEFT_TOP, - views::BubbleBorder::RIGHT_TOP}; + views::BubbleBorder::RIGHT_TOP, views::BubbleBorder::BOTTOM_LEFT, + }; for (size_t i = 0; i < arraysize(kAlignments); i++) { shelf_view_->shelf()->SetAlignment(kAlignments[i]); @@ -1653,7 +1654,7 @@ int item_width = test_api_->GetButtonSize() + test_api_->GetButtonSpacing(); OverflowBubbleView* bubble_view = test_api_->overflow_bubble()->bubble_view(); - test::OverflowBubbleViewTestAPI bubble_view_api(bubble_view); + OverflowBubbleViewTestAPI bubble_view_api(bubble_view); // Add more buttons until OverflowBubble is scrollable and it has 3 invisible // items.
diff --git a/ash/shelf/shelf_widget.cc b/ash/shelf/shelf_widget.cc index 1a3e9b6..01e6cbf 100644 --- a/ash/shelf/shelf_widget.cc +++ b/ash/shelf/shelf_widget.cc
@@ -13,6 +13,7 @@ #include "ash/shelf/shelf_layout_manager.h" #include "ash/shelf/shelf_model.h" #include "ash/shelf/shelf_navigator.h" +#include "ash/shelf/shelf_util.h" #include "ash/shelf/shelf_view.h" #include "ash/shelf/shelf_widget.h" #include "ash/shell.h" @@ -41,6 +42,8 @@ #include "ui/wm/core/easy_resize_window_targeter.h" #include "ui/wm/public/activation_client.h" +namespace ash { + namespace { // Size of black border at bottom (or side) of shelf. const int kNumBlackPixels = 3; @@ -54,11 +57,11 @@ // Class used to slightly dim shelf items when maximized and visible. class DimmerView : public views::View, public views::WidgetDelegate, - ash::BackgroundAnimatorDelegate { + BackgroundAnimatorDelegate { public: // If |disable_dimming_animations_for_test| is set, all alpha animations will // be performed instantly. - DimmerView(ash::ShelfWidget* shelf_widget, + DimmerView(ShelfWidget* shelf_widget, bool disable_dimming_animations_for_test); ~DimmerView() override; @@ -72,7 +75,7 @@ views::Widget* GetWidget() override { return View::GetWidget(); } const views::Widget* GetWidget() const override { return View::GetWidget(); } - // ash::BackgroundAnimatorDelegate overrides: + // BackgroundAnimatorDelegate overrides: void UpdateBackground(int alpha) override { alpha_ = alpha; SchedulePaint(); @@ -108,8 +111,8 @@ DISALLOW_COPY_AND_ASSIGN(DimmerEventFilter); }; - // The owning shelf. - ash::ShelfWidget* shelf_; + // The owning shelf widget. + ShelfWidget* shelf_; // The alpha to use for covering the shelf. int alpha_; @@ -124,7 +127,7 @@ bool disable_dimming_animations_for_test_; // The animator for the background transitions. - ash::BackgroundAnimator background_animator_; + BackgroundAnimator background_animator_; // Notification of entering / exiting of the shelf area by mouse. std::unique_ptr<DimmerEventFilter> event_filter_; @@ -132,7 +135,7 @@ DISALLOW_COPY_AND_ASSIGN(DimmerView); }; -DimmerView::DimmerView(ash::ShelfWidget* shelf_widget, +DimmerView::DimmerView(ShelfWidget* shelf_widget, bool disable_dimming_animations_for_test) : shelf_(shelf_widget), alpha_(kDimAlpha), @@ -143,8 +146,7 @@ event_filter_.reset(new DimmerEventFilter(this)); // Make sure it is undimmed at the beginning and then fire off the dimming // animation. - background_animator_.SetPaintsBackground(false, - ash::BACKGROUND_CHANGE_IMMEDIATE); + background_animator_.SetPaintsBackground(false, BACKGROUND_CHANGE_IMMEDIATE); SetHovered(false); } @@ -159,8 +161,9 @@ hovered |= force_hovered_; background_animator_.SetDuration(hovered ? kTimeToUnDimMs : kTimeToDimMs); background_animator_.SetPaintsBackground(!hovered, - disable_dimming_animations_for_test_ ? - ash::BACKGROUND_CHANGE_IMMEDIATE : ash::BACKGROUND_CHANGE_ANIMATE); + disable_dimming_animations_for_test_ + ? BACKGROUND_CHANGE_IMMEDIATE + : BACKGROUND_CHANGE_ANIMATE); } void DimmerView::ForceUndimming(bool force) { @@ -177,37 +180,27 @@ gfx::ImageSkia shelf_background = *rb->GetImageNamed(IDR_ASH_SHELF_DIMMING).ToImageSkia(); - if (shelf_->GetAlignment() != ash::SHELF_ALIGNMENT_BOTTOM) { + if (!IsHorizontalAlignment(shelf_->GetAlignment())) { shelf_background = gfx::ImageSkiaOperations::CreateRotatedImage( - shelf_background, - shelf_->shelf_layout_manager()->SelectValueForShelfAlignment( - SkBitmapOperations::ROTATION_90_CW, - SkBitmapOperations::ROTATION_90_CW, - SkBitmapOperations::ROTATION_270_CW)); + shelf_background, shelf_->GetAlignment() == SHELF_ALIGNMENT_LEFT + ? SkBitmapOperations::ROTATION_90_CW + : SkBitmapOperations::ROTATION_270_CW); } paint.setAlpha(alpha_); - canvas->DrawImageInt(shelf_background, - 0, - 0, - shelf_background.width(), - shelf_background.height(), - 0, - 0, - width(), - height(), - false, - paint); + canvas->DrawImageInt(shelf_background, 0, 0, shelf_background.width(), + shelf_background.height(), 0, 0, width(), height(), + false, paint); } DimmerView::DimmerEventFilter::DimmerEventFilter(DimmerView* owner) : owner_(owner), mouse_inside_(false), touch_inside_(false) { - ash::Shell::GetInstance()->AddPreTargetHandler(this); + Shell::GetInstance()->AddPreTargetHandler(this); } DimmerView::DimmerEventFilter::~DimmerEventFilter() { - ash::Shell::GetInstance()->RemovePreTargetHandler(this); + Shell::GetInstance()->RemovePreTargetHandler(this); } void DimmerView::DimmerEventFilter::OnMouseEvent(ui::MouseEvent* event) { @@ -239,17 +232,14 @@ touch_inside_ = touch_inside; } -using ash::ShelfLayoutManager; - // ShelfWindowTargeter makes it easier to resize windows with the mouse when the // window-edge slightly overlaps with the shelf edge. The targeter also makes it // easier to drag the shelf out with touch while it is hidden. -class ShelfWindowTargeter : public wm::EasyResizeWindowTargeter, - public ash::ShelfLayoutManagerObserver { +class ShelfWindowTargeter : public ::wm::EasyResizeWindowTargeter, + public ShelfLayoutManagerObserver { public: - ShelfWindowTargeter(aura::Window* container, - ShelfLayoutManager* shelf) - : wm::EasyResizeWindowTargeter(container, gfx::Insets(), gfx::Insets()), + ShelfWindowTargeter(aura::Window* container, ShelfLayoutManager* shelf) + : ::wm::EasyResizeWindowTargeter(container, gfx::Insets(), gfx::Insets()), shelf_(shelf) { WillChangeVisibilityState(shelf_->visibility_state()); shelf_->AddObserver(this); @@ -262,36 +252,30 @@ } private: - gfx::Insets GetInsetsForAlignment(int distance, - ash::ShelfAlignment alignment) { - switch (alignment) { - case ash::SHELF_ALIGNMENT_BOTTOM: - return gfx::Insets(distance, 0, 0, 0); - case ash::SHELF_ALIGNMENT_LEFT: - return gfx::Insets(0, 0, 0, distance); - case ash::SHELF_ALIGNMENT_RIGHT: - return gfx::Insets(0, distance, 0, 0); - } - NOTREACHED(); - return gfx::Insets(); + gfx::Insets GetInsetsForAlignment(int distance, ShelfAlignment alignment) { + if (alignment == SHELF_ALIGNMENT_LEFT) + return gfx::Insets(0, 0, 0, distance); + if (alignment == SHELF_ALIGNMENT_RIGHT) + return gfx::Insets(0, distance, 0, 0); + return gfx::Insets(distance, 0, 0, 0); } - // ash::ShelfLayoutManagerObserver: + // ShelfLayoutManagerObserver: void WillDeleteShelf() override { shelf_->RemoveObserver(this); shelf_ = NULL; } - void WillChangeVisibilityState(ash::ShelfVisibilityState new_state) override { + void WillChangeVisibilityState(ShelfVisibilityState new_state) override { gfx::Insets mouse_insets; gfx::Insets touch_insets; - if (new_state == ash::SHELF_VISIBLE) { + if (new_state == SHELF_VISIBLE) { // Let clicks at the very top of the shelf through so windows can be // resized with the bottom-right corner and bottom edge. mouse_insets = GetInsetsForAlignment( ShelfLayoutManager::kWorkspaceAreaVisibleInset, shelf_->GetAlignment()); - } else if (new_state == ash::SHELF_AUTO_HIDE) { + } else if (new_state == SHELF_AUTO_HIDE) { // Extend the touch hit target out a bit to allow users to drag shelf out // while hidden. touch_insets = GetInsetsForAlignment( @@ -310,8 +294,6 @@ } // namespace -namespace ash { - // The contents view of the Shelf. This view contains ShelfView and // sizes it to the width of the shelf minus the size of the status area. class ShelfWidget::DelegateView : public views::WidgetDelegate, @@ -467,34 +449,25 @@ ui::ResourceBundle* rb = &ui::ResourceBundle::GetSharedInstance(); gfx::ImageSkia shelf_background = *rb->GetImageSkiaNamed(IDR_ASH_SHELF_BACKGROUND); - if (SHELF_ALIGNMENT_BOTTOM != shelf_->GetAlignment()) + const bool horizontal = IsHorizontalAlignment(shelf_->GetAlignment()); + if (!horizontal) { shelf_background = gfx::ImageSkiaOperations::CreateRotatedImage( - shelf_background, - shelf_->shelf_layout_manager()->SelectValueForShelfAlignment( - SkBitmapOperations::ROTATION_90_CW, - SkBitmapOperations::ROTATION_90_CW, - SkBitmapOperations::ROTATION_270_CW)); + shelf_background, shelf_->GetAlignment() == SHELF_ALIGNMENT_LEFT + ? SkBitmapOperations::ROTATION_90_CW + : SkBitmapOperations::ROTATION_270_CW); + } const gfx::Rect dock_bounds(shelf_->shelf_layout_manager()->dock_bounds()); SkPaint paint; paint.setAlpha(alpha_); - canvas->DrawImageInt(shelf_background, - 0, - 0, - shelf_background.width(), - shelf_background.height(), - (SHELF_ALIGNMENT_BOTTOM == shelf_->GetAlignment() && - dock_bounds.x() == 0 && dock_bounds.width() > 0) - ? dock_bounds.width() - : 0, - 0, - SHELF_ALIGNMENT_BOTTOM == shelf_->GetAlignment() - ? width() - dock_bounds.width() - : width(), - height(), - false, - paint); - if (SHELF_ALIGNMENT_BOTTOM == shelf_->GetAlignment() && - dock_bounds.width() > 0) { + canvas->DrawImageInt( + shelf_background, 0, 0, shelf_background.width(), + shelf_background.height(), + (horizontal && dock_bounds.x() == 0 && dock_bounds.width() > 0) + ? dock_bounds.width() + : 0, + 0, horizontal ? width() - dock_bounds.width() : width(), height(), false, + paint); + if (horizontal && dock_bounds.width() > 0) { // The part of the shelf background that is in the corner below the docked // windows close to the work area is an arched gradient that blends // vertically oriented docked background and horizontal shelf. @@ -504,30 +477,16 @@ shelf_corner, SkBitmapOperations::ROTATION_90_CW); } canvas->DrawImageInt( - shelf_corner, - 0, - 0, - shelf_corner.width(), - shelf_corner.height(), + shelf_corner, 0, 0, shelf_corner.width(), shelf_corner.height(), dock_bounds.x() > 0 ? dock_bounds.x() : dock_bounds.width() - height(), - 0, - height(), - height(), - false, - paint); + 0, height(), height(), false, paint); // The part of the shelf background that is just below the docked windows // is drawn using the last (lowest) 1-pixel tall strip of the image asset. // This avoids showing the border 3D shadow between the shelf and the dock. - canvas->DrawImageInt(shelf_background, - 0, - shelf_background.height() - 1, - shelf_background.width(), - 1, + canvas->DrawImageInt(shelf_background, 0, shelf_background.height() - 1, + shelf_background.width(), 1, dock_bounds.x() > 0 ? dock_bounds.x() + height() : 0, - 0, - dock_bounds.width() - height(), - height(), - false, + 0, dock_bounds.width() - height(), height(), false, paint); } gfx::Rect black_rect = @@ -728,7 +687,7 @@ ShelfAlignment ShelfWidget::GetAlignment() const { // TODO(msw): This should not be called before |shelf_| is created. - return shelf_ ? shelf_->GetAlignment() : SHELF_ALIGNMENT_BOTTOM; + return shelf_ ? shelf_->alignment() : SHELF_ALIGNMENT_BOTTOM_LOCKED; } void ShelfWidget::OnShelfAlignmentChanged() {
diff --git a/ash/shelf/shelf_widget_unittest.cc b/ash/shelf/shelf_widget_unittest.cc index c1f7780..b596bc0cf 100644 --- a/ash/shelf/shelf_widget_unittest.cc +++ b/ash/shelf/shelf_widget_unittest.cc
@@ -65,6 +65,11 @@ "0,0 400x353"); } { + SCOPED_TRACE("Single Locked"); + TestLauncherAlignment(Shell::GetPrimaryRootWindow(), + SHELF_ALIGNMENT_BOTTOM_LOCKED, "0,0 400x353"); + } + { SCOPED_TRACE("Single Right"); TestLauncherAlignment(Shell::GetPrimaryRootWindow(), SHELF_ALIGNMENT_RIGHT, @@ -88,6 +93,11 @@ "0,0 300x253"); } { + SCOPED_TRACE("Primary Locked"); + TestLauncherAlignment(root_windows[0], SHELF_ALIGNMENT_BOTTOM_LOCKED, + "0,0 300x253"); + } + { SCOPED_TRACE("Primary Right"); TestLauncherAlignment(root_windows[0], SHELF_ALIGNMENT_RIGHT, @@ -106,6 +116,11 @@ "300,0 500x453"); } { + SCOPED_TRACE("Secondary Locked"); + TestLauncherAlignment(root_windows[1], SHELF_ALIGNMENT_BOTTOM_LOCKED, + "300,0 500x453"); + } + { SCOPED_TRACE("Secondary Right"); TestLauncherAlignment(root_windows[1], SHELF_ALIGNMENT_RIGHT, @@ -447,4 +462,11 @@ SHELF_AUTO_HIDE_HIDDEN); } +TEST_F(ShelfWidgetTestWithDelegate, CreateLockedShelf) { + // The auto hide state 'HIDDEN' is returned for any non-auto-hide behavior. + TestCreateShelfWithInitialValues(SHELF_ALIGNMENT_BOTTOM_LOCKED, + SHELF_AUTO_HIDE_BEHAVIOR_NEVER, + SHELF_VISIBLE, SHELF_AUTO_HIDE_HIDDEN); +} + } // namespace ash
diff --git a/ash/shell.cc b/ash/shell.cc index 55f13e6..24397967 100644 --- a/ash/shell.cc +++ b/ash/shell.cc
@@ -513,7 +513,7 @@ ShelfAutoHideBehavior Shell::GetShelfAutoHideBehavior( aura::Window* root_window) const { - return Shelf::ForWindow(root_window)->GetAutoHideBehavior(); + return Shelf::ForWindow(root_window)->auto_hide_behavior(); } void Shell::SetShelfAlignment(ShelfAlignment alignment, @@ -522,7 +522,7 @@ } ShelfAlignment Shell::GetShelfAlignment(const aura::Window* root_window) const { - return Shelf::ForWindow(root_window)->GetAlignment(); + return Shelf::ForWindow(root_window)->alignment(); } void Shell::OnShelfAlignmentChanged(aura::Window* root_window) {
diff --git a/ash/system/cast/tray_cast.cc b/ash/system/cast/tray_cast.cc index 2767e86..fbbc8b5 100644 --- a/ash/system/cast/tray_cast.cc +++ b/ash/system/cast/tray_cast.cc
@@ -6,6 +6,7 @@ #include "ash/session/session_state_delegate.h" #include "ash/shelf/shelf_types.h" +#include "ash/shelf/shelf_util.h" #include "ash/shell.h" #include "ash/system/chromeos/screen_security/screen_tray_item.h" #include "ash/system/tray/fixed_sized_image_view.h" @@ -357,16 +358,9 @@ void CastTrayView::UpdateAlignment(ShelfAlignment alignment) { // Center the item dependent on the orientation of the shelf. - views::BoxLayout::Orientation layout = views::BoxLayout::kHorizontal; - switch (alignment) { - case ash::SHELF_ALIGNMENT_BOTTOM: - layout = views::BoxLayout::kHorizontal; - break; - case ash::SHELF_ALIGNMENT_LEFT: - case ash::SHELF_ALIGNMENT_RIGHT: - layout = views::BoxLayout::kVertical; - break; - } + views::BoxLayout::Orientation layout = IsHorizontalAlignment(alignment) + ? views::BoxLayout::kVertical + : views::BoxLayout::kHorizontal; SetLayoutManager(new views::BoxLayout(layout, 0, 0, 0)); Layout(); }
diff --git a/ash/system/chromeos/network/tray_network.cc b/ash/system/chromeos/network/tray_network.cc index 4bdb4284..5bc9c8f 100644 --- a/ash/system/chromeos/network/tray_network.cc +++ b/ash/system/chromeos/network/tray_network.cc
@@ -6,6 +6,7 @@ #include "ash/ash_switches.h" #include "ash/metrics/user_metrics_recorder.h" +#include "ash/shelf/shelf_util.h" #include "ash/shell.h" #include "ash/system/chromeos/network/network_state_list_detailed_view.h" #include "ash/system/chromeos/network/tray_network_state_observer.h" @@ -91,7 +92,7 @@ } void UpdateAlignment(ShelfAlignment alignment) { - SetLayoutManager(new views::BoxLayout(alignment == SHELF_ALIGNMENT_BOTTOM + SetLayoutManager(new views::BoxLayout(IsHorizontalAlignment(alignment) ? views::BoxLayout::kHorizontal : views::BoxLayout::kVertical, 0, 0, 0));
diff --git a/ash/system/chromeos/screen_security/screen_tray_item.cc b/ash/system/chromeos/screen_security/screen_tray_item.cc index ab8b003..8d5be35 100644 --- a/ash/system/chromeos/screen_security/screen_tray_item.cc +++ b/ash/system/chromeos/screen_security/screen_tray_item.cc
@@ -4,6 +4,7 @@ #include "ash/system/chromeos/screen_security/screen_tray_item.h" +#include "ash/shelf/shelf_util.h" #include "ash/system/tray/fixed_sized_image_view.h" #include "ash/system/tray/tray_constants.h" #include "ui/base/resource/resource_bundle.h" @@ -187,9 +188,9 @@ return; // Center the item dependent on the orientation of the shelf. - views::BoxLayout::Orientation layout = - alignment == ash::SHELF_ALIGNMENT_BOTTOM ? views::BoxLayout::kHorizontal - : views::BoxLayout::kVertical; + views::BoxLayout::Orientation layout = IsHorizontalAlignment(alignment) + ? views::BoxLayout::kHorizontal + : views::BoxLayout::kVertical; tray_view_->SetLayoutManager(new views::BoxLayout(layout, 0, 0, 0)); tray_view_->Layout(); }
diff --git a/ash/system/chromeos/virtual_keyboard/virtual_keyboard_tray.cc b/ash/system/chromeos/virtual_keyboard/virtual_keyboard_tray.cc index 956442a..8e0de69 100644 --- a/ash/system/chromeos/virtual_keyboard/virtual_keyboard_tray.cc +++ b/ash/system/chromeos/virtual_keyboard/virtual_keyboard_tray.cc
@@ -7,6 +7,7 @@ #include "ash/keyboard/keyboard_ui.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_constants.h" +#include "ash/shelf/shelf_util.h" #include "ash/shell.h" #include "ash/system/status_area_widget.h" #include "ash/system/tray/system_tray_notifier.h" @@ -60,7 +61,7 @@ // Square up the padding if horizontally aligned. Avoid extra padding when // vertically aligned as the button would violate the width constraint on the // shelf. - if (alignment == SHELF_ALIGNMENT_BOTTOM) { + if (IsHorizontalAlignment(alignment)) { gfx::Insets insets = button_->GetInsets(); int additional_padding = std::max(0, top_padding - left_padding); left_padding += additional_padding;
diff --git a/ash/system/date/tray_date.cc b/ash/system/date/tray_date.cc index 7d9e4c39..dc0ace7 100644 --- a/ash/system/date/tray_date.cc +++ b/ash/system/date/tray_date.cc
@@ -4,6 +4,7 @@ #include "ash/system/date/tray_date.h" +#include "ash/shelf/shelf_util.h" #include "ash/shell.h" #include "ash/system/date/date_default_view.h" #include "ash/system/date/date_view.h" @@ -95,7 +96,7 @@ void TrayDate::UpdateAfterShelfAlignmentChange(ShelfAlignment alignment) { if (time_tray_) { ClockLayout clock_layout = - alignment == SHELF_ALIGNMENT_BOTTOM ? HORIZONTAL_CLOCK : VERTICAL_CLOCK; + IsHorizontalAlignment(alignment) ? HORIZONTAL_CLOCK : VERTICAL_CLOCK; time_tray_->UpdateClockLayout(clock_layout); } }
diff --git a/ash/system/overview/overview_button_tray.cc b/ash/system/overview/overview_button_tray.cc index e68a193..eb6dce8 100644 --- a/ash/system/overview/overview_button_tray.cc +++ b/ash/system/overview/overview_button_tray.cc
@@ -6,6 +6,7 @@ #include "ash/session/session_state_delegate.h" #include "ash/shelf/shelf_types.h" +#include "ash/shelf/shelf_util.h" #include "ash/shell.h" #include "ash/system/tray/system_tray_delegate.h" #include "ash/system/tray/tray_utils.h" @@ -107,7 +108,7 @@ } void OverviewButtonTray::SetIconBorderForShelfAlignment() { - if (shelf_alignment() == SHELF_ALIGNMENT_BOTTOM) { + if (IsHorizontalAlignment(shelf_alignment())) { icon_->SetBorder(views::Border::CreateEmptyBorder( kHorizontalShelfVerticalPadding, kHorizontalShelfHorizontalPadding,
diff --git a/ash/system/status_area_widget_delegate.cc b/ash/system/status_area_widget_delegate.cc index ce8852de..bce3ef5 100644 --- a/ash/system/status_area_widget_delegate.cc +++ b/ash/system/status_area_widget_delegate.cc
@@ -7,6 +7,7 @@ #include "ash/ash_export.h" #include "ash/ash_switches.h" #include "ash/focus_cycler.h" +#include "ash/shelf/shelf_util.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" #include "ash/system/tray/tray_constants.h" @@ -112,7 +113,7 @@ SetLayoutManager(layout); views::ColumnSet* columns = layout->AddColumnSet(0); - if (alignment_ == SHELF_ALIGNMENT_BOTTOM) { + if (IsHorizontalAlignment(alignment_)) { bool is_first_visible_child = true; for (int c = 0; c < child_count(); ++c) { views::View* child = child_at(c);
diff --git a/ash/system/tray/system_tray.cc b/ash/system/tray/system_tray.cc index 2115708..6be418a 100644 --- a/ash/system/tray/system_tray.cc +++ b/ash/system/tray/system_tray.cc
@@ -7,6 +7,7 @@ #include "ash/ash_switches.h" #include "ash/metrics/user_metrics_recorder.h" #include "ash/shelf/shelf_layout_manager.h" +#include "ash/shelf/shelf_util.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" #include "ash/system/audio/tray_audio.h" @@ -311,15 +312,12 @@ DestroySystemBubble(); UpdateNotificationBubble(); - for (std::vector<SystemTrayItem*>::iterator it = items_.begin(); - it != items_.end(); - ++it) { - (*it)->UpdateAfterLoginStatusChange(login_status); - } + for (SystemTrayItem* item : items_) + item->UpdateAfterLoginStatusChange(login_status); // Items default to SHELF_ALIGNMENT_BOTTOM. Update them if the initial // position of the shelf differs. - if (shelf_alignment() != SHELF_ALIGNMENT_BOTTOM) + if (!IsHorizontalAlignment(shelf_alignment())) UpdateAfterShelfAlignmentChange(shelf_alignment()); SetVisible(true); @@ -327,11 +325,8 @@ } void SystemTray::UpdateAfterShelfAlignmentChange(ShelfAlignment alignment) { - for (std::vector<SystemTrayItem*>::iterator it = items_.begin(); - it != items_.end(); - ++it) { - (*it)->UpdateAfterShelfAlignmentChange(alignment); - } + for (SystemTrayItem* item : items_) + item->UpdateAfterShelfAlignmentChange(alignment); } void SystemTray::SetHideNotifications(bool hide_notifications) { @@ -422,7 +417,7 @@ int SystemTray::GetTrayXOffset(SystemTrayItem* item) const { // Don't attempt to align the arrow if the shelf is on the left or right. - if (shelf_alignment() != SHELF_ALIGNMENT_BOTTOM) + if (!IsHorizontalAlignment(shelf_alignment())) return TrayBubbleView::InitParams::kArrowDefaultOffset; std::map<SystemTrayItem*, views::View*>::const_iterator it = @@ -717,7 +712,7 @@ if (event.IsMouseEvent() || event.type() == ui::ET_GESTURE_TAP) { const ui::LocatedEvent& located_event = static_cast<const ui::LocatedEvent&>(event); - if (shelf_alignment() == SHELF_ALIGNMENT_BOTTOM) { + if (IsHorizontalAlignment(shelf_alignment())) { gfx::Point point(located_event.x(), 0); ConvertPointToWidget(this, &point); arrow_offset = point.x();
diff --git a/ash/system/tray/system_tray_unittest.cc b/ash/system/tray/system_tray_unittest.cc index 30c2b120..ac972887 100644 --- a/ash/system/tray/system_tray_unittest.cc +++ b/ash/system/tray/system_tray_unittest.cc
@@ -365,6 +365,15 @@ EXPECT_TRUE(window_bounds.x() >= tray_bounds.x()); EXPECT_TRUE(window_bounds.y() >= tray_bounds.y()); + // Test in locked alignment. + manager->SetAlignment(SHELF_ALIGNMENT_BOTTOM_LOCKED); + window_bounds = widget->GetWindowBoundsInScreen(); + tray_bounds = tray->GetBoundsInScreen(); + EXPECT_TRUE(window_bounds.bottom() >= tray_bounds.bottom()); + EXPECT_TRUE(window_bounds.right() >= tray_bounds.right()); + EXPECT_TRUE(window_bounds.x() >= tray_bounds.x()); + EXPECT_TRUE(window_bounds.y() >= tray_bounds.y()); + // Test in the left alignment. manager->SetAlignment(SHELF_ALIGNMENT_LEFT); window_bounds = widget->GetWindowBoundsInScreen();
diff --git a/ash/system/tray/tray_background_view.cc b/ash/system/tray/tray_background_view.cc index e0f2fec..0997d77 100644 --- a/ash/system/tray/tray_background_view.cc +++ b/ash/system/tray/tray_background_view.cc
@@ -7,6 +7,7 @@ #include "ash/root_window_controller.h" #include "ash/screen_util.h" #include "ash/shelf/shelf_layout_manager.h" +#include "ash/shelf/shelf_util.h" #include "ash/shelf/shelf_widget.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" @@ -192,7 +193,7 @@ void TrayBackgroundView::TrayContainer::UpdateLayout() { // Adjust the size of status tray dark background by adding additional // empty border. - if (alignment_ == SHELF_ALIGNMENT_BOTTOM) { + if (IsHorizontalAlignment(alignment_)) { SetBorder(views::Border::CreateEmptyBorder( kPaddingFromEdgeOfShelf, kPaddingFromEdgeOfShelf, @@ -403,7 +404,7 @@ // Tray views are laid out right-to-left or bottom-to-top bool on_edge = (this == parent->child_at(0)); int left_edge, top_edge, right_edge, bottom_edge; - if (shelf_alignment() == SHELF_ALIGNMENT_BOTTOM) { + if (IsHorizontalAlignment(shelf_alignment())) { top_edge = ShelfLayoutManager::kShelfItemInset; left_edge = 0; bottom_edge = kShelfSize - @@ -450,7 +451,7 @@ void TrayBackgroundView::HideTransformation() { gfx::Transform transform; - if (shelf_alignment_ == SHELF_ALIGNMENT_BOTTOM) + if (IsHorizontalAlignment(shelf_alignment_)) transform.Translate(width(), 0.0f); else transform.Translate(0.0f, height()); @@ -559,15 +560,10 @@ } TrayBubbleView::AnchorAlignment TrayBackgroundView::GetAnchorAlignment() const { - switch (shelf_alignment_) { - case SHELF_ALIGNMENT_BOTTOM: - return TrayBubbleView::ANCHOR_ALIGNMENT_BOTTOM; - case SHELF_ALIGNMENT_LEFT: - return TrayBubbleView::ANCHOR_ALIGNMENT_LEFT; - case SHELF_ALIGNMENT_RIGHT: - return TrayBubbleView::ANCHOR_ALIGNMENT_RIGHT; - } - NOTREACHED(); + if (shelf_alignment_ == SHELF_ALIGNMENT_LEFT) + return TrayBubbleView::ANCHOR_ALIGNMENT_LEFT; + if (shelf_alignment_ == SHELF_ALIGNMENT_RIGHT) + return TrayBubbleView::ANCHOR_ALIGNMENT_RIGHT; return TrayBubbleView::ANCHOR_ALIGNMENT_BOTTOM; }
diff --git a/ash/system/tray/tray_image_item.cc b/ash/system/tray/tray_image_item.cc index b7891c3f..ba81d02 100644 --- a/ash/system/tray/tray_image_item.cc +++ b/ash/system/tray/tray_image_item.cc
@@ -4,6 +4,7 @@ #include "ash/system/tray/tray_image_item.h" +#include "ash/shelf/shelf_util.h" #include "ash/system/tray/system_tray.h" #include "ash/system/tray/tray_item_view.h" #include "ash/system/tray/tray_utils.h" @@ -73,16 +74,9 @@ void TrayImageItem::SetItemAlignment(ShelfAlignment alignment) { // Center the item dependent on the orientation of the shelf. - views::BoxLayout::Orientation layout = views::BoxLayout::kHorizontal; - switch (alignment) { - case ash::SHELF_ALIGNMENT_BOTTOM: - layout = views::BoxLayout::kHorizontal; - break; - case ash::SHELF_ALIGNMENT_LEFT: - case ash::SHELF_ALIGNMENT_RIGHT: - layout = views::BoxLayout::kVertical; - break; - } + views::BoxLayout::Orientation layout = IsHorizontalAlignment(alignment) + ? views::BoxLayout::kHorizontal + : views::BoxLayout::kVertical; tray_view_->SetLayoutManager(new views::BoxLayout(layout, 0, 0, 0)); tray_view_->Layout(); }
diff --git a/ash/system/tray/tray_item_view.cc b/ash/system/tray/tray_item_view.cc index a1a749a..829360f 100644 --- a/ash/system/tray/tray_item_view.cc +++ b/ash/system/tray/tray_item_view.cc
@@ -5,6 +5,7 @@ #include "ash/system/tray/tray_item_view.h" #include "ash/shelf/shelf_types.h" +#include "ash/shelf/shelf_util.h" #include "ash/system/tray/system_tray.h" #include "ash/system/tray/system_tray_item.h" #include "ui/compositor/layer.h" @@ -85,13 +86,13 @@ gfx::Size TrayItemView::GetPreferredSize() const { gfx::Size size = DesiredSize(); - if (owner()->system_tray()->shelf_alignment() == SHELF_ALIGNMENT_BOTTOM) + if (IsHorizontalAlignment(owner()->system_tray()->shelf_alignment())) size.set_height(kTrayIconHeight); else size.set_width(kTrayIconWidth); if (!animation_.get() || !animation_->is_animating()) return size; - if (owner()->system_tray()->shelf_alignment() == SHELF_ALIGNMENT_BOTTOM) { + if (IsHorizontalAlignment(owner()->system_tray()->shelf_alignment())) { size.set_width(std::max(1, static_cast<int>(size.width() * animation_->GetCurrentValue()))); } else { @@ -111,7 +112,7 @@ void TrayItemView::AnimationProgressed(const gfx::Animation* animation) { gfx::Transform transform; - if (owner()->system_tray()->shelf_alignment() == SHELF_ALIGNMENT_BOTTOM) { + if (IsHorizontalAlignment(owner()->system_tray()->shelf_alignment())) { transform.Translate(0, animation->CurrentValueBetween( static_cast<double>(height()) / 2, 0.)); } else {
diff --git a/ash/system/tray/tray_utils.cc b/ash/system/tray/tray_utils.cc index fd2c81c..9d58afb 100644 --- a/ash/system/tray/tray_utils.cc +++ b/ash/system/tray/tray_utils.cc
@@ -4,6 +4,7 @@ #include "ash/system/tray/tray_utils.h" +#include "ash/shelf/shelf_util.h" #include "ash/system/tray/tray_constants.h" #include "ash/system/tray/tray_item_view.h" #include "ui/accessibility/ax_view_state.h" @@ -26,11 +27,9 @@ void SetTrayImageItemBorder(views::View* tray_view, ShelfAlignment alignment) { - if (alignment == SHELF_ALIGNMENT_BOTTOM) { + if (IsHorizontalAlignment(alignment)) { tray_view->SetBorder(views::Border::CreateEmptyBorder( - 0, - kTrayImageItemHorizontalPaddingBottomAlignment, - 0, + 0, kTrayImageItemHorizontalPaddingBottomAlignment, 0, kTrayImageItemHorizontalPaddingBottomAlignment)); } else { tray_view->SetBorder(views::Border::CreateEmptyBorder( @@ -43,11 +42,9 @@ void SetTrayLabelItemBorder(TrayItemView* tray_view, ShelfAlignment alignment) { - if (alignment == SHELF_ALIGNMENT_BOTTOM) { + if (IsHorizontalAlignment(alignment)) { tray_view->SetBorder(views::Border::CreateEmptyBorder( - 0, - kTrayLabelItemHorizontalPaddingBottomAlignment, - 0, + 0, kTrayLabelItemHorizontalPaddingBottomAlignment, 0, kTrayLabelItemHorizontalPaddingBottomAlignment)); } else { // Center the label for vertical launcher alignment. @@ -55,10 +52,8 @@ (tray_view->GetPreferredSize().width() - tray_view->label()->GetPreferredSize().width()) / 2); tray_view->SetBorder(views::Border::CreateEmptyBorder( - kTrayLabelItemVerticalPaddingVerticalAlignment, - horizontal_padding, - kTrayLabelItemVerticalPaddingVerticalAlignment, - horizontal_padding)); + kTrayLabelItemVerticalPaddingVerticalAlignment, horizontal_padding, + kTrayLabelItemVerticalPaddingVerticalAlignment, horizontal_padding)); } }
diff --git a/ash/system/user/tray_user.cc b/ash/system/user/tray_user.cc index a92bad5..8fe7af4 100644 --- a/ash/system/user/tray_user.cc +++ b/ash/system/user/tray_user.cc
@@ -8,6 +8,7 @@ #include "ash/root_window_controller.h" #include "ash/session/session_state_delegate.h" #include "ash/shelf/shelf_layout_manager.h" +#include "ash/shelf/shelf_util.h" #include "ash/shell_delegate.h" #include "ash/system/tray/system_tray.h" #include "ash/system/tray/system_tray_delegate.h" @@ -191,7 +192,7 @@ // Inactive users won't have a layout. if (!layout_view_) return; - if (alignment == SHELF_ALIGNMENT_BOTTOM) { + if (IsHorizontalAlignment(alignment)) { if (avatar_) { avatar_->SetBorder(views::Border::NullBorder()); avatar_->SetCornerRadii(
diff --git a/ash/system/web_notification/web_notification_tray.cc b/ash/system/web_notification/web_notification_tray.cc index 6692452..1f2e461 100644 --- a/ash/system/web_notification/web_notification_tray.cc +++ b/ash/system/web_notification/web_notification_tray.cc
@@ -8,6 +8,7 @@ #include "ash/root_window_controller.h" #include "ash/shelf/shelf_layout_manager.h" #include "ash/shelf/shelf_layout_manager_observer.h" +#include "ash/shelf/shelf_util.h" #include "ash/shelf/shelf_widget.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" @@ -218,25 +219,14 @@ message_center_tray_.get(), true); - int max_height = 0; + // Assume the status area and bubble bottoms are aligned when vertical. aura::Window* status_area_window = status_area_widget()->GetNativeView(); - switch (GetShelfLayoutManager()->GetAlignment()) { - case SHELF_ALIGNMENT_BOTTOM: { - gfx::Rect shelf_bounds = GetShelfLayoutManager()->GetIdealBounds(); - max_height = shelf_bounds.y(); - break; - } - case SHELF_ALIGNMENT_LEFT: - case SHELF_ALIGNMENT_RIGHT: { - // Assume that the bottom line of the status area widget and the bubble - // are aligned. - max_height = status_area_window->GetBoundsInRootWindow().bottom(); - break; - } - } + const int max_height = + IsHorizontalAlignment(GetShelfLayoutManager()->GetAlignment()) + ? GetShelfLayoutManager()->GetIdealBounds().y() + : status_area_window->GetBoundsInRootWindow().bottom(); - message_center_bubble->SetMaxHeight(std::max(0, - max_height - kTraySpacing)); + message_center_bubble->SetMaxHeight(std::max(0, max_height - kTraySpacing)); if (show_settings) message_center_bubble->SetSettingsVisible(); message_center_bubble_.reset(
diff --git a/ash/test/shelf_test_api.cc b/ash/test/shelf_test_api.cc deleted file mode 100644 index 83bc841f..0000000 --- a/ash/test/shelf_test_api.cc +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ash/test/shelf_test_api.h" - -#include "ash/shelf/shelf.h" - -namespace ash { -namespace test { - -ShelfTestAPI::ShelfTestAPI(Shelf* shelf) : shelf_(shelf) {} - -ShelfTestAPI::~ShelfTestAPI() {} - -ShelfView* ShelfTestAPI::shelf_view() { return shelf_->shelf_view_; } - -void ShelfTestAPI::SetShelfDelegate(ShelfDelegate* delegate) { - shelf_->delegate_ = delegate; -} - -} // namespace test -} // namespace ash
diff --git a/ash/test/shelf_test_api.h b/ash/test/shelf_test_api.h index 94e86fb5..78d099e 100644 --- a/ash/test/shelf_test_api.h +++ b/ash/test/shelf_test_api.h
@@ -5,28 +5,25 @@ #ifndef ASH_TEST_SHELF_TEST_API_H_ #define ASH_TEST_SHELF_TEST_API_H_ +#include "ash/shelf/shelf.h" #include "base/macros.h" namespace ash { - -class Shelf; -class ShelfDelegate; -class ShelfView; - namespace test { // Use the api in this class to access private members of Shelf. class ShelfTestAPI { public: - explicit ShelfTestAPI(Shelf* shelf); + explicit ShelfTestAPI(Shelf* shelf) : shelf_(shelf) {} + ~ShelfTestAPI() {} - ~ShelfTestAPI(); + ShelfView* shelf_view() { return shelf_->shelf_view_; } - // An accessor for |shelf_view|. - ShelfView* shelf_view(); + ShelfLockingManager* shelf_locking_manager() { + return &shelf_->shelf_locking_manager_; + } - // Set ShelfDelegate. - void SetShelfDelegate(ShelfDelegate* delegate); + void set_delegate(ShelfDelegate* delegate) { shelf_->delegate_ = delegate; } private: Shelf* shelf_;
diff --git a/ash/wm/panels/attached_panel_window_targeter.cc b/ash/wm/panels/attached_panel_window_targeter.cc index 23b0141f..cb3c67ff 100644 --- a/ash/wm/panels/attached_panel_window_targeter.cc +++ b/ash/wm/panels/attached_panel_window_targeter.cc
@@ -49,21 +49,11 @@ return; DCHECK(panel_layout_manager_->shelf()); - gfx::Insets touch(default_touch_extend_); - switch (panel_layout_manager_->shelf()->alignment()) { - case SHELF_ALIGNMENT_BOTTOM: - touch = gfx::Insets(touch.top(), touch.left(), 0, touch.right()); - break; - case SHELF_ALIGNMENT_LEFT: - touch = gfx::Insets(touch.top(), 0, touch.bottom(), touch.right()); - break; - case SHELF_ALIGNMENT_RIGHT: - touch = gfx::Insets(touch.top(), touch.left(), touch.bottom(), 0); - break; - } - - set_touch_extend(touch); + set_touch_extend(panel_layout_manager_->shelf()->SelectValueForShelfAlignment( + gfx::Insets(touch.top(), touch.left(), 0, touch.right()), + gfx::Insets(touch.top(), 0, touch.bottom(), touch.right()), + gfx::Insets(touch.top(), touch.left(), touch.bottom(), 0))); } } // namespace ash
diff --git a/ash/wm/panels/panel_layout_manager.cc b/ash/wm/panels/panel_layout_manager.cc index fa2af7a5..3fb4738b 100644 --- a/ash/wm/panels/panel_layout_manager.cc +++ b/ash/wm/panels/panel_layout_manager.cc
@@ -70,6 +70,7 @@ SkPath path; switch (alignment_) { case SHELF_ALIGNMENT_BOTTOM: + case SHELF_ALIGNMENT_BOTTOM_LOCKED: path.moveTo(SkIntToScalar(0), SkIntToScalar(0)); path.lineTo(SkIntToScalar(kArrowWidth / 2), SkIntToScalar(kArrowHeight)); @@ -94,13 +95,9 @@ canvas->DrawPath(path, paint); } - ShelfAlignment alignment() { - return alignment_; - } + ShelfAlignment alignment() { return alignment_; } - void set_alignment(ShelfAlignment alignment) { - alignment_ = alignment; - } + void set_alignment(ShelfAlignment alignment) { alignment_ = alignment; } private: ShelfAlignment alignment_; @@ -179,17 +176,12 @@ gfx::Vector2d GetSlideInAnimationOffset(ShelfAlignment alignment) { gfx::Vector2d offset; - switch (alignment) { - case SHELF_ALIGNMENT_BOTTOM: - offset.set_y(kPanelSlideInOffset); - break; - case SHELF_ALIGNMENT_LEFT: - offset.set_x(-kPanelSlideInOffset); - break; - case SHELF_ALIGNMENT_RIGHT: - offset.set_x(kPanelSlideInOffset); - break; - } + if (alignment == SHELF_ALIGNMENT_LEFT) + offset.set_x(-kPanelSlideInOffset); + else if (alignment == SHELF_ALIGNMENT_RIGHT) + offset.set_x(kPanelSlideInOffset); + else + offset.set_y(kPanelSlideInOffset); return offset; } @@ -204,7 +196,7 @@ void SetAlignment(ShelfAlignment alignment) { gfx::Rect callout_bounds = GetWindowBoundsInScreen(); - if (alignment == SHELF_ALIGNMENT_BOTTOM) { + if (IsHorizontalAlignment(alignment)) { callout_bounds.set_width(kArrowWidth); callout_bounds.set_height(kArrowHeight); } else { @@ -704,17 +696,12 @@ continue; bool slide_in = visible_panels[i].slide_in; gfx::Rect bounds = visible_panels[i].window->GetTargetBounds(); - switch (alignment) { - case SHELF_ALIGNMENT_BOTTOM: - bounds.set_y(shelf_bounds.y() - bounds.height()); - break; - case SHELF_ALIGNMENT_LEFT: - bounds.set_x(shelf_bounds.right()); - break; - case SHELF_ALIGNMENT_RIGHT: - bounds.set_x(shelf_bounds.x() - bounds.width()); - break; - } + if (alignment == SHELF_ALIGNMENT_LEFT) + bounds.set_x(shelf_bounds.right()); + else if (alignment == SHELF_ALIGNMENT_RIGHT) + bounds.set_x(shelf_bounds.x() - bounds.width()); + else + bounds.set_y(shelf_bounds.y() - bounds.height()); bool on_shelf = visible_panels[i].window->GetTargetBounds() == bounds; if (horizontal) { @@ -847,17 +834,12 @@ current_bounds.y() - callout_bounds.y(), callout_bounds.bottom() - current_bounds.bottom()); } - switch (shelf_->alignment()) { - case SHELF_ALIGNMENT_BOTTOM: - callout_bounds.set_y(bounds.bottom()); - break; - case SHELF_ALIGNMENT_LEFT: - callout_bounds.set_x(bounds.x() - callout_bounds.width()); - break; - case SHELF_ALIGNMENT_RIGHT: - callout_bounds.set_x(bounds.right()); - break; - } + if (shelf_->alignment() == SHELF_ALIGNMENT_LEFT) + callout_bounds.set_x(bounds.x() - callout_bounds.width()); + else if (shelf_->alignment() == SHELF_ALIGNMENT_RIGHT) + callout_bounds.set_x(bounds.right()); + else + callout_bounds.set_y(bounds.bottom()); callout_bounds = ScreenUtil::ConvertRectFromScreen( callout_widget->GetNativeWindow()->parent(), callout_bounds);
diff --git a/ash/wm/panels/panel_layout_manager_unittest.cc b/ash/wm/panels/panel_layout_manager_unittest.cc index 66b2ff9..1e742b6 100644 --- a/ash/wm/panels/panel_layout_manager_unittest.cc +++ b/ash/wm/panels/panel_layout_manager_unittest.cc
@@ -141,17 +141,12 @@ EXPECT_GE(window_bounds.bottom(), icon_bounds.bottom()); } - switch (alignment) { - case SHELF_ALIGNMENT_BOTTOM: - EXPECT_EQ(shelf_bounds.y(), window_bounds.bottom()); - break; - case SHELF_ALIGNMENT_LEFT: - EXPECT_EQ(shelf_bounds.right(), window_bounds.x()); - break; - case SHELF_ALIGNMENT_RIGHT: - EXPECT_EQ(shelf_bounds.x(), window_bounds.right()); - break; - } + if (alignment == SHELF_ALIGNMENT_LEFT) + EXPECT_EQ(shelf_bounds.right(), window_bounds.x()); + else if (alignment == SHELF_ALIGNMENT_RIGHT) + EXPECT_EQ(shelf_bounds.x(), window_bounds.right()); + else + EXPECT_EQ(shelf_bounds.y(), window_bounds.bottom()); } void IsCalloutAboveLauncherIcon(aura::Window* panel) { @@ -170,17 +165,12 @@ EXPECT_TRUE(widget->IsVisible()); ShelfAlignment alignment = GetAlignment(panel->GetRootWindow()); - switch (alignment) { - case SHELF_ALIGNMENT_BOTTOM: - EXPECT_EQ(panel_bounds.bottom(), callout_bounds.y()); - break; - case SHELF_ALIGNMENT_LEFT: - EXPECT_EQ(panel_bounds.x(), callout_bounds.right()); - break; - case SHELF_ALIGNMENT_RIGHT: - EXPECT_EQ(panel_bounds.right(), callout_bounds.x()); - break; - } + if (alignment == SHELF_ALIGNMENT_LEFT) + EXPECT_EQ(panel_bounds.x(), callout_bounds.right()); + else if (alignment == SHELF_ALIGNMENT_RIGHT) + EXPECT_EQ(panel_bounds.right(), callout_bounds.x()); + else + EXPECT_EQ(panel_bounds.bottom(), callout_bounds.y()); if (IsHorizontal(alignment)) { EXPECT_NEAR(icon_bounds.CenterPoint().x(), @@ -220,13 +210,11 @@ } void SetAlignment(aura::Window* root_window, ShelfAlignment alignment) { - ash::Shell* shell = ash::Shell::GetInstance(); - shell->SetShelfAlignment(alignment, root_window); + Shelf::ForWindow(root_window)->SetAlignment(alignment); } ShelfAlignment GetAlignment(const aura::Window* root_window) { - ash::Shell* shell = ash::Shell::GetInstance(); - return shell->GetShelfAlignment(root_window); + return Shelf::ForWindow(root_window)->alignment(); } void SetShelfAutoHideBehavior(aura::Window* window,
diff --git a/ash/wm/panels/panel_window_resizer.cc b/ash/wm/panels/panel_window_resizer.cc index 501503a..b5c44bc 100644 --- a/ash/wm/panels/panel_window_resizer.cc +++ b/ash/wm/panels/panel_window_resizer.cc
@@ -140,6 +140,7 @@ shelf_widget()->GetWindowBoundsInScreen()); switch (panel_layout_manager->shelf()->alignment()) { case SHELF_ALIGNMENT_BOTTOM: + case SHELF_ALIGNMENT_BOTTOM_LOCKED: if (bounds.bottom() >= (launcher_bounds.y() - kPanelSnapToLauncherDistance)) { should_attach = true;
diff --git a/ash/wm/window_animations.cc b/ash/wm/window_animations.cc index a71c7c2..58417ec 100644 --- a/ash/wm/window_animations.cc +++ b/ash/wm/window_animations.cc
@@ -468,17 +468,12 @@ if (item_rect.width() != 0 || item_rect.height() != 0) { if (shelf->shelf_layout_manager()->visibility_state() == SHELF_AUTO_HIDE) { gfx::Rect shelf_bounds = shelf->shelf_widget()->GetWindowBoundsInScreen(); - switch (shelf->alignment()) { - case SHELF_ALIGNMENT_BOTTOM: - item_rect.set_y(shelf_bounds.y()); - break; - case SHELF_ALIGNMENT_LEFT: - item_rect.set_x(shelf_bounds.right()); - break; - case SHELF_ALIGNMENT_RIGHT: - item_rect.set_x(shelf_bounds.x()); - break; - } + if (shelf->alignment() == SHELF_ALIGNMENT_LEFT) + item_rect.set_x(shelf_bounds.right()); + else if (shelf->alignment() == SHELF_ALIGNMENT_RIGHT) + item_rect.set_x(shelf_bounds.x()); + else + item_rect.set_y(shelf_bounds.y()); return item_rect; } }
diff --git a/base/BUILD.gn b/base/BUILD.gn index 8bec3f9..9d53e79 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -2241,6 +2241,7 @@ "test/android/javatests/src/org/chromium/base/test/util/DisabledTest.java", "test/android/javatests/src/org/chromium/base/test/util/EnormousTest.java", "test/android/javatests/src/org/chromium/base/test/util/Feature.java", + "test/android/javatests/src/org/chromium/base/test/util/FlakyTest.java", "test/android/javatests/src/org/chromium/base/test/util/InMemorySharedPreferences.java", "test/android/javatests/src/org/chromium/base/test/util/InstrumentationUtils.java", "test/android/javatests/src/org/chromium/base/test/util/IntegrationTest.java",
diff --git a/base/android/java/src/org/chromium/base/OWNERS b/base/android/java/src/org/chromium/base/OWNERS deleted file mode 100644 index d99aec1..0000000 --- a/base/android/java/src/org/chromium/base/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -per-file ApiCompatibilityUtils.java=aurimas@chromium.org -per-file ApiCompatibilityUtils.java=newt@chromium.org
diff --git a/base/files/file_util.h b/base/files/file_util.h index 8f7d53c..8fd9fff 100644 --- a/base/files/file_util.h +++ b/base/files/file_util.h
@@ -288,6 +288,10 @@ // be resolved with this function. BASE_EXPORT bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path); + +// Given an existing file in |path|, returns whether this file is on a network +// drive or not. If |path| does not exist, this function returns false. +BASE_EXPORT bool IsOnNetworkDrive(const base::FilePath& path); #endif // This function will return if the given file is a symlink or not.
diff --git a/base/files/file_util_unittest.cc b/base/files/file_util_unittest.cc index a0d0a289..ac3a654 100644 --- a/base/files/file_util_unittest.cc +++ b/base/files/file_util_unittest.cc
@@ -33,6 +33,7 @@ #include <shlobj.h> #include <tchar.h> #include <winioctl.h> +#include "base/environment.h" #include "base/win/scoped_handle.h" #include "base/win/windows_version.h" #endif @@ -1664,6 +1665,63 @@ ::_tputenv_s(kTmpKey, _T("")); } } + +TEST_F(FileUtilTest, IsOnNetworkDrive) { + struct LocalTestData { + const FilePath::CharType* input; + bool expected; + }; + + const LocalTestData local_cases[] = { + { FPL(""), false }, + { FPL("c:\\"), false }, + { FPL("c:"), false }, + { FPL("c:\\windows\\notepad.exe"), false } + }; + + for (const auto& test_case : local_cases) { + FilePath input(test_case.input); + bool observed = IsOnNetworkDrive(input); + EXPECT_EQ(test_case.expected, observed) << " input: " << input.value(); + } + + Environment* env = Environment::Create(); + ASSERT_TRUE(!!env); + + // To test IsOnNetworkDrive() for remote cases, set up a file server + // and place a file called file.txt on the server e.g. + // \\DC01\TESTSHARE\file.txt + // then set the two environment variables: + // set BASE_TEST_FILE_SERVER=DC01 + // set BASE_TEST_FILE_SHARE=TESTSHARE + if (!env->HasVar("BASE_TEST_FILE_SERVER") || + !env->HasVar("BASE_TEST_FILE_SHARE")) { + return; + } + + struct NetworkTestData { + const wchar_t* input; + bool expected; + }; + + const NetworkTestData network_cases[] = { + { L"\\\\%BASE_TEST_FILE_SERVER%", false }, + { L"\\\\%BASE_TEST_FILE_SERVER%\\", false }, + { L"\\\\%BASE_TEST_FILE_SERVER%\\file.txt", false }, + { L"\\\\%BASE_TEST_FILE_SERVER%\\%BASE_TEST_FILE_SHARE%", true }, + { L"\\\\%BASE_TEST_FILE_SERVER%\\%BASE_TEST_FILE_SHARE%\\", true }, + { L"\\\\%BASE_TEST_FILE_SERVER%\\%BASE_TEST_FILE_SHARE%\\file.txt", true }, + { L"\\\\%BASE_TEST_FILE_SERVER%\\%BASE_TEST_FILE_SHARE%\\no.txt", false } + }; + + for (const auto& test_case : network_cases) { + wchar_t path[MAX_PATH] = {0}; + ::ExpandEnvironmentStringsW(test_case.input, path, arraysize(path)); + FilePath input(path); + EXPECT_EQ(test_case.expected, IsOnNetworkDrive(input)) << " input : " + << input.value(); + } +} #endif // OS_WIN TEST_F(FileUtilTest, CreateTemporaryFileTest) {
diff --git a/base/files/file_util_win.cc b/base/files/file_util_win.cc index d70454df..ddb9c28 100644 --- a/base/files/file_util_win.cc +++ b/base/files/file_util_win.cc
@@ -559,6 +559,26 @@ return success; } +bool IsOnNetworkDrive(const base::FilePath& path) { + win::ScopedHandle handle( + ::CreateFileW(path.value().c_str(), + GENERIC_READ, + kFileShareAll, + NULL, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, // Needed to open directory. + NULL)); + + if (!handle.IsValid()) + return false; + + // If able to get network information, then the file is on a network. + FILE_REMOTE_PROTOCOL_INFO remote_proto_info = {0}; + return !!::GetFileInformationByHandleEx(handle.Get(), FileRemoteProtocolInfo, + &remote_proto_info, + sizeof(remote_proto_info)); +} + // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle // them if we do decide to. bool IsLink(const FilePath& file_path) {
diff --git a/base/logging.h b/base/logging.h index 07674698..bbbfce14 100644 --- a/base/logging.h +++ b/base/logging.h
@@ -572,7 +572,7 @@ #define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2) #define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2) -#if defined(NDEBUG) +#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON) #define ENABLE_DLOG 0 #else #define ENABLE_DLOG 1
diff --git a/base/logging_unittest.cc b/base/logging_unittest.cc index 22fb855..531af1a3 100644 --- a/base/logging_unittest.cc +++ b/base/logging_unittest.cc
@@ -191,7 +191,7 @@ #endif TEST_F(LoggingTest, DebugLoggingReleaseBehavior) { -#if !defined(NDEBUG) +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) int debug_only_variable = 1; #endif // These should avoid emitting references to |debug_only_variable| @@ -226,7 +226,7 @@ // Release build with real DCHECKS. SetLogAssertHandler(&LogSink); EXPECT_TRUE(DCHECK_IS_ON()); - EXPECT_FALSE(DLOG_IS_ON(DCHECK)); + EXPECT_TRUE(DLOG_IS_ON(DCHECK)); #else // Debug build. SetLogAssertHandler(&LogSink);
diff --git a/base/memory/shared_memory.h b/base/memory/shared_memory.h index 13238aa..b7e5a05 100644 --- a/base/memory/shared_memory.h +++ b/base/memory/shared_memory.h
@@ -32,10 +32,7 @@ struct BASE_EXPORT SharedMemoryCreateOptions { SharedMemoryCreateOptions(); -#if defined(OS_MACOSX) && !defined(OS_IOS) - // The type of OS primitive that should back the SharedMemory object. - SharedMemoryHandle::Type type; -#else +#if !(defined(OS_MACOSX) && !defined(OS_IOS)) // DEPRECATED (crbug.com/345734): // If NULL, the object is anonymous. This pointer is owned by the caller // and must live through the call to Create(). @@ -47,7 +44,7 @@ // shared memory must not exist. This flag is meaningless unless // name_deprecated is non-NULL. bool open_existing_deprecated; -#endif // defined(OS_MACOSX) && !defined(OS_IOS) +#endif // !(defined(OS_MACOSX) && !defined(OS_IOS)) // Size of the shared memory object to be created. // When opening an existing object, this has no effect. @@ -102,7 +99,7 @@ // The caller is responsible for destroying the duplicated OS primitive. static SharedMemoryHandle DuplicateHandle(const SharedMemoryHandle& handle); -#if defined(OS_POSIX) +#if defined(OS_POSIX) && !(defined(OS_MACOSX) && !defined(OS_IOS)) // This method requires that the SharedMemoryHandle is backed by a POSIX fd. static int GetFdFromSharedMemoryHandle(const SharedMemoryHandle& handle); #endif @@ -123,16 +120,6 @@ // Returns true on success and false on failure. bool CreateAndMapAnonymous(size_t size); -#if defined(OS_MACOSX) && !defined(OS_IOS) - // These two methods are analogs of CreateAndMapAnonymous and CreateAnonymous - // that force the underlying OS primitive to be a POSIX fd. Do not add new - // uses of these methods unless absolutely necessary, since constructing a - // fd-backed SharedMemory object frequently takes 100ms+. - // http://crbug.com/466437. - bool CreateAndMapAnonymousPosix(size_t size); - bool CreateAnonymousPosix(size_t size); -#endif // defined(OS_MACOSX) && !defined(OS_IOS) - // Creates an anonymous shared memory segment of size size. // Returns true on success and false on failure. bool CreateAnonymous(size_t size) { @@ -257,12 +244,11 @@ } private: -#if defined(OS_POSIX) && !defined(OS_NACL) && !defined(OS_ANDROID) +#if defined(OS_POSIX) && !defined(OS_NACL) && !defined(OS_ANDROID) && \ + !(defined(OS_MACOSX) && !defined(OS_IOS)) bool PrepareMapFile(ScopedFILE fp, ScopedFD readonly); -#if !(defined(OS_MACOSX) && !defined(OS_IOS)) bool FilePathForMemoryName(const std::string& mem_name, FilePath* path); #endif -#endif // defined(OS_POSIX) && !defined(OS_NACL) && !defined(OS_ANDROID) enum ShareMode { SHARE_READONLY, SHARE_CURRENT_MODE, @@ -282,10 +268,6 @@ // The OS primitive that backs the shared memory region. SharedMemoryHandle shm_; - // The mechanism by which the memory is mapped. Only valid if |memory_| is not - // |nullptr|. - SharedMemoryHandle::Type mapped_memory_mechanism_; - int readonly_mapped_file_; #elif defined(OS_POSIX) int mapped_file_;
diff --git a/base/memory/shared_memory_handle.h b/base/memory/shared_memory_handle.h index 5befcdd6..8eff26b 100644 --- a/base/memory/shared_memory_handle.h +++ b/base/memory/shared_memory_handle.h
@@ -14,9 +14,7 @@ #include "base/process/process_handle.h" #elif defined(OS_MACOSX) && !defined(OS_IOS) #include <mach/mach.h> -#include <sys/types.h> #include "base/base_export.h" -#include "base/file_descriptor_posix.h" #include "base/macros.h" #include "base/process/process_handle.h" #elif defined(OS_POSIX) @@ -87,32 +85,9 @@ #else class BASE_EXPORT SharedMemoryHandle { public: - // The values of these enums must not change, as they are used by the - // histogram OSX.SharedMemory.Mechanism. - enum Type { - // The SharedMemoryHandle is backed by a POSIX fd. - POSIX, - // The SharedMemoryHandle is backed by the Mach primitive "memory object". - MACH, - }; - static const int TypeMax = 2; - - // The format that should be used to transmit |Type| over the wire. - typedef int TypeWireFormat; - // The default constructor returns an invalid SharedMemoryHandle. SharedMemoryHandle(); - // Constructs a SharedMemoryHandle backed by the components of a - // FileDescriptor. The newly created instance has the same ownership semantics - // as base::FileDescriptor. This typically means that the SharedMemoryHandle - // takes ownership of the |fd| if |auto_close| is true. Unfortunately, it's - // common for existing code to make shallow copies of SharedMemoryHandle, and - // the one that is finally passed into a base::SharedMemory is the one that - // "consumes" the fd. - explicit SharedMemoryHandle(const base::FileDescriptor& file_descriptor); - SharedMemoryHandle(int fd, bool auto_close); - // Makes a Mach-based SharedMemoryHandle of the given size. On error, // subsequent calls to IsValid() return false. explicit SharedMemoryHandle(mach_vm_size_t size); @@ -138,28 +113,16 @@ bool operator==(const SharedMemoryHandle& handle) const; bool operator!=(const SharedMemoryHandle& handle) const; - // Returns the type. - Type GetType() const; - // Whether the underlying OS primitive is valid. Once the SharedMemoryHandle // is backed by a valid OS primitive, it becomes immutable. bool IsValid() const; - // Sets the POSIX fd backing the SharedMemoryHandle. Requires that the - // SharedMemoryHandle be backed by a POSIX fd. - void SetFileHandle(int fd, bool auto_close); - - // This method assumes that the SharedMemoryHandle is backed by a POSIX fd. - // This is eventually no longer going to be true, so please avoid adding new - // uses of this method. - const FileDescriptor GetFileDescriptor() const; - // Exposed so that the SharedMemoryHandle can be transported between // processes. mach_port_t GetMemoryObject() const; // Returns false on a failure to determine the size. On success, populates the - // output variable |size|. + // output variable |size|. Returns 0 if the handle is invalid. bool GetSize(size_t* size) const; // The SharedMemoryHandle must be valid. @@ -178,31 +141,21 @@ // Shared code between copy constructor and operator=. void CopyRelevantData(const SharedMemoryHandle& handle); - Type type_; + mach_port_t memory_object_ = MACH_PORT_NULL; - // Each instance of a SharedMemoryHandle is backed either by a POSIX fd or a - // mach port. |type_| determines the backing member. - union { - FileDescriptor file_descriptor_; + // The size of the shared memory region when |type_| is MACH. Only + // relevant if |memory_object_| is not |MACH_PORT_NULL|. + mach_vm_size_t size_ = 0; - struct { - mach_port_t memory_object_; + // The pid of the process in which |memory_object_| is usable. Only + // relevant if |memory_object_| is not |MACH_PORT_NULL|. + base::ProcessId pid_ = 0; - // The size of the shared memory region when |type_| is MACH. Only - // relevant if |memory_object_| is not |MACH_PORT_NULL|. - mach_vm_size_t size_; - - // The pid of the process in which |memory_object_| is usable. Only - // relevant if |memory_object_| is not |MACH_PORT_NULL|. - base::ProcessId pid_; - - // Whether passing this object as a parameter to an IPC message passes - // ownership of |memory_object_| to the IPC stack. This is meant to mimic - // the behavior of the |auto_close| parameter of FileDescriptor. - // Defaults to |false|. - bool ownership_passes_to_ipc_; - }; - }; + // Whether passing this object as a parameter to an IPC message passes + // ownership of |memory_object_| to the IPC stack. This is meant to mimic + // the behavior of the |auto_close| parameter of FileDescriptor. + // Defaults to |false|. + bool ownership_passes_to_ipc_ = false; }; #endif
diff --git a/base/memory/shared_memory_handle_mac.cc b/base/memory/shared_memory_handle_mac.cc index 600d2bb..ad470bea 100644 --- a/base/memory/shared_memory_handle_mac.cc +++ b/base/memory/shared_memory_handle_mac.cc
@@ -14,22 +14,9 @@ namespace base { -static_assert(sizeof(SharedMemoryHandle::Type) <= - sizeof(SharedMemoryHandle::TypeWireFormat), - "Size of enum SharedMemoryHandle::Type exceeds size of type " - "transmitted over wire."); - -SharedMemoryHandle::SharedMemoryHandle() : type_(POSIX), file_descriptor_() {} - -SharedMemoryHandle::SharedMemoryHandle( - const base::FileDescriptor& file_descriptor) - : type_(POSIX), file_descriptor_(file_descriptor) {} - -SharedMemoryHandle::SharedMemoryHandle(int fd, bool auto_close) - : type_(POSIX), file_descriptor_(fd, auto_close) {} +SharedMemoryHandle::SharedMemoryHandle() {} SharedMemoryHandle::SharedMemoryHandle(mach_vm_size_t size) { - type_ = MACH; mach_port_t named_right; kern_return_t kr = mach_make_memory_entry_64( mach_task_self(), @@ -52,14 +39,12 @@ SharedMemoryHandle::SharedMemoryHandle(mach_port_t memory_object, mach_vm_size_t size, base::ProcessId pid) - : type_(MACH), - memory_object_(memory_object), + : memory_object_(memory_object), size_(size), pid_(pid), ownership_passes_to_ipc_(false) {} -SharedMemoryHandle::SharedMemoryHandle(const SharedMemoryHandle& handle) - : type_(handle.type_) { +SharedMemoryHandle::SharedMemoryHandle(const SharedMemoryHandle& handle) { CopyRelevantData(handle); } @@ -68,104 +53,51 @@ if (this == &handle) return *this; - type_ = handle.type_; CopyRelevantData(handle); return *this; } SharedMemoryHandle SharedMemoryHandle::Duplicate() const { - switch (type_) { - case POSIX: { - if (!IsValid()) - return SharedMemoryHandle(); + if (!IsValid()) + return SharedMemoryHandle(MACH_PORT_NULL, 0, 0); - int duped_fd = HANDLE_EINTR(dup(file_descriptor_.fd)); - if (duped_fd < 0) - return SharedMemoryHandle(); - return SharedMemoryHandle(duped_fd, true); - } - case MACH: { - if (!IsValid()) - return SharedMemoryHandle(MACH_PORT_NULL, 0, 0); - - // Increment the ref count. - kern_return_t kr = mach_port_mod_refs(mach_task_self(), memory_object_, - MACH_PORT_RIGHT_SEND, 1); - DCHECK_EQ(kr, KERN_SUCCESS); - SharedMemoryHandle handle(*this); - handle.SetOwnershipPassesToIPC(true); - return handle; - } - } + // Increment the ref count. + kern_return_t kr = mach_port_mod_refs(mach_task_self(), memory_object_, + MACH_PORT_RIGHT_SEND, 1); + DCHECK_EQ(kr, KERN_SUCCESS); + SharedMemoryHandle handle(*this); + handle.SetOwnershipPassesToIPC(true); + return handle; } bool SharedMemoryHandle::operator==(const SharedMemoryHandle& handle) const { if (!IsValid() && !handle.IsValid()) return true; - if (type_ != handle.type_) - return false; - - switch (type_) { - case POSIX: - return file_descriptor_ == handle.file_descriptor_; - case MACH: - return memory_object_ == handle.memory_object_ && size_ == handle.size_ && - pid_ == handle.pid_; - } + return memory_object_ == handle.memory_object_ && size_ == handle.size_ && + pid_ == handle.pid_; } bool SharedMemoryHandle::operator!=(const SharedMemoryHandle& handle) const { return !(*this == handle); } -SharedMemoryHandle::Type SharedMemoryHandle::GetType() const { - return type_; -} - bool SharedMemoryHandle::IsValid() const { - switch (type_) { - case POSIX: - return file_descriptor_.fd >= 0; - case MACH: - return memory_object_ != MACH_PORT_NULL; - } -} - -void SharedMemoryHandle::SetFileHandle(int fd, bool auto_close) { - DCHECK(!IsValid()); - file_descriptor_.fd = fd; - file_descriptor_.auto_close = auto_close; - type_ = POSIX; -} - -const FileDescriptor SharedMemoryHandle::GetFileDescriptor() const { - DCHECK_EQ(type_, POSIX); - return file_descriptor_; + return memory_object_ != MACH_PORT_NULL; } mach_port_t SharedMemoryHandle::GetMemoryObject() const { - DCHECK_EQ(type_, MACH); return memory_object_; } bool SharedMemoryHandle::GetSize(size_t* size) const { - if (!IsValid()) - return false; - - switch (type_) { - case SharedMemoryHandle::POSIX: - struct stat st; - if (fstat(file_descriptor_.fd, &st) != 0) - return false; - if (st.st_size < 0) - return false; - *size = st.st_size; - return true; - case SharedMemoryHandle::MACH: - *size = size_; - return true; + if (!IsValid()) { + *size = 0; + return true; } + + *size = size_; + return true; } bool SharedMemoryHandle::MapAt(off_t offset, @@ -173,72 +105,42 @@ void** memory, bool read_only) { DCHECK(IsValid()); - switch (type_) { - case SharedMemoryHandle::POSIX: - *memory = mmap(nullptr, bytes, PROT_READ | (read_only ? 0 : PROT_WRITE), - MAP_SHARED, file_descriptor_.fd, offset); - - return *memory && *memory != reinterpret_cast<void*>(-1); - case SharedMemoryHandle::MACH: - // The flag VM_PROT_IS_MASK is only supported on OSX 10.7+. - DCHECK(mac::IsOSLionOrLater()); - - DCHECK_EQ(pid_, GetCurrentProcId()); - kern_return_t kr = mach_vm_map( - mach_task_self(), - reinterpret_cast<mach_vm_address_t*>(memory), // Output parameter - bytes, - 0, // Alignment mask - VM_FLAGS_ANYWHERE, - memory_object_, - offset, - FALSE, // Copy - VM_PROT_READ | (read_only ? 0 : VM_PROT_WRITE), // Current protection - VM_PROT_WRITE | VM_PROT_READ | VM_PROT_IS_MASK, // Maximum protection - VM_INHERIT_NONE); - return kr == KERN_SUCCESS; - } + DCHECK_EQ(pid_, GetCurrentProcId()); + kern_return_t kr = mach_vm_map( + mach_task_self(), + reinterpret_cast<mach_vm_address_t*>(memory), // Output parameter + bytes, + 0, // Alignment mask + VM_FLAGS_ANYWHERE, memory_object_, offset, + FALSE, // Copy + VM_PROT_READ | (read_only ? 0 : VM_PROT_WRITE), // Current protection + VM_PROT_WRITE | VM_PROT_READ | VM_PROT_IS_MASK, // Maximum protection + VM_INHERIT_NONE); + return kr == KERN_SUCCESS; } void SharedMemoryHandle::Close() const { if (!IsValid()) return; - switch (type_) { - case POSIX: - if (IGNORE_EINTR(close(file_descriptor_.fd)) < 0) - DPLOG(ERROR) << "Error closing fd."; - break; - case MACH: - kern_return_t kr = mach_port_deallocate(mach_task_self(), memory_object_); - if (kr != KERN_SUCCESS) - DPLOG(ERROR) << "Error deallocating mach port: " << kr; - break; - } + kern_return_t kr = mach_port_deallocate(mach_task_self(), memory_object_); + if (kr != KERN_SUCCESS) + DPLOG(ERROR) << "Error deallocating mach port: " << kr; } void SharedMemoryHandle::SetOwnershipPassesToIPC(bool ownership_passes) { - DCHECK_EQ(type_, MACH); ownership_passes_to_ipc_ = ownership_passes; } bool SharedMemoryHandle::OwnershipPassesToIPC() const { - DCHECK_EQ(type_, MACH); return ownership_passes_to_ipc_; } void SharedMemoryHandle::CopyRelevantData(const SharedMemoryHandle& handle) { - switch (type_) { - case POSIX: - file_descriptor_ = handle.file_descriptor_; - break; - case MACH: - memory_object_ = handle.memory_object_; - size_ = handle.size_; - pid_ = handle.pid_; - ownership_passes_to_ipc_ = handle.ownership_passes_to_ipc_; - break; - } + memory_object_ = handle.memory_object_; + size_ = handle.size_; + pid_ = handle.pid_; + ownership_passes_to_ipc_ = handle.ownership_passes_to_ipc_; } } // namespace base
diff --git a/base/memory/shared_memory_mac.cc b/base/memory/shared_memory_mac.cc index 6dd95762..c9882fd0 100644 --- a/base/memory/shared_memory_mac.cc +++ b/base/memory/shared_memory_mac.cc
@@ -4,33 +4,22 @@ #include "base/memory/shared_memory.h" -#include <errno.h> -#include <fcntl.h> #include <mach/mach_vm.h> -#include <stddef.h> -#include <sys/mman.h> -#include <sys/stat.h> -#include <unistd.h> #include "base/files/file_util.h" #include "base/files/scoped_file.h" #include "base/logging.h" +#include "base/mac/foundation_util.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_mach_vm.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram_macros.h" -#include "base/posix/eintr_wrapper.h" -#include "base/posix/safe_strerror.h" #include "base/process/process_metrics.h" #include "base/profiler/scoped_tracker.h" #include "base/scoped_generic.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" -#if defined(OS_MACOSX) -#include "base/mac/foundation_util.h" -#endif // OS_MACOSX - namespace base { namespace { @@ -78,81 +67,15 @@ return true; } -struct ScopedPathUnlinkerTraits { - static FilePath* InvalidValue() { return nullptr; } - - static void Free(FilePath* path) { - // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437 - // is fixed. - tracked_objects::ScopedTracker tracking_profile( - FROM_HERE_WITH_EXPLICIT_FUNCTION( - "466437 SharedMemory::Create::Unlink")); - if (unlink(path->value().c_str())) - PLOG(WARNING) << "unlink"; - } -}; - -// Unlinks the FilePath when the object is destroyed. -typedef ScopedGeneric<FilePath*, ScopedPathUnlinkerTraits> ScopedPathUnlinker; - -// Makes a temporary file, fdopens it, and then unlinks it. |fp| is populated -// with the fdopened FILE. |readonly_fd| is populated with the opened fd if -// options.share_read_only is true. |path| is populated with the location of -// the file before it was unlinked. -// Returns false if there's an unhandled failure. -bool CreateAnonymousSharedMemory(const SharedMemoryCreateOptions& options, - ScopedFILE* fp, - ScopedFD* readonly_fd, - FilePath* path) { - // Q: Why not use the shm_open() etc. APIs? - // A: Because they're limited to 4mb on OS X. FFFFFFFUUUUUUUUUUU - FilePath directory; - ScopedPathUnlinker path_unlinker; - if (GetShmemTempDir(options.executable, &directory)) { - // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437 - // is fixed. - tracked_objects::ScopedTracker tracking_profile( - FROM_HERE_WITH_EXPLICIT_FUNCTION( - "466437 SharedMemory::Create::OpenTemporaryFile")); - fp->reset(CreateAndOpenTemporaryFileInDir(directory, path)); - - // Deleting the file prevents anyone else from mapping it in (making it - // private), and prevents the need for cleanup (once the last fd is - // closed, it is truly freed). - if (*fp) - path_unlinker.reset(path); - } - - if (*fp) { - if (options.share_read_only) { - // TODO(erikchen): Remove ScopedTracker below once - // http://crbug.com/466437 is fixed. - tracked_objects::ScopedTracker tracking_profile( - FROM_HERE_WITH_EXPLICIT_FUNCTION( - "466437 SharedMemory::Create::OpenReadonly")); - // Also open as readonly so that we can ShareReadOnlyToProcess. - readonly_fd->reset(HANDLE_EINTR(open(path->value().c_str(), O_RDONLY))); - if (!readonly_fd->is_valid()) { - DPLOG(ERROR) << "open(\"" << path->value() << "\", O_RDONLY) failed"; - fp->reset(); - return false; - } - } - } - return true; -} - } // namespace SharedMemoryCreateOptions::SharedMemoryCreateOptions() - : type(SharedMemoryHandle::MACH), - size(0), + : size(0), executable(false), share_read_only(false) {} SharedMemory::SharedMemory() - : mapped_memory_mechanism_(SharedMemoryHandle::POSIX), - readonly_mapped_file_(-1), + : readonly_mapped_file_(-1), mapped_size_(0), memory_(NULL), read_only_(false), @@ -160,7 +83,6 @@ SharedMemory::SharedMemory(const SharedMemoryHandle& handle, bool read_only) : shm_(handle), - mapped_memory_mechanism_(SharedMemoryHandle::POSIX), readonly_mapped_file_(-1), mapped_size_(0), memory_(NULL), @@ -189,7 +111,8 @@ // static size_t SharedMemory::GetHandleLimit() { - return GetMaxFds(); + // This should be effectively unlimited on OS X. + return 10000; } // static @@ -198,27 +121,10 @@ return handle.Duplicate(); } -// static -int SharedMemory::GetFdFromSharedMemoryHandle( - const SharedMemoryHandle& handle) { - return handle.GetFileDescriptor().fd; -} - bool SharedMemory::CreateAndMapAnonymous(size_t size) { return CreateAnonymous(size) && Map(size); } -bool SharedMemory::CreateAndMapAnonymousPosix(size_t size) { - return CreateAnonymousPosix(size) && Map(size); -} - -bool SharedMemory::CreateAnonymousPosix(size_t size) { - SharedMemoryCreateOptions options; - options.type = SharedMemoryHandle::POSIX; - options.size = size; - return Create(options); -} - // static bool SharedMemory::GetSizeFromSharedMemoryHandle( const SharedMemoryHandle& handle, @@ -240,42 +146,9 @@ if (options.size > static_cast<size_t>(std::numeric_limits<int>::max())) return false; - if (options.type == SharedMemoryHandle::MACH) { - shm_ = SharedMemoryHandle(options.size); - requested_size_ = options.size; - return shm_.IsValid(); - } - - // This function theoretically can block on the disk. Both profiling of real - // users and local instrumentation shows that this is a real problem. - // https://code.google.com/p/chromium/issues/detail?id=466437 - base::ThreadRestrictions::ScopedAllowIO allow_io; - - ScopedFILE fp; - ScopedFD readonly_fd; - - FilePath path; - bool result = CreateAnonymousSharedMemory(options, &fp, &readonly_fd, &path); - if (!result) - return false; - - if (!fp) { - PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed"; - return false; - } - - // Get current size. - struct stat stat; - if (fstat(fileno(fp.get()), &stat) != 0) - return false; - const size_t current_size = stat.st_size; - if (current_size != options.size) { - if (HANDLE_EINTR(ftruncate(fileno(fp.get()), options.size)) != 0) - return false; - } + shm_ = SharedMemoryHandle(options.size); requested_size_ = options.size; - - return PrepareMapFile(std::move(fp), std::move(readonly_fd)); + return shm_.IsValid(); } bool SharedMemory::MapAt(off_t offset, size_t bytes) { @@ -291,7 +164,6 @@ mapped_size_ = bytes; DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_) & (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1)); - mapped_memory_mechanism_ = shm_.GetType(); } else { memory_ = NULL; } @@ -303,142 +175,49 @@ if (memory_ == NULL) return false; - switch (mapped_memory_mechanism_) { - case SharedMemoryHandle::POSIX: - munmap(memory_, mapped_size_); - break; - case SharedMemoryHandle::MACH: - mach_vm_deallocate(mach_task_self(), - reinterpret_cast<mach_vm_address_t>(memory_), - mapped_size_); - break; - } - + mach_vm_deallocate(mach_task_self(), + reinterpret_cast<mach_vm_address_t>(memory_), + mapped_size_); memory_ = NULL; mapped_size_ = 0; return true; } SharedMemoryHandle SharedMemory::handle() const { - switch (shm_.GetType()) { - case SharedMemoryHandle::POSIX: - return SharedMemoryHandle(shm_.GetFileDescriptor().fd, false); - case SharedMemoryHandle::MACH: - return shm_; - } + return shm_; } void SharedMemory::Close() { shm_.Close(); shm_ = SharedMemoryHandle(); - if (shm_.GetType() == SharedMemoryHandle::POSIX) { - if (readonly_mapped_file_ > 0) { - if (IGNORE_EINTR(close(readonly_mapped_file_)) < 0) - PLOG(ERROR) << "close"; - readonly_mapped_file_ = -1; - } - } -} - -bool SharedMemory::PrepareMapFile(ScopedFILE fp, ScopedFD readonly_fd) { - DCHECK(!shm_.IsValid()); - DCHECK_EQ(-1, readonly_mapped_file_); - if (fp == NULL) - return false; - - // This function theoretically can block on the disk, but realistically - // the temporary files we create will just go into the buffer cache - // and be deleted before they ever make it out to disk. - base::ThreadRestrictions::ScopedAllowIO allow_io; - - struct stat st = {}; - if (fstat(fileno(fp.get()), &st)) - NOTREACHED(); - if (readonly_fd.is_valid()) { - struct stat readonly_st = {}; - if (fstat(readonly_fd.get(), &readonly_st)) - NOTREACHED(); - if (st.st_dev != readonly_st.st_dev || st.st_ino != readonly_st.st_ino) { - LOG(ERROR) << "writable and read-only inodes don't match; bailing"; - return false; - } - } - - int mapped_file = HANDLE_EINTR(dup(fileno(fp.get()))); - if (mapped_file == -1) { - if (errno == EMFILE) { - LOG(WARNING) << "Shared memory creation failed; out of file descriptors"; - return false; - } else { - NOTREACHED() << "Call to dup failed, errno=" << errno; - } - } - shm_ = SharedMemoryHandle(mapped_file, false); - readonly_mapped_file_ = readonly_fd.release(); - - return true; } bool SharedMemory::ShareToProcessCommon(ProcessHandle process, SharedMemoryHandle* new_handle, bool close_self, ShareMode share_mode) { - if (shm_.GetType() == SharedMemoryHandle::MACH) { - DCHECK(shm_.IsValid()); + DCHECK(shm_.IsValid()); - bool success = false; - switch (share_mode) { - case SHARE_CURRENT_MODE: - *new_handle = shm_.Duplicate(); - success = true; - break; - case SHARE_READONLY: - success = MakeMachSharedMemoryHandleReadOnly(new_handle, shm_, memory_); - break; - } - - if (success) - new_handle->SetOwnershipPassesToIPC(true); - - if (close_self) { - Unmap(); - Close(); - } - - return success; - } - - int handle_to_dup = -1; + bool success = false; switch (share_mode) { case SHARE_CURRENT_MODE: - handle_to_dup = shm_.GetFileDescriptor().fd; + *new_handle = shm_.Duplicate(); + success = true; break; case SHARE_READONLY: - // We could imagine re-opening the file from /dev/fd, but that can't make - // it readonly on Mac: https://codereview.chromium.org/27265002/#msg10 - CHECK_GE(readonly_mapped_file_, 0); - handle_to_dup = readonly_mapped_file_; + success = MakeMachSharedMemoryHandleReadOnly(new_handle, shm_, memory_); break; } - const int new_fd = HANDLE_EINTR(dup(handle_to_dup)); - if (new_fd < 0) { - if (close_self) { - Unmap(); - Close(); - } - DPLOG(ERROR) << "dup() failed."; - return false; - } - - new_handle->SetFileHandle(new_fd, true); + if (success) + new_handle->SetOwnershipPassesToIPC(true); if (close_self) { Unmap(); Close(); } - return true; + return success; } } // namespace base
diff --git a/base/memory/shared_memory_unittest.cc b/base/memory/shared_memory_unittest.cc index 948a9d0d..8251f60 100644 --- a/base/memory/shared_memory_unittest.cc +++ b/base/memory/shared_memory_unittest.cc
@@ -316,6 +316,8 @@ } } +// The Mach functionality is tested in shared_memory_mac_unittest.cc. +#if !(defined(OS_MACOSX) && !defined(OS_IOS)) TEST(SharedMemoryTest, ShareReadOnly) { StringPiece contents = "Hello World"; @@ -323,10 +325,6 @@ SharedMemoryCreateOptions options; options.size = contents.size(); options.share_read_only = true; -#if defined(OS_MACOSX) && !defined(OS_IOS) - // The Mach functionality is tested in shared_memory_mac_unittest.cc. - options.type = SharedMemoryHandle::POSIX; -#endif ASSERT_TRUE(writable_shmem.Create(options)); ASSERT_TRUE(writable_shmem.Map(options.size)); memcpy(writable_shmem.memory(), contents.data(), contents.size()); @@ -402,6 +400,7 @@ #error Unexpected platform; write a test that tries to make 'handle' writable. #endif // defined(OS_POSIX) || defined(OS_WIN) } +#endif // !(defined(OS_MACOSX) && !defined(OS_IOS)) TEST(SharedMemoryTest, ShareToSelf) { StringPiece contents = "Hello World"; @@ -475,7 +474,7 @@ EXPECT_EQ(old_address, memory.memory()); } -#if defined(OS_POSIX) +#if defined(OS_POSIX) && !(defined(OS_MACOSX) && !defined(OS_IOS)) // This test is not applicable for iOS (crbug.com/399384). #if !defined(OS_IOS) // Create a shared memory object, mmap it, and mprotect it to PROT_EXEC. @@ -486,10 +485,6 @@ SharedMemoryCreateOptions options; options.size = kTestSize; options.executable = true; -#if defined(OS_MACOSX) && !defined(OS_IOS) - // The Mach functionality is tested in shared_memory_mac_unittest.cc. - options.type = SharedMemoryHandle::POSIX; -#endif EXPECT_TRUE(shared_memory.Create(options)); EXPECT_TRUE(shared_memory.Map(shared_memory.requested_size())); @@ -523,10 +518,6 @@ SharedMemory shared_memory; SharedMemoryCreateOptions options; options.size = kTestSize; -#if defined(OS_MACOSX) && !defined(OS_IOS) - // The Mach functionality is tested in shared_memory_mac_unittest.cc. - options.type = SharedMemoryHandle::POSIX; -#endif // Set a file mode creation mask that gives all permissions. ScopedUmaskSetter permissive_mask(S_IWGRP | S_IWOTH); @@ -549,10 +540,6 @@ SharedMemory shared_memory; SharedMemoryCreateOptions options; options.size = kTestSize; -#if defined(OS_MACOSX) && !defined(OS_IOS) - // The Mach functionality is tested in shared_memory_mac_unittest.cc. - options.type = SharedMemoryHandle::POSIX; -#endif // Set a file mode creation mask that gives all permissions. ScopedUmaskSetter permissive_mask(S_IWGRP | S_IWOTH); @@ -569,7 +556,7 @@ } #endif // !defined(OS_ANDROID) -#endif // defined(OS_POSIX) +#endif // defined(OS_POSIX) && !(defined(OS_MACOSX) && !defined(OS_IOS)) // Map() will return addresses which are aligned to the platform page size, this // varies from platform to platform though. Since we'd like to advertise a
diff --git a/base/message_loop/incoming_task_queue.cc b/base/message_loop/incoming_task_queue.cc index 05bb288..ebecc1b 100644 --- a/base/message_loop/incoming_task_queue.cc +++ b/base/message_loop/incoming_task_queue.cc
@@ -17,7 +17,7 @@ namespace { -#ifndef NDEBUG +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) // Delays larger than this are often bogus, and a warning should be emitted in // debug builds to warn developers. http://crbug.com/450045 const int kTaskDelayWarningThresholdInSeconds =
diff --git a/base/metrics/persistent_histogram_allocator.cc b/base/metrics/persistent_histogram_allocator.cc index b38c1ef..62e8cd6d 100644 --- a/base/metrics/persistent_histogram_allocator.cc +++ b/base/metrics/persistent_histogram_allocator.cc
@@ -291,9 +291,14 @@ if (!initialized) { initialized = true; if (g_allocator) { +// Don't log in release-with-asserts builds, otherwise the test_installer step +// fails because this code writes to a log file before the installer code had a +// chance to set the log file's location. +#if !defined(DCHECK_ALWAYS_ON) DLOG(WARNING) << "Creating the results-histogram inside persistent" << " memory can cause future allocations to crash if" << " that memory is ever released (for testing)."; +#endif } histogram_pointer = LinearHistogram::FactoryGet(
diff --git a/base/task_scheduler/priority_queue.cc b/base/task_scheduler/priority_queue.cc index 05a90b22..2cd8980a 100644 --- a/base/task_scheduler/priority_queue.cc +++ b/base/task_scheduler/priority_queue.cc
@@ -20,6 +20,9 @@ const SequenceSortKey& sort_key) : sequence(std::move(sequence)), sort_key(sort_key) {} +PriorityQueue::SequenceAndSortKey::SequenceAndSortKey( + const SequenceAndSortKey& other) = default; + PriorityQueue::SequenceAndSortKey::~SequenceAndSortKey() = default; PriorityQueue::Transaction::Transaction(PriorityQueue* outer_queue)
diff --git a/base/task_scheduler/priority_queue.h b/base/task_scheduler/priority_queue.h index 36c4bd9a..8676c93 100644 --- a/base/task_scheduler/priority_queue.h +++ b/base/task_scheduler/priority_queue.h
@@ -33,6 +33,8 @@ SequenceAndSortKey(scoped_refptr<Sequence> sequence, const SequenceSortKey& sort_key); + SequenceAndSortKey(const SequenceAndSortKey& other); + ~SequenceAndSortKey(); // Returns true if this is a null SequenceAndSortKey.
diff --git a/base/task_scheduler/priority_queue_unittest.cc b/base/task_scheduler/priority_queue_unittest.cc index 1396414..9733cd0d 100644 --- a/base/task_scheduler/priority_queue_unittest.cc +++ b/base/task_scheduler/priority_queue_unittest.cc
@@ -72,27 +72,27 @@ TEST(TaskSchedulerPriorityQueueTest, PushPopPeek) { // Create test sequences. scoped_refptr<Sequence> sequence_a(new Sequence); - sequence_a->PushTask(WrapUnique( - new Task(FROM_HERE, Closure(), - TaskTraits().WithPriority(TaskPriority::USER_VISIBLE)))); + sequence_a->PushTask(WrapUnique(new Task( + FROM_HERE, Closure(), + TaskTraits().WithPriority(TaskPriority::USER_VISIBLE), TimeTicks()))); SequenceSortKey sort_key_a = sequence_a->GetSortKey(); scoped_refptr<Sequence> sequence_b(new Sequence); - sequence_b->PushTask(WrapUnique( - new Task(FROM_HERE, Closure(), - TaskTraits().WithPriority(TaskPriority::USER_BLOCKING)))); + sequence_b->PushTask(WrapUnique(new Task( + FROM_HERE, Closure(), + TaskTraits().WithPriority(TaskPriority::USER_BLOCKING), TimeTicks()))); SequenceSortKey sort_key_b = sequence_b->GetSortKey(); scoped_refptr<Sequence> sequence_c(new Sequence); - sequence_c->PushTask(WrapUnique( - new Task(FROM_HERE, Closure(), - TaskTraits().WithPriority(TaskPriority::USER_BLOCKING)))); + sequence_c->PushTask(WrapUnique(new Task( + FROM_HERE, Closure(), + TaskTraits().WithPriority(TaskPriority::USER_BLOCKING), TimeTicks()))); SequenceSortKey sort_key_c = sequence_c->GetSortKey(); scoped_refptr<Sequence> sequence_d(new Sequence); - sequence_d->PushTask(WrapUnique( - new Task(FROM_HERE, Closure(), - TaskTraits().WithPriority(TaskPriority::BACKGROUND)))); + sequence_d->PushTask(WrapUnique(new Task( + FROM_HERE, Closure(), TaskTraits().WithPriority(TaskPriority::BACKGROUND), + TimeTicks()))); SequenceSortKey sort_key_d = sequence_d->GetSortKey(); // Create a PriorityQueue and a Transaction.
diff --git a/base/task_scheduler/scheduler_worker_thread_unittest.cc b/base/task_scheduler/scheduler_worker_thread_unittest.cc index 541d1bc..0131dcf 100644 --- a/base/task_scheduler/scheduler_worker_thread_unittest.cc +++ b/base/task_scheduler/scheduler_worker_thread_unittest.cc
@@ -118,7 +118,7 @@ std::unique_ptr<Task> task(new Task( FROM_HERE, Bind(&TaskSchedulerWorkerThreadTest::RunTaskCallback, Unretained(this)), - TaskTraits())); + TaskTraits(), TimeTicks())); EXPECT_TRUE(task_tracker_.WillPostTask(task.get())); sequence->PushTask(std::move(task)); }
diff --git a/base/task_scheduler/sequence_unittest.cc b/base/task_scheduler/sequence_unittest.cc index 17826a0..78114c8 100644 --- a/base/task_scheduler/sequence_unittest.cc +++ b/base/task_scheduler/sequence_unittest.cc
@@ -19,23 +19,28 @@ : task_a_owned_( new Task(FROM_HERE, Closure(), - TaskTraits().WithPriority(TaskPriority::BACKGROUND))), + TaskTraits().WithPriority(TaskPriority::BACKGROUND), + TimeTicks())), task_b_owned_( new Task(FROM_HERE, Closure(), - TaskTraits().WithPriority(TaskPriority::USER_VISIBLE))), + TaskTraits().WithPriority(TaskPriority::USER_VISIBLE), + TimeTicks())), task_c_owned_( new Task(FROM_HERE, Closure(), - TaskTraits().WithPriority(TaskPriority::USER_BLOCKING))), + TaskTraits().WithPriority(TaskPriority::USER_BLOCKING), + TimeTicks())), task_d_owned_( new Task(FROM_HERE, Closure(), - TaskTraits().WithPriority(TaskPriority::USER_BLOCKING))), + TaskTraits().WithPriority(TaskPriority::USER_BLOCKING), + TimeTicks())), task_e_owned_( new Task(FROM_HERE, Closure(), - TaskTraits().WithPriority(TaskPriority::BACKGROUND))), + TaskTraits().WithPriority(TaskPriority::BACKGROUND), + TimeTicks())), task_a_(task_a_owned_.get()), task_b_(task_b_owned_.get()), task_c_(task_c_owned_.get()),
diff --git a/base/task_scheduler/task.cc b/base/task_scheduler/task.cc index ae63403..e738bed2 100644 --- a/base/task_scheduler/task.cc +++ b/base/task_scheduler/task.cc
@@ -9,11 +9,12 @@ Task::Task(const tracked_objects::Location& posted_from, const Closure& task, - const TaskTraits& traits) + const TaskTraits& traits, + const TimeTicks& delayed_run_time) : PendingTask(posted_from, task, - TimeTicks(), // No delayed run time. - false), // Not nestable. + delayed_run_time, + false), // Not nestable. traits(traits) {} Task::~Task() = default;
diff --git a/base/task_scheduler/task.h b/base/task_scheduler/task.h index 6ac483d5..dcdda00 100644 --- a/base/task_scheduler/task.h +++ b/base/task_scheduler/task.h
@@ -18,9 +18,14 @@ // A task is a unit of work inside the task scheduler. Support for tracing and // profiling inherited from PendingTask. struct BASE_EXPORT Task : public PendingTask { + // |posted_from| is the site the task was posted from. |task| is the closure + // to run. |traits| is metadata about the task. |delayed_run_time| is the time + // at which the task should be run (null TimeTicks if the task can run + // immediately). Task(const tracked_objects::Location& posted_from, const Closure& task, - const TaskTraits& traits); + const TaskTraits& traits, + const TimeTicks& delayed_run_time); ~Task(); // The TaskTraits of this task.
diff --git a/base/task_scheduler/task_tracker_unittest.cc b/base/task_scheduler/task_tracker_unittest.cc index a490fce..3403caa 100644 --- a/base/task_scheduler/task_tracker_unittest.cc +++ b/base/task_scheduler/task_tracker_unittest.cc
@@ -71,7 +71,7 @@ return WrapUnique(new Task( FROM_HERE, Bind(&TaskSchedulerTaskTrackerTest::RunTaskCallback, Unretained(this)), - TaskTraits().WithShutdownBehavior(shutdown_behavior))); + TaskTraits().WithShutdownBehavior(shutdown_behavior), TimeTicks())); } // Calls tracker_->Shutdown() on a new thread. When this returns, Shutdown() @@ -146,7 +146,7 @@ WaitableEvent event(false, false); std::unique_ptr<Task> blocked_task( new Task(FROM_HERE, Bind(&WaitableEvent::Wait, Unretained(&event)), - TaskTraits().WithShutdownBehavior(GetParam()))); + TaskTraits().WithShutdownBehavior(GetParam()), TimeTicks())); // Inform |task_tracker_| that |blocked_task| will be posted. EXPECT_TRUE(tracker_.WillPostTask(blocked_task.get()));
diff --git a/base/task_scheduler/task_traits.cc b/base/task_scheduler/task_traits.cc index 8f037f61..1229d0d 100644 --- a/base/task_scheduler/task_traits.cc +++ b/base/task_scheduler/task_traits.cc
@@ -4,6 +4,8 @@ #include "base/task_scheduler/task_traits.h" +#include <stddef.h> + #include <ostream> namespace base { @@ -35,6 +37,10 @@ } bool TaskTraits::operator==(const TaskTraits& other) const { + static_assert(sizeof(TaskTraits) == + offsetof(TaskTraits, shutdown_behavior_) + + sizeof(TaskTraits::shutdown_behavior_), + "TaskTraits members changed. Update operator==."); return with_file_io_ == other.with_file_io_ && priority_ == other.priority_ && shutdown_behavior_ == other.shutdown_behavior_; }
diff --git a/base/task_scheduler/utils.cc b/base/task_scheduler/utils.cc index f47ca93..88bdcf9 100644 --- a/base/task_scheduler/utils.cc +++ b/base/task_scheduler/utils.cc
@@ -33,7 +33,8 @@ // TODO(fdoray): Support delayed tasks. DCHECK(delay.is_zero()); - std::unique_ptr<Task> task(new Task(posted_from, closure, traits)); + std::unique_ptr<Task> task( + new Task(posted_from, closure, traits, TimeTicks())); if (!task_tracker->WillPostTask(task.get())) return false;
diff --git a/base/task_scheduler/utils_unittest.cc b/base/task_scheduler/utils_unittest.cc index 1b199fa..c2962f6 100644 --- a/base/task_scheduler/utils_unittest.cc +++ b/base/task_scheduler/utils_unittest.cc
@@ -75,7 +75,7 @@ TEST(TaskSchedulerAddTaskToSequenceAndPriorityQueueTest, PostTaskInEmptySequence) { std::unique_ptr<Task> task( - new Task(FROM_HERE, Bind(&DoNothing), TaskTraits())); + new Task(FROM_HERE, Bind(&DoNothing), TaskTraits(), TimeTicks())); const Task* task_raw = task.get(); scoped_refptr<Sequence> sequence(new Sequence); PriorityQueue priority_queue; @@ -99,14 +99,14 @@ TEST(TaskSchedulerAddTaskToSequenceAndPriorityQueueTest, PostTaskInNonEmptySequence) { std::unique_ptr<Task> task( - new Task(FROM_HERE, Bind(&DoNothing), TaskTraits())); + new Task(FROM_HERE, Bind(&DoNothing), TaskTraits(), TimeTicks())); const Task* task_raw = task.get(); scoped_refptr<Sequence> sequence(new Sequence); PriorityQueue priority_queue; // Add an initial task in |sequence|. - sequence->PushTask( - WrapUnique(new Task(FROM_HERE, Bind(&DoNothing), TaskTraits()))); + sequence->PushTask(WrapUnique( + new Task(FROM_HERE, Bind(&DoNothing), TaskTraits(), TimeTicks()))); // Post |task|. EXPECT_FALSE(AddTaskToSequenceAndPriorityQueue(std::move(task), sequence,
diff --git a/base/threading/platform_thread_win.cc b/base/threading/platform_thread_win.cc index d5bd9be..eae2366 100644 --- a/base/threading/platform_thread_win.cc +++ b/base/threading/platform_thread_win.cc
@@ -251,7 +251,7 @@ } DCHECK_NE(desired_priority, THREAD_PRIORITY_ERROR_RETURN); -#ifndef NDEBUG +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) const BOOL success = #endif ::SetThreadPriority(PlatformThread::CurrentHandle().platform_handle(),
diff --git a/blimp/client/feature/compositor/decoding_image_generator.cc b/blimp/client/feature/compositor/decoding_image_generator.cc index 692dd373..5ceab09e 100644 --- a/blimp/client/feature/compositor/decoding_image_generator.cc +++ b/blimp/client/feature/compositor/decoding_image_generator.cc
@@ -4,7 +4,9 @@ #include "blimp/client/feature/compositor/decoding_image_generator.h" +#include "base/numerics/safe_conversions.h" #include "blimp/common/compositor/webp_decoder.h" +#include "blimp/common/proto/blob_cache.pb.h" #include "third_party/libwebp/webp/decode.h" #include "third_party/libwebp/webp/demux.h" #include "third_party/skia/include/core/SkData.h" @@ -13,16 +15,19 @@ namespace client { SkImageGenerator* DecodingImageGenerator::create(SkData* data) { - WebPData inputData = {reinterpret_cast<const uint8_t*>(data->data()), - data->size()}; - WebPDemuxState demuxState(WEBP_DEMUX_PARSING_HEADER); - WebPDemuxer* demux = WebPDemuxPartial(&inputData, &demuxState); + BlobCacheImageMetadata parsed_metadata; + int signed_size = base::checked_cast<int>(data->size()); + if (!parsed_metadata.ParseFromArray(data->data(), signed_size)) { + // Failed to parse proto, so will fail to decode later as well. Inform + // Skia by giving back an empty SkImageInfo. + return new DecodingImageGenerator(SkImageInfo::MakeN32Premul(0, 0), + data->data(), data->size()); + } - uint32_t width = WebPDemuxGetI(demux, WEBP_FF_CANVAS_WIDTH); - uint32_t height = WebPDemuxGetI(demux, WEBP_FF_CANVAS_HEIGHT); - - const SkImageInfo info = SkImageInfo::MakeN32Premul(width, height); - return new DecodingImageGenerator(info, data->data(), data->size()); + return new DecodingImageGenerator( + SkImageInfo::MakeN32Premul(parsed_metadata.width(), + parsed_metadata.height()), + data->data(), data->size()); } DecodingImageGenerator::DecodingImageGenerator(const SkImageInfo info,
diff --git a/blimp/common/BUILD.gn b/blimp/common/BUILD.gn index 2bfed0f7..6548853 100644 --- a/blimp/common/BUILD.gn +++ b/blimp/common/BUILD.gn
@@ -7,6 +7,11 @@ component("blimp_common") { sources = [ "blimp_common_export.h", + "blob_cache/blob_cache.h", + "blob_cache/id_util.cc", + "blob_cache/id_util.h", + "blob_cache/in_memory_blob_cache.cc", + "blob_cache/in_memory_blob_cache.h", "compositor/blimp_image_serialization_processor.cc", "compositor/blimp_image_serialization_processor.h", "compositor/blimp_task_graph_runner.cc", @@ -37,6 +42,7 @@ testonly = true sources = [ + "blob_cache/in_memory_blob_cache_unittest.cc", "create_blimp_message_unittest.cc", "logging_unittest.cc", ]
diff --git a/blimp/common/blob_cache/blob_cache.h b/blimp/common/blob_cache/blob_cache.h new file mode 100644 index 0000000..54993238 --- /dev/null +++ b/blimp/common/blob_cache/blob_cache.h
@@ -0,0 +1,38 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BLIMP_COMMON_BLOB_CACHE_BLOB_CACHE_H_ +#define BLIMP_COMMON_BLOB_CACHE_BLOB_CACHE_H_ + +#include <string> +#include <vector> + +#include "base/memory/ref_counted.h" +#include "blimp/common/blimp_common_export.h" + +namespace blimp { + +using BlobId = std::string; +using BlobData = scoped_refptr<base::RefCountedData<const std::string>>; + +// An interface for a cache of blobs. +class BLIMP_COMMON_EXPORT BlobCache { + public: + virtual ~BlobCache() {} + + // Returns true if there is a cache item |id|. + virtual bool Contains(const BlobId& id) const = 0; + + // Stores |data| with the identifier |id| in the cache. + // Command is ignored if there is already a cache item stored under |id|. + virtual void Put(const BlobId& id, BlobData data) = 0; + + // Returns a pointer to the cache item |id|, or nullptr if no cache item + // exists under that identifier. + virtual BlobData Get(const BlobId& id) const = 0; +}; + +} // namespace blimp + +#endif // BLIMP_COMMON_BLOB_CACHE_BLOB_CACHE_H_
diff --git a/blimp/common/blob_cache/id_util.cc b/blimp/common/blob_cache/id_util.cc new file mode 100644 index 0000000..c6f33fc --- /dev/null +++ b/blimp/common/blob_cache/id_util.cc
@@ -0,0 +1,27 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "blimp/common/blob_cache/id_util.h" + +#include "base/sha1.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_util.h" +#include "blimp/common/blob_cache/blob_cache.h" + +namespace blimp { + +const BlobId CalculateBlobId(const void* data, size_t data_size) { + std::vector<unsigned char> sha1_hash(base::kSHA1Length); + base::SHA1HashBytes(static_cast<const unsigned char*>(data), data_size, + sha1_hash.data()); + return std::string(reinterpret_cast<char*>(sha1_hash.data()), + sha1_hash.size()); +} + +const std::string FormatBlobId(const BlobId& data) { + DCHECK_EQ(base::kSHA1Length, data.length()); + return base::ToLowerASCII(base::HexEncode(data.data(), data.length())); +} + +} // namespace blimp
diff --git a/blimp/common/blob_cache/id_util.h b/blimp/common/blob_cache/id_util.h new file mode 100644 index 0000000..902d48a --- /dev/null +++ b/blimp/common/blob_cache/id_util.h
@@ -0,0 +1,27 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BLIMP_COMMON_BLOB_CACHE_ID_UTIL_H_ +#define BLIMP_COMMON_BLOB_CACHE_ID_UTIL_H_ + +#include <string> +#include <vector> + +#include "blimp/common/blimp_common_export.h" +#include "blimp/common/blob_cache/blob_cache.h" + +namespace blimp { + +// Returns the bytes of a SHA1 hash of the input. The string is guaranteed +// to have length base::kSHA1Length. +BLIMP_COMMON_EXPORT const BlobId CalculateBlobId(const void* data, + size_t data_size); + +// Returns a hexadecimal string representation of a SHA1 hash. The input is +// required to have length base::kSHA1Length. +BLIMP_COMMON_EXPORT const std::string FormatBlobId(const BlobId& data); + +} // namespace blimp + +#endif // BLIMP_COMMON_BLOB_CACHE_ID_UTIL_H_
diff --git a/blimp/common/blob_cache/in_memory_blob_cache.cc b/blimp/common/blob_cache/in_memory_blob_cache.cc new file mode 100644 index 0000000..5928faa --- /dev/null +++ b/blimp/common/blob_cache/in_memory_blob_cache.cc
@@ -0,0 +1,41 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "blimp/common/blob_cache/in_memory_blob_cache.h" + +#include "base/logging.h" +#include "base/sha1.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_util.h" + +namespace blimp { + +InMemoryBlobCache::InMemoryBlobCache() {} + +InMemoryBlobCache::~InMemoryBlobCache() {} + +void InMemoryBlobCache::Put(const BlobId& id, BlobData data) { + if (Contains(id)) { + // In cases where the engine has miscalculated what is already available + // on the client, Put() might be called unnecessarily, which should be + // ignored. + VLOG(2) << "Item with ID " << id << " already exists in cache."; + return; + } + cache_.insert(std::make_pair(id, std::move(data))); +} + +bool InMemoryBlobCache::Contains(const BlobId& id) const { + return cache_.find(id) != cache_.end(); +} + +BlobData InMemoryBlobCache::Get(const BlobId& id) const { + if (!Contains(id)) { + return nullptr; + } + + return cache_.find(id)->second; +} + +} // namespace blimp
diff --git a/blimp/common/blob_cache/in_memory_blob_cache.h b/blimp/common/blob_cache/in_memory_blob_cache.h new file mode 100644 index 0000000..986feb4 --- /dev/null +++ b/blimp/common/blob_cache/in_memory_blob_cache.h
@@ -0,0 +1,38 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BLIMP_COMMON_BLOB_CACHE_IN_MEMORY_BLOB_CACHE_H_ +#define BLIMP_COMMON_BLOB_CACHE_IN_MEMORY_BLOB_CACHE_H_ + +#include <map> +#include <string> + +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "blimp/common/blimp_common_export.h" +#include "blimp/common/blob_cache/blob_cache.h" + +namespace blimp { + +// InMemoryBlobCache provides an in-memory implementation of BlobCache that +// never evicts items. +class BLIMP_COMMON_EXPORT InMemoryBlobCache : public BlobCache { + public: + InMemoryBlobCache(); + ~InMemoryBlobCache() override; + + // BlobCache implementation. + bool Contains(const BlobId& id) const override; + void Put(const BlobId& id, BlobData data) override; + BlobData Get(const BlobId& id) const override; + + private: + std::map<const BlobId, BlobData> cache_; + + DISALLOW_COPY_AND_ASSIGN(InMemoryBlobCache); +}; + +} // namespace blimp + +#endif // BLIMP_COMMON_BLOB_CACHE_IN_MEMORY_BLOB_CACHE_H_
diff --git a/blimp/common/blob_cache/in_memory_blob_cache_unittest.cc b/blimp/common/blob_cache/in_memory_blob_cache_unittest.cc new file mode 100644 index 0000000..e0531e4c --- /dev/null +++ b/blimp/common/blob_cache/in_memory_blob_cache_unittest.cc
@@ -0,0 +1,68 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <algorithm> +#include <memory> +#include <vector> + +#include "base/logging.h" +#include "base/memory/ptr_util.h" +#include "base/memory/ref_counted.h" +#include "blimp/common/blob_cache/blob_cache.h" +#include "blimp/common/blob_cache/in_memory_blob_cache.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace blimp { +namespace { + +const char kFoo[] = "foo"; +const char kBar[] = "bar"; +const char kDeadbeef[] = "\xde\xad\xbe\xef"; +const char kForbiddenCode[] = "\x4b\x1d\xc0\xd3"; + +BlobData CreateBlobData(const std::string& data) { + return new base::RefCountedData<const std::string>(data); +} + +class InMemoryBlobCacheTest : public testing::Test { + public: + InMemoryBlobCacheTest() {} + ~InMemoryBlobCacheTest() override {} + + protected: + InMemoryBlobCache cache_; +}; + +TEST_F(InMemoryBlobCacheTest, SimplePutContainsAndGetOperations) { + EXPECT_FALSE(cache_.Contains(kFoo)); + EXPECT_EQ(nullptr, cache_.Get(kFoo)); + + BlobData blob_data = CreateBlobData(kDeadbeef); + cache_.Put(kFoo, blob_data); + + EXPECT_TRUE(cache_.Contains(kFoo)); + EXPECT_FALSE(cache_.Contains(kBar)); + + BlobData out = cache_.Get(kFoo); + + EXPECT_EQ(blob_data, out); +} + +TEST_F(InMemoryBlobCacheTest, TestDuplicatePut) { + BlobData first = CreateBlobData(kDeadbeef); + BlobData duplicate = CreateBlobData(kForbiddenCode); + cache_.Put(kFoo, first); + + BlobData out1 = cache_.Get(kFoo); + EXPECT_EQ(first, out1); + + // The second put should be ignored and retrieving kFoo should still retrieve + // the first item. + cache_.Put(kFoo, duplicate); + BlobData out2 = cache_.Get(kFoo); + EXPECT_EQ(first, out2); +} + +} // namespace +} // namespace blimp
diff --git a/blimp/common/compositor/webp_decoder.cc b/blimp/common/compositor/webp_decoder.cc index 7f4d363..436df4e 100644 --- a/blimp/common/compositor/webp_decoder.cc +++ b/blimp/common/compositor/webp_decoder.cc
@@ -4,12 +4,28 @@ #include "blimp/common/compositor/webp_decoder.h" +#include "base/lazy_instance.h" #include "base/logging.h" +#include "base/numerics/safe_conversions.h" +#include "base/sha1.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_util.h" +#include "blimp/common/blob_cache/blob_cache.h" +#include "blimp/common/blob_cache/id_util.h" +#include "blimp/common/blob_cache/in_memory_blob_cache.h" +#include "blimp/common/proto/blob_cache.pb.h" #include "third_party/libwebp/webp/decode.h" #include "third_party/libwebp/webp/demux.h" #include "third_party/skia/include/core/SkBitmap.h" namespace blimp { +namespace { + +// TODO(nyquist): Make this not be infinite size. +static base::LazyInstance<InMemoryBlobCache> g_blob_cache = + LAZY_INSTANCE_INITIALIZER; + +} // namespace bool WebPDecoder(const void* input, size_t input_size, SkBitmap* bitmap) { DCHECK(bitmap); @@ -21,13 +37,54 @@ return false; } - // Treat the input as uint8_t. - WebPData data = {reinterpret_cast<const uint8_t*>(input), input_size}; + BlobCacheImageMetadata deserialized; + int signed_size = base::checked_cast<int>(input_size); + if (!deserialized.ParseFromArray(input, signed_size)) { + LOG(WARNING) << "Failed to parse BlobCacheImageMetadata"; + return false; + } + + // The cache uses the SHA1 hex string of the ID. + if (deserialized.id().length() != base::kSHA1Length) { + LOG(WARNING) << "Length of ID is not base::kSHA1Length (" + << base::kSHA1Length << "), but " + << deserialized.id().length(); + return false; + } + std::string hex_id = FormatBlobId(deserialized.id()); + + // Declared here to still be in scope while decoding WebP data. + BlobData cached; + + // Set to true if the client already has the data in its cache. If it does not + // keeping |found_in_cache| as false will trigger caching the input in the + // end of this function. + bool found_in_cache = false; + + // Used later to decode the image and is initialized either based on a cached + // item or from the |payload| of the proto. + WebPData webp_data; + + if (g_blob_cache.Get().Contains(deserialized.id())) { + // The image was found in the cache, so decode using cached data. + cached = g_blob_cache.Get().Get(deserialized.id()); + webp_data.bytes = reinterpret_cast<const uint8_t*>(cached->data.data()); + webp_data.size = cached->data.size(); + DVLOG(2) << "Found SHA1 " << hex_id << " with size = " << webp_data.size; + found_in_cache = true; + } else { + // The image was not found in the cache, so decode using the payload. + DCHECK(deserialized.has_payload()); + webp_data.bytes = + reinterpret_cast<const uint8_t*>(deserialized.payload().c_str()); + webp_data.size = deserialized.payload().size(); + } // Read WebP feature information into |config.input|, which is a // WebPBitstreamFeatures. It contains information such as width, height and // whether the WebP image has an alpha channel or not. - if (WebPGetFeatures(data.bytes, data.size, &config.input) != VP8_STATUS_OK) { + if (WebPGetFeatures(webp_data.bytes, webp_data.size, &config.input) != + VP8_STATUS_OK) { LOG(WARNING) << "Failed to get WebP features."; return false; } @@ -59,7 +116,8 @@ config.output = decoderBuffer; // Decode the input data into the bitmap buffer. - bool success = WebPDecode(data.bytes, data.size, &config) == VP8_STATUS_OK; + bool success = + WebPDecode(webp_data.bytes, webp_data.size, &config) == VP8_STATUS_OK; // Now free the buffer. It is safe to call this even when the buffer is // external and not allocated by WebPDecode. @@ -69,6 +127,15 @@ LOG(WARNING) << "Failed to decode WebP data."; return false; } + + if (!found_in_cache) { + DVLOG(2) << "Inserting image to cache with SHA1: " << hex_id + << " size: " << webp_data.size; + BlobData to_cache(new base::RefCountedData<const std::string>(std::string( + reinterpret_cast<const char*>(webp_data.bytes), webp_data.size))); + g_blob_cache.Get().Put(deserialized.id(), std::move(to_cache)); + } + return true; }
diff --git a/blimp/common/proto/BUILD.gn b/blimp/common/proto/BUILD.gn index f14f64e5..a56bfa6 100644 --- a/blimp/common/proto/BUILD.gn +++ b/blimp/common/proto/BUILD.gn
@@ -26,6 +26,7 @@ sources = [ "blimp_message.proto", + "blob_cache.proto", "compositor.proto", "ime.proto", "input.proto",
diff --git a/blimp/common/proto/blob_cache.proto b/blimp/common/proto/blob_cache.proto new file mode 100644 index 0000000..04efd9f6b --- /dev/null +++ b/blimp/common/proto/blob_cache.proto
@@ -0,0 +1,21 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +// +// Message definitions related to the BlobCache. + +syntax = "proto2"; + +option optimize_for = LITE_RUNTIME; + +package blimp; + +// An representation sent from the engine to the client for retrieving an image +// from the cache or reading from |payload|. +message BlobCacheImageMetadata { + optional bytes id = 1; + optional int32 width = 2; + optional int32 height = 3; + // TODO(nyquist): Remove |payload| after incorporation of BlobChannel. + optional bytes payload = 4; +}
diff --git a/blimp/engine/BUILD.gn b/blimp/engine/BUILD.gn index 8503ab46..fda282b 100644 --- a/blimp/engine/BUILD.gn +++ b/blimp/engine/BUILD.gn
@@ -160,6 +160,8 @@ deps = [ ":blob_channel_mojo", "//base", + "//blimp/common:blimp_common", + "//blimp/common/proto", "//cc", "//skia", "//third_party/libwebp",
diff --git a/blimp/engine/renderer/engine_image_serialization_processor.cc b/blimp/engine/renderer/engine_image_serialization_processor.cc index 8b670197..c3adf059 100644 --- a/blimp/engine/renderer/engine_image_serialization_processor.cc +++ b/blimp/engine/renderer/engine_image_serialization_processor.cc
@@ -5,10 +5,18 @@ #include "blimp/engine/renderer/engine_image_serialization_processor.h" #include <stddef.h> +#include <set> +#include <string> #include <vector> +#include "base/lazy_instance.h" #include "base/logging.h" +#include "base/sha1.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_util.h" +#include "blimp/common/blob_cache/id_util.h" #include "blimp/common/compositor/webp_decoder.h" +#include "blimp/common/proto/blob_cache.pb.h" #include "content/public/renderer/render_frame.h" #include "third_party/libwebp/webp/encode.h" #include "third_party/skia/include/core/SkData.h" @@ -16,7 +24,22 @@ #include "third_party/skia/include/core/SkPixelSerializer.h" #include "third_party/skia/include/core/SkUnPreMultiply.h" +namespace blimp { namespace { + +// TODO(nyquist): Add support for changing this from the client. +static base::LazyInstance<std::set<BlobId>> g_client_cache_contents = + LAZY_INSTANCE_INITIALIZER; + +SkData* BlobCacheImageMetadataProtoAsSkData( + const BlobCacheImageMetadata& proto) { + int signed_size = proto.ByteSize(); + size_t unsigned_size = base::checked_cast<size_t>(signed_size); + std::vector<uint8_t> serialized(unsigned_size); + proto.SerializeWithCachedSizesToArray(serialized.data()); + return SkData::NewWithCopy(serialized.data(), serialized.size()); +} + // TODO(nyquist): Make sure encoder does not serialize images more than once. // See crbug.com/548434. class WebPImageEncoder : public SkPixelSerializer { @@ -25,10 +48,8 @@ ~WebPImageEncoder() override{}; bool onUseEncodedData(const void* data, size_t len) override { - const unsigned char* cast_data = static_cast<const unsigned char*>(data); - if (len < 14) - return false; - return !memcmp(cast_data, "RIFF", 4) && !memcmp(cast_data + 8, "WEBPVP", 6); + // Encode all images regardless of their format, including WebP images. + return false; } SkData* onEncode(const SkPixmap& pixmap) override { @@ -50,6 +71,24 @@ return nullptr; picture.height = pixmap.height(); + const BlobId blob_id = CalculateBlobId(pixmap.addr(), pixmap.getSafeSize()); + std::string blob_id_hex = FormatBlobId(blob_id); + + // Create proto with all requires information. + BlobCacheImageMetadata proto; + proto.set_id(blob_id); + proto.set_width(pixmap.width()); + proto.set_height(pixmap.height()); + + if (g_client_cache_contents.Get().find(blob_id) != + g_client_cache_contents.Get().end()) { + // Found image in client cache, so skip sending decoded payload. + SkData* sk_data = BlobCacheImageMetadataProtoAsSkData(proto); + DVLOG(2) << "Sending cached: " << blob_id_hex + << " size = " << sk_data->size(); + return sk_data; + } + DVLOG(2) << "Encoding image color_type=" << pixmap.colorType() << ", alpha_type=" << pixmap.alphaType() << " " << pixmap.width() << "x" << pixmap.height(); @@ -60,8 +99,8 @@ return nullptr; // Create a buffer for where to store the output data. - std::vector<unsigned char> data; - picture.custom_ptr = &data; + std::vector<unsigned char> encoded_data; + picture.custom_ptr = &encoded_data; // Use our own WebPWriterFunction implementation. picture.writer = &WebPImageEncoder::WriteOutput; @@ -88,9 +127,16 @@ if (!success) return nullptr; - // Copy WebP data into SkData. |data| is allocated only on the stack, so - // it is automatically deleted after this. - return SkData::NewWithCopy(&data.front(), data.size()); + // Did not find item in cache, so add it to client cache representation + // and send full item. + g_client_cache_contents.Get().insert(blob_id); + proto.set_payload(&encoded_data.front(), encoded_data.size()); + + // Copy proto into SkData. + SkData* sk_data = BlobCacheImageMetadataProtoAsSkData(proto); + DVLOG(2) << "Sending image: " << blob_id_hex + << " size = " << sk_data->size(); + return sk_data; } private: @@ -154,7 +200,6 @@ } // namespace -namespace blimp { namespace engine { EngineImageSerializationProcessor::EngineImageSerializationProcessor(
diff --git a/build/android/adb_command_line.py b/build/android/adb_command_line.py index c242aa1..72f42b6 100755 --- a/build/android/adb_command_line.py +++ b/build/android/adb_command_line.py
@@ -24,8 +24,8 @@ Otherwise: Writes command-line file. ''' - parser.add_argument('-d', '--device', dest='device', - help='Target device for apk to install on.') + parser.add_argument('-d', '--device', dest='devices', action='append', + default=[], help='Target device serial (repeatable).') parser.add_argument('--device-path', required=True, help='Remote path to flags file.') parser.add_argument('-e', '--executable', dest='executable', default='chrome', @@ -36,13 +36,8 @@ as_root = not args.device_path.startswith('/data/local/tmp/') - if args.device: - devices = [device_utils.DeviceUtils(args.device, default_retries=0)] - else: - devices = device_utils.DeviceUtils.HealthyDevices(default_retries=0) - if not devices: - raise device_errors.NoDevicesError() - + devices = device_utils.DeviceUtils.HealthyDevices(device_arg=args.devices, + default_retries=0) all_devices = device_utils.DeviceUtils.parallel(devices) def print_args():
diff --git a/build/android/adb_install_apk.py b/build/android/adb_install_apk.py index 4bf5ad5..bc55bf88 100755 --- a/build/android/adb_install_apk.py +++ b/build/android/adb_install_apk.py
@@ -54,6 +54,7 @@ help='If set, run test suites under out/Release. ' 'Default is env var BUILDTYPE or Debug.') parser.add_argument('-d', '--device', dest='devices', action='append', + default=[], help='Target device for apk to install on. Enter multiple' ' times for multiple devices.') parser.add_argument('--adb-path', @@ -109,14 +110,8 @@ blacklist = (device_blacklist.Blacklist(args.blacklist_file) if args.blacklist_file else None) - devices = device_utils.DeviceUtils.HealthyDevices(blacklist) - - if args.devices: - devices = [d for d in devices if d in args.devices] - if not devices: - raise device_errors.DeviceUnreachableError(args.devices) - elif not devices: - raise device_errors.NoDevicesError() + devices = device_utils.DeviceUtils.HealthyDevices(blacklist=blacklist, + device_arg=args.devices) def blacklisting_install(device): try:
diff --git a/build/android/adb_reverse_forwarder.py b/build/android/adb_reverse_forwarder.py index d3da6fe..e3a7b50 100755 --- a/build/android/adb_reverse_forwarder.py +++ b/build/android/adb_reverse_forwarder.py
@@ -11,7 +11,6 @@ to be built. """ -import logging import optparse import sys import time @@ -19,7 +18,6 @@ import devil_chromium from devil.android import device_blacklist -from devil.android import device_errors from devil.android import device_utils from devil.android import forwarder from devil.utils import run_tests_helper @@ -63,18 +61,8 @@ blacklist = (device_blacklist.Blacklist(options.blacklist_file) if options.blacklist_file else None) - devices = device_utils.DeviceUtils.HealthyDevices(blacklist) - - if options.device: - device = next((d for d in devices if d == options.device), None) - if not device: - raise device_errors.DeviceUnreachableError(options.device) - elif devices: - device = devices[0] - logging.info('No device specified. Defaulting to %s', devices[0]) - else: - raise device_errors.NoDevicesError() - + device = device_utils.DeviceUtils.HealthyDevices(blacklist=blacklist, + device_arg=options.device) constants.SetBuildType(options.build_type) try: forwarder.Forwarder.Map(port_pairs, device)
diff --git a/build/android/gyp/javac.py b/build/android/gyp/javac.py index e8cee1c..5722fb1d 100755 --- a/build/android/gyp/javac.py +++ b/build/android/gyp/javac.py
@@ -351,13 +351,16 @@ javac_cmd.extend(['-XDignore.symbol.file']) classpath_inputs = options.bootclasspath - # TODO(agrieve): Remove this .TOC heuristic once GYP is no more. - if options.classpath and not options.classpath[0].endswith('.interface.jar'): - for path in options.classpath: - if os.path.exists(path + '.TOC'): - classpath_inputs.append(path + '.TOC') - else: - classpath_inputs.append(path) + if options.classpath: + if options.classpath[0].endswith('.interface.jar'): + classpath_inputs.extend(options.classpath) + else: + # TODO(agrieve): Remove this .TOC heuristic once GYP is no more. + for path in options.classpath: + if os.path.exists(path + '.TOC'): + classpath_inputs.append(path + '.TOC') + else: + classpath_inputs.append(path) # Compute the list of paths that when changed, we need to rebuild. input_paths = classpath_inputs + options.java_srcjars + java_files
diff --git a/build/android/gyp/lint.py b/build/android/gyp/lint.py index 72d81033..cc44a437 100755 --- a/build/android/gyp/lint.py +++ b/build/android/gyp/lint.py
@@ -21,7 +21,7 @@ '..', '..', '..')) -def _OnStaleMd5(changes, lint_path, config_path, processed_config_path, +def _OnStaleMd5(lint_path, config_path, processed_config_path, manifest_path, result_path, product_dir, sources, jar_path, cache_dir, android_sdk_version, resource_dir=None, classpath=None, can_fail_build=False, silent=False): @@ -77,13 +77,6 @@ print >> sys.stderr, error_line.encode('utf-8') return len(issues) - # Need to include all sources when a resource_dir is set so that resources are - # not marked as unused. - # TODO(agrieve): Figure out how IDEs do incremental linting. - if not resource_dir and changes.AddedOrModifiedOnly(): - changed_paths = set(changes.IterChangedPaths()) - sources = [s for s in sources if s in changed_paths] - with build_utils.TempDir() as temp_dir: _ProcessConfigFile() @@ -310,23 +303,22 @@ output_paths = [ args.result_path ] build_utils.CallAndWriteDepfileIfStale( - lambda changes: _OnStaleMd5(changes, args.lint_path, - args.config_path, - args.processed_config_path, - args.manifest_path, args.result_path, - args.product_dir, sources, - args.jar_path, - args.cache_dir, - args.android_sdk_version, - resource_dir=args.resource_dir, - classpath=classpath, - can_fail_build=args.can_fail_build, - silent=args.silent), + lambda: _OnStaleMd5(args.lint_path, + args.config_path, + args.processed_config_path, + args.manifest_path, args.result_path, + args.product_dir, sources, + args.jar_path, + args.cache_dir, + args.android_sdk_version, + resource_dir=args.resource_dir, + classpath=classpath, + can_fail_build=args.can_fail_build, + silent=args.silent), args, input_paths=input_paths, input_strings=input_strings, output_paths=output_paths, - pass_changes=True, depfile_deps=classpath)
diff --git a/build/android/gyp/util/build_utils.py b/build/android/gyp/util/build_utils.py index d260289..7c32bc1b 100644 --- a/build/android/gyp/util/build_utils.py +++ b/build/android/gyp/util/build_utils.py
@@ -337,9 +337,6 @@ # Ignore directories. if info.filename[-1] == '/': continue - # Don't validate CRCs. ijar sets them all to 0. - if hasattr(info, 'CRC'): - del info.CRC dst_name = path_transform(info.filename, in_file) already_added = dst_name in added_names if not already_added and not MatchesGlob(dst_name, exclude_patterns):
diff --git a/build/android/incremental_install/installer.py b/build/android/incremental_install/installer.py index 25a0295..421318cf 100755 --- a/build/android/incremental_install/installer.py +++ b/build/android/incremental_install/installer.py
@@ -286,27 +286,12 @@ logging.fatal(args.dont_even_try) return 1 - if args.device: - # Retries are annoying when commands fail for legitimate reasons. Might want - # to enable them if this is ever used on bots though. - device = device_utils.DeviceUtils( - args.device, default_retries=0, enable_device_files_cache=True) - else: - devices = device_utils.DeviceUtils.HealthyDevices( - default_retries=0, enable_device_files_cache=True) - if not devices: - raise device_errors.NoDevicesError() - elif len(devices) == 1: - device = devices[0] - else: - all_devices = device_utils.DeviceUtils.parallel(devices) - msg = ('More than one device available.\n' - 'Use --device=SERIAL to select a device.\n' - 'Available devices:\n') - descriptions = all_devices.pMap(lambda d: d.build_description).pGet(None) - for d, desc in zip(devices, descriptions): - msg += ' %s (%s)\n' % (d, desc) - raise Exception(msg) + # Retries are annoying when commands fail for legitimate reasons. Might want + # to enable them if this is ever used on bots though. + device = device_utils.DeviceUtils.HealthyDevices( + device_arg=args.device, + default_retries=0, + enable_device_files_cache=True)[0] apk = apk_helper.ToHelper(args.apk_path) if args.uninstall:
diff --git a/build/android/lint/OWNERS b/build/android/lint/OWNERS deleted file mode 100644 index cd396e7..0000000 --- a/build/android/lint/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -newt@chromium.org -aurimas@chromium.org
diff --git a/build/android/pylib/constants/__init__.py b/build/android/pylib/constants/__init__.py index f1844df3..2e84cea 100644 --- a/build/android/pylib/constants/__init__.py +++ b/build/android/pylib/constants/__init__.py
@@ -27,106 +27,89 @@ os.pardir, os.pardir, os.pardir, os.pardir))) PackageInfo = collections.namedtuple('PackageInfo', - ['package', 'activity', 'cmdline_file', 'devtools_socket', - 'test_package']) + ['package', 'activity', 'cmdline_file', 'devtools_socket']) PACKAGE_INFO = { 'chrome_document': PackageInfo( 'com.google.android.apps.chrome.document', 'com.google.android.apps.chrome.document.ChromeLauncherActivity', '/data/local/chrome-command-line', - 'chrome_devtools_remote', - None), + 'chrome_devtools_remote'), 'chrome': PackageInfo( 'com.google.android.apps.chrome', 'com.google.android.apps.chrome.Main', '/data/local/chrome-command-line', - 'chrome_devtools_remote', - 'com.google.android.apps.chrome.tests'), + 'chrome_devtools_remote'), 'chrome_beta': PackageInfo( 'com.chrome.beta', 'com.google.android.apps.chrome.Main', '/data/local/chrome-command-line', - 'chrome_devtools_remote', - None), + 'chrome_devtools_remote'), 'chrome_stable': PackageInfo( 'com.android.chrome', 'com.google.android.apps.chrome.Main', '/data/local/chrome-command-line', - 'chrome_devtools_remote', - None), + 'chrome_devtools_remote'), 'chrome_dev': PackageInfo( 'com.chrome.dev', 'com.google.android.apps.chrome.Main', '/data/local/chrome-command-line', - 'chrome_devtools_remote', - None), + 'chrome_devtools_remote'), 'chrome_canary': PackageInfo( 'com.chrome.canary', 'com.google.android.apps.chrome.Main', '/data/local/chrome-command-line', - 'chrome_devtools_remote', - None), + 'chrome_devtools_remote'), 'chrome_work': PackageInfo( 'com.chrome.work', 'com.google.android.apps.chrome.Main', '/data/local/chrome-command-line', - 'chrome_devtools_remote', - None), + 'chrome_devtools_remote'), 'chromium': PackageInfo( 'org.chromium.chrome', 'com.google.android.apps.chrome.Main', '/data/local/chrome-command-line', - 'chrome_devtools_remote', - 'org.chromium.chrome.tests'), + 'chrome_devtools_remote'), 'legacy_browser': PackageInfo( 'com.google.android.browser', 'com.android.browser.BrowserActivity', None, - None, None), 'chromecast_shell': PackageInfo( 'com.google.android.apps.mediashell', 'com.google.android.apps.mediashell.MediaShellActivity', '/data/local/tmp/castshell-command-line', - None, None), 'content_shell': PackageInfo( 'org.chromium.content_shell_apk', 'org.chromium.content_shell_apk.ContentShellActivity', '/data/local/tmp/content-shell-command-line', - None, - 'org.chromium.content_shell_apk.tests'), + None), 'android_webview_shell': PackageInfo( 'org.chromium.android_webview.shell', 'org.chromium.android_webview.shell.AwShellActivity', '/data/local/tmp/android-webview-command-line', - None, - 'org.chromium.android_webview.test'), + None), 'gtest': PackageInfo( 'org.chromium.native_test', 'org.chromium.native_test.NativeUnitTestActivity', '/data/local/tmp/chrome-native-tests-command-line', - None, None), 'components_browsertests': PackageInfo( 'org.chromium.components_browsertests_apk', ('org.chromium.components_browsertests_apk' + '.ComponentsBrowserTestsActivity'), '/data/local/tmp/chrome-native-tests-command-line', - None, None), 'content_browsertests': PackageInfo( 'org.chromium.content_browsertests_apk', 'org.chromium.content_browsertests_apk.ContentBrowserTestsActivity', '/data/local/tmp/chrome-native-tests-command-line', - None, None), 'chromedriver_webview_shell': PackageInfo( 'org.chromium.chromedriver_webview_shell', 'org.chromium.chromedriver_webview_shell.Main', None, - None, None), }
diff --git a/build/android/pylib/instrumentation/instrumentation_test_instance.py b/build/android/pylib/instrumentation/instrumentation_test_instance.py index cd8617c..e9c33f1c 100644 --- a/build/android/pylib/instrumentation/instrumentation_test_instance.py +++ b/build/android/pylib/instrumentation/instrumentation_test_instance.py
@@ -276,9 +276,11 @@ self._test_runner = self._test_apk.GetInstrumentationName() self._package_info = None - for package_info in constants.PACKAGE_INFO.itervalues(): - if self._test_package == package_info.test_package: - self._package_info = package_info + if self._apk_under_test: + package_under_test = self._apk_under_test.GetPackageName() + for package_info in constants.PACKAGE_INFO.itervalues(): + if package_under_test == package_info.package: + self._package_info = package_info if not self._package_info: logging.warning('Unable to find package info for %s', self._test_package)
diff --git a/build/common.gypi b/build/common.gypi index a3b5053..609422e 100644 --- a/build/common.gypi +++ b/build/common.gypi
@@ -2262,7 +2262,8 @@ }], ], 'clang_plugin_args%': '-Xclang -plugin-arg-find-bad-constructs -Xclang check-templates ' - '-Xclang -plugin-arg-find-bad-constructs -Xclang follow-macro-expansion ', + '-Xclang -plugin-arg-find-bad-constructs -Xclang follow-macro-expansion ' + '-Xclang -plugin-arg-find-bad-constructs -Xclang check-implicit-copy-ctors ', }, # If you change these, also change build/config/clang/BUILD.gn. 'clang_chrome_plugins_flags%': @@ -3563,11 +3564,6 @@ 'NS_BLOCK_ASSERTIONS=1', ], }], - # Force disable blink assertions on Cast device builds (overriding DCHECK_ALWAYS_ON) - # Only defined for Release builds (NDEBUG), otherwise blink won't compile. - ['chromecast==1 and OS=="linux" and is_cast_desktop_build==0', { - 'defines': ['ENABLE_ASSERT=0'], - }], ], }, #
diff --git a/build/config/android/config.gni b/build/config/android/config.gni index 16d5373..c5dbb54 100644 --- a/build/config/android/config.gni +++ b/build/config/android/config.gni
@@ -40,9 +40,10 @@ "//third_party/android_tools:google_play_services_default_resources" } + webview_public_framework_jar = + "//third_party/android_platform/webview/frameworks_6.0.jar" if (!defined(webview_framework_jar)) { - webview_framework_jar = - "//third_party/android_platform/webview/frameworks_6.0.jar" + webview_framework_jar = webview_public_framework_jar } declare_args() {
diff --git a/build/config/android/internal_rules.gni b/build/config/android/internal_rules.gni index 50938cd64..c7fed43 100644 --- a/build/config/android/internal_rules.gni +++ b/build/config/android/internal_rules.gni
@@ -93,7 +93,7 @@ "--jar-path", rebase_path(invoker.jar_path, root_build_dir), "--java-files=$_rebased_java_files", - "--classpath=@FileArg($_rebased_build_config:javac:classpath)", + "--classpath=@FileArg($_rebased_build_config:javac:interface_classpath)", ] } }
diff --git a/build/config/clang/BUILD.gn b/build/config/clang/BUILD.gn index b2113b7..c2249f21 100644 --- a/build/config/clang/BUILD.gn +++ b/build/config/clang/BUILD.gn
@@ -44,6 +44,10 @@ "-plugin-arg-find-bad-constructs", "-Xclang", "follow-macro-expansion", + "-Xclang", + "-plugin-arg-find-bad-constructs", + "-Xclang", + "check-implicit-copy-ctors", ] } }
diff --git a/build/config/ios/rules.gni b/build/config/ios/rules.gni index 3265700..171dbf5 100644 --- a/build/config/ios/rules.gni +++ b/build/config/ios/rules.gni
@@ -330,18 +330,6 @@ ] } - _framework_public_config = _target_name + "_public_config" - config(_framework_public_config) { - # TODO(sdefresne): should we have a framework_dirs similar to lib_dirs - # and include_dirs to avoid duplicate values on the command-line. - common_flags = [ "-F" + rebase_path("$root_out_dir/.", root_out_dir) ] - cflags_objc = common_flags - cflags_objcc = common_flags - ldflags = common_flags - lib_dirs = [ root_out_dir ] - libs = [ _framework_name ] - } - group(_framework_headers_target) { deps = [ ":$_compile_headers_map_target", @@ -383,13 +371,9 @@ "public_configs", ]) - deps = [ + public_deps = [ ":$_framework_target", ] - if (!defined(public_configs)) { - public_configs = [] - } - public_configs += [ ":$_framework_public_config" ] } } }
diff --git a/build/config/mac/rules.gni b/build/config/mac/rules.gni index f8ec3613..cdb12d9 100644 --- a/build/config/mac/rules.gni +++ b/build/config/mac/rules.gni
@@ -74,6 +74,19 @@ ] } + _framework_public_config = _target_name + "_public_config" + config(_framework_public_config) { + # TODO(sdefresne): should we have a framework_dirs similar to lib_dirs + # and include_dirs to avoid duplicate values on the command-line. + visibility = [ ":$_framework_target" ] + common_flags = [ "-F" + rebase_path("$root_out_dir/.", root_out_dir) ] + cflags_objc = common_flags + cflags_objcc = common_flags + ldflags = common_flags + lib_dirs = [ root_out_dir ] + libs = [ _framework_name ] + } + create_bundle(_framework_target) { forward_variables_from(invoker, [ @@ -94,6 +107,8 @@ } public_deps += [ ":$_shared_library_bundle_data" ] + public_configs = [ ":$_framework_public_config" ] + bundle_root_dir = _framework_root_dir bundle_resources_dir = "$bundle_root_dir/Resources" bundle_executable_dir = "$bundle_root_dir" @@ -263,3 +278,58 @@ bundle_executable_dir = "$bundle_root_dir/MacOS" } } + +# Template to package a loadable_module into a .plugin bundle. +# +# This takes no extra arguments that differ from a loadable_module. +template("mac_plugin_bundle") { + assert(defined(invoker.deps), + "Dependencies must be specified for $target_name") + + _target_name = target_name + _loadable_module_target = _target_name + "_loadable_module" + _loadable_module_bundle_data = _loadable_module_target + "_bundle_data" + + loadable_module(_loadable_module_target) { + visibility = [ ":$_loadable_module_bundle_data" ] + forward_variables_from(invoker, + "*", + [ + "assert_no_deps", + "data_deps", + "output_name", + "visibility", + ]) + } + + bundle_data(_loadable_module_bundle_data) { + visibility = [ ":$_target_name" ] + sources = [ + "$root_out_dir/${_loadable_module_target}.so", + ] + outputs = [ + "{{bundle_executable_dir}}/$_target_name", + ] + public_deps = [ + ":$_loadable_module_target", + ] + } + + create_bundle(_target_name) { + forward_variables_from(invoker, + [ + "data_deps", + "deps", + "public_deps", + "testonly", + "visibility", + ]) + if (!defined(deps)) { + deps = [] + } + deps += [ ":$_loadable_module_bundle_data" ] + + bundle_root_dir = "$root_out_dir/$_target_name.plugin/Contents" + bundle_executable_dir = "$bundle_root_dir/MacOS" + } +}
diff --git a/build/config/sanitizers/BUILD.gn b/build/config/sanitizers/BUILD.gn index ce48fed..e7e36b5 100644 --- a/build/config/sanitizers/BUILD.gn +++ b/build/config/sanitizers/BUILD.gn
@@ -33,7 +33,9 @@ } config("sanitizer_options_link_helper") { - if (!is_win) { + if (is_mac) { + ldflags = [ "-Wl,-U,_sanitizer_options_link_helper" ] + } else if (!is_win) { ldflags = [ "-Wl,-u_sanitizer_options_link_helper" ] } }
diff --git a/build/gyp_chromium.py b/build/gyp_chromium.py index e491216..fe06bc1 100644 --- a/build/gyp_chromium.py +++ b/build/gyp_chromium.py
@@ -343,7 +343,7 @@ # Off we go... gyp_rc = gyp.main(args) - if not use_analyzer: + if gyp_rc == 0 and not use_analyzer: vs2013_runtime_dll_dirs = vs_toolchain.SetEnvironmentAndGetRuntimeDllDirs() if vs2013_runtime_dll_dirs: x64_runtime, x86_runtime = vs2013_runtime_dll_dirs
diff --git a/build/linux/unbundle/ffmpeg.gyp b/build/linux/unbundle/ffmpeg.gyp index e3c37238..b86a1c4 100644 --- a/build/linux/unbundle/ffmpeg.gyp +++ b/build/linux/unbundle/ffmpeg.gyp
@@ -41,6 +41,17 @@ 'USE_SYSTEM_FFMPEG', ], }, + 'variables': { + 'headers_root_path': '.', + 'header_filenames': [ + 'libavcodec/avcodec.h', + 'libavformat/avformat.h', + 'libavutil/imgutils.h', + ], + }, + 'includes': [ + '../../build/shim_headers.gypi', + ], 'link_settings': { 'ldflags': [ '<!@(pkg-config --libs-only-L --libs-only-other libavcodec libavformat libavutil)',
diff --git a/build/toolchain/gcc_toolchain.gni b/build/toolchain/gcc_toolchain.gni index 77bc16f..6ff2b586 100644 --- a/build/toolchain/gcc_toolchain.gni +++ b/build/toolchain/gcc_toolchain.gni
@@ -475,6 +475,7 @@ "toolchain_cpu", "toolchain_os", "use_gold", + "strip", ]) } }
diff --git a/build/vs_toolchain.py b/build/vs_toolchain.py index 12e8654..1012216 100755 --- a/build/vs_toolchain.py +++ b/build/vs_toolchain.py
@@ -153,12 +153,14 @@ def _CopyRuntimeImpl(target, source, verbose=True): - """Copy |source| to |target| if it doesn't already exist or if it - needs to be updated. + """Copy |source| to |target| if it doesn't already exist or if it needs to be + updated (comparing last modified time as an approximate float match as for + some reason the values tend to differ by ~1e-07 despite being copies of the + same file... https://crbug.com/603603). """ if (os.path.isdir(os.path.dirname(target)) and (not os.path.isfile(target) or - os.stat(target).st_mtime != os.stat(source).st_mtime)): + abs(os.stat(target).st_mtime - os.stat(source).st_mtime) >= 0.01)): if verbose: print 'Copying %s to %s...' % (source, target) if os.path.exists(target): @@ -185,7 +187,6 @@ source = os.path.join(source_dir, dll) _CopyRuntimeImpl(target, source) ucrt_src_dir = os.path.join(source_dir, 'api-ms-win-*.dll') - print 'Copying %s to %s...' % (ucrt_src_dir, target_dir) for ucrt_src_file in glob.glob(ucrt_src_dir): file_part = os.path.basename(ucrt_src_file) ucrt_dst_file = os.path.join(target_dir, file_part)
diff --git a/build/win/copy_cdb_to_output.py b/build/win/copy_cdb_to_output.py index 5cb52b23..1354336 100755 --- a/build/win/copy_cdb_to_output.py +++ b/build/win/copy_cdb_to_output.py
@@ -48,13 +48,13 @@ directory, which is created if it does not exist. The output directory, and target architecture that should be copied, are passed. Supported values for the target architecture are the GYP - values "ia32" and "x64". + values "ia32" and "x64" and the GN values "x86" and "x64". """ if not os.path.isdir(output_dir): os.makedirs(output_dir) vs_toolchain.SetEnvironmentAndGetRuntimeDllDirs() win_sdk_dir = os.path.normpath(os.environ['WINDOWSSDKDIR']) - if target_arch == 'ia32': + if target_arch == 'ia32' or target_arch == 'x86': src_arch = 'x86' elif target_arch == 'x64': src_arch = 'x64'
diff --git a/cc/BUILD.gn b/cc/BUILD.gn index ffe865f..fae8e87 100644 --- a/cc/BUILD.gn +++ b/cc/BUILD.gn
@@ -28,7 +28,6 @@ "animation/keyframed_animation_curve.h", "animation/layer_animation_controller.cc", "animation/layer_animation_controller.h", - "animation/layer_animation_event_observer.h", "animation/layer_animation_value_observer.h", "animation/layer_animation_value_provider.h", "animation/scroll_offset_animation_curve.cc",
diff --git a/cc/animation/animation_host.cc b/cc/animation/animation_host.cc index 824f8a6..482bfd2 100644 --- a/cc/animation/animation_host.cc +++ b/cc/animation/animation_host.cc
@@ -206,14 +206,14 @@ } void AnimationHost::RegisterLayer(int layer_id, LayerTreeType tree_type) { - ElementAnimations* element_animations = + scoped_refptr<ElementAnimations> element_animations = GetElementAnimationsForLayerId(layer_id); if (element_animations) element_animations->LayerRegistered(layer_id, tree_type); } void AnimationHost::UnregisterLayer(int layer_id, LayerTreeType tree_type) { - ElementAnimations* element_animations = + scoped_refptr<ElementAnimations> element_animations = GetElementAnimationsForLayerId(layer_id); if (element_animations) element_animations->LayerUnregistered(layer_id, tree_type); @@ -224,14 +224,12 @@ DCHECK(layer_id); DCHECK(player); - ElementAnimations* element_animations = + scoped_refptr<ElementAnimations> element_animations = GetElementAnimationsForLayerId(layer_id); if (!element_animations) { - auto new_element_animations = ElementAnimations::Create(this); - element_animations = new_element_animations.get(); + element_animations = ElementAnimations::Create(this); + layer_to_element_animations_map_[layer_id] = element_animations; - layer_to_element_animations_map_[layer_id] = - std::move(new_element_animations); element_animations->CreateLayerAnimationController(layer_id); } @@ -244,7 +242,7 @@ DCHECK(layer_id); DCHECK(player); - ElementAnimations* element_animations = + scoped_refptr<ElementAnimations> element_animations = GetElementAnimationsForLayerId(layer_id); DCHECK(element_animations); element_animations->RemovePlayer(player); @@ -252,7 +250,6 @@ if (element_animations->IsEmpty()) { element_animations->DestroyLayerAnimationController(); layer_to_element_animations_map_.erase(layer_id); - element_animations = nullptr; } } @@ -321,17 +318,17 @@ // Secondly, sync properties for created layer animation controllers. for (auto& kv : layer_to_element_animations_map_) { - ElementAnimations* element_animations = kv.second.get(); - ElementAnimations* element_animations_impl = + const auto& element_animations = kv.second; + auto element_animations_impl = host_impl->GetElementAnimationsForLayerId(kv.first); if (element_animations_impl) - element_animations->PushPropertiesTo(element_animations_impl); + element_animations->PushPropertiesTo(std::move(element_animations_impl)); } } LayerAnimationController* AnimationHost::GetControllerForLayerId( int layer_id) const { - const ElementAnimations* element_animations = + const scoped_refptr<ElementAnimations> element_animations = GetElementAnimationsForLayerId(layer_id); if (!element_animations) return nullptr; @@ -339,12 +336,12 @@ return element_animations->layer_animation_controller_.get(); } -ElementAnimations* AnimationHost::GetElementAnimationsForLayerId( +scoped_refptr<ElementAnimations> AnimationHost::GetElementAnimationsForLayerId( int layer_id) const { DCHECK(layer_id); auto iter = layer_to_element_animations_map_.find(layer_id); return iter == layer_to_element_animations_map_.end() ? nullptr - : iter->second.get(); + : iter->second; } void AnimationHost::SetSupportsScrollAnimations(
diff --git a/cc/animation/animation_host.h b/cc/animation/animation_host.h index f2ce2ac7..04d5989 100644 --- a/cc/animation/animation_host.h +++ b/cc/animation/animation_host.h
@@ -61,7 +61,8 @@ void RegisterPlayerForLayer(int layer_id, AnimationPlayer* player); void UnregisterPlayerForLayer(int layer_id, AnimationPlayer* player); - ElementAnimations* GetElementAnimationsForLayerId(int layer_id) const; + scoped_refptr<ElementAnimations> GetElementAnimationsForLayerId( + int layer_id) const; // TODO(loyso): Get rid of LayerAnimationController. LayerAnimationController* GetControllerForLayerId(int layer_id) const; @@ -179,11 +180,10 @@ void EraseTimeline(scoped_refptr<AnimationTimeline> timeline); - // TODO(loyso): For now AnimationPlayers share LayerAnimationController object - // if they are attached to the same element(layer). Note that Element can - // contain many Layers. + // AnimationPlayers share ElementAnimations object if they are attached to the + // same element(layer). Note that Element can contain many Layers. using LayerToElementAnimationsMap = - std::unordered_map<int, std::unique_ptr<ElementAnimations>>; + std::unordered_map<int, scoped_refptr<ElementAnimations>>; LayerToElementAnimationsMap layer_to_element_animations_map_; // A list of all timelines which this host owns.
diff --git a/cc/animation/animation_player.cc b/cc/animation/animation_player.cc index 73eff56..218c9ad 100644 --- a/cc/animation/animation_player.cc +++ b/cc/animation/animation_player.cc
@@ -7,7 +7,6 @@ #include "cc/animation/animation_delegate.h" #include "cc/animation/animation_host.h" #include "cc/animation/animation_timeline.h" -#include "cc/animation/element_animations.h" #include "cc/animation/layer_animation_controller.h" namespace cc {
diff --git a/cc/animation/animation_player.h b/cc/animation/animation_player.h index 301e932..92fca11b 100644 --- a/cc/animation/animation_player.h +++ b/cc/animation/animation_player.h
@@ -13,6 +13,7 @@ #include "base/time/time.h" #include "cc/animation/animation.h" #include "cc/animation/animation_curve.h" +#include "cc/animation/element_animations.h" #include "cc/base/cc_export.h" namespace cc { @@ -56,8 +57,9 @@ void SetAnimationTimeline(AnimationTimeline* timeline); // ElementAnimations object where this player is listed. - // ElementAnimations has a reference to shared LayerAnimationController. - ElementAnimations* element_animations() const { return element_animations_; } + scoped_refptr<ElementAnimations> element_animations() const { + return element_animations_; + } void set_layer_animation_delegate(AnimationDelegate* delegate) { layer_animation_delegate_ = delegate; @@ -117,7 +119,7 @@ AnimationHost* animation_host_; AnimationTimeline* animation_timeline_; // element_animations isn't null if player attached to an element (layer). - ElementAnimations* element_animations_; + scoped_refptr<ElementAnimations> element_animations_; AnimationDelegate* layer_animation_delegate_; int id_;
diff --git a/cc/animation/element_animations.cc b/cc/animation/element_animations.cc index 3eab9e7..6cf9ea3 100644 --- a/cc/animation/element_animations.cc +++ b/cc/animation/element_animations.cc
@@ -12,9 +12,9 @@ namespace cc { -std::unique_ptr<ElementAnimations> ElementAnimations::Create( +scoped_refptr<ElementAnimations> ElementAnimations::Create( AnimationHost* host) { - return base::WrapUnique(new ElementAnimations(host)); + return make_scoped_refptr(new ElementAnimations(host)); } ElementAnimations::ElementAnimations(AnimationHost* host) @@ -103,7 +103,7 @@ } void ElementAnimations::PushPropertiesTo( - ElementAnimations* element_animations_impl) { + scoped_refptr<ElementAnimations> element_animations_impl) { DCHECK(layer_animation_controller_); DCHECK(element_animations_impl->layer_animation_controller_); @@ -143,16 +143,6 @@ return layer_animation_controller_->GetAnimationById(animation_id); } -void ElementAnimations::AddEventObserver( - LayerAnimationEventObserver* observer) { - layer_animation_controller_->AddEventObserver(observer); -} - -void ElementAnimations::RemoveEventObserver( - LayerAnimationEventObserver* observer) { - layer_animation_controller_->RemoveEventObserver(observer); -} - void ElementAnimations::OnFilterAnimated(LayerTreeType tree_type, const FilterOperations& filters) { DCHECK(layer_id()); @@ -191,8 +181,8 @@ } void ElementAnimations::OnAnimationWaitingForDeletion() { - // TODO(loyso): See Layer::OnAnimationWaitingForDeletion. But we always do - // PushProperties for AnimationTimelines for now. + // TODO(loyso): Invalidate AnimationHost::SetNeedsPushProperties here. + // But we always do PushProperties in AnimationHost for now. crbug.com/604280 } void ElementAnimations::OnTransformIsPotentiallyAnimatingChanged(
diff --git a/cc/animation/element_animations.h b/cc/animation/element_animations.h index bff3661b..4214f317 100644 --- a/cc/animation/element_animations.h +++ b/cc/animation/element_animations.h
@@ -37,12 +37,12 @@ // of animation layers. // This is a CC counterpart for blink::ElementAnimations (in 1:1 relationship). // No pointer to/from respective blink::ElementAnimations object for now. -class CC_EXPORT ElementAnimations : public AnimationDelegate, +class CC_EXPORT ElementAnimations : public base::RefCounted<ElementAnimations>, + public AnimationDelegate, public LayerAnimationValueObserver, public LayerAnimationValueProvider { public: - static std::unique_ptr<ElementAnimations> Create(AnimationHost* host); - ~ElementAnimations() override; + static scoped_refptr<ElementAnimations> Create(AnimationHost* host); int layer_id() const { return layer_animation_controller_ ? layer_animation_controller_->id() : 0; @@ -73,7 +73,8 @@ typedef base::LinkNode<AnimationPlayer> PlayersListNode; const PlayersList& players_list() const { return *players_list_.get(); } - void PushPropertiesTo(ElementAnimations* element_animations_impl); + void PushPropertiesTo( + scoped_refptr<ElementAnimations> element_animations_impl); void AddAnimation(std::unique_ptr<Animation> animation); void PauseAnimation(int animation_id, base::TimeDelta time_offset); @@ -89,14 +90,14 @@ // Returns the active animation for the given unique animation id. Animation* GetAnimationById(int animation_id) const; - void AddEventObserver(LayerAnimationEventObserver* observer); - void RemoveEventObserver(LayerAnimationEventObserver* observer); - private: + friend class base::RefCounted<ElementAnimations>; + // TODO(loyso): Erase this when LAC merged into ElementAnimations. friend class AnimationHost; explicit ElementAnimations(AnimationHost* host); + ~ElementAnimations() override; // LayerAnimationValueObserver implementation. void OnFilterAnimated(LayerTreeType tree_type,
diff --git a/cc/animation/element_animations_unittest.cc b/cc/animation/element_animations_unittest.cc index ed51918..90c622a3 100644 --- a/cc/animation/element_animations_unittest.cc +++ b/cc/animation/element_animations_unittest.cc
@@ -37,7 +37,8 @@ timeline_->AttachPlayer(player_); player_->AttachLayer(layer_id_); - ElementAnimations* element_animations = player_->element_animations(); + scoped_refptr<ElementAnimations> element_animations = + player_->element_animations(); EXPECT_TRUE(element_animations); EXPECT_TRUE(element_animations->needs_active_value_observations()); @@ -47,7 +48,7 @@ GetImplTimelineAndPlayerByID(); - ElementAnimations* element_animations_impl = + scoped_refptr<ElementAnimations> element_animations_impl = player_impl_->element_animations(); EXPECT_TRUE(element_animations_impl); @@ -109,7 +110,8 @@ player_->AttachLayer(layer_id_); - ElementAnimations* element_animations = player_->element_animations(); + scoped_refptr<ElementAnimations> element_animations = + player_->element_animations(); EXPECT_TRUE(element_animations); EXPECT_FALSE(element_animations->needs_active_value_observations()); @@ -117,7 +119,7 @@ host_->PushPropertiesTo(host_impl_); - ElementAnimations* element_animations_impl = + scoped_refptr<ElementAnimations> element_animations_impl = player_impl_->element_animations(); EXPECT_TRUE(element_animations_impl); @@ -143,7 +145,8 @@ timeline_->AttachPlayer(player_); player_->AttachLayer(layer_id_); - ElementAnimations* element_animations = player_->element_animations(); + scoped_refptr<ElementAnimations> element_animations = + player_->element_animations(); EXPECT_TRUE(element_animations); scoped_refptr<AnimationPlayer> player1 = @@ -164,7 +167,7 @@ host_->PushPropertiesTo(host_impl_); GetImplTimelineAndPlayerByID(); - ElementAnimations* element_animations_impl = + scoped_refptr<ElementAnimations> element_animations_impl = player_impl_->element_animations(); EXPECT_TRUE(element_animations_impl);
diff --git a/cc/animation/layer_animation_controller.cc b/cc/animation/layer_animation_controller.cc index b2130b8..21a88508 100644 --- a/cc/animation/layer_animation_controller.cc +++ b/cc/animation/layer_animation_controller.cc
@@ -390,8 +390,6 @@ void LayerAnimationController::NotifyAnimationStarted( const AnimationEvent& event) { if (event.is_impl_only) { - FOR_EACH_OBSERVER(LayerAnimationEventObserver, event_observers_, - OnAnimationStarted(event)); if (layer_animation_delegate_) layer_animation_delegate_->NotifyAnimationStarted( event.monotonic_time, event.target_property, event.group_id); @@ -406,8 +404,6 @@ if (!animations_[i]->has_set_start_time()) animations_[i]->set_start_time(event.monotonic_time); - FOR_EACH_OBSERVER(LayerAnimationEventObserver, event_observers_, - OnAnimationStarted(event)); if (layer_animation_delegate_) layer_animation_delegate_->NotifyAnimationStarted( event.monotonic_time, event.target_property, event.group_id); @@ -488,17 +484,6 @@ } } -void LayerAnimationController::AddEventObserver( - LayerAnimationEventObserver* observer) { - if (!event_observers_.HasObserver(observer)) - event_observers_.AddObserver(observer); -} - -void LayerAnimationController::RemoveEventObserver( - LayerAnimationEventObserver* observer) { - event_observers_.RemoveObserver(observer); -} - bool LayerAnimationController::HasFilterAnimationThatInflatesBounds() const { for (size_t i = 0; i < animations_.size(); ++i) { if (!animations_[i]->is_finished() &&
diff --git a/cc/animation/layer_animation_controller.h b/cc/animation/layer_animation_controller.h index 323a069..8dd1f51 100644 --- a/cc/animation/layer_animation_controller.h +++ b/cc/animation/layer_animation_controller.h
@@ -11,10 +11,9 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/observer_list.h" #include "base/time/time.h" #include "cc/animation/animation.h" -#include "cc/animation/layer_animation_event_observer.h" +#include "cc/animation/animation_events.h" #include "cc/animation/target_property.h" #include "cc/base/cc_export.h" #include "ui/gfx/geometry/scroll_offset.h" @@ -121,9 +120,6 @@ needs_pending_value_observations_ = needs_pending_value_observations; } - void AddEventObserver(LayerAnimationEventObserver* observer); - void RemoveEventObserver(LayerAnimationEventObserver* observer); - void set_value_provider(LayerAnimationValueProvider* provider) { value_provider_ = provider; } @@ -169,8 +165,7 @@ // Sets |max_scale| to the maximum scale along any dimension at any // destination in active animations. Returns false if the maximum scale cannot // be computed. - bool MaximumTargetScale(ObserverType event_observers_, - float* max_scale) const; + bool MaximumTargetScale(ObserverType observer_type, float* max_scale) const; // When a scroll animation is removed on the main thread, its compositor // thread counterpart continues producing scroll deltas until activation. @@ -252,7 +247,6 @@ base::TimeTicks last_tick_time_; - base::ObserverList<LayerAnimationEventObserver> event_observers_; LayerAnimationValueObserver* value_observer_; LayerAnimationValueProvider* value_provider_; AnimationDelegate* layer_animation_delegate_;
diff --git a/cc/animation/layer_animation_controller_unittest.cc b/cc/animation/layer_animation_controller_unittest.cc index cbea341..095ed3a8 100644 --- a/cc/animation/layer_animation_controller_unittest.cc +++ b/cc/animation/layer_animation_controller_unittest.cc
@@ -1208,62 +1208,6 @@ EXPECT_EQ(start_time, delegate.start_time()); } -class FakeLayerAnimationEventObserver : public LayerAnimationEventObserver { - public: - FakeLayerAnimationEventObserver() : start_time_(base::TimeTicks()) {} - - void OnAnimationStarted(const AnimationEvent& event) override { - start_time_ = event.monotonic_time; - } - - TimeTicks start_time() { return start_time_; } - - private: - TimeTicks start_time_; -}; - -// Tests that specified start times are sent to the event observers -TEST(LayerAnimationControllerTest, SpecifiedStartTimesAreSentToEventObservers) { - FakeLayerAnimationValueObserver dummy_impl; - scoped_refptr<LayerAnimationController> controller_impl( - LayerAnimationController::Create(0)); - controller_impl->set_value_observer(&dummy_impl); - controller_impl->set_needs_active_value_observations(true); - - FakeLayerAnimationValueObserver dummy; - scoped_refptr<LayerAnimationController> controller( - LayerAnimationController::Create(0)); - controller->set_value_observer(&dummy); - controller->set_needs_active_value_observations(true); - - FakeLayerAnimationEventObserver observer; - controller->AddEventObserver(&observer); - - int animation_id = - AddOpacityTransitionToController(controller.get(), 1, 0, 1, false); - - const TimeTicks start_time = TicksFromSecondsF(123); - controller->GetAnimation(TargetProperty::OPACITY)->set_start_time(start_time); - - controller->PushAnimationUpdatesTo(controller_impl.get()); - controller_impl->ActivateAnimations(); - - EXPECT_TRUE(controller_impl->GetAnimationById(animation_id)); - EXPECT_EQ(Animation::WAITING_FOR_TARGET_AVAILABILITY, - controller_impl->GetAnimationById(animation_id)->run_state()); - - AnimationEvents events; - controller_impl->Animate(kInitialTickTime); - controller_impl->UpdateState(true, &events); - - // Synchronize the start times. - EXPECT_EQ(1u, events.events_.size()); - controller->NotifyAnimationStarted(events.events_[0]); - - // Validate start time on the event observer. - EXPECT_EQ(start_time, observer.start_time()); -} - // Tests animations that are waiting for a synchronized start time do not // finish. TEST(LayerAnimationControllerTest,
diff --git a/cc/animation/layer_animation_event_observer.h b/cc/animation/layer_animation_event_observer.h deleted file mode 100644 index 93d606e..0000000 --- a/cc/animation/layer_animation_event_observer.h +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CC_ANIMATION_LAYER_ANIMATION_EVENT_OBSERVER_H_ -#define CC_ANIMATION_LAYER_ANIMATION_EVENT_OBSERVER_H_ - -#include "cc/base/cc_export.h" - -namespace cc { - -struct AnimationEvent; - -class CC_EXPORT LayerAnimationEventObserver { - public: - virtual void OnAnimationStarted(const AnimationEvent& event) = 0; - - protected: - virtual ~LayerAnimationEventObserver() {} -}; - -} // namespace cc - -#endif // CC_ANIMATION_LAYER_ANIMATION_EVENT_OBSERVER_H_ -
diff --git a/cc/cc.gyp b/cc/cc.gyp index 3c735ca..7b29a6e 100644 --- a/cc/cc.gyp +++ b/cc/cc.gyp
@@ -56,7 +56,6 @@ 'animation/keyframed_animation_curve.h', 'animation/layer_animation_controller.cc', 'animation/layer_animation_controller.h', - 'animation/layer_animation_event_observer.h', 'animation/layer_animation_value_observer.h', 'animation/layer_animation_value_provider.h', 'animation/scroll_offset_animation_curve.cc',
diff --git a/cc/layers/layer_list_iterator.cc b/cc/layers/layer_list_iterator.cc index e71238d6..ec72899 100644 --- a/cc/layers/layer_list_iterator.cc +++ b/cc/layers/layer_list_iterator.cc
@@ -4,42 +4,45 @@ #include "cc/layers/layer_list_iterator.h" +#include "cc/layers/layer.h" #include "cc/layers/layer_impl.h" namespace cc { -LayerListIterator::LayerListIterator(LayerImpl* root_layer) +template <typename LayerType> +LayerListIterator<LayerType>::LayerListIterator(LayerType* root_layer) : current_layer_(root_layer) { DCHECK(!root_layer || !root_layer->parent()); list_indices_.push_back(0); } -LayerListIterator::LayerListIterator(const LayerListIterator& other) = default; +template <typename LayerType> +LayerListIterator<LayerType>::LayerListIterator( + const LayerListIterator<LayerType>& other) = default; -LayerListIterator::~LayerListIterator() {} +template <typename LayerType> +LayerListIterator<LayerType>::~LayerListIterator() {} -LayerListIterator& LayerListIterator::operator++() { +template <typename LayerType> +LayerListIterator<LayerType>& LayerListIterator<LayerType>::operator++() { // case 0: done if (!current_layer_) return *this; // case 1: descend. - const LayerImplList& current_list = current_layer_->children(); - if (!current_list.empty()) { - current_layer_ = current_list[0]; + if (!current_layer_->children().empty()) { + current_layer_ = current_layer_->child_at(0); list_indices_.push_back(0); return *this; } - for (LayerImpl* parent = current_layer_->parent(); parent; + for (LayerType* parent = current_layer_->parent(); parent; parent = parent->parent()) { // We now try and advance in some list of siblings. - const LayerImplList& sibling_list = parent->children(); - // case 2: Advance to a sibling. - if (list_indices_.back() + 1 < sibling_list.size()) { + if (list_indices_.back() + 1 < parent->children().size()) { ++list_indices_.back(); - current_layer_ = sibling_list[list_indices_.back()]; + current_layer_ = parent->child_at(list_indices_.back()); return *this; } @@ -51,48 +54,58 @@ return *this; } -LayerListReverseIterator::LayerListReverseIterator(LayerImpl* root_layer) - : LayerListIterator(root_layer) { +template <typename LayerType> +LayerListReverseIterator<LayerType>::LayerListReverseIterator( + LayerType* root_layer) + : LayerListIterator<LayerType>(root_layer) { DescendToRightmostInSubtree(); } -LayerListReverseIterator::~LayerListReverseIterator() {} +template <typename LayerType> +LayerListReverseIterator<LayerType>::~LayerListReverseIterator() {} // We will only support prefix increment. -LayerListIterator& LayerListReverseIterator::operator++() { +template <typename LayerType> +LayerListIterator<LayerType>& LayerListReverseIterator<LayerType>:: +operator++() { // case 0: done - if (!current_layer_) + if (!current_layer()) return *this; // case 1: we're the leftmost sibling. - if (!list_indices_.back()) { - list_indices_.pop_back(); - current_layer_ = current_layer_->parent(); + if (!list_indices().back()) { + list_indices().pop_back(); + this->current_layer_ = current_layer()->parent(); return *this; } // case 2: we're not the leftmost sibling. In this case, we want to move one // sibling over, and then descend to the rightmost descendant in that subtree. - CHECK(current_layer_->parent()); - --list_indices_.back(); - const LayerImplList& parent_list = current_layer_->parent()->children(); - current_layer_ = parent_list[list_indices_.back()]; + CHECK(current_layer()->parent()); + --list_indices().back(); + this->current_layer_ = + current_layer()->parent()->child_at(list_indices().back()); DescendToRightmostInSubtree(); return *this; } -void LayerListReverseIterator::DescendToRightmostInSubtree() { - if (!current_layer_) +template <typename LayerType> +void LayerListReverseIterator<LayerType>::DescendToRightmostInSubtree() { + if (!current_layer()) return; - const LayerImplList& current_list = current_layer_->children(); - if (current_list.empty()) + if (current_layer()->children().empty()) return; - size_t last_index = current_list.size() - 1; - current_layer_ = current_list[last_index]; - list_indices_.push_back(last_index); + size_t last_index = current_layer()->children().size() - 1; + this->current_layer_ = current_layer()->child_at(last_index); + list_indices().push_back(last_index); DescendToRightmostInSubtree(); } +template class LayerListIterator<Layer>; +template class LayerListIterator<LayerImpl>; +template class LayerListReverseIterator<Layer>; +template class LayerListReverseIterator<LayerImpl>; + } // namespace cc
diff --git a/cc/layers/layer_list_iterator.h b/cc/layers/layer_list_iterator.h index bdc4a4a4..948ec25e 100644 --- a/cc/layers/layer_list_iterator.h +++ b/cc/layers/layer_list_iterator.h
@@ -12,6 +12,7 @@ namespace cc { +class Layer; class LayerImpl; // Unlike LayerIterator and friends, these iterators are not intended to permit @@ -19,43 +20,47 @@ // stacking order. All recursive walks over the LayerImpl tree should be // switched to use these classes instead as the concept of a LayerImpl tree is // deprecated. +template <typename LayerType> class CC_EXPORT LayerListIterator { public: - explicit LayerListIterator(LayerImpl* root_layer); - LayerListIterator(const LayerListIterator& other); + explicit LayerListIterator(LayerType* root_layer); + LayerListIterator(const LayerListIterator<LayerType>& other); virtual ~LayerListIterator(); - bool operator==(const LayerListIterator& other) const { + bool operator==(const LayerListIterator<LayerType>& other) const { return current_layer_ == other.current_layer_; } - bool operator!=(const LayerListIterator& other) const { + bool operator!=(const LayerListIterator<LayerType>& other) const { return !(*this == other); } // We will only support prefix increment. virtual LayerListIterator& operator++(); - LayerImpl* operator->() const { return current_layer_; } - LayerImpl* operator*() const { return current_layer_; } + LayerType* operator->() const { return current_layer_; } + LayerType* operator*() const { return current_layer_; } protected: // The implementation of this iterator is currently tied tightly to the layer // tree, but it should be straightforward to reimplement in terms of a list // when it's ready. - LayerImpl* current_layer_; + LayerType* current_layer_; std::vector<size_t> list_indices_; }; -class CC_EXPORT LayerListReverseIterator : public LayerListIterator { +template <typename LayerType> +class CC_EXPORT LayerListReverseIterator : public LayerListIterator<LayerType> { public: - explicit LayerListReverseIterator(LayerImpl* root_layer); + explicit LayerListReverseIterator(LayerType* root_layer); ~LayerListReverseIterator() override; // We will only support prefix increment. - LayerListIterator& operator++() override; + LayerListIterator<LayerType>& operator++() override; private: void DescendToRightmostInSubtree(); + LayerType* current_layer() { return this->current_layer_; } + std::vector<size_t>& list_indices() { return this->list_indices_; } }; } // namespace cc
diff --git a/cc/layers/layer_list_iterator_unittest.cc b/cc/layers/layer_list_iterator_unittest.cc index d098509..503c1e6 100644 --- a/cc/layers/layer_list_iterator_unittest.cc +++ b/cc/layers/layer_list_iterator_unittest.cc
@@ -8,6 +8,7 @@ #include "base/containers/adapters.h" #include "cc/test/fake_impl_task_runner_provider.h" +#include "cc/test/fake_layer_tree_host.h" #include "cc/test/fake_layer_tree_host_impl.h" #include "cc/test/fake_output_surface.h" #include "cc/test/test_shared_bitmap_manager.h" @@ -18,8 +19,184 @@ namespace cc { namespace { +// Layer version unit tests + TEST(LayerListIteratorTest, VerifyTraversalOrder) { // Unfortunate preamble. + FakeLayerTreeHostClient client(FakeLayerTreeHostClient::DIRECT_3D); + TestTaskGraphRunner task_graph_runner; + std::unique_ptr<FakeLayerTreeHost> host_ptr = + FakeLayerTreeHost::Create(&client, &task_graph_runner); + FakeLayerTreeHost* host = host_ptr.get(); + + // This test constructs the following tree. + // 1 + // +-2 + // | +-3 + // | +-4 + // + 5 + // +-6 + // +-7 + // We expect to visit all seven layers in that order. + scoped_refptr<Layer> layer1 = Layer::Create(); + scoped_refptr<Layer> layer2 = Layer::Create(); + scoped_refptr<Layer> layer3 = Layer::Create(); + scoped_refptr<Layer> layer4 = Layer::Create(); + scoped_refptr<Layer> layer5 = Layer::Create(); + scoped_refptr<Layer> layer6 = Layer::Create(); + scoped_refptr<Layer> layer7 = Layer::Create(); + + std::unordered_map<int, int> layer_id_to_order; + layer_id_to_order[layer1->id()] = 1; + layer_id_to_order[layer2->id()] = 2; + layer_id_to_order[layer3->id()] = 3; + layer_id_to_order[layer4->id()] = 4; + layer_id_to_order[layer5->id()] = 5; + layer_id_to_order[layer6->id()] = 6; + layer_id_to_order[layer7->id()] = 7; + + layer2->AddChild(std::move(layer3)); + layer2->AddChild(std::move(layer4)); + + layer5->AddChild(std::move(layer6)); + layer5->AddChild(std::move(layer7)); + + layer1->AddChild(std::move(layer2)); + layer1->AddChild(std::move(layer5)); + + host->SetRootLayer(std::move(layer1)); + + int i = 1; + for (auto* layer : *host) { + EXPECT_EQ(i++, layer_id_to_order[layer->id()]); + } + EXPECT_EQ(8, i); +} + +TEST(LayerListIteratorTest, VerifySingleLayer) { + // Unfortunate preamble. + FakeLayerTreeHostClient client(FakeLayerTreeHostClient::DIRECT_3D); + TestTaskGraphRunner task_graph_runner; + std::unique_ptr<FakeLayerTreeHost> host_ptr = + FakeLayerTreeHost::Create(&client, &task_graph_runner); + FakeLayerTreeHost* host = host_ptr.get(); + + // This test constructs a tree consisting of a single layer. + scoped_refptr<Layer> layer1 = Layer::Create(); + std::unordered_map<int, int> layer_id_to_order; + layer_id_to_order[layer1->id()] = 1; + host->SetRootLayer(std::move(layer1)); + + int i = 1; + for (auto* layer : *host) { + EXPECT_EQ(i++, layer_id_to_order[layer->id()]); + } + EXPECT_EQ(2, i); +} + +TEST(LayerListIteratorTest, VerifyNullFirstLayer) { + // Ensures that if an iterator is constructed with a nullptr, that it can be + // iterated without issue and that it remains equal to any other + // null-initialized iterator. + LayerListIterator<Layer> it(nullptr); + LayerListIterator<Layer> end(nullptr); + + EXPECT_EQ(it, end); + ++it; + EXPECT_EQ(it, end); +} + +TEST(LayerListReverseIteratorTest, VerifyTraversalOrder) { + // Unfortunate preamble. + FakeLayerTreeHostClient client(FakeLayerTreeHostClient::DIRECT_3D); + TestTaskGraphRunner task_graph_runner; + std::unique_ptr<FakeLayerTreeHost> host_ptr = + FakeLayerTreeHost::Create(&client, &task_graph_runner); + FakeLayerTreeHost* host = host_ptr.get(); + + // This test constructs the following tree. + // 1 + // +-2 + // | +-3 + // | +-4 + // + 5 + // +-6 + // +-7 + // We expect to visit all seven layers in reverse order. + scoped_refptr<Layer> layer1 = Layer::Create(); + scoped_refptr<Layer> layer2 = Layer::Create(); + scoped_refptr<Layer> layer3 = Layer::Create(); + scoped_refptr<Layer> layer4 = Layer::Create(); + scoped_refptr<Layer> layer5 = Layer::Create(); + scoped_refptr<Layer> layer6 = Layer::Create(); + scoped_refptr<Layer> layer7 = Layer::Create(); + + std::unordered_map<int, int> layer_id_to_order; + layer_id_to_order[layer1->id()] = 1; + layer_id_to_order[layer2->id()] = 2; + layer_id_to_order[layer3->id()] = 3; + layer_id_to_order[layer4->id()] = 4; + layer_id_to_order[layer5->id()] = 5; + layer_id_to_order[layer6->id()] = 6; + layer_id_to_order[layer7->id()] = 7; + + layer2->AddChild(std::move(layer3)); + layer2->AddChild(std::move(layer4)); + + layer5->AddChild(std::move(layer6)); + layer5->AddChild(std::move(layer7)); + + layer1->AddChild(std::move(layer2)); + layer1->AddChild(std::move(layer5)); + + host->SetRootLayer(std::move(layer1)); + + int i = 7; + + for (auto* layer : base::Reversed(*host)) { + EXPECT_EQ(i--, layer_id_to_order[layer->id()]); + } + + EXPECT_EQ(0, i); +} + +TEST(LayerListReverseIteratorTest, VerifySingleLayer) { + // Unfortunate preamble. + FakeLayerTreeHostClient client(FakeLayerTreeHostClient::DIRECT_3D); + TestTaskGraphRunner task_graph_runner; + std::unique_ptr<FakeLayerTreeHost> host_ptr = + FakeLayerTreeHost::Create(&client, &task_graph_runner); + FakeLayerTreeHost* host = host_ptr.get(); + + // This test constructs a tree consisting of a single layer. + scoped_refptr<Layer> layer1 = Layer::Create(); + std::unordered_map<int, int> layer_id_to_order; + layer_id_to_order[layer1->id()] = 1; + host->SetRootLayer(std::move(layer1)); + + int i = 1; + for (auto* layer : base::Reversed(*host)) { + EXPECT_EQ(i--, layer_id_to_order[layer->id()]); + } + EXPECT_EQ(0, i); +} + +TEST(LayerListReverseIteratorTest, VerifyNullFirstLayer) { + // Ensures that if an iterator is constructed with a nullptr, that it can be + // iterated without issue and that it remains equal to any other + // null-initialized iterator. + LayerListReverseIterator<Layer> it(nullptr); + LayerListReverseIterator<Layer> end(nullptr); + + EXPECT_EQ(it, end); + ++it; + EXPECT_EQ(it, end); +} + +// LayerImpl version unit tests + +TEST(LayerListIteratorTest, VerifyTraversalOrderImpl) { + // Unfortunate preamble. FakeImplTaskRunnerProvider task_runner_provider; TestSharedBitmapManager shared_bitmap_manager; TestTaskGraphRunner task_graph_runner; @@ -71,7 +248,7 @@ EXPECT_EQ(8, i); } -TEST(LayerListIteratorTest, VerifySingleLayer) { +TEST(LayerListIteratorTest, VerifySingleLayerImpl) { // Unfortunate preamble. FakeImplTaskRunnerProvider task_runner_provider; TestSharedBitmapManager shared_bitmap_manager; @@ -94,19 +271,19 @@ EXPECT_EQ(2, i); } -TEST(LayerListIteratorTest, VerifyNullFirstLayer) { +TEST(LayerListIteratorTest, VerifyNullFirstLayerImpl) { // Ensures that if an iterator is constructed with a nullptr, that it can be // iterated without issue and that it remains equal to any other // null-initialized iterator. - LayerListIterator it(nullptr); - LayerListIterator end(nullptr); + LayerListIterator<LayerImpl> it(nullptr); + LayerListIterator<LayerImpl> end(nullptr); EXPECT_EQ(it, end); ++it; EXPECT_EQ(it, end); } -TEST(LayerListReverseIteratorTest, VerifyTraversalOrder) { +TEST(LayerListReverseIteratorTest, VerifyTraversalOrderImpl) { // Unfortunate preamble. FakeImplTaskRunnerProvider task_runner_provider; TestSharedBitmapManager shared_bitmap_manager; @@ -161,7 +338,7 @@ EXPECT_EQ(0, i); } -TEST(LayerListReverseIteratorTest, VerifySingleLayer) { +TEST(LayerListReverseIteratorTest, VerifySingleLayerImpl) { // Unfortunate preamble. FakeImplTaskRunnerProvider task_runner_provider; TestSharedBitmapManager shared_bitmap_manager; @@ -184,12 +361,12 @@ EXPECT_EQ(0, i); } -TEST(LayerListReverseIteratorTest, VerifyNullFirstLayer) { +TEST(LayerListReverseIteratorTest, VerifyNullFirstLayerImpl) { // Ensures that if an iterator is constructed with a nullptr, that it can be // iterated without issue and that it remains equal to any other // null-initialized iterator. - LayerListReverseIterator it(nullptr); - LayerListReverseIterator end(nullptr); + LayerListReverseIterator<LayerImpl> it(nullptr); + LayerListReverseIterator<LayerImpl> end(nullptr); EXPECT_EQ(it, end); ++it;
diff --git a/cc/output/filter_operation.cc b/cc/output/filter_operation.cc index 37ff871..72c0371 100644 --- a/cc/output/filter_operation.cc +++ b/cc/output/filter_operation.cc
@@ -293,14 +293,11 @@ break; case FilterOperation::REFERENCE: { int count_inputs = 0; - bool can_filter_image_gpu = false; if (image_filter_) { count_inputs = image_filter_->countInputs(); - can_filter_image_gpu = image_filter_->canFilterImageGPU(); } value->SetBoolean("is_null", !image_filter_); value->SetInteger("count_inputs", count_inputs); - value->SetBoolean("can_filter_image_gpu", can_filter_image_gpu); break; } case FilterOperation::ALPHA_THRESHOLD: {
diff --git a/cc/raster/one_copy_tile_task_worker_pool.cc b/cc/raster/one_copy_tile_task_worker_pool.cc index 1c14fb94..de1ab4d 100644 --- a/cc/raster/one_copy_tile_task_worker_pool.cc +++ b/cc/raster/one_copy_tile_task_worker_pool.cc
@@ -335,8 +335,8 @@ gl->CompressedCopyTextureCHROMIUM(staging_buffer->texture_id, resource_lock->texture_id()); } else { - int bytes_per_row = - (BitsPerPixel(resource->format()) * resource->size().width()) / 8; + int bytes_per_row = ResourceUtil::UncheckedWidthInBytes<int>( + resource->size().width(), resource->format()); int chunk_size_in_rows = std::max(1, max_bytes_per_copy_operation_ / bytes_per_row); // Align chunk size to 4. Required to support compressed texture formats.
diff --git a/cc/resources/resource_provider.cc b/cc/resources/resource_provider.cc index fa9fa859d..5b277f0 100644 --- a/cc/resources/resource_provider.cc +++ b/cc/resources/resource_provider.cc
@@ -221,7 +221,7 @@ gl_pixel_buffer_id(0), gl_upload_query_id(0), gl_read_lock_query_id(0), - pixels(NULL), + pixels(nullptr), lock_for_read_count(0), imported_count(0), exported_count(0), @@ -233,7 +233,7 @@ read_lock_fences_enabled(false), has_shared_bitmap_id(false), is_overlay_candidate(false), - read_lock_fence(NULL), + read_lock_fence(nullptr), size(size), origin(origin), target(target), @@ -244,8 +244,7 @@ hint(hint), type(type), format(format), - shared_bitmap(NULL), - gpu_memory_buffer(NULL) {} + shared_bitmap(nullptr) {} ResourceProvider::Resource::Resource(uint8_t* pixels, SharedBitmap* bitmap, @@ -269,7 +268,7 @@ read_lock_fences_enabled(false), has_shared_bitmap_id(!!bitmap), is_overlay_candidate(false), - read_lock_fence(NULL), + read_lock_fence(nullptr), size(size), origin(origin), target(0), @@ -280,8 +279,7 @@ hint(TEXTURE_HINT_IMMUTABLE), type(RESOURCE_TYPE_BITMAP), format(RGBA_8888), - shared_bitmap(bitmap), - gpu_memory_buffer(NULL) { + shared_bitmap(bitmap) { DCHECK(origin == DELEGATED || pixels); if (bitmap) shared_bitmap_id = bitmap->id(); @@ -296,7 +294,7 @@ gl_pixel_buffer_id(0), gl_upload_query_id(0), gl_read_lock_query_id(0), - pixels(NULL), + pixels(nullptr), lock_for_read_count(0), imported_count(0), exported_count(0), @@ -308,7 +306,7 @@ read_lock_fences_enabled(false), has_shared_bitmap_id(true), is_overlay_candidate(false), - read_lock_fence(NULL), + read_lock_fence(nullptr), size(size), origin(origin), target(0), @@ -320,10 +318,9 @@ type(RESOURCE_TYPE_BITMAP), format(RGBA_8888), shared_bitmap_id(bitmap_id), - shared_bitmap(NULL), - gpu_memory_buffer(NULL) {} + shared_bitmap(nullptr) {} -ResourceProvider::Resource::Resource(const Resource& other) = default; +ResourceProvider::Resource::Resource(Resource&& other) = default; void ResourceProvider::Resource::set_mailbox(const TextureMailbox& mailbox) { mailbox_ = mailbox; @@ -714,17 +711,16 @@ DCHECK(resource->origin != Resource::EXTERNAL); DCHECK_EQ(RESOURCE_TYPE_BITMAP, resource->type); delete resource->shared_bitmap; - resource->pixels = NULL; + resource->pixels = nullptr; } if (resource->pixels) { DCHECK(resource->origin == Resource::INTERNAL); delete[] resource->pixels; - resource->pixels = NULL; + resource->pixels = nullptr; } if (resource->gpu_memory_buffer) { DCHECK(resource->origin == Resource::INTERNAL); - delete resource->gpu_memory_buffer; - resource->gpu_memory_buffer = NULL; + resource->gpu_memory_buffer.reset(); } resources_.erase(it); } @@ -826,9 +822,9 @@ ResourceProvider::Resource* ResourceProvider::InsertResource( ResourceId id, - const Resource& resource) { + Resource resource) { std::pair<ResourceMap::iterator, bool> result = - resources_.insert(ResourceMap::value_type(id, resource)); + resources_.insert(ResourceMap::value_type(id, std::move(resource))); DCHECK(result.second); return &result.first->second; } @@ -1050,7 +1046,7 @@ : resource_provider_(resource_provider), resource_(resource_provider->LockForWrite(resource_id)) { DCHECK(IsGpuResourceType(resource_->type)); - gpu_memory_buffer_.reset(resource_->gpu_memory_buffer); + gpu_memory_buffer_ = std::move(resource_->gpu_memory_buffer); resource_->gpu_memory_buffer = nullptr; } @@ -1063,7 +1059,7 @@ DCHECK(!resource_->gpu_memory_buffer); resource_provider_->LazyCreate(resource_); - resource_->gpu_memory_buffer = gpu_memory_buffer_.release(); + resource_->gpu_memory_buffer = std::move(gpu_memory_buffer_); resource_->allocated = true; resource_provider_->LazyCreateImage(resource_); resource_->dirty_image = true; @@ -1782,11 +1778,9 @@ gl->BindTexture(resource->target, resource->gl_id); if (resource->type == RESOURCE_TYPE_GPU_MEMORY_BUFFER) { resource->gpu_memory_buffer = - gpu_memory_buffer_manager_ - ->AllocateGpuMemoryBuffer(size, BufferFormat(format), - gfx::BufferUsage::GPU_READ_CPU_READ_WRITE, - 0 /* surface_id */) - .release(); + gpu_memory_buffer_manager_->AllocateGpuMemoryBuffer( + size, BufferFormat(format), + gfx::BufferUsage::GPU_READ_CPU_READ_WRITE, 0 /* surface_id */); LazyCreateImage(resource); resource->dirty_image = true; resource->is_overlay_candidate = true; @@ -1801,7 +1795,7 @@ if (format != ETC1) { gl->TexImage2D(resource->target, 0, GLInternalFormat(format), size.width(), size.height(), 0, GLDataFormat(format), - GLDataType(format), NULL); + GLDataType(format), nullptr); } } } @@ -1881,14 +1875,14 @@ GLES2Interface* ResourceProvider::ContextGL() const { ContextProvider* context_provider = output_surface_->context_provider(); - return context_provider ? context_provider->ContextGL() : NULL; + return context_provider ? context_provider->ContextGL() : nullptr; } class GrContext* ResourceProvider::GrContext(bool worker_context) const { ContextProvider* context_provider = worker_context ? output_surface_->worker_context_provider() : output_surface_->context_provider(); - return context_provider ? context_provider->GrContext() : NULL; + return context_provider ? context_provider->GrContext() : nullptr; } bool ResourceProvider::OnMemoryDump(
diff --git a/cc/resources/resource_provider.h b/cc/resources/resource_provider.h index bd395bf0..5b5e5be 100644 --- a/cc/resources/resource_provider.h +++ b/cc/resources/resource_provider.h
@@ -518,7 +518,7 @@ const gfx::Size& size, Origin origin, GLenum filter); - Resource(const Resource& other); + Resource(Resource&& other); bool needs_sync_token() const { return needs_sync_token_; } @@ -570,12 +570,14 @@ ResourceFormat format; SharedBitmapId shared_bitmap_id; SharedBitmap* shared_bitmap; - gfx::GpuMemoryBuffer* gpu_memory_buffer; + std::unique_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer; private: SynchronizationState synchronization_state_ = SYNCHRONIZED; bool needs_sync_token_ = false; TextureMailbox mailbox_; + + DISALLOW_COPY_AND_ASSIGN(Resource); }; using ResourceMap = std::unordered_map<ResourceId, Resource>; @@ -602,7 +604,7 @@ ResourceType type, ResourceFormat format); ResourceId CreateBitmap(const gfx::Size& size); - Resource* InsertResource(ResourceId id, const Resource& resource); + Resource* InsertResource(ResourceId id, Resource resource); Resource* GetResource(ResourceId id); const Resource* LockForRead(ResourceId id); void UnlockForRead(ResourceId id);
diff --git a/cc/scheduler/scheduler.cc b/cc/scheduler/scheduler.cc index e2a531f..e7abd808 100644 --- a/cc/scheduler/scheduler.cc +++ b/cc/scheduler/scheduler.cc
@@ -290,11 +290,6 @@ BeginFrameArgs adjusted_args(args); adjusted_args.deadline -= EstimatedParentDrawTime(); - // Deliver BeginFrames to children. - // TODO(brianderson): Move this responsibility to the DisplayScheduler. - if (state_machine_.children_need_begin_frames()) - client_->SendBeginFramesToChildren(adjusted_args); - if (settings_.using_synchronous_renderer_compositor) { BeginImplFrameSynchronous(adjusted_args); return true; @@ -328,11 +323,6 @@ return true; } -void Scheduler::SetChildrenNeedBeginFrames(bool children_need_begin_frames) { - state_machine_.SetChildrenNeedBeginFrames(children_need_begin_frames); - ProcessScheduledActions(); -} - void Scheduler::SetVideoNeedsBeginFrames(bool video_needs_begin_frames) { state_machine_.SetVideoNeedsBeginFrames(video_needs_begin_frames); ProcessScheduledActions();
diff --git a/cc/scheduler/scheduler.h b/cc/scheduler/scheduler.h index 9aade7e..0a3ace7 100644 --- a/cc/scheduler/scheduler.h +++ b/cc/scheduler/scheduler.h
@@ -46,7 +46,6 @@ virtual void ScheduledActionPrepareTiles() = 0; virtual void ScheduledActionInvalidateOutputSurface() = 0; virtual void DidFinishImplFrame() = 0; - virtual void SendBeginFramesToChildren(const BeginFrameArgs& args) = 0; virtual void SendBeginMainFrameNotExpectedSoon() = 0; protected: @@ -138,7 +137,6 @@ std::unique_ptr<base::trace_event::ConvertableToTraceFormat> AsValue() const; void AsValueInto(base::trace_event::TracedValue* value) const override; - void SetChildrenNeedBeginFrames(bool children_need_begin_frames); void SetVideoNeedsBeginFrames(bool video_needs_begin_frames); const BeginFrameSource* begin_frame_source() const {
diff --git a/cc/scheduler/scheduler_state_machine.cc b/cc/scheduler/scheduler_state_machine.cc index 35e73f6..210d7382 100644 --- a/cc/scheduler/scheduler_state_machine.cc +++ b/cc/scheduler/scheduler_state_machine.cc
@@ -55,7 +55,6 @@ critical_begin_main_frame_to_activate_is_fast_(true), main_thread_missed_last_deadline_(false), skip_next_begin_main_frame_to_reduce_latency_(false), - children_need_begin_frames_(false), defer_commits_(false), video_needs_begin_frames_(false), last_commit_had_no_updates_(false), @@ -256,7 +255,6 @@ main_thread_missed_last_deadline_); state->SetBoolean("skip_next_begin_main_frame_to_reduce_latency", skip_next_begin_main_frame_to_reduce_latency_); - state->SetBoolean("children_need_begin_frames", children_need_begin_frames_); state->SetBoolean("video_needs_begin_frames", video_needs_begin_frames_); state->SetBoolean("defer_commits", defer_commits_); state->SetBoolean("last_commit_had_no_updates", last_commit_had_no_updates_); @@ -765,10 +763,6 @@ skip_next_begin_main_frame_to_reduce_latency_ = true; } -bool SchedulerStateMachine::BeginFrameRequiredForChildren() const { - return children_need_begin_frames_; -} - bool SchedulerStateMachine::BeginFrameNeededForVideo() const { return video_needs_begin_frames_; } @@ -783,13 +777,8 @@ if (!visible_) return false; - return (BeginFrameRequiredForAction() || BeginFrameRequiredForChildren() || - BeginFrameNeededForVideo() || ProactiveBeginFrameWanted()); -} - -void SchedulerStateMachine::SetChildrenNeedBeginFrames( - bool children_need_begin_frames) { - children_need_begin_frames_ = children_need_begin_frames; + return BeginFrameRequiredForAction() || BeginFrameNeededForVideo() || + ProactiveBeginFrameWanted(); } void SchedulerStateMachine::SetVideoNeedsBeginFrames(
diff --git a/cc/scheduler/scheduler_state_machine.h b/cc/scheduler/scheduler_state_machine.h index 2d0ee144..f6492e26 100644 --- a/cc/scheduler/scheduler_state_machine.h +++ b/cc/scheduler/scheduler_state_machine.h
@@ -272,17 +272,11 @@ void SetDeferCommits(bool defer_commits); - void SetChildrenNeedBeginFrames(bool children_need_begin_frames); - bool children_need_begin_frames() const { - return children_need_begin_frames_; - } - void SetVideoNeedsBeginFrames(bool video_needs_begin_frames); bool video_needs_begin_frames() const { return video_needs_begin_frames_; } protected: bool BeginFrameRequiredForAction() const; - bool BeginFrameRequiredForChildren() const; bool BeginFrameNeededForVideo() const; bool ProactiveBeginFrameWanted() const; @@ -353,7 +347,6 @@ bool critical_begin_main_frame_to_activate_is_fast_; bool main_thread_missed_last_deadline_; bool skip_next_begin_main_frame_to_reduce_latency_; - bool children_need_begin_frames_; bool defer_commits_; bool video_needs_begin_frames_; bool last_commit_had_no_updates_;
diff --git a/cc/scheduler/scheduler_state_machine_unittest.cc b/cc/scheduler/scheduler_state_machine_unittest.cc index ee88bfc1..acaa3fc 100644 --- a/cc/scheduler/scheduler_state_machine_unittest.cc +++ b/cc/scheduler/scheduler_state_machine_unittest.cc
@@ -2060,16 +2060,6 @@ EXPECT_TRUE(state.ShouldTriggerBeginImplFrameDeadlineImmediately()); } -TEST(SchedulerStateMachineTest, TestForwardBeginFramesToChildren) { - SchedulerSettings settings; - StateMachine state(settings); - SET_UP_STATE(state) - - EXPECT_FALSE(state.BeginFrameNeeded()); - state.SetChildrenNeedBeginFrames(true); - EXPECT_TRUE(state.BeginFrameNeeded()); -} - TEST(SchedulerStateMachineTest, TestDeferCommit) { SchedulerSettings settings; StateMachine state(settings);
diff --git a/cc/scheduler/scheduler_unittest.cc b/cc/scheduler/scheduler_unittest.cc index 4b12a5d..0ff7e87 100644 --- a/cc/scheduler/scheduler_unittest.cc +++ b/cc/scheduler/scheduler_unittest.cc
@@ -67,7 +67,6 @@ draw_will_happen_ = true; swap_will_happen_if_draw_happens_ = true; num_draws_ = 0; - begin_frame_args_sent_to_children_ = BeginFrameArgs(); last_begin_main_frame_args_ = BeginFrameArgs(); } @@ -166,10 +165,6 @@ states_.push_back(scheduler_->AsValue()); } - void SendBeginFramesToChildren(const BeginFrameArgs& args) override { - begin_frame_args_sent_to_children_ = args; - } - void SendBeginMainFrameNotExpectedSoon() override { PushAction("SendBeginMainFrameNotExpectedSoon"); } @@ -180,14 +175,6 @@ state); } - bool begin_frame_is_sent_to_children() const { - return begin_frame_args_sent_to_children_.IsValid(); - } - - const BeginFrameArgs& begin_frame_args_sent_to_children() const { - return begin_frame_args_sent_to_children_; - } - void PushAction(const char* description) { actions_.push_back(description); states_.push_back(scheduler_->AsValue()); @@ -204,7 +191,6 @@ bool swap_will_happen_if_draw_happens_; bool automatic_swap_ack_; int num_draws_; - BeginFrameArgs begin_frame_args_sent_to_children_; BeginFrameArgs last_begin_main_frame_args_; base::TimeTicks posted_begin_impl_frame_deadline_; std::vector<const char*> actions_; @@ -463,69 +449,6 @@ EXPECT_NO_ACTION(client_); } -TEST_F(SchedulerTest, SendBeginFramesToChildren) { - scheduler_settings_.use_external_begin_frame_source = true; - SetUpScheduler(true); - - EXPECT_FALSE(client_->begin_frame_is_sent_to_children()); - scheduler_->SetNeedsBeginMainFrame(); - EXPECT_SINGLE_ACTION("AddObserver(this)", client_); - EXPECT_TRUE(scheduler_->begin_frames_expected()); - - scheduler_->SetChildrenNeedBeginFrames(true); - - client_->Reset(); - EXPECT_SCOPED(AdvanceFrame()); - EXPECT_TRUE(client_->begin_frame_is_sent_to_children()); - EXPECT_TRUE(scheduler_->BeginImplFrameDeadlinePending()); - EXPECT_ACTION("WillBeginImplFrame", client_, 0, 2); - EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client_, 1, 2); - EXPECT_TRUE(scheduler_->begin_frames_expected()); -} - -TEST_F(SchedulerTest, SendBeginFramesToChildrenWithoutCommit) { - scheduler_settings_.use_external_begin_frame_source = true; - SetUpScheduler(true); - - EXPECT_FALSE(scheduler_->begin_frames_expected()); - scheduler_->SetChildrenNeedBeginFrames(true); - EXPECT_SINGLE_ACTION("AddObserver(this)", client_); - EXPECT_TRUE(scheduler_->begin_frames_expected()); - - client_->Reset(); - EXPECT_SCOPED(AdvanceFrame()); - EXPECT_TRUE(client_->begin_frame_is_sent_to_children()); -} - -TEST_F(SchedulerTest, SendBeginFramesToChildrenDeadlineNotAdjusted) { - // Set up client with specified estimates. - scheduler_settings_.use_external_begin_frame_source = true; - SetUpScheduler(true); - - fake_compositor_timing_history_ - ->SetBeginMainFrameStartToCommitDurationEstimate( - base::TimeDelta::FromMilliseconds(2)); - fake_compositor_timing_history_->SetCommitToReadyToActivateDurationEstimate( - base::TimeDelta::FromMilliseconds(4)); - fake_compositor_timing_history_->SetDrawDurationEstimate( - base::TimeDelta::FromMilliseconds(1)); - - EXPECT_FALSE(scheduler_->begin_frames_expected()); - scheduler_->SetChildrenNeedBeginFrames(true); - EXPECT_SINGLE_ACTION("AddObserver(this)", client_); - EXPECT_TRUE(scheduler_->begin_frames_expected()); - - client_->Reset(); - - BeginFrameArgs frame_args = - CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE, now_src()); - fake_external_begin_frame_source()->TestOnBeginFrame(frame_args); - - EXPECT_TRUE(client_->begin_frame_is_sent_to_children()); - EXPECT_EQ(client_->begin_frame_args_sent_to_children().deadline, - frame_args.deadline); -} - TEST_F(SchedulerTest, VideoNeedsBeginFrames) { scheduler_settings_.use_external_begin_frame_source = true; SetUpScheduler(true);
diff --git a/cc/test/animation_timelines_test_common.cc b/cc/test/animation_timelines_test_common.cc index 1f6fb9b8..55250327 100644 --- a/cc/test/animation_timelines_test_common.cc +++ b/cc/test/animation_timelines_test_common.cc
@@ -246,14 +246,14 @@ } AnimationPlayer* AnimationTimelinesTest::GetPlayerForLayerId(int layer_id) { - const ElementAnimations* element_animations = + const scoped_refptr<ElementAnimations> element_animations = host_->GetElementAnimationsForLayerId(layer_id); return element_animations ? element_animations->players_list().head()->value() : nullptr; } AnimationPlayer* AnimationTimelinesTest::GetImplPlayerForLayerId(int layer_id) { - const ElementAnimations* element_animations = + const scoped_refptr<ElementAnimations> element_animations = host_impl_->GetElementAnimationsForLayerId(layer_id); return element_animations ? element_animations->players_list().head()->value() : nullptr;
diff --git a/cc/test/fake_proxy.h b/cc/test/fake_proxy.h index 92a7a97..3c47423 100644 --- a/cc/test/fake_proxy.h +++ b/cc/test/fake_proxy.h
@@ -39,7 +39,6 @@ void Stop() override {} bool SupportsImplScrolling() const override; bool MainFrameWillHappenForTesting() override; - void SetChildrenNeedBeginFrames(bool children_need_begin_frames) override {} void SetAuthoritativeVSyncInterval(const base::TimeDelta& interval) override { } void UpdateTopControlsState(TopControlsState constraints,
diff --git a/cc/test/layer_tree_test.cc b/cc/test/layer_tree_test.cc index a8559e3..8ff231a 100644 --- a/cc/test/layer_tree_test.cc +++ b/cc/test/layer_tree_test.cc
@@ -371,10 +371,6 @@ test_hooks_->DidInitializeOutputSurface(); } - void SendBeginFramesToChildren(const BeginFrameArgs& args) override { - test_hooks_->SendBeginFramesToChildren(args); - } - void DidFailToInitializeOutputSurface() override { test_hooks_->DidFailToInitializeOutputSurface(); RequestNewOutputSurface();
diff --git a/cc/test/test_hooks.h b/cc/test/test_hooks.h index 918b0dbc..075bdd1 100644 --- a/cc/test/test_hooks.h +++ b/cc/test/test_hooks.h
@@ -90,7 +90,6 @@ virtual void ScheduledActionBeginOutputSurfaceCreation() {} virtual void ScheduledActionPrepareTiles() {} virtual void ScheduledActionInvalidateOutputSurface() {} - virtual void SendBeginFramesToChildren(const BeginFrameArgs& args) {} virtual void SendBeginMainFrameNotExpectedSoon() {} // Hooks for ProxyImpl
diff --git a/cc/tiles/picture_layer_tiling.cc b/cc/tiles/picture_layer_tiling.cc index 9e79f4a4..01beed6 100644 --- a/cc/tiles/picture_layer_tiling.cc +++ b/cc/tiles/picture_layer_tiling.cc
@@ -386,10 +386,15 @@ const Region* layer_invalidation = client_->GetPendingInvalidation(); // If this tile is invalidated, then the pending tree should create one. - if (layer_invalidation && - layer_invalidation->Intersects(info.enclosing_layer_rect)) - return true; - + // Do the intersection test in content space to match the corresponding check + // on the active tree and avoid floating point inconsistencies. + for (Region::Iterator iter(*layer_invalidation); iter.has_rect(); + iter.next()) { + gfx::Rect invalid_content_rect = + gfx::ScaleToEnclosingRect(iter.rect(), contents_scale_); + if (invalid_content_rect.Intersects(info.content_rect)) + return true; + } // If the active tree doesn't have a tile here, but it's in the pending tree's // visible rect, then the pending tree should create a tile. This can happen // if the pending visible rect is outside of the active tree's live tiles
diff --git a/cc/tiles/picture_layer_tiling_unittest.cc b/cc/tiles/picture_layer_tiling_unittest.cc index 631845f9..e4d5d6da 100644 --- a/cc/tiles/picture_layer_tiling_unittest.cc +++ b/cc/tiles/picture_layer_tiling_unittest.cc
@@ -472,6 +472,46 @@ EXPECT_TRUE(tiling_->TileAt(0, 0)); } +TEST_F(PictureLayerTilingIteratorTest, CreateTileJustCoverBorderUp) { + float content_scale = 1.2000000476837158f; + gfx::Size tile_size(512, 512); + gfx::Size layer_size(1440, 4560); + FakePictureLayerTilingClient active_client; + + active_client.SetTileSize(tile_size); + scoped_refptr<FakeRasterSource> raster_source = + FakeRasterSource::CreateFilled(layer_size); + std::unique_ptr<TestablePictureLayerTiling> active_tiling = + TestablePictureLayerTiling::Create(ACTIVE_TREE, content_scale, + raster_source, &active_client, + LayerTreeSettings()); + active_tiling->set_resolution(HIGH_RESOLUTION); + + gfx::Rect invalid_rect(0, 750, 220, 100); + Initialize(tile_size, content_scale, layer_size); + client_.set_twin_tiling(active_tiling.get()); + client_.set_invalidation(invalid_rect); + SetLiveRectAndVerifyTiles(gfx::Rect(layer_size)); + // When it creates a tile in pending tree, verify that tiles are invalidated + // even if only their border pixels intersect the invalidation rect + EXPECT_TRUE(tiling_->TileAt(0, 1)); + gfx::Rect scaled_invalid_rect = + gfx::ScaleToEnclosingRect(invalid_rect, content_scale); + EXPECT_FALSE(scaled_invalid_rect.Intersects( + tiling_->TilingDataForTesting().TileBounds(0, 2))); + EXPECT_TRUE(scaled_invalid_rect.Intersects( + tiling_->TilingDataForTesting().TileBoundsWithBorder(0, 2))); + EXPECT_TRUE(tiling_->TileAt(0, 2)); + + bool recreate_tiles = false; + active_tiling->RemoveTilesInRegion(invalid_rect, recreate_tiles); + // Even though a tile just touch border area of invalid region, verify that + // RemoveTilesInRegion behaves the same as SetLiveRectAndVerifyTiles with + // respect to the tiles that it invalidates + EXPECT_FALSE(active_tiling->TileAt(0, 1)); + EXPECT_FALSE(active_tiling->TileAt(0, 2)); +} + TEST_F(PictureLayerTilingIteratorTest, LiveTilesExactlyCoverLiveTileRect) { Initialize(gfx::Size(100, 100), 1.f, gfx::Size(1099, 801)); SetLiveRectAndVerifyTiles(gfx::Rect(100, 100));
diff --git a/cc/trees/layer_tree_host.cc b/cc/trees/layer_tree_host.cc index 17b1e6b..f91f925 100644 --- a/cc/trees/layer_tree_host.cc +++ b/cc/trees/layer_tree_host.cc
@@ -902,6 +902,22 @@ return result || next_commit_forces_redraw_; } +LayerListIterator<Layer> LayerTreeHost::begin() { + return LayerListIterator<Layer>(root_layer_.get()); +} + +LayerListIterator<Layer> LayerTreeHost::end() { + return LayerListIterator<Layer>(nullptr); +} + +LayerListReverseIterator<Layer> LayerTreeHost::rbegin() { + return LayerListReverseIterator<Layer>(root_layer_.get()); +} + +LayerListReverseIterator<Layer> LayerTreeHost::rend() { + return LayerListReverseIterator<Layer>(nullptr); +} + void LayerTreeHost::DidCompletePageScaleAnimation() { did_complete_scale_animation_ = true; } @@ -1260,16 +1276,6 @@ return SurfaceSequence(surface_id_namespace_, next_surface_sequence_++); } -void LayerTreeHost::SetChildrenNeedBeginFrames( - bool children_need_begin_frames) const { - proxy_->SetChildrenNeedBeginFrames(children_need_begin_frames); -} - -void LayerTreeHost::SendBeginFramesToChildren( - const BeginFrameArgs& args) const { - client_->SendBeginFramesToChildren(args); -} - void LayerTreeHost::SetAuthoritativeVSyncInterval( const base::TimeDelta& interval) { proxy_->SetAuthoritativeVSyncInterval(interval);
diff --git a/cc/trees/layer_tree_host.h b/cc/trees/layer_tree_host.h index 0573db3a..0fcf1d5d 100644 --- a/cc/trees/layer_tree_host.h +++ b/cc/trees/layer_tree_host.h
@@ -31,6 +31,7 @@ #include "cc/input/scrollbar.h" #include "cc/input/top_controls_state.h" #include "cc/layers/layer_collections.h" +#include "cc/layers/layer_list_iterator.h" #include "cc/output/output_surface.h" #include "cc/output/renderer_capabilities.h" #include "cc/output/swap_promise.h" @@ -147,6 +148,11 @@ void DidCompleteSwapBuffers() { client_->DidCompleteSwapBuffers(); } bool UpdateLayers(); + LayerListIterator<Layer> begin(); + LayerListIterator<Layer> end(); + LayerListReverseIterator<Layer> rbegin(); + LayerListReverseIterator<Layer> rend(); + // Called when the compositor completed page scale animation. void DidCompletePageScaleAnimation(); @@ -342,9 +348,6 @@ void set_surface_id_namespace(uint32_t id_namespace); SurfaceSequence CreateSurfaceSequence(); - void SetChildrenNeedBeginFrames(bool children_need_begin_frames) const; - void SendBeginFramesToChildren(const BeginFrameArgs& args) const; - void SetAuthoritativeVSyncInterval(const base::TimeDelta& interval); PropertyTrees* property_trees() { return &property_trees_; }
diff --git a/cc/trees/layer_tree_host_unittest.cc b/cc/trees/layer_tree_host_unittest.cc index f10f157..a4482371 100644 --- a/cc/trees/layer_tree_host_unittest.cc +++ b/cc/trees/layer_tree_host_unittest.cc
@@ -4812,77 +4812,6 @@ // LayerTreeHostTestBeginMainFrameTimeIsAlsoImplTime); SINGLE_THREAD_TEST_F(LayerTreeHostTestBeginMainFrameTimeIsAlsoImplTime); -class LayerTreeHostTestSendBeginFramesToChildren : public LayerTreeHostTest { - public: - LayerTreeHostTestSendBeginFramesToChildren() - : begin_frame_sent_to_children_(false) { - } - - void BeginTest() override { - // Kick off the test with a commit. - PostSetNeedsCommitToMainThread(); - } - - void SendBeginFramesToChildren(const BeginFrameArgs& args) override { - begin_frame_sent_to_children_ = true; - EndTest(); - } - - void DidBeginMainFrame() override { - // Children requested BeginFrames. - layer_tree_host()->SetChildrenNeedBeginFrames(true); - } - - void AfterTest() override { - // Ensure that BeginFrame message is sent to children during parent - // scheduler handles its BeginFrame. - EXPECT_TRUE(begin_frame_sent_to_children_); - } - - private: - bool begin_frame_sent_to_children_; -}; - -SINGLE_THREAD_TEST_F(LayerTreeHostTestSendBeginFramesToChildren); - -class LayerTreeHostTestSendBeginFramesToChildrenWithExternalBFS - : public LayerTreeHostTest { - public: - LayerTreeHostTestSendBeginFramesToChildrenWithExternalBFS() - : begin_frame_sent_to_children_(false) { - } - - void InitializeSettings(LayerTreeSettings* settings) override { - settings->use_external_begin_frame_source = true; - } - - void BeginTest() override { - // Kick off the test with a commit. - PostSetNeedsCommitToMainThread(); - } - - void SendBeginFramesToChildren(const BeginFrameArgs& args) override { - begin_frame_sent_to_children_ = true; - EndTest(); - } - - void DidBeginMainFrame() override { - // Children requested BeginFrames. - layer_tree_host()->SetChildrenNeedBeginFrames(true); - } - - void AfterTest() override { - // Ensure that BeginFrame message is sent to children during parent - // scheduler handles its BeginFrame. - EXPECT_TRUE(begin_frame_sent_to_children_); - } - - private: - bool begin_frame_sent_to_children_; -}; - -SINGLE_THREAD_TEST_F(LayerTreeHostTestSendBeginFramesToChildrenWithExternalBFS); - class LayerTreeHostTestActivateOnInvisible : public LayerTreeHostTest { public: LayerTreeHostTestActivateOnInvisible()
diff --git a/cc/trees/layer_tree_impl.cc b/cc/trees/layer_tree_impl.cc index 5fbc305b..7d178db 100644 --- a/cc/trees/layer_tree_impl.cc +++ b/cc/trees/layer_tree_impl.cc
@@ -441,20 +441,20 @@ target_tree->has_ever_been_drawn_ = false; } -LayerListIterator LayerTreeImpl::begin() { - return LayerListIterator(root_layer_); +LayerListIterator<LayerImpl> LayerTreeImpl::begin() { + return LayerListIterator<LayerImpl>(root_layer_); } -LayerListIterator LayerTreeImpl::end() { - return LayerListIterator(nullptr); +LayerListIterator<LayerImpl> LayerTreeImpl::end() { + return LayerListIterator<LayerImpl>(nullptr); } -LayerListReverseIterator LayerTreeImpl::rbegin() { - return LayerListReverseIterator(root_layer_); +LayerListReverseIterator<LayerImpl> LayerTreeImpl::rbegin() { + return LayerListReverseIterator<LayerImpl>(root_layer_); } -LayerListReverseIterator LayerTreeImpl::rend() { - return LayerListReverseIterator(nullptr); +LayerListReverseIterator<LayerImpl> LayerTreeImpl::rend() { + return LayerListReverseIterator<LayerImpl>(nullptr); } void LayerTreeImpl::AddToElementMap(LayerImpl* layer) {
diff --git a/cc/trees/layer_tree_impl.h b/cc/trees/layer_tree_impl.h index 5e061e5d3..6f47b3e 100644 --- a/cc/trees/layer_tree_impl.h +++ b/cc/trees/layer_tree_impl.h
@@ -154,10 +154,10 @@ void PushPropertiesTo(LayerTreeImpl* tree_impl); - LayerListIterator begin(); - LayerListIterator end(); - LayerListReverseIterator rbegin(); - LayerListReverseIterator rend(); + LayerListIterator<LayerImpl> begin(); + LayerListIterator<LayerImpl> end(); + LayerListReverseIterator<LayerImpl> rbegin(); + LayerListReverseIterator<LayerImpl> rend(); // TODO(thakis): Consider marking this CC_EXPORT once we understand // http://crbug.com/575700 better.
diff --git a/cc/trees/proxy.h b/cc/trees/proxy.h index 5c39d70..fefa774 100644 --- a/cc/trees/proxy.h +++ b/cc/trees/proxy.h
@@ -74,8 +74,6 @@ virtual bool SupportsImplScrolling() const = 0; - virtual void SetChildrenNeedBeginFrames(bool children_need_begin_frames) = 0; - virtual void SetAuthoritativeVSyncInterval( const base::TimeDelta& interval) = 0;
diff --git a/cc/trees/proxy_impl.cc b/cc/trees/proxy_impl.cc index bca90cb..428ad91 100644 --- a/cc/trees/proxy_impl.cc +++ b/cc/trees/proxy_impl.cc
@@ -614,10 +614,6 @@ layer_tree_host_impl_->output_surface()->Invalidate(); } -void ProxyImpl::SendBeginFramesToChildren(const BeginFrameArgs& args) { - NOTREACHED() << "Only used by SingleThreadProxy"; -} - void ProxyImpl::SendBeginMainFrameNotExpectedSoon() { DCHECK(IsImplThread()); channel_impl_->BeginMainFrameNotExpectedSoon();
diff --git a/cc/trees/proxy_impl.h b/cc/trees/proxy_impl.h index ba4c8df03..181fb293 100644 --- a/cc/trees/proxy_impl.h +++ b/cc/trees/proxy_impl.h
@@ -123,7 +123,6 @@ void ScheduledActionBeginOutputSurfaceCreation() override; void ScheduledActionPrepareTiles() override; void ScheduledActionInvalidateOutputSurface() override; - void SendBeginFramesToChildren(const BeginFrameArgs& args) override; void SendBeginMainFrameNotExpectedSoon() override; DrawResult DrawAndSwapInternal(bool forced_draw);
diff --git a/cc/trees/proxy_main.cc b/cc/trees/proxy_main.cc index eae3ad4f..8feb0a29 100644 --- a/cc/trees/proxy_main.cc +++ b/cc/trees/proxy_main.cc
@@ -429,10 +429,6 @@ return main_frame_will_happen; } -void ProxyMain::SetChildrenNeedBeginFrames(bool children_need_begin_frames) { - NOTREACHED() << "Only used by SingleThreadProxy"; -} - void ProxyMain::SetAuthoritativeVSyncInterval(const base::TimeDelta& interval) { NOTREACHED() << "Only used by SingleProxyMain"; }
diff --git a/cc/trees/proxy_main.h b/cc/trees/proxy_main.h index 29a71132..77b61a33 100644 --- a/cc/trees/proxy_main.h +++ b/cc/trees/proxy_main.h
@@ -109,7 +109,6 @@ void Stop() override; bool SupportsImplScrolling() const override; bool MainFrameWillHappenForTesting() override; - void SetChildrenNeedBeginFrames(bool children_need_begin_frames) override; void SetAuthoritativeVSyncInterval(const base::TimeDelta& interval) override; void ReleaseOutputSurface() override; void UpdateTopControlsState(TopControlsState constraints,
diff --git a/cc/trees/remote_channel_impl.cc b/cc/trees/remote_channel_impl.cc index e5e97628..a7639e9 100644 --- a/cc/trees/remote_channel_impl.cc +++ b/cc/trees/remote_channel_impl.cc
@@ -300,11 +300,6 @@ return true; } -void RemoteChannelImpl::SetChildrenNeedBeginFrames( - bool children_need_begin_frames) { - NOTREACHED() << "Should not be called on the remote client LayerTreeHost"; -} - void RemoteChannelImpl::SetAuthoritativeVSyncInterval( const base::TimeDelta& interval) { NOTREACHED() << "Should not be called on the remote client LayerTreeHost";
diff --git a/cc/trees/remote_channel_impl.h b/cc/trees/remote_channel_impl.h index 122e790b..485b155 100644 --- a/cc/trees/remote_channel_impl.h +++ b/cc/trees/remote_channel_impl.h
@@ -159,7 +159,6 @@ std::unique_ptr<BeginFrameSource> external_begin_frame_source) override; void Stop() override; bool SupportsImplScrolling() const override; - void SetChildrenNeedBeginFrames(bool children_need_begin_frames) override; void SetAuthoritativeVSyncInterval(const base::TimeDelta& interval) override; void UpdateTopControlsState(TopControlsState constraints, TopControlsState current,
diff --git a/cc/trees/single_thread_proxy.cc b/cc/trees/single_thread_proxy.cc index 3d991c0..1fdf005 100644 --- a/cc/trees/single_thread_proxy.cc +++ b/cc/trees/single_thread_proxy.cc
@@ -728,12 +728,6 @@ return scheduler_on_impl_thread_->MainFrameForTestingWillHappen(); } -void SingleThreadProxy::SetChildrenNeedBeginFrames( - bool children_need_begin_frames) { - scheduler_on_impl_thread_->SetChildrenNeedBeginFrames( - children_need_begin_frames); -} - void SingleThreadProxy::SetAuthoritativeVSyncInterval( const base::TimeDelta& interval) { authoritative_vsync_interval_ = interval; @@ -914,8 +908,4 @@ #endif } -void SingleThreadProxy::SendBeginFramesToChildren(const BeginFrameArgs& args) { - layer_tree_host_->SendBeginFramesToChildren(args); -} - } // namespace cc
diff --git a/cc/trees/single_thread_proxy.h b/cc/trees/single_thread_proxy.h index 6f515299..65d717c 100644 --- a/cc/trees/single_thread_proxy.h +++ b/cc/trees/single_thread_proxy.h
@@ -58,7 +58,6 @@ void Stop() override; bool SupportsImplScrolling() const override; bool MainFrameWillHappenForTesting() override; - void SetChildrenNeedBeginFrames(bool children_need_begin_frames) override; void SetAuthoritativeVSyncInterval(const base::TimeDelta& interval) override; void UpdateTopControlsState(TopControlsState constraints, TopControlsState current, @@ -76,7 +75,6 @@ void ScheduledActionBeginOutputSurfaceCreation() override; void ScheduledActionPrepareTiles() override; void ScheduledActionInvalidateOutputSurface() override; - void SendBeginFramesToChildren(const BeginFrameArgs& args) override; void SendBeginMainFrameNotExpectedSoon() override; // LayerTreeHostImplClient implementation
diff --git a/chrome/android/java/res/OWNERS b/chrome/android/java/res/OWNERS index 7b0bde5..b36a488 100644 --- a/chrome/android/java/res/OWNERS +++ b/chrome/android/java/res/OWNERS
@@ -1,7 +1,8 @@ set noparent -tedchoc@chromium.org -aurimas@chromium.org -newt@chromium.org -dtrainor@chromium.org -yusufo@chromium.org dfalcantara@chromium.org +dtrainor@chromium.org +tedchoc@chromium.org +yusufo@chromium.org + +# New Tab Page changes only: +bauerb@chromium.org
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java index cfa226b..f1b3357 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeActivity.java
@@ -87,6 +87,7 @@ import org.chromium.chrome.browser.metrics.LaunchMetrics; import org.chromium.chrome.browser.metrics.StartupMetrics; import org.chromium.chrome.browser.metrics.UmaSessionStats; +import org.chromium.chrome.browser.multiwindow.MultiWindowUtils; import org.chromium.chrome.browser.nfc.BeamController; import org.chromium.chrome.browser.nfc.BeamProvider; import org.chromium.chrome.browser.offlinepages.OfflinePageUtils; @@ -250,11 +251,7 @@ ApplicationInitialization.enableFullscreenFlags( getResources(), this, getControlContainerHeightResource()); - // TODO(twellington): Remove this work around when the underlying bug is fixed. - // See crbug.com/583099. - if (!Build.VERSION.CODENAME.equals("N")) { - getWindow().setBackgroundDrawable(getBackgroundDrawable()); - } + getWindow().setBackgroundDrawable(getBackgroundDrawable()); mWindowAndroid = ((ChromeApplication) getApplicationContext()) .createActivityWindowAndroid(this); mWindowAndroid.restoreInstanceState(getSavedInstanceState()); @@ -638,6 +635,8 @@ LaunchMetrics.commitLaunchMetrics(getActivityTab().getWebContents()); } FeatureUtilities.setCustomTabVisible(isCustomTab()); + FeatureUtilities.setIsInMultiWindowMode( + MultiWindowUtils.getInstance().isInMultiWindowMode(this)); } @Override @@ -1290,6 +1289,25 @@ super.onConfigurationChanged(newConfig); } + /** + * Called by the system when the activity changes from fullscreen mode to multi-window mode + * and visa-versa. + * @param isInMultiWindowMode True if the activity is in multi-window mode. + */ + public void onMultiWindowModeChanged(boolean isInMultiWindowMode) { + if (!isInMultiWindowMode + && ApplicationStatus.getStateForActivity(this) == ActivityState.RESUMED) { + // Start a new UMA session when exiting multi-window mode if the activity is currently + // resumed. When entering multi-window Android recents gains focus, so ChromeActivity + // will get a call to onPauseWithNative(), ending the current UMA session. When exiting + // multi-window, however, if ChromeActivity is resumed it stays in that state. + markSessionEnd(); + markSessionResume(); + FeatureUtilities.setIsInMultiWindowMode( + MultiWindowUtils.getInstance().isInMultiWindowMode(this)); + } + } + @Override public final void onBackPressed() { if (mCompositorViewHolder != null) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/appmenu/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/appmenu/OWNERS deleted file mode 100644 index 99f087eb..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/appmenu/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -aurimas@chromium.org -kkimlabs@chromium.org
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/autofill/OWNERS index 2ff8227..ddde0a8 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/OWNERS +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/OWNERS
@@ -1,3 +1 @@ -aurimas@chromium.org - per-file PasswordGeneration*=rouslan@chromium.org
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java index c58c262..e603ddaf 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/PersonalDataManager.java
@@ -11,6 +11,7 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.chrome.R; +import org.chromium.chrome.browser.ResourceId; import java.util.ArrayList; import java.util.List; @@ -270,17 +271,21 @@ private String mObfuscatedNumber; private String mMonth; private String mYear; + private String mBasicCardPaymentType; + private int mIssuerIconDrawableId; @CalledByNative("CreditCard") public static CreditCard create(String guid, String origin, boolean isLocal, boolean isCached, String name, String number, String obfuscatedNumber, String month, - String year) { - return new CreditCard( - guid, origin, isLocal, isCached, name, number, obfuscatedNumber, month, year); + String year, String basicCardPaymentType, int enumeratedIconId) { + return new CreditCard(guid, origin, isLocal, isCached, name, number, obfuscatedNumber, + month, year, basicCardPaymentType, + ResourceId.mapToDrawableId(enumeratedIconId)); } public CreditCard(String guid, String origin, boolean isLocal, boolean isCached, - String name, String number, String obfuscatedNumber, String month, String year) { + String name, String number, String obfuscatedNumber, String month, String year, + String basicCardPaymentType, int issuerIconDrawableId) { mGUID = guid; mOrigin = origin; mIsLocal = isLocal; @@ -290,6 +295,8 @@ mObfuscatedNumber = obfuscatedNumber; mMonth = month; mYear = year; + mBasicCardPaymentType = basicCardPaymentType; + mIssuerIconDrawableId = issuerIconDrawableId; } /** TODO(estade): remove this constructor. */ @@ -355,6 +362,14 @@ return mIsCached; } + public String getBasicCardPaymentType() { + return mBasicCardPaymentType; + } + + public int getIssuerIconDrawableId() { + return mIssuerIconDrawableId; + } + @VisibleForTesting public void setGUID(String guid) { mGUID = guid;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/findinpage/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/findinpage/OWNERS deleted file mode 100644 index 812e8d9..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/findinpage/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -aurimas@chromium.org
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/OWNERS deleted file mode 100644 index 812e8d9..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -aurimas@chromium.org
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/remote/AbstractMediaRouteController.java b/chrome/android/java/src/org/chromium/chrome/browser/media/remote/AbstractMediaRouteController.java index c6e08b12..dbe38dff 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/remote/AbstractMediaRouteController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/remote/AbstractMediaRouteController.java
@@ -404,7 +404,7 @@ } private void recordEndOfSessionUMA() { - long remotePlaybackStoppedTimestampMs = SystemClock.uptimeMillis(); + long remotePlaybackStoppedTimestampMs = SystemClock.elapsedRealtime(); // There was no media element ever... if (mMediaElementAttachedTimestampMs == 0) return; @@ -473,12 +473,12 @@ public void setMediaStateListener(MediaStateListener mediaStateListener) { if (mMediaStateListener != null && mediaStateListener == null && mMediaElementAttachedTimestampMs != 0) { - mMediaElementDetachedTimestampMs = SystemClock.uptimeMillis(); + mMediaElementDetachedTimestampMs = SystemClock.elapsedRealtime(); } else if (mMediaStateListener == null && mediaStateListener != null) { // We're switching the videos so let's record the UMA for the previous one. if (mMediaElementDetachedTimestampMs != 0) recordEndOfSessionUMA(); - mMediaElementAttachedTimestampMs = SystemClock.uptimeMillis(); + mMediaElementAttachedTimestampMs = SystemClock.elapsedRealtime(); mMediaElementDetachedTimestampMs = 0; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/router/ChromeMediaRouter.java b/chrome/android/java/src/org/chromium/chrome/browser/media/router/ChromeMediaRouter.java index 19eb2bc..9236349 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/router/ChromeMediaRouter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/router/ChromeMediaRouter.java
@@ -138,6 +138,14 @@ } @Override + public void onRouteClosedWithError(String mediaRouteId, String message) { + if (mNativeMediaRouterAndroid != 0) { + nativeOnRouteClosedWithError(mNativeMediaRouterAndroid, mediaRouteId, message); + } + mRouteIdsToProviders.remove(mediaRouteId); + } + + @Override public void onMessageSentResult(boolean success, int callbackId) { nativeOnMessageSentResult(mNativeMediaRouterAndroid, success, callbackId); } @@ -369,6 +377,8 @@ native void nativeOnRouteRequestError( long nativeMediaRouterAndroid, String errorText, int createRouteRequestId); native void nativeOnRouteClosed(long nativeMediaRouterAndroid, String mediaRouteId); + native void nativeOnRouteClosedWithError( + long nativeMediaRouterAndroid, String mediaRouteId, String message); native void nativeOnMessageSentResult( long nativeMediaRouterAndroid, boolean success, int callbackId); native void nativeOnMessage(long nativeMediaRouterAndroid, String mediaRouteId, String message);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/router/MediaRouteManager.java b/chrome/android/java/src/org/chromium/chrome/browser/media/router/MediaRouteManager.java index 991fcd5..34ee889 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/router/MediaRouteManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/router/MediaRouteManager.java
@@ -45,10 +45,18 @@ /** * Called when the route is closed either as a result of * {@link MediaRouteProvider#closeRoute(String)} or an external event (e.g. screen disconnect). + * @param mediaRouteId the id of the created route. */ public void onRouteClosed(String mediaRouteId); /** + * Called when the route is closed because of an error, for example, session launch failure. + * @param mediaRouteId the id of the created route. + * @param message The error message. + */ + public void onRouteClosedWithError(String mediaRouteId, String message); + + /** * Called when sending the message to the route finished. * @param success Indicates if the message was sent successfully. * @param callbackId The identifier of the callback to pass the result to.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CastMediaRouteProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CastMediaRouteProvider.java index 0a5e008..f6ed546d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CastMediaRouteProvider.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CastMediaRouteProvider.java
@@ -101,8 +101,12 @@ return new CastMediaRouteProvider(applicationContext, androidMediaRouter, manager); } - public void onRouteRequestError(String message, int requestId) { - mManager.onRouteRequestError(message, requestId); + public void onLaunchError() { + for (String routeId : mRoutes.keySet()) { + mManager.onRouteClosedWithError(routeId, "Launch error"); + } + mRoutes.clear(); + mClientRecords.clear(); } public void onSessionStopAction() {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CreateRouteRequest.java b/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CreateRouteRequest.java index ce4a2be..7139eaa 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CreateRouteRequest.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/router/cast/CreateRouteRequest.java
@@ -38,13 +38,6 @@ private static final int STATE_LAUNCH_SUCCEEDED = 4; private static final int STATE_TERMINATED = 5; - private static final String ERROR_NEW_ROUTE_LAUNCH_APPLICATION_FAILED = - "Launch application failed: %s, %s"; - private static final String ERROR_NEW_ROUTE_LAUNCH_APPLICATION_FAILED_STATUS = - "Launch application failed with status: %s, %d, %s"; - private static final String ERROR_NEW_ROUTE_CLIENT_CONNECTION_FAILED = - "GoogleApiClient connection failed: %d, %b"; - private class CastListener extends Cast.Listener { private CastSession mSession; @@ -195,8 +188,8 @@ .setResultCallback(this); mState = STATE_LAUNCHING_APPLICATION; } catch (Exception e) { - reportError(String.format(ERROR_NEW_ROUTE_LAUNCH_APPLICATION_FAILED, - mSource.getApplicationId(), e)); + Log.e(TAG, "Launch application failed: %s", mSource.getApplicationId(), e); + reportError(); } } @@ -216,11 +209,9 @@ Status status = result.getStatus(); if (!status.isSuccess()) { - reportError(String.format( - ERROR_NEW_ROUTE_LAUNCH_APPLICATION_FAILED_STATUS, - mSource.getApplicationId(), - status.getStatusCode(), - status.getStatusMessage())); + Log.e(TAG, "Launch application failed with status: %s, %d, %s", + mSource.getApplicationId(), status.getStatusCode(), status.getStatusMessage()); + reportError(); } mState = STATE_LAUNCH_SUCCEEDED; @@ -233,10 +224,9 @@ public void onConnectionFailed(ConnectionResult result) { if (mState != STATE_CONNECTING_TO_API) throwInvalidState(); - reportError(String.format( - ERROR_NEW_ROUTE_CLIENT_CONNECTION_FAILED, - result.getErrorCode(), - result.hasResolution())); + Log.e(TAG, "GoogleApiClient connection failed: %d, %b", + result.getErrorCode(), result.hasResolution()); + reportError(); } private GoogleApiClient createApiClient(Cast.Listener listener, Context context) { @@ -283,11 +273,11 @@ terminate(); } - private void reportError(String message) { + private void reportError() { if (mState == STATE_TERMINATED) throwInvalidState(); assert mRouteProvider != null; - mRouteProvider.onRouteRequestError(message, mRequestId); + mRouteProvider.onLaunchError(); terminate(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/nfc/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/nfc/OWNERS deleted file mode 100644 index 577bf987..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/nfc/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -aurimas@chromium.org -newt@chromium.org
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/AnswerTextBuilder.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/AnswerTextBuilder.java index 9904bf3d..666c928 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/AnswerTextBuilder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/AnswerTextBuilder.java
@@ -25,64 +25,50 @@ private static final String TAG = "AnswerTextBuilder"; // Types, sizes and colors specified at http://goto.google.com/ais_api. - private static final int ANSWERS_ANSWER_TEXT_TYPE = 1; - private static final int ANSWERS_HEADLINE_TEXT_TYPE = 2; + // Deprecated: ANSWERS_ANSWER_TEXT_TYPE = 1; + // Deprecated: ANSWERS_HEADLINE_TEXT_TYPE = 2; private static final int ANSWERS_TOP_ALIGNED_TEXT_TYPE = 3; - private static final int ANSWERS_DESCRIPTION_TEXT_TYPE = 4; + // Deprecated: ANSWERS_DESCRIPTION_TEXT_TYPE = 4; private static final int ANSWERS_DESCRIPTION_TEXT_NEGATIVE_TYPE = 5; private static final int ANSWERS_DESCRIPTION_TEXT_POSITIVE_TYPE = 6; - private static final int ANSWERS_MORE_INFO_TEXT_TYPE = 7; + // Deprecated: ANSWERS_MORE_INFO_TEXT_TYPE = 7; private static final int ANSWERS_SUGGESTION_TEXT_TYPE = 8; - private static final int ANSWERS_SUGGESTION_TEXT_POSITIVE_TYPE = 9; - private static final int ANSWERS_SUGGESTION_TEXT_NEGATIVE_TYPE = 10; - private static final int ANSWERS_SUGGESTION_LINK_COLOR_TYPE = 11; - private static final int ANSWERS_STATUS_TEXT_TYPE = 12; + // Deprecated: ANSWERS_SUGGESTION_TEXT_POSITIVE_TYPE = 9; + // Deprecated: ANSWERS_SUGGESTION_TEXT_NEGATIVE_TYPE = 10; + // Deprecated: ANSWERS_SUGGESTION_LINK_COLOR_TYPE = 11; + // Deprecated: ANSWERS_STATUS_TEXT_TYPE = 12; private static final int ANSWERS_PERSONALIZED_SUGGESTION_TEXT_TYPE = 13; - // Deprecated: IMMERSIVE_DESCRIPTION_TEXT = 14, - // Deprecated: DATE_TEXT = 15, - // Deprecated: PREVIEW_TEXT = 16, + // Deprecated: ANSWERS_IMMERSIVE_DESCRIPTION_TEXT = 14; + // Deprecated: ANSWERS_DATE_TEXT = 15; + // Deprecated: ANSWERS_PREVIEW_TEXT = 16; private static final int ANSWERS_ANSWER_TEXT_MEDIUM_TYPE = 17; private static final int ANSWERS_ANSWER_TEXT_LARGE_TYPE = 18; private static final int ANSWERS_SECONDARY_TEXT_SMALL_TYPE = 19; private static final int ANSWERS_SECONDARY_TEXT_MEDIUM_TYPE = 20; - private static final int ANSWERS_ANSWER_TEXT_SIZE_SP = 28; - private static final int ANSWERS_HEADLINE_TEXT_SIZE_SP = 24; private static final int ANSWERS_TOP_ALIGNED_TEXT_SIZE_SP = 12; - private static final int ANSWERS_DESCRIPTION_TEXT_SIZE_SP = 15; private static final int ANSWERS_DESCRIPTION_TEXT_NEGATIVE_SIZE_SP = 16; private static final int ANSWERS_DESCRIPTION_TEXT_POSITIVE_SIZE_SP = 16; - private static final int ANSWERS_MORE_INFO_TEXT_SIZE_SP = 12; private static final int ANSWERS_SUGGESTION_TEXT_SIZE_SP = 16; - private static final int ANSWERS_SUGGESTION_TEXT_POSITIVE_SIZE_SP = 15; - private static final int ANSWERS_SUGGESTION_TEXT_NEGATIVE_SIZE_SP = 15; - private static final int ANSWERS_SUGGESTION_LINK_COLOR_SIZE_SP = 15; - private static final int ANSWERS_STATUS_TEXT_SIZE_SP = 13; private static final int ANSWERS_PERSONALIZED_SUGGESTION_TEXT_SIZE_SP = 15; private static final int ANSWERS_ANSWER_TEXT_MEDIUM_SIZE_SP = 20; private static final int ANSWERS_ANSWER_TEXT_LARGE_SIZE_SP = 24; private static final int ANSWERS_SECONDARY_TEXT_SMALL_SIZE_SP = 12; private static final int ANSWERS_SECONDARY_TEXT_MEDIUM_SIZE_SP = 14; - private static final int ANSWERS_ANSWER_TEXT_COLOR = 0xFF212121; - private static final int ANSWERS_HEADLINE_TEXT_COLOR = Color.BLACK; private static final int ANSWERS_TOP_ALIGNED_TEXT_COLOR = 0xFF8A8A8A; - private static final int ANSWERS_DESCRIPTION_TEXT_COLOR = Color.BLACK; // These two colors deviate from the AIS spec because they provide better // contrast over the background in Chrome, but they do come from the // Google pallette. private static final int ANSWERS_DESCRIPTION_TEXT_NEGATIVE_COLOR = 0xFFC53929; private static final int ANSWERS_DESCRIPTION_TEXT_POSITIVE_COLOR = 0xFF0B8043; - private static final int ANSWERS_MORE_INFO_TEXT_COLOR = Color.BLACK; - private static final int ANSWERS_SUGGESTION_TEXT_COLOR = 0xFF212121; - private static final int ANSWERS_SUGGESTION_TEXT_POSITIVE_COLOR = Color.GREEN; - private static final int ANSWERS_SUGGESTION_TEXT_NEGATIVE_COLOR = Color.RED; - // TODO(jdonnelly): Links should be purple if visited. - private static final int ANSWERS_SUGGESTION_LINK_COLOR_COLOR = Color.BLUE; - private static final int ANSWERS_STATUS_TEXT_COLOR = Color.GRAY; + private static final int ANSWERS_SUGGESTION_TEXT_COLOR = + SuggestionView.TITLE_COLOR_STANDARD_FONT_DARK; private static final int ANSWERS_PERSONALIZED_SUGGESTION_TEXT_COLOR = Color.BLACK; - private static final int ANSWERS_ANSWER_TEXT_MEDIUM_COLOR = 0xFF212121; - private static final int ANSWERS_ANSWER_TEXT_LARGE_COLOR = 0xFF212121; + private static final int ANSWERS_ANSWER_TEXT_MEDIUM_COLOR = + SuggestionView.TITLE_COLOR_STANDARD_FONT_DARK; + private static final int ANSWERS_ANSWER_TEXT_LARGE_COLOR = + SuggestionView.TITLE_COLOR_STANDARD_FONT_DARK; private static final int ANSWERS_SECONDARY_TEXT_SMALL_COLOR = 0xFF8A8A8A; private static final int ANSWERS_SECONDARY_TEXT_MEDIUM_COLOR = 0xFF8A8A8A; @@ -202,30 +188,14 @@ */ private static int getAnswerTextSizeSp(int type) { switch (type) { - case ANSWERS_ANSWER_TEXT_TYPE: - return ANSWERS_ANSWER_TEXT_SIZE_SP; - case ANSWERS_HEADLINE_TEXT_TYPE: - return ANSWERS_HEADLINE_TEXT_SIZE_SP; case ANSWERS_TOP_ALIGNED_TEXT_TYPE: return ANSWERS_TOP_ALIGNED_TEXT_SIZE_SP; - case ANSWERS_DESCRIPTION_TEXT_TYPE: - return ANSWERS_DESCRIPTION_TEXT_SIZE_SP; case ANSWERS_DESCRIPTION_TEXT_NEGATIVE_TYPE: return ANSWERS_DESCRIPTION_TEXT_NEGATIVE_SIZE_SP; case ANSWERS_DESCRIPTION_TEXT_POSITIVE_TYPE: return ANSWERS_DESCRIPTION_TEXT_POSITIVE_SIZE_SP; - case ANSWERS_MORE_INFO_TEXT_TYPE: - return ANSWERS_MORE_INFO_TEXT_SIZE_SP; case ANSWERS_SUGGESTION_TEXT_TYPE: return ANSWERS_SUGGESTION_TEXT_SIZE_SP; - case ANSWERS_SUGGESTION_TEXT_POSITIVE_TYPE: - return ANSWERS_SUGGESTION_TEXT_POSITIVE_SIZE_SP; - case ANSWERS_SUGGESTION_TEXT_NEGATIVE_TYPE: - return ANSWERS_SUGGESTION_TEXT_NEGATIVE_SIZE_SP; - case ANSWERS_SUGGESTION_LINK_COLOR_TYPE: - return ANSWERS_SUGGESTION_LINK_COLOR_SIZE_SP; - case ANSWERS_STATUS_TEXT_TYPE: - return ANSWERS_STATUS_TEXT_SIZE_SP; case ANSWERS_PERSONALIZED_SUGGESTION_TEXT_TYPE: return ANSWERS_PERSONALIZED_SUGGESTION_TEXT_SIZE_SP; case ANSWERS_ANSWER_TEXT_MEDIUM_TYPE: @@ -249,30 +219,14 @@ */ private static int getAnswerTextColor(int type) { switch (type) { - case ANSWERS_ANSWER_TEXT_TYPE: - return ANSWERS_ANSWER_TEXT_COLOR; - case ANSWERS_HEADLINE_TEXT_TYPE: - return ANSWERS_HEADLINE_TEXT_COLOR; case ANSWERS_TOP_ALIGNED_TEXT_TYPE: return ANSWERS_TOP_ALIGNED_TEXT_COLOR; - case ANSWERS_DESCRIPTION_TEXT_TYPE: - return ANSWERS_DESCRIPTION_TEXT_COLOR; case ANSWERS_DESCRIPTION_TEXT_NEGATIVE_TYPE: return ANSWERS_DESCRIPTION_TEXT_NEGATIVE_COLOR; case ANSWERS_DESCRIPTION_TEXT_POSITIVE_TYPE: return ANSWERS_DESCRIPTION_TEXT_POSITIVE_COLOR; - case ANSWERS_MORE_INFO_TEXT_TYPE: - return ANSWERS_MORE_INFO_TEXT_COLOR; case ANSWERS_SUGGESTION_TEXT_TYPE: return ANSWERS_SUGGESTION_TEXT_COLOR; - case ANSWERS_SUGGESTION_TEXT_POSITIVE_TYPE: - return ANSWERS_SUGGESTION_TEXT_POSITIVE_COLOR; - case ANSWERS_SUGGESTION_TEXT_NEGATIVE_TYPE: - return ANSWERS_SUGGESTION_TEXT_NEGATIVE_COLOR; - case ANSWERS_SUGGESTION_LINK_COLOR_TYPE: - return ANSWERS_SUGGESTION_LINK_COLOR_COLOR; - case ANSWERS_STATUS_TEXT_TYPE: - return ANSWERS_STATUS_TEXT_COLOR; case ANSWERS_PERSONALIZED_SUGGESTION_TEXT_TYPE: return ANSWERS_PERSONALIZED_SUGGESTION_TEXT_COLOR; case ANSWERS_ANSWER_TEXT_MEDIUM_TYPE:
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarTablet.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarTablet.java index 2577935d..a8a4f4a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarTablet.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/LocationBarTablet.java
@@ -94,6 +94,7 @@ private float mWidthChangePercent; private float mLayoutLeft; private float mLayoutRight; + private int mToolbarStartPaddingDifference; /** * Constructor used to inflate from XML. @@ -343,9 +344,13 @@ * while width of the location bar gets smaller. There are toolbar buttons that also show at * the same time, causing the width of the location bar to change. * + * @param toolbarStartPaddingDifference The difference in the toolbar's start padding between + * the beginning and end of the animation. * @return An ArrayList of animators to run. */ - public List<Animator> getShowButtonsWhenUnfocusedAnimators() { + public List<Animator> getShowButtonsWhenUnfocusedAnimators(int toolbarStartPaddingDifference) { + mToolbarStartPaddingDifference = toolbarStartPaddingDifference; + ArrayList<Animator> animators = new ArrayList<>(); Animator widthChangeAnimator = ObjectAnimator.ofFloat( @@ -391,9 +396,13 @@ * while width of the location bar gets larger. There are toolbar buttons that also hide at the * same time, causing the width of the location bar to change. * + * @param toolbarStartPaddingDifference The difference in the toolbar's start padding between + * the beginning and end of the animation. * @return An ArrayList of animators to run. */ - public List<Animator> getHideButtonsWhenUnfocusedAnimators() { + public List<Animator> getHideButtonsWhenUnfocusedAnimators(int toolbarStartPaddingDifference) { + mToolbarStartPaddingDifference = toolbarStartPaddingDifference; + ArrayList<Animator> animators = new ArrayList<>(); Animator widthChangeAnimator = @@ -463,7 +472,7 @@ */ private void setWidthChangeAnimationPercent(float percent) { mWidthChangePercent = percent; - float offset = mToolbarButtonsWidth * percent; + float offset = (mToolbarButtonsWidth + mToolbarStartPaddingDifference) * percent; if (LocalizationUtils.isLayoutRtl()) { // The location bar's right edge is its regular layout position when toolbar buttons are
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/SuggestionView.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/SuggestionView.java index d1f7dba..d9e3df0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/SuggestionView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/SuggestionView.java
@@ -57,7 +57,7 @@ private static final long RELAYOUT_DELAY_MS = 20; - private static final int TITLE_COLOR_STANDARD_FONT_DARK = 0xFF333333; + static final int TITLE_COLOR_STANDARD_FONT_DARK = 0xFF333333; private static final int TITLE_COLOR_STANDARD_FONT_LIGHT = 0xFFFFFFFF; private static final int URL_COLOR = 0xFF5595FE;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/physicalweb/PhysicalWebUma.java b/chrome/android/java/src/org/chromium/chrome/browser/physicalweb/PhysicalWebUma.java index 867f56f..780402e8 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/physicalweb/PhysicalWebUma.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/physicalweb/PhysicalWebUma.java
@@ -53,6 +53,16 @@ private static final String TOTAL_URLS_REFRESH_COUNTS = "PhysicalWeb.TotalUrls.OnRefresh"; private static final String ACTIVITY_REFERRALS = "PhysicalWeb.ActivityReferral"; + private static final String PHYSICAL_WEB_STATE = "PhysicalWeb.State"; + private static final String LAUNCH_FROM_PREFERENCES = "LaunchFromPreferences"; + private static final String LAUNCH_FROM_DIAGNOSTICS = "LaunchFromDiagnostics"; + private static final String BLUETOOTH = "Bluetooth"; + private static final String DATA_CONNECTION = "DataConnection"; + private static final String LOCATION_PERMISSION = "LocationPermission"; + private static final String LOCATION_SERVICES = "LocationServices"; + private static final String PREFERENCE = "Preference"; + private static final int BOOLEAN_BOUNDARY = 2; + private static final int TRISTATE_BOUNDARY = 3; private static boolean sUploadAllowed = false; /** @@ -173,30 +183,56 @@ * histograms.xml. */ public static void onActivityReferral(Context context, int referer) { - if (sUploadAllowed) { - RecordHistogram.recordEnumeratedHistogram( - ACTIVITY_REFERRALS, referer, ListUrlsActivity.REFERER_BOUNDARY); - } else { - storeValue(context, ACTIVITY_REFERRALS, referer); - } - long delay; + handleEnum(context, ACTIVITY_REFERRALS, referer, ListUrlsActivity.REFERER_BOUNDARY); switch (referer) { case ListUrlsActivity.NOTIFICATION_REFERER: - delay = UrlManager.getInstance(context).getTimeSinceNotificationUpdate(); - handleTime(context, STANDARD_NOTIFICATION_PRESS_DELAYS, delay, + handleTime(context, STANDARD_NOTIFICATION_PRESS_DELAYS, + UrlManager.getInstance(context).getTimeSinceNotificationUpdate(), TimeUnit.MILLISECONDS); break; case ListUrlsActivity.OPTIN_REFERER: - delay = UrlManager.getInstance(context).getTimeSinceNotificationUpdate(); - handleTime(context, OPT_IN_NOTIFICATION_PRESS_DELAYS, delay, + handleTime(context, OPT_IN_NOTIFICATION_PRESS_DELAYS, + UrlManager.getInstance(context).getTimeSinceNotificationUpdate(), TimeUnit.MILLISECONDS); break; + case ListUrlsActivity.PREFERENCE_REFERER: + recordPhysicalWebState(context, LAUNCH_FROM_PREFERENCES); + break; + case ListUrlsActivity.DIAGNOSTICS_REFERER: + recordPhysicalWebState(context, LAUNCH_FROM_DIAGNOSTICS); + break; default: break; } } /** + * Calculate a Physical Web state. + * The Physical Web state includes: + * - The location provider + * - The location permission + * - The bluetooth status + * - The data connection status + * - The Physical Web preference status + */ + public static void recordPhysicalWebState(Context context, String actionName) { + handleEnum(context, createStateString(LOCATION_SERVICES, actionName), + Utils.isLocationServicesEnabled(context) ? 1 : 0, BOOLEAN_BOUNDARY); + handleEnum(context, createStateString(LOCATION_PERMISSION, actionName), + Utils.isLocationPermissionGranted(context) ? 1 : 0, BOOLEAN_BOUNDARY); + handleEnum(context, createStateString(BLUETOOTH, actionName), + Utils.getBluetoothEnabledStatus(context), TRISTATE_BOUNDARY); + handleEnum(context, createStateString(DATA_CONNECTION, actionName), + Utils.isDataConnectionActive(context) ? 1 : 0, BOOLEAN_BOUNDARY); + int preferenceState = 2; + if (!PhysicalWeb.isOnboarding(context)) { + preferenceState = PhysicalWeb.isPhysicalWebPreferenceEnabled(context) ? 1 : 0; + } + handleEnum(context, createStateString(PREFERENCE, actionName), + preferenceState, TRISTATE_BOUNDARY); + } + + /** * Uploads metrics that we have deferred for uploading. * Additionally, this method will cause future stat records not to be deferred and instead * uploaded immediately. @@ -212,6 +248,10 @@ } } + private static String createStateString(String stateName, String actionName) { + return PHYSICAL_WEB_STATE + "." + stateName + "." + actionName; + } + private static void storeAction(Context context, String key) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); int count = prefs.getInt(key, 0); @@ -256,6 +296,14 @@ } } + private static void handleEnum(Context context, String key, int value, int boundary) { + if (sUploadAllowed) { + RecordHistogram.recordEnumeratedHistogram(key, value, boundary); + } else { + storeValue(context, key, value); + } + } + private static class UmaUploader implements Runnable { SharedPreferences mPrefs; @@ -282,6 +330,22 @@ uploadCounts(TOTAL_URLS_INITIAL_COUNTS); uploadCounts(TOTAL_URLS_REFRESH_COUNTS); uploadEnums(ACTIVITY_REFERRALS, ListUrlsActivity.REFERER_BOUNDARY); + uploadEnums(createStateString(LOCATION_SERVICES, LAUNCH_FROM_DIAGNOSTICS), + BOOLEAN_BOUNDARY); + uploadEnums(createStateString(LOCATION_PERMISSION, LAUNCH_FROM_DIAGNOSTICS), + BOOLEAN_BOUNDARY); + uploadEnums(createStateString(BLUETOOTH, LAUNCH_FROM_DIAGNOSTICS), TRISTATE_BOUNDARY); + uploadEnums(createStateString(DATA_CONNECTION, LAUNCH_FROM_DIAGNOSTICS), + BOOLEAN_BOUNDARY); + uploadEnums(createStateString(PREFERENCE, LAUNCH_FROM_DIAGNOSTICS), TRISTATE_BOUNDARY); + uploadEnums(createStateString(LOCATION_SERVICES, LAUNCH_FROM_PREFERENCES), + BOOLEAN_BOUNDARY); + uploadEnums(createStateString(LOCATION_PERMISSION, LAUNCH_FROM_PREFERENCES), + BOOLEAN_BOUNDARY); + uploadEnums(createStateString(BLUETOOTH, LAUNCH_FROM_PREFERENCES), TRISTATE_BOUNDARY); + uploadEnums(createStateString(DATA_CONNECTION, LAUNCH_FROM_PREFERENCES), + BOOLEAN_BOUNDARY); + uploadEnums(createStateString(PREFERENCE, LAUNCH_FROM_PREFERENCES), TRISTATE_BOUNDARY); removePref(HAS_DEFERRED_METRICS_KEY); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/physicalweb/UrlManager.java b/chrome/android/java/src/org/chromium/chrome/browser/physicalweb/UrlManager.java index a71d7d8..e8b4f49 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/physicalweb/UrlManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/physicalweb/UrlManager.java
@@ -484,4 +484,14 @@ NotificationManagerProxy notificationManager) { mNotificationManager = notificationManager; } + + @VisibleForTesting + static void clearPrefsForTesting(Context context) { + PreferenceManager.getDefaultSharedPreferences(context).edit() + .remove(PREFS_VERSION_KEY) + .remove(PREFS_NEARBY_URLS_KEY) + .remove(PREFS_RESOLVED_URLS_KEY) + .remove(PREFS_NOTIFICATION_UPDATE_TIMESTAMP) + .apply(); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/autofill/AutofillCreditCardEditor.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/autofill/AutofillCreditCardEditor.java index 2bbb4af..83ca42c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/autofill/AutofillCreditCardEditor.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/autofill/AutofillCreditCardEditor.java
@@ -192,7 +192,8 @@ true /* isLocal */, false /* isCached */, mNameText.getText().toString().trim(), cardNumber, "" /* obfuscatedNumber */, String.valueOf(mExpirationMonth.getSelectedItemPosition() + 1), - (String) mExpirationYear.getSelectedItem()); + (String) mExpirationYear.getSelectedItem(), "" /* basicCardPaymentType */, + 0 /* issuerIconDrawableId */); PersonalDataManager.getInstance().setCreditCard(card); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/services/AccountsChangedReceiver.java b/chrome/android/java/src/org/chromium/chrome/browser/services/AccountsChangedReceiver.java index 3a6a219..ed514c4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/services/AccountsChangedReceiver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/services/AccountsChangedReceiver.java
@@ -72,7 +72,7 @@ AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { - SigninHelper.updateAccountRenameData(appContext); + SigninHelper.get(appContext).updateAccountRenameData(); return null; } @@ -94,7 +94,7 @@ startBrowserIfNeededAndValidateAccounts(context); } else { // Notify SigninHelper of changed accounts (via shared prefs). - SigninHelper.markAccountsChangedPref(context); + SigninHelper.get(context).markAccountsChangedPref(); } notifyAccountsChangedOnBrowserStartup(context, intent); } @@ -116,7 +116,7 @@ public void onStartupFailure() { // Startup failed. So notify SigninHelper of changed accounts via // shared prefs. - SigninHelper.markAccountsChangedPref(context); + SigninHelper.get(context).markAccountsChangedPref(); } }; try {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/services/GoogleServicesManager.java b/chrome/android/java/src/org/chromium/chrome/browser/services/GoogleServicesManager.java index 9c0ce2d..dffb8259 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/services/GoogleServicesManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/services/GoogleServicesManager.java
@@ -24,8 +24,8 @@ * - sets up the Android status bar notification controller. * - start Tango service if sync setup is completed. * <p/> - * It is intended to be an application level object and is not tied to any particulary - * activity, although re-verifies some settings whe browser is launched. + * It is intended to be an application level object and is not tied to any particularly + * activity, although re-verifies some settings when browser is launched. * <p/> * The object must be created on the main thread. * <p/> @@ -40,7 +40,7 @@ private static GoogleServicesManager sGoogleServicesManager; @VisibleForTesting - protected final Context mContext; + protected final Context mAppContext; private final ChromeSigninController mChromeSigninController; @@ -68,17 +68,17 @@ ThreadUtils.assertOnUiThread(); // We should store the application context, as we outlive any activity which may create // us. - mContext = context.getApplicationContext(); + mAppContext = context.getApplicationContext(); - mChromeSigninController = ChromeSigninController.get(mContext); - mSigninHelper = SigninHelper.get(mContext); + mChromeSigninController = ChromeSigninController.get(mAppContext); + mSigninHelper = SigninHelper.get(mAppContext); // The sign out flow starts by clearing the signed in user in the ChromeSigninController // on the Java side, and then performs a sign out on the native side. If there is a // crash on the native side then the signin state may get out of sync. Make sure that // the native side is signed out if the Java side doesn't have a currently signed in // user. - SigninManager signinManager = SigninManager.get(mContext); + SigninManager signinManager = SigninManager.get(mAppContext); if (!mChromeSigninController.isSignedIn() && signinManager.isSignedInOnNative()) { Log.w(TAG, "Signed in state got out of sync, forcing native sign out"); signinManager.signOut(); @@ -101,7 +101,7 @@ public void onMainActivityStart() { try { TraceEvent.begin("GoogleServicesManager.onMainActivityStart"); - boolean accountsChanged = SigninHelper.checkAndClearAccountsChangedPref(mContext); + boolean accountsChanged = mSigninHelper.checkAndClearAccountsChangedPref(); mSigninHelper.validateAccountSettings(accountsChanged); } finally { TraceEvent.end("GoogleServicesManager.onMainActivityStart");
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/share/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/share/OWNERS index c203f93..4eb7497 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/share/OWNERS +++ b/chrome/android/java/src/org/chromium/chrome/browser/share/OWNERS
@@ -1,2 +1 @@ -aurimas@chromium.org -dtrainor@chromium.org \ No newline at end of file +dtrainor@chromium.org
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninHelper.java index b01572db..a4669b82 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninHelper.java
@@ -100,7 +100,7 @@ @VisibleForTesting - protected final Context mContext; + protected final Context mAppContext; private final ChromeSigninController mChromeSigninController; @@ -112,6 +112,8 @@ private final OAuth2TokenService mOAuth2TokenService; + private SharedPreferences mSharedPreferences; + public static SigninHelper get(Context context) { synchronized (LOCK) { @@ -122,13 +124,39 @@ return sInstance; } - private SigninHelper(Context context) { - mContext = context; - mProfileSyncService = ProfileSyncService.get(); - mSigninManager = SigninManager.get(mContext); - mAccountTrackerService = AccountTrackerService.get(mContext); - mOAuth2TokenService = OAuth2TokenService.getForProfile(Profile.getLastUsedProfile()); - mChromeSigninController = ChromeSigninController.get(mContext); + /** + * Create an instance of SigninHelper without native dependencies for tests. + */ + @VisibleForTesting + public static void initializeForTests(Context context) { + synchronized (LOCK) { + Context appContext = context.getApplicationContext(); + sInstance = new SigninHelper(appContext, null, null, null, null, null, + PreferenceManager.getDefaultSharedPreferences(appContext)); + } + } + + private SigninHelper(Context appContext, ProfileSyncService profileSyncService, + SigninManager signinManager, AccountTrackerService accountTrackerService, + OAuth2TokenService oAuth2TokenService, ChromeSigninController chromeSigninController, + SharedPreferences sharedPreferences) { + mAppContext = appContext; + mProfileSyncService = profileSyncService; + mSigninManager = signinManager; + mAccountTrackerService = accountTrackerService; + mOAuth2TokenService = oAuth2TokenService; + mChromeSigninController = chromeSigninController; + mSharedPreferences = sharedPreferences; + } + + private SigninHelper(Context appContext) { + this(appContext, + ProfileSyncService.get(), + SigninManager.get(appContext), + AccountTrackerService.get(appContext), + OAuth2TokenService.getForProfile(Profile.getLastUsedProfile()), + ChromeSigninController.get(appContext), + PreferenceManager.getDefaultSharedPreferences(appContext)); } public void validateAccountSettings(boolean accountsChanged) { @@ -144,18 +172,17 @@ PrefServiceBridge.getInstance().getSyncLastAccountName(); if (lastSyncAccountName != null && !lastSyncAccountName.isEmpty()) return; - SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext); - boolean hasKnownAccountKeys = sharedPrefs.contains(ANDROID_ACCOUNTS_PREFS_KEY); + boolean hasKnownAccountKeys = mSharedPreferences.contains(ANDROID_ACCOUNTS_PREFS_KEY); // Nothing to do if Android accounts are not changed and already known to Chrome. if (hasKnownAccountKeys && !accountsChanged) return; List<String> currentAccountNames = - AccountManagerHelper.get(mContext).getGoogleAccountNames(); + AccountManagerHelper.get(mAppContext).getGoogleAccountNames(); if (hasKnownAccountKeys) { ChromePreferenceManager chromePreferenceManager = - ChromePreferenceManager.getInstance(mContext); + ChromePreferenceManager.getInstance(mAppContext); if (!chromePreferenceManager.getSigninPromoShown()) { - Set<String> lastKnownAccountNames = sharedPrefs.getStringSet( + Set<String> lastKnownAccountNames = mSharedPreferences.getStringSet( ANDROID_ACCOUNTS_PREFS_KEY, new HashSet<String>()); Set<String> newAccountNames = new HashSet<String>(currentAccountNames); newAccountNames.removeAll(lastKnownAccountNames); @@ -165,33 +192,33 @@ } } - sharedPrefs.edit().putStringSet( + mSharedPreferences.edit().putStringSet( ANDROID_ACCOUNTS_PREFS_KEY, new HashSet<String>(currentAccountNames)).apply(); return; } - String renamedAccount = getNewSignedInAccountName(mContext); + String renamedAccount = getNewSignedInAccountName(); if (accountsChanged && renamedAccount != null) { - handleAccountRename(ChromeSigninController.get(mContext).getSignedInAccountName(), + handleAccountRename(ChromeSigninController.get(mAppContext).getSignedInAccountName(), renamedAccount); return; } // Always check for account deleted. - if (!accountExists(mContext, syncAccount)) { + if (!accountExists(syncAccount)) { // It is possible that Chrome got to this point without account // rename notification. Let us signout before doing a rename. // updateAccountRenameData(mContext, new SystemAccountChangeEventChecker()); AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { - updateAccountRenameData(mContext, new SystemAccountChangeEventChecker()); + updateAccountRenameData(new SystemAccountChangeEventChecker()); return null; } @Override protected void onPostExecute(Void result) { - String renamedAccount = getNewSignedInAccountName(mContext); + String renamedAccount = getNewSignedInAccountName(); if (renamedAccount == null) { mSigninManager.signOut(); } else { @@ -206,10 +233,10 @@ if (accountsChanged) { // Account details have changed so inform the token service that credentials // should now be available. - mOAuth2TokenService.validateAccounts(mContext, false); + mOAuth2TokenService.validateAccounts(mAppContext, false); } - if (mProfileSyncService != null && AndroidSyncSettings.isSyncEnabled(mContext)) { + if (mProfileSyncService != null && AndroidSyncSettings.isSyncEnabled(mAppContext)) { if (mProfileSyncService.isFirstSetupComplete()) { if (accountsChanged) { // Nudge the syncer to ensure it does a full sync. @@ -244,7 +271,7 @@ // If Chrome dies, we can try it again on next run. // Otherwise, if re-sign-in fails, we'll just leave chrome // signed-out. - clearNewSignedInAccountName(mContext); + clearNewSignedInAccountName(); performResignin(newName); } }); @@ -268,8 +295,8 @@ }); } - private static boolean accountExists(Context context, Account account) { - Account[] accounts = AccountManagerHelper.get(context).getGoogleAccounts(); + private boolean accountExists(Account account) { + Account[] accounts = AccountManagerHelper.get(mAppContext).getGoogleAccounts(); for (Account a : accounts) { if (a.equals(account)) { return true; @@ -281,48 +308,46 @@ /** * Sets the ACCOUNTS_CHANGED_PREFS_KEY to true. */ - public static void markAccountsChangedPref(Context context) { + public void markAccountsChangedPref() { // The process may go away as soon as we return from onReceive but Android makes sure // that in-flight disk writes from apply() complete before changing component states. - PreferenceManager.getDefaultSharedPreferences(context) - .edit().putBoolean(ACCOUNTS_CHANGED_PREFS_KEY, true).apply(); + mSharedPreferences.edit().putBoolean(ACCOUNTS_CHANGED_PREFS_KEY, true).apply(); } /** * @return The new account name of the current user. Null if it wasn't renamed. */ - public static String getNewSignedInAccountName(Context context) { - return (PreferenceManager.getDefaultSharedPreferences(context) - .getString(ACCOUNT_RENAMED_PREFS_KEY, null)); + @VisibleForTesting + public String getNewSignedInAccountName() { + return (mSharedPreferences.getString(ACCOUNT_RENAMED_PREFS_KEY, null)); } - private static void clearNewSignedInAccountName(Context context) { - PreferenceManager.getDefaultSharedPreferences(context) - .edit() - .putString(ACCOUNT_RENAMED_PREFS_KEY, null) - .apply(); + private void clearNewSignedInAccountName() { + mSharedPreferences.edit().putString(ACCOUNT_RENAMED_PREFS_KEY, null).apply(); } - private static String getLastKnownAccountName(Context context) { + private String getLastKnownAccountName() { // This is the last known name of the currently signed in user. // It can be: // 1. The signed in account name known to the ChromeSigninController. // 2. A pending newly choosen name that is differed from the one known to // ChromeSigninController but is stored in ACCOUNT_RENAMED_PREFS_KEY. - String name = PreferenceManager.getDefaultSharedPreferences(context).getString( - ACCOUNT_RENAMED_PREFS_KEY, null); + String name = mSharedPreferences.getString(ACCOUNT_RENAMED_PREFS_KEY, null); // If there is no pending rename, take the name known to ChromeSigninController. - return name == null ? ChromeSigninController.get(context).getSignedInAccountName() : name; + if (name == null) { + return ChromeSigninController.get(mAppContext).getSignedInAccountName(); + } + return name; } - public static void updateAccountRenameData(Context context) { - updateAccountRenameData(context, new SystemAccountChangeEventChecker()); + public void updateAccountRenameData() { + updateAccountRenameData(new SystemAccountChangeEventChecker()); } @VisibleForTesting - public static void updateAccountRenameData(Context context, AccountChangeEventChecker checker) { - String curName = getLastKnownAccountName(context); + public void updateAccountRenameData(AccountChangeEventChecker checker) { + String curName = getLastKnownAccountName(); // Skip the search if there is no signed in account. if (curName == null) return; @@ -330,7 +355,7 @@ String newName = curName; // This is the last read index of all the account change event. - int eventIndex = PreferenceManager.getDefaultSharedPreferences(context).getInt( + int eventIndex = mSharedPreferences.getInt( ACCOUNT_RENAME_EVENT_INDEX_PREFS_KEY, 0); int newIndex = eventIndex; @@ -338,7 +363,7 @@ try { outerLoop: while (true) { - List<String> nameChanges = checker.getAccountChangeEvents(context, + List<String> nameChanges = checker.getAccountChangeEvents(mAppContext, newIndex, newName); for (String name : nameChanges) { @@ -346,8 +371,7 @@ // We have found a rename event of the current account. // We need to check if that account is further renamed. newName = name; - if (!accountExists(context, AccountManagerHelper.get(context) - .createAccountFromName(newName))) { + if (!accountExists(AccountManagerHelper.createAccountFromName(newName))) { newIndex = 0; // Start from the beginning of the new account. continue outerLoop; } @@ -365,31 +389,26 @@ } if (!curName.equals(newName)) { - PreferenceManager.getDefaultSharedPreferences(context) - .edit().putString(ACCOUNT_RENAMED_PREFS_KEY, newName).apply(); + mSharedPreferences.edit().putString(ACCOUNT_RENAMED_PREFS_KEY, newName).apply(); } if (newIndex != eventIndex) { - PreferenceManager.getDefaultSharedPreferences(context) - .edit().putInt(ACCOUNT_RENAME_EVENT_INDEX_PREFS_KEY, newIndex).apply(); + mSharedPreferences.edit().putInt( + ACCOUNT_RENAME_EVENT_INDEX_PREFS_KEY, newIndex).apply(); } } @VisibleForTesting - public static void resetAccountRenameEventIndex(Context context) { - PreferenceManager.getDefaultSharedPreferences(context) - .edit().putInt(ACCOUNT_RENAME_EVENT_INDEX_PREFS_KEY, 0).apply(); + public void resetAccountRenameEventIndex() { + mSharedPreferences.edit().putInt(ACCOUNT_RENAME_EVENT_INDEX_PREFS_KEY, 0).apply(); } - public static boolean checkAndClearAccountsChangedPref(Context context) { - if (PreferenceManager.getDefaultSharedPreferences(context) - .getBoolean(ACCOUNTS_CHANGED_PREFS_KEY, false)) { + public boolean checkAndClearAccountsChangedPref() { + if (mSharedPreferences.getBoolean(ACCOUNTS_CHANGED_PREFS_KEY, false)) { // Clear the value in prefs. - PreferenceManager.getDefaultSharedPreferences(context) - .edit().putBoolean(ACCOUNTS_CHANGED_PREFS_KEY, false).apply(); + mSharedPreferences.edit().putBoolean(ACCOUNTS_CHANGED_PREFS_KEY, false).apply(); return true; - } else { - return false; } + return false; } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarTablet.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarTablet.java index 5fca0368..ad6b6568 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarTablet.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarTablet.java
@@ -488,10 +488,16 @@ button.setVisibility(visible ? View.VISIBLE : View.GONE); } mLocationBar.setShouldShowButtonsWhenUnfocused(visible); + setStartPaddingBasedOnButtonVisibility(visible); } + } - boolean buttonsVisible = mHomeButton.getVisibility() == View.VISIBLE - || visible; + /** + * Sets the toolbar start padding based on whether the buttons are visible. + * @param buttonsVisible Whether the toolbar buttons are visible. + */ + private void setStartPaddingBasedOnButtonVisibility(boolean buttonsVisible) { + buttonsVisible = buttonsVisible || mHomeButton.getVisibility() == View.VISIBLE; ApiCompatibilityUtils.setPaddingRelative(this, buttonsVisible ? mStartPaddingWithButtons : mStartPaddingWithoutButtons, @@ -500,11 +506,21 @@ getPaddingBottom()); } + /** + * @return The difference in start padding when the buttons are visible and when they are not + * visible. + */ + public int getStartPaddingDifferenceForButtonVisibilityAnimation() { + // If the home button is visible then the padding doesn't change. + return mHomeButton.getVisibility() == View.VISIBLE ? 0 + : mStartPaddingWithButtons - mStartPaddingWithoutButtons; + } + private void runToolbarButtonsVisibilityAnimation(boolean visible) { if (mButtonVisibilityAnimators != null) mButtonVisibilityAnimators.cancel(); mButtonVisibilityAnimators = visible ? buildShowToolbarButtonsAnimation() - : buildHideToolbarButtonsAniamtion(); + : buildHideToolbarButtonsAnimation(); mButtonVisibilityAnimators.start(); } @@ -517,7 +533,8 @@ } // Add animators for location bar. - animators.addAll(mLocationBar.getShowButtonsWhenUnfocusedAnimators()); + animators.addAll(mLocationBar.getShowButtonsWhenUnfocusedAnimators( + getStartPaddingDifferenceForButtonVisibilityAnimation())); AnimatorSet set = new AnimatorSet(); set.playTogether(animators); @@ -528,6 +545,9 @@ for (TintedImageButton button : mToolbarButtons) { button.setVisibility(View.VISIBLE); } + // Set the padding at the start of the animation so the toolbar buttons don't jump + // when the animation ends. + setStartPaddingBasedOnButtonVisibility(true); } @Override @@ -539,7 +559,7 @@ return set; } - private AnimatorSet buildHideToolbarButtonsAniamtion() { + private AnimatorSet buildHideToolbarButtonsAnimation() { Collection<Animator> animators = new ArrayList<>(); // Create animators for all of the toolbar buttons. @@ -548,7 +568,8 @@ } // Add animators for location bar. - animators.addAll(mLocationBar.getHideButtonsWhenUnfocusedAnimators()); + animators.addAll(mLocationBar.getHideButtonsWhenUnfocusedAnimators( + getStartPaddingDifferenceForButtonVisibilityAnimation())); AnimatorSet set = new AnimatorSet(); set.playTogether(animators); @@ -556,10 +577,18 @@ set.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { - for (TintedImageButton button : mToolbarButtons) { - button.setVisibility(View.GONE); - button.setAlpha(1.f); + // Only set end visibility and alpha if the animation is ending because it's + // completely finished and not because it was canceled. + if (mToolbarButtons[0].getAlpha() == 0.f) { + for (TintedImageButton button : mToolbarButtons) { + button.setVisibility(View.GONE); + button.setAlpha(1.f); + } + // Set the padding at the end of the animation so the toolbar buttons don't jump + // when the animation starts. + setStartPaddingBasedOnButtonVisibility(false); } + mButtonVisibilityAnimators = null; } });
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/util/FeatureUtilities.java b/chrome/android/java/src/org/chromium/chrome/browser/util/FeatureUtilities.java index d0d01f7..1f74eacc 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/util/FeatureUtilities.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/util/FeatureUtilities.java
@@ -155,6 +155,14 @@ } /** + * Records whether the activity is in multi-window mode with native-side feature utilities. + * @param isInMultiWindowMode Whether the activity is in Android N multi-window mode. + */ + public static void setIsInMultiWindowMode(boolean isInMultiWindowMode) { + nativeSetIsInMultiWindowMode(isInMultiWindowMode); + } + + /** * Check whether tab switching is enabled for the current context. * Note that this may return false if native library is not yet ready. * @param context The context @@ -283,5 +291,6 @@ private static native void nativeSetDocumentModeEnabled(boolean enabled); private static native void nativeSetCustomTabVisible(boolean visible); + private static native void nativeSetIsInMultiWindowMode(boolean isInMultiWindowMode); public static native void nativeSetSqlMmapDisabledByDefault(); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/AudioTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/AudioTest.java index cd55dd99..586f7518 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/AudioTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/AudioTest.java
@@ -5,8 +5,8 @@ package org.chromium.chrome.browser; import android.os.Environment; -import android.test.FlakyTest; +import org.chromium.base.test.util.FlakyTest; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.test.ChromeActivityTestCaseBase; import org.chromium.chrome.test.util.browser.TabTitleObserver; @@ -41,12 +41,11 @@ /** * Test playing a small mp3 audio file. - * http://crbug.com/331122 * @Feature({"Media", "Media-Audio", "Main"}) * @MediumTest */ // TODO(jbudorick): Attempt to reenable this after the server switch has stabilized. - @FlakyTest + @FlakyTest(message = "crbug.com/331122") public void testPlayMp3() throws InterruptedException, TimeoutException { Tab tab = getActivity().getActivityTab(); TabTitleObserver titleObserver = new TabTitleObserver(tab, "ready_to_play");
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/ContentViewFocusTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/ContentViewFocusTest.java index e5b60bb4..a7a80a6 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/ContentViewFocusTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/ContentViewFocusTest.java
@@ -4,13 +4,13 @@ package org.chromium.chrome.browser; -import android.test.FlakyTest; import android.test.suitebuilder.annotation.MediumTest; import android.view.View; import android.view.View.OnFocusChangeListener; import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.Feature; +import org.chromium.base.test.util.FlakyTest; import org.chromium.base.test.util.Restriction; import org.chromium.base.test.util.UrlUtils; import org.chromium.chrome.R; @@ -78,9 +78,8 @@ * @MediumTest * @Feature({"TabContents"}) * @Restriction(RESTRICTION_TYPE_PHONE) - * Bug: http://crbug.com/172473 */ - @FlakyTest + @FlakyTest(message = "http://crbug.com/172473") public void testHideSelectionOnPhoneTabSwiping() throws Exception { // Setup ChromeTabUtils.newTabsFromMenu(getInstrumentation(), getActivity(), 2);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/PowerBroadcastReceiverTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/PowerBroadcastReceiverTest.java index 6102b17..cb27ba1a 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/PowerBroadcastReceiverTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/PowerBroadcastReceiverTest.java
@@ -6,10 +6,10 @@ import android.content.Context; import android.content.Intent; -import android.test.FlakyTest; import android.test.suitebuilder.annotation.MediumTest; import org.chromium.base.test.util.Feature; +import org.chromium.base.test.util.FlakyTest; import org.chromium.chrome.test.ChromeTabbedActivityTestBase; import org.chromium.chrome.test.util.ApplicationTestUtils; import org.chromium.content.browser.test.util.CallbackHelper; @@ -115,7 +115,7 @@ /** * Check that the runnable gets posted and canceled when Main is sent to the background. */ - @FlakyTest // https://crbug.com/579363 + @FlakyTest(message = "https://crbug.com/579363") @MediumTest @Feature({"Omaha", "Sync"}) public void testRunnableGetsCanceled() throws Exception { @@ -140,7 +140,7 @@ */ @MediumTest @Feature({"Omaha", "Sync"}) - @FlakyTest // https://crbug.com/587138 + @FlakyTest(message = "https://crbug.com/587138") public void testRunnableGetsRunWhenScreenIsOn() throws Exception { // Claim the screen is off. mReceiver.setPowerManagerHelperForTests(sScreenOff);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/PrerenderTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/PrerenderTest.java index 2ea23ed..bf1c479 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/PrerenderTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/PrerenderTest.java
@@ -7,13 +7,13 @@ import static org.chromium.base.test.util.Restriction.RESTRICTION_TYPE_NON_LOW_END_DEVICE; import android.os.Environment; -import android.test.FlakyTest; import android.test.MoreAsserts; import android.test.suitebuilder.annotation.LargeTest; import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; +import org.chromium.base.test.util.FlakyTest; import org.chromium.base.test.util.Restriction; import org.chromium.chrome.browser.prerender.ExternalPrerenderHandler; import org.chromium.chrome.browser.tab.Tab; @@ -73,12 +73,11 @@ } /* - crbug.com/339668 @LargeTest @Restriction({RESTRICTION_TYPE_NON_LOW_END_DEVICE}) @Feature({"TabContents"}) */ - @FlakyTest + @FlakyTest(message = "crbug.com/339668") public void testPrerenderNotDead() throws InterruptedException, TimeoutException { String testUrl = mTestServer.getURL( "/chrome/test/data/android/prerender/google.html");
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/TabsOpenedFromExternalAppTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/TabsOpenedFromExternalAppTest.java index e1d1efd0..7003571 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/TabsOpenedFromExternalAppTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/TabsOpenedFromExternalAppTest.java
@@ -9,7 +9,6 @@ import android.os.Bundle; import android.os.Environment; import android.provider.Browser; -import android.test.FlakyTest; import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.MediumTest; import android.text.TextUtils; @@ -22,6 +21,7 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Feature; +import org.chromium.base.test.util.FlakyTest; import org.chromium.chrome.R; import org.chromium.chrome.browser.tab.EmptyTabObserver; import org.chromium.chrome.browser.tab.Tab; @@ -498,9 +498,8 @@ /** * @LargeTest * @Feature({"Navigation"}) - * Bug 6467101 */ - @FlakyTest + @FlakyTest(message = "http://crbug.com/6467101") public void testNewTabWhenPageEdited() throws InterruptedException, TimeoutException { startMainActivityFromLauncher(); @@ -546,9 +545,8 @@ /** * Catches regressions for https://crbug.com/495877. - * Flakiness reported in https://crbug.com/571030 */ - @FlakyTest + @FlakyTest(message = "https://crbug.com/571030") @MediumTest @CommandLineFlags.Add(BaseSwitches.ENABLE_LOW_END_DEVICE_MODE) public void testBackgroundSvelteTabIsSelectedAfterClosingExternalTab() throws Exception {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/TabsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/TabsTest.java index 914deec..929aa28 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/TabsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/TabsTest.java
@@ -11,7 +11,6 @@ import android.os.Debug; import android.os.Environment; import android.os.SystemClock; -import android.test.FlakyTest; import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; @@ -27,6 +26,7 @@ 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.FlakyTest; import org.chromium.base.test.util.Restriction; import org.chromium.base.test.util.UrlUtils; import org.chromium.chrome.R; @@ -409,12 +409,11 @@ * Verify close button works in the TabSwitcher in landscape mode. * This code does not handle properly different screen densities. * @throws InterruptedException - * Bug: crbug.com/170179 * @Restriction({RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_NON_LOW_END_DEVICE}) * @LargeTest * @Feature({"Android-TabSwitcher"}) */ - @FlakyTest + @FlakyTest(message = "crbug.com/170179") public void testTabSwitcherLandscapeCloseButton() throws InterruptedException { getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // Hard-coded coordinates of the close button on the bottom left of the screen. @@ -491,9 +490,8 @@ * @EnormousTest * @TimeoutScale(30) * @Feature({"Navigation"}) - * crbug/223110 */ - @FlakyTest + @FlakyTest(message = "crbug.com/223110") public void testOpenManyTabsAtOnce10() throws InterruptedException { openAndVerifyManyTestTabs(10); } @@ -620,11 +618,10 @@ * Verifies that the tab are actually stacking at the bottom and top of the screen. */ /** - * Bug: crbug.com/170179 * @LargeTest * @Feature({"Android-TabSwitcher"}) */ - @FlakyTest + @FlakyTest(message = "crbug.com/170179") @Restriction({ChromeRestriction.RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_NON_LOW_END_DEVICE}) public void testTabsStacking() throws InterruptedException { final int count = openTabs(12, false); @@ -686,11 +683,10 @@ * Verify that switching back and forth to the tabswitcher does not leak memory. */ /** - * Bug: crbug.com/303319 * @LargeTest * @Feature({"Android-TabSwitcher"}) */ - @FlakyTest + @FlakyTest(message = "crbug.com/303319") @Restriction(ChromeRestriction.RESTRICTION_TYPE_PHONE) public void testTabSwitcherMemoryLeak() throws InterruptedException { openTabs(4, true); @@ -759,11 +755,10 @@ } /** - * Bug: crbug.com/170179 * @LargeTest * @Feature({"Android-TabSwitcher"}) */ - @FlakyTest + @FlakyTest(message = "crbug.com/170179") @Restriction({ChromeRestriction.RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_NON_LOW_END_DEVICE}) public void testTabSelectionLandscape() throws InterruptedException { getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/appmenu/OWNERS b/chrome/android/javatests/src/org/chromium/chrome/browser/appmenu/OWNERS deleted file mode 100644 index 6b0cb442..0000000 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/appmenu/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -aurimas@chromium.org -kkimlabs@chromium.org \ No newline at end of file
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/AutofillKeyboardAccessoryTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/AutofillKeyboardAccessoryTest.java index d52cc49..88d92e7 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/AutofillKeyboardAccessoryTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/AutofillKeyboardAccessoryTest.java
@@ -4,7 +4,6 @@ package org.chromium.chrome.browser.autofill; -import android.test.FlakyTest; import android.test.suitebuilder.annotation.MediumTest; import android.view.View; import android.view.ViewGroup; @@ -13,6 +12,7 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Feature; +import org.chromium.base.test.util.FlakyTest; import org.chromium.base.test.util.UrlUtils; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ChromeSwitches; @@ -142,9 +142,8 @@ /* @MediumTest @Feature({"keyboard-accessory"}) - Bug https://crbug.com/563640 */ - @FlakyTest + @FlakyTest(message = "https://crbug.com/563640") public void testSwitchFieldsRescrollsKeyboardAccessory() throws ExecutionException, InterruptedException, TimeoutException { loadTestPage(false);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/OWNERS b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/OWNERS deleted file mode 100644 index 812e8d9..0000000 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -aurimas@chromium.org
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/compositor/overlays/strip/TabStripTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/compositor/overlays/strip/TabStripTest.java index eb60b9b..4315e95 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/compositor/overlays/strip/TabStripTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/compositor/overlays/strip/TabStripTest.java
@@ -5,11 +5,11 @@ package org.chromium.chrome.browser.compositor.overlays.strip; import android.content.pm.ActivityInfo; -import android.test.FlakyTest; import android.test.suitebuilder.annotation.LargeTest; import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.Feature; +import org.chromium.base.test.util.FlakyTest; import org.chromium.base.test.util.Restriction; import org.chromium.chrome.browser.compositor.layouts.components.CompositorButton; import org.chromium.chrome.browser.tab.Tab; @@ -80,7 +80,7 @@ @LargeTest @Restriction(ChromeRestriction.RESTRICTION_TYPE_TABLET) @Feature({"TabStrip"}) - @FlakyTest // crbug.com/592961 + @FlakyTest(message = "crbug.com/592961") public void testNewTabButtonWithManyTabs() throws InterruptedException { ChromeTabUtils.newTabsFromMenu(getInstrumentation(), getActivity(), 3); getInstrumentation().runOnMainSync(new Runnable() {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java index 63e2be7..f830f640 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java
@@ -17,7 +17,6 @@ import android.os.Environment; import android.os.SystemClock; import android.preference.PreferenceManager; -import android.test.FlakyTest; import android.test.suitebuilder.annotation.SmallTest; import android.view.KeyEvent; import android.view.View; @@ -27,6 +26,7 @@ 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.FlakyTest; import org.chromium.base.test.util.Restriction; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/document/DocumentModeTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/document/DocumentModeTest.java index 0f53325..fb0c393 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/document/DocumentModeTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/document/DocumentModeTest.java
@@ -11,7 +11,6 @@ import android.net.Uri; import android.os.Build; import android.os.Environment; -import android.test.FlakyTest; import android.test.suitebuilder.annotation.MediumTest; import android.text.TextUtils; import android.view.View; @@ -20,6 +19,7 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.DisabledTest; +import org.chromium.base.test.util.FlakyTest; import org.chromium.base.test.util.MinAndroidSdkLevel; import org.chromium.base.test.util.UrlUtils; import org.chromium.chrome.browser.ChromeActivity; @@ -624,10 +624,9 @@ * URL in the Intent. */ /* - * Bug: http://crbug/554487 * @MediumTest */ - @FlakyTest + @FlakyTest(message = "http://crbug/554487") public void testBehemothUrlWindowOpen() throws Exception { Intent lastIntent = performNewWindowTest( HUGE_URL_PAGE, "behemoth URL page", true, "behemoth result", true);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/feedback/ConnectivityCheckerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/feedback/ConnectivityCheckerTest.java index 90342c7..c551ac0b 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/feedback/ConnectivityCheckerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/feedback/ConnectivityCheckerTest.java
@@ -40,63 +40,63 @@ @MediumTest @Feature({"Feedback"}) public void testNoContentShouldWorkSystemStack() throws Exception { - executeTest(GENERATE_204_URL, ConnectivityCheckResult.CONNECTED, TIMEOUT_MS, true); + executeTest(mGenerate204Url, ConnectivityCheckResult.CONNECTED, TIMEOUT_MS, true); } @MediumTest @Feature({"Feedback"}) public void testNoContentShouldWorkChromeStack() throws Exception { - executeTest(GENERATE_204_URL, ConnectivityCheckResult.CONNECTED, TIMEOUT_MS, false); + executeTest(mGenerate204Url, ConnectivityCheckResult.CONNECTED, TIMEOUT_MS, false); } @MediumTest @Feature({"Feedback"}) public void testSlowNoContentShouldNotWorkSystemStack() throws Exception { // Force quick timeout. The server will wait TIMEOUT_MS, so this triggers well before. - executeTest(GENERATE_204_SLOW_URL, ConnectivityCheckResult.TIMEOUT, 100, true); + executeTest(mGenerateSlowUrl, ConnectivityCheckResult.TIMEOUT, 100, true); } @MediumTest @Feature({"Feedback"}) public void testSlowNoContentShouldNotWorkChromeStack() throws Exception { // Force quick timeout. The server will wait TIMEOUT_MS, so this triggers well before. - executeTest(GENERATE_204_SLOW_URL, ConnectivityCheckResult.TIMEOUT, 100, false); + executeTest(mGenerateSlowUrl, ConnectivityCheckResult.TIMEOUT, 100, false); } @MediumTest @Feature({"Feedback"}) public void testHttpOKShouldFailSystemStack() throws Exception { - executeTest(GENERATE_200_URL, ConnectivityCheckResult.NOT_CONNECTED, TIMEOUT_MS, true); + executeTest(mGenerate200Url, ConnectivityCheckResult.NOT_CONNECTED, TIMEOUT_MS, true); } @MediumTest @Feature({"Feedback"}) public void testHttpOKShouldFailChromeStack() throws Exception { - executeTest(GENERATE_200_URL, ConnectivityCheckResult.NOT_CONNECTED, TIMEOUT_MS, false); + executeTest(mGenerate200Url, ConnectivityCheckResult.NOT_CONNECTED, TIMEOUT_MS, false); } @MediumTest @Feature({"Feedback"}) public void testMovedTemporarilyShouldFailSystemStack() throws Exception { - executeTest(GENERATE_302_URL, ConnectivityCheckResult.NOT_CONNECTED, TIMEOUT_MS, true); + executeTest(mGenerate302Url, ConnectivityCheckResult.NOT_CONNECTED, TIMEOUT_MS, true); } @MediumTest @Feature({"Feedback"}) public void testMovedTemporarilyShouldFailChromeStack() throws Exception { - executeTest(GENERATE_302_URL, ConnectivityCheckResult.NOT_CONNECTED, TIMEOUT_MS, false); + executeTest(mGenerate302Url, ConnectivityCheckResult.NOT_CONNECTED, TIMEOUT_MS, false); } @MediumTest @Feature({"Feedback"}) public void testNotFoundShouldFailSystemStack() throws Exception { - executeTest(GENERATE_404_URL, ConnectivityCheckResult.NOT_CONNECTED, TIMEOUT_MS, true); + executeTest(mGenerate404Url, ConnectivityCheckResult.NOT_CONNECTED, TIMEOUT_MS, true); } @MediumTest @Feature({"Feedback"}) public void testNotFoundShouldFailChromeStack() throws Exception { - executeTest(GENERATE_404_URL, ConnectivityCheckResult.NOT_CONNECTED, TIMEOUT_MS, false); + executeTest(mGenerate404Url, ConnectivityCheckResult.NOT_CONNECTED, TIMEOUT_MS, false); } @MediumTest
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/feedback/ConnectivityCheckerTestBase.java b/chrome/android/javatests/src/org/chromium/chrome/browser/feedback/ConnectivityCheckerTestBase.java index 3c8ce13..484b9c2 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/feedback/ConnectivityCheckerTestBase.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/feedback/ConnectivityCheckerTestBase.java
@@ -4,14 +4,8 @@ package org.chromium.chrome.browser.feedback; -import android.os.Handler; -import android.os.HandlerThread; - import org.chromium.content.browser.test.NativeLibraryTestBase; -import org.chromium.net.test.BaseHttpTestServer; - -import java.io.IOException; -import java.net.Socket; +import org.chromium.net.test.EmbeddedTestServer; /** * Base class for tests related to checking connectivity. @@ -19,170 +13,34 @@ * It includes a {@link ConnectivityTestServer} which is set up and torn down automatically * for tests. */ -// TODO(nyquist): fix deprecation warnings crbug.com/537053 -@SuppressWarnings("deprecation") public class ConnectivityCheckerTestBase extends NativeLibraryTestBase { - static final int TIMEOUT_MS = 5000; - /** - * Port number which spells out DUMMY on a numeric keypad. - */ - private static final int DUMMY_PORT = 38669; - // Helper URLs for each of the given HTTP response codes. - private static final String BASE_URL = "http://127.0.0.1:" + DUMMY_PORT; - private static final String GENERATE_200_PATH = "/generate_200"; - static final String GENERATE_200_URL = BASE_URL + GENERATE_200_PATH; - private static final String GENERATE_204_PATH = "/generate_204"; - static final String GENERATE_204_URL = BASE_URL + GENERATE_204_PATH; - private static final String GENERATE_204_SLOW_PATH = "/generate_slow_204"; - static final String GENERATE_204_SLOW_URL = BASE_URL + GENERATE_204_SLOW_PATH; - private static final String GENERATE_302_PATH = "/generate_302"; - static final String GENERATE_302_URL = BASE_URL + GENERATE_302_PATH; - private static final String GENERATE_404_PATH = "/generate_404"; - static final String GENERATE_404_URL = BASE_URL + GENERATE_404_PATH; + protected static final int TIMEOUT_MS = 5000; - private static class ConnectivityTestServer extends BaseHttpTestServer { - /** - * The lock object used when inspecting and manipulating {@link #mHasStarted}, - * {@link #mHasStopped}, {@link #mHandlerThread} and {@link #mHandler}. - */ - private final Object mLock = new Object(); - - /** - * Flag for whether the server has started yet. This field must only be accessed when - * the thread has synchronized on {@link #mLock}. - */ - private boolean mHasStarted; - - /** - * Flag for whether the server has stopped yet. This field must only be accessed when - * the thread has synchronized on {@link #mLock}. - */ - private boolean mHasStopped; - - /** - * A {@link HandlerThread} for {@link #mHandler}. This field must only be accessed when - * the thread has synchronized on {@link #mLock}. - */ - private HandlerThread mHandlerThread; - - /** - * A Handler used for posting delayed callbacks. This field must only be accessed when - * the thread has synchronized on {@link #mLock}. - */ - private Handler mHandler; - - /** - * Create an HTTP test server. - */ - public ConnectivityTestServer() throws IOException { - super(DUMMY_PORT, TIMEOUT_MS); - } - - @Override - public void run() { - synchronized (mLock) { - if (mHasStarted) return; - mHasStarted = true; - - mHandlerThread = new HandlerThread("ConnectivityTestServerHandler"); - mHandlerThread.start(); - mHandler = new Handler(mHandlerThread.getLooper()); - } - super.run(); - } - - @Override - public void stop() { - synchronized (mLock) { - if (!mHasStarted || mHasStopped) return; - mHasStopped = true; - - mHandler = null; - mHandlerThread.quit(); - } - super.stop(); - } - - @Override - protected boolean validateSocket(Socket sock) { - return sock.getInetAddress().isLoopbackAddress(); - } - - @Override - protected org.apache.http.params.HttpParams getConnectionParams() { - org.apache.http.params.HttpParams httpParams = - new org.apache.http.params.BasicHttpParams(); - httpParams.setParameter(org.apache.http.params.CoreProtocolPNames.PROTOCOL_VERSION, - org.apache.http.HttpVersion.HTTP_1_1); - return httpParams; - } - - @Override - protected void handleGet(org.apache.http.HttpRequest request, HttpResponseCallback callback) - throws org.apache.http.HttpException { - String requestPath = request.getRequestLine().getUri(); - if (GENERATE_204_SLOW_PATH.equals(requestPath)) { - sendDelayedResponse(callback, requestPath); - } else { - sendResponse(callback, requestPath); - } - } - - private void sendDelayedResponse( - final HttpResponseCallback callback, final String requestPath) { - synchronized (mLock) { - if (mHandler == null) throw new IllegalStateException("Handler not created."); - mHandler.postDelayed(new Runnable() { - @Override - public void run() { - sendResponse(callback, requestPath); - } - }, TIMEOUT_MS); - } - } - - private void sendResponse(HttpResponseCallback callback, String requestPath) { - int httpStatus = getStatusCodeFromRequestPath(requestPath); - String reason = String.valueOf(httpStatus); - callback.onResponse(new org.apache.http.message.BasicHttpResponse( - org.apache.http.HttpVersion.HTTP_1_1, httpStatus, reason)); - } - - private int getStatusCodeFromRequestPath(String requestPath) { - switch (requestPath) { - case GENERATE_200_PATH: - return org.apache.http.HttpStatus.SC_OK; - case GENERATE_204_PATH: // Intentional fall through. - case GENERATE_204_SLOW_PATH: - return org.apache.http.HttpStatus.SC_NO_CONTENT; - case GENERATE_302_PATH: - return org.apache.http.HttpStatus.SC_MOVED_TEMPORARILY; - case GENERATE_404_PATH: - return org.apache.http.HttpStatus.SC_NOT_FOUND; - default: - return org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR; - } - } - } - - private ConnectivityTestServer mTestServer; - private Thread mTestServerThread; + private EmbeddedTestServer mTestServer; + protected String mGenerate200Url; + protected String mGenerate204Url; + protected String mGenerate302Url; + protected String mGenerate404Url; + protected String mGenerateSlowUrl; @Override protected void setUp() throws Exception { super.setUp(); loadNativeLibraryAndInitBrowserProcess(); - mTestServer = new ConnectivityTestServer(); - mTestServerThread = new Thread(mTestServer); - mTestServerThread.start(); - mTestServer.waitForServerToStart(); + + mTestServer = EmbeddedTestServer.createAndStartDefaultServer( + getInstrumentation().getContext()); + mGenerate200Url = mTestServer.getURL("/echo?status=200"); + mGenerate204Url = mTestServer.getURL("/echo?status=204"); + mGenerate302Url = mTestServer.getURL("/echo?status=302"); + mGenerate404Url = mTestServer.getURL("/echo?status=404"); + mGenerateSlowUrl = mTestServer.getURL("/slow?5"); } @Override protected void tearDown() throws Exception { - mTestServer.stop(); - mTestServerThread.join(); + mTestServer.stopAndDestroyServer(); super.tearDown(); } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/feedback/ConnectivityTaskTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/feedback/ConnectivityTaskTest.java index 87c87eb2..e6252a17d 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/feedback/ConnectivityTaskTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/feedback/ConnectivityTaskTest.java
@@ -38,8 +38,7 @@ public ConnectivityTask call() { // Intentionally make HTTPS-connection fail which should result in // NOT_CONNECTED. - ConnectivityChecker.overrideUrlsForTest(GENERATE_204_URL, - GENERATE_404_URL); + ConnectivityChecker.overrideUrlsForTest(mGenerate204Url, mGenerate404Url); return ConnectivityTask.create(Profile.getLastUsedProfile(), TIMEOUT_MS, null); } @@ -99,7 +98,7 @@ @Override public void run() { // Intentionally make HTTPS-connection fail which should result in NOT_CONNECTED. - ConnectivityChecker.overrideUrlsForTest(GENERATE_204_URL, GENERATE_404_URL); + ConnectivityChecker.overrideUrlsForTest(mGenerate204Url, mGenerate404Url); ConnectivityTask.create(Profile.getLastUsedProfile(), TIMEOUT_MS, callback); } }); @@ -129,8 +128,7 @@ @Override public void run() { // Intentionally make HTTPS connections slow which should result in TIMEOUT. - ConnectivityChecker.overrideUrlsForTest(GENERATE_204_URL, - GENERATE_204_SLOW_URL); + ConnectivityChecker.overrideUrlsForTest(mGenerate204Url, mGenerateSlowUrl); ConnectivityTask.create(Profile.getLastUsedProfile(), checkTimeoutMs, callback); } }); @@ -153,8 +151,8 @@ public ConnectivityTask call() { // Intentionally make HTTPS connections slow which should result in // UNKNOWN. - ConnectivityChecker.overrideUrlsForTest(GENERATE_204_URL, - GENERATE_204_SLOW_URL); + ConnectivityChecker.overrideUrlsForTest(mGenerate204Url, + mGenerateSlowUrl); return ConnectivityTask.create(Profile.getLastUsedProfile(), TIMEOUT_MS, null); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/media/router/MediaRouterIntegrationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/media/router/MediaRouterIntegrationTest.java index c11ed69..0a65f72 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/media/router/MediaRouterIntegrationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/media/router/MediaRouterIntegrationTest.java
@@ -221,9 +221,7 @@ String defaultRequestSessionId = getJavaScriptVariable( webContents, "defaultRequestSessionId"); assertEquals(sessionId, defaultRequestSessionId); - // TODO(zqzhang): The route state change callbacks are not properly called in Android, so - // the following script is skipped. See http://crbug.com/592732 - // executeJavaScriptApi(webContents, TERMINATE_SESSION_SCRIPT); + executeJavaScriptApi(webContents, TERMINATE_SESSION_SCRIPT); } @Restriction({ChromeRestriction.RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_NON_LOW_END_DEVICE}) @@ -248,6 +246,7 @@ @Feature({"MediaRouter"}) @LargeTest public void testOnClose() throws InterruptedException, TimeoutException { + MockMediaRouteProvider.Builder.sProvider.setCloseRouteWithErrorOnSend(true); loadUrl(mTestServer.getURL(TEST_PAGE)); WebContents webContents = getActivity().getActivityTab().getWebContents(); executeJavaScriptApi(webContents, WAIT_DEVICE_SCRIPT); @@ -258,10 +257,8 @@ executeJavaScriptApi(webContents, CHECK_SESSION_SCRIPT); String sessionId = getJavaScriptVariable(webContents, "startedConnection.id"); assertFalse(sessionId.length() == 0); - // TODO(zqzhang): The route state change callbacks are not properly called in Android, so - // the following script is skipped. See http://crbug.com/592732 - // executeJavaScriptApi(webContents, - // SEND_MESSAGE_AND_EXPECT_CONNECTION_CLOSE_ON_ERROR_SCRIPT); + executeJavaScriptApi(webContents, + SEND_MESSAGE_AND_EXPECT_CONNECTION_CLOSE_ON_ERROR_SCRIPT); } @Restriction({ChromeRestriction.RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_NON_LOW_END_DEVICE}) @@ -317,9 +314,7 @@ String reconnectedSessionId = getJavaScriptVariable(newWebContents, "reconnectedSession.id"); assertEquals(sessionId, reconnectedSessionId); - // TODO(zqzhang): The route state change callbacks are not properly called in Android, so - // the following script is skipped. See http://crbug.com/592732 - // executeJavaScriptApi(webContents, TERMINATE_SESSION_SCRIPT); + executeJavaScriptApi(webContents, TERMINATE_SESSION_SCRIPT); } @Restriction({ChromeRestriction.RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_NON_LOW_END_DEVICE})
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/media/router/MockMediaRouteProvider.java b/chrome/android/javatests/src/org/chromium/chrome/browser/media/router/MockMediaRouteProvider.java index da6ab420..b567ee13 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/media/router/MockMediaRouteProvider.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/media/router/MockMediaRouteProvider.java
@@ -175,9 +175,7 @@ @Override public void sendStringMessage(String routeId, String message, int nativeCallbackId) { if (mCloseRouteWithErrorOnSend) { - // TODO(zqzhang): The method need to notify the router that the connection state has - // changed, so PresentationConnection.onclose will be called. See - // http://crbug.com/592732 + mManager.onRouteClosedWithError(routeId, "Sending message failed. Closing the route."); } else { // Sending a string enclosed by double quotes to behave like JSON.stringify(). mManager.onMessage(routeId, "\"" + "Pong: " + message + "\"");
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/ntp/interests/InterestsServiceTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/ntp/interests/InterestsServiceTest.java index 1bcd55e2..49fe3b8 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/ntp/interests/InterestsServiceTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/ntp/interests/InterestsServiceTest.java
@@ -6,10 +6,10 @@ import android.accounts.Account; import android.content.Context; -import android.test.FlakyTest; import org.chromium.base.CommandLine; import org.chromium.base.ThreadUtils; +import org.chromium.base.test.util.FlakyTest; import org.chromium.chrome.browser.ntp.interests.InterestsService.Interest; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.signin.AccountTrackerService; @@ -90,11 +90,10 @@ } /** - * http://crbug.com/585173 * @SmallTest * @Feature({"NewTabPage"}) */ - @FlakyTest + @FlakyTest(message = "http://crbug.com/585173") public void testEmptyInterests() throws Exception { String response = "{\n" + " \"interests\": []\n" @@ -106,11 +105,10 @@ } /** - * http://crbug.com/585173 * @SmallTest * @Feature({"NewTabPage"}) */ - @FlakyTest + @FlakyTest(message = "http://crbug.com/585173") public void testInterests() throws Exception { String response = "{\n" + " \"interests\": [\n" @@ -138,7 +136,7 @@ * @SmallTest * @Feature({"NewTabPage"}) */ - @FlakyTest + @FlakyTest(message = "http://crbug.com/585173") public void testBadlyFormedInterests() throws Exception { String response = "{\n" + " \"interests\": ["; @@ -148,11 +146,10 @@ } /** - * http://crbug.com/585173 * @SmallTest * @Feature({"NewTabPage"}) */ - @FlakyTest + @FlakyTest(message = "http://crbug.com/585173") public void testEmptyResponse() throws Exception { Interest[] result = serveResponseAndRequestInterests("");
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/OmniboxTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/OmniboxTest.java index 1f47f7f..5546e04d 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/OmniboxTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/OmniboxTest.java
@@ -9,7 +9,6 @@ import android.os.Environment; import android.os.SystemClock; import android.support.v4.view.ViewCompat; -import android.test.FlakyTest; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; import android.text.Selection; @@ -24,6 +23,7 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.EnormousTest; import org.chromium.base.test.util.Feature; +import org.chromium.base.test.util.FlakyTest; import org.chromium.base.test.util.ScalableTimeout; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; @@ -534,11 +534,10 @@ } /** - * crbug.com/414353 * Test to verify security-icon "lock or globe" on visiting http and secured Urls. * @EnormousTest */ - @FlakyTest + @FlakyTest(message = "crbug.com/414353") public void testSecurityIcon() throws InterruptedException { EmbeddedTestServer testServer = EmbeddedTestServer.createAndStartFileServer( getInstrumentation().getContext(), Environment.getExternalStorageDirectory());
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/physicalweb/ListUrlsActivityTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/physicalweb/ListUrlsActivityTest.java index 8515373..bbba646 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/physicalweb/ListUrlsActivityTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/physicalweb/ListUrlsActivityTest.java
@@ -9,6 +9,7 @@ import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; +import android.preference.PreferenceManager; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.SmallTest; import android.view.View; @@ -16,6 +17,8 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.preferences.privacy.PrivacyPreferencesManager; import org.chromium.chrome.test.util.browser.notifications.MockNotificationManagerProxy; +import org.chromium.content.browser.test.util.Criteria; +import org.chromium.content.browser.test.util.CriteriaHelper; import org.chromium.content.browser.test.util.TestTouchUtils; import java.util.ArrayList; @@ -45,12 +48,24 @@ startedIntents.add(intent); super.startActivity(intent); } + + public void waitForStartActivity(long timeout) throws InterruptedException { + CriteriaHelper.pollInstrumentationThread(new Criteria() { + @Override + public boolean isSatisfied() { + return !startedIntents.isEmpty(); + } + }, timeout, CriteriaHelper.DEFAULT_POLLING_INTERVAL); + } } @Override protected void setUp() throws Exception { super.setUp(); mContext = getInstrumentation().getTargetContext(); + // Restore the onboarding state + PreferenceManager.getDefaultSharedPreferences(mContext).edit() + .putInt("physical_web", 2).apply(); UrlManager urlManager = UrlManager.getInstance(mContext); mMockPwsClient = new MockPwsClient(); urlManager.overridePwsClientForTesting(mMockPwsClient); @@ -58,7 +73,7 @@ } @SmallTest - public void testTapEntryOpensUrl() { + public void testTapEntryOpensUrl() throws InterruptedException { // Ensure the Physical Web is enabled. PrivacyPreferencesManager prefsManager = PrivacyPreferencesManager.getInstance(mContext); prefsManager.setPhysicalWebEnabled(true); @@ -80,7 +95,8 @@ listView.findViewsWithText(entries, TITLE, View.FIND_VIEWS_WITH_TEXT); assertEquals(1, entries.size()); View entry = entries.get(0); - TestTouchUtils.clickView(this, entry); + TestTouchUtils.singleClickView(getInstrumentation(), entry); + testContextWrapper.waitForStartActivity(1000); // Test the fired intent. assertEquals(1, testContextWrapper.startedIntents.size());
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/physicalweb/UrlManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/physicalweb/UrlManagerTest.java index d90928f..81c399d 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/physicalweb/UrlManagerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/physicalweb/UrlManagerTest.java
@@ -40,6 +40,7 @@ Context context = getInstrumentation().getTargetContext().getApplicationContext(); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); mSharedPreferences.edit().putInt(PREF_PHYSICAL_WEB, PHYSICAL_WEB_ON).apply(); + UrlManager.clearPrefsForTesting(context); mUrlManager = new UrlManager(context); mMockPwsClient = new MockPwsClient(); mUrlManager.overridePwsClientForTesting(mMockPwsClient);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninHelperTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninHelperTest.java index f9cde750..ca0c015d 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninHelperTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninHelperTest.java
@@ -23,6 +23,7 @@ private MockAccountManager mAccountManager; private AdvancedMockContext mContext; private MockChangeEventChecker mEventChecker; + private SigninHelper mSigninHelper; @Override public void setUp() { @@ -32,41 +33,43 @@ // Mock out the account manager on the device. mAccountManager = new MockAccountManager(mContext, getInstrumentation().getContext()); AccountManagerHelper.overrideAccountManagerHelperForTests(mContext, mAccountManager); + SigninHelper.initializeForTests(mContext); + mSigninHelper = SigninHelper.get(mContext); } @SmallTest public void testAccountsChangedPref() { assertEquals("Should never return true before the pref has ever been set.", - false, SigninHelper.checkAndClearAccountsChangedPref(mContext)); + false, mSigninHelper.checkAndClearAccountsChangedPref()); assertEquals("Should never return true before the pref has ever been set.", - false, SigninHelper.checkAndClearAccountsChangedPref(mContext)); + false, mSigninHelper.checkAndClearAccountsChangedPref()); // Mark the pref as set. - SigninHelper.markAccountsChangedPref(mContext); + mSigninHelper.markAccountsChangedPref(); assertEquals("Should return true first time after marking accounts changed", - true, SigninHelper.checkAndClearAccountsChangedPref(mContext)); + true, mSigninHelper.checkAndClearAccountsChangedPref()); assertEquals("Should only return true first time after marking accounts changed", - false, SigninHelper.checkAndClearAccountsChangedPref(mContext)); + false, mSigninHelper.checkAndClearAccountsChangedPref()); assertEquals("Should only return true first time after marking accounts changed", - false, SigninHelper.checkAndClearAccountsChangedPref(mContext)); + false, mSigninHelper.checkAndClearAccountsChangedPref()); // Mark the pref as set again. - SigninHelper.markAccountsChangedPref(mContext); + mSigninHelper.markAccountsChangedPref(); assertEquals("Should return true first time after marking accounts changed", - true, SigninHelper.checkAndClearAccountsChangedPref(mContext)); + true, mSigninHelper.checkAndClearAccountsChangedPref()); assertEquals("Should only return true first time after marking accounts changed", - false, SigninHelper.checkAndClearAccountsChangedPref(mContext)); + false, mSigninHelper.checkAndClearAccountsChangedPref()); assertEquals("Should only return true first time after marking accounts changed", - false, SigninHelper.checkAndClearAccountsChangedPref(mContext)); + false, mSigninHelper.checkAndClearAccountsChangedPref()); } @SmallTest public void testSimpleAccountRename() { setSignedInAccountName("A"); mEventChecker.insertRenameEvent("A", "B"); - SigninHelper.updateAccountRenameData(mContext, mEventChecker); + mSigninHelper.updateAccountRenameData(mEventChecker); assertEquals("B", getNewSignedInAccountName()); } @@ -75,7 +78,7 @@ public void testNotSignedInAccountRename() { setSignedInAccountName("A"); mEventChecker.insertRenameEvent("B", "C"); - SigninHelper.updateAccountRenameData(mContext, mEventChecker); + mSigninHelper.updateAccountRenameData(mEventChecker); assertEquals(null, getNewSignedInAccountName()); } @@ -83,10 +86,10 @@ public void testSimpleAccountRenameTwice() { setSignedInAccountName("A"); mEventChecker.insertRenameEvent("A", "B"); - SigninHelper.updateAccountRenameData(mContext, mEventChecker); + mSigninHelper.updateAccountRenameData(mEventChecker); assertEquals("B", getNewSignedInAccountName()); mEventChecker.insertRenameEvent("B", "C"); - SigninHelper.updateAccountRenameData(mContext, mEventChecker); + mSigninHelper.updateAccountRenameData(mEventChecker); assertEquals("C", getNewSignedInAccountName()); } @@ -95,7 +98,7 @@ setSignedInAccountName("A"); mEventChecker.insertRenameEvent("B", "C"); mEventChecker.insertRenameEvent("C", "D"); - SigninHelper.updateAccountRenameData(mContext, mEventChecker); + mSigninHelper.updateAccountRenameData(mEventChecker); assertEquals(null, getNewSignedInAccountName()); } @@ -107,7 +110,7 @@ mEventChecker.insertRenameEvent("Y", "X"); // Unrelated. mEventChecker.insertRenameEvent("B", "C"); mEventChecker.insertRenameEvent("C", "D"); - SigninHelper.updateAccountRenameData(mContext, mEventChecker); + mSigninHelper.updateAccountRenameData(mEventChecker); assertEquals("D", getNewSignedInAccountName()); } @@ -123,7 +126,7 @@ Account account = AccountManagerHelper.createAccountFromName("D"); AccountHolder accountHolder = AccountHolder.create().account(account).build(); mAccountManager.addAccountHolderExplicitly(accountHolder); - SigninHelper.updateAccountRenameData(mContext, mEventChecker); + mSigninHelper.updateAccountRenameData(mEventChecker); assertEquals("D", getNewSignedInAccountName()); } @@ -136,6 +139,6 @@ } private String getNewSignedInAccountName() { - return SigninHelper.getNewSignedInAccountName(mContext); + return mSigninHelper.getNewSignedInAccountName(); } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/UndoTabModelTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/UndoTabModelTest.java index db27686..5a66461 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/UndoTabModelTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/UndoTabModelTest.java
@@ -4,10 +4,10 @@ package org.chromium.chrome.browser.tabmodel; -import android.test.FlakyTest; import android.test.suitebuilder.annotation.MediumTest; import org.chromium.base.ThreadUtils; +import org.chromium.base.test.util.FlakyTest; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType; import org.chromium.chrome.browser.tabmodel.TabModel.TabSelectionType; @@ -997,7 +997,7 @@ * @throws InterruptedException */ @MediumTest - @FlakyTest // crbug.com/592969 + @FlakyTest(message = "crbug.com/592969") public void testOutOfOrder2() throws InterruptedException { TabModel model = getActivity().getTabModelSelector().getModel(false); ChromeTabCreator tabCreator = getActivity().getTabCreator(false);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/video/FullscreenVideoTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/video/FullscreenVideoTest.java index fa6e227..1c385dc3 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/video/FullscreenVideoTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/video/FullscreenVideoTest.java
@@ -5,10 +5,10 @@ package org.chromium.chrome.browser.video; import android.os.Environment; -import android.test.FlakyTest; import android.view.KeyEvent; import org.chromium.base.ThreadUtils; +import org.chromium.base.test.util.FlakyTest; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.tab.EmptyTabObserver; import org.chromium.chrome.browser.tab.Tab; @@ -46,9 +46,8 @@ * exit fullscreen mode without changing its URL. * * @MediumTest - * crbug.com/458368. */ - @FlakyTest + @FlakyTest(message = "crbug.com/458368") public void testExitFullscreenNotifiesTabObservers() throws InterruptedException { EmbeddedTestServer testServer = EmbeddedTestServer.createAndStartFileServer( getInstrumentation().getContext(), Environment.getExternalStorageDirectory());
diff --git a/chrome/android/javatests/src/org/chromium/chrome/test/ParametersOnMultiTest.java b/chrome/android/javatests/src/org/chromium/chrome/test/ParametersOnMultiTest.java index df73705..3ef2d96 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/test/ParametersOnMultiTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/test/ParametersOnMultiTest.java
@@ -4,11 +4,11 @@ package org.chromium.chrome.test; -import android.test.FlakyTest; import android.test.MoreAsserts; import android.test.suitebuilder.annotation.SmallTest; import org.chromium.base.test.util.EnormousTest; +import org.chromium.base.test.util.FlakyTest; import org.chromium.base.test.util.Restriction; import org.chromium.base.test.util.parameter.Parameter; import org.chromium.base.test.util.parameter.ParameterizedTest;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/test/util/ChromeSigninUtilsTest.java b/chrome/android/javatests/src/org/chromium/chrome/test/util/ChromeSigninUtilsTest.java index 7b65f179..957d899 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/test/util/ChromeSigninUtilsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/test/util/ChromeSigninUtilsTest.java
@@ -4,11 +4,11 @@ package org.chromium.chrome.test.util; -import android.test.FlakyTest; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.SmallTest; import org.chromium.base.test.util.EnormousTest; +import org.chromium.base.test.util.FlakyTest; import org.chromium.base.test.util.Restriction; import org.chromium.sync.signin.ChromeSigninController; @@ -67,8 +67,7 @@ mSigninUtil.isExistingGoogleAccountOnOs(GOOGLE_ACCOUNT_USERNAME)); } - // https://crbug.com/517849 - @FlakyTest + @FlakyTest(message = "https://crbug.com/517849") @EnormousTest @Restriction(Restriction.RESTRICTION_TYPE_INTERNET) public void testIsSignedInOnGoogleOS() { @@ -94,8 +93,7 @@ mSigninUtil.isExistingGoogleAccountOnOs(GOOGLE_ACCOUNT_USERNAME)); } - // https://crbug.com/517849 - @FlakyTest + @FlakyTest(message = "https://crbug.com/517849") @EnormousTest @Restriction(Restriction.RESTRICTION_TYPE_INTERNET) public void testIsSignedInOnAppAndGoogleOS() { @@ -110,8 +108,7 @@ mSigninUtil.isExistingGoogleAccountOnOs(GOOGLE_ACCOUNT_USERNAME)); } - // https://crbug.com/517849 - @FlakyTest + @FlakyTest(message = "https://crbug.com/517849") @EnormousTest @Restriction(Restriction.RESTRICTION_TYPE_INTERNET) public void testIsSignedInOnFakeOSandGoogleOS() { @@ -126,8 +123,7 @@ mSigninUtil.isExistingGoogleAccountOnOs(GOOGLE_ACCOUNT_USERNAME)); } - // https://crbug.com/517849 - @FlakyTest + @FlakyTest(message = "https://crbug.com/517849") @EnormousTest @Restriction(Restriction.RESTRICTION_TYPE_INTERNET) public void testIsSignedInOnAppAndFakeOSandGoogleOS() {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/test/util/parameters/SigninParametersTest.java b/chrome/android/javatests/src/org/chromium/chrome/test/util/parameters/SigninParametersTest.java index 4bd4f2c6..8a9b30ab 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/test/util/parameters/SigninParametersTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/test/util/parameters/SigninParametersTest.java
@@ -4,11 +4,11 @@ package org.chromium.chrome.test.util.parameters; -import android.test.FlakyTest; import android.test.suitebuilder.annotation.SmallTest; import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.EnormousTest; +import org.chromium.base.test.util.FlakyTest; import org.chromium.base.test.util.Restriction; import org.chromium.base.test.util.parameter.Parameter; import org.chromium.base.test.util.parameter.ParameterizedTest;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkModelUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkModelUnitTest.java index 5126009..720d708 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkModelUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkModelUnitTest.java
@@ -7,6 +7,7 @@ import static org.junit.Assert.assertEquals; import org.chromium.base.BaseChromiumApplication; +import org.chromium.base.test.shadows.ShadowMultiDex; import org.chromium.chrome.browser.offlinepages.ClientId; import org.chromium.components.bookmarks.BookmarkId; import org.chromium.components.bookmarks.BookmarkType; @@ -20,7 +21,8 @@ * Robolectric tests for {@link BookmarkUtils}. */ @RunWith(LocalRobolectricTestRunner.class) -@Config(manifest = Config.NONE, application = BaseChromiumApplication.class) +@Config(manifest = Config.NONE, application = BaseChromiumApplication.class, + shadows = {ShadowMultiDex.class}) public class BookmarkModelUnitTest { @Test public void testGetBookmarkIdForOfflineClientIdBadId() {
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkUtilsTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkUtilsTest.java index b3cc006..ea631d72 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkUtilsTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkUtilsTest.java
@@ -12,7 +12,7 @@ import android.content.Intent; import org.chromium.base.BaseChromiumApplication; -import org.chromium.base.test.util.DisabledTest; +import org.chromium.base.test.shadows.ShadowMultiDex; import org.chromium.base.test.util.Feature; import org.chromium.components.bookmarks.BookmarkId; import org.chromium.components.bookmarks.BookmarkType; @@ -31,7 +31,8 @@ * Robolectric tests for {@link BookmarkUtils}. */ @RunWith(LocalRobolectricTestRunner.class) -@Config(manifest = Config.NONE, application = BaseChromiumApplication.class) +@Config(manifest = Config.NONE, application = BaseChromiumApplication.class, + shadows = {ShadowMultiDex.class}) public class BookmarkUtilsTest { @Mock private Context mContext; @Mock private BookmarkModel mBookmarkModel; @@ -42,13 +43,8 @@ MockitoAnnotations.initMocks(this); } - - /* - * @Test - * @Feature({"Bookmark"}) - * Bug=crbug.com/604025 - */ - @DisabledTest + @Test + @Feature({"Bookmark"}) public void testStartEditActivityWithoutWebContents() { BookmarkId bookmarkId = new BookmarkId(12345L, BookmarkType.NORMAL); BookmarkUtils.startEditActivity(mContext, bookmarkId, null /* webContents */);
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/ClientIdTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/ClientIdTest.java index 19da9fc..7a663e4 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/ClientIdTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/ClientIdTest.java
@@ -9,6 +9,7 @@ import static org.junit.Assert.assertNull; import org.chromium.base.BaseChromiumApplication; +import org.chromium.base.test.shadows.ShadowMultiDex; import org.chromium.base.test.util.Feature; import org.chromium.components.bookmarks.BookmarkId; import org.chromium.components.bookmarks.BookmarkType; @@ -21,7 +22,8 @@ * Unit tests for ClientId. */ @RunWith(LocalRobolectricTestRunner.class) -@Config(manifest = Config.NONE, application = BaseChromiumApplication.class) +@Config(manifest = Config.NONE, application = BaseChromiumApplication.class, + shadows = {ShadowMultiDex.class}) public class ClientIdTest { private static final long INVALID_BOOKMARK_ID = -1;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/OfflinePageBridgeTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/OfflinePageBridgeTest.java index dc7134c..e279f84 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/OfflinePageBridgeTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/OfflinePageBridgeTest.java
@@ -19,6 +19,7 @@ import org.chromium.base.BaseChromiumApplication; import org.chromium.base.ThreadUtils; +import org.chromium.base.test.shadows.ShadowMultiDex; import org.chromium.base.test.util.Feature; import org.chromium.chrome.browser.offlinepages.OfflinePageBridge.MultipleOfflinePageItemCallback; import org.chromium.chrome.browser.offlinepages.OfflinePageBridge.OfflinePageModelObserver; @@ -40,7 +41,8 @@ * Unit tests for OfflinePageUtils. */ @RunWith(LocalRobolectricTestRunner.class) -@Config(manifest = Config.NONE, application = BaseChromiumApplication.class) +@Config(manifest = Config.NONE, application = BaseChromiumApplication.class, + shadows = {ShadowMultiDex.class}) public class OfflinePageBridgeTest { private OfflinePageBridge mBridge;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/OfflinePageTabObserverTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/OfflinePageTabObserverTest.java index 8206447..511bed40 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/OfflinePageTabObserverTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/OfflinePageTabObserverTest.java
@@ -17,6 +17,7 @@ import android.content.Context; import org.chromium.base.BaseChromiumApplication; +import org.chromium.base.test.shadows.ShadowMultiDex; import org.chromium.base.test.util.Feature; import org.chromium.chrome.browser.snackbar.SnackbarManager; import org.chromium.chrome.browser.snackbar.SnackbarManager.SnackbarController; @@ -33,7 +34,8 @@ * Unit tests for OfflinePageUtils. */ @RunWith(LocalRobolectricTestRunner.class) -@Config(manifest = Config.NONE, application = BaseChromiumApplication.class) +@Config(manifest = Config.NONE, application = BaseChromiumApplication.class, + shadows = {ShadowMultiDex.class}) public class OfflinePageTabObserverTest { // Using a null tab, as it cannot be mocked. TabHelper will help return proper mocked responses. private static final Tab TAB = null;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtilsTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtilsTest.java index 647895ae..fb15360f 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtilsTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtilsTest.java
@@ -12,6 +12,7 @@ import android.os.Environment; import org.chromium.base.BaseChromiumApplication; +import org.chromium.base.test.shadows.ShadowMultiDex; import org.chromium.base.test.util.Feature; import org.chromium.testing.local.LocalRobolectricTestRunner; import org.junit.Before; @@ -31,7 +32,7 @@ @RunWith(LocalRobolectricTestRunner.class) @Config(manifest = Config.NONE, application = BaseChromiumApplication.class, - shadows = { OfflinePageUtilsTest.WrappedEnvironment.class }) + shadows = { OfflinePageUtilsTest.WrappedEnvironment.class, ShadowMultiDex.class }) public class OfflinePageUtilsTest { @Mock private File mMockDataDirectory;
diff --git a/chrome/android/sync_shell/javatests/src/org/chromium/chrome/browser/sync/OpenTabsTest.java b/chrome/android/sync_shell/javatests/src/org/chromium/chrome/browser/sync/OpenTabsTest.java index 75615c6..6b2f652f 100644 --- a/chrome/android/sync_shell/javatests/src/org/chromium/chrome/browser/sync/OpenTabsTest.java +++ b/chrome/android/sync_shell/javatests/src/org/chromium/chrome/browser/sync/OpenTabsTest.java
@@ -4,12 +4,12 @@ package org.chromium.chrome.browser.sync; -import android.test.FlakyTest; import android.test.suitebuilder.annotation.LargeTest; import android.util.Pair; import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.Feature; +import org.chromium.base.test.util.FlakyTest; import org.chromium.chrome.browser.ChromeApplication; import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.tabmodel.TabModelUtils; @@ -93,9 +93,8 @@ // Test syncing multiple open tabs from client to server. @LargeTest @Feature({"Sync"}) - https://crbug.com/592437 */ - @FlakyTest + @FlakyTest(message = "https://crbug.com/592437") public void testUploadMultipleOpenTabs() throws Exception { loadUrl(URL); loadUrlInNewTab(URL2); @@ -108,9 +107,8 @@ // Test syncing an open tab from client to server. @LargeTest @Feature({"Sync"}) - https://crbug.com/592437 */ - @FlakyTest + @FlakyTest(message = "https://crbug.com/592437") public void testUploadAndCloseOpenTab() throws Exception { loadUrl(URL); // Can't have zero tabs, so we have to open two to test closing one.
diff --git a/chrome/android/sync_shell/javatests/src/org/chromium/chrome/browser/sync/SyncTest.java b/chrome/android/sync_shell/javatests/src/org/chromium/chrome/browser/sync/SyncTest.java index 31ea2d92..24d825d 100644 --- a/chrome/android/sync_shell/javatests/src/org/chromium/chrome/browser/sync/SyncTest.java +++ b/chrome/android/sync_shell/javatests/src/org/chromium/chrome/browser/sync/SyncTest.java
@@ -6,7 +6,6 @@ import android.accounts.Account; import android.app.Activity; -import android.test.FlakyTest; import android.test.suitebuilder.annotation.LargeTest; import org.chromium.base.ActivityState; @@ -14,6 +13,7 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; +import org.chromium.base.test.util.FlakyTest; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.signin.AccountIdProvider; import org.chromium.chrome.browser.signin.AccountTrackerService; @@ -67,9 +67,8 @@ * @FlakyTest * @LargeTest * @Feature({"Sync"}) - * BUG = crbug.com/588050, crbug.com/595893 */ - @DisabledTest + @DisabledTest(message = "crbug.com/588050,crbug.com/595893") public void testRename() throws InterruptedException { // The two accounts object that would represent the account rename. final Account oldAccount = setUpTestAccountAndSignInToSync(); @@ -83,8 +82,8 @@ // real account rename events instead of the mocks. MockChangeEventChecker eventChecker = new MockChangeEventChecker(); eventChecker.insertRenameEvent(oldAccount.name, newAccount.name); - SigninHelper.resetAccountRenameEventIndex(mContext); - SigninHelper.updateAccountRenameData(mContext, eventChecker); + SigninHelper.get(mContext).resetAccountRenameEventIndex(); + SigninHelper.get(mContext).updateAccountRenameData(eventChecker); // Tell the fake content resolver that a rename had happen and copy over the sync // settings. This would normally be done by the SystemSyncContentResolver. @@ -130,9 +129,8 @@ /* * @LargeTest * @Feature({"Sync"}) - * BUG = crbug.com/594558 */ - @FlakyTest + @FlakyTest(message = "crbug.com/594558") public void testStopAndStartSyncThroughAndroid() throws InterruptedException { Account account = setUpTestAccountAndSignInToSync(); SyncTestUtil.waitForSyncActive();
diff --git a/chrome/android/sync_shell/javatests/src/org/chromium/chrome/browser/sync/ui/PassphraseTypeDialogFragmentTest.java b/chrome/android/sync_shell/javatests/src/org/chromium/chrome/browser/sync/ui/PassphraseTypeDialogFragmentTest.java index dc8bc5c..0273106 100644 --- a/chrome/android/sync_shell/javatests/src/org/chromium/chrome/browser/sync/ui/PassphraseTypeDialogFragmentTest.java +++ b/chrome/android/sync_shell/javatests/src/org/chromium/chrome/browser/sync/ui/PassphraseTypeDialogFragmentTest.java
@@ -4,12 +4,12 @@ package org.chromium.chrome.browser.sync.ui; -import android.test.FlakyTest; import android.test.suitebuilder.annotation.SmallTest; import android.widget.CheckedTextView; import android.widget.ListView; import org.chromium.base.test.util.Feature; +import org.chromium.base.test.util.FlakyTest; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.test.ChromeActivityTestCaseBase; @@ -69,9 +69,8 @@ /* * @SmallTest * @Feature({"Sync"}) - * BUG = crbug.com/588050 */ - @FlakyTest + @FlakyTest(message = "crbug.com/588050") public void testFrozenImplicitEncryptionOptions() throws Exception { createFragment(PassphraseType.FROZEN_IMPLICIT_PASSPHRASE, true); assertPassphraseTypeOptions(
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 97758e22c..d4e63c5 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -12542,10 +12542,10 @@ Allow <ph name="HANDLER_HOSTNAME">$1<ex>google.com</ex></ph> to open all <ph name="PROTOCOL">$2<ex>search</ex></ph> links instead of <ph name="REPLACED_HANDLER_TITLE">$3<ex>Elgoog Search</ex></ph>? </message> <message name="IDS_REGISTER_PROTOCOL_HANDLER_CONFIRM_FRAGMENT" desc="The permission fragment to display when asking a user to confirm the registration of a protocol handler in a permission bubble. Follows a prompt 'This site would like to:'."> - Open <ph name="PROTOCOL">$3<ex>search</ex></ph> links + Open <ph name="PROTOCOL">$1<ex>search</ex></ph> links </message> <message name="IDS_REGISTER_PROTOCOL_HANDLER_CONFIRM_REPLACE_FRAGMENT" desc="The permission fragment to display when asking a user to confirm the registration of a protocol handler. Follows a prompt 'This site would like to:'."> - Open <ph name="PROTOCOL">$3<ex>search</ex></ph> links instead of <ph name="REPLACED_HANDLER_TITLE">$4<ex>Elgoog Search</ex></ph> + Open <ph name="PROTOCOL">$1<ex>search</ex></ph> links instead of <ph name="REPLACED_HANDLER_TITLE">$2<ex>Elgoog Search</ex></ph> </message> <message name="IDS_REGISTER_PROTOCOL_HANDLER_ACCEPT" desc="Text to show for the accept button for the register protocol handler request infobar."> Allow @@ -14607,7 +14607,7 @@ <if expr="not is_android and not is_ios"> <!-- Chooser Bubble Prompt --> <message name="IDS_CHOOSER_BUBBLE_PROMPT" desc="The label that is used to introduce chooser details to the user in a popup."> - This site wants to connect to: + <ph name="Origin">$1<ex>www.google.com</ex></ph> wants to connect to: </message> <!-- Chooser Bubble No Devices Found Prompt --> <message name="IDS_CHOOSER_BUBBLE_NO_DEVICES_FOUND_PROMPT" desc="The label that is used to inform user that no devices found in the chooser popup.">
diff --git a/chrome/browser/DEPS b/chrome/browser/DEPS index a056070..877d390 100644 --- a/chrome/browser/DEPS +++ b/chrome/browser/DEPS
@@ -94,6 +94,7 @@ # No inclusion of WebKit from the browser, other than strictly enum/POD, # header-only types, and some selected common code. "-third_party/WebKit", + "+third_party/WebKit/public/platform/WebDisplayMode.h", "+third_party/WebKit/public/platform/WebLoadingBehaviorFlag.h", "+third_party/WebKit/public/platform/WebReferrerPolicy.h", "+third_party/WebKit/public/platform/modules/app_banner/WebAppBannerPromptReply.h",
diff --git a/chrome/browser/after_startup_task_utils.cc b/chrome/browser/after_startup_task_utils.cc index dac77d0a..f61fec8 100644 --- a/chrome/browser/after_startup_task_utils.cc +++ b/chrome/browser/after_startup_task_utils.cc
@@ -4,11 +4,12 @@ #include "chrome/browser/after_startup_task_utils.h" +#include <memory> #include <utility> #include "base/lazy_instance.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/process/process_info.h" #include "base/rand_util.h" @@ -57,13 +58,13 @@ return g_startup_complete_flag.Get().IsSet(); } -void RunTask(scoped_ptr<AfterStartupTask> queued_task) { +void RunTask(std::unique_ptr<AfterStartupTask> queued_task) { // We're careful to delete the caller's |task| on the target runner's thread. DCHECK(queued_task->task_runner->RunsTasksOnCurrentThread()); queued_task->task.Run(); } -void ScheduleTask(scoped_ptr<AfterStartupTask> queued_task) { +void ScheduleTask(std::unique_ptr<AfterStartupTask> queued_task) { // Spread their execution over a brief time. const int kMinDelaySec = 0; const int kMaxDelaySec = 10; @@ -74,7 +75,7 @@ base::TimeDelta::FromSeconds(base::RandInt(kMinDelaySec, kMaxDelaySec))); } -void QueueTask(scoped_ptr<AfterStartupTask> queued_task) { +void QueueTask(std::unique_ptr<AfterStartupTask> queued_task) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, @@ -106,7 +107,7 @@ g_after_startup_tasks.Get().size()); g_startup_complete_flag.Get().Set(); for (AfterStartupTask* queued_task : g_after_startup_tasks.Get()) - ScheduleTask(make_scoped_ptr(queued_task)); + ScheduleTask(base::WrapUnique(queued_task)); g_after_startup_tasks.Get().clear(); // The shrink_to_fit() method is not available for all of our build targets. @@ -206,7 +207,7 @@ return; } - scoped_ptr<AfterStartupTask> queued_task( + std::unique_ptr<AfterStartupTask> queued_task( new AfterStartupTask(from_here, task_runner, task)); QueueTask(std::move(queued_task)); }
diff --git a/chrome/browser/after_startup_task_utils_unittest.cc b/chrome/browser/after_startup_task_utils_unittest.cc index 5d51db4c..a480782 100644 --- a/chrome/browser/after_startup_task_utils_unittest.cc +++ b/chrome/browser/after_startup_task_utils_unittest.cc
@@ -4,10 +4,11 @@ #include "chrome/browser/after_startup_task_utils.h" +#include <memory> + #include "base/bind.h" #include "base/bind_helpers.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/task_runner_util.h"
diff --git a/chrome/browser/android/compositor/tab_content_manager.cc b/chrome/browser/android/compositor/tab_content_manager.cc index 556f8c25..c2948b62 100644 --- a/chrome/browser/android/compositor/tab_content_manager.cc +++ b/chrome/browser/android/compositor/tab_content_manager.cc
@@ -28,7 +28,10 @@ #include "jni/TabContentManager_jni.h" #include "ui/android/resources/ui_resource_provider.h" #include "ui/gfx/android/java_bitmap.h" +#include "ui/gfx/display.h" +#include "ui/gfx/geometry/dip_util.h" #include "ui/gfx/geometry/rect.h" +#include "ui/gfx/screen.h" #include "url/gurl.h" namespace { @@ -44,9 +47,11 @@ class TabContentManager::TabReadbackRequest { public: TabReadbackRequest(jobject content_view_core, + gfx::Rect src_rect, float thumbnail_scale, const TabReadbackCallback& end_callback) - : thumbnail_scale_(thumbnail_scale), + : src_rect_(src_rect), + thumbnail_scale_(thumbnail_scale), end_callback_(end_callback), drop_after_readback_(false), weak_factory_(this) { @@ -84,10 +89,17 @@ SkColorType color_type = kN32_SkColorType; - // Calling this method with an empty rect will return a bitmap of the size - // of the content. - view->GetScaledContentBitmap(thumbnail_scale_, color_type, gfx::Rect(), - result_callback); + const gfx::Display& display = gfx::Screen::GetScreen()->GetPrimaryDisplay(); + float device_scale_factor = display.device_scale_factor(); + DCHECK_GT(device_scale_factor, 0); + gfx::Size dst_size( + gfx::ScaleToCeiledSize(src_rect_.size(), + thumbnail_scale_ / device_scale_factor)); + gfx::Rect src_rect = gfx::ConvertRectToDIP(device_scale_factor, src_rect_); + view->GetWebContents() + ->GetRenderViewHost() + ->GetWidget() + ->CopyFromBackingStore(src_rect, dst_size, result_callback, color_type); } void OnFinishGetTabThumbnailBitmap(const SkBitmap& bitmap, @@ -120,6 +132,7 @@ private: base::android::ScopedJavaGlobalRef<jobject> j_content_view_core_; + gfx::Rect src_rect_; const float thumbnail_scale_; TabReadbackCallback end_callback_; bool drop_after_readback_; @@ -260,6 +273,8 @@ if (thumbnail_cache_->CheckAndUpdateThumbnailMetaData(tab_id, url)) { if (!view || + !view->GetWebContents()->GetRenderViewHost() || + !view->GetWebContents()->GetRenderViewHost()->GetWidget() || !view->GetWebContents() ->GetRenderViewHost() ->GetWidget() @@ -270,12 +285,14 @@ return; } + gfx::Rect src_rect = gfx::Rect(GetLiveLayer(tab_id)->bounds()); TabReadbackCallback readback_done_callback = base::Bind(&TabContentManager::PutThumbnailIntoCache, weak_factory_.GetWeakPtr(), tab_id); std::unique_ptr<TabReadbackRequest> readback_request = base::WrapUnique(new TabReadbackRequest( - content_view_core, thumbnail_scale, readback_done_callback)); + content_view_core, src_rect, thumbnail_scale, + readback_done_callback)); pending_tab_readbacks_.set(tab_id, std::move(readback_request)); pending_tab_readbacks_.get(tab_id)->Run(); }
diff --git a/chrome/browser/android/feature_utilities.cc b/chrome/browser/android/feature_utilities.cc index 41ff282..4b40c4f 100644 --- a/chrome/browser/android/feature_utilities.cc +++ b/chrome/browser/android/feature_utilities.cc
@@ -11,6 +11,7 @@ namespace { bool document_mode_enabled = false; bool custom_tab_visible = false; +bool is_in_multi_window_mode = false; } // namespace namespace chrome { @@ -26,6 +27,10 @@ VISIBLE_CHROME_TAB; } +bool GetIsInMultiWindowModeValue() { + return is_in_multi_window_mode; +} + } // namespace android } // namespace chrome @@ -41,6 +46,12 @@ custom_tab_visible = visible; } +static void SetIsInMultiWindowMode(JNIEnv* env, + const JavaParamRef<jclass>& clazz, + jboolean j_is_in_multi_window_mode) { + is_in_multi_window_mode = j_is_in_multi_window_mode; +} + static void SetSqlMmapDisabledByDefault(JNIEnv* env, const JavaParamRef<jclass>& clazz) { sql::Connection::set_mmap_disabled_by_default();
diff --git a/chrome/browser/android/feature_utilities.h b/chrome/browser/android/feature_utilities.h index 5ead288..bc7667d 100644 --- a/chrome/browser/android/feature_utilities.h +++ b/chrome/browser/android/feature_utilities.h
@@ -26,6 +26,8 @@ CustomTabsVisibilityHistogram GetCustomTabsVisibleValue(); +bool GetIsInMultiWindowModeValue(); + } // namespace android } // namespace chrome
diff --git a/chrome/browser/app_controller_mac.h b/chrome/browser/app_controller_mac.h index 850b270..80d2f38 100644 --- a/chrome/browser/app_controller_mac.h +++ b/chrome/browser/app_controller_mac.h
@@ -8,11 +8,12 @@ #if defined(__OBJC__) #import <Cocoa/Cocoa.h> + +#include <memory> #include <vector> #include "base/files/file_path.h" #include "base/mac/scoped_nsobject.h" -#include "base/memory/scoped_ptr.h" #include "base/observer_list.h" #include "base/time/time.h" #include "components/prefs/pref_change_registrar.h" @@ -43,7 +44,7 @@ NSApplicationDelegate> { @private // Manages the state of the command menu items. - scoped_ptr<CommandUpdater> menuState_; + std::unique_ptr<CommandUpdater> menuState_; // The profile last used by a Browser. It is this profile that was used to // build the user-data specific main menu items. @@ -51,7 +52,8 @@ // The ProfileObserver observes the ProfileAttrbutesStorage and gets notified // when a profile has been deleted. - scoped_ptr<AppControllerProfileObserver> profileAttributesStorageObserver_; + std::unique_ptr<AppControllerProfileObserver> + profileAttributesStorageObserver_; // Management of the bookmark menu which spans across all windows // (and Browser*s). |profileBookmarkMenuBridgeMap_| is a cache that owns one @@ -61,7 +63,7 @@ BookmarkMenuBridge* bookmarkMenuBridge_; std::map<base::FilePath, BookmarkMenuBridge*> profileBookmarkMenuBridgeMap_; - scoped_ptr<HistoryMenuBridge> historyMenuBridge_; + std::unique_ptr<HistoryMenuBridge> historyMenuBridge_; // Controller that manages main menu items for packaged apps. base::scoped_nsobject<AppShimMenuController> appShimMenuController_; @@ -93,7 +95,7 @@ // Observers that listen to the work area changes. base::ObserverList<ui::WorkAreaWatcherObserver> workAreaChangeObservers_; - scoped_ptr<PrefChangeRegistrar> profilePrefRegistrar_; + std::unique_ptr<PrefChangeRegistrar> profilePrefRegistrar_; PrefChangeRegistrar localPrefRegistrar_; // Displays a notification when quitting while apps are running. @@ -103,14 +105,14 @@ base::scoped_nsobject<HandoffManager> handoffManager_; // Observes changes to the active URL. - scoped_ptr<HandoffActiveURLObserverBridge> + std::unique_ptr<HandoffActiveURLObserverBridge> handoff_active_url_observer_bridge_; // This will be true after receiving a NSWorkspaceWillPowerOffNotification. BOOL isPoweringOff_; // Request to keep the browser alive during that object's lifetime. - scoped_ptr<ScopedKeepAlive> keep_alive_; + std::unique_ptr<ScopedKeepAlive> keep_alive_; } @property(readonly, nonatomic) BOOL startupComplete; @@ -140,6 +142,13 @@ // dialogs that are window modal will block the browser. - (BOOL)keyWindowIsModal; +// Called when the user picks a menu item when there are no key windows, or when +// there is no foreground browser window. Calls through to the browser object to +// execute the command. This assumes that the command is supported and doesn't +// check, otherwise it should have been disabled in the UI in +// |-validateUserInterfaceItem:|. +- (void)commandDispatch:(id)sender; + // Show the preferences window, or bring it to the front if it's already // visible. - (IBAction)showPreferences:(id)sender;
diff --git a/chrome/browser/app_controller_mac.mm b/chrome/browser/app_controller_mac.mm index 5e46b72..f482d56c 100644 --- a/chrome/browser/app_controller_mac.mm +++ b/chrome/browser/app_controller_mac.mm
@@ -1005,11 +1005,6 @@ return enable; } -// Called when the user picks a menu item when there are no key windows, or when -// there is no foreground browser window. Calls through to the browser object to -// execute the command. This assumes that the command is supported and doesn't -// check, otherwise it should have been disabled in the UI in -// |-validateUserInterfaceItem:|. - (void)commandDispatch:(id)sender { Profile* lastProfile = [self safeLastProfileForNewWindows];
diff --git a/chrome/browser/app_controller_mac_browsertest.mm b/chrome/browser/app_controller_mac_browsertest.mm index 79a34c97..2a19e987 100644 --- a/chrome/browser/app_controller_mac_browsertest.mm +++ b/chrome/browser/app_controller_mac_browsertest.mm
@@ -437,7 +437,8 @@ IN_PROC_BROWSER_TEST_F(AppControllerMainMenuBrowserTest, HistoryMenuResetAfterProfileDeletion) { ProfileManager* profile_manager = g_browser_process->profile_manager(); - AppController* ac = [NSApp delegate]; + AppController* ac = + base::mac::ObjCCastStrict<AppController>([NSApp delegate]); // Use the existing profile as profile 1. Profile* profile1 = browser()->profile();
diff --git a/chrome/browser/app_icon_win.cc b/chrome/browser/app_icon_win.cc index 33b66f4..9c3e7d69d 100644 --- a/chrome/browser/app_icon_win.cc +++ b/chrome/browser/app_icon_win.cc
@@ -58,7 +58,7 @@ GetSystemMetrics(SM_CYSMICON)); } -scoped_ptr<gfx::ImageFamily> GetAppIconImageFamily() { +std::unique_ptr<gfx::ImageFamily> GetAppIconImageFamily() { const int icon_id = GetAppIconResourceId(); // Get the icon from chrome.dll (not chrome.exe, which has different resource // IDs). If chrome.dll is not loaded, we are probably in a unit test, so fall
diff --git a/chrome/browser/app_icon_win.h b/chrome/browser/app_icon_win.h index c3e6308..9be98c5 100644 --- a/chrome/browser/app_icon_win.h +++ b/chrome/browser/app_icon_win.h
@@ -7,7 +7,7 @@ #include <windows.h> -#include "base/memory/scoped_ptr.h" +#include <memory> namespace gfx { class ImageFamily; @@ -24,6 +24,6 @@ // Retrieve the application icon for the current process. This returns all of // the different sizes of the icon as an ImageFamily. -scoped_ptr<gfx::ImageFamily> GetAppIconImageFamily(); +std::unique_ptr<gfx::ImageFamily> GetAppIconImageFamily(); #endif // CHROME_BROWSER_APP_ICON_WIN_H_
diff --git a/chrome/browser/autocomplete/autocomplete_classifier_factory.cc b/chrome/browser/autocomplete/autocomplete_classifier_factory.cc index 35cab6f5..0ffd0b9 100644 --- a/chrome/browser/autocomplete/autocomplete_classifier_factory.cc +++ b/chrome/browser/autocomplete/autocomplete_classifier_factory.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/autocomplete/autocomplete_classifier_factory.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/autocomplete/chrome_autocomplete_provider_client.h" #include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h" #include "chrome/browser/autocomplete/in_memory_url_index_factory.h" @@ -33,14 +34,14 @@ } // static -scoped_ptr<KeyedService> AutocompleteClassifierFactory::BuildInstanceFor( +std::unique_ptr<KeyedService> AutocompleteClassifierFactory::BuildInstanceFor( content::BrowserContext* context) { Profile* profile = static_cast<Profile*>(context); - return make_scoped_ptr(new AutocompleteClassifier( - make_scoped_ptr(new AutocompleteController( - make_scoped_ptr(new ChromeAutocompleteProviderClient(profile)), NULL, + return base::WrapUnique(new AutocompleteClassifier( + base::WrapUnique(new AutocompleteController( + base::WrapUnique(new ChromeAutocompleteProviderClient(profile)), NULL, AutocompleteClassifier::kDefaultOmniboxProviders)), - scoped_ptr<AutocompleteSchemeClassifier>( + std::unique_ptr<AutocompleteSchemeClassifier>( new ChromeAutocompleteSchemeClassifier(profile)))); }
diff --git a/chrome/browser/autocomplete/autocomplete_classifier_factory.h b/chrome/browser/autocomplete/autocomplete_classifier_factory.h index 1bfc755c..6d9ccc27 100644 --- a/chrome/browser/autocomplete/autocomplete_classifier_factory.h +++ b/chrome/browser/autocomplete/autocomplete_classifier_factory.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_AUTOCOMPLETE_AUTOCOMPLETE_CLASSIFIER_FACTORY_H_ #define CHROME_BROWSER_AUTOCOMPLETE_AUTOCOMPLETE_CLASSIFIER_FACTORY_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" @@ -22,7 +23,7 @@ static AutocompleteClassifierFactory* GetInstance(); - static scoped_ptr<KeyedService> BuildInstanceFor( + static std::unique_ptr<KeyedService> BuildInstanceFor( content::BrowserContext* context); private:
diff --git a/chrome/browser/autocomplete/chrome_autocomplete_provider_client.cc b/chrome/browser/autocomplete/chrome_autocomplete_provider_client.cc index 113c3dd..a0b1ac5 100644 --- a/chrome/browser/autocomplete/chrome_autocomplete_provider_client.cc +++ b/chrome/browser/autocomplete/chrome_autocomplete_provider_client.cc
@@ -7,6 +7,7 @@ #include <stddef.h> #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/autocomplete/autocomplete_classifier_factory.h" @@ -137,11 +138,11 @@ return ShortcutsBackendFactory::GetForProfileIfExists(profile_); } -scoped_ptr<KeywordExtensionsDelegate> +std::unique_ptr<KeywordExtensionsDelegate> ChromeAutocompleteProviderClient::GetKeywordExtensionsDelegate( KeywordProvider* keyword_provider) { #if defined(ENABLE_EXTENSIONS) - return make_scoped_ptr( + return base::WrapUnique( new KeywordExtensionsDelegateImpl(profile_, keyword_provider)); #else return nullptr;
diff --git a/chrome/browser/autocomplete/chrome_autocomplete_provider_client.h b/chrome/browser/autocomplete/chrome_autocomplete_provider_client.h index 1c97706..618a585c 100644 --- a/chrome/browser/autocomplete/chrome_autocomplete_provider_client.h +++ b/chrome/browser/autocomplete/chrome_autocomplete_provider_client.h
@@ -32,7 +32,7 @@ const SearchTermsData& GetSearchTermsData() const override; scoped_refptr<ShortcutsBackend> GetShortcutsBackend() override; scoped_refptr<ShortcutsBackend> GetShortcutsBackendIfExists() override; - scoped_ptr<KeywordExtensionsDelegate> GetKeywordExtensionsDelegate( + std::unique_ptr<KeywordExtensionsDelegate> GetKeywordExtensionsDelegate( KeywordProvider* keyword_provider) override; std::string GetAcceptLanguages() const override; std::string GetEmbedderRepresentationOfAboutScheme() override;
diff --git a/chrome/browser/autocomplete/keyword_extensions_delegate_impl_unittest.cc b/chrome/browser/autocomplete/keyword_extensions_delegate_impl_unittest.cc index 4ffae48..27a0881d 100644 --- a/chrome/browser/autocomplete/keyword_extensions_delegate_impl_unittest.cc +++ b/chrome/browser/autocomplete/keyword_extensions_delegate_impl_unittest.cc
@@ -83,7 +83,8 @@ } void KeywordExtensionsDelegateImplTest::RunTest(bool incognito) { - scoped_ptr<TemplateURLService> empty_model(new TemplateURLService(NULL, 0)); + std::unique_ptr<TemplateURLService> empty_model( + new TemplateURLService(NULL, 0)); MockAutocompleteProviderClient client; client.set_template_url_service(std::move(empty_model)); scoped_refptr<KeywordProvider> keyword_provider =
diff --git a/chrome/browser/autocomplete/search_provider_unittest.cc b/chrome/browser/autocomplete/search_provider_unittest.cc index bd1f56b6..d5b9a86 100644 --- a/chrome/browser/autocomplete/search_provider_unittest.cc +++ b/chrome/browser/autocomplete/search_provider_unittest.cc
@@ -10,6 +10,7 @@ #include "base/command_line.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" #include "base/run_loop.h" #include "base/strings/string16.h" @@ -167,7 +168,7 @@ protected: // Needed for AutocompleteFieldTrial::ActivateStaticTrials(); - scoped_ptr<base::FieldTrialList> field_trial_list_; + std::unique_ptr<base::FieldTrialList> field_trial_list_; // Default values used for testing. static const std::string kNotApplicable; @@ -257,7 +258,7 @@ net::TestURLFetcherFactory test_factory_; TestingProfile profile_; - scoped_ptr<ChromeAutocompleteProviderClient> client_; + std::unique_ptr<ChromeAutocompleteProviderClient> client_; scoped_refptr<SearchProviderForTest> provider_; // If non-NULL, OnProviderUpdate quits the current |run_loop_|. @@ -1090,8 +1091,8 @@ profile_.BlockUntilHistoryProcessesPendingRequests(); AutocompleteController controller( - make_scoped_ptr(new ChromeAutocompleteProviderClient(&profile_)), nullptr, - AutocompleteProvider::TYPE_SEARCH); + base::WrapUnique(new ChromeAutocompleteProviderClient(&profile_)), + nullptr, AutocompleteProvider::TYPE_SEARCH); controller.Start(AutocompleteInput( ASCIIToUTF16("k t"), base::string16::npos, std::string(), GURL(), metrics::OmniboxEventProto::INVALID_SPEC, false, false, true, true, false,
diff --git a/chrome/browser/autocomplete/shortcuts_backend_factory.cc b/chrome/browser/autocomplete/shortcuts_backend_factory.cc index c39588b4..4ccf932 100644 --- a/chrome/browser/autocomplete/shortcuts_backend_factory.cc +++ b/chrome/browser/autocomplete/shortcuts_backend_factory.cc
@@ -4,7 +4,9 @@ #include "chrome/browser/autocomplete/shortcuts_backend_factory.h" -#include "base/memory/scoped_ptr.h" +#include <memory> + +#include "base/memory/ptr_util.h" #include "chrome/browser/autocomplete/shortcuts_extensions_manager.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile.h" @@ -90,7 +92,7 @@ bool suppress_db) { scoped_refptr<ShortcutsBackend> backend(new ShortcutsBackend( TemplateURLServiceFactory::GetForProfile(profile), - make_scoped_ptr(new UIThreadSearchTermsData(profile)), + base::WrapUnique(new UIThreadSearchTermsData(profile)), HistoryServiceFactory::GetForProfile(profile, ServiceAccessType::EXPLICIT_ACCESS), content::BrowserThread::GetMessageLoopProxyForThread(
diff --git a/chrome/browser/autofill/android/OWNERS b/chrome/browser/autofill/android/OWNERS deleted file mode 100644 index 812e8d9..0000000 --- a/chrome/browser/autofill/android/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -aurimas@chromium.org
diff --git a/chrome/browser/autofill/android/personal_data_manager_android.cc b/chrome/browser/autofill/android/personal_data_manager_android.cc index 5cb515ca..56234fef 100644 --- a/chrome/browser/autofill/android/personal_data_manager_android.cc +++ b/chrome/browser/autofill/android/personal_data_manager_android.cc
@@ -12,6 +12,7 @@ #include "base/format_macros.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/browser/android/resource_mapper.h" #include "chrome/browser/autofill/personal_data_manager_factory.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" @@ -122,6 +123,32 @@ Java_AutofillProfile_getLanguageCode(env, jprofile.obj()))); } +// Mapping from Chrome card types to basic card payment spec. +// https://w3c.github.io/browser-payment-api/specs/basic-card-payment.html#method-id +// Note that "generic" is not in the spec. +const struct { + const char* card_type; + const char* basic_card_payment_type; +} kBasicCardPaymentTypes[] { + {"genericCC", "generic"}, + {"americanExpressCC", "amex"}, + {"dinersCC", "diners"}, + {"discoverCC", "discover"}, + {"jcbCC", "jcb"}, + {"masterCardCC", "mastercard"}, + {"visaCC", "visa"} +}; + +// Returns the type of this card according to the basic card payment spec. Will +// return "generic" for unrecognized card type. +const char* ConvertToBasicCardPaymentType(const std::string& type) { + for (size_t i = 0; i < arraysize(kBasicCardPaymentTypes); ++i) { + if (type == kBasicCardPaymentTypes[i].card_type) + return kBasicCardPaymentTypes[i].basic_card_payment_type; + } + return kBasicCardPaymentTypes[0].basic_card_payment_type; +} + ScopedJavaLocalRef<jobject> CreateJavaCreditCardFromNative( JNIEnv* env, const CreditCard& card) { @@ -138,7 +165,11 @@ .obj(), ConvertUTF16ToJavaString(env, card.GetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR)) - .obj()); + .obj(), + ConvertUTF8ToJavaString(env, ConvertToBasicCardPaymentType(card.type())) + .obj(), + ResourceMapper::MapFromChromiumId( + CreditCard::IconResourceId(card.type()))); } void PopulateNativeCreditCardFromJava(
diff --git a/chrome/browser/background/background_application_list_model.cc b/chrome/browser/background/background_application_list_model.cc index 91dacd6..60cd674 100644 --- a/chrome/browser/background/background_application_list_model.cc +++ b/chrome/browser/background/background_application_list_model.cc
@@ -74,7 +74,7 @@ void RequestIcon(extension_misc::ExtensionIcons size); const Extension* extension_; - scoped_ptr<gfx::ImageSkia> icon_; + std::unique_ptr<gfx::ImageSkia> icon_; BackgroundApplicationListModel* model_; };
diff --git a/chrome/browser/background/background_application_list_model_unittest.cc b/chrome/browser/background/background_application_list_model_unittest.cc index 29e68d5..9aababc 100644 --- a/chrome/browser/background/background_application_list_model_unittest.cc +++ b/chrome/browser/background/background_application_list_model_unittest.cc
@@ -4,16 +4,16 @@ // TODO(rickcam): Bug 73183: Add unit tests for image loading +#include "chrome/browser/background/background_application_list_model.h" + #include <stddef.h> #include <cstdlib> +#include <memory> #include <set> -#include "chrome/browser/background/background_application_list_model.h" - #include "base/command_line.h" #include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/stl_util.h" #include "build/build_config.h" @@ -150,7 +150,7 @@ InitializeAndLoadEmptyExtensionService(); ASSERT_TRUE(service()->is_ready()); ASSERT_TRUE(registry()->enabled_extensions().is_empty()); - scoped_ptr<BackgroundApplicationListModel> model( + std::unique_ptr<BackgroundApplicationListModel> model( new BackgroundApplicationListModel(profile_.get())); ASSERT_EQ(0U, model->size()); @@ -222,7 +222,7 @@ InitializeAndLoadEmptyExtensionService(); ASSERT_TRUE(service()->is_ready()); ASSERT_TRUE(registry()->enabled_extensions().is_empty()); - scoped_ptr<BackgroundApplicationListModel> model( + std::unique_ptr<BackgroundApplicationListModel> model( new BackgroundApplicationListModel(profile_.get())); ASSERT_EQ(0U, model->size()); @@ -378,7 +378,7 @@ InitializeAndLoadEmptyExtensionService(); ASSERT_TRUE(service()->is_ready()); ASSERT_TRUE(registry()->enabled_extensions().is_empty()); - scoped_ptr<BackgroundApplicationListModel> model( + std::unique_ptr<BackgroundApplicationListModel> model( new BackgroundApplicationListModel(profile_.get())); ASSERT_EQ(0U, model->size());
diff --git a/chrome/browser/background/background_contents.h b/chrome/browser/background/background_contents.h index 3e62e901..08c740d 100644 --- a/chrome/browser/background/background_contents.h +++ b/chrome/browser/background/background_contents.h
@@ -7,10 +7,10 @@ #include <stdint.h> +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/observer_list.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" @@ -109,10 +109,10 @@ Delegate* delegate_; // Delegate for choosing an ExtensionHostQueue. - scoped_ptr<extensions::ExtensionHostDelegate> extension_host_delegate_; + std::unique_ptr<extensions::ExtensionHostDelegate> extension_host_delegate_; Profile* profile_; - scoped_ptr<content::WebContents> web_contents_; + std::unique_ptr<content::WebContents> web_contents_; content::NotificationRegistrar registrar_; base::ObserverList<extensions::DeferredStartRenderHostObserver> deferred_start_render_host_observer_list_;
diff --git a/chrome/browser/background/background_contents_service_unittest.cc b/chrome/browser/background/background_contents_service_unittest.cc index fe0cc7b..7aba4a9 100644 --- a/chrome/browser/background/background_contents_service_unittest.cc +++ b/chrome/browser/background/background_contents_service_unittest.cc
@@ -2,16 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/background/background_contents_service.h" + +#include <memory> #include <string> #include "base/command_line.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/background/background_contents.h" -#include "chrome/browser/background/background_contents_service.h" #include "chrome/browser/background/background_contents_service_factory.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/ui/browser_list.h" @@ -69,7 +70,7 @@ } content::TestBrowserThreadBundle thread_bundle_; - scoped_ptr<base::CommandLine> command_line_; + std::unique_ptr<base::CommandLine> command_line_; }; class MockBackgroundContents : public BackgroundContents { @@ -221,7 +222,7 @@ } private: - scoped_ptr<TestingProfileManager> profile_manager_; + std::unique_ptr<TestingProfileManager> profile_manager_; DISALLOW_COPY_AND_ASSIGN(BackgroundContentsServiceNotificationTest); }; @@ -253,7 +254,7 @@ GURL url("http://a/"); GURL url2("http://a/"); { - scoped_ptr<MockBackgroundContents> contents( + std::unique_ptr<MockBackgroundContents> contents( new MockBackgroundContents(&profile)); EXPECT_EQ(0U, GetPrefs(&profile)->size()); contents->SendOpenedNotification(&service); @@ -300,8 +301,8 @@ GURL url("http://a/"); { - scoped_ptr<MockBackgroundContents> contents(new MockBackgroundContents( - &profile, "appid")); + std::unique_ptr<MockBackgroundContents> contents( + new MockBackgroundContents(&profile, "appid")); contents->SendOpenedNotification(&service); contents->Navigate(url); EXPECT_EQ(1U, GetPrefs(&profile)->size()); @@ -313,8 +314,8 @@ { // Reopen the BackgroundContents to the same URL, we should not register the // URL again. - scoped_ptr<MockBackgroundContents> contents(new MockBackgroundContents( - &profile, "appid")); + std::unique_ptr<MockBackgroundContents> contents( + new MockBackgroundContents(&profile, "appid")); contents->SendOpenedNotification(&service); contents->Navigate(url); EXPECT_EQ(1U, GetPrefs(&profile)->size()); @@ -334,7 +335,7 @@ service.GetAppBackgroundContents(base::ASCIIToUTF16("appid"))); MockBackgroundContents* contents = new MockBackgroundContents(&profile, "appid"); - scoped_ptr<MockBackgroundContents> contents2( + std::unique_ptr<MockBackgroundContents> contents2( new MockBackgroundContents(&profile, "appid2")); contents->SendOpenedNotification(&service); EXPECT_EQ(contents, service.GetAppBackgroundContents(contents->appid()));
diff --git a/chrome/browser/background/background_mode_manager.cc b/chrome/browser/background/background_mode_manager.cc index fcd2c672..9458942 100644 --- a/chrome/browser/background/background_mode_manager.cc +++ b/chrome/browser/background/background_mode_manager.cc
@@ -884,7 +884,7 @@ // the ImageFamily abstraction. Note: We could just use the LoadImage function // from the Windows API, but that does a *terrible* job scaling images. // Therefore, we fetch the images and do our own high-quality scaling. - scoped_ptr<gfx::ImageFamily> family = GetAppIconImageFamily(); + std::unique_ptr<gfx::ImageFamily> family = GetAppIconImageFamily(); DCHECK(family); if (!family) return gfx::ImageSkia(); @@ -940,7 +940,7 @@ command_id_handler_vector_.clear(); submenus.clear(); - scoped_ptr<StatusIconMenuModel> menu(new StatusIconMenuModel(this)); + std::unique_ptr<StatusIconMenuModel> menu(new StatusIconMenuModel(this)); menu->AddItem(IDC_ABOUT, l10n_util::GetStringUTF16(IDS_ABOUT)); menu->AddItemWithStringId(IDC_TASK_MANAGER, IDS_TASK_MANAGER); menu->AddSeparator(ui::NORMAL_SEPARATOR);
diff --git a/chrome/browser/background/background_mode_manager.h b/chrome/browser/background/background_mode_manager.h index 5878c0ac..986863d 100644 --- a/chrome/browser/background/background_mode_manager.h +++ b/chrome/browser/background/background_mode_manager.h
@@ -152,7 +152,7 @@ ~BackgroundModeData() override; // The cached list of BackgroundApplications. - scoped_ptr<BackgroundApplicationListModel> applications_; + std::unique_ptr<BackgroundApplicationListModel> applications_; // Overrides from StatusIconMenuModel::Delegate implementation. void ExecuteCommand(int command_id, int event_flags) override; @@ -420,12 +420,12 @@ // Background mode does not always keep Chrome alive. When it does, it is // using this scoped object. - scoped_ptr<ScopedKeepAlive> keep_alive_; + std::unique_ptr<ScopedKeepAlive> keep_alive_; // Set when we are keeping chrome running during the startup process - this // is required when running with the --no-startup-window flag, as otherwise // chrome would immediately exit due to having no open windows. - scoped_ptr<ScopedKeepAlive> keep_alive_for_startup_; + std::unique_ptr<ScopedKeepAlive> keep_alive_for_startup_; // Set to true when Chrome is running with the --keep-alive-for-test flag // (used for testing background mode without having to install a background
diff --git a/chrome/browser/background/background_mode_manager_unittest.cc b/chrome/browser/background/background_mode_manager_unittest.cc index b1af033d..eae39289 100644 --- a/chrome/browser/background/background_mode_manager_unittest.cc +++ b/chrome/browser/background/background_mode_manager_unittest.cc
@@ -2,20 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/background/background_mode_manager.h" + #include <stddef.h> +#include <memory> #include <string> #include "base/bind.h" #include "base/command_line.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/test/test_simple_task_runner.h" #include "base/thread_task_runner_handle.h" #include "build/build_config.h" -#include "chrome/browser/background/background_mode_manager.h" #include "chrome/browser/background/background_trigger.h" #include "chrome/browser/browser_shutdown.h" #include "chrome/browser/extensions/extension_function_test_utils.h" @@ -58,8 +59,8 @@ namespace { -scoped_ptr<TestingProfileManager> CreateTestingProfileManager() { - scoped_ptr<TestingProfileManager> profile_manager( +std::unique_ptr<TestingProfileManager> CreateTestingProfileManager() { + std::unique_ptr<TestingProfileManager> profile_manager( new TestingProfileManager(TestingBrowserProcess::GetGlobal())); EXPECT_TRUE(profile_manager->SetUp()); return profile_manager; @@ -207,9 +208,9 @@ protected: content::TestBrowserThreadBundle thread_bundle_; - scoped_ptr<base::CommandLine> command_line_; + std::unique_ptr<base::CommandLine> command_line_; - scoped_ptr<TestingProfileManager> profile_manager_; + std::unique_ptr<TestingProfileManager> profile_manager_; // Test profile used by all tests - this is owned by profile_manager_. TestingProfile* profile_; @@ -286,7 +287,7 @@ extensions::Manifest::Location location, const std::string& data, const std::string& id) { - scoped_ptr<base::DictionaryValue> parsed_manifest( + std::unique_ptr<base::DictionaryValue> parsed_manifest( extensions::api_test_utils::ParseDictionary(data)); return extensions::api_test_utils::CreateExtension( location, parsed_manifest.get(), id); @@ -301,11 +302,11 @@ return false; } - scoped_ptr<TestBackgroundModeManager> manager_; + std::unique_ptr<TestBackgroundModeManager> manager_; - scoped_ptr<base::CommandLine> command_line_; + std::unique_ptr<base::CommandLine> command_line_; - scoped_ptr<TestingProfileManager> profile_manager_; + std::unique_ptr<TestingProfileManager> profile_manager_; // Test profile used by all tests - this is owned by profile_manager_. TestingProfile* profile_; @@ -317,7 +318,7 @@ // tearing down our thread bundle before we've had chance to clean // everything up. Keeping Chrome alive prevents this. // We aren't interested in if the keep alive works correctly in this test. - scoped_ptr<ScopedKeepAlive> test_keep_alive_; + std::unique_ptr<ScopedKeepAlive> test_keep_alive_; #if defined(OS_CHROMEOS) // ChromeOS needs extra services to run in the following order. @@ -708,8 +709,8 @@ service->AddExtension(regular_extension_with_options.get()); Mock::VerifyAndClearExpectations(manager_.get()); - scoped_ptr<StatusIconMenuModel> menu(new StatusIconMenuModel(NULL)); - scoped_ptr<StatusIconMenuModel> submenu(new StatusIconMenuModel(NULL)); + std::unique_ptr<StatusIconMenuModel> menu(new StatusIconMenuModel(NULL)); + std::unique_ptr<StatusIconMenuModel> submenu(new StatusIconMenuModel(NULL)); BackgroundModeManager::BackgroundModeData* bmd = manager_->GetBackgroundModeData(profile_); bmd->BuildProfileMenu(submenu.get(), menu.get());
diff --git a/chrome/browser/background_sync/background_sync_controller_impl_unittest.cc b/chrome/browser/background_sync/background_sync_controller_impl_unittest.cc index 99507fa..93d1b78 100644 --- a/chrome/browser/background_sync/background_sync_controller_impl_unittest.cc +++ b/chrome/browser/background_sync/background_sync_controller_impl_unittest.cc
@@ -66,8 +66,8 @@ content::TestBrowserThreadBundle thread_bundle_; TestingProfile profile_; rappor::TestRapporService rappor_service_; - scoped_ptr<TestBackgroundSyncControllerImpl> controller_; - scoped_ptr<base::FieldTrialList> field_trial_list_; + std::unique_ptr<TestBackgroundSyncControllerImpl> controller_; + std::unique_ptr<base::FieldTrialList> field_trial_list_; DISALLOW_COPY_AND_ASSIGN(BackgroundSyncControllerImplTest); };
diff --git a/chrome/browser/banners/app_banner_data_fetcher.cc b/chrome/browser/banners/app_banner_data_fetcher.cc index 5282804f..bd7667e 100644 --- a/chrome/browser/banners/app_banner_data_fetcher.cc +++ b/chrome/browser/banners/app_banner_data_fetcher.cc
@@ -27,6 +27,7 @@ #include "content/public/browser/service_worker_context.h" #include "content/public/browser/storage_partition.h" #include "net/base/load_flags.h" +#include "third_party/WebKit/public/platform/WebDisplayMode.h" #include "third_party/WebKit/public/platform/modules/app_banner/WebAppBannerPromptReply.h" #include "ui/gfx/screen.h" @@ -460,11 +461,23 @@ is_debug_mode); return false; } - if (manifest.name.is_null() && manifest.short_name.is_null()) { + if ((manifest.name.is_null() || manifest.name.string().empty()) && + (manifest.short_name.is_null() || manifest.short_name.string().empty())) { OutputDeveloperNotShownMessage( web_contents, kManifestMissingNameOrShortName, is_debug_mode); return false; } + + // TODO(dominickn,mlamouri): when Chrome supports "minimal-ui", it should be + // accepted. If we accept it today, it would fallback to "browser" and make + // this check moot. See https://crbug.com/604390 + if (manifest.display != blink::WebDisplayModeStandalone && + manifest.display != blink::WebDisplayModeFullscreen) { + OutputDeveloperNotShownMessage( + web_contents, kManifestDisplayStandaloneFullscreen, is_debug_mode); + return false; + } + if (!DoesManifestContainRequiredIcon(manifest)) { OutputDeveloperNotShownMessage(web_contents, kManifestMissingSuitableIcon, is_debug_mode);
diff --git a/chrome/browser/banners/app_banner_data_fetcher.h b/chrome/browser/banners/app_banner_data_fetcher.h index 194bf0b..e07d839 100644 --- a/chrome/browser/banners/app_banner_data_fetcher.h +++ b/chrome/browser/banners/app_banner_data_fetcher.h
@@ -5,9 +5,10 @@ #ifndef CHROME_BROWSER_BANNERS_APP_BANNER_DATA_FETCHER_H_ #define CHROME_BROWSER_BANNERS_APP_BANNER_DATA_FETCHER_H_ +#include <memory> + #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/time/time.h" @@ -191,7 +192,7 @@ const bool is_debug_mode_; ui::PageTransition transition_type_; int event_request_id_; - scoped_ptr<SkBitmap> app_icon_; + std::unique_ptr<SkBitmap> app_icon_; std::string referrer_; GURL validated_url_;
diff --git a/chrome/browser/banners/app_banner_data_fetcher_browsertest.cc b/chrome/browser/banners/app_banner_data_fetcher_browsertest.cc index 57d3883..1e6d329 100644 --- a/chrome/browser/banners/app_banner_data_fetcher_browsertest.cc +++ b/chrome/browser/banners/app_banner_data_fetcher_browsertest.cc
@@ -55,7 +55,7 @@ private: AppBannerDataFetcher* fetcher_; base::Closure quit_closure_; - scoped_ptr<bool> will_show_; + std::unique_ptr<bool> will_show_; }; class AppBannerDataFetcherBrowserTest : public InProcessBrowserTest, @@ -102,8 +102,8 @@ base::HistogramTester histograms; base::RunLoop run_loop; quit_closure_ = run_loop.QuitClosure(); - scoped_ptr<TestObserver> observer(new TestObserver(fetcher.get(), - run_loop.QuitClosure())); + std::unique_ptr<TestObserver> observer( + new TestObserver(fetcher.get(), run_loop.QuitClosure())); fetcher->Start(url, transition); run_loop.Run();
diff --git a/chrome/browser/banners/app_banner_data_fetcher_desktop.h b/chrome/browser/banners/app_banner_data_fetcher_desktop.h index 3bef84ae..fe05ad35 100644 --- a/chrome/browser/banners/app_banner_data_fetcher_desktop.h +++ b/chrome/browser/banners/app_banner_data_fetcher_desktop.h
@@ -42,7 +42,7 @@ const base::string16& title, const std::string& referrer) override; - scoped_ptr<extensions::BookmarkAppHelper> bookmark_app_helper_; + std::unique_ptr<extensions::BookmarkAppHelper> bookmark_app_helper_; DISALLOW_COPY_AND_ASSIGN(AppBannerDataFetcherDesktop); };
diff --git a/chrome/browser/banners/app_banner_data_fetcher_unittest.cc b/chrome/browser/banners/app_banner_data_fetcher_unittest.cc index 4be44fe..1de8aef 100644 --- a/chrome/browser/banners/app_banner_data_fetcher_unittest.cc +++ b/chrome/browser/banners/app_banner_data_fetcher_unittest.cc
@@ -6,6 +6,7 @@ #include "base/strings/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/WebKit/public/platform/WebDisplayMode.h" namespace banners { @@ -23,6 +24,7 @@ manifest.name = ToNullableUTF16("foo"); manifest.short_name = ToNullableUTF16("bar"); manifest.start_url = GURL("http://example.com"); + manifest.display = blink::WebDisplayModeStandalone; content::Manifest::Icon icon; icon.type = ToNullableUTF16("image/png"); @@ -67,6 +69,20 @@ EXPECT_FALSE(IsManifestValid(manifest)); } +TEST_F(AppBannerDataFetcherUnitTest, ManifestRequiresNonEmptyNameORShortName) { + content::Manifest manifest = GetValidManifest(); + + manifest.name = ToNullableUTF16(""); + EXPECT_TRUE(IsManifestValid(manifest)); + + manifest.name = ToNullableUTF16("foo"); + manifest.short_name = ToNullableUTF16(""); + EXPECT_TRUE(IsManifestValid(manifest)); + + manifest.name = ToNullableUTF16(""); + EXPECT_FALSE(IsManifestValid(manifest)); +} + TEST_F(AppBannerDataFetcherUnitTest, ManifestRequiresValidStartURL) { content::Manifest manifest = GetValidManifest(); @@ -110,4 +126,23 @@ EXPECT_TRUE(IsManifestValid(manifest)); } +TEST_F(AppBannerDataFetcherUnitTest, ManifestDisplayStandaloneFullscreen) { + content::Manifest manifest = GetValidManifest(); + + manifest.display = blink::WebDisplayModeUndefined; + EXPECT_FALSE(IsManifestValid(manifest)); + + manifest.display = blink::WebDisplayModeBrowser; + EXPECT_FALSE(IsManifestValid(manifest)); + + manifest.display = blink::WebDisplayModeMinimalUi; + EXPECT_FALSE(IsManifestValid(manifest)); + + manifest.display = blink::WebDisplayModeStandalone; + EXPECT_TRUE(IsManifestValid(manifest)); + + manifest.display = blink::WebDisplayModeFullscreen; + EXPECT_TRUE(IsManifestValid(manifest)); +} + } // namespace banners
diff --git a/chrome/browser/banners/app_banner_debug_log.cc b/chrome/browser/banners/app_banner_debug_log.cc index bff2cdf..dac19e0 100644 --- a/chrome/browser/banners/app_banner_debug_log.cc +++ b/chrome/browser/banners/app_banner_debug_log.cc
@@ -30,6 +30,8 @@ "the user navigated before the banner could be shown"; static const char kStartURLNotValidMessage[] = "start URL in manifest is not valid"; +static const char kManifestDisplayStandaloneFullscreenMessage[] = + "manifest display property must be set to 'standalone' or 'fullscreen'"; static const char kManifestMissingNameOrShortNameMessage[] = "one of manifest name or short name must be specified"; static const char kManifestMissingSuitableIconMessage[] = @@ -94,6 +96,9 @@ case kStartURLNotValid: pattern = kStartURLNotValidMessage; break; + case kManifestDisplayStandaloneFullscreen: + pattern = kManifestDisplayStandaloneFullscreenMessage; + break; case kManifestMissingNameOrShortName: pattern = kManifestMissingNameOrShortNameMessage; break;
diff --git a/chrome/browser/banners/app_banner_debug_log.h b/chrome/browser/banners/app_banner_debug_log.h index fa9dbe6..2a8d80a 100644 --- a/chrome/browser/banners/app_banner_debug_log.h +++ b/chrome/browser/banners/app_banner_debug_log.h
@@ -25,6 +25,7 @@ kNoIconAvailable, kUserNavigatedBeforeBannerShown, kStartURLNotValid, + kManifestDisplayStandaloneFullscreen, kManifestMissingNameOrShortName, kManifestMissingSuitableIcon, kNotLoadedInMainFrame,
diff --git a/chrome/browser/banners/app_banner_infobar_delegate_desktop.cc b/chrome/browser/banners/app_banner_infobar_delegate_desktop.cc index 604f8ab9..62f6cf1 100644 --- a/chrome/browser/banners/app_banner_infobar_delegate_desktop.cc +++ b/chrome/browser/banners/app_banner_infobar_delegate_desktop.cc
@@ -49,8 +49,9 @@ InfoBarService* infobar_service = InfoBarService::FromWebContents(web_contents); return infobar_service->AddInfoBar(infobar_service->CreateConfirmInfoBar( - scoped_ptr<ConfirmInfoBarDelegate>(new AppBannerInfoBarDelegateDesktop( - fetcher, web_manifest, bookmark_app_helper, event_request_id)))); + std::unique_ptr<ConfirmInfoBarDelegate>( + new AppBannerInfoBarDelegateDesktop( + fetcher, web_manifest, bookmark_app_helper, event_request_id)))); } infobars::InfoBarDelegate::Type
diff --git a/chrome/browser/banners/app_banner_infobar_delegate_desktop.h b/chrome/browser/banners/app_banner_infobar_delegate_desktop.h index d0a4cfc7..bf4fc21 100644 --- a/chrome/browser/banners/app_banner_infobar_delegate_desktop.h +++ b/chrome/browser/banners/app_banner_infobar_delegate_desktop.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_BANNERS_APP_BANNER_INFOBAR_DELEGATE_DESKTOP_H_ #define CHROME_BROWSER_BANNERS_APP_BANNER_INFOBAR_DELEGATE_DESKTOP_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "components/infobars/core/confirm_infobar_delegate.h" #include "content/public/common/manifest.h"
diff --git a/chrome/browser/banners/app_banner_manager.h b/chrome/browser/banners/app_banner_manager.h index efcf332d..f29c0bdb 100644 --- a/chrome/browser/banners/app_banner_manager.h +++ b/chrome/browser/banners/app_banner_manager.h
@@ -5,9 +5,10 @@ #ifndef CHROME_BROWSER_BANNERS_APP_BANNER_MANAGER_H_ #define CHROME_BROWSER_BANNERS_APP_BANNER_MANAGER_H_ +#include <memory> + #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/banners/app_banner_data_fetcher.h" #include "content/public/browser/web_contents_observer.h"
diff --git a/chrome/browser/banners/app_banner_settings_helper.cc b/chrome/browser/banners/app_banner_settings_helper.cc index 824ff63..0e0f24b 100644 --- a/chrome/browser/banners/app_banner_settings_helper.cc +++ b/chrome/browser/banners/app_banner_settings_helper.cc
@@ -5,11 +5,13 @@ #include "chrome/browser/banners/app_banner_settings_helper.h" #include <stddef.h> + #include <algorithm> #include <string> #include <utility> #include "base/command_line.h" +#include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" @@ -88,18 +90,18 @@ // Total engagement score required before a banner will actually be triggered. double gTotalEngagementToTrigger = kDefaultTotalEngagementToTrigger; -scoped_ptr<base::DictionaryValue> GetOriginDict( +std::unique_ptr<base::DictionaryValue> GetOriginDict( HostContentSettingsMap* settings, const GURL& origin_url) { if (!settings) - return make_scoped_ptr(new base::DictionaryValue()); + return base::WrapUnique(new base::DictionaryValue()); - scoped_ptr<base::DictionaryValue> dict = + std::unique_ptr<base::DictionaryValue> dict = base::DictionaryValue::From(settings->GetWebsiteSetting( origin_url, origin_url, CONTENT_SETTINGS_TYPE_APP_BANNER, std::string(), NULL)); if (!dict) - return make_scoped_ptr(new base::DictionaryValue()); + return base::WrapUnique(new base::DictionaryValue()); return dict; } @@ -111,7 +113,8 @@ // Don't allow more than kMaxAppsPerSite dictionaries. if (origin_dict->size() < kMaxAppsPerSite) { app_dict = new base::DictionaryValue(); - origin_dict->SetWithoutPathExpansion(key_name, make_scoped_ptr(app_dict)); + origin_dict->SetWithoutPathExpansion(key_name, + base::WrapUnique(app_dict)); } } @@ -268,7 +271,7 @@ HostContentSettingsMap* settings = HostContentSettingsMapFactory::GetForProfile(profile); - scoped_ptr<base::DictionaryValue> origin_dict = + std::unique_ptr<base::DictionaryValue> origin_dict = GetOriginDict(settings, origin_url); if (!origin_dict) return; @@ -309,7 +312,7 @@ HostContentSettingsMap* settings = HostContentSettingsMapFactory::GetForProfile(profile); - scoped_ptr<base::DictionaryValue> origin_dict = + std::unique_ptr<base::DictionaryValue> origin_dict = GetOriginDict(settings, origin_url); if (!origin_dict) return; @@ -325,7 +328,7 @@ base::ListValue* could_show_list = nullptr; if (!app_dict->GetList(event_key, &could_show_list)) { could_show_list = new base::ListValue(); - app_dict->Set(event_key, make_scoped_ptr(could_show_list)); + app_dict->Set(event_key, base::WrapUnique(could_show_list)); } // Trim any items that are older than we should care about. For comparisons @@ -371,7 +374,7 @@ // Dates are stored in their raw form (i.e. not local dates) to be resilient // to time zone changes. - scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> value(new base::DictionaryValue()); value->SetDouble(kBannerTimeKey, time.ToInternalValue()); value->SetDouble(kBannerEngagementKey, engagement); could_show_list->Append(std::move(value)); @@ -457,7 +460,7 @@ Profile::FromBrowserContext(web_contents->GetBrowserContext()); HostContentSettingsMap* settings = HostContentSettingsMapFactory::GetForProfile(profile); - scoped_ptr<base::DictionaryValue> origin_dict = + std::unique_ptr<base::DictionaryValue> origin_dict = GetOriginDict(settings, origin_url); if (!origin_dict) @@ -503,7 +506,7 @@ Profile::FromBrowserContext(web_contents->GetBrowserContext()); HostContentSettingsMap* settings = HostContentSettingsMapFactory::GetForProfile(profile); - scoped_ptr<base::DictionaryValue> origin_dict = + std::unique_ptr<base::DictionaryValue> origin_dict = GetOriginDict(settings, origin_url); if (!origin_dict)
diff --git a/chrome/browser/bitmap_fetcher/bitmap_fetcher.h b/chrome/browser/bitmap_fetcher/bitmap_fetcher.h index 3e928c00..38542767 100644 --- a/chrome/browser/bitmap_fetcher/bitmap_fetcher.h +++ b/chrome/browser/bitmap_fetcher/bitmap_fetcher.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_BITMAP_FETCHER_BITMAP_FETCHER_H_ #define CHROME_BROWSER_BITMAP_FETCHER_BITMAP_FETCHER_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/bitmap_fetcher/bitmap_fetcher_delegate.h" #include "chrome/browser/image_decoder.h" #include "net/url_request/url_fetcher_delegate.h" @@ -69,7 +70,7 @@ // Alerts the delegate that a failure occurred. void ReportFailure(); - scoped_ptr<net::URLFetcher> url_fetcher_; + std::unique_ptr<net::URLFetcher> url_fetcher_; const GURL url_; BitmapFetcherDelegate* const delegate_;
diff --git a/chrome/browser/bitmap_fetcher/bitmap_fetcher_browsertest.cc b/chrome/browser/bitmap_fetcher/bitmap_fetcher_browsertest.cc index 27b322d..d4f1211 100644 --- a/chrome/browser/bitmap_fetcher/bitmap_fetcher_browsertest.cc +++ b/chrome/browser/bitmap_fetcher/bitmap_fetcher_browsertest.cc
@@ -80,7 +80,7 @@ protected: net::URLFetcherImplFactory url_fetcher_impl_factory_; - scoped_ptr<net::FakeURLFetcherFactory> url_fetcher_factory_; + std::unique_ptr<net::FakeURLFetcherFactory> url_fetcher_factory_; }; // WARNING: These tests work with --single_process, but not
diff --git a/chrome/browser/bitmap_fetcher/bitmap_fetcher_service.cc b/chrome/browser/bitmap_fetcher/bitmap_fetcher_service.cc index 42fb706..f1a2f9a 100644 --- a/chrome/browser/bitmap_fetcher/bitmap_fetcher_service.cc +++ b/chrome/browser/bitmap_fetcher/bitmap_fetcher_service.cc
@@ -37,7 +37,7 @@ private: const BitmapFetcherService::RequestId request_id_; - scoped_ptr<BitmapFetcherService::Observer> observer_; + std::unique_ptr<BitmapFetcherService::Observer> observer_; const chrome::BitmapFetcher* fetcher_; DISALLOW_COPY_AND_ASSIGN(BitmapFetcherRequest); @@ -89,7 +89,7 @@ if (current_request_id_ == REQUEST_ID_INVALID) ++current_request_id_; int request_id = current_request_id_; - scoped_ptr<BitmapFetcherRequest> request( + std::unique_ptr<BitmapFetcherRequest> request( new BitmapFetcherRequest(request_id, observer)); // Reject invalid URLs. @@ -123,9 +123,9 @@ EnsureFetcherForUrl(url); } -scoped_ptr<chrome::BitmapFetcher> BitmapFetcherService::CreateFetcher( +std::unique_ptr<chrome::BitmapFetcher> BitmapFetcherService::CreateFetcher( const GURL& url) { - scoped_ptr<chrome::BitmapFetcher> new_fetcher( + std::unique_ptr<chrome::BitmapFetcher> new_fetcher( new chrome::BitmapFetcher(url, this)); new_fetcher->Init( @@ -144,7 +144,7 @@ if (fetcher) return fetcher; - scoped_ptr<chrome::BitmapFetcher> new_fetcher = CreateFetcher(url); + std::unique_ptr<chrome::BitmapFetcher> new_fetcher = CreateFetcher(url); active_fetchers_.push_back(std::move(new_fetcher)); return active_fetchers_.back().get(); } @@ -186,7 +186,7 @@ } if (bitmap && !bitmap->isNull()) { - scoped_ptr<CacheEntry> entry(new CacheEntry); + std::unique_ptr<CacheEntry> entry(new CacheEntry); entry->bitmap.reset(new SkBitmap(*bitmap)); cache_.Put(fetcher->url(), std::move(entry)); }
diff --git a/chrome/browser/bitmap_fetcher/bitmap_fetcher_service.h b/chrome/browser/bitmap_fetcher/bitmap_fetcher_service.h index f9c5962..4df69f2 100644 --- a/chrome/browser/bitmap_fetcher/bitmap_fetcher_service.h +++ b/chrome/browser/bitmap_fetcher/bitmap_fetcher_service.h
@@ -4,11 +4,12 @@ #ifndef CHROME_BROWSER_BITMAP_FETCHER_BITMAP_FETCHER_SERVICE_H_ #define CHROME_BROWSER_BITMAP_FETCHER_BITMAP_FETCHER_SERVICE_H_ +#include <memory> + #include "base/compiler_specific.h" #include "base/containers/mru_cache.h" #include "base/containers/scoped_ptr_hash_map.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "chrome/browser/bitmap_fetcher/bitmap_fetcher_delegate.h" #include "components/keyed_service/core/keyed_service.h" @@ -64,7 +65,7 @@ protected: // Create a bitmap fetcher for the given |url| and start it. Virtual method // so tests can override this for different behavior. - virtual scoped_ptr<chrome::BitmapFetcher> CreateFetcher(const GURL& url); + virtual std::unique_ptr<chrome::BitmapFetcher> CreateFetcher(const GURL& url); private: friend class BitmapFetcherServiceTest; @@ -84,7 +85,7 @@ void OnFetchComplete(const GURL& url, const SkBitmap* bitmap) override; // Currently active image fetchers. - std::vector<scoped_ptr<chrome::BitmapFetcher>> active_fetchers_; + std::vector<std::unique_ptr<chrome::BitmapFetcher>> active_fetchers_; // Currently active requests. ScopedVector<BitmapFetcherRequest> requests_; @@ -94,9 +95,9 @@ CacheEntry(); ~CacheEntry(); - scoped_ptr<const SkBitmap> bitmap; + std::unique_ptr<const SkBitmap> bitmap; }; - base::MRUCache<GURL, scoped_ptr<CacheEntry>> cache_; + base::MRUCache<GURL, std::unique_ptr<CacheEntry>> cache_; // Current request ID to be used. int current_request_id_;
diff --git a/chrome/browser/bitmap_fetcher/bitmap_fetcher_service_unittest.cc b/chrome/browser/bitmap_fetcher/bitmap_fetcher_service_unittest.cc index 7ba9458..74c1906b 100644 --- a/chrome/browser/bitmap_fetcher/bitmap_fetcher_service_unittest.cc +++ b/chrome/browser/bitmap_fetcher/bitmap_fetcher_service_unittest.cc
@@ -7,6 +7,7 @@ #include <stddef.h> #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/bitmap_fetcher/bitmap_fetcher.h" #include "chrome/test/base/testing_profile.h" #include "content/public/test/test_browser_thread_bundle.h" @@ -45,8 +46,9 @@ // Create a fetcher, but don't start downloading. That allows side-stepping // the decode step, which requires a utility process. - scoped_ptr<chrome::BitmapFetcher> CreateFetcher(const GURL& url) override { - return make_scoped_ptr(new chrome::BitmapFetcher(url, this)); + std::unique_ptr<chrome::BitmapFetcher> CreateFetcher( + const GURL& url) override { + return base::WrapUnique(new chrome::BitmapFetcher(url, this)); } }; @@ -69,7 +71,7 @@ const ScopedVector<BitmapFetcherRequest>& requests() const { return service_->requests_; } - const std::vector<scoped_ptr<chrome::BitmapFetcher>>& active_fetchers() + const std::vector<std::unique_ptr<chrome::BitmapFetcher>>& active_fetchers() const { return service_->active_fetchers_; } @@ -106,7 +108,7 @@ } protected: - scoped_ptr<BitmapFetcherService> service_; + std::unique_ptr<BitmapFetcherService> service_; int images_changed_; int requests_finished_;
diff --git a/chrome/browser/bookmarks/bookmark_html_writer.cc b/chrome/browser/bookmarks/bookmark_html_writer.cc index 34bd5c6..efcf365 100644 --- a/chrome/browser/bookmarks/bookmark_html_writer.cc +++ b/chrome/browser/bookmarks/bookmark_html_writer.cc
@@ -7,13 +7,14 @@ #include <stddef.h> #include <stdint.h> +#include <memory> + #include "base/base64.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" #include "base/files/file.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" @@ -366,19 +367,19 @@ // The BookmarkModel as a base::Value. This value was generated from the // BookmarkCodec. - scoped_ptr<base::Value> bookmarks_; + std::unique_ptr<base::Value> bookmarks_; // Path we're writing to. base::FilePath path_; // Map that stores favicon per URL. - scoped_ptr<BookmarkFaviconFetcher::URLFaviconMap> favicons_map_; + std::unique_ptr<BookmarkFaviconFetcher::URLFaviconMap> favicons_map_; // Observer to be notified on finish. BookmarksExportObserver* observer_; // File we're writing to. - scoped_ptr<base::File> file_; + std::unique_ptr<base::File> file_; // How much we indent when writing a bookmark/folder. This is modified // via IncrementIndent and DecrementIndent.
diff --git a/chrome/browser/bookmarks/bookmark_html_writer.h b/chrome/browser/bookmarks/bookmark_html_writer.h index 00c540d..ed8ae816 100644 --- a/chrome/browser/bookmarks/bookmark_html_writer.h +++ b/chrome/browser/bookmarks/bookmark_html_writer.h
@@ -88,7 +88,7 @@ base::CancelableTaskTracker cancelable_task_tracker_; // Map that stores favicon per URL. - scoped_ptr<URLFaviconMap> favicons_map_; + std::unique_ptr<URLFaviconMap> favicons_map_; // Path where html output is stored. base::FilePath path_;
diff --git a/chrome/browser/bookmarks/bookmark_model_factory.cc b/chrome/browser/bookmarks/bookmark_model_factory.cc index 13297fa1..4d9846a48 100644 --- a/chrome/browser/bookmarks/bookmark_model_factory.cc +++ b/chrome/browser/bookmarks/bookmark_model_factory.cc
@@ -6,6 +6,7 @@ #include "base/command_line.h" #include "base/deferred_sequenced_task_runner.h" +#include "base/memory/ptr_util.h" #include "base/memory/singleton.h" #include "base/values.h" #include "build/build_config.h" @@ -71,7 +72,7 @@ content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); BookmarkModel* bookmark_model = - new BookmarkModel(make_scoped_ptr(new ChromeBookmarkClient( + new BookmarkModel(base::WrapUnique(new ChromeBookmarkClient( profile, ManagedBookmarkServiceFactory::GetForProfile(profile)))); bookmark_model->Load(profile->GetPrefs(), profile->GetPath(),
diff --git a/chrome/browser/bookmarks/managed_bookmark_service_factory.cc b/chrome/browser/bookmarks/managed_bookmark_service_factory.cc index 64fed097..069f036 100644 --- a/chrome/browser/bookmarks/managed_bookmark_service_factory.cc +++ b/chrome/browser/bookmarks/managed_bookmark_service_factory.cc
@@ -7,6 +7,7 @@ #include <string> #include "base/bind.h" +#include "base/memory/ptr_util.h" #include "base/memory/singleton.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" @@ -26,10 +27,10 @@ return std::string(); } -scoped_ptr<KeyedService> BuildManagedBookmarkService( +std::unique_ptr<KeyedService> BuildManagedBookmarkService( content::BrowserContext* context) { Profile* profile = Profile::FromBrowserContext(context); - return make_scoped_ptr(new bookmarks::ManagedBookmarkService( + return base::WrapUnique(new bookmarks::ManagedBookmarkService( profile->GetPrefs(), base::Bind(&GetManagedBookmarksDomain, base::Unretained(profile)))); }
diff --git a/chrome/browser/bookmarks/managed_bookmark_service_factory.h b/chrome/browser/bookmarks/managed_bookmark_service_factory.h index 3ce2f65..208372b6 100644 --- a/chrome/browser/bookmarks/managed_bookmark_service_factory.h +++ b/chrome/browser/bookmarks/managed_bookmark_service_factory.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_BOOKMARKS_MANAGED_BOOKMARK_SERVICE_FACTORY_H_ #define CHROME_BROWSER_BOOKMARKS_MANAGED_BOOKMARK_SERVICE_FACTORY_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" namespace base {
diff --git a/chrome/browser/bookmarks/managed_bookmark_service_unittest.cc b/chrome/browser/bookmarks/managed_bookmark_service_unittest.cc index ab173f5..5d7fd31 100644 --- a/chrome/browser/bookmarks/managed_bookmark_service_unittest.cc +++ b/chrome/browser/bookmarks/managed_bookmark_service_unittest.cc
@@ -4,8 +4,9 @@ #include "components/bookmarks/managed/managed_bookmark_service.h" +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" @@ -158,14 +159,14 @@ EXPECT_FALSE(managed_->managed_node()->empty()); EXPECT_TRUE(managed_->managed_node()->IsVisible()); - scoped_ptr<base::DictionaryValue> expected(CreateExpectedTree()); + std::unique_ptr<base::DictionaryValue> expected(CreateExpectedTree()); EXPECT_TRUE(NodeMatchesValue(managed_->managed_node(), expected.get())); } TEST_F(ManagedBookmarkServiceTest, SwapNodes) { // Swap the Google bookmark with the Folder. - scoped_ptr<base::ListValue> updated(CreateTestTree()); - scoped_ptr<base::Value> removed; + std::unique_ptr<base::ListValue> updated(CreateTestTree()); + std::unique_ptr<base::Value> removed; ASSERT_TRUE(updated->Remove(0, &removed)); updated->Append(removed.release()); @@ -177,14 +178,14 @@ Mock::VerifyAndClearExpectations(&observer_); // Verify the final tree. - scoped_ptr<base::DictionaryValue> expected( + std::unique_ptr<base::DictionaryValue> expected( CreateFolder(GetManagedFolderTitle(), updated.release())); EXPECT_TRUE(NodeMatchesValue(managed_->managed_node(), expected.get())); } TEST_F(ManagedBookmarkServiceTest, RemoveNode) { // Remove the Folder. - scoped_ptr<base::ListValue> updated(CreateTestTree()); + std::unique_ptr<base::ListValue> updated(CreateTestTree()); ASSERT_TRUE(updated->Remove(1, NULL)); const BookmarkNode* parent = managed_->managed_node(); @@ -194,14 +195,14 @@ Mock::VerifyAndClearExpectations(&observer_); // Verify the final tree. - scoped_ptr<base::DictionaryValue> expected( + std::unique_ptr<base::DictionaryValue> expected( CreateFolder(GetManagedFolderTitle(), updated.release())); EXPECT_TRUE(NodeMatchesValue(managed_->managed_node(), expected.get())); } TEST_F(ManagedBookmarkServiceTest, CreateNewNodes) { // Put all the nodes inside another folder. - scoped_ptr<base::ListValue> updated(new base::ListValue); + std::unique_ptr<base::ListValue> updated(new base::ListValue); updated->Append(CreateFolder("Container", CreateTestTree())); EXPECT_CALL(observer_, BookmarkNodeAdded(model_, _, _)).Times(5); @@ -214,7 +215,7 @@ Mock::VerifyAndClearExpectations(&observer_); // Verify the final tree. - scoped_ptr<base::DictionaryValue> expected( + std::unique_ptr<base::DictionaryValue> expected( CreateFolder(GetManagedFolderTitle(), updated.release())); EXPECT_TRUE(NodeMatchesValue(managed_->managed_node(), expected.get())); }
diff --git a/chrome/browser/browser_about_handler_unittest.cc b/chrome/browser/browser_about_handler_unittest.cc index c676c41..5e51f0e 100644 --- a/chrome/browser/browser_about_handler_unittest.cc +++ b/chrome/browser/browser_about_handler_unittest.cc
@@ -2,12 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/browser_about_handler.h" + #include <stddef.h> +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" -#include "chrome/browser/browser_about_handler.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/testing_profile.h" #include "content/public/browser/navigation_controller.h" @@ -94,9 +96,10 @@ GURL rewritten_url("http://foo/"); TestingProfile profile; - scoped_ptr<NavigationEntry> entry(NavigationController::CreateNavigationEntry( - url, Referrer(), ui::PAGE_TRANSITION_RELOAD, false, std::string(), - &profile)); + std::unique_ptr<NavigationEntry> entry( + NavigationController::CreateNavigationEntry( + url, Referrer(), ui::PAGE_TRANSITION_RELOAD, false, std::string(), + &profile)); EXPECT_EQ(fixed_url, entry->GetVirtualURL()); EXPECT_EQ(rewritten_url, entry->GetURL()); }
diff --git a/chrome/browser/browser_process.h b/chrome/browser/browser_process.h index 540ba2a..b380707 100644 --- a/chrome/browser/browser_process.h +++ b/chrome/browser/browser_process.h
@@ -12,10 +12,10 @@ #include <stdint.h> +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "build/build_config.h" #include "chrome/browser/browser_process_platform_part.h" #include "chrome/browser/shell_integration.h" @@ -208,7 +208,7 @@ // Returns the object that manages background applications. virtual BackgroundModeManager* background_mode_manager() = 0; virtual void set_background_mode_manager_for_test( - scoped_ptr<BackgroundModeManager> manager) = 0; + std::unique_ptr<BackgroundModeManager> manager) = 0; // Returns the StatusTray, which provides an API for displaying status icons // in the system status tray. Returns NULL if status icons are not supported
diff --git a/chrome/browser/browser_process_impl.cc b/chrome/browser/browser_process_impl.cc index 5f02ede..0b2d2d4 100644 --- a/chrome/browser/browser_process_impl.cc +++ b/chrome/browser/browser_process_impl.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/browser_process_impl.h" #include <stddef.h> + #include <algorithm> #include <map> #include <utility> @@ -18,6 +19,7 @@ #include "base/debug/leak_annotations.h" #include "base/files/file_path.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram_macros.h" #include "base/path_service.h" @@ -494,7 +496,7 @@ DCHECK(CalledOnValidThread()); if (!metrics_services_manager_) { metrics_services_manager_.reset( - new metrics_services_manager::MetricsServicesManager(make_scoped_ptr( + new metrics_services_manager::MetricsServicesManager(base::WrapUnique( new ChromeMetricsServicesManagerClient(local_state())))); } return metrics_services_manager_.get(); @@ -726,9 +728,8 @@ network_time::NetworkTimeTracker* BrowserProcessImpl::network_time_tracker() { if (!network_time_tracker_) { network_time_tracker_.reset(new network_time::NetworkTimeTracker( - make_scoped_ptr(new base::DefaultClock()), - make_scoped_ptr(new base::DefaultTickClock()), - local_state())); + base::WrapUnique(new base::DefaultClock()), + base::WrapUnique(new base::DefaultTickClock()), local_state())); } return network_time_tracker_.get(); } @@ -819,7 +820,7 @@ } void BrowserProcessImpl::set_background_mode_manager_for_test( - scoped_ptr<BackgroundModeManager> manager) { + std::unique_ptr<BackgroundModeManager> manager) { #if BUILDFLAG(ENABLE_BACKGROUND) background_mode_manager_ = std::move(manager); #endif @@ -936,7 +937,7 @@ DCHECK(!created_watchdog_thread_ && watchdog_thread_.get() == NULL); created_watchdog_thread_ = true; - scoped_ptr<WatchDogThread> thread(new WatchDogThread()); + std::unique_ptr<WatchDogThread> thread(new WatchDogThread()); base::Thread::Options options; options.timer_slack = base::TIMER_SLACK_MAXIMUM; if (!thread->StartWithOptions(options)) @@ -1052,7 +1053,7 @@ void BrowserProcessImpl::CreateIntranetRedirectDetector() { DCHECK(intranet_redirect_detector_.get() == NULL); - scoped_ptr<IntranetRedirectDetector> intranet_redirect_detector( + std::unique_ptr<IntranetRedirectDetector> intranet_redirect_detector( new IntranetRedirectDetector); intranet_redirect_detector_.swap(intranet_redirect_detector); } @@ -1129,11 +1130,8 @@ base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)); gcm_driver_ = gcm::CreateGCMDriverDesktop( - make_scoped_ptr(new gcm::GCMClientFactory), - local_state(), - store_path, - system_request_context(), - chrome::GetChannel(), + base::WrapUnique(new gcm::GCMClientFactory), local_state(), store_path, + system_request_context(), chrome::GetChannel(), content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::UI), content::BrowserThread::GetMessageLoopProxyForThread( @@ -1245,7 +1243,7 @@ void BrowserProcessImpl::RestartBackgroundInstance() { base::CommandLine* old_cl = base::CommandLine::ForCurrentProcess(); - scoped_ptr<base::CommandLine> new_cl( + std::unique_ptr<base::CommandLine> new_cl( new base::CommandLine(old_cl->GetProgram())); std::map<std::string, base::CommandLine::StringType> switches =
diff --git a/chrome/browser/browser_process_impl.h b/chrome/browser/browser_process_impl.h index a237759..e4a287d 100644 --- a/chrome/browser/browser_process_impl.h +++ b/chrome/browser/browser_process_impl.h
@@ -12,12 +12,12 @@ #include <stdint.h> +#include <memory> #include <string> #include "base/debug/stack_trace.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/threading/non_thread_safe.h" #include "base/timer/timer.h" #include "build/build_config.h" @@ -128,7 +128,7 @@ DownloadRequestLimiter* download_request_limiter() override; BackgroundModeManager* background_mode_manager() override; void set_background_mode_manager_for_test( - scoped_ptr<BackgroundModeManager> manager) override; + std::unique_ptr<BackgroundModeManager> manager) override; StatusTray* status_tray() override; safe_browsing::SafeBrowsingService* safe_browsing_service() override; safe_browsing::ClientSideDetectionService* safe_browsing_detection_service() @@ -190,62 +190,64 @@ void Pin(); void Unpin(); - scoped_ptr<metrics_services_manager::MetricsServicesManager> + std::unique_ptr<metrics_services_manager::MetricsServicesManager> metrics_services_manager_; - scoped_ptr<IOThread> io_thread_; + std::unique_ptr<IOThread> io_thread_; bool created_watchdog_thread_; - scoped_ptr<WatchDogThread> watchdog_thread_; + std::unique_ptr<WatchDogThread> watchdog_thread_; bool created_browser_policy_connector_; // Must be destroyed after |local_state_|. - scoped_ptr<policy::BrowserPolicyConnector> browser_policy_connector_; + std::unique_ptr<policy::BrowserPolicyConnector> browser_policy_connector_; bool created_profile_manager_; - scoped_ptr<ProfileManager> profile_manager_; + std::unique_ptr<ProfileManager> profile_manager_; bool created_local_state_; - scoped_ptr<PrefService> local_state_; + std::unique_ptr<PrefService> local_state_; bool created_icon_manager_; - scoped_ptr<IconManager> icon_manager_; + std::unique_ptr<IconManager> icon_manager_; - scoped_ptr<GLStringManager> gl_string_manager_; + std::unique_ptr<GLStringManager> gl_string_manager_; - scoped_ptr<GpuModeManager> gpu_mode_manager_; + std::unique_ptr<GpuModeManager> gpu_mode_manager_; #if defined(ENABLE_EXTENSIONS) - scoped_ptr<extensions::ExtensionsBrowserClient> extensions_browser_client_; + std::unique_ptr<extensions::ExtensionsBrowserClient> + extensions_browser_client_; scoped_refptr<extensions::EventRouterForwarder> extension_event_router_forwarder_; - scoped_ptr<MediaFileSystemRegistry> media_file_system_registry_; + std::unique_ptr<MediaFileSystemRegistry> media_file_system_registry_; #endif #if !defined(OS_ANDROID) - scoped_ptr<RemoteDebuggingServer> remote_debugging_server_; - scoped_ptr<DevToolsAutoOpener> devtools_auto_opener_; + std::unique_ptr<RemoteDebuggingServer> remote_debugging_server_; + std::unique_ptr<DevToolsAutoOpener> devtools_auto_opener_; #endif #if defined(ENABLE_PRINT_PREVIEW) scoped_refptr<printing::PrintPreviewDialogController> print_preview_dialog_controller_; - scoped_ptr<printing::BackgroundPrintingManager> background_printing_manager_; + std::unique_ptr<printing::BackgroundPrintingManager> + background_printing_manager_; #endif // Manager for desktop notification UI. bool created_notification_ui_manager_; - scoped_ptr<NotificationUIManager> notification_ui_manager_; + std::unique_ptr<NotificationUIManager> notification_ui_manager_; - scoped_ptr<IntranetRedirectDetector> intranet_redirect_detector_; + std::unique_ptr<IntranetRedirectDetector> intranet_redirect_detector_; - scoped_ptr<StatusTray> status_tray_; + std::unique_ptr<StatusTray> status_tray_; #if BUILDFLAG(ENABLE_BACKGROUND) - scoped_ptr<BackgroundModeManager> background_mode_manager_; + std::unique_ptr<BackgroundModeManager> background_mode_manager_; #endif bool created_safe_browsing_service_; @@ -256,14 +258,14 @@ bool tearing_down_; // Ensures that all the print jobs are finished before closing the browser. - scoped_ptr<printing::PrintJobManager> print_job_manager_; + std::unique_ptr<printing::PrintJobManager> print_job_manager_; std::string locale_; // Download status updates (like a changing application icon on dock/taskbar) // are global per-application. DownloadStatusUpdater does no work in the ctor // so we don't have to worry about lazy initialization. - scoped_ptr<DownloadStatusUpdater> download_status_updater_; + std::unique_ptr<DownloadStatusUpdater> download_status_updater_; scoped_refptr<DownloadRequestLimiter> download_request_limiter_; @@ -275,12 +277,12 @@ PrefChangeRegistrar pref_change_registrar_; // Lives here so can safely log events on shutdown. - scoped_ptr<net_log::ChromeNetLog> net_log_; + std::unique_ptr<net_log::ChromeNetLog> net_log_; - scoped_ptr<ChromeResourceDispatcherHostDelegate> + std::unique_ptr<ChromeResourceDispatcherHostDelegate> resource_dispatcher_host_delegate_; - scoped_ptr<web_resource::PromoResourceService> promo_resource_service_; + std::unique_ptr<web_resource::PromoResourceService> promo_resource_service_; #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS) base::RepeatingTimer autoupdate_timer_; @@ -295,7 +297,7 @@ // component updater is normally not used under ChromeOS due // to concerns over integrity of data shared between profiles, // but some users of component updater only install per-user. - scoped_ptr<component_updater::ComponentUpdateService> component_updater_; + std::unique_ptr<component_updater::ComponentUpdateService> component_updater_; scoped_refptr<CRLSetFetcher> crl_set_fetcher_; #if !defined(DISABLE_NACL) @@ -303,14 +305,14 @@ pnacl_component_installer_; #endif - scoped_ptr<component_updater::SupervisedUserWhitelistInstaller> + std::unique_ptr<component_updater::SupervisedUserWhitelistInstaller> supervised_user_whitelist_installer_; #if defined(ENABLE_PLUGIN_INSTALLATION) - scoped_ptr<PluginsResourceService> plugins_resource_service_; + std::unique_ptr<PluginsResourceService> plugins_resource_service_; #endif - scoped_ptr<BrowserProcessPlatformPart> platform_part_; + std::unique_ptr<BrowserProcessPlatformPart> platform_part_; // TODO(eroman): Remove this when done debugging 113031. This tracks // the callstack which released the final module reference count. @@ -318,21 +320,21 @@ #if defined(ENABLE_WEBRTC) // Lazily initialized. - scoped_ptr<WebRtcLogUploader> webrtc_log_uploader_; + std::unique_ptr<WebRtcLogUploader> webrtc_log_uploader_; #endif - scoped_ptr<network_time::NetworkTimeTracker> network_time_tracker_; + std::unique_ptr<network_time::NetworkTimeTracker> network_time_tracker_; - scoped_ptr<gcm::GCMDriver> gcm_driver_; + std::unique_ptr<gcm::GCMDriver> gcm_driver_; - scoped_ptr<ChromeChildProcessWatcher> child_process_watcher_; + std::unique_ptr<ChromeChildProcessWatcher> child_process_watcher_; - scoped_ptr<ChromeDeviceClient> device_client_; + std::unique_ptr<ChromeDeviceClient> device_client_; #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS) // Any change to this #ifdef must be reflected as well in // chrome/browser/memory/tab_manager_browsertest.cc - scoped_ptr<memory::TabManager> tab_manager_; + std::unique_ptr<memory::TabManager> tab_manager_; #endif shell_integration::DefaultWebClientState cached_default_web_client_state_;
diff --git a/chrome/browser/browser_process_impl_unittest.cc b/chrome/browser/browser_process_impl_unittest.cc index b86f2e7..7a79ae62 100644 --- a/chrome/browser/browser_process_impl_unittest.cc +++ b/chrome/browser/browser_process_impl_unittest.cc
@@ -4,8 +4,9 @@ #include "chrome/browser/browser_process_impl.h" +#include <memory> + #include "base/command_line.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/thread_task_runner_handle.h" @@ -67,10 +68,10 @@ BrowserProcess* stashed_browser_process_; base::MessageLoop loop_; content::TestBrowserThread ui_thread_; - scoped_ptr<content::TestBrowserThread> file_thread_; - scoped_ptr<content::TestBrowserThread> io_thread_; + std::unique_ptr<content::TestBrowserThread> file_thread_; + std::unique_ptr<content::TestBrowserThread> io_thread_; base::CommandLine command_line_; - scoped_ptr<BrowserProcessImpl> browser_process_impl_; + std::unique_ptr<BrowserProcessImpl> browser_process_impl_; }; @@ -85,7 +86,7 @@ browser_process_impl()->PreMainMessageLoopRun(); // Force the creation of the NTPResourceCache, to test the destruction order. - scoped_ptr<Profile> profile(new TestingProfile); + std::unique_ptr<Profile> profile(new TestingProfile); NTPResourceCache* cache = NTPResourceCacheFactory::GetForProfile(profile.get()); ASSERT_TRUE(cache);
diff --git a/chrome/browser/browser_process_platform_part_base.cc b/chrome/browser/browser_process_platform_part_base.cc index fd7bee8..e2acee9 100644 --- a/chrome/browser/browser_process_platform_part_base.cc +++ b/chrome/browser/browser_process_platform_part_base.cc
@@ -36,8 +36,8 @@ void BrowserProcessPlatformPartBase::PreMainMessageLoopRun() { } -scoped_ptr<policy::BrowserPolicyConnector> +std::unique_ptr<policy::BrowserPolicyConnector> BrowserProcessPlatformPartBase::CreateBrowserPolicyConnector() { - return scoped_ptr<policy::BrowserPolicyConnector>( + return std::unique_ptr<policy::BrowserPolicyConnector>( new policy::ChromeBrowserPolicyConnector()); }
diff --git a/chrome/browser/browser_process_platform_part_base.h b/chrome/browser/browser_process_platform_part_base.h index d662dbd..af9d60c 100644 --- a/chrome/browser/browser_process_platform_part_base.h +++ b/chrome/browser/browser_process_platform_part_base.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_BROWSER_PROCESS_PLATFORM_PART_BASE_H_ #define CHROME_BROWSER_BROWSER_PROCESS_PLATFORM_PART_BASE_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" namespace base { class CommandLine; @@ -37,8 +38,8 @@ // Called at the end of BrowserProcessImpl::PreMainMessageLoopRun(). virtual void PreMainMessageLoopRun(); - virtual scoped_ptr<policy::BrowserPolicyConnector> - CreateBrowserPolicyConnector(); + virtual std::unique_ptr<policy::BrowserPolicyConnector> + CreateBrowserPolicyConnector(); private: DISALLOW_COPY_AND_ASSIGN(BrowserProcessPlatformPartBase);
diff --git a/chrome/browser/browser_process_platform_part_chromeos.cc b/chrome/browser/browser_process_platform_part_chromeos.cc index b5debb4..0378fdd 100644 --- a/chrome/browser/browser_process_platform_part_chromeos.cc +++ b/chrome/browser/browser_process_platform_part_chromeos.cc
@@ -41,7 +41,7 @@ DCHECK(!automatic_reboot_manager_); automatic_reboot_manager_.reset(new chromeos::system::AutomaticRebootManager( - scoped_ptr<base::TickClock>(new base::DefaultTickClock))); + std::unique_ptr<base::TickClock>(new base::DefaultTickClock))); } void BrowserProcessPlatformPart::ShutdownAutomaticRebootManager() { @@ -155,9 +155,9 @@ profile_helper_.reset(); } -scoped_ptr<policy::BrowserPolicyConnector> +std::unique_ptr<policy::BrowserPolicyConnector> BrowserProcessPlatformPart::CreateBrowserPolicyConnector() { - return scoped_ptr<policy::BrowserPolicyConnector>( + return std::unique_ptr<policy::BrowserPolicyConnector>( new policy::BrowserPolicyConnectorChromeOS()); }
diff --git a/chrome/browser/browser_process_platform_part_chromeos.h b/chrome/browser/browser_process_platform_part_chromeos.h index e90c9e50..48612f92 100644 --- a/chrome/browser/browser_process_platform_part_chromeos.h +++ b/chrome/browser/browser_process_platform_part_chromeos.h
@@ -5,9 +5,10 @@ #ifndef CHROME_BROWSER_BROWSER_PROCESS_PLATFORM_PART_CHROMEOS_H_ #define CHROME_BROWSER_BROWSER_PROCESS_PLATFORM_PART_CHROMEOS_H_ +#include <memory> + #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/threading/non_thread_safe.h" #include "chrome/browser/browser_process_platform_part_base.h" @@ -102,7 +103,7 @@ // Overridden from BrowserProcessPlatformPartBase: void StartTearDown() override; - scoped_ptr<policy::BrowserPolicyConnector> CreateBrowserPolicyConnector() + std::unique_ptr<policy::BrowserPolicyConnector> CreateBrowserPolicyConnector() override; chromeos::system::SystemClock* GetSystemClock(); @@ -110,28 +111,28 @@ private: void CreateProfileHelper(); - scoped_ptr<session_manager::SessionManager> session_manager_; + std::unique_ptr<session_manager::SessionManager> session_manager_; bool created_profile_helper_; - scoped_ptr<chromeos::ProfileHelper> profile_helper_; + std::unique_ptr<chromeos::ProfileHelper> profile_helper_; - scoped_ptr<chromeos::system::AutomaticRebootManager> + std::unique_ptr<chromeos::system::AutomaticRebootManager> automatic_reboot_manager_; - scoped_ptr<chromeos::ChromeUserManager> chrome_user_manager_; + std::unique_ptr<chromeos::ChromeUserManager> chrome_user_manager_; - scoped_ptr<chromeos::system::DeviceDisablingManagerDefaultDelegate> + std::unique_ptr<chromeos::system::DeviceDisablingManagerDefaultDelegate> device_disabling_manager_delegate_; - scoped_ptr<chromeos::system::DeviceDisablingManager> + std::unique_ptr<chromeos::system::DeviceDisablingManager> device_disabling_manager_; - scoped_ptr<chromeos::system::TimeZoneResolverManager> + std::unique_ptr<chromeos::system::TimeZoneResolverManager> timezone_resolver_manager_; - scoped_ptr<chromeos::TimeZoneResolver> timezone_resolver_; + std::unique_ptr<chromeos::TimeZoneResolver> timezone_resolver_; - scoped_ptr<chromeos::system::SystemClock> system_clock_; + std::unique_ptr<chromeos::system::SystemClock> system_clock_; - scoped_ptr<ScopedKeepAlive> keep_alive_; + std::unique_ptr<ScopedKeepAlive> keep_alive_; DISALLOW_COPY_AND_ASSIGN(BrowserProcessPlatformPart); };
diff --git a/chrome/browser/browser_process_platform_part_mac.h b/chrome/browser/browser_process_platform_part_mac.h index d60a44b..38a3693a 100644 --- a/chrome/browser/browser_process_platform_part_mac.h +++ b/chrome/browser/browser_process_platform_part_mac.h
@@ -5,9 +5,10 @@ #ifndef CHROME_BROWSER_BROWSER_PROCESS_PLATFORM_PART_MAC_H_ #define CHROME_BROWSER_BROWSER_PROCESS_PLATFORM_PART_MAC_H_ +#include <memory> + #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/apps/app_shim/app_shim_host_manager_mac.h" #include "chrome/browser/browser_process_platform_part_base.h"
diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index 8cfe0fd7..232b255 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd
@@ -172,6 +172,11 @@ <include name="IDR_POPULAR_SITES_INTERNALS_CSS" file="resources\popular_sites_internals.css" type="BINDATA" /> <include name="IDR_POPULAR_SITES_INTERNALS_JS" file="resources\popular_sites_internals.js" type="BINDATA" /> </if> + <if expr="is_android"> + <include name="IDR_SNIPPETS_INTERNALS_HTML" file="resources\snippets_internals.html" allowexternalscript="true" type="BINDATA" /> + <include name="IDR_SNIPPETS_INTERNALS_CSS" file="resources\snippets_internals.css" type="BINDATA" /> + <include name="IDR_SNIPPETS_INTERNALS_JS" file="resources\snippets_internals.js" type="BINDATA" /> + </if> <include name="IDR_SUPERVISED_USER_INTERNALS_HTML" file="resources\supervised_user_internals.html" allowexternalscript="true" type="BINDATA" /> <include name="IDR_SUPERVISED_USER_INTERNALS_CSS" file="resources\supervised_user_internals.css" type="BINDATA" /> <include name="IDR_SUPERVISED_USER_INTERNALS_JS" file="resources\supervised_user_internals.js" type="BINDATA" />
diff --git a/chrome/browser/browser_shutdown.cc b/chrome/browser/browser_shutdown.cc index fc6d8218..b81446a 100644 --- a/chrome/browser/browser_shutdown.cc +++ b/chrome/browser/browser_shutdown.cc
@@ -224,7 +224,7 @@ // 46182). We therefore use GetSwitches to copy the command line (it stops // at the switch argument terminator). base::CommandLine old_cl(*base::CommandLine::ForCurrentProcess()); - scoped_ptr<base::CommandLine> new_cl( + std::unique_ptr<base::CommandLine> new_cl( new base::CommandLine(old_cl.GetProgram())); std::map<std::string, base::CommandLine::StringType> switches = old_cl.GetSwitches();
diff --git a/chrome/browser/browsing_data/OWNERS b/chrome/browser/browsing_data/OWNERS index 0944d92..8d54d3ca 100644 --- a/chrome/browser/browsing_data/OWNERS +++ b/chrome/browser/browsing_data/OWNERS
@@ -1,4 +1,5 @@ -markusheintz@chromium.org -mkwst@chromium.org bauerb@chromium.org +markusheintz@chromium.org michaeln@chromium.org +mkwst@chromium.org +msramek@chromium.org
diff --git a/chrome/browser/browsing_data/autofill_counter.cc b/chrome/browser/browsing_data/autofill_counter.cc index 7c2712e6..db83e1a 100644 --- a/chrome/browser/browsing_data/autofill_counter.cc +++ b/chrome/browser/browsing_data/autofill_counter.cc
@@ -143,8 +143,8 @@ if (HasPendingQuery()) return; - scoped_ptr<Result> reported_result(new AutofillResult( - this, num_suggestions_, num_credit_cards_, num_addresses_)); + std::unique_ptr<Result> reported_result(new AutofillResult( + this, num_suggestions_, num_credit_cards_, num_addresses_)); ReportResult(std::move(reported_result)); }
diff --git a/chrome/browser/browsing_data/autofill_counter_browsertest.cc b/chrome/browser/browsing_data/autofill_counter_browsertest.cc index c5735ab..3a03de82 100644 --- a/chrome/browser/browsing_data/autofill_counter_browsertest.cc +++ b/chrome/browser/browsing_data/autofill_counter_browsertest.cc
@@ -161,7 +161,7 @@ return num_addresses_; } - void Callback(scoped_ptr<BrowsingDataCounter::Result> result) { + void Callback(std::unique_ptr<BrowsingDataCounter::Result> result) { finished_ = result->Finished(); if (finished_) { @@ -178,7 +178,7 @@ } private: - scoped_ptr<base::RunLoop> run_loop_; + std::unique_ptr<base::RunLoop> run_loop_; std::vector<std::string> credit_card_ids_; std::vector<std::string> address_ids_;
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 73eccc1..d3f1f7bf 100644 --- a/chrome/browser/browsing_data/browsing_data_channel_id_helper.cc +++ b/chrome/browser/browsing_data/browsing_data_channel_id_helper.cc
@@ -4,11 +4,12 @@ #include "chrome/browser/browsing_data/browsing_data_channel_id_helper.h" +#include <memory> + #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/single_thread_task_runner.h" #include "base/thread_task_runner_handle.h" #include "content/public/browser/browser_thread.h"
diff --git a/chrome/browser/browsing_data/browsing_data_channel_id_helper_unittest.cc b/chrome/browser/browsing_data/browsing_data_channel_id_helper_unittest.cc index 74bff944..e5ef6c6 100644 --- a/chrome/browser/browsing_data/browsing_data_channel_id_helper_unittest.cc +++ b/chrome/browser/browsing_data/browsing_data_channel_id_helper_unittest.cc
@@ -4,8 +4,10 @@ #include "chrome/browser/browsing_data/browsing_data_channel_id_helper.h" +#include <memory> + #include "base/bind.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "chrome/test/base/testing_profile.h" #include "content/public/browser/browser_thread.h" @@ -40,13 +42,13 @@ net::ChannelIDStore* channel_id_store = context->channel_id_service()->GetChannelIDStore(); channel_id_store->SetChannelID( - make_scoped_ptr(new net::ChannelIDStore::ChannelID( + base::WrapUnique(new net::ChannelIDStore::ChannelID( "https://www.google.com:443", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create())))); + base::WrapUnique(crypto::ECPrivateKey::Create())))); channel_id_store->SetChannelID( - make_scoped_ptr(new net::ChannelIDStore::ChannelID( + base::WrapUnique(new net::ChannelIDStore::ChannelID( "https://www.youtube.com:443", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create())))); + base::WrapUnique(crypto::ECPrivateKey::Create())))); } void FetchCallback( @@ -60,7 +62,7 @@ protected: content::TestBrowserThreadBundle thread_bundle_; - scoped_ptr<TestingProfile> testing_profile_; + std::unique_ptr<TestingProfile> testing_profile_; net::ChannelIDStore::ChannelIDList channel_id_list_; @@ -140,7 +142,7 @@ ASSERT_TRUE(helper->empty()); helper->AddChannelID(net::ChannelIDStore::ChannelID( - origin, base::Time(), make_scoped_ptr(crypto::ECPrivateKey::Create()))); + origin, base::Time(), base::WrapUnique(crypto::ECPrivateKey::Create()))); ASSERT_FALSE(helper->empty()); helper->Reset(); ASSERT_TRUE(helper->empty());
diff --git a/chrome/browser/browsing_data/browsing_data_cookie_helper.cc b/chrome/browser/browsing_data/browsing_data_cookie_helper.cc index cac6e2d68..fe405c4e 100644 --- a/chrome/browser/browsing_data/browsing_data_cookie_helper.cc +++ b/chrome/browser/browsing_data/browsing_data_cookie_helper.cc
@@ -4,12 +4,12 @@ #include "chrome/browser/browsing_data/browsing_data_cookie_helper.h" +#include <memory> #include <utility> #include "base/bind.h" #include "base/location.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/stl_util.h" #include "chrome/browser/profiles/profile.h" #include "content/public/browser/browser_thread.h" @@ -102,7 +102,7 @@ const GURL& url, const std::string& cookie_line, const net::CookieOptions& options) { - scoped_ptr<net::CanonicalCookie> cookie(net::CanonicalCookie::Create( + std::unique_ptr<net::CanonicalCookie> cookie(net::CanonicalCookie::Create( url, cookie_line, base::Time::Now(), options)); if (cookie.get()) AddCookie(frame_url, *cookie);
diff --git a/chrome/browser/browsing_data/browsing_data_cookie_helper_unittest.cc b/chrome/browser/browsing_data/browsing_data_cookie_helper_unittest.cc index 7ea83353..0220cd5 100644 --- a/chrome/browser/browsing_data/browsing_data_cookie_helper_unittest.cc +++ b/chrome/browser/browsing_data/browsing_data_cookie_helper_unittest.cc
@@ -198,7 +198,7 @@ protected: content::TestBrowserThreadBundle thread_bundle_; - scoped_ptr<TestingProfile> testing_profile_; + std::unique_ptr<TestingProfile> testing_profile_; std::vector<CookieExpectation> cookie_expectations_; net::CookieList cookie_list_; @@ -396,7 +396,7 @@ ASSERT_TRUE(helper->empty()); net::CookieList cookies; - scoped_ptr<net::CanonicalCookie> cookie(net::CanonicalCookie::Create( + std::unique_ptr<net::CanonicalCookie> cookie(net::CanonicalCookie::Create( url_google, "a=1", base::Time::Now(), net::CookieOptions())); cookies.push_back(*cookie);
diff --git a/chrome/browser/browsing_data/browsing_data_counter.cc b/chrome/browser/browsing_data/browsing_data_counter.cc index f469e66..04c7772 100644 --- a/chrome/browser/browsing_data/browsing_data_counter.cc +++ b/chrome/browser/browsing_data/browsing_data_counter.cc
@@ -6,6 +6,7 @@ #include <utility> +#include "base/memory/ptr_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" @@ -55,17 +56,17 @@ if (!profile_->GetPrefs()->GetBoolean(GetPrefName())) return; - callback_.Run(make_scoped_ptr(new Result(this))); + callback_.Run(base::WrapUnique(new Result(this))); Count(); } void BrowsingDataCounter::ReportResult(ResultInt value) { DCHECK(initialized_); - callback_.Run(make_scoped_ptr(new FinishedResult(this, value))); + callback_.Run(base::WrapUnique(new FinishedResult(this, value))); } -void BrowsingDataCounter::ReportResult(scoped_ptr<Result> result) { +void BrowsingDataCounter::ReportResult(std::unique_ptr<Result> result) { DCHECK(initialized_); callback_.Run(std::move(result)); }
diff --git a/chrome/browser/browsing_data/browsing_data_counter.h b/chrome/browser/browsing_data/browsing_data_counter.h index 7d5cb00..3bd1e4b9 100644 --- a/chrome/browser/browsing_data/browsing_data_counter.h +++ b/chrome/browser/browsing_data/browsing_data_counter.h
@@ -54,7 +54,7 @@ DISALLOW_COPY_AND_ASSIGN(FinishedResult); }; - typedef base::Callback<void(scoped_ptr<Result>)> Callback; + typedef base::Callback<void(std::unique_ptr<Result>)> Callback; BrowsingDataCounter(); virtual ~BrowsingDataCounter(); @@ -81,7 +81,7 @@ // A convenience overload of the previous method that allows subclasses to // provide a custom |result|. - void ReportResult(scoped_ptr<Result> result); + void ReportResult(std::unique_ptr<Result> result); // Calculates the beginning of the counting period as |period_| before now. base::Time GetPeriodStart();
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 302dffe3..85487b6 100644 --- a/chrome/browser/browsing_data/browsing_data_file_system_helper.cc +++ b/chrome/browser/browsing_data/browsing_data_file_system_helper.cc
@@ -4,12 +4,12 @@ #include "chrome/browser/browsing_data/browsing_data_file_system_helper.h" +#include <memory> #include <set> #include "base/bind.h" #include "base/location.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/sequenced_task_runner.h" #include "chrome/browser/browsing_data/browsing_data_helper.h" #include "content/public/browser/browser_thread.h"
diff --git a/chrome/browser/browsing_data/browsing_data_file_system_helper_unittest.cc b/chrome/browser/browsing_data/browsing_data_file_system_helper_unittest.cc index ceb8dd2..1573faa 100644 --- a/chrome/browser/browsing_data/browsing_data_file_system_helper_unittest.cc +++ b/chrome/browser/browsing_data/browsing_data_file_system_helper_unittest.cc
@@ -53,7 +53,7 @@ typedef std::list<BrowsingDataFileSystemHelper::FileSystemInfo> FileSystemInfoList; -typedef scoped_ptr<FileSystemInfoList> ScopedFileSystemInfoList; +typedef std::unique_ptr<FileSystemInfoList> ScopedFileSystemInfoList; // The FileSystem APIs are all asynchronous; this testing class wraps up the // boilerplate code necessary to deal with waiting for responses. In a nutshell, @@ -187,7 +187,7 @@ protected: content::TestBrowserThreadBundle thread_bundle_; - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<TestingProfile> profile_; // Temporary storage to pass information back from callbacks. base::File::Error open_file_system_result_;
diff --git a/chrome/browser/browsing_data/browsing_data_remover.cc b/chrome/browser/browsing_data/browsing_data_remover.cc index dd96d388..05e0c2e 100644 --- a/chrome/browser/browsing_data/browsing_data_remover.cc +++ b/chrome/browser/browsing_data/browsing_data_remover.cc
@@ -1034,7 +1034,7 @@ #if BUILDFLAG(ANDROID_JAVA_UI) void BrowsingDataRemover::OverrideWebappRegistryForTesting( - scoped_ptr<WebappRegistry> webapp_registry) { + std::unique_ptr<WebappRegistry> webapp_registry) { webapp_registry_.reset(webapp_registry.release()); } #endif
diff --git a/chrome/browser/browsing_data/browsing_data_remover.h b/chrome/browser/browsing_data/browsing_data_remover.h index 441cf1e..19c8921b 100644 --- a/chrome/browser/browsing_data/browsing_data_remover.h +++ b/chrome/browser/browsing_data/browsing_data_remover.h
@@ -204,7 +204,7 @@ }; using Callback = base::Callback<void(const NotificationDetails&)>; - using CallbackSubscription = scoped_ptr< + using CallbackSubscription = std::unique_ptr< base::CallbackList<void(const NotificationDetails&)>::Subscription>; // The completion inhibitor can artificially delay completion of the browsing @@ -276,7 +276,7 @@ #if BUILDFLAG(ANDROID_JAVA_UI) void OverrideWebappRegistryForTesting( - scoped_ptr<WebappRegistry> webapp_registry); + std::unique_ptr<WebappRegistry> webapp_registry); #endif private: @@ -456,11 +456,11 @@ #if defined(ENABLE_PLUGINS) // Used to delete plugin data. - scoped_ptr<content::PluginDataRemover> plugin_data_remover_; + std::unique_ptr<content::PluginDataRemover> plugin_data_remover_; base::WaitableEventWatcher watcher_; // Used to deauthorize content licenses for Pepper Flash. - scoped_ptr<PepperFlashSettingsManager> pepper_flash_settings_manager_; + std::unique_ptr<PepperFlashSettingsManager> pepper_flash_settings_manager_; #endif uint32_t deauthorize_content_licenses_request_id_ = 0; @@ -508,7 +508,7 @@ // Used if we need to clear history. base::CancelableTaskTracker history_task_tracker_; - scoped_ptr<TemplateURLService::Subscription> template_url_sub_; + std::unique_ptr<TemplateURLService::Subscription> template_url_sub_; // We do not own this. content::StoragePartition* storage_partition_for_testing_ = nullptr; @@ -516,7 +516,7 @@ #if BUILDFLAG(ANDROID_JAVA_UI) // WebappRegistry makes calls across the JNI. In unit tests, the Java side is // not initialised, so the registry must be mocked out. - scoped_ptr<WebappRegistry> webapp_registry_; + std::unique_ptr<WebappRegistry> webapp_registry_; #endif base::WeakPtrFactory<BrowsingDataRemover> weak_ptr_factory_;
diff --git a/chrome/browser/browsing_data/browsing_data_remover_browsertest.cc b/chrome/browser/browsing_data/browsing_data_remover_browsertest.cc index eb2ddbf..840d1e2 100644 --- a/chrome/browser/browsing_data/browsing_data_remover_browsertest.cc +++ b/chrome/browser/browsing_data/browsing_data_remover_browsertest.cc
@@ -73,7 +73,7 @@ // Start a download. content::DownloadManager* download_manager = content::BrowserContext::GetDownloadManager(browser()->profile()); - scoped_ptr<content::DownloadTestObserver> observer( + std::unique_ptr<content::DownloadTestObserver> observer( new content::DownloadTestObserverTerminal( download_manager, 1, content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
diff --git a/chrome/browser/browsing_data/browsing_data_remover_unittest.cc b/chrome/browser/browsing_data/browsing_data_remover_unittest.cc index 538eec2..62fc5f4d 100644 --- a/chrome/browser/browsing_data/browsing_data_remover_unittest.cc +++ b/chrome/browser/browsing_data/browsing_data_remover_unittest.cc
@@ -7,6 +7,7 @@ #include <stddef.h> #include <stdint.h> +#include <memory> #include <set> #include <string> #include <vector> @@ -17,7 +18,7 @@ #include "base/files/file_util.h" #include "base/guid.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" @@ -493,9 +494,9 @@ void AddChannelIDWithTimes(const std::string& server_identifier, base::Time creation_time) { GetChannelIDStore()->SetChannelID( - make_scoped_ptr(new net::ChannelIDStore::ChannelID( + base::WrapUnique(new net::ChannelIDStore::ChannelID( server_identifier, creation_time, - make_scoped_ptr(crypto::ECPrivateKey::Create())))); + base::WrapUnique(crypto::ECPrivateKey::Create())))); } // Add a server bound cert for |server|, with the current time as the @@ -838,11 +839,11 @@ ~MockDomainReliabilityService() override {} - scoped_ptr<DomainReliabilityMonitor> CreateMonitor( + std::unique_ptr<DomainReliabilityMonitor> CreateMonitor( scoped_refptr<base::SingleThreadTaskRunner> network_task_runner) override { NOTREACHED(); - return scoped_ptr<DomainReliabilityMonitor>(); + return std::unique_ptr<DomainReliabilityMonitor>(); } void ClearBrowsingData(DomainReliabilityClearMode clear_mode, @@ -852,7 +853,7 @@ callback.Run(); } - void GetWebUIData(const base::Callback<void(scoped_ptr<base::Value>)>& + void GetWebUIData(const base::Callback<void(std::unique_ptr<base::Value>)>& callback) const override { NOTREACHED(); } @@ -889,7 +890,7 @@ const void* TestingDomainReliabilityServiceFactoryUserData::kKey = &TestingDomainReliabilityServiceFactoryUserData::kKey; -scoped_ptr<KeyedService> TestingDomainReliabilityServiceFactoryFunction( +std::unique_ptr<KeyedService> TestingDomainReliabilityServiceFactoryFunction( content::BrowserContext* context) { const void* kKey = TestingDomainReliabilityServiceFactoryUserData::kKey; @@ -901,7 +902,7 @@ EXPECT_FALSE(data->attached); data->attached = true; - return make_scoped_ptr(data->service); + return base::WrapUnique(data->service); } class ClearDomainReliabilityTester { @@ -1009,7 +1010,7 @@ BrowsingDataRemover* remover = BrowsingDataRemoverFactory::GetForBrowserContext(profile_.get()); remover->OverrideWebappRegistryForTesting( - scoped_ptr<WebappRegistry>(new TestWebappRegistry())); + std::unique_ptr<WebappRegistry>(new TestWebappRegistry())); #endif } @@ -1143,11 +1144,12 @@ } protected: - scoped_ptr<BrowsingDataRemover::NotificationDetails> called_with_details_; + std::unique_ptr<BrowsingDataRemover::NotificationDetails> + called_with_details_; private: content::TestBrowserThreadBundle thread_bundle_; - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<TestingProfile> profile_; StoragePartitionRemovalData storage_partition_removal_data_; @@ -2219,12 +2221,12 @@ AccountId::FromUserEmail("test@example.com")); chromeos::ScopedUserManagerEnabler user_manager_enabler(mock_user_manager); - scoped_ptr<chromeos::DBusThreadManagerSetter> dbus_setter = + std::unique_ptr<chromeos::DBusThreadManagerSetter> dbus_setter = chromeos::DBusThreadManager::GetSetterForTesting(); chromeos::MockCryptohomeClient* cryptohome_client = new chromeos::MockCryptohomeClient; dbus_setter->SetCryptohomeClient( - scoped_ptr<chromeos::CryptohomeClient>(cryptohome_client)); + std::unique_ptr<chromeos::CryptohomeClient>(cryptohome_client)); // Expect exactly one call. No calls means no attempt to delete keys and more // than one call means a significant performance problem. @@ -2461,7 +2463,7 @@ host_content_settings_map->SetWebsiteSettingCustomScope( pattern2, ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_APP_BANNER, std::string(), - make_scoped_ptr(new base::DictionaryValue())); + base::WrapUnique(new base::DictionaryValue())); // First, test that we clear only IMAGES (not APP_BANNER), and pattern2. BrowsingDataRemover::ClearSettingsForOneTypeWithPredicate(
diff --git a/chrome/browser/browsing_data/cache_counter_browsertest.cc b/chrome/browser/browsing_data/cache_counter_browsertest.cc index 0d4d6a9..1b1b6795 100644 --- a/chrome/browser/browsing_data/cache_counter_browsertest.cc +++ b/chrome/browser/browsing_data/cache_counter_browsertest.cc
@@ -129,7 +129,7 @@ } // Callback from the counter. - void CountingCallback(scoped_ptr<BrowsingDataCounter::Result> result) { + void CountingCallback(std::unique_ptr<BrowsingDataCounter::Result> result) { DCHECK_CURRENTLY_ON(BrowserThread::UI); finished_ = result->Finished(); @@ -159,7 +159,7 @@ disk_cache::Backend* backend_; disk_cache::Entry* entry_; - scoped_ptr<base::RunLoop> run_loop_; + std::unique_ptr<base::RunLoop> run_loop_; bool finished_; BrowsingDataCounter::ResultInt result_;
diff --git a/chrome/browser/browsing_data/cookies_tree_model.cc b/chrome/browser/browsing_data/cookies_tree_model.cc index cd94f346..959624e 100644 --- a/chrome/browser/browsing_data/cookies_tree_model.cc +++ b/chrome/browser/browsing_data/cookies_tree_model.cc
@@ -599,8 +599,7 @@ CookieTreeRootNode::~CookieTreeRootNode() {} CookieTreeHostNode* CookieTreeRootNode::GetOrCreateHostNode(const GURL& url) { - scoped_ptr<CookieTreeHostNode> host_node( - new CookieTreeHostNode(url)); + std::unique_ptr<CookieTreeHostNode> host_node(new CookieTreeHostNode(url)); // First see if there is an existing match. std::vector<CookieTreeNode*>::iterator host_node_iterator =
diff --git a/chrome/browser/browsing_data/cookies_tree_model.h b/chrome/browser/browsing_data/cookies_tree_model.h index f543767..e54d927 100644 --- a/chrome/browser/browsing_data/cookies_tree_model.h +++ b/chrome/browser/browsing_data/cookies_tree_model.h
@@ -14,6 +14,7 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/strings/string16.h" @@ -850,7 +851,7 @@ // Map of app ids to LocalDataContainer objects to use when retrieving // locally stored data. - scoped_ptr<LocalDataContainer> data_container_; + std::unique_ptr<LocalDataContainer> data_container_; #if defined(ENABLE_EXTENSIONS) // The extension special storage policy; see ExtensionsProtectingNode() above.
diff --git a/chrome/browser/browsing_data/cookies_tree_model_unittest.cc b/chrome/browser/browsing_data/cookies_tree_model_unittest.cc index e78380805..3141e25 100644 --- a/chrome/browser/browsing_data/cookies_tree_model_unittest.cc +++ b/chrome/browser/browsing_data/cookies_tree_model_unittest.cc
@@ -6,6 +6,7 @@ #include <string> +#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/browsing_data/mock_browsing_data_appcache_helper.h" @@ -108,7 +109,7 @@ base::MessageLoop::current()->RunUntilIdle(); } - scoped_ptr<CookiesTreeModel> CreateCookiesTreeModelWithInitialSample() { + std::unique_ptr<CookiesTreeModel> CreateCookiesTreeModelWithInitialSample() { LocalDataContainer* container = new LocalDataContainer(mock_browsing_data_cookie_helper_.get(), mock_browsing_data_database_helper_.get(), @@ -208,7 +209,7 @@ EXPECT_EQ("xyz.com", GetDisplayedFlashLSOs(cookies_model)); } - return make_scoped_ptr(cookies_model); + return base::WrapUnique(cookies_model); } // Checks that, when setting content settings for host nodes in the @@ -434,7 +435,7 @@ } content::TestBrowserThreadBundle thread_bundle_; - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<TestingProfile> profile_; scoped_refptr<MockBrowsingDataCookieHelper> mock_browsing_data_cookie_helper_; scoped_refptr<MockBrowsingDataDatabaseHelper> @@ -466,7 +467,7 @@ }; TEST_F(CookiesTreeModelTest, RemoveAll) { - scoped_ptr<CookiesTreeModel> cookies_model( + std::unique_ptr<CookiesTreeModel> cookies_model( CreateCookiesTreeModelWithInitialSample()); // Reset the selection of the first row. @@ -531,7 +532,7 @@ } TEST_F(CookiesTreeModelTest, Remove) { - scoped_ptr<CookiesTreeModel> cookies_model( + std::unique_ptr<CookiesTreeModel> cookies_model( CreateCookiesTreeModelWithInitialSample()); // Children start out arranged as follows: @@ -940,7 +941,7 @@ } TEST_F(CookiesTreeModelTest, RemoveCookiesNode) { - scoped_ptr<CookiesTreeModel> cookies_model( + std::unique_ptr<CookiesTreeModel> cookies_model( CreateCookiesTreeModelWithInitialSample()); DeleteStoredObjects(cookies_model->GetRoot()->GetChild(2)->GetChild(0)); @@ -1013,7 +1014,7 @@ } TEST_F(CookiesTreeModelTest, RemoveCookieNode) { - scoped_ptr<CookiesTreeModel> cookies_model( + std::unique_ptr<CookiesTreeModel> cookies_model( CreateCookiesTreeModelWithInitialSample()); DeleteStoredObjects(cookies_model->GetRoot()->GetChild(3)->GetChild(0)); @@ -1440,7 +1441,7 @@ } TEST_F(CookiesTreeModelTest, FileSystemFilter) { - scoped_ptr<CookiesTreeModel> cookies_model( + std::unique_ptr<CookiesTreeModel> cookies_model( CreateCookiesTreeModelWithInitialSample()); cookies_model->UpdateSearchResults(base::ASCIIToUTF16("fshost1")); @@ -1461,7 +1462,7 @@ } TEST_F(CookiesTreeModelTest, ServiceWorkerFilter) { - scoped_ptr<CookiesTreeModel> cookies_model( + std::unique_ptr<CookiesTreeModel> cookies_model( CreateCookiesTreeModelWithInitialSample()); cookies_model->UpdateSearchResults(base::ASCIIToUTF16("swhost1")); @@ -1481,7 +1482,7 @@ } TEST_F(CookiesTreeModelTest, CacheStorageFilter) { - scoped_ptr<CookiesTreeModel> cookies_model( + std::unique_ptr<CookiesTreeModel> cookies_model( CreateCookiesTreeModelWithInitialSample()); cookies_model->UpdateSearchResults(base::ASCIIToUTF16("cshost1"));
diff --git a/chrome/browser/browsing_data/history_counter.cc b/chrome/browser/browsing_data/history_counter.cc index 00f8b51..edb0372 100644 --- a/chrome/browser/browsing_data/history_counter.cc +++ b/chrome/browser/browsing_data/history_counter.cc
@@ -2,11 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/browsing_data/history_counter.h" + #include <limits.h> #include <stdint.h> +#include "base/memory/ptr_util.h" #include "base/timer/timer.h" -#include "chrome/browser/browsing_data/history_counter.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/history/web_history_service_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" @@ -165,8 +167,8 @@ if (!local_counting_finished_ || !web_counting_finished_) return; - ReportResult(make_scoped_ptr(new HistoryResult( - this, local_result_, has_synced_visits_))); + ReportResult(base::WrapUnique( + new HistoryResult(this, local_result_, has_synced_visits_))); } HistoryCounter::HistoryResult::HistoryResult(
diff --git a/chrome/browser/browsing_data/history_counter.h b/chrome/browser/browsing_data/history_counter.h index 3c02096..1fb8c589 100644 --- a/chrome/browser/browsing_data/history_counter.h +++ b/chrome/browser/browsing_data/history_counter.h
@@ -56,7 +56,7 @@ history::WebHistoryService* testing_web_history_service_; base::CancelableTaskTracker cancelable_task_tracker_; - scoped_ptr<history::WebHistoryService::Request> web_history_request_; + std::unique_ptr<history::WebHistoryService::Request> web_history_request_; base::OneShotTimer web_history_timeout_; base::ThreadChecker thread_checker_;
diff --git a/chrome/browser/browsing_data/history_counter_browsertest.cc b/chrome/browser/browsing_data/history_counter_browsertest.cc index ca55482..8bf2fc04 100644 --- a/chrome/browser/browsing_data/history_counter_browsertest.cc +++ b/chrome/browser/browsing_data/history_counter_browsertest.cc
@@ -80,7 +80,7 @@ return has_synced_visits_; } - void Callback(scoped_ptr<BrowsingDataCounter::Result> result) { + void Callback(std::unique_ptr<BrowsingDataCounter::Result> result) { finished_ = result->Finished(); if (finished_) { @@ -110,7 +110,7 @@ } private: - scoped_ptr<base::RunLoop> run_loop_; + std::unique_ptr<base::RunLoop> run_loop_; history::HistoryService* service_; base::Time time_; @@ -239,7 +239,7 @@ IN_PROC_BROWSER_TEST_F(HistoryCounterTest, Synced) { // WebHistoryService makes network requests, so we need to use a fake one // for testing. - scoped_ptr<history::FakeWebHistoryService> service( + std::unique_ptr<history::FakeWebHistoryService> service( new history::FakeWebHistoryService( ProfileOAuth2TokenServiceFactory::GetForProfile(browser()->profile()), SigninManagerFactory::GetForProfile(browser()->profile()), @@ -325,7 +325,7 @@ Profile* profile = GetProfile(kFirstProfileIndex); // Set up the fake web history service and the counter. - scoped_ptr<history::FakeWebHistoryService> web_history_service( + std::unique_ptr<history::FakeWebHistoryService> web_history_service( new history::FakeWebHistoryService( ProfileOAuth2TokenServiceFactory::GetForProfile(browser()->profile()), SigninManagerFactory::GetForProfile(browser()->profile()),
diff --git a/chrome/browser/browsing_data/mock_browsing_data_channel_id_helper.cc b/chrome/browser/browsing_data/mock_browsing_data_channel_id_helper.cc index 86831dce..5c4a040 100644 --- a/chrome/browser/browsing_data/mock_browsing_data_channel_id_helper.cc +++ b/chrome/browser/browsing_data/mock_browsing_data_channel_id_helper.cc
@@ -7,6 +7,7 @@ #include <utility> #include "base/logging.h" +#include "base/memory/scoped_ptr.h" #include "base/stl_util.h" #include "testing/gtest/include/gtest/gtest.h" @@ -33,7 +34,7 @@ void MockBrowsingDataChannelIDHelper::AddChannelIDSample( const std::string& server_id) { ASSERT_FALSE(ContainsKey(channel_ids_, server_id)); - scoped_ptr<crypto::ECPrivateKey> key(crypto::ECPrivateKey::Create()); + std::unique_ptr<crypto::ECPrivateKey> key(crypto::ECPrivateKey::Create()); channel_id_list_.push_back( net::ChannelIDStore::ChannelID(server_id, base::Time(), std::move(key))); channel_ids_[server_id] = true;
diff --git a/chrome/browser/browsing_data/mock_browsing_data_cookie_helper.cc b/chrome/browser/browsing_data/mock_browsing_data_cookie_helper.cc index 6ae519b..f6dfebc 100644 --- a/chrome/browser/browsing_data/mock_browsing_data_cookie_helper.cc +++ b/chrome/browser/browsing_data/mock_browsing_data_cookie_helper.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/browsing_data/mock_browsing_data_cookie_helper.h" #include "base/logging.h" +#include "base/memory/scoped_ptr.h" #include "base/stl_util.h" #include "base/time/time.h" #include "net/cookies/cookie_options.h" @@ -35,7 +36,7 @@ void MockBrowsingDataCookieHelper::AddCookieSamples( const GURL& url, const std::string& cookie_line) { - scoped_ptr<net::CanonicalCookie> cc(net::CanonicalCookie::Create( + std::unique_ptr<net::CanonicalCookie> cc(net::CanonicalCookie::Create( url, cookie_line, base::Time::Now(), net::CookieOptions())); if (cc.get()) {
diff --git a/chrome/browser/browsing_data/passwords_counter_browsertest.cc b/chrome/browser/browsing_data/passwords_counter_browsertest.cc index 1ee92946..8344e4a 100644 --- a/chrome/browser/browsing_data/passwords_counter_browsertest.cc +++ b/chrome/browser/browsing_data/passwords_counter_browsertest.cc
@@ -87,7 +87,7 @@ return result_; } - void Callback(scoped_ptr<BrowsingDataCounter::Result> result) { + void Callback(std::unique_ptr<BrowsingDataCounter::Result> result) { finished_ = result->Finished(); if (finished_) { @@ -115,7 +115,7 @@ scoped_refptr<password_manager::PasswordStore> store_; - scoped_ptr<base::RunLoop> run_loop_; + std::unique_ptr<base::RunLoop> run_loop_; base::Time time_; bool finished_;
diff --git a/chrome/browser/browsing_data/registrable_domain_filter_builder_unittest.cc b/chrome/browser/browsing_data/registrable_domain_filter_builder_unittest.cc index 172f0100..f6f2bd07 100644 --- a/chrome/browser/browsing_data/registrable_domain_filter_builder_unittest.cc +++ b/chrome/browser/browsing_data/registrable_domain_filter_builder_unittest.cc
@@ -5,11 +5,11 @@ #include "chrome/browser/browsing_data/registrable_domain_filter_builder.h" #include <algorithm> +#include <memory> #include <string> #include <vector> #include "base/callback.h" -#include "base/memory/scoped_ptr.h" #include "components/content_settings/core/common/content_settings_pattern.h" #include "net/cookies/canonical_cookie.h" #include "testing/gtest/include/gtest/gtest.h" @@ -53,7 +53,7 @@ std::string cookie_line = "A=2"; GURL test_url(test_case.url); EXPECT_TRUE(test_url.is_valid()) << test_case.url; - scoped_ptr<net::CanonicalCookie> cookie = net::CanonicalCookie::Create( + std::unique_ptr<net::CanonicalCookie> cookie = net::CanonicalCookie::Create( test_url, cookie_line, base::Time::Now(), net::CookieOptions()); EXPECT_TRUE(cookie) << cookie_line << " from " << test_case.url << " is not a valid cookie";
diff --git a/chrome/browser/caps/generate_state_json.cc b/chrome/browser/caps/generate_state_json.cc index f876aa63..14c3fb6 100644 --- a/chrome/browser/caps/generate_state_json.cc +++ b/chrome/browser/caps/generate_state_json.cc
@@ -7,6 +7,7 @@ #include <stddef.h> #include <stdint.h> +#include <memory> #include <string> #include <utility> @@ -16,7 +17,6 @@ #include "base/json/json_writer.h" #include "base/location.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/single_thread_task_runner.h" #include "base/strings/stringprintf.h" #include "base/sys_info.h"
diff --git a/chrome/browser/captive_portal/captive_portal_browsertest.cc b/chrome/browser/captive_portal/captive_portal_browsertest.cc index 18e860f..8fa21fbd 100644 --- a/chrome/browser/captive_portal/captive_portal_browsertest.cc +++ b/chrome/browser/captive_portal/captive_portal_browsertest.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include <map> +#include <memory> #include <set> #include <string> #include <utility> @@ -14,7 +15,6 @@ #include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" @@ -411,7 +411,7 @@ // Create a new Interceptor and add it to |interceptors_|, though it returns // ownership. - scoped_ptr<net::URLRequestInterceptor> CreateInterceptor(); + std::unique_ptr<net::URLRequestInterceptor> CreateInterceptor(); // These variables are only accessed on IO thread, though // URLRequestMockCaptivePortalJobFactory is created and @@ -441,10 +441,11 @@ base::Unretained(this), behind_captive_portal)); } -scoped_ptr<net::URLRequestInterceptor> +std::unique_ptr<net::URLRequestInterceptor> URLRequestMockCaptivePortalJobFactory::CreateInterceptor() { EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO)); - scoped_ptr<Interceptor> interceptor(new Interceptor(behind_captive_portal_)); + std::unique_ptr<Interceptor> interceptor( + new Interceptor(behind_captive_portal_)); interceptors_.push_back(interceptor.get()); return std::move(interceptor); }
diff --git a/chrome/browser/captive_portal/captive_portal_service.h b/chrome/browser/captive_portal/captive_portal_service.h index 7f7f87e..f100dac 100644 --- a/chrome/browser/captive_portal/captive_portal_service.h +++ b/chrome/browser/captive_portal/captive_portal_service.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_CAPTIVE_PORTAL_CAPTIVE_PORTAL_SERVICE_H_ #define CHROME_BROWSER_CAPTIVE_PORTAL_CAPTIVE_PORTAL_SERVICE_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/threading/non_thread_safe.h" #include "base/time/tick_clock.h" #include "base/time/time.h" @@ -180,7 +181,7 @@ // captive_portal::CaptivePortalResult, BackoffEntry::Policy is updated and // |backoff_entry_| is recreated. Each check that returns the same result // is considered a "failure", to trigger throttling. - scoped_ptr<net::BackoffEntry> backoff_entry_; + std::unique_ptr<net::BackoffEntry> backoff_entry_; // URL that returns a 204 response code when connected to the Internet. GURL test_url_;
diff --git a/chrome/browser/captive_portal/captive_portal_service_unittest.cc b/chrome/browser/captive_portal/captive_portal_service_unittest.cc index 5a60bb2..01bad9c 100644 --- a/chrome/browser/captive_portal/captive_portal_service_unittest.cc +++ b/chrome/browser/captive_portal/captive_portal_service_unittest.cc
@@ -282,16 +282,16 @@ content::TestBrowserThreadBundle thread_bundle_; // Note that the construction order of these matters. - scoped_ptr<TestingProfile> profile_; - scoped_ptr<base::SimpleTestTickClock> tick_clock_; - scoped_ptr<CaptivePortalService> service_; + std::unique_ptr<TestingProfile> profile_; + std::unique_ptr<base::SimpleTestTickClock> tick_clock_; + std::unique_ptr<CaptivePortalService> service_; }; // Verify that an observer doesn't get messages from the wrong profile. TEST_F(CaptivePortalServiceTest, CaptivePortalTwoProfiles) { Initialize(CaptivePortalService::SKIP_OS_CHECK_FOR_TESTING); TestingProfile profile2; - scoped_ptr<CaptivePortalService> service2( + std::unique_ptr<CaptivePortalService> service2( new CaptivePortalService(&profile2)); CaptivePortalObserver observer2(&profile2, service2.get());
diff --git a/chrome/browser/captive_portal/captive_portal_tab_helper.h b/chrome/browser/captive_portal/captive_portal_tab_helper.h index f27c4c2..b2ced03c 100644 --- a/chrome/browser/captive_portal/captive_portal_tab_helper.h +++ b/chrome/browser/captive_portal/captive_portal_tab_helper.h
@@ -5,9 +5,10 @@ #ifndef CHROME_BROWSER_CAPTIVE_PORTAL_CAPTIVE_PORTAL_TAB_HELPER_H_ #define CHROME_BROWSER_CAPTIVE_PORTAL_CAPTIVE_PORTAL_TAB_HELPER_H_ +#include <memory> + #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/threading/non_thread_safe.h" #include "chrome/browser/captive_portal/captive_portal_service.h" #include "content/public/browser/notification_observer.h" @@ -115,8 +116,8 @@ content::NavigationHandle* navigation_handle_; // Neither of these will ever be NULL. - scoped_ptr<CaptivePortalTabReloader> tab_reloader_; - scoped_ptr<CaptivePortalLoginDetector> login_detector_; + std::unique_ptr<CaptivePortalTabReloader> tab_reloader_; + std::unique_ptr<CaptivePortalLoginDetector> login_detector_; content::NotificationRegistrar registrar_;
diff --git a/chrome/browser/captive_portal/captive_portal_tab_helper_unittest.cc b/chrome/browser/captive_portal/captive_portal_tab_helper_unittest.cc index fba2d1f8..11efa40a 100644 --- a/chrome/browser/captive_portal/captive_portal_tab_helper_unittest.cc +++ b/chrome/browser/captive_portal/captive_portal_tab_helper_unittest.cc
@@ -4,9 +4,10 @@ #include "chrome/browser/captive_portal/captive_portal_tab_helper.h" +#include <memory> + #include "base/callback.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/captive_portal/captive_portal_service.h" #include "chrome/browser/captive_portal/captive_portal_tab_reloader.h" #include "chrome/browser/chrome_notification_types.h" @@ -192,7 +193,7 @@ void SetIsLoginTab() { tab_helper()->SetIsLoginTab(); } private: - scoped_ptr<CaptivePortalTabHelper> tab_helper_; + std::unique_ptr<CaptivePortalTabHelper> tab_helper_; // Owned by |tab_helper_|. testing::StrictMock<MockCaptivePortalTabReloader>* mock_reloader_;
diff --git a/chrome/browser/captive_portal/captive_portal_tab_reloader_unittest.cc b/chrome/browser/captive_portal/captive_portal_tab_reloader_unittest.cc index 18fa4a5..07103607 100644 --- a/chrome/browser/captive_portal/captive_portal_tab_reloader_unittest.cc +++ b/chrome/browser/captive_portal/captive_portal_tab_reloader_unittest.cc
@@ -104,7 +104,7 @@ TestCaptivePortalTabReloader& tab_reloader() { return *tab_reloader_.get(); } private: - scoped_ptr<TestCaptivePortalTabReloader> tab_reloader_; + std::unique_ptr<TestCaptivePortalTabReloader> tab_reloader_; }; // Simulates a slow SSL load when the Internet is connected.
diff --git a/chrome/browser/certificate_manager_model.cc b/chrome/browser/certificate_manager_model.cc index 77f22c0..3d366ed 100644 --- a/chrome/browser/certificate_manager_model.cc +++ b/chrome/browser/certificate_manager_model.cc
@@ -225,7 +225,7 @@ const CreationCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - scoped_ptr<CertificateManagerModel> model(new CertificateManagerModel( + std::unique_ptr<CertificateManagerModel> model(new CertificateManagerModel( cert_db, is_user_db_available, is_tpm_available, observer)); callback.Run(std::move(model)); }
diff --git a/chrome/browser/certificate_manager_model.h b/chrome/browser/certificate_manager_model.h index ee315c4..64fcb2c 100644 --- a/chrome/browser/certificate_manager_model.h +++ b/chrome/browser/certificate_manager_model.h
@@ -6,12 +6,12 @@ #define CHROME_BROWSER_CERTIFICATE_MANAGER_MODEL_H_ #include <map> +#include <memory> #include <string> #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "net/cert/nss_cert_database.h" @@ -29,7 +29,7 @@ // subject's CertPrincipal::GetDisplayName() value is used instead. typedef std::map<std::string, net::CertificateList> OrgGroupingMap; - typedef base::Callback<void(scoped_ptr<CertificateManagerModel>)> + typedef base::Callback<void(std::unique_ptr<CertificateManagerModel>)> CreationCallback; // Enumeration of the possible columns in the certificate manager tree view.
diff --git a/chrome/browser/character_encoding.cc b/chrome/browser/character_encoding.cc index 6ee4e73..b7c9f6fdd 100644 --- a/chrome/browser/character_encoding.cc +++ b/chrome/browser/character_encoding.cc
@@ -7,11 +7,11 @@ #include <stddef.h> #include <map> +#include <memory> #include <set> #include "base/logging.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string_tokenizer.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -121,9 +121,9 @@ } private: - scoped_ptr<IdToCanonicalEncodingNameMapType> id_to_encoding_name_map_; - scoped_ptr<CanonicalEncodingNameToIdMapType> encoding_name_to_id_map_; - scoped_ptr<CanonicalNameDisplayNameMapType> + std::unique_ptr<IdToCanonicalEncodingNameMapType> id_to_encoding_name_map_; + std::unique_ptr<CanonicalEncodingNameToIdMapType> encoding_name_to_id_map_; + std::unique_ptr<CanonicalNameDisplayNameMapType> encoding_name_to_display_name_map_; std::vector<int> locale_dependent_encoding_ids_; std::vector<CharacterEncoding::EncodingInfo> current_display_encodings_;
diff --git a/chrome/browser/chrome_browser_application_mac_unittest.mm b/chrome/browser/chrome_browser_application_mac_unittest.mm index 69faabf..09d10bf 100644 --- a/chrome/browser/chrome_browser_application_mac_unittest.mm +++ b/chrome/browser/chrome_browser_application_mac_unittest.mm
@@ -2,14 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#import "chrome/browser/chrome_browser_application_mac.h" + #import <Cocoa/Cocoa.h> #include <stddef.h> -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "base/metrics/histogram.h" #include "base/metrics/histogram_samples.h" #include "base/metrics/statistics_recorder.h" -#import "chrome/browser/chrome_browser_application_mac.h" #include "testing/gtest/include/gtest/gtest.h" using base::HistogramBase; @@ -76,7 +78,7 @@ EXPECT_EQ(1U, histograms.size()); EXPECT_EQ(HistogramBase::kUmaTargetedHistogramFlag, histograms[0]->flags()); - scoped_ptr<HistogramSamples> samples(histograms[0]->SnapshotSamples()); + std::unique_ptr<HistogramSamples> samples(histograms[0]->SnapshotSamples()); EXPECT_EQ(4, samples->GetCount(0)); EXPECT_EQ(1, samples->GetCount(1)); EXPECT_EQ(3, samples->GetCount(2));
diff --git a/chrome/browser/chrome_browser_main.cc b/chrome/browser/chrome_browser_main.cc index c3e48db..1d00e40 100644 --- a/chrome/browser/chrome_browser_main.cc +++ b/chrome/browser/chrome_browser_main.cc
@@ -6,6 +6,7 @@ #include <stddef.h> #include <stdint.h> + #include <set> #include <string> #include <utility> @@ -20,6 +21,7 @@ #include "base/feature_list.h" #include "base/files/file_path.h" #include "base/files/file_util.h" +#include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram_macros.h" #include "base/path_service.h" @@ -335,13 +337,10 @@ base::FilePath parent_profile = parsed_command_line.GetSwitchValuePath(switches::kParentProfile); scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple(); - scoped_ptr<PrefService> parent_local_state( + std::unique_ptr<PrefService> parent_local_state( chrome_prefs::CreateLocalState( - parent_profile, - local_state_task_runner, - g_browser_process->policy_service(), - registry, - false)); + parent_profile, local_state_task_runner, + g_browser_process->policy_service(), registry, false)); registry->RegisterStringPref(prefs::kApplicationLocale, std::string()); // Right now, we only inherit the locale setting from the parent profile. local_state->SetString( @@ -718,7 +717,7 @@ metrics->AddSyntheticTrialObserver(provider); } - scoped_ptr<base::FeatureList> feature_list(new base::FeatureList); + std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList); feature_list->InitializeFromCommandLine( command_line->GetSwitchValueASCII(switches::kEnableFeatures), command_line->GetSwitchValueASCII(switches::kDisableFeatures)); @@ -1122,7 +1121,7 @@ // Initialize tracking synchronizer system. tracking_synchronizer_ = new metrics::TrackingSynchronizer( - make_scoped_ptr(new base::DefaultTickClock()), + base::WrapUnique(new base::DefaultTickClock()), base::Bind(&metrics::ContentTrackingSynchronizerDelegate::Create)); #if defined(OS_MACOSX) @@ -1606,7 +1605,7 @@ // Negative ping delay means to send ping immediately after a first search is // recorded. rlz::RLZTracker::SetRlzDelegate( - make_scoped_ptr(new ChromeRLZTrackerDelegate)); + base::WrapUnique(new ChromeRLZTrackerDelegate)); rlz::RLZTracker::InitRlzDelayed( first_run::IsChromeFirstRun(), ping_delay < 0, base::TimeDelta::FromMilliseconds(abs(ping_delay)),
diff --git a/chrome/browser/chrome_browser_main.h b/chrome/browser/chrome_browser_main.h index da58d17..326406eb 100644 --- a/chrome/browser/chrome_browser_main.h +++ b/chrome/browser/chrome_browser_main.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_CHROME_BROWSER_MAIN_H_ #define CHROME_BROWSER_CHROME_BROWSER_MAIN_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/field_trial.h" #include "base/profiler/stack_sampling_profiler.h" #include "base/tracked_objects.h" @@ -129,25 +130,25 @@ int result_code_; // Create StartupTimeBomb object for watching jank during startup. - scoped_ptr<StartupTimeBomb> startup_watcher_; + std::unique_ptr<StartupTimeBomb> startup_watcher_; // Create ShutdownWatcherHelper object for watching jank during shutdown. // Please keep |shutdown_watcher| as the first object constructed, and hence // it is destroyed last. - scoped_ptr<ShutdownWatcherHelper> shutdown_watcher_; + std::unique_ptr<ShutdownWatcherHelper> shutdown_watcher_; // Statistical testing infrastructure for the entire browser. NULL until // SetupMetricsAndFieldTrials is called. - scoped_ptr<base::FieldTrialList> field_trial_list_; + std::unique_ptr<base::FieldTrialList> field_trial_list_; ChromeBrowserFieldTrials browser_field_trials_; #if !defined(OS_ANDROID) && !defined(OS_IOS) // A monitor for attributing power consumption to origins. - scoped_ptr<ProcessPowerCollector> process_power_collector_; + std::unique_ptr<ProcessPowerCollector> process_power_collector_; - scoped_ptr<webusb::WebUsbBrowserClient> webusb_browser_client_; - scoped_ptr<webusb::WebUsbDetector> webusb_detector_; + std::unique_ptr<webusb::WebUsbBrowserClient> webusb_browser_client_; + std::unique_ptr<webusb::WebUsbDetector> webusb_detector_; #endif // Vector of additional ChromeBrowserMainExtraParts. @@ -163,23 +164,23 @@ // Members initialized after / released before main_message_loop_ ------------ - scoped_ptr<BrowserProcessImpl> browser_process_; + std::unique_ptr<BrowserProcessImpl> browser_process_; scoped_refptr<metrics::TrackingSynchronizer> tracking_synchronizer_; #if !defined(OS_ANDROID) // Browser creation happens on the Java side in Android. - scoped_ptr<StartupBrowserCreator> browser_creator_; + std::unique_ptr<StartupBrowserCreator> browser_creator_; // Android doesn't support multiple browser processes, so it doesn't implement // ProcessSingleton. - scoped_ptr<ChromeProcessSingleton> process_singleton_; + std::unique_ptr<ChromeProcessSingleton> process_singleton_; // Android's first run is done in Java instead of native. - scoped_ptr<first_run::MasterPrefs> master_prefs_; + std::unique_ptr<first_run::MasterPrefs> master_prefs_; #endif Profile* profile_; bool run_message_loop_; ProcessSingleton::NotifyResult notify_result_; - scoped_ptr<ThreeDAPIObserver> three_d_observer_; + std::unique_ptr<ThreeDAPIObserver> three_d_observer_; // Initialized in SetupMetricsAndFieldTrials. scoped_refptr<FieldTrialSynchronizer> field_trial_synchronizer_;
diff --git a/chrome/browser/chrome_browser_main_android.h b/chrome/browser/chrome_browser_main_android.h index d9c996b..7d919c4 100644 --- a/chrome/browser/chrome_browser_main_android.h +++ b/chrome/browser/chrome_browser_main_android.h
@@ -29,8 +29,8 @@ void ShowMissingLocaleMessageBox() override; private: - scoped_ptr<base::MessageLoop> main_message_loop_; - scoped_ptr<breakpad::CrashDumpManager> crash_dump_manager_; + std::unique_ptr<base::MessageLoop> main_message_loop_; + std::unique_ptr<breakpad::CrashDumpManager> crash_dump_manager_; DISALLOW_COPY_AND_ASSIGN(ChromeBrowserMainPartsAndroid); };
diff --git a/chrome/browser/chrome_browser_main_extra_parts_exo.cc b/chrome/browser/chrome_browser_main_extra_parts_exo.cc index 54d0a17..cdd2a698 100644 --- a/chrome/browser/chrome_browser_main_extra_parts_exo.cc +++ b/chrome/browser/chrome_browser_main_extra_parts_exo.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/chrome_browser_main_extra_parts_exo.h" +#include "base/memory/ptr_util.h" + #if defined(USE_GLIB) #include <glib.h> #endif @@ -74,7 +76,7 @@ private: // The poll attached to |wayland_source_|. - scoped_ptr<GPollFD> wayland_poll_; + std::unique_ptr<GPollFD> wayland_poll_; // The GLib event source for wayland events. GLibWaylandSource* wayland_source_; @@ -120,7 +122,7 @@ switches::kEnableWaylandServer)) { wayland_server_ = exo::wayland::Server::Create(display_.get()); wayland_watcher_ = - make_scoped_ptr(new WaylandWatcher(wayland_server_.get())); + base::WrapUnique(new WaylandWatcher(wayland_server_.get())); } }
diff --git a/chrome/browser/chrome_browser_main_extra_parts_exo.h b/chrome/browser/chrome_browser_main_extra_parts_exo.h index 16960e9..aa56120 100644 --- a/chrome/browser/chrome_browser_main_extra_parts_exo.h +++ b/chrome/browser/chrome_browser_main_extra_parts_exo.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_CHROME_BROWSER_MAIN_EXTRA_PARTS_EXO_H_ #define CHROME_BROWSER_CHROME_BROWSER_MAIN_EXTRA_PARTS_EXO_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/chrome_browser_main_extra_parts.h" namespace exo { @@ -26,10 +27,10 @@ void PostMainMessageLoopRun() override; private: - scoped_ptr<exo::Display> display_; - scoped_ptr<exo::wayland::Server> wayland_server_; + std::unique_ptr<exo::Display> display_; + std::unique_ptr<exo::wayland::Server> wayland_server_; class WaylandWatcher; - scoped_ptr<WaylandWatcher> wayland_watcher_; + std::unique_ptr<WaylandWatcher> wayland_watcher_; DISALLOW_COPY_AND_ASSIGN(ChromeBrowserMainExtraPartsExo); };
diff --git a/chrome/browser/chrome_browser_main_mac.mm b/chrome/browser/chrome_browser_main_mac.mm index 3bf08bed..3f478125 100644 --- a/chrome/browser/chrome_browser_main_mac.mm +++ b/chrome/browser/chrome_browser_main_mac.mm
@@ -10,6 +10,7 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/mac/bundle_locations.h" +#import "base/mac/foundation_util.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_nsobject.h" #include "base/path_service.h" @@ -204,6 +205,7 @@ } void ChromeBrowserMainPartsMac::DidEndMainMessageLoop() { - AppController* appController = [NSApp delegate]; + AppController* appController = + base::mac::ObjCCastStrict<AppController>([NSApp delegate]); [appController didEndMainMessageLoop]; }
diff --git a/chrome/browser/chrome_browser_main_win.cc b/chrome/browser/chrome_browser_main_win.cc index 05463bd5..2dcaec9e 100644 --- a/chrome/browser/chrome_browser_main_win.cc +++ b/chrome/browser/chrome_browser_main_win.cc
@@ -4,11 +4,12 @@ #include "chrome/browser/chrome_browser_main_win.h" -#include <windows.h> #include <shellapi.h> #include <stddef.h> +#include <windows.h> #include <algorithm> +#include <memory> #include "base/base_switches.h" #include "base/command_line.h" @@ -19,7 +20,6 @@ #include "base/i18n/rtl.h" #include "base/location.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/histogram.h" #include "base/path_service.h" #include "base/scoped_native_library.h" @@ -360,7 +360,7 @@ void ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment( const base::CommandLine& parsed_command_line) { // Clear this var so child processes don't show the dialog by default. - scoped_ptr<base::Environment> env(base::Environment::Create()); + std::unique_ptr<base::Environment> env(base::Environment::Create()); env->UnSetVar(env_vars::kShowRestart); // For non-interactive tests we don't restart on crash.
diff --git a/chrome/browser/chrome_browser_main_win.h b/chrome/browser/chrome_browser_main_win.h index c948edbf..35165b00 100644 --- a/chrome/browser/chrome_browser_main_win.h +++ b/chrome/browser/chrome_browser_main_win.h
@@ -71,7 +71,7 @@ private: #if defined(GOOGLE_CHROME_BUILD) - scoped_ptr<DidRunUpdater> did_run_updater_; + std::unique_ptr<DidRunUpdater> did_run_updater_; #endif #if BUILDFLAG(ENABLE_KASKO) // Cleans up Kasko crash reports that exceeded the maximum upload attempts.
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 12d723d..2a8495a 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -16,6 +16,7 @@ #include "base/files/scoped_file.h" #include "base/lazy_instance.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/path_service.h" #include "base/strings/string_number_conversions.h" @@ -1418,7 +1419,7 @@ base::CommandLine* command_line, int child_process_id) { #if defined(OS_MACOSX) - scoped_ptr<metrics::ClientInfo> client_info = + std::unique_ptr<metrics::ClientInfo> client_info = GoogleUpdateSettings::LoadMetricsClientInfo(); if (client_info) { command_line->AppendSwitchASCII(switches::kMetricsClientID, @@ -1427,7 +1428,7 @@ #elif defined(OS_POSIX) if (breakpad::IsCrashReporterEnabled()) { std::string switch_value; - scoped_ptr<metrics::ClientInfo> client_info = + std::unique_ptr<metrics::ClientInfo> client_info = GoogleUpdateSettings::LoadMetricsClientInfo(); if (client_info) switch_value = client_info->client_id; @@ -2025,11 +2026,11 @@ return new ChromeQuotaPermissionContext(); } -scoped_ptr<storage::QuotaEvictionPolicy> +std::unique_ptr<storage::QuotaEvictionPolicy> ChromeContentBrowserClient::GetTemporaryStorageEvictionPolicy( content::BrowserContext* context) { return SiteEngagementEvictionPolicy::IsEnabled() - ? make_scoped_ptr(new SiteEngagementEvictionPolicy(context)) + ? base::WrapUnique(new SiteEngagementEvictionPolicy(context)) : nullptr; } @@ -2075,7 +2076,7 @@ safe_browsing::SafeBrowsingService* safe_browsing_service = g_browser_process->safe_browsing_service(); - scoped_ptr<SafeBrowsingSSLCertReporter> cert_reporter( + std::unique_ptr<SafeBrowsingSSLCertReporter> cert_reporter( new SafeBrowsingSSLCertReporter(safe_browsing_service ? safe_browsing_service->ui_manager() : nullptr)); @@ -2087,7 +2088,7 @@ void ChromeContentBrowserClient::SelectClientCertificate( content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, - scoped_ptr<content::ClientCertificateDelegate> delegate) { + std::unique_ptr<content::ClientCertificateDelegate> delegate) { prerender::PrerenderContents* prerender_contents = prerender::PrerenderContents::FromWebContents(web_contents); if (prerender_contents) { @@ -2103,13 +2104,10 @@ Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); - scoped_ptr<base::Value> filter = + std::unique_ptr<base::Value> filter = HostContentSettingsMapFactory::GetForProfile(profile)->GetWebsiteSetting( - requesting_url, - requesting_url, - CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE, - std::string(), - NULL); + requesting_url, requesting_url, + CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE, std::string(), NULL); if (filter.get()) { // Try to automatically select a client certificate. @@ -2867,7 +2865,7 @@ if (handle->IsInMainFrame()) { // Redirect some navigations to apps that have registered matching URL // handlers ('url_handlers' in the manifest). - scoped_ptr<content::NavigationThrottle> url_to_app_throttle = + std::unique_ptr<content::NavigationThrottle> url_to_app_throttle = AppUrlRedirector::MaybeCreateThrottleFor(handle); if (url_to_app_throttle) throttles.push_back(std::move(url_to_app_throttle));
diff --git a/chrome/browser/chrome_content_browser_client.h b/chrome/browser/chrome_content_browser_client.h index 043218d..a01f4d5 100644 --- a/chrome/browser/chrome_content_browser_client.h +++ b/chrome/browser/chrome_content_browser_client.h
@@ -7,13 +7,13 @@ #include <stddef.h> +#include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "build/build_config.h" #include "content/public/browser/content_browser_client.h" @@ -166,8 +166,8 @@ const GURL& url, content::ResourceContext* context) override; content::QuotaPermissionContext* CreateQuotaPermissionContext() override; - scoped_ptr<storage::QuotaEvictionPolicy> GetTemporaryStorageEvictionPolicy( - content::BrowserContext* context) override; + std::unique_ptr<storage::QuotaEvictionPolicy> + GetTemporaryStorageEvictionPolicy(content::BrowserContext* context) override; void AllowCertificateError( content::WebContents* web_contents, int cert_error, @@ -182,7 +182,7 @@ void SelectClientCertificate( content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, - scoped_ptr<content::ClientCertificateDelegate> delegate) override; + std::unique_ptr<content::ClientCertificateDelegate> delegate) override; void AddCertificate(net::CertificateMimeType cert_type, const void* cert_data, size_t cert_size,
diff --git a/chrome/browser/chrome_content_browser_client_unittest.cc b/chrome/browser/chrome_content_browser_client_unittest.cc index c8b4b437..191985b 100644 --- a/chrome/browser/chrome_content_browser_client_unittest.cc +++ b/chrome/browser/chrome_content_browser_client_unittest.cc
@@ -362,7 +362,7 @@ template_url_service->SetUserSelectedDefaultSearchProvider(template_url); } - scoped_ptr<base::FieldTrialList> field_trial_list_; + std::unique_ptr<base::FieldTrialList> field_trial_list_; }; TEST_F(InstantNTPURLRewriteTest, UberURLHandler_InstantExtendedNewTabPage) {
diff --git a/chrome/browser/chrome_device_client.h b/chrome/browser/chrome_device_client.h index a121a69..aa6635efb 100644 --- a/chrome/browser/chrome_device_client.h +++ b/chrome/browser/chrome_device_client.h
@@ -7,9 +7,10 @@ #include "device/core/device_client.h" +#include <memory> + #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" // Implementation of device::DeviceClient that returns //device service // singletons appropriate for use within the Chrome application. @@ -23,8 +24,8 @@ device::HidService* GetHidService() override; private: - scoped_ptr<device::HidService> hid_service_; - scoped_ptr<device::UsbService> usb_service_; + std::unique_ptr<device::HidService> hid_service_; + std::unique_ptr<device::UsbService> usb_service_; DISALLOW_COPY_AND_ASSIGN(ChromeDeviceClient); };
diff --git a/chrome/browser/chrome_elf_init_unittest_win.cc b/chrome/browser/chrome_elf_init_unittest_win.cc index 648de0a5..92d8567e 100644 --- a/chrome/browser/chrome_elf_init_unittest_win.cc +++ b/chrome/browser/chrome_elf_init_unittest_win.cc
@@ -4,8 +4,9 @@ #include "chrome/browser/chrome_elf_init_win.h" +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/field_trial.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" @@ -54,7 +55,7 @@ return blacklist_version; } - scoped_ptr<base::win::RegKey> blacklist_registry_key_; + std::unique_ptr<base::win::RegKey> blacklist_registry_key_; registry_util::RegistryOverrideManager override_manager_; content::TestBrowserThreadBundle test_browser_thread_bundle_;
diff --git a/chrome/browser/chrome_net_benchmarking_message_filter.cc b/chrome/browser/chrome_net_benchmarking_message_filter.cc index 9dbe3d12..b95edb4 100644 --- a/chrome/browser/chrome_net_benchmarking_message_filter.cc +++ b/chrome/browser/chrome_net_benchmarking_message_filter.cc
@@ -4,11 +4,12 @@ #include "chrome/browser/chrome_net_benchmarking_message_filter.h" +#include <memory> + #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/net/predictor.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/benchmarking_messages.h"
diff --git a/chrome/browser/chrome_quota_permission_context.cc b/chrome/browser/chrome_quota_permission_context.cc index 0de3b2b..a517382a 100644 --- a/chrome/browser/chrome_quota_permission_context.cc +++ b/chrome/browser/chrome_quota_permission_context.cc
@@ -175,7 +175,7 @@ int64_t requested_quota, const content::QuotaPermissionContext::PermissionCallback& callback) { infobar_service->AddInfoBar(infobar_service->CreateConfirmInfoBar( - scoped_ptr<ConfirmInfoBarDelegate>(new RequestQuotaInfoBarDelegate( + std::unique_ptr<ConfirmInfoBarDelegate>(new RequestQuotaInfoBarDelegate( context, origin_url, requested_quota, callback)))); }
diff --git a/chrome/browser/chrome_webusb_browser_client.cc b/chrome/browser/chrome_webusb_browser_client.cc index 709040f8..4cfe5ac 100644 --- a/chrome/browser/chrome_webusb_browser_client.cc +++ b/chrome/browser/chrome_webusb_browser_client.cc
@@ -113,7 +113,7 @@ ResourceBundle& rb = ResourceBundle::GetSharedInstance(); message_center::RichNotificationData rich_notification_data; - scoped_ptr<message_center::Notification> notification( + std::unique_ptr<message_center::Notification> notification( new message_center::Notification( message_center::NOTIFICATION_TYPE_SIMPLE, notification_id, l10n_util::GetStringFUTF16( @@ -121,11 +121,10 @@ l10n_util::GetStringFUTF16( IDS_WEBUSB_DEVICE_DETECTED_NOTIFICATION, base::UTF8ToUTF16(landing_page.GetContent())), - rb.GetNativeImageNamed(IDR_USB_NOTIFICATION_ICON), - base::string16(), GURL(), - message_center::NotifierId( - message_center::NotifierId::SYSTEM_COMPONENT, - kWebUsbDetectorNotificationID), + rb.GetNativeImageNamed(IDR_USB_NOTIFICATION_ICON), base::string16(), + GURL(), message_center::NotifierId( + message_center::NotifierId::SYSTEM_COMPONENT, + kWebUsbDetectorNotificationID), rich_notification_data, new WebUsbNotificationDelegate(landing_page, notification_id)));
diff --git a/chrome/browser/chromeos/extensions/wallpaper_private_api.cc b/chrome/browser/chromeos/extensions/wallpaper_private_api.cc index fd443495..6555895f 100644 --- a/chrome/browser/chromeos/extensions/wallpaper_private_api.cc +++ b/chrome/browser/chromeos/extensions/wallpaper_private_api.cc
@@ -959,7 +959,7 @@ } bool WallpaperPrivateRecordWallpaperUMAFunction::RunSync() { - scoped_ptr<record_wallpaper_uma::Params> params( + std::unique_ptr<record_wallpaper_uma::Params> params( record_wallpaper_uma::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params);
diff --git a/chrome/browser/chromeos/policy/bluetooth_policy_handler.cc b/chrome/browser/chromeos/policy/bluetooth_policy_handler.cc new file mode 100644 index 0000000..b6379d8 --- /dev/null +++ b/chrome/browser/chromeos/policy/bluetooth_policy_handler.cc
@@ -0,0 +1,56 @@ +// Copyright (c) 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/policy/bluetooth_policy_handler.h" + +#include "base/bind.h" +#include "base/memory/ref_counted.h" +#include "chromeos/settings/cros_settings_names.h" +#include "chromeos/settings/cros_settings_provider.h" +#include "device/bluetooth/bluetooth_adapter.h" +#include "device/bluetooth/bluetooth_adapter_factory.h" + +namespace policy { + +namespace { + +void SetBluetoothPolicy(bool allow_bluetooth, + scoped_refptr<device::BluetoothAdapter> adapter) { + if (!allow_bluetooth) + adapter->Shutdown(); +} + +} // namespace + +BluetoothPolicyHandler::BluetoothPolicyHandler( + chromeos::CrosSettings* cros_settings) + : cros_settings_(cros_settings), weak_factory_(this) { + bluetooth_policy_subscription_ = cros_settings_->AddSettingsObserver( + chromeos::kAllowBluetooth, + base::Bind(&BluetoothPolicyHandler::OnBluetoothPolicyChanged, + weak_factory_.GetWeakPtr())); + + // Fire it once so we're sure we get an invocation on startup. + OnBluetoothPolicyChanged(); +} + +BluetoothPolicyHandler::~BluetoothPolicyHandler() {} + +void BluetoothPolicyHandler::OnBluetoothPolicyChanged() { + chromeos::CrosSettingsProvider::TrustedStatus status = + cros_settings_->PrepareTrustedValues( + base::Bind(&BluetoothPolicyHandler::OnBluetoothPolicyChanged, + weak_factory_.GetWeakPtr())); + if (status != chromeos::CrosSettingsProvider::TRUSTED) + return; + + // Get the updated policy. + bool allow_bluetooth = true; + cros_settings_->GetBoolean(chromeos::kAllowBluetooth, &allow_bluetooth); + + device::BluetoothAdapterFactory::GetAdapter( + base::Bind(&SetBluetoothPolicy, allow_bluetooth)); +} + +} // namespace policy
diff --git a/chrome/browser/chromeos/policy/bluetooth_policy_handler.h b/chrome/browser/chromeos/policy/bluetooth_policy_handler.h new file mode 100644 index 0000000..0d1200a7 --- /dev/null +++ b/chrome/browser/chromeos/policy/bluetooth_policy_handler.h
@@ -0,0 +1,40 @@ +// Copyright (c) 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_POLICY_BLUETOOTH_POLICY_HANDLER_H_ +#define CHROME_BROWSER_CHROMEOS_POLICY_BLUETOOTH_POLICY_HANDLER_H_ + +#include <memory> + +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "chrome/browser/chromeos/settings/cros_settings.h" + +namespace policy { + +// This class observes the device setting |DeviceAllowBluetooth|, and calls +// BluetoothAdapter::SetDisabled() appropriately based on the value of that +// setting. +class BluetoothPolicyHandler { + public: + explicit BluetoothPolicyHandler(chromeos::CrosSettings* cros_settings); + ~BluetoothPolicyHandler(); + + private: + // Once a trusted set of policies is established, this function calls + // |SetDisabled| with the trusted state of the |DeviceAllowBluetooth| policy + // through helper function |SetBluetoothPolicy|. + void OnBluetoothPolicyChanged(); + + chromeos::CrosSettings* cros_settings_; + std::unique_ptr<chromeos::CrosSettings::ObserverSubscription> + bluetooth_policy_subscription_; + base::WeakPtrFactory<BluetoothPolicyHandler> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(BluetoothPolicyHandler); +}; + +} // namespace policy + +#endif // CHROME_BROWSER_CHROMEOS_POLICY_BLUETOOTH_POLICY_HANDLER_H_
diff --git a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc index 9af9062..90b4ad1 100644 --- a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc +++ b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc
@@ -21,6 +21,7 @@ #include "chrome/browser/chromeos/policy/affiliated_cloud_policy_invalidator.h" #include "chrome/browser/chromeos/policy/affiliated_invalidation_service_provider.h" #include "chrome/browser/chromeos/policy/affiliated_invalidation_service_provider_impl.h" +#include "chrome/browser/chromeos/policy/bluetooth_policy_handler.h" #include "chrome/browser/chromeos/policy/consumer_management_service.h" #include "chrome/browser/chromeos/policy/device_cloud_policy_initializer.h" #include "chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos.h" @@ -218,6 +219,9 @@ ->managed_network_configuration_handler(), chromeos::NetworkHandler::Get()->network_device_handler(), chromeos::CrosSettings::Get()); + + bluetooth_policy_handler_.reset( + new BluetoothPolicyHandler(chromeos::CrosSettings::Get())); } void BrowserPolicyConnectorChromeOS::PreShutdown() {
diff --git a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h index 5b54e2c..368a8955 100644 --- a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h +++ b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h
@@ -29,6 +29,7 @@ class AffiliatedCloudPolicyInvalidator; class AffiliatedInvalidationServiceProvider; class AffiliatedRemoteCommandsInvalidator; +class BluetoothPolicyHandler; class ConsumerManagementService; class DeviceCloudPolicyInitializer; class DeviceLocalAccountPolicyService; @@ -173,6 +174,8 @@ std::unique_ptr<AffiliatedRemoteCommandsInvalidator> device_remote_commands_invalidator_; + std::unique_ptr<BluetoothPolicyHandler> bluetooth_policy_handler_; + // This policy provider is used on Chrome OS to feed user policy into the // global PolicyService instance. This works by installing the cloud policy // provider of the primary profile as the delegate of the ProxyPolicyProvider,
diff --git a/chrome/browser/chromeos/settings/device_settings_provider.cc b/chrome/browser/chromeos/settings/device_settings_provider.cc index bb5b2404..be2bb1e 100644 --- a/chrome/browser/chromeos/settings/device_settings_provider.cc +++ b/chrome/browser/chromeos/settings/device_settings_provider.cc
@@ -457,10 +457,13 @@ policy.display_rotation_default().display_rotation_default()); } - new_values_cache->SetBoolean( - kAllowBluetooth, policy.has_allow_bluetooth() && - policy.allow_bluetooth().has_allow_bluetooth() && - policy.allow_bluetooth().allow_bluetooth()); + if (policy.has_allow_bluetooth() && + policy.allow_bluetooth().has_allow_bluetooth()) { + new_values_cache->SetBoolean(kAllowBluetooth, + policy.allow_bluetooth().allow_bluetooth()); + } else { + new_values_cache->SetBoolean(kAllowBluetooth, true); + } if (policy.has_quirks_download_enabled() && policy.quirks_download_enabled().has_quirks_download_enabled()) {
diff --git a/chrome/browser/component_updater/caps_installer_win.cc b/chrome/browser/component_updater/caps_installer_win.cc index a02bf53..d2d3630 100644 --- a/chrome/browser/component_updater/caps_installer_win.cc +++ b/chrome/browser/component_updater/caps_installer_win.cc
@@ -86,9 +86,10 @@ return true; } - void ComponentReady(const base::Version& version, - const base::FilePath& install_dir, - scoped_ptr<base::DictionaryValue> manifest) override { + void ComponentReady( + const base::Version& version, + const base::FilePath& install_dir, + std::unique_ptr<base::DictionaryValue> manifest) override { // Can't block here. This is usually the browser UI thread. base::WorkerPool::PostTask( FROM_HERE, @@ -118,8 +119,7 @@ void RegisterCAPSComponent(ComponentUpdateService* cus) { // The component updater takes ownership of |installer|. - scoped_ptr<ComponentInstallerTraits> traits( - new CAPSInstallerTraits()); + std::unique_ptr<ComponentInstallerTraits> traits(new CAPSInstallerTraits()); DefaultComponentInstaller* installer = new DefaultComponentInstaller(std::move(traits)); installer->Register(cus, base::Closure());
diff --git a/chrome/browser/component_updater/cld_component_installer.cc b/chrome/browser/component_updater/cld_component_installer.cc index 672848fc..fc0a5e6 100644 --- a/chrome/browser/component_updater/cld_component_installer.cc +++ b/chrome/browser/component_updater/cld_component_installer.cc
@@ -79,7 +79,7 @@ void CldComponentInstallerTraits::ComponentReady( const base::Version& version, const base::FilePath& path, - scoped_ptr<base::DictionaryValue> manifest) { + std::unique_ptr<base::DictionaryValue> manifest) { VLOG(1) << "Component ready, version " << version.GetString() << " in " << path.value(); SetLatestCldDataFile(GetInstalledPath(path)); @@ -129,7 +129,7 @@ // configured. See also: chrome://translate-internals VLOG(1) << "Registering CLD component with the component update service"; - scoped_ptr<ComponentInstallerTraits> traits( + std::unique_ptr<ComponentInstallerTraits> traits( new CldComponentInstallerTraits()); // |cus| will take ownership of |installer| during installer->Register(cus). DefaultComponentInstaller* installer =
diff --git a/chrome/browser/component_updater/cld_component_installer.h b/chrome/browser/component_updater/cld_component_installer.h index 7a27976..32a04fc 100644 --- a/chrome/browser/component_updater/cld_component_installer.h +++ b/chrome/browser/component_updater/cld_component_installer.h
@@ -49,7 +49,7 @@ const base::FilePath& install_dir) const override; void ComponentReady(const base::Version& version, const base::FilePath& path, - scoped_ptr<base::DictionaryValue> manifest) override; + std::unique_ptr<base::DictionaryValue> manifest) override; base::FilePath GetBaseDirectory() const override; void GetHash(std::vector<uint8_t>* hash) const override; std::string GetName() const override;
diff --git a/chrome/browser/component_updater/cld_component_installer_unittest.cc b/chrome/browser/component_updater/cld_component_installer_unittest.cc index 97ceb44..5cf6e483 100644 --- a/chrome/browser/component_updater/cld_component_installer_unittest.cc +++ b/chrome/browser/component_updater/cld_component_installer_unittest.cc
@@ -6,6 +6,8 @@ #include <stddef.h> #include <stdint.h> + +#include <memory> #include <utility> #include <vector> @@ -13,7 +15,6 @@ #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" @@ -125,7 +126,7 @@ } TEST_F(CldComponentInstallerTest, ComponentReady) { - scoped_ptr<base::DictionaryValue> manifest; + std::unique_ptr<base::DictionaryValue> manifest; const base::FilePath install_dir(FILE_PATH_LITERAL("/foo")); const base::Version version("1.2.3.4"); traits_.ComponentReady(version, install_dir, std::move(manifest));
diff --git a/chrome/browser/component_updater/component_installers_unittest.cc b/chrome/browser/component_updater/component_installers_unittest.cc index e56b51c..aefce5f 100644 --- a/chrome/browser/component_updater/component_installers_unittest.cc +++ b/chrome/browser/component_updater/component_installers_unittest.cc
@@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> + #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/json/json_file_value_serializer.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/version.h" @@ -15,7 +16,6 @@ #include "chrome/common/pepper_flash.h" #include "content/public/test/test_browser_thread.h" #include "ppapi/shared_impl/test_globals.h" - #include "testing/gtest/include/gtest/gtest.h" using content::BrowserThread; @@ -75,7 +75,7 @@ JSONFileValueDeserializer deserializer(manifest); std::string error; - scoped_ptr<base::DictionaryValue> root = + std::unique_ptr<base::DictionaryValue> root = base::DictionaryValue::From(deserializer.Deserialize(NULL, &error)); ASSERT_TRUE(root);
diff --git a/chrome/browser/component_updater/component_patcher_operation_out_of_process.cc b/chrome/browser/component_updater/component_patcher_operation_out_of_process.cc index 64257ac1..72ff040d 100644 --- a/chrome/browser/component_updater/component_patcher_operation_out_of_process.cc +++ b/chrome/browser/component_updater/component_patcher_operation_out_of_process.cc
@@ -30,7 +30,7 @@ PatchHost(base::Callback<void(int result)> callback, scoped_refptr<base::SequencedTaskRunner> task_runner); - void StartProcess(scoped_ptr<IPC::Message> message); + void StartProcess(std::unique_ptr<IPC::Message> message); private: ~PatchHost() override; @@ -54,7 +54,7 @@ PatchHost::~PatchHost() { } -void PatchHost::StartProcess(scoped_ptr<IPC::Message> message) { +void PatchHost::StartProcess(std::unique_ptr<IPC::Message> message) { // The DeltaUpdateOpPatchHost is not responsible for deleting the // UtilityProcessHost object. content::UtilityProcessHost* host = content::UtilityProcessHost::Create( @@ -102,7 +102,7 @@ const base::FilePath& output_abs_path, base::Callback<void(int result)> callback) { host_ = new PatchHost(callback, task_runner); - scoped_ptr<IPC::Message> patch_message; + std::unique_ptr<IPC::Message> patch_message; if (operation == update_client::kBsdiff) { patch_message.reset(new ChromeUtilityMsg_PatchFileBsdiff( input_abs_path, patch_abs_path, output_abs_path));
diff --git a/chrome/browser/component_updater/ev_whitelist_component_installer.cc b/chrome/browser/component_updater/ev_whitelist_component_installer.cc index c543611..8007b5a 100644 --- a/chrome/browser/component_updater/ev_whitelist_component_installer.cc +++ b/chrome/browser/component_updater/ev_whitelist_component_installer.cc
@@ -98,7 +98,7 @@ void EVWhitelistComponentInstallerTraits::ComponentReady( const base::Version& version, const base::FilePath& install_dir, - scoped_ptr<base::DictionaryValue> manifest) { + std::unique_ptr<base::DictionaryValue> manifest) { VLOG(1) << "Component ready, version " << version.GetString() << " in " << install_dir.value(); @@ -140,7 +140,7 @@ const base::FilePath& user_data_dir) { VLOG(1) << "Registering EV whitelist component."; - scoped_ptr<ComponentInstallerTraits> traits( + std::unique_ptr<ComponentInstallerTraits> traits( new EVWhitelistComponentInstallerTraits()); // |cus| will take ownership of |installer| during installer->Register(cus). DefaultComponentInstaller* installer =
diff --git a/chrome/browser/component_updater/ev_whitelist_component_installer.h b/chrome/browser/component_updater/ev_whitelist_component_installer.h index 99b5d18..72a1382b 100644 --- a/chrome/browser/component_updater/ev_whitelist_component_installer.h +++ b/chrome/browser/component_updater/ev_whitelist_component_installer.h
@@ -37,7 +37,7 @@ const base::FilePath& install_dir) const override; void ComponentReady(const base::Version& version, const base::FilePath& install_dir, - scoped_ptr<base::DictionaryValue> manifest) override; + std::unique_ptr<base::DictionaryValue> manifest) override; base::FilePath GetBaseDirectory() const override; void GetHash(std::vector<uint8_t>* hash) const override; std::string GetName() const override;
diff --git a/chrome/browser/component_updater/pnacl_component_installer.cc b/chrome/browser/component_updater/pnacl_component_installer.cc index 1eec3895..9319cf9 100644 --- a/chrome/browser/component_updater/pnacl_component_installer.cc +++ b/chrome/browser/component_updater/pnacl_component_installer.cc
@@ -128,7 +128,7 @@ base::DictionaryValue* ReadJSONManifest(const base::FilePath& manifest_path) { JSONFileValueDeserializer deserializer(manifest_path); std::string error; - scoped_ptr<base::Value> root = deserializer.Deserialize(NULL, &error); + std::unique_ptr<base::Value> root = deserializer.Deserialize(NULL, &error); if (!root.get()) return NULL; if (!root->IsType(base::Value::TYPE_DICTIONARY)) @@ -227,7 +227,7 @@ bool PnaclComponentInstaller::Install(const base::DictionaryValue& manifest, const base::FilePath& unpack_path) { - scoped_ptr<base::DictionaryValue> pnacl_manifest( + std::unique_ptr<base::DictionaryValue> pnacl_manifest( ReadPnaclManifest(unpack_path)); if (pnacl_manifest == NULL) { LOG(WARNING) << "Failed to read pnacl manifest."; @@ -329,8 +329,10 @@ std::string current_fingerprint; std::vector<base::FilePath> older_dirs; if (GetLatestPnaclDirectory(pci, &path, ¤t_version, &older_dirs)) { - scoped_ptr<base::DictionaryValue> manifest(ReadComponentManifest(path)); - scoped_ptr<base::DictionaryValue> pnacl_manifest(ReadPnaclManifest(path)); + std::unique_ptr<base::DictionaryValue> manifest( + ReadComponentManifest(path)); + std::unique_ptr<base::DictionaryValue> pnacl_manifest( + ReadPnaclManifest(path)); Version manifest_version; // Check that the component manifest and PNaCl manifest files // are legit, and that the indicated version matches the one
diff --git a/chrome/browser/component_updater/pnacl_component_installer.h b/chrome/browser/component_updater/pnacl_component_installer.h index 5b7e3cd..5e44209 100644 --- a/chrome/browser/component_updater/pnacl_component_installer.h +++ b/chrome/browser/component_updater/pnacl_component_installer.h
@@ -6,13 +6,13 @@ #define CHROME_BROWSER_COMPONENT_UPDATER_PNACL_COMPONENT_INSTALLER_H_ #include <list> +#include <memory> #include <string> #include "base/callback.h" #include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/version.h" #include "components/update_client/update_client.h"
diff --git a/chrome/browser/component_updater/recovery_component_installer.cc b/chrome/browser/component_updater/recovery_component_installer.cc index 41c61b3..26660c9 100644 --- a/chrome/browser/component_updater/recovery_component_installer.cc +++ b/chrome/browser/component_updater/recovery_component_installer.cc
@@ -5,6 +5,8 @@ #include "chrome/browser/component_updater/recovery_component_installer.h" #include <stdint.h> + +#include <memory> #include <string> #include "base/base_paths.h" @@ -14,7 +16,6 @@ #include "base/files/file_util.h" #include "base/json/json_file_value_serializer.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/histogram.h" #include "base/path_service.h" #include "base/process/kill.h" @@ -115,7 +116,8 @@ } #if defined(OS_WIN) -scoped_ptr<base::DictionaryValue> ReadManifest(const base::FilePath& manifest) { +std::unique_ptr<base::DictionaryValue> ReadManifest( + const base::FilePath& manifest) { JSONFileValueDeserializer deserializer(manifest); std::string error; return base::DictionaryValue::From(deserializer.Deserialize(NULL, &error)); @@ -142,7 +144,7 @@ if (!base::PathExists(main_file) || !base::PathExists(manifest_file)) return; - scoped_ptr<base::DictionaryValue> manifest(ReadManifest(manifest_file)); + std::unique_ptr<base::DictionaryValue> manifest(ReadManifest(manifest_file)); std::string name; manifest->GetStringASCII("name", &name); if (name != kRecoveryManifestName)
diff --git a/chrome/browser/component_updater/sth_set_component_installer.cc b/chrome/browser/component_updater/sth_set_component_installer.cc index 6c63be4..fc393cef 100644 --- a/chrome/browser/component_updater/sth_set_component_installer.cc +++ b/chrome/browser/component_updater/sth_set_component_installer.cc
@@ -49,7 +49,7 @@ const char kSTHSetFetcherManifestName[] = "Signed Tree Heads"; STHSetComponentInstallerTraits::STHSetComponentInstallerTraits( - scoped_ptr<net::ct::STHObserver> sth_observer) + std::unique_ptr<net::ct::STHObserver> sth_observer) : sth_observer_(std::move(sth_observer)) {} STHSetComponentInstallerTraits::~STHSetComponentInstallerTraits() {} @@ -72,7 +72,7 @@ void STHSetComponentInstallerTraits::ComponentReady( const base::Version& version, const base::FilePath& install_dir, - scoped_ptr<base::DictionaryValue> manifest) { + std::unique_ptr<base::DictionaryValue> manifest) { if (!content::BrowserThread::PostBlockingPoolTask( FROM_HERE, base::Bind(&STHSetComponentInstallerTraits::LoadSTHsFromDisk, @@ -156,7 +156,7 @@ void STHSetComponentInstallerTraits::OnJsonParseSuccess( const std::string& log_id, - scoped_ptr<base::Value> parsed_json) { + std::unique_ptr<base::Value> parsed_json) { net::ct::SignedTreeHead signed_tree_head; DVLOG(1) << "STH parsing success for log: " << base::HexEncode(log_id.data(), log_id.length()); @@ -187,10 +187,10 @@ // TODO(eranm): The next step in auditing CT logs (crbug.com/506227) is to // pass the distributor to the IOThread so it can be used in a per-profile // context for checking inclusion of SCTs. - scoped_ptr<net::ct::STHDistributor> distributor( + std::unique_ptr<net::ct::STHDistributor> distributor( new net::ct::STHDistributor()); - scoped_ptr<ComponentInstallerTraits> traits( + std::unique_ptr<ComponentInstallerTraits> traits( new STHSetComponentInstallerTraits(std::move(distributor))); // |cus| will take ownership of |installer| during installer->Register(cus). DefaultComponentInstaller* installer =
diff --git a/chrome/browser/component_updater/sth_set_component_installer.h b/chrome/browser/component_updater/sth_set_component_installer.h index d02061f0..ba3df76 100644 --- a/chrome/browser/component_updater/sth_set_component_installer.h +++ b/chrome/browser/component_updater/sth_set_component_installer.h
@@ -7,11 +7,11 @@ #include <stdint.h> +#include <memory> #include <string> #include <vector> #include "base/gtest_prod_util.h" -#include "base/memory/scoped_ptr.h" #include "components/component_updater/default_component_installer.h" namespace base { @@ -41,7 +41,7 @@ public: // The |sth_distributor| will be notified each time a new STH is observed. explicit STHSetComponentInstallerTraits( - scoped_ptr<net::ct::STHObserver> sth_observer); + std::unique_ptr<net::ct::STHObserver> sth_observer); ~STHSetComponentInstallerTraits() override; private: @@ -56,7 +56,7 @@ const base::FilePath& install_dir) const override; void ComponentReady(const base::Version& version, const base::FilePath& install_dir, - scoped_ptr<base::DictionaryValue> manifest) override; + std::unique_ptr<base::DictionaryValue> manifest) override; base::FilePath GetBaseDirectory() const override; void GetHash(std::vector<uint8_t>* hash) const override; std::string GetName() const override; @@ -68,12 +68,12 @@ // Handle successful parsing of JSON by distributing the new STH. void OnJsonParseSuccess(const std::string& log_id, - scoped_ptr<base::Value> parsed_json); + std::unique_ptr<base::Value> parsed_json); // STH parsing failed - do nothing. void OnJsonParseError(const std::string& log_id, const std::string& error); - scoped_ptr<net::ct::STHObserver> sth_observer_; + std::unique_ptr<net::ct::STHObserver> sth_observer_; DISALLOW_COPY_AND_ASSIGN(STHSetComponentInstallerTraits); };
diff --git a/chrome/browser/component_updater/sth_set_component_installer_unittest.cc b/chrome/browser/component_updater/sth_set_component_installer_unittest.cc index 4f2480b4..5b6b101 100644 --- a/chrome/browser/component_updater/sth_set_component_installer_unittest.cc +++ b/chrome/browser/component_updater/sth_set_component_installer_unittest.cc
@@ -5,13 +5,13 @@ #include "chrome/browser/component_updater/sth_set_component_installer.h" #include <map> +#include <memory> #include <string> #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -44,7 +44,7 @@ ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - scoped_ptr<StoringSTHObserver> observer(new StoringSTHObserver()); + std::unique_ptr<StoringSTHObserver> observer(new StoringSTHObserver()); observer_ = observer.get(); traits_.reset(new STHSetComponentInstallerTraits(std::move(observer))); } @@ -82,7 +82,7 @@ content::TestBrowserThreadBundle thread_bundle_; base::ScopedTempDir temp_dir_; - scoped_ptr<STHSetComponentInstallerTraits> traits_; + std::unique_ptr<STHSetComponentInstallerTraits> traits_; StoringSTHObserver* observer_; safe_json::TestingJsonParser::ScopedFactoryOverride factory_override_;
diff --git a/chrome/browser/component_updater/supervised_user_whitelist_installer.cc b/chrome/browser/component_updater/supervised_user_whitelist_installer.cc index 323bfbc..1636411f 100644 --- a/chrome/browser/component_updater/supervised_user_whitelist_installer.cc +++ b/chrome/browser/component_updater/supervised_user_whitelist_installer.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/component_updater/supervised_user_whitelist_installer.h" #include <stddef.h> + #include <map> #include <utility> @@ -16,6 +17,7 @@ #include "base/files/important_file_writer.h" #include "base/location.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" #include "base/metrics/user_metrics.h" #include "base/metrics/user_metrics_action.h" @@ -254,7 +256,7 @@ const base::FilePath& install_dir) override; void ComponentReady(const base::Version& version, const base::FilePath& install_dir, - scoped_ptr<base::DictionaryValue> manifest) override; + std::unique_ptr<base::DictionaryValue> manifest) override; base::FilePath GetBaseDirectory() const override; void GetHash(std::vector<uint8_t>* hash) const override; std::string GetName() const override; @@ -294,7 +296,7 @@ void SupervisedUserWhitelistComponentInstallerTraits::ComponentReady( const base::Version& version, const base::FilePath& install_dir, - scoped_ptr<base::DictionaryValue> manifest) { + std::unique_ptr<base::DictionaryValue> manifest) { // TODO(treib): Before getting the title, we should localize the manifest // using extension_l10n_util::LocalizeExtension, but that doesn't exist on // Android. crbug.com/558387 @@ -392,7 +394,7 @@ const std::string& crx_id, const std::string& name, const base::Closure& callback) { - scoped_ptr<ComponentInstallerTraits> traits( + std::unique_ptr<ComponentInstallerTraits> traits( new SupervisedUserWhitelistComponentInstallerTraits( crx_id, name, base::Bind(&SupervisedUserWhitelistInstallerImpl::OnRawWhitelistReady, @@ -582,12 +584,12 @@ } // namespace // static -scoped_ptr<SupervisedUserWhitelistInstaller> +std::unique_ptr<SupervisedUserWhitelistInstaller> SupervisedUserWhitelistInstaller::Create( ComponentUpdateService* cus, ProfileAttributesStorage* profile_attributes_storage, PrefService* local_state) { - return make_scoped_ptr(new SupervisedUserWhitelistInstallerImpl( + return base::WrapUnique(new SupervisedUserWhitelistInstallerImpl( cus, profile_attributes_storage, local_state)); }
diff --git a/chrome/browser/component_updater/supervised_user_whitelist_installer.h b/chrome/browser/component_updater/supervised_user_whitelist_installer.h index 47ea4c66..5137442 100644 --- a/chrome/browser/component_updater/supervised_user_whitelist_installer.h +++ b/chrome/browser/component_updater/supervised_user_whitelist_installer.h
@@ -7,12 +7,12 @@ #include <stdint.h> +#include <memory> #include <set> #include <string> #include <vector> #include "base/callback_forward.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" namespace base { @@ -38,7 +38,7 @@ virtual ~SupervisedUserWhitelistInstaller() {} - static scoped_ptr<SupervisedUserWhitelistInstaller> Create( + static std::unique_ptr<SupervisedUserWhitelistInstaller> Create( ComponentUpdateService* cus, ProfileAttributesStorage* profile_attributes_storage, PrefService* local_state);
diff --git a/chrome/browser/component_updater/supervised_user_whitelist_installer_unittest.cc b/chrome/browser/component_updater/supervised_user_whitelist_installer_unittest.cc index a45fb3a3..81ab714 100644 --- a/chrome/browser/component_updater/supervised_user_whitelist_installer_unittest.cc +++ b/chrome/browser/component_updater/supervised_user_whitelist_installer_unittest.cc
@@ -151,7 +151,7 @@ private: scoped_refptr<base::SequencedTaskRunner> task_runner_; - scoped_ptr<CrxComponent> component_; + std::unique_ptr<CrxComponent> component_; base::Closure registration_callback_; bool on_demand_update_called_; }; @@ -228,21 +228,22 @@ whitelist_path_ = installed_whitelist_directory_.AppendASCII(crx_id + ".json"); - scoped_ptr<base::DictionaryValue> whitelist_dict( + std::unique_ptr<base::DictionaryValue> whitelist_dict( new base::DictionaryValue); whitelist_dict->SetString("sites", kWhitelistFile); manifest_.Set("whitelisted_content", whitelist_dict.release()); large_icon_path_ = whitelist_version_directory_.AppendASCII(kLargeIconFile); - scoped_ptr<base::DictionaryValue> icons_dict(new base::DictionaryValue); + std::unique_ptr<base::DictionaryValue> icons_dict( + new base::DictionaryValue); icons_dict->SetString("128", kLargeIconFile); manifest_.Set("icons", icons_dict.release()); manifest_.SetString("version", kVersion); - scoped_ptr<base::DictionaryValue> crx_dict(new base::DictionaryValue); + std::unique_ptr<base::DictionaryValue> crx_dict(new base::DictionaryValue); crx_dict->SetString("name", kName); - scoped_ptr<base::ListValue> clients(new base::ListValue); + std::unique_ptr<base::ListValue> clients(new base::ListValue); clients->AppendString(kClientId); clients->AppendString(kOtherClientId); crx_dict->Set("clients", clients.release()); @@ -293,7 +294,7 @@ safe_json::TestingJsonParser::ScopedFactoryOverride json_parser_override_; MockComponentUpdateService component_update_service_; TestingPrefServiceSimple local_state_; - scoped_ptr<SupervisedUserWhitelistInstaller> installer_; + std::unique_ptr<SupervisedUserWhitelistInstaller> installer_; base::FilePath whitelist_base_directory_; base::FilePath whitelist_directory_; base::FilePath whitelist_version_directory_;
diff --git a/chrome/browser/component_updater/sw_reporter_installer_win.cc b/chrome/browser/component_updater/sw_reporter_installer_win.cc index 7d930fc..d3ffde3 100644 --- a/chrome/browser/component_updater/sw_reporter_installer_win.cc +++ b/chrome/browser/component_updater/sw_reporter_installer_win.cc
@@ -122,9 +122,10 @@ return true; } - void ComponentReady(const base::Version& version, - const base::FilePath& install_dir, - scoped_ptr<base::DictionaryValue> manifest) override { + void ComponentReady( + const base::Version& version, + const base::FilePath& install_dir, + std::unique_ptr<base::DictionaryValue> manifest) override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); safe_browsing::RunSwReporter(install_dir.Append(kSwReporterExeName), version, base::ThreadTaskRunnerHandle::Get(), @@ -240,7 +241,8 @@ } // Install the component. - scoped_ptr<ComponentInstallerTraits> traits(new SwReporterInstallerTraits()); + std::unique_ptr<ComponentInstallerTraits> traits( + new SwReporterInstallerTraits()); // |cus| will take ownership of |installer| during installer->Register(cus). DefaultComponentInstaller* installer = new DefaultComponentInstaller(std::move(traits));
diff --git a/chrome/browser/component_updater/widevine_cdm_component_installer.cc b/chrome/browser/component_updater/widevine_cdm_component_installer.cc index 8458acf..134abb7 100644 --- a/chrome/browser/component_updater/widevine_cdm_component_installer.cc +++ b/chrome/browser/component_updater/widevine_cdm_component_installer.cc
@@ -200,9 +200,10 @@ } } -void RegisterWidevineCdmWithChrome(const base::Version& cdm_version, - const base::FilePath& adapter_install_path, - scoped_ptr<base::DictionaryValue> manifest) { +void RegisterWidevineCdmWithChrome( + const base::Version& cdm_version, + const base::FilePath& adapter_install_path, + std::unique_ptr<base::DictionaryValue> manifest) { DCHECK_CURRENTLY_ON(BrowserThread::UI); std::vector<base::string16> additional_param_names; std::vector<base::string16> additional_param_values; @@ -242,10 +243,9 @@ bool VerifyInstallation( const base::DictionaryValue& manifest, const base::FilePath& install_dir) const override; - void ComponentReady( - const base::Version& version, - const base::FilePath& path, - scoped_ptr<base::DictionaryValue> manifest) override; + void ComponentReady(const base::Version& version, + const base::FilePath& path, + std::unique_ptr<base::DictionaryValue> manifest) override; base::FilePath GetBaseDirectory() const override; void GetHash(std::vector<uint8_t>* hash) const override; std::string GetName() const override; @@ -258,7 +258,7 @@ // VerifyInstallation). void UpdateCdmAdapter(const base::Version& cdm_version, const base::FilePath& cdm_install_dir, - scoped_ptr<base::DictionaryValue> manifest); + std::unique_ptr<base::DictionaryValue> manifest); DISALLOW_COPY_AND_ASSIGN(WidevineCdmComponentInstallerTraits); }; @@ -284,7 +284,7 @@ void WidevineCdmComponentInstallerTraits::ComponentReady( const base::Version& version, const base::FilePath& path, - scoped_ptr<base::DictionaryValue> manifest) { + std::unique_ptr<base::DictionaryValue> manifest) { if (!IsCompatibleWithChrome(*manifest)) { VLOG(1) << "Installed Widevine CDM component is incompatible."; return; @@ -331,7 +331,7 @@ void WidevineCdmComponentInstallerTraits::UpdateCdmAdapter( const base::Version& cdm_version, const base::FilePath& cdm_install_dir, - scoped_ptr<base::DictionaryValue> manifest) { + std::unique_ptr<base::DictionaryValue> manifest) { const base::FilePath adapter_version_path = GetPlatformDirectory(cdm_install_dir).AppendASCII(kCdmAdapterVersionName); const base::FilePath adapter_install_path = @@ -380,7 +380,7 @@ PathService::Get(chrome::FILE_WIDEVINE_CDM_ADAPTER, &adapter_source_path); if (!base::PathExists(adapter_source_path)) return; - scoped_ptr<ComponentInstallerTraits> traits( + std::unique_ptr<ComponentInstallerTraits> traits( new WidevineCdmComponentInstallerTraits); // |cus| will take ownership of |installer| during installer->Register(cus). DefaultComponentInstaller* installer =
diff --git a/chrome/browser/content_settings/chrome_content_settings_client.cc b/chrome/browser/content_settings/chrome_content_settings_client.cc index 40c49f7..26666c6e 100644 --- a/chrome/browser/content_settings/chrome_content_settings_client.cc +++ b/chrome/browser/content_settings/chrome_content_settings_client.cc
@@ -74,7 +74,7 @@ return blocked_local_shared_objects_; } -scoped_ptr<CookiesTreeModel> +std::unique_ptr<CookiesTreeModel> ChromeContentSettingsClient::CreateCookiesTreeModel(AccessType type) const { switch (type) { case ALLOWED: @@ -85,7 +85,7 @@ // Some compilers don't believe this is not reachable, so let's return a dummy // value. NOTREACHED(); - return scoped_ptr<CookiesTreeModel>(); + return std::unique_ptr<CookiesTreeModel>(); } ChromeContentSettingsClient::ChromeContentSettingsClient(
diff --git a/chrome/browser/content_settings/chrome_content_settings_client.h b/chrome/browser/content_settings/chrome_content_settings_client.h index 3e33275c..6fdf9f1 100644 --- a/chrome/browser/content_settings/chrome_content_settings_client.h +++ b/chrome/browser/content_settings/chrome_content_settings_client.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_CONTENT_SETTINGS_CHROME_CONTENT_SETTINGS_CLIENT_H_ #define CHROME_BROWSER_CONTENT_SETTINGS_CHROME_CONTENT_SETTINGS_CLIENT_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/browsing_data/cookies_tree_model.h" #include "chrome/browser/content_settings/local_shared_objects_container.h" #include "components/content_settings/core/browser/content_settings_client.h" @@ -45,7 +46,8 @@ // Creates a new copy of a CookiesTreeModel for all allowed (or blocked, // depending on |type|) local shared objects. - scoped_ptr<CookiesTreeModel> CreateCookiesTreeModel(AccessType type) const; + std::unique_ptr<CookiesTreeModel> CreateCookiesTreeModel( + AccessType type) const; private: friend class content::WebContentsUserData<ChromeContentSettingsClient>;
diff --git a/chrome/browser/content_settings/content_settings_default_provider_unittest.cc b/chrome/browser/content_settings/content_settings_default_provider_unittest.cc index 6283f11a..cba972c 100644 --- a/chrome/browser/content_settings/content_settings_default_provider_unittest.cc +++ b/chrome/browser/content_settings/content_settings_default_provider_unittest.cc
@@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "base/message_loop/message_loop.h" #include "chrome/browser/content_settings/content_settings_mock_observer.h" #include "chrome/common/pref_names.h" @@ -68,7 +69,7 @@ CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string(), false)); - scoped_ptr<base::Value> value(TestUtils::GetContentSettingValue( + std::unique_ptr<base::Value> value(TestUtils::GetContentSettingValue( &provider_, GURL("http://example.com/"), GURL("http://example.com/"), CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE, std::string(), false)); EXPECT_FALSE(value.get()); @@ -82,7 +83,7 @@ TestUtils::GetContentSetting(&provider_, primary_url, secondary_url, CONTENT_SETTINGS_TYPE_COOKIES, std::string(), false)); - scoped_ptr<base::Value> value( + std::unique_ptr<base::Value> value( new base::FundamentalValue(CONTENT_SETTING_BLOCK)); bool owned = provider_.SetWebsiteSetting( ContentSettingsPattern::FromURL(primary_url), @@ -182,7 +183,7 @@ std::string(), true /* include_incognito */)); // Changing content settings on the incognito provider should be ignored. - scoped_ptr<base::Value> value( + std::unique_ptr<base::Value> value( new base::FundamentalValue(CONTENT_SETTING_ALLOW)); bool owned = otr_provider.SetWebsiteSetting( ContentSettingsPattern::Wildcard(),
diff --git a/chrome/browser/content_settings/content_settings_internal_extension_provider.cc b/chrome/browser/content_settings/content_settings_internal_extension_provider.cc index 0a5891eb..239039fc 100644 --- a/chrome/browser/content_settings/content_settings_internal_extension_provider.cc +++ b/chrome/browser/content_settings/content_settings_internal_extension_provider.cc
@@ -63,7 +63,7 @@ DCHECK(!registrar_.get()); } -scoped_ptr<RuleIterator> InternalExtensionProvider::GetRuleIterator( +std::unique_ptr<RuleIterator> InternalExtensionProvider::GetRuleIterator( ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, bool incognito) const { @@ -195,7 +195,7 @@ const extensions::Extension* extension, const ResourceIdentifier& resource, ContentSetting setting) { - scoped_ptr<ContentSettingsPattern::BuilderInterface> pattern_builder( + std::unique_ptr<ContentSettingsPattern::BuilderInterface> pattern_builder( ContentSettingsPattern::CreateBuilder(false)); pattern_builder->WithScheme(extensions::kExtensionScheme); pattern_builder->WithHost(extension->id());
diff --git a/chrome/browser/content_settings/content_settings_internal_extension_provider.h b/chrome/browser/content_settings/content_settings_internal_extension_provider.h index 39ca41d7..c38383a 100644 --- a/chrome/browser/content_settings/content_settings_internal_extension_provider.h +++ b/chrome/browser/content_settings/content_settings_internal_extension_provider.h
@@ -5,11 +5,11 @@ #ifndef CHROME_BROWSER_CONTENT_SETTINGS_CONTENT_SETTINGS_INTERNAL_EXTENSION_PROVIDER_H_ #define CHROME_BROWSER_CONTENT_SETTINGS_CONTENT_SETTINGS_INTERNAL_EXTENSION_PROVIDER_H_ +#include <memory> #include <set> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/synchronization/lock.h" #include "components/content_settings/core/browser/content_settings_observable_provider.h" #include "components/content_settings/core/browser/content_settings_origin_identifier_value_map.h" @@ -37,7 +37,7 @@ ~InternalExtensionProvider() override; // ProviderInterface methods: - scoped_ptr<RuleIterator> GetRuleIterator( + std::unique_ptr<RuleIterator> GetRuleIterator( ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, bool incognito) const override; @@ -80,7 +80,7 @@ // Used around accesses to the |value_map_| list to guarantee thread safety. mutable base::Lock lock_; - scoped_ptr<content::NotificationRegistrar> registrar_; + std::unique_ptr<content::NotificationRegistrar> registrar_; // Extension IDs used by the Chrome Remote Desktop app. std::set<std::string> chrome_remote_desktop_;
diff --git a/chrome/browser/content_settings/content_settings_origin_identifier_value_map_unittest.cc b/chrome/browser/content_settings/content_settings_origin_identifier_value_map_unittest.cc index 96bcc4e..7ac0d44 100644 --- a/chrome/browser/content_settings/content_settings_origin_identifier_value_map_unittest.cc +++ b/chrome/browser/content_settings/content_settings_origin_identifier_value_map_unittest.cc
@@ -4,7 +4,8 @@ #include "components/content_settings/core/browser/content_settings_origin_identifier_value_map.h" -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "base/values.h" #include "components/content_settings/core/browser/content_settings_rule.h" #include "components/content_settings/core/browser/content_settings_utils.h" @@ -25,7 +26,7 @@ std::string(), new base::FundamentalValue(1)); - scoped_ptr<base::Value> expected_value(new base::FundamentalValue(1)); + std::unique_ptr<base::Value> expected_value(new base::FundamentalValue(1)); EXPECT_TRUE(expected_value->Equals(map.GetValue(GURL("http://www.google.com"), GURL("http://www.google.com"), CONTENT_SETTINGS_TYPE_COOKIES, @@ -172,7 +173,7 @@ TEST(OriginIdentifierValueMapTest, IterateEmpty) { content_settings::OriginIdentifierValueMap map; - scoped_ptr<content_settings::RuleIterator> rule_iterator( + std::unique_ptr<content_settings::RuleIterator> rule_iterator( map.GetRuleIterator(CONTENT_SETTINGS_TYPE_COOKIES, std::string(), NULL)); EXPECT_FALSE(rule_iterator->HasNext()); } @@ -195,7 +196,7 @@ std::string(), new base::FundamentalValue(2)); - scoped_ptr<content_settings::RuleIterator> rule_iterator( + std::unique_ptr<content_settings::RuleIterator> rule_iterator( map.GetRuleIterator(CONTENT_SETTINGS_TYPE_COOKIES, std::string(), NULL)); ASSERT_TRUE(rule_iterator->HasNext()); content_settings::Rule rule = rule_iterator->Next();
diff --git a/chrome/browser/content_settings/content_settings_policy_provider_unittest.cc b/chrome/browser/content_settings/content_settings_policy_provider_unittest.cc index 5ed0ab4..f287af6 100644 --- a/chrome/browser/content_settings/content_settings_policy_provider_unittest.cc +++ b/chrome/browser/content_settings/content_settings_policy_provider_unittest.cc
@@ -4,11 +4,11 @@ #include "components/content_settings/core/browser/content_settings_policy_provider.h" +#include <memory> #include <string> #include "base/auto_reset.h" #include "base/command_line.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "chrome/browser/content_settings/content_settings_mock_observer.h" #include "chrome/common/chrome_switches.h" @@ -43,11 +43,8 @@ Rules rules; - scoped_ptr<RuleIterator> rule_iterator( - provider.GetRuleIterator( - CONTENT_SETTINGS_TYPE_GEOLOCATION, - std::string(), - false)); + std::unique_ptr<RuleIterator> rule_iterator(provider.GetRuleIterator( + CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string(), false)); EXPECT_FALSE(rule_iterator->HasNext()); // Change the managed value of the default geolocation setting @@ -76,11 +73,8 @@ prefs->SetManagedPref(prefs::kManagedDefaultPluginsSetting, new base::FundamentalValue(CONTENT_SETTING_BLOCK)); - scoped_ptr<RuleIterator> rule_iterator( - provider.GetRuleIterator( - CONTENT_SETTINGS_TYPE_PLUGINS, - std::string(), - false)); + std::unique_ptr<RuleIterator> rule_iterator(provider.GetRuleIterator( + CONTENT_SETTINGS_TYPE_PLUGINS, std::string(), false)); EXPECT_TRUE(rule_iterator->HasNext()); Rule rule = rule_iterator->Next(); EXPECT_FALSE(rule_iterator->HasNext()); @@ -152,7 +146,7 @@ TestUtils::GetContentSetting(&provider, google_url, google_url, CONTENT_SETTINGS_TYPE_IMAGES, std::string(), false)); - scoped_ptr<base::Value> value_ptr(TestUtils::GetContentSettingValue( + std::unique_ptr<base::Value> value_ptr(TestUtils::GetContentSettingValue( &provider, google_url, google_url, CONTENT_SETTINGS_TYPE_IMAGES, std::string(), false)); @@ -163,7 +157,7 @@ // The PolicyProvider does not allow setting content settings as they are // enforced via policies and not set by the user or extension. So a call to // SetWebsiteSetting does nothing. - scoped_ptr<base::Value> value_block( + std::unique_ptr<base::Value> value_block( new base::FundamentalValue(CONTENT_SETTING_BLOCK)); bool owned = provider.SetWebsiteSetting(yt_url_pattern, yt_url_pattern, @@ -241,7 +235,7 @@ &provider, youtube_url, youtube_url, CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE, std::string(), false)); - scoped_ptr<base::Value> cert_filter(TestUtils::GetContentSettingValue( + std::unique_ptr<base::Value> cert_filter(TestUtils::GetContentSettingValue( &provider, google_url, google_url, CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE, std::string(), false));
diff --git a/chrome/browser/content_settings/content_settings_pref_provider_unittest.cc b/chrome/browser/content_settings/content_settings_pref_provider_unittest.cc index 7bd4b66..0d31af29 100644 --- a/chrome/browser/content_settings/content_settings_pref_provider_unittest.cc +++ b/chrome/browser/content_settings/content_settings_pref_provider_unittest.cc
@@ -4,10 +4,12 @@ #include "components/content_settings/core/browser/content_settings_pref_provider.h" +#include <memory> + #include "base/auto_reset.h" #include "base/command_line.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/test/simple_test_clock.h" #include "base/threading/platform_thread.h" @@ -160,11 +162,11 @@ chrome::RegisterUserProfilePrefs(otr_registry.get()); TestingProfile::Builder profile_builder; - profile_builder.SetPrefService(make_scoped_ptr(regular_prefs)); - scoped_ptr<TestingProfile> profile = profile_builder.Build(); + profile_builder.SetPrefService(base::WrapUnique(regular_prefs)); + std::unique_ptr<TestingProfile> profile = profile_builder.Build(); TestingProfile::Builder otr_profile_builder; - otr_profile_builder.SetPrefService(make_scoped_ptr(otr_prefs)); + otr_profile_builder.SetPrefService(base::WrapUnique(otr_prefs)); otr_profile_builder.BuildIncognito(profile.get()); PrefProvider pref_content_settings_provider(regular_prefs, false); @@ -224,7 +226,7 @@ TestUtils::GetContentSetting(&provider, primary_url, primary_url, CONTENT_SETTINGS_TYPE_IMAGES, std::string(), false)); - scoped_ptr<base::Value> value_ptr(TestUtils::GetContentSettingValue( + std::unique_ptr<base::Value> value_ptr(TestUtils::GetContentSettingValue( &provider, primary_url, primary_url, CONTENT_SETTINGS_TYPE_IMAGES, std::string(), false)); int int_value = -1; @@ -376,7 +378,7 @@ test_clock->SetNow(base::Time::Now()); pref_content_settings_provider.SetClockForTesting( - scoped_ptr<base::Clock>(test_clock)); + std::unique_ptr<base::Clock>(test_clock)); GURL host("http://example.com/"); ContentSettingsPattern pattern = ContentSettingsPattern::FromString("[*.]example.com"); @@ -413,7 +415,7 @@ ContentSettingsPattern::FromString("www.google.com"); ContentSettingsPattern wildcard = ContentSettingsPattern::FromString("*"); - scoped_ptr<base::Value> value( + std::unique_ptr<base::Value> value( new base::FundamentalValue(CONTENT_SETTING_ALLOW)); // Create a normal provider and set a setting. @@ -426,7 +428,7 @@ // Non-OTR provider, Non-OTR iterator has one setting (pattern 1). { - scoped_ptr<RuleIterator> it(normal_provider.GetRuleIterator( + std::unique_ptr<RuleIterator> it(normal_provider.GetRuleIterator( CONTENT_SETTINGS_TYPE_IMAGES, std::string(), false)); EXPECT_TRUE(it->HasNext()); EXPECT_EQ(pattern_1, it->Next().primary_pattern); @@ -435,7 +437,7 @@ // Non-OTR provider, OTR iterator has no settings. { - scoped_ptr<RuleIterator> it(normal_provider.GetRuleIterator( + std::unique_ptr<RuleIterator> it(normal_provider.GetRuleIterator( CONTENT_SETTINGS_TYPE_IMAGES, std::string(), true)); EXPECT_FALSE(it->HasNext()); } @@ -450,7 +452,7 @@ // OTR provider, non-OTR iterator has one setting (pattern 1). { - scoped_ptr<RuleIterator> it(incognito_provider.GetRuleIterator( + std::unique_ptr<RuleIterator> it(incognito_provider.GetRuleIterator( CONTENT_SETTINGS_TYPE_IMAGES, std::string(), false)); EXPECT_TRUE(it->HasNext()); EXPECT_EQ(pattern_1, it->Next().primary_pattern); @@ -459,7 +461,7 @@ // OTR provider, OTR iterator has one setting (pattern 2). { - scoped_ptr<RuleIterator> it(incognito_provider.GetRuleIterator( + std::unique_ptr<RuleIterator> it(incognito_provider.GetRuleIterator( CONTENT_SETTINGS_TYPE_IMAGES, std::string(), true)); EXPECT_TRUE(it->HasNext()); EXPECT_EQ(pattern_2, it->Next().primary_pattern); @@ -478,7 +480,7 @@ ContentSettingsPattern::FromString("google.com"); ContentSettingsPattern wildcard = ContentSettingsPattern::FromString("*"); - scoped_ptr<base::Value> value( + std::unique_ptr<base::Value> value( new base::FundamentalValue(CONTENT_SETTING_ALLOW)); ResourceIdentifier res_id("abcde");
diff --git a/chrome/browser/content_settings/content_settings_supervised_provider.cc b/chrome/browser/content_settings/content_settings_supervised_provider.cc index 6a199a5..75cfcd21 100644 --- a/chrome/browser/content_settings/content_settings_supervised_provider.cc +++ b/chrome/browser/content_settings/content_settings_supervised_provider.cc
@@ -52,11 +52,11 @@ SupervisedProvider::~SupervisedProvider() { } -scoped_ptr<RuleIterator> SupervisedProvider::GetRuleIterator( +std::unique_ptr<RuleIterator> SupervisedProvider::GetRuleIterator( ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, bool incognito) const { - scoped_ptr<base::AutoLock> auto_lock(new base::AutoLock(lock_)); + std::unique_ptr<base::AutoLock> auto_lock(new base::AutoLock(lock_)); return value_map_.GetRuleIterator(content_type, resource_identifier, std::move(auto_lock)); }
diff --git a/chrome/browser/content_settings/content_settings_supervised_provider.h b/chrome/browser/content_settings/content_settings_supervised_provider.h index 9a01168d..942ff23 100644 --- a/chrome/browser/content_settings/content_settings_supervised_provider.h +++ b/chrome/browser/content_settings/content_settings_supervised_provider.h
@@ -27,7 +27,7 @@ ~SupervisedProvider() override; // ProviderInterface implementations. - scoped_ptr<RuleIterator> GetRuleIterator( + std::unique_ptr<RuleIterator> GetRuleIterator( ContentSettingsType content_type, const ResourceIdentifier& resource_identifier, bool incognito) const override; @@ -52,8 +52,9 @@ // thread safety. mutable base::Lock lock_; - scoped_ptr<base::CallbackList<void( - const base::DictionaryValue*)>::Subscription> user_settings_subscription_; + std::unique_ptr< + base::CallbackList<void(const base::DictionaryValue*)>::Subscription> + user_settings_subscription_; DISALLOW_COPY_AND_ASSIGN(SupervisedProvider); };
diff --git a/chrome/browser/content_settings/content_settings_supervised_provider_unittest.cc b/chrome/browser/content_settings/content_settings_supervised_provider_unittest.cc index d0199af..726ed496 100644 --- a/chrome/browser/content_settings/content_settings_supervised_provider_unittest.cc +++ b/chrome/browser/content_settings/content_settings_supervised_provider_unittest.cc
@@ -4,9 +4,9 @@ #include "chrome/browser/content_settings/content_settings_supervised_provider.h" +#include <memory> #include <string> -#include "base/memory/scoped_ptr.h" #include "chrome/browser/content_settings/content_settings_mock_observer.h" #include "chrome/browser/supervised_user/supervised_user_constants.h" #include "chrome/browser/supervised_user/supervised_user_settings_service.h" @@ -29,7 +29,7 @@ protected: SupervisedUserSettingsService service_; scoped_refptr<TestingPrefStore> pref_store_; - scoped_ptr<SupervisedProvider> provider_; + std::unique_ptr<SupervisedProvider> provider_; content_settings::MockObserver mock_observer_; }; @@ -49,7 +49,7 @@ } TEST_F(SupervisedUserProviderTest, GeolocationTest) { - scoped_ptr<RuleIterator> rule_iterator(provider_->GetRuleIterator( + std::unique_ptr<RuleIterator> rule_iterator(provider_->GetRuleIterator( CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string(), false)); EXPECT_FALSE(rule_iterator->HasNext()); rule_iterator.reset(); @@ -59,7 +59,7 @@ _, _, CONTENT_SETTINGS_TYPE_GEOLOCATION, "")); service_.SetLocalSetting( supervised_users::kGeolocationDisabled, - scoped_ptr<base::Value>(new base::FundamentalValue(true))); + std::unique_ptr<base::Value>(new base::FundamentalValue(true))); rule_iterator = provider_->GetRuleIterator(CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string(), false); @@ -77,7 +77,7 @@ _, _, CONTENT_SETTINGS_TYPE_GEOLOCATION, "")); service_.SetLocalSetting( supervised_users::kGeolocationDisabled, - scoped_ptr<base::Value>(new base::FundamentalValue(false))); + std::unique_ptr<base::Value>(new base::FundamentalValue(false))); rule_iterator = provider_->GetRuleIterator(CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string(), false); @@ -85,7 +85,7 @@ } TEST_F(SupervisedUserProviderTest, CameraMicTest) { - scoped_ptr<RuleIterator> rule_iterator(provider_->GetRuleIterator( + std::unique_ptr<RuleIterator> rule_iterator(provider_->GetRuleIterator( CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA, std::string(), false)); EXPECT_FALSE(rule_iterator->HasNext()); rule_iterator.reset(); @@ -103,7 +103,7 @@ OnContentSettingChanged(_, _, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC, "")); service_.SetLocalSetting( supervised_users::kCameraMicDisabled, - scoped_ptr<base::Value>(new base::FundamentalValue(true))); + std::unique_ptr<base::Value>(new base::FundamentalValue(true))); rule_iterator = provider_->GetRuleIterator( CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA, std::string(), false); @@ -136,7 +136,7 @@ OnContentSettingChanged(_, _, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC, "")); service_.SetLocalSetting( supervised_users::kCameraMicDisabled, - scoped_ptr<base::Value>(new base::FundamentalValue(false))); + std::unique_ptr<base::Value>(new base::FundamentalValue(false))); rule_iterator = provider_->GetRuleIterator( CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA, std::string(), false);
diff --git a/chrome/browser/content_settings/host_content_settings_map_factory.cc b/chrome/browser/content_settings/host_content_settings_map_factory.cc index c95b1049..a96b421 100644 --- a/chrome/browser/content_settings/host_content_settings_map_factory.cc +++ b/chrome/browser/content_settings/host_content_settings_map_factory.cc
@@ -85,7 +85,7 @@ SupervisedUserSettingsServiceFactory::GetForProfile(profile); // This may be null in testing. if (supervised_service) { - scoped_ptr<content_settings::SupervisedProvider> supervised_provider( + std::unique_ptr<content_settings::SupervisedProvider> supervised_provider( new content_settings::SupervisedProvider(supervised_service)); settings_map->RegisterProvider(HostContentSettingsMap::SUPERVISED_PROVIDER, std::move(supervised_provider));
diff --git a/chrome/browser/content_settings/host_content_settings_map_unittest.cc b/chrome/browser/content_settings/host_content_settings_map_unittest.cc index 8347f04..b890f95 100644 --- a/chrome/browser/content_settings/host_content_settings_map_unittest.cc +++ b/chrome/browser/content_settings/host_content_settings_map_unittest.cc
@@ -340,7 +340,7 @@ PrefService* prefs = profile.GetPrefs(); // Make a copy of the default pref value so we can reset it later. - scoped_ptr<base::Value> default_value( + std::unique_ptr<base::Value> default_value( prefs->FindPreference(GetPrefName(CONTENT_SETTINGS_TYPE_IMAGES)) ->GetValue() ->DeepCopy()); @@ -359,7 +359,7 @@ host, host, CONTENT_SETTINGS_TYPE_IMAGES, std::string())); // Make a copy of the pref's new value so we can reset it later. - scoped_ptr<base::Value> new_value( + std::unique_ptr<base::Value> new_value( prefs->FindPreference(GetPrefName(CONTENT_SETTINGS_TYPE_IMAGES)) ->GetValue() ->DeepCopy()); @@ -763,7 +763,7 @@ test_value.DeepCopy()); // The setting is not inherted by |otr_map|. - scoped_ptr<base::Value> stored_value = + std::unique_ptr<base::Value> stored_value = host_content_settings_map->GetWebsiteSetting( host, host, CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA, std::string(), nullptr); @@ -808,12 +808,12 @@ TEST_F(HostContentSettingsMapTest, CanonicalizeExceptionsUnicodeAndPunycode) { TestingProfile profile; - scoped_ptr<base::Value> value = + std::unique_ptr<base::Value> value = base::JSONReader::Read("{\"[*.]\\xC4\\x87ira.com,*\":{\"setting\":1}}"); profile.GetPrefs()->Set(GetPrefName(CONTENT_SETTINGS_TYPE_COOKIES), *value); // Set punycode equivalent, with different setting. - scoped_ptr<base::Value> puny_value = + std::unique_ptr<base::Value> puny_value = base::JSONReader::Read("{\"[*.]xn--ira-ppa.com,*\":{\"setting\":2}}"); profile.GetPrefs()->Set(GetPrefName(CONTENT_SETTINGS_TYPE_COOKIES), *puny_value); @@ -1129,7 +1129,7 @@ profile.SetGuestSession(true); // Set a pref manually in the guest profile. - scoped_ptr<base::Value> value = + std::unique_ptr<base::Value> value = base::JSONReader::Read("{\"[*.]\\xC4\\x87ira.com,*\":{\"setting\":1}}"); profile.GetPrefs()->Set(GetPrefName(CONTENT_SETTINGS_TYPE_IMAGES), *value);
diff --git a/chrome/browser/content_settings/local_shared_objects_container.cc b/chrome/browser/content_settings/local_shared_objects_container.cc index 29598c1..7327d2a3 100644 --- a/chrome/browser/content_settings/local_shared_objects_container.cc +++ b/chrome/browser/content_settings/local_shared_objects_container.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/content_settings/local_shared_objects_container.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/browsing_data/browsing_data_appcache_helper.h" #include "chrome/browser/browsing_data/browsing_data_cache_storage_helper.h" #include "chrome/browser/browsing_data/browsing_data_channel_id_helper.h" @@ -216,12 +217,12 @@ session_storages_->Reset(); } -scoped_ptr<CookiesTreeModel> +std::unique_ptr<CookiesTreeModel> LocalSharedObjectsContainer::CreateCookiesTreeModel() const { LocalDataContainer* container = new LocalDataContainer( cookies(), databases(), local_storages(), session_storages(), appcaches(), indexed_dbs(), file_systems(), NULL, channel_ids(), service_workers(), cache_storages(), NULL); - return make_scoped_ptr(new CookiesTreeModel(container, NULL, true)); + return base::WrapUnique(new CookiesTreeModel(container, NULL, true)); }
diff --git a/chrome/browser/content_settings/local_shared_objects_container.h b/chrome/browser/content_settings/local_shared_objects_container.h index bfc59802..e9928c19 100644 --- a/chrome/browser/content_settings/local_shared_objects_container.h +++ b/chrome/browser/content_settings/local_shared_objects_container.h
@@ -7,9 +7,10 @@ #include <stddef.h> +#include <memory> + #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "components/content_settings/core/browser/local_shared_objects_counter.h" class CannedBrowsingDataAppCacheHelper; @@ -38,7 +39,7 @@ // Creates a new CookiesTreeModel for all objects in the container, // copying each of them. - scoped_ptr<CookiesTreeModel> CreateCookiesTreeModel() const; + std::unique_ptr<CookiesTreeModel> CreateCookiesTreeModel() const; CannedBrowsingDataAppCacheHelper* appcaches() const { return appcaches_.get();
diff --git a/chrome/browser/content_settings/tab_specific_content_settings.h b/chrome/browser/content_settings/tab_specific_content_settings.h index 99df942..dc20cd1 100644 --- a/chrome/browser/content_settings/tab_specific_content_settings.h +++ b/chrome/browser/content_settings/tab_specific_content_settings.h
@@ -8,11 +8,11 @@ #include <stdint.h> #include <map> +#include <memory> #include <string> #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/observer_list.h" #include "base/scoped_observer.h" #include "build/build_config.h" @@ -286,11 +286,11 @@ // Creates a new copy of a CookiesTreeModel for all allowed, and blocked, // respectively, local shared objects. - scoped_ptr<CookiesTreeModel> CreateAllowedCookiesTreeModel() const { + std::unique_ptr<CookiesTreeModel> CreateAllowedCookiesTreeModel() const { return allowed_local_shared_objects_.CreateCookiesTreeModel(); } - scoped_ptr<CookiesTreeModel> CreateBlockedCookiesTreeModel() const { + std::unique_ptr<CookiesTreeModel> CreateBlockedCookiesTreeModel() const { return blocked_local_shared_objects_.CreateCookiesTreeModel(); }
diff --git a/chrome/browser/content_settings/tab_specific_content_settings_unittest.cc b/chrome/browser/content_settings/tab_specific_content_settings_unittest.cc index a5e400b..b7a7166 100644 --- a/chrome/browser/content_settings/tab_specific_content_settings_unittest.cc +++ b/chrome/browser/content_settings/tab_specific_content_settings_unittest.cc
@@ -244,10 +244,9 @@ net::CookieOptions(), blocked_by_policy); net::CookieList cookie_list; - scoped_ptr<net::CanonicalCookie> cookie( - net::CanonicalCookie::Create(GURL("http://google.com"), - "CookieName=CookieValue", - base::Time::Now(), net::CookieOptions())); + std::unique_ptr<net::CanonicalCookie> cookie(net::CanonicalCookie::Create( + GURL("http://google.com"), "CookieName=CookieValue", base::Time::Now(), + net::CookieOptions())); cookie_list.push_back(*cookie); content_settings->OnCookiesRead(GURL("http://google.com"),
diff --git a/chrome/browser/copresence/chrome_whispernet_client.cc b/chrome/browser/copresence/chrome_whispernet_client.cc index 0c84c79b..95e13a37 100644 --- a/chrome/browser/copresence/chrome_whispernet_client.cc +++ b/chrome/browser/copresence/chrome_whispernet_client.cc
@@ -5,8 +5,10 @@ #include "chrome/browser/copresence/chrome_whispernet_client.h" #include <stddef.h> + #include <utility> +#include "base/memory/ptr_util.h" #include "chrome/browser/copresence/chrome_whispernet_config.h" #include "chrome/browser/extensions/api/copresence_private/copresence_private_api.h" #include "chrome/browser/extensions/component_loader.h" @@ -134,7 +136,7 @@ params.token.audible = (type == AUDIBLE); ConvertTokenParams(token_params[type], ¶ms.token_params); - SendEventIfLoaded(make_scoped_ptr(new Event( + SendEventIfLoaded(base::WrapUnique(new Event( extensions::events::COPRESENCE_PRIVATE_ON_ENCODE_TOKEN_REQUEST, OnEncodeTokenRequest::kEventName, OnEncodeTokenRequest::Create(client_id_, params), browser_context_))); @@ -151,7 +153,7 @@ ConvertTokenParams(token_params[AUDIBLE], ¶ms.audible_token_params); ConvertTokenParams(token_params[INAUDIBLE], ¶ms.inaudible_token_params); - SendEventIfLoaded(make_scoped_ptr(new Event( + SendEventIfLoaded(base::WrapUnique(new Event( extensions::events::COPRESENCE_PRIVATE_ON_DECODE_SAMPLES_REQUEST, OnDecodeSamplesRequest::kEventName, OnDecodeSamplesRequest::Create(client_id_, params), browser_context_))); @@ -193,14 +195,14 @@ memcpy(audio_params.param_data.data(), ¶ms, params_size); DVLOG(3) << "Configuring audio for client " << client_id_; - SendEventIfLoaded(make_scoped_ptr(new Event( + SendEventIfLoaded(base::WrapUnique(new Event( extensions::events::COPRESENCE_PRIVATE_ON_CONFIG_AUDIO, OnConfigAudio::kEventName, OnConfigAudio::Create(client_id_, audio_params), browser_context_))); } void ChromeWhispernetClient::SendEventIfLoaded( - scoped_ptr<extensions::Event> event) { + std::unique_ptr<extensions::Event> event) { DCHECK(event_router_); if (extension_loaded_) { @@ -226,7 +228,7 @@ DCHECK(event_router_); for (Event* event : queued_events_) { event_router_->DispatchEventToExtension(kWhispernetProxyExtensionId, - make_scoped_ptr(event)); + base::WrapUnique(event)); } queued_events_.weak_clear();
diff --git a/chrome/browser/copresence/chrome_whispernet_client.h b/chrome/browser/copresence/chrome_whispernet_client.h index 5548104..62beccb 100644 --- a/chrome/browser/copresence/chrome_whispernet_client.h +++ b/chrome/browser/copresence/chrome_whispernet_client.h
@@ -66,7 +66,7 @@ // Fire an event to configure whispernet with the given audio parameters. void AudioConfiguration(const AudioParamData& params); - void SendEventIfLoaded(scoped_ptr<extensions::Event> event); + void SendEventIfLoaded(std::unique_ptr<extensions::Event> event); // This gets called when the proxy extension loads. void OnExtensionLoaded(bool success);
diff --git a/chrome/browser/copresence/chrome_whispernet_client_browsertest.cc b/chrome/browser/copresence/chrome_whispernet_client_browsertest.cc index 11ee462..c51fb77 100644 --- a/chrome/browser/copresence/chrome_whispernet_client_browsertest.cc +++ b/chrome/browser/copresence/chrome_whispernet_client_browsertest.cc
@@ -8,11 +8,11 @@ #include <cmath> #include <cstdlib> +#include <memory> #include <string> #include "base/bind.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "base/stl_util.h" #include "build/build_config.h" @@ -79,7 +79,7 @@ ~ChromeWhispernetClientTest() override {} void InitializeWhispernet() { - scoped_ptr<WhispernetClient> client( + std::unique_ptr<WhispernetClient> client( new ChromeWhispernetClient(browser()->profile())); client->Initialize(base::Bind( &ChromeWhispernetClientTest::InitCallback, base::Unretained(this))); @@ -225,7 +225,7 @@ return 1.0; } - scoped_ptr<base::RunLoop> run_loop_; + std::unique_ptr<base::RunLoop> run_loop_; bool initialized_; std::string expected_token_; @@ -235,7 +235,7 @@ scoped_refptr<media::AudioBusRefCounted> saved_samples_stereo_; int saved_samples_index_; - scoped_ptr<media::AudioConverter> converter_; + std::unique_ptr<media::AudioConverter> converter_; media::AudioParameters default_params_; media::AudioParameters coder_params_; @@ -271,7 +271,7 @@ } IN_PROC_BROWSER_TEST_F(ChromeWhispernetClientTest, MAYBE_EncodeAndDecode) { - scoped_ptr<WhispernetClient> client( + std::unique_ptr<WhispernetClient> client( new ChromeWhispernetClient(browser()->profile())); client->Initialize(base::Bind(&IgnoreResult)); SetupDecode(); @@ -287,7 +287,7 @@ } IN_PROC_BROWSER_TEST_F(ChromeWhispernetClientTest, MAYBE_TokenLengths) { - scoped_ptr<WhispernetClient> client( + std::unique_ptr<WhispernetClient> client( new ChromeWhispernetClient(browser()->profile())); client->Initialize(base::Bind(&IgnoreResult)); SetupDecode(); @@ -304,7 +304,7 @@ } IN_PROC_BROWSER_TEST_F(ChromeWhispernetClientTest, MAYBE_Crc) { - scoped_ptr<WhispernetClient> client( + std::unique_ptr<WhispernetClient> client( new ChromeWhispernetClient(browser()->profile())); client->Initialize(base::Bind(&IgnoreResult)); SetupDecode(); @@ -322,7 +322,7 @@ } IN_PROC_BROWSER_TEST_F(ChromeWhispernetClientTest, MAYBE_Parity) { - scoped_ptr<WhispernetClient> client( + std::unique_ptr<WhispernetClient> client( new ChromeWhispernetClient(browser()->profile())); client->Initialize(base::Bind(&IgnoreResult)); SetupDecode(); @@ -340,11 +340,11 @@ } IN_PROC_BROWSER_TEST_F(ChromeWhispernetClientTest, MAYBE_MultipleClients) { - scoped_ptr<WhispernetClient> client_1( + std::unique_ptr<WhispernetClient> client_1( new ChromeWhispernetClient(browser()->profile())); - scoped_ptr<WhispernetClient> client_2( + std::unique_ptr<WhispernetClient> client_2( new ChromeWhispernetClient(browser()->profile())); - scoped_ptr<WhispernetClient> client_3( + std::unique_ptr<WhispernetClient> client_3( new ChromeWhispernetClient(browser()->profile())); SetupDecode();
diff --git a/chrome/browser/crash_recovery_browsertest.cc b/chrome/browser/crash_recovery_browsertest.cc index cb6073f..e7ca591 100644 --- a/chrome/browser/crash_recovery_browsertest.cc +++ b/chrome/browser/crash_recovery_browsertest.cc
@@ -52,13 +52,13 @@ explicit CacheMaxAgeHandler(const std::string& path) : path_(path), request_count_(0) { } - scoped_ptr<net::test_server::HttpResponse> HandleRequest( + std::unique_ptr<net::test_server::HttpResponse> HandleRequest( const net::test_server::HttpRequest& request) { if (request.relative_url != path_) - return scoped_ptr<net::test_server::HttpResponse>(); + return std::unique_ptr<net::test_server::HttpResponse>(); request_count_++; - scoped_ptr<net::test_server::BasicHttpResponse> response( + std::unique_ptr<net::test_server::BasicHttpResponse> response( new net::test_server::BasicHttpResponse); response->set_content(base::StringPrintf("<title>%d</title>", request_count_));
diff --git a/chrome/browser/custom_handlers/protocol_handler_registry.cc b/chrome/browser/custom_handlers/protocol_handler_registry.cc index 71fa56a..ab597622 100644 --- a/chrome/browser/custom_handlers/protocol_handler_registry.cc +++ b/chrome/browser/custom_handlers/protocol_handler_registry.cc
@@ -173,7 +173,7 @@ } void ProtocolHandlerRegistry::JobInterceptorFactory::Chain( - scoped_ptr<net::URLRequestJobFactory> job_factory) { + std::unique_ptr<net::URLRequestJobFactory> job_factory) { job_factory_ = std::move(job_factory); } @@ -696,9 +696,10 @@ if (is_loading_) { return; } - scoped_ptr<base::Value> registered_protocol_handlers( + std::unique_ptr<base::Value> registered_protocol_handlers( EncodeRegisteredHandlers()); - scoped_ptr<base::Value> ignored_protocol_handlers(EncodeIgnoredHandlers()); + std::unique_ptr<base::Value> ignored_protocol_handlers( + EncodeIgnoredHandlers()); PrefService* prefs = user_prefs::UserPrefs::Get(context_); prefs->Set(prefs::kRegisteredProtocolHandlers, @@ -920,12 +921,12 @@ weak_ptr_factory_.GetWeakPtr(), protocol); } -scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory> +std::unique_ptr<ProtocolHandlerRegistry::JobInterceptorFactory> ProtocolHandlerRegistry::CreateJobInterceptorFactory() { DCHECK_CURRENTLY_ON(BrowserThread::UI); // this is always created on the UI thread (in profile_io's // InitializeOnUIThread. Any method calls must be done // on the IO thread (this is checked). - return scoped_ptr<JobInterceptorFactory>( + return std::unique_ptr<JobInterceptorFactory>( new JobInterceptorFactory(io_thread_delegate_.get())); }
diff --git a/chrome/browser/custom_handlers/protocol_handler_registry.h b/chrome/browser/custom_handlers/protocol_handler_registry.h index a5926fd..00d08c2 100644 --- a/chrome/browser/custom_handlers/protocol_handler_registry.h +++ b/chrome/browser/custom_handlers/protocol_handler_registry.h
@@ -6,11 +6,11 @@ #define CHROME_BROWSER_CUSTOM_HANDLERS_PROTOCOL_HANDLER_REGISTRY_H_ #include <map> +#include <memory> #include <string> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/sequenced_task_runner_helpers.h" #include "base/values.h" @@ -75,7 +75,7 @@ // |job_factory| is set as the URLRequestJobFactory where requests are // forwarded if JobInterceptorFactory decides to pass on them. - void Chain(scoped_ptr<net::URLRequestJobFactory> job_factory); + void Chain(std::unique_ptr<net::URLRequestJobFactory> job_factory); // URLRequestJobFactory implementation. net::URLRequestJob* MaybeCreateJobWithProtocolHandler( @@ -99,7 +99,7 @@ private: // When JobInterceptorFactory decides to pass on particular requests, // they're forwarded to the chained URLRequestJobFactory, |job_factory_|. - scoped_ptr<URLRequestJobFactory> job_factory_; + std::unique_ptr<URLRequestJobFactory> job_factory_; // |io_thread_delegate_| performs the actual job creation decisions by // mirroring the ProtocolHandlerRegistry on the IO thread. scoped_refptr<IOThreadDelegate> io_thread_delegate_; @@ -117,7 +117,7 @@ // Returns a net::URLRequestJobFactory suitable for use on the IO thread, but // is initialized on the UI thread. - scoped_ptr<JobInterceptorFactory> CreateJobInterceptorFactory(); + std::unique_ptr<JobInterceptorFactory> CreateJobInterceptorFactory(); // Called when a site tries to register as a protocol handler. If the request // can be handled silently by the registry - either to ignore the request @@ -347,7 +347,7 @@ content::BrowserContext* context_; // The Delegate that registers / deregisters external handlers on our behalf. - scoped_ptr<Delegate> delegate_; + std::unique_ptr<Delegate> delegate_; // If false then registered protocol handlers will not be used to handle // requests.
diff --git a/chrome/browser/custom_handlers/protocol_handler_registry_browsertest.cc b/chrome/browser/custom_handlers/protocol_handler_registry_browsertest.cc index abb2ca63..62680a7 100644 --- a/chrome/browser/custom_handlers/protocol_handler_registry_browsertest.cc +++ b/chrome/browser/custom_handlers/protocol_handler_registry_browsertest.cc
@@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> #include <string> -#include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" @@ -76,7 +76,7 @@ IN_PROC_BROWSER_TEST_F(RegisterProtocolHandlerBrowserTest, ContextMenuEntryAppearsForHandledUrls) { - scoped_ptr<TestRenderViewContextMenu> menu( + std::unique_ptr<TestRenderViewContextMenu> menu( CreateContextMenu(GURL("http://www.google.com/"))); ASSERT_FALSE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKWITH)); @@ -93,7 +93,7 @@ IN_PROC_BROWSER_TEST_F(RegisterProtocolHandlerBrowserTest, UnregisterProtocolHandler) { - scoped_ptr<TestRenderViewContextMenu> menu( + std::unique_ptr<TestRenderViewContextMenu> menu( CreateContextMenu(GURL("http://www.google.com/"))); ASSERT_FALSE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKWITH));
diff --git a/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc b/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc index ea07eeb..fd3e3dc 100644 --- a/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc +++ b/chrome/browser/custom_handlers/protocol_handler_registry_unittest.cc
@@ -6,9 +6,9 @@ #include <stddef.h> +#include <memory> #include <set> -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/synchronization/waitable_event.h" @@ -39,9 +39,9 @@ net::URLRequestJobFactory* interceptor) { DCHECK_CURRENTLY_ON(BrowserThread::IO); net::URLRequestContext context; - scoped_ptr<net::URLRequest> request( + std::unique_ptr<net::URLRequest> request( context.CreateRequest(url, net::DEFAULT_PRIORITY, nullptr)); - scoped_ptr<net::URLRequestJob> job( + std::unique_ptr<net::URLRequestJob> job( interceptor->MaybeCreateJobWithProtocolHandler( url.scheme(), request.get(), context.network_delegate())); ASSERT_TRUE(job.get()); @@ -100,10 +100,10 @@ bool expected, ProtocolHandlerRegistry::JobInterceptorFactory* interceptor) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - interceptor->Chain(scoped_ptr<net::URLRequestJobFactory>( + interceptor->Chain(std::unique_ptr<net::URLRequestJobFactory>( new FakeURLRequestJobFactory())); ASSERT_EQ(expected, interceptor->IsHandledProtocol(scheme)); - interceptor->Chain(scoped_ptr<net::URLRequestJobFactory>()); + interceptor->Chain(std::unique_ptr<net::URLRequestJobFactory>()); } void AssertWillHandle( @@ -410,9 +410,9 @@ content::TestBrowserThread file_thread_; content::TestBrowserThread io_thread_; - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<TestingProfile> profile_; FakeDelegate* delegate_; // Registry assumes ownership of delegate_. - scoped_ptr<ProtocolHandlerRegistry> registry_; + std::unique_ptr<ProtocolHandlerRegistry> registry_; ProtocolHandler test_protocol_handler_; }; @@ -783,7 +783,7 @@ registry()->OnAcceptRegisterProtocolHandler(ph1); GURL url("mailto:someone@something.com"); - scoped_ptr<net::URLRequestJobFactory> interceptor( + std::unique_ptr<net::URLRequestJobFactory> interceptor( registry()->CreateJobInterceptorFactory()); AssertIntercepted(url, interceptor.get()); } @@ -794,7 +794,7 @@ ProtocolHandler ph1 = CreateProtocolHandler(scheme, "test1"); registry()->OnAcceptRegisterProtocolHandler(ph1); - scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory> interceptor( + std::unique_ptr<ProtocolHandlerRegistry::JobInterceptorFactory> interceptor( registry()->CreateJobInterceptorFactory()); AssertWillHandle(scheme, true, interceptor.get()); } @@ -841,7 +841,7 @@ registry()->OnAcceptRegisterProtocolHandler(ph1); registry()->ClearDefault(scheme); - scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory> interceptor( + std::unique_ptr<ProtocolHandlerRegistry::JobInterceptorFactory> interceptor( registry()->CreateJobInterceptorFactory()); AssertWillHandle(scheme, false, interceptor.get()); } @@ -851,7 +851,7 @@ ProtocolHandler ph1 = CreateProtocolHandler(mailto, "MailtoHandler"); registry()->OnAcceptRegisterProtocolHandler(ph1); - scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory> interceptor( + std::unique_ptr<ProtocolHandlerRegistry::JobInterceptorFactory> interceptor( registry()->CreateJobInterceptorFactory()); AssertWillHandle(mailto, true, interceptor.get()); registry()->Disable();
diff --git a/chrome/browser/data_saver/data_saver_browsertest.cc b/chrome/browser/data_saver/data_saver_browsertest.cc index 0929030..740db97 100644 --- a/chrome/browser/data_saver/data_saver_browsertest.cc +++ b/chrome/browser/data_saver/data_saver_browsertest.cc
@@ -63,7 +63,7 @@ prefs->SetBoolean(prefs::kDataSaverEnabled, enabled); } - scoped_ptr<net::test_server::HttpResponse> VerifySaveDataHeader( + std::unique_ptr<net::test_server::HttpResponse> VerifySaveDataHeader( const net::test_server::HttpRequest& request) { auto save_data_header_it = request.headers.find("save-data"); @@ -73,10 +73,10 @@ } else { EXPECT_TRUE(save_data_header_it == request.headers.end()); } - return scoped_ptr<net::test_server::HttpResponse>(); + return std::unique_ptr<net::test_server::HttpResponse>(); } - scoped_ptr<net::EmbeddedTestServer> test_server_; + std::unique_ptr<net::EmbeddedTestServer> test_server_; std::string expected_save_data_header_; };
diff --git a/chrome/browser/data_usage/tab_id_annotator.cc b/chrome/browser/data_usage/tab_id_annotator.cc index c3b1992..6754b20 100644 --- a/chrome/browser/data_usage/tab_id_annotator.cc +++ b/chrome/browser/data_usage/tab_id_annotator.cc
@@ -44,7 +44,7 @@ // destroyed. This doesn't make much of a difference for production code, but // makes it easier to test the TabIdAnnotator. void AnnotateDataUse( - scoped_ptr<DataUse> data_use, + std::unique_ptr<DataUse> data_use, const data_usage::DataUseAnnotator::DataUseConsumerCallback& callback, int32_t tab_id) { DCHECK(data_use); @@ -58,7 +58,7 @@ TabIdAnnotator::~TabIdAnnotator() {} void TabIdAnnotator::Annotate(net::URLRequest* request, - scoped_ptr<DataUse> data_use, + std::unique_ptr<DataUse> data_use, const DataUseConsumerCallback& callback) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(data_use); @@ -82,7 +82,7 @@ scoped_refptr<base::SingleThreadTaskRunner> ui_thread_task_runner = BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI); - scoped_ptr<TabIdProvider> tab_id_provider(new TabIdProvider( + std::unique_ptr<TabIdProvider> tab_id_provider(new TabIdProvider( ui_thread_task_runner.get(), FROM_HERE, base::Bind(&GetTabIdForRenderFrame, render_process_id, render_frame_id))); tab_id_provider->ProvideTabId(
diff --git a/chrome/browser/data_usage/tab_id_annotator.h b/chrome/browser/data_usage/tab_id_annotator.h index f4fcccf..513cd17a 100644 --- a/chrome/browser/data_usage/tab_id_annotator.h +++ b/chrome/browser/data_usage/tab_id_annotator.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_DATA_USAGE_TAB_ID_ANNOTATOR_H_ #define CHROME_BROWSER_DATA_USAGE_TAB_ID_ANNOTATOR_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/threading/thread_checker.h" #include "components/data_usage/core/data_use_annotator.h" @@ -33,7 +34,7 @@ // data if there isn't one attached already and |request| has enough // information to get a tab ID. void Annotate(net::URLRequest* request, - scoped_ptr<data_usage::DataUse> data_use, + std::unique_ptr<data_usage::DataUse> data_use, const DataUseConsumerCallback& callback) override; private:
diff --git a/chrome/browser/data_usage/tab_id_annotator_unittest.cc b/chrome/browser/data_usage/tab_id_annotator_unittest.cc index c17ccb52..cee5463 100644 --- a/chrome/browser/data_usage/tab_id_annotator_unittest.cc +++ b/chrome/browser/data_usage/tab_id_annotator_unittest.cc
@@ -5,6 +5,8 @@ #include "chrome/browser/data_usage/tab_id_annotator.h" #include <stdint.h> + +#include <memory> #include <string> #include <utility> @@ -12,7 +14,6 @@ #include "base/callback.h" #include "base/location.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "base/time/time.h" #include "chrome/browser/sessions/session_tab_helper.h" @@ -51,14 +52,15 @@ }; // Synthesizes a DataUse object with the given |tab_id|. -scoped_ptr<DataUse> CreateDataUse(int32_t tab_id) { - return scoped_ptr<DataUse>(new DataUse( +std::unique_ptr<DataUse> CreateDataUse(int32_t tab_id) { + return std::unique_ptr<DataUse>(new DataUse( GURL("http://foo.com"), base::TimeTicks(), GURL(), tab_id, net::NetworkChangeNotifier::CONNECTION_UNKNOWN, std::string(), 100, 100)); } // Expects that |expected| and |actual| are equal. -void ExpectDataUse(scoped_ptr<DataUse> expected, scoped_ptr<DataUse> actual) { +void ExpectDataUse(std::unique_ptr<DataUse> expected, + std::unique_ptr<DataUse> actual) { // Single out the |tab_id| for better debug output in failure cases. EXPECT_EQ(expected->tab_id, actual->tab_id); EXPECT_EQ(*expected, *actual); @@ -67,8 +69,8 @@ // Expects that |expected| and |actual| are equal, then quits |ui_run_loop| on // the UI thread. void ExpectDataUseAndQuit(base::RunLoop* ui_run_loop, - scoped_ptr<DataUse> expected, - scoped_ptr<DataUse> actual) { + std::unique_ptr<DataUse> expected, + std::unique_ptr<DataUse> actual) { DCHECK(ui_run_loop); ExpectDataUse(std::move(expected), std::move(actual)); @@ -95,7 +97,7 @@ TabIdAnnotator annotator; net::TestURLRequestContext context; net::TestDelegate test_delegate; - scoped_ptr<net::URLRequest> request = + std::unique_ptr<net::URLRequest> request = context.CreateRequest(GURL("http://foo.com"), net::IDLE, &test_delegate); if (render_process_id != -1 && render_frame_id != -1) { @@ -113,13 +115,15 @@ // Annotate two separate DataUse objects to ensure that repeated annotations // for the same URLRequest work properly. - scoped_ptr<DataUse> first_expected_data_use = CreateDataUse(expected_tab_id); + std::unique_ptr<DataUse> first_expected_data_use = + CreateDataUse(expected_tab_id); annotator.Annotate( request.get(), CreateDataUse(kInvalidTabId), base::Bind(&ExpectDataUse, base::Passed(&first_expected_data_use))); // Quit the |ui_run_loop| after the second annotation. - scoped_ptr<DataUse> second_expected_data_use = CreateDataUse(expected_tab_id); + std::unique_ptr<DataUse> second_expected_data_use = + CreateDataUse(expected_tab_id); annotator.Annotate(request.get(), CreateDataUse(kInvalidTabId), base::Bind(&ExpectDataUseAndQuit, ui_run_loop, base::Passed(&second_expected_data_use)));
diff --git a/chrome/browser/data_usage/tab_id_provider.cc b/chrome/browser/data_usage/tab_id_provider.cc index 89fee80..4278666 100644 --- a/chrome/browser/data_usage/tab_id_provider.cc +++ b/chrome/browser/data_usage/tab_id_provider.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/data_usage/tab_id_provider.h" +#include <memory> #include <vector> #include "base/bind.h" @@ -11,7 +12,6 @@ #include "base/location.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/single_thread_task_runner.h" #include "base/task_runner.h" #include "base/task_runner_util.h" @@ -79,7 +79,7 @@ const tracked_objects::Location& from_here, const TabIdGetter& tab_id_getter) : is_tab_id_ready_(false), tab_id_(-1), weak_ptr_factory_(this) { - scoped_ptr<CallbackRunner> callback_runner(new CallbackRunner()); + std::unique_ptr<CallbackRunner> callback_runner(new CallbackRunner()); weak_callback_runner_ = callback_runner->GetWeakPtr(); callback_runner->AddCallback( base::Bind(&TabIdProvider::OnTabIdReady, GetWeakPtr()));
diff --git a/chrome/browser/data_usage/tab_id_provider_unittest.cc b/chrome/browser/data_usage/tab_id_provider_unittest.cc index 057b544..0413865 100644 --- a/chrome/browser/data_usage/tab_id_provider_unittest.cc +++ b/chrome/browser/data_usage/tab_id_provider_unittest.cc
@@ -6,12 +6,13 @@ #include <stdint.h> +#include <memory> + #include "base/bind.h" #include "base/callback.h" #include "base/location.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" @@ -116,7 +117,7 @@ } TEST_F(TabIdProviderTest, ProvideTabIdAfterProviderDestroyed) { - scoped_ptr<TabIdProvider> provider( + std::unique_ptr<TabIdProvider> provider( new TabIdProvider(task_runner(), FROM_HERE, TabIdGetterCallback())); // Ask for two tab IDs.
diff --git a/chrome/browser/diagnostics/diagnostics_controller.cc b/chrome/browser/diagnostics/diagnostics_controller.cc index c8d7280a..3ef7cd4 100644 --- a/chrome/browser/diagnostics/diagnostics_controller.cc +++ b/chrome/browser/diagnostics/diagnostics_controller.cc
@@ -4,11 +4,11 @@ #include "chrome/browser/diagnostics/diagnostics_controller.h" +#include <memory> #include <string> #include "base/command_line.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/histogram.h" #include "base/time/time.h" #include "build/build_config.h"
diff --git a/chrome/browser/diagnostics/diagnostics_controller.h b/chrome/browser/diagnostics/diagnostics_controller.h index b62c5346..a98608b 100644 --- a/chrome/browser/diagnostics/diagnostics_controller.h +++ b/chrome/browser/diagnostics/diagnostics_controller.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_DIAGNOSTICS_DIAGNOSTICS_CONTROLLER_H_ #define CHROME_BROWSER_DIAGNOSTICS_DIAGNOSTICS_CONTROLLER_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" namespace base { @@ -53,7 +54,7 @@ DiagnosticsController(); ~DiagnosticsController(); - scoped_ptr<DiagnosticsModel> model_; + std::unique_ptr<DiagnosticsModel> model_; DiagnosticsWriter* writer_; DISALLOW_COPY_AND_ASSIGN(DiagnosticsController);
diff --git a/chrome/browser/diagnostics/diagnostics_controller_unittest.cc b/chrome/browser/diagnostics/diagnostics_controller_unittest.cc index bed7f36..a2f005c9 100644 --- a/chrome/browser/diagnostics/diagnostics_controller_unittest.cc +++ b/chrome/browser/diagnostics/diagnostics_controller_unittest.cc
@@ -4,12 +4,13 @@ #include "chrome/browser/diagnostics/diagnostics_controller.h" +#include <memory> + #include "base/base_paths.h" #include "base/command_line.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/browser/diagnostics/diagnostics_model.h" @@ -71,10 +72,10 @@ base::WriteFile(path, bogus_data, arraysize(bogus_data)); } - scoped_ptr<DiagnosticsModel> model_; + std::unique_ptr<DiagnosticsModel> model_; base::CommandLine cmdline_; base::ScopedTempDir temp_dir_; - scoped_ptr<DiagnosticsWriter> writer_; + std::unique_ptr<DiagnosticsWriter> writer_; base::FilePath profile_dir_; #if defined(OS_CHROMEOS)
diff --git a/chrome/browser/diagnostics/diagnostics_model_unittest.cc b/chrome/browser/diagnostics/diagnostics_model_unittest.cc index d593bb4..e6ab6e5 100644 --- a/chrome/browser/diagnostics/diagnostics_model_unittest.cc +++ b/chrome/browser/diagnostics/diagnostics_model_unittest.cc
@@ -4,10 +4,11 @@ #include "chrome/browser/diagnostics/diagnostics_model.h" +#include <memory> + #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "testing/gtest/include/gtest/gtest.h" namespace diagnostics { @@ -26,7 +27,7 @@ void TearDown() override { model_.reset(); } - scoped_ptr<DiagnosticsModel> model_; + std::unique_ptr<DiagnosticsModel> model_; base::CommandLine cmdline_; DISALLOW_COPY_AND_ASSIGN(DiagnosticsModelTest);
diff --git a/chrome/browser/diagnostics/diagnostics_writer.h b/chrome/browser/diagnostics/diagnostics_writer.h index 7b4e9adc..094ae64 100644 --- a/chrome/browser/diagnostics/diagnostics_writer.h +++ b/chrome/browser/diagnostics/diagnostics_writer.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_DIAGNOSTICS_DIAGNOSTICS_WRITER_H_ #define CHROME_BROWSER_DIAGNOSTICS_DIAGNOSTICS_WRITER_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/diagnostics/diagnostics_model.h" namespace diagnostics { @@ -54,7 +55,7 @@ int outcome_code, const std::string& extra); - scoped_ptr<SimpleConsole> console_; + std::unique_ptr<SimpleConsole> console_; // Keeps track of how many tests reported failure. int failures_;
diff --git a/chrome/browser/diagnostics/recon_diagnostics.cc b/chrome/browser/diagnostics/recon_diagnostics.cc index 366d9c5..11d1af8 100644 --- a/chrome/browser/diagnostics/recon_diagnostics.cc +++ b/chrome/browser/diagnostics/recon_diagnostics.cc
@@ -7,13 +7,13 @@ #include <stddef.h> #include <stdint.h> +#include <memory> #include <string> #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/json/json_string_value_serializer.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" @@ -63,7 +63,7 @@ EnumerateModulesModel* model = EnumerateModulesModel::GetInstance(); model->set_limited_mode(true); model->ScanNow(); - scoped_ptr<base::ListValue> list(model->GetModuleList()); + std::unique_ptr<base::ListValue> list(model->GetModuleList()); if (!model->confirmed_bad_modules_detected() && !model->suspected_bad_modules_detected()) { RecordSuccess("No conflicting modules found"); @@ -220,7 +220,7 @@ JSONStringValueDeserializer json(json_data); int error_code = base::JSONReader::JSON_NO_ERROR; std::string error_message; - scoped_ptr<base::Value> json_root( + std::unique_ptr<base::Value> json_root( json.Deserialize(&error_code, &error_message)); if (base::JSONReader::JSON_NO_ERROR != error_code) { if (error_message.empty()) {
diff --git a/chrome/browser/dom_distiller/dom_distiller_service_factory.cc b/chrome/browser/dom_distiller/dom_distiller_service_factory.cc index ceea050..1048e7dd 100644 --- a/chrome/browser/dom_distiller/dom_distiller_service_factory.cc +++ b/chrome/browser/dom_distiller/dom_distiller_service_factory.cc
@@ -23,10 +23,10 @@ namespace dom_distiller { DomDistillerContextKeyedService::DomDistillerContextKeyedService( - scoped_ptr<DomDistillerStoreInterface> store, - scoped_ptr<DistillerFactory> distiller_factory, - scoped_ptr<DistillerPageFactory> distiller_page_factory, - scoped_ptr<DistilledPagePrefs> distilled_page_prefs) + std::unique_ptr<DomDistillerStoreInterface> store, + std::unique_ptr<DistillerFactory> distiller_factory, + std::unique_ptr<DistillerPageFactory> distiller_page_factory, + std::unique_ptr<DistilledPagePrefs> distilled_page_prefs) : DomDistillerService(std::move(store), std::move(distiller_factory), std::move(distiller_page_factory), @@ -58,22 +58,22 @@ content::BrowserThread::GetBlockingPool()->GetSequencedTaskRunner( base::SequencedWorkerPool::GetSequenceToken()); - scoped_ptr<leveldb_proto::ProtoDatabaseImpl<ArticleEntry> > db( + std::unique_ptr<leveldb_proto::ProtoDatabaseImpl<ArticleEntry>> db( new leveldb_proto::ProtoDatabaseImpl<ArticleEntry>( background_task_runner)); base::FilePath database_dir( profile->GetPath().Append(FILE_PATH_LITERAL("Articles"))); - scoped_ptr<DomDistillerStore> dom_distiller_store( + std::unique_ptr<DomDistillerStore> dom_distiller_store( new DomDistillerStore(std::move(db), database_dir)); - scoped_ptr<DistillerPageFactory> distiller_page_factory( + std::unique_ptr<DistillerPageFactory> distiller_page_factory( new DistillerPageWebContentsFactory(profile)); - scoped_ptr<DistillerURLFetcherFactory> distiller_url_fetcher_factory( + std::unique_ptr<DistillerURLFetcherFactory> distiller_url_fetcher_factory( new DistillerURLFetcherFactory( - content::BrowserContext::GetDefaultStoragePartition(profile)-> - GetURLRequestContext())); + content::BrowserContext::GetDefaultStoragePartition(profile) + ->GetURLRequestContext())); dom_distiller::proto::DomDistillerOptions options; if (VLOG_IS_ON(1)) { @@ -85,9 +85,9 @@ // - "pagenum": detect anchors with numeric page numbers // Default is "next". options.set_pagination_algo("next"); - scoped_ptr<DistillerFactory> distiller_factory(new DistillerFactoryImpl( + std::unique_ptr<DistillerFactory> distiller_factory(new DistillerFactoryImpl( std::move(distiller_url_fetcher_factory), options)); - scoped_ptr<DistilledPagePrefs> distilled_page_prefs( + std::unique_ptr<DistilledPagePrefs> distilled_page_prefs( new DistilledPagePrefs(Profile::FromBrowserContext(profile)->GetPrefs())); DomDistillerContextKeyedService* service =
diff --git a/chrome/browser/dom_distiller/dom_distiller_service_factory.h b/chrome/browser/dom_distiller/dom_distiller_service_factory.h index 1632bae7..db65e63 100644 --- a/chrome/browser/dom_distiller/dom_distiller_service_factory.h +++ b/chrome/browser/dom_distiller/dom_distiller_service_factory.h
@@ -24,10 +24,10 @@ public DomDistillerService { public: DomDistillerContextKeyedService( - scoped_ptr<DomDistillerStoreInterface> store, - scoped_ptr<DistillerFactory> distiller_factory, - scoped_ptr<DistillerPageFactory> distiller_page_factory, - scoped_ptr<DistilledPagePrefs> distilled_page_prefs); + std::unique_ptr<DomDistillerStoreInterface> store, + std::unique_ptr<DistillerFactory> distiller_factory, + std::unique_ptr<DistillerPageFactory> distiller_page_factory, + std::unique_ptr<DistilledPagePrefs> distilled_page_prefs); ~DomDistillerContextKeyedService() override {} private:
diff --git a/chrome/browser/dom_distiller/dom_distiller_viewer_source_browsertest.cc b/chrome/browser/dom_distiller/dom_distiller_viewer_source_browsertest.cc index 323949a..f67d5c6 100644 --- a/chrome/browser/dom_distiller/dom_distiller_viewer_source_browsertest.cc +++ b/chrome/browser/dom_distiller/dom_distiller_viewer_source_browsertest.cc
@@ -3,11 +3,12 @@ // found in the LICENSE file. #include <string.h> + +#include <memory> #include <utility> #include "base/command_line.h" #include "base/guid.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/dom_distiller/dom_distiller_service_factory.h" @@ -119,18 +120,18 @@ command_line->AppendSwitch(switches::kEnableDomDistiller); } - static scoped_ptr<KeyedService> Build(content::BrowserContext* context) { + static std::unique_ptr<KeyedService> Build(content::BrowserContext* context) { FakeDB<ArticleEntry>* fake_db = new FakeDB<ArticleEntry>(database_model_); distiller_factory_ = new MockDistillerFactory(); MockDistillerPageFactory* distiller_page_factory_ = new MockDistillerPageFactory(); - scoped_ptr<DomDistillerContextKeyedService> service( + std::unique_ptr<DomDistillerContextKeyedService> service( new DomDistillerContextKeyedService( - scoped_ptr<DomDistillerStoreInterface>(CreateStoreWithFakeDB( + std::unique_ptr<DomDistillerStoreInterface>(CreateStoreWithFakeDB( fake_db, FakeDB<ArticleEntry>::EntryMap())), - scoped_ptr<DistillerFactory>(distiller_factory_), - scoped_ptr<DistillerPageFactory>(distiller_page_factory_), - scoped_ptr<DistilledPagePrefs>(new DistilledPagePrefs( + std::unique_ptr<DistillerFactory>(distiller_factory_), + std::unique_ptr<DistillerPageFactory>(distiller_page_factory_), + std::unique_ptr<DistilledPagePrefs>(new DistilledPagePrefs( Profile::FromBrowserContext(context)->GetPrefs())))); fake_db->InitCallback(true); fake_db->LoadCallback(true); @@ -226,8 +227,14 @@ EXPECT_EQ(expected_mime_type, contents_after_nav->GetContentsMimeType()); } +#if defined(OS_LINUX) +// Flaky on Ubuntu-12.04 bots: https://crbug.com/604362 +#define MAYBE_TestBadUrlErrorPage DISABLED_TestBadUrlErrorPage +#else +#define MAYBE_TestBadUrlErrorPage TestBadUrlErrorPage +#endif IN_PROC_BROWSER_TEST_F(DomDistillerViewerSourceBrowserTest, - TestBadUrlErrorPage) { + MAYBE_TestBadUrlErrorPage) { GURL url("chrome-distiller://bad"); // Navigate to a distiller URL. @@ -266,8 +273,15 @@ ViewSingleDistilledPage(url, "text/css"); } + +#if defined(OS_LINUX) +// Flaky on Ubuntu-12.04 bots: https://crbug.com/604362 +#define MAYBE_EmptyURLShouldNotCrash DISABLED_EmptyURLShouldNotCrash +#else +#define MAYBE_EmptyURLShouldNotCrash EmptyURLShouldNotCrash +#endif IN_PROC_BROWSER_TEST_F(DomDistillerViewerSourceBrowserTest, - EmptyURLShouldNotCrash) { + MAYBE_EmptyURLShouldNotCrash) { // This is a bogus URL, so no distillation will happen. expect_distillation_ = false; expect_distiller_page_ = false; @@ -323,7 +337,7 @@ // Finish distillation and make sure the spinner has been replaced by text. std::vector<scoped_refptr<ArticleDistillationUpdate::RefCountedPageProto> > update_pages; - scoped_ptr<DistilledArticleProto> article(new DistilledArticleProto()); + std::unique_ptr<DistilledArticleProto> article(new DistilledArticleProto()); scoped_refptr<base::RefCountedData<DistilledPageProto> > page_proto = new base::RefCountedData<DistilledPageProto>(); @@ -432,7 +446,7 @@ std::vector<scoped_refptr<ArticleDistillationUpdate::RefCountedPageProto> > update_pages; - scoped_ptr<DistilledArticleProto> article(new DistilledArticleProto()); + std::unique_ptr<DistilledArticleProto> article(new DistilledArticleProto()); // Flush page 1. { @@ -502,10 +516,18 @@ PrefTest(false); } -IN_PROC_BROWSER_TEST_F(DomDistillerViewerSourceBrowserTest, PrefChangeError) { +#if defined(OS_LINUX) +// Flaky on Ubuntu-12.04 bots: https://crbug.com/604362 +#define MAYBE_PrefChangeError DISABLED_PrefChangeError +#else +#define MAYBE_PrefChangeError PrefChangeError +#endif +IN_PROC_BROWSER_TEST_F(DomDistillerViewerSourceBrowserTest, + MAYBE_PrefChangeError) { PrefTest(true); } + void DomDistillerViewerSourceBrowserTest::PrefTest(bool is_error_page) { GURL url; if (is_error_page) {
diff --git a/chrome/browser/dom_distiller/lazy_dom_distiller_service.cc b/chrome/browser/dom_distiller/lazy_dom_distiller_service.cc index eefec748..90419f6 100644 --- a/chrome/browser/dom_distiller/lazy_dom_distiller_service.cc +++ b/chrome/browser/dom_distiller/lazy_dom_distiller_service.cc
@@ -58,7 +58,7 @@ const std::string LazyDomDistillerService::AddToList( const GURL& url, - scoped_ptr<DistillerPage> distiller_page, + std::unique_ptr<DistillerPage> distiller_page, const ArticleAvailableCallback& article_cb) { return instance()->AddToList(url, std::move(distiller_page), article_cb); } @@ -67,34 +67,34 @@ return instance()->GetEntries(); } -scoped_ptr<ArticleEntry> LazyDomDistillerService::RemoveEntry( +std::unique_ptr<ArticleEntry> LazyDomDistillerService::RemoveEntry( const std::string& entry_id) { return instance()->RemoveEntry(entry_id); } -scoped_ptr<ViewerHandle> LazyDomDistillerService::ViewEntry( +std::unique_ptr<ViewerHandle> LazyDomDistillerService::ViewEntry( ViewRequestDelegate* delegate, - scoped_ptr<DistillerPage> distiller_page, + std::unique_ptr<DistillerPage> distiller_page, const std::string& entry_id) { return instance()->ViewEntry(delegate, std::move(distiller_page), entry_id); } -scoped_ptr<ViewerHandle> LazyDomDistillerService::ViewUrl( +std::unique_ptr<ViewerHandle> LazyDomDistillerService::ViewUrl( ViewRequestDelegate* delegate, - scoped_ptr<DistillerPage> distiller_page, + std::unique_ptr<DistillerPage> distiller_page, const GURL& url) { return instance()->ViewUrl(delegate, std::move(distiller_page), url); } -scoped_ptr<DistillerPage> +std::unique_ptr<DistillerPage> LazyDomDistillerService::CreateDefaultDistillerPage( const gfx::Size& render_view_size) { return instance()->CreateDefaultDistillerPage(render_view_size); } -scoped_ptr<DistillerPage> +std::unique_ptr<DistillerPage> LazyDomDistillerService::CreateDefaultDistillerPageWithHandle( - scoped_ptr<SourcePageHandle> handle) { + std::unique_ptr<SourcePageHandle> handle) { return instance()->CreateDefaultDistillerPageWithHandle(std::move(handle)); }
diff --git a/chrome/browser/dom_distiller/lazy_dom_distiller_service.h b/chrome/browser/dom_distiller/lazy_dom_distiller_service.h index a39dc45e..9264f033 100644 --- a/chrome/browser/dom_distiller/lazy_dom_distiller_service.h +++ b/chrome/browser/dom_distiller/lazy_dom_distiller_service.h
@@ -6,6 +6,7 @@ #define CHROME_BROWSER_DOM_DISTILLER_LAZY_DOM_DISTILLER_SERVICE_H_ #include "base/macros.h" +#include "base/memory/scoped_ptr.h" #include "components/dom_distiller/core/dom_distiller_service.h" #include "components/dom_distiller/core/task_tracker.h" #include "content/public/browser/notification_observer.h" @@ -37,22 +38,25 @@ syncer::SyncableService* GetSyncableService() const override; const std::string AddToList( const GURL& url, - scoped_ptr<DistillerPage> distiller_page, + std::unique_ptr<DistillerPage> distiller_page, const ArticleAvailableCallback& article_cb) override; bool HasEntry(const std::string& entry_id) override; std::string GetUrlForEntry(const std::string& entry_id) override; std::vector<ArticleEntry> GetEntries() const override; - scoped_ptr<ArticleEntry> RemoveEntry(const std::string& entry_id) override; - scoped_ptr<ViewerHandle> ViewEntry(ViewRequestDelegate* delegate, - scoped_ptr<DistillerPage> distiller_page, - const std::string& entry_id) override; - scoped_ptr<ViewerHandle> ViewUrl(ViewRequestDelegate* delegate, - scoped_ptr<DistillerPage> distiller_page, - const GURL& url) override; - scoped_ptr<DistillerPage> CreateDefaultDistillerPage( + std::unique_ptr<ArticleEntry> RemoveEntry( + const std::string& entry_id) override; + std::unique_ptr<ViewerHandle> ViewEntry( + ViewRequestDelegate* delegate, + std::unique_ptr<DistillerPage> distiller_page, + const std::string& entry_id) override; + std::unique_ptr<ViewerHandle> ViewUrl( + ViewRequestDelegate* delegate, + std::unique_ptr<DistillerPage> distiller_page, + const GURL& url) override; + std::unique_ptr<DistillerPage> CreateDefaultDistillerPage( const gfx::Size& render_view_size) override; - scoped_ptr<DistillerPage> CreateDefaultDistillerPageWithHandle( - scoped_ptr<SourcePageHandle> handle) override; + std::unique_ptr<DistillerPage> CreateDefaultDistillerPageWithHandle( + std::unique_ptr<SourcePageHandle> handle) override; void AddObserver(DomDistillerObserver* observer) override; void RemoveObserver(DomDistillerObserver* observer) override; DistilledPagePrefs* GetDistilledPagePrefs() override;
diff --git a/chrome/browser/dom_distiller/profile_utils.cc b/chrome/browser/dom_distiller/profile_utils.cc index e365c6f..bc1038d 100644 --- a/chrome/browser/dom_distiller/profile_utils.cc +++ b/chrome/browser/dom_distiller/profile_utils.cc
@@ -4,10 +4,10 @@ #include "chrome/browser/dom_distiller/profile_utils.h" +#include <memory> #include <utility> #include "base/command_line.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/dom_distiller/dom_distiller_service_factory.h" #include "chrome/browser/dom_distiller/lazy_dom_distiller_service.h" #include "chrome/browser/profiles/profile.h" @@ -43,7 +43,7 @@ dom_distiller::LazyDomDistillerService* lazy_service = new dom_distiller::LazyDomDistillerService( profile, dom_distiller_service_factory); - scoped_ptr<dom_distiller::DistillerUIHandle> ui_handle; + std::unique_ptr<dom_distiller::DistillerUIHandle> ui_handle; #if BUILDFLAG(ANDROID_JAVA_UI) ui_handle.reset(
diff --git a/chrome/browser/dom_distiller/tab_utils.cc b/chrome/browser/dom_distiller/tab_utils.cc index 8f93f38..85eac2a 100644 --- a/chrome/browser/dom_distiller/tab_utils.cc +++ b/chrome/browser/dom_distiller/tab_utils.cc
@@ -55,12 +55,12 @@ // Takes ownership of the ViewerHandle to keep distillation alive until |this| // is deleted. - void TakeViewerHandle(scoped_ptr<ViewerHandle> viewer_handle); + void TakeViewerHandle(std::unique_ptr<ViewerHandle> viewer_handle); private: // The handle to the view request towards the DomDistillerService. It // needs to be kept around to ensure the distillation request finishes. - scoped_ptr<ViewerHandle> viewer_handle_; + std::unique_ptr<ViewerHandle> viewer_handle_; }; void SelfDeletingRequestDelegate::DidNavigateMainFrame( @@ -98,7 +98,7 @@ } void SelfDeletingRequestDelegate::TakeViewerHandle( - scoped_ptr<ViewerHandle> viewer_handle) { + std::unique_ptr<ViewerHandle> viewer_handle) { viewer_handle_ = std::move(viewer_handle); } @@ -113,7 +113,7 @@ } void MaybeStartDistillation( - scoped_ptr<SourcePageHandleWebContents> source_page_handle) { + std::unique_ptr<SourcePageHandleWebContents> source_page_handle) { const GURL& last_committed_url = source_page_handle->web_contents()->GetLastCommittedURL(); if (!dom_distiller::url_utils::IsUrlDistillable(last_committed_url)) @@ -126,11 +126,11 @@ DomDistillerService* dom_distiller_service = DomDistillerServiceFactory::GetForBrowserContext( source_page_handle->web_contents()->GetBrowserContext()); - scoped_ptr<DistillerPage> distiller_page = + std::unique_ptr<DistillerPage> distiller_page = dom_distiller_service->CreateDefaultDistillerPageWithHandle( std::move(source_page_handle)); - scoped_ptr<ViewerHandle> viewer_handle = dom_distiller_service->ViewUrl( + std::unique_ptr<ViewerHandle> viewer_handle = dom_distiller_service->ViewUrl( view_request_delegate, std::move(distiller_page), last_committed_url); view_request_delegate->TakeViewerHandle(std::move(viewer_handle)); } @@ -160,7 +160,7 @@ CoreTabHelper::FromWebContents(old_web_contents)->delegate()->SwapTabContents( old_web_contents, new_web_contents, false, false); - scoped_ptr<SourcePageHandleWebContents> source_page_handle( + std::unique_ptr<SourcePageHandleWebContents> source_page_handle( new SourcePageHandleWebContents(old_web_contents, true)); MaybeStartDistillation(std::move(source_page_handle)); @@ -171,7 +171,7 @@ DCHECK(source_web_contents); DCHECK(destination_web_contents); - scoped_ptr<SourcePageHandleWebContents> source_page_handle( + std::unique_ptr<SourcePageHandleWebContents> source_page_handle( new SourcePageHandleWebContents(source_web_contents, false)); MaybeStartDistillation(std::move(source_page_handle));
diff --git a/chrome/browser/dom_distiller/tab_utils_browsertest.cc b/chrome/browser/dom_distiller/tab_utils_browsertest.cc index 2d5fa76..ddc07da6 100644 --- a/chrome/browser/dom_distiller/tab_utils_browsertest.cc +++ b/chrome/browser/dom_distiller/tab_utils_browsertest.cc
@@ -111,7 +111,7 @@ browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(after_web_contents != NULL); base::RunLoop new_url_loaded_runner; - scoped_ptr<WebContentsMainFrameHelper> distilled_page_loaded( + std::unique_ptr<WebContentsMainFrameHelper> distilled_page_loaded( new WebContentsMainFrameHelper(after_web_contents, new_url_loaded_runner.QuitClosure())); new_url_loaded_runner.Run(); @@ -154,7 +154,7 @@ // Wait until the destination WebContents has fully navigated. base::RunLoop new_url_loaded_runner; - scoped_ptr<WebContentsMainFrameHelper> distilled_page_loaded( + std::unique_ptr<WebContentsMainFrameHelper> distilled_page_loaded( new WebContentsMainFrameHelper(destination_web_contents, new_url_loaded_runner.QuitClosure())); new_url_loaded_runner.Run();
diff --git a/chrome/browser/download/download_extensions.cc b/chrome/browser/download/download_extensions.cc index 00d0bd5..34a58cc 100644 --- a/chrome/browser/download/download_extensions.cc +++ b/chrome/browser/download/download_extensions.cc
@@ -498,6 +498,23 @@ // Automator Workflow. {"workflow", ALLOW_ON_USER_GESTURE, DISALLOW_AUTO_OPEN}, + + // Executable file extensions for Mac. + {"cdr", ALLOW_ON_USER_GESTURE, DISALLOW_AUTO_OPEN}, + {"dart", ALLOW_ON_USER_GESTURE, DISALLOW_AUTO_OPEN}, + {"dc42", ALLOW_ON_USER_GESTURE, DISALLOW_AUTO_OPEN}, + {"diskcopy42", ALLOW_ON_USER_GESTURE, DISALLOW_AUTO_OPEN}, + {"dmg", ALLOW_ON_USER_GESTURE, DISALLOW_AUTO_OPEN}, + {"dmgpart", ALLOW_ON_USER_GESTURE, DISALLOW_AUTO_OPEN}, + {"dvdr", ALLOW_ON_USER_GESTURE, DISALLOW_AUTO_OPEN}, + {"img", ALLOW_ON_USER_GESTURE, DISALLOW_AUTO_OPEN}, + {"imgpart", ALLOW_ON_USER_GESTURE, DISALLOW_AUTO_OPEN}, + {"ndif", ALLOW_ON_USER_GESTURE, DISALLOW_AUTO_OPEN}, + {"smi", ALLOW_ON_USER_GESTURE, DISALLOW_AUTO_OPEN}, + {"sparsebundle", ALLOW_ON_USER_GESTURE, DISALLOW_AUTO_OPEN}, + {"sparseimage", ALLOW_ON_USER_GESTURE, DISALLOW_AUTO_OPEN}, + {"toast", ALLOW_ON_USER_GESTURE, DISALLOW_AUTO_OPEN}, + {"udif", ALLOW_ON_USER_GESTURE, DISALLOW_AUTO_OPEN}, #endif // Package management formats. OS_WIN package formats are handled above.
diff --git a/chrome/browser/engagement/site_engagement_eviction_policy.h b/chrome/browser/engagement/site_engagement_eviction_policy.h index d160beea..4266449 100644 --- a/chrome/browser/engagement/site_engagement_eviction_policy.h +++ b/chrome/browser/engagement/site_engagement_eviction_policy.h
@@ -8,10 +8,10 @@ #include <stdint.h> #include <map> +#include <memory> #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "storage/browser/quota/quota_manager.h" #include "url/gurl.h"
diff --git a/chrome/browser/engagement/site_engagement_eviction_policy_unittest.cc b/chrome/browser/engagement/site_engagement_eviction_policy_unittest.cc index 85127f9f..da297828 100644 --- a/chrome/browser/engagement/site_engagement_eviction_policy_unittest.cc +++ b/chrome/browser/engagement/site_engagement_eviction_policy_unittest.cc
@@ -2,15 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/engagement/site_engagement_eviction_policy.h" + #include <stdint.h> +#include <memory> + #include "base/files/scoped_temp_dir.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h" #include "base/thread_task_runner_handle.h" -#include "chrome/browser/engagement/site_engagement_eviction_policy.h" #include "chrome/browser/engagement/site_engagement_service.h" #include "content/public/test/mock_special_storage_policy.h" #include "content/public/test/mock_storage_client.h" @@ -84,7 +86,7 @@ } private: - scoped_ptr<TestSiteEngagementScoreProvider> score_provider_; + std::unique_ptr<TestSiteEngagementScoreProvider> score_provider_; scoped_refptr<content::MockSpecialStoragePolicy> storage_policy_; DISALLOW_COPY_AND_ASSIGN(SiteEngagementEvictionPolicyTest);
diff --git a/chrome/browser/engagement/site_engagement_helper.cc b/chrome/browser/engagement/site_engagement_helper.cc index 265580e0..5e9bdb1 100644 --- a/chrome/browser/engagement/site_engagement_helper.cc +++ b/chrome/browser/engagement/site_engagement_helper.cc
@@ -53,7 +53,7 @@ } void SiteEngagementHelper::PeriodicTracker::SetPauseTimerForTesting( - scoped_ptr<base::Timer> timer) { + std::unique_ptr<base::Timer> timer) { pause_timer_ = std::move(timer); }
diff --git a/chrome/browser/engagement/site_engagement_helper.h b/chrome/browser/engagement/site_engagement_helper.h index 0b002ab..4a56fb0 100644 --- a/chrome/browser/engagement/site_engagement_helper.h +++ b/chrome/browser/engagement/site_engagement_helper.h
@@ -57,7 +57,7 @@ bool IsTimerRunning(); // Set the timer object for testing. - void SetPauseTimerForTesting(scoped_ptr<base::Timer> timer); + void SetPauseTimerForTesting(std::unique_ptr<base::Timer> timer); SiteEngagementHelper* helper() { return helper_; } @@ -76,7 +76,7 @@ private: SiteEngagementHelper* helper_; - scoped_ptr<base::Timer> pause_timer_; + std::unique_ptr<base::Timer> pause_timer_; }; // Class to encapsulate time-on-site engagement detection. Time-on-site is
diff --git a/chrome/browser/engagement/site_engagement_helper_unittest.cc b/chrome/browser/engagement/site_engagement_helper_unittest.cc index 88a0719..919837f9 100644 --- a/chrome/browser/engagement/site_engagement_helper_unittest.cc +++ b/chrome/browser/engagement/site_engagement_helper_unittest.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/engagement/site_engagement_helper.h" +#include "base/memory/ptr_util.h" #include "base/test/histogram_tester.h" #include "base/timer/mock_timer.h" #include "base/values.h" @@ -69,13 +70,13 @@ // Set a pause timer on the input tracker for test purposes. void SetInputTrackerPauseTimer(SiteEngagementHelper* helper, - scoped_ptr<base::Timer> timer) { + std::unique_ptr<base::Timer> timer) { helper->input_tracker_.SetPauseTimerForTesting(std::move(timer)); } // Set a pause timer on the input tracker for test purposes. void SetMediaTrackerPauseTimer(SiteEngagementHelper* helper, - scoped_ptr<base::Timer> timer) { + std::unique_ptr<base::Timer> timer) { helper->media_tracker_.SetPauseTimerForTesting(std::move(timer)); } @@ -213,7 +214,7 @@ base::MockTimer* media_tracker_timer = new base::MockTimer(true, false); SiteEngagementHelper* helper = GetHelper(contents); - SetMediaTrackerPauseTimer(helper, make_scoped_ptr(media_tracker_timer)); + SetMediaTrackerPauseTimer(helper, base::WrapUnique(media_tracker_timer)); SiteEngagementService* service = SiteEngagementServiceFactory::GetForProfile(profile()); DCHECK(service); @@ -398,8 +399,8 @@ base::MockTimer* input_tracker_timer = new base::MockTimer(true, false); base::MockTimer* media_tracker_timer = new base::MockTimer(true, false); SiteEngagementHelper* helper = GetHelper(contents); - SetInputTrackerPauseTimer(helper, make_scoped_ptr(input_tracker_timer)); - SetMediaTrackerPauseTimer(helper, make_scoped_ptr(media_tracker_timer)); + SetInputTrackerPauseTimer(helper, base::WrapUnique(input_tracker_timer)); + SetMediaTrackerPauseTimer(helper, base::WrapUnique(media_tracker_timer)); SiteEngagementService* service = SiteEngagementServiceFactory::GetForProfile(profile()); @@ -506,8 +507,8 @@ base::MockTimer* input_tracker_timer = new base::MockTimer(true, false); base::MockTimer* media_tracker_timer = new base::MockTimer(true, false); SiteEngagementHelper* helper = GetHelper(contents); - SetInputTrackerPauseTimer(helper, make_scoped_ptr(input_tracker_timer)); - SetMediaTrackerPauseTimer(helper, make_scoped_ptr(media_tracker_timer)); + SetInputTrackerPauseTimer(helper, base::WrapUnique(input_tracker_timer)); + SetMediaTrackerPauseTimer(helper, base::WrapUnique(media_tracker_timer)); Navigate(url1); input_tracker_timer->Fire(); @@ -557,7 +558,7 @@ base::MockTimer* input_tracker_timer = new base::MockTimer(true, false); SiteEngagementHelper* helper = GetHelper(contents); - SetInputTrackerPauseTimer(helper, make_scoped_ptr(input_tracker_timer)); + SetInputTrackerPauseTimer(helper, base::WrapUnique(input_tracker_timer)); // Navigation should start the initial delay timer. Navigate(url1);
diff --git a/chrome/browser/engagement/site_engagement_service.cc b/chrome/browser/engagement/site_engagement_service.cc index b33670844..8eeb49c 100644 --- a/chrome/browser/engagement/site_engagement_service.cc +++ b/chrome/browser/engagement/site_engagement_service.cc
@@ -5,12 +5,14 @@ #include "chrome/browser/engagement/site_engagement_service.h" #include <stddef.h> + #include <algorithm> #include <cmath> #include <utility> #include <vector> #include "base/command_line.h" +#include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" @@ -67,9 +69,9 @@ // for which WEB_APP_INSTALLED_POINTS will be added to the engagement score. const int kMaxDaysSinceShortcutLaunch = 10; -scoped_ptr<ContentSettingsForOneType> GetEngagementContentSettings( +std::unique_ptr<ContentSettingsForOneType> GetEngagementContentSettings( HostContentSettingsMap* settings_map) { - scoped_ptr<ContentSettingsForOneType> engagement_settings( + std::unique_ptr<ContentSettingsForOneType> engagement_settings( new ContentSettingsForOneType); settings_map->GetSettingsForOneType(CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT, std::string(), engagement_settings.get()); @@ -97,22 +99,22 @@ ui::PAGE_TRANSITION_KEYWORD_GENERATED); } -scoped_ptr<base::DictionaryValue> GetScoreDictForOrigin( +std::unique_ptr<base::DictionaryValue> GetScoreDictForOrigin( HostContentSettingsMap* settings, const GURL& origin_url) { if (!settings) - return scoped_ptr<base::DictionaryValue>(); + return std::unique_ptr<base::DictionaryValue>(); - scoped_ptr<base::Value> value = settings->GetWebsiteSetting( + std::unique_ptr<base::Value> value = settings->GetWebsiteSetting( origin_url, origin_url, CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT, std::string(), NULL); if (!value.get()) - return make_scoped_ptr(new base::DictionaryValue()); + return base::WrapUnique(new base::DictionaryValue()); if (!value->IsType(base::Value::TYPE_DICTIONARY)) - return make_scoped_ptr(new base::DictionaryValue()); + return base::WrapUnique(new base::DictionaryValue()); - return make_scoped_ptr(static_cast<base::DictionaryValue*>(value.release())); + return base::WrapUnique(static_cast<base::DictionaryValue*>(value.release())); } } // namespace @@ -396,7 +398,7 @@ } SiteEngagementService::SiteEngagementService(Profile* profile) - : SiteEngagementService(profile, make_scoped_ptr(new base::DefaultClock)) { + : SiteEngagementService(profile, base::WrapUnique(new base::DefaultClock)) { content::BrowserThread::PostAfterStartupTask( FROM_HERE, content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::UI), @@ -451,7 +453,7 @@ HostContentSettingsMap* settings_map = HostContentSettingsMapFactory::GetForProfile(profile_); - scoped_ptr<base::DictionaryValue> score_dict = + std::unique_ptr<base::DictionaryValue> score_dict = GetScoreDictForOrigin(settings_map, url); SiteEngagementScore engagement_score(clock_.get(), *score_dict); @@ -491,7 +493,7 @@ void SiteEngagementService::SetLastShortcutLaunchTime(const GURL& url) { HostContentSettingsMap* settings_map = HostContentSettingsMapFactory::GetForProfile(profile_); - scoped_ptr<base::DictionaryValue> score_dict = + std::unique_ptr<base::DictionaryValue> score_dict = GetScoreDictForOrigin(settings_map, url); SiteEngagementScore score(clock_.get(), *score_dict); @@ -517,7 +519,7 @@ double SiteEngagementService::GetScore(const GURL& url) const { HostContentSettingsMap* settings_map = HostContentSettingsMapFactory::GetForProfile(profile_); - scoped_ptr<base::DictionaryValue> score_dict = + std::unique_ptr<base::DictionaryValue> score_dict = GetScoreDictForOrigin(settings_map, url); SiteEngagementScore score(clock_.get(), *score_dict); @@ -537,7 +539,7 @@ std::map<GURL, double> SiteEngagementService::GetScoreMap() const { HostContentSettingsMap* settings_map = HostContentSettingsMapFactory::GetForProfile(profile_); - scoped_ptr<ContentSettingsForOneType> engagement_settings = + std::unique_ptr<ContentSettingsForOneType> engagement_settings = GetEngagementContentSettings(settings_map); std::map<GURL, double> score_map; @@ -546,7 +548,7 @@ if (!origin.is_valid()) continue; - scoped_ptr<base::DictionaryValue> score_dict = + std::unique_ptr<base::DictionaryValue> score_dict = GetScoreDictForOrigin(settings_map, origin); SiteEngagementScore score(clock_.get(), *score_dict); score_map[origin] = score.Score(); @@ -603,7 +605,7 @@ } SiteEngagementService::SiteEngagementService(Profile* profile, - scoped_ptr<base::Clock> clock) + std::unique_ptr<base::Clock> clock) : profile_(profile), clock_(std::move(clock)), weak_factory_(this) { // May be null in tests. history::HistoryService* history = HistoryServiceFactory::GetForProfile( @@ -615,7 +617,7 @@ void SiteEngagementService::AddPoints(const GURL& url, double points) { HostContentSettingsMap* settings_map = HostContentSettingsMapFactory::GetForProfile(profile_); - scoped_ptr<base::DictionaryValue> score_dict = + std::unique_ptr<base::DictionaryValue> score_dict = GetScoreDictForOrigin(settings_map, url); SiteEngagementScore score(clock_.get(), *score_dict); @@ -635,13 +637,13 @@ void SiteEngagementService::CleanupEngagementScores() { HostContentSettingsMap* settings_map = HostContentSettingsMapFactory::GetForProfile(profile_); - scoped_ptr<ContentSettingsForOneType> engagement_settings = + std::unique_ptr<ContentSettingsForOneType> engagement_settings = GetEngagementContentSettings(settings_map); for (const auto& site : *engagement_settings) { GURL origin(site.primary_pattern.ToString()); if (origin.is_valid()) { - scoped_ptr<base::DictionaryValue> score_dict = + std::unique_ptr<base::DictionaryValue> score_dict = GetScoreDictForOrigin(settings_map, origin); SiteEngagementScore score(clock_.get(), *score_dict); if (score.Score() != 0) @@ -711,7 +713,7 @@ int SiteEngagementService::OriginsWithMaxDailyEngagement() const { HostContentSettingsMap* settings_map = HostContentSettingsMapFactory::GetForProfile(profile_); - scoped_ptr<ContentSettingsForOneType> engagement_settings = + std::unique_ptr<ContentSettingsForOneType> engagement_settings = GetEngagementContentSettings(settings_map); int total_origins = 0; @@ -722,7 +724,7 @@ if (!origin.is_valid()) continue; - scoped_ptr<base::DictionaryValue> score_dict = + std::unique_ptr<base::DictionaryValue> score_dict = GetScoreDictForOrigin(settings_map, origin); SiteEngagementScore score(clock_.get(), *score_dict); if (score.MaxPointsPerDayAdded())
diff --git a/chrome/browser/engagement/site_engagement_service.h b/chrome/browser/engagement/site_engagement_service.h index 4cfdc78a..554fb2df 100644 --- a/chrome/browser/engagement/site_engagement_service.h +++ b/chrome/browser/engagement/site_engagement_service.h
@@ -278,7 +278,7 @@ FRIEND_TEST_ALL_PREFIXES(AppBannerSettingsHelperTest, SiteEngagementTrigger); // Only used in tests. - SiteEngagementService(Profile* profile, scoped_ptr<base::Clock> clock); + SiteEngagementService(Profile* profile, std::unique_ptr<base::Clock> clock); // Adds the specified number of points to the given origin, respecting the // maximum limits for the day and overall. @@ -306,7 +306,7 @@ Profile* profile_; // The clock used to vend times. - scoped_ptr<base::Clock> clock_; + std::unique_ptr<base::Clock> clock_; // Metrics are recorded at non-incognito browser startup, and then // approximately once per hour thereafter. Store the local time at which
diff --git a/chrome/browser/engagement/site_engagement_service_unittest.cc b/chrome/browser/engagement/site_engagement_service_unittest.cc index 29cfa2e9..08da629 100644 --- a/chrome/browser/engagement/site_engagement_service_unittest.cc +++ b/chrome/browser/engagement/site_engagement_service_unittest.cc
@@ -8,6 +8,7 @@ #include "base/files/scoped_temp_dir.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/test/histogram_tester.h" #include "base/test/simple_test_clock.h" @@ -89,9 +90,10 @@ return base::Time::FromLocalExploded(exploded_reference_time); } -scoped_ptr<KeyedService> BuildTestHistoryService( +std::unique_ptr<KeyedService> BuildTestHistoryService( content::BrowserContext* context) { - scoped_ptr<history::HistoryService> service(new history::HistoryService()); + std::unique_ptr<history::HistoryService> service( + new history::HistoryService()); service->Init(history::TestHistoryDatabaseParamsForPath(g_temp_history_dir)); return std::move(service); } @@ -652,8 +654,8 @@ TEST_F(SiteEngagementServiceTest, LastShortcutLaunch) { base::SimpleTestClock* clock = new base::SimpleTestClock(); - scoped_ptr<SiteEngagementService> service( - new SiteEngagementService(profile(), make_scoped_ptr(clock))); + std::unique_ptr<SiteEngagementService> service( + new SiteEngagementService(profile(), base::WrapUnique(clock))); base::HistogramTester histograms; @@ -717,8 +719,8 @@ base::HistogramTester histograms; base::SimpleTestClock* clock = new base::SimpleTestClock(); - scoped_ptr<SiteEngagementService> service( - new SiteEngagementService(profile(), make_scoped_ptr(clock))); + std::unique_ptr<SiteEngagementService> service( + new SiteEngagementService(profile(), base::WrapUnique(clock))); base::Time current_day = GetReferenceTime(); clock->SetNow(current_day); @@ -982,8 +984,8 @@ // Expect that sites that have reached zero engagement are cleaned up. TEST_F(SiteEngagementServiceTest, CleanupEngagementScores) { base::SimpleTestClock* clock = new base::SimpleTestClock(); - scoped_ptr<SiteEngagementService> service( - new SiteEngagementService(profile(), make_scoped_ptr(clock))); + std::unique_ptr<SiteEngagementService> service( + new SiteEngagementService(profile(), base::WrapUnique(clock))); base::Time current_day = GetReferenceTime(); clock->SetNow(current_day); @@ -1080,8 +1082,8 @@ TEST_F(SiteEngagementServiceTest, IsBootstrapped) { base::SimpleTestClock* clock = new base::SimpleTestClock(); - scoped_ptr<SiteEngagementService> service( - new SiteEngagementService(profile(), make_scoped_ptr(clock))); + std::unique_ptr<SiteEngagementService> service( + new SiteEngagementService(profile(), base::WrapUnique(clock))); base::Time current_day = GetReferenceTime(); clock->SetNow(current_day); @@ -1192,8 +1194,8 @@ "enum values should not be equal"); base::SimpleTestClock* clock = new base::SimpleTestClock(); - scoped_ptr<SiteEngagementService> service( - new SiteEngagementService(profile(), make_scoped_ptr(clock))); + std::unique_ptr<SiteEngagementService> service( + new SiteEngagementService(profile(), base::WrapUnique(clock))); base::Time current_day = GetReferenceTime(); clock->SetNow(current_day); @@ -1292,8 +1294,8 @@ TEST_F(SiteEngagementServiceTest, ScoreDecayHistograms) { base::SimpleTestClock* clock = new base::SimpleTestClock(); - scoped_ptr<SiteEngagementService> service( - new SiteEngagementService(profile(), make_scoped_ptr(clock))); + std::unique_ptr<SiteEngagementService> service( + new SiteEngagementService(profile(), base::WrapUnique(clock))); base::Time current_day = GetReferenceTime(); clock->SetNow(current_day);
diff --git a/chrome/browser/enumerate_modules_model_win.cc b/chrome/browser/enumerate_modules_model_win.cc index 372f367..a199a9f 100644 --- a/chrome/browser/enumerate_modules_model_win.cc +++ b/chrome/browser/enumerate_modules_model_win.cc
@@ -4,11 +4,13 @@ #include "chrome/browser/enumerate_modules_model_win.h" +#include <Tlhelp32.h> #include <stddef.h> #include <stdint.h> -#include <Tlhelp32.h> #include <wintrust.h> + #include <algorithm> +#include <memory> #include "base/bind.h" #include "base/command_line.h" @@ -17,7 +19,6 @@ #include "base/files/file_path.h" #include "base/i18n/case_conversion.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/histogram.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" @@ -627,7 +628,7 @@ module->digital_signer = GetSubjectNameFromDigitalSignature(base::FilePath(module->location)); module->recommended_action = NONE; - scoped_ptr<FileVersionInfo> version_info( + std::unique_ptr<FileVersionInfo> version_info( FileVersionInfo::CreateFileVersionInfo(base::FilePath(module->location))); if (version_info.get()) { FileVersionInfoWin* version_info_win = @@ -663,7 +664,7 @@ void ModuleEnumerator::PreparePathMappings() { path_mapping_.clear(); - scoped_ptr<base::Environment> environment(base::Environment::Create()); + std::unique_ptr<base::Environment> environment(base::Environment::Create()); std::vector<base::string16> env_vars; env_vars.push_back(L"LOCALAPPDATA"); env_vars.push_back(L"ProgramFiles"); @@ -787,7 +788,7 @@ return base::string16(); // Allocate enough space to hold the signer info. - scoped_ptr<BYTE[]> signer_info_buffer(new BYTE[signer_info_size]); + std::unique_ptr<BYTE[]> signer_info_buffer(new BYTE[signer_info_size]); CMSG_SIGNER_INFO* signer_info = reinterpret_cast<CMSG_SIGNER_INFO*>(signer_info_buffer.get());
diff --git a/chrome/browser/errorpage_browsertest.cc b/chrome/browser/errorpage_browsertest.cc index 676f642ad88..eddd55d4 100644 --- a/chrome/browser/errorpage_browsertest.cc +++ b/chrome/browser/errorpage_browsertest.cc
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> #include <utility> #include "base/bind.h" @@ -10,7 +11,6 @@ #include "base/files/scoped_temp_dir.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/path_service.h" #include "base/strings/stringprintf.h" @@ -155,9 +155,8 @@ return l10n_util::GetStringUTF8(IDS_ERRORPAGES_BUTTON_SHOW_SAVED_COPY); } -void AddInterceptorForURL( - const GURL& url, - scoped_ptr<net::URLRequestInterceptor> handler) { +void AddInterceptorForURL(const GURL& url, + std::unique_ptr<net::URLRequestInterceptor> handler) { DCHECK_CURRENTLY_ON(BrowserThread::IO); net::URLRequestFilter::GetInstance()->AddUrlInterceptor(url, std::move(handler)); @@ -274,7 +273,7 @@ // These are only used on the UI thread. int num_requests_; int requests_to_wait_for_; - scoped_ptr<base::RunLoop> run_loop_; + std::unique_ptr<base::RunLoop> run_loop_; // This prevents any risk of flake if any test doesn't wait for a request // it sent. Mutable so it can be accessed from a const function. @@ -285,7 +284,7 @@ void InstallMockInterceptors( const GURL& search_url, - scoped_ptr<net::URLRequestInterceptor> link_doctor_interceptor) { + std::unique_ptr<net::URLRequestInterceptor> link_doctor_interceptor) { chrome_browser_net::SetUrlRequestMocksEnabled(true); AddInterceptorForURL(google_util::LinkDoctorBaseURL(), @@ -425,7 +424,7 @@ protected: void SetUpOnMainThread() override { link_doctor_interceptor_ = new LinkDoctorInterceptor(); - scoped_ptr<net::URLRequestInterceptor> owned_interceptor( + std::unique_ptr<net::URLRequestInterceptor> owned_interceptor( link_doctor_interceptor_); // Ownership of the |interceptor_| is passed to an object the IO thread, but // a pointer is kept in the test fixture. As soon as anything calls @@ -518,7 +517,7 @@ net::HttpCache* cache( getter->GetURLRequestContext()->http_transaction_factory()->GetCache()); DCHECK(cache); - scoped_ptr<net::HttpTransactionFactory> factory( + std::unique_ptr<net::HttpTransactionFactory> factory( new net::FailingHttpTransactionFactory(cache->GetSession(), error)); // Throw away old version; since this is a a browser test, we don't // need to restore the old state. @@ -1020,7 +1019,7 @@ void InstallInterceptor(const GURL& url, int requests_to_fail) { interceptor_ = new FailFirstNRequestsInterceptor(requests_to_fail); - scoped_ptr<net::URLRequestInterceptor> owned_interceptor(interceptor_); + std::unique_ptr<net::URLRequestInterceptor> owned_interceptor(interceptor_); // Tests don't need to wait for this task to complete before using the // filter; any requests that might be affected by it will end up in the IO @@ -1184,7 +1183,7 @@ net::URLRequestFilter::GetInstance()->AddUrlInterceptor( google_util::LinkDoctorBaseURL(), - scoped_ptr<net::URLRequestInterceptor>( + std::unique_ptr<net::URLRequestInterceptor>( new AddressUnreachableInterceptor())); } @@ -1266,7 +1265,7 @@ #if defined(OS_CHROMEOS) if (enroll_) { // Set up fake install attributes. - scoped_ptr<policy::StubEnterpriseInstallAttributes> attributes( + std::unique_ptr<policy::StubEnterpriseInstallAttributes> attributes( new policy::StubEnterpriseInstallAttributes()); attributes->SetDomain("example.com"); attributes->SetRegistrationUser("user@example.com");
diff --git a/chrome/browser/extensions/api/declarative_content/content_action.cc b/chrome/browser/extensions/api/declarative_content/content_action.cc index d8e1497..72d2aaa7 100644 --- a/chrome/browser/extensions/api/declarative_content/content_action.cc +++ b/chrome/browser/extensions/api/declarative_content/content_action.cc
@@ -39,6 +39,7 @@ "ImageData2}"; const char kInvalidInstanceTypeError[] = "An action has an invalid instanceType: %s"; +const char kMissingInstanceTypeError[] = "Action is missing instanceType"; const char kMissingParameter[] = "Missing parameter is required: %s"; const char kNoPageAction[] = "Can't use declarativeContent.ShowPageAction without a page action"; @@ -424,8 +425,10 @@ const base::DictionaryValue* action_dict = NULL; std::string instance_type; if (!(json_action.GetAsDictionary(&action_dict) && - action_dict->GetString(keys::kInstanceType, &instance_type))) + action_dict->GetString(keys::kInstanceType, &instance_type))) { + *error = kMissingInstanceTypeError; return std::unique_ptr<ContentAction>(); + } ContentActionFactory& factory = g_content_action_factory.Get(); std::map<std::string, ContentActionFactory::FactoryMethod>::iterator
diff --git a/chrome/browser/extensions/api/declarative_content/content_action_unittest.cc b/chrome/browser/extensions/api/declarative_content/content_action_unittest.cc index 37f605b..44454fed 100644 --- a/chrome/browser/extensions/api/declarative_content/content_action_unittest.cc +++ b/chrome/browser/extensions/api/declarative_content/content_action_unittest.cc
@@ -76,14 +76,14 @@ error.clear(); result = ContentAction::Create( NULL, NULL, *ParseJson("[]"), &error); - EXPECT_EQ("", error); + EXPECT_THAT(error, HasSubstr("missing instanceType")); EXPECT_FALSE(result.get()); // Test missing instanceType element. error.clear(); result = ContentAction::Create( NULL, NULL, *ParseJson("{}"), &error); - EXPECT_EQ("", error); + EXPECT_THAT(error, HasSubstr("missing instanceType")); EXPECT_FALSE(result.get()); // Test wrong instanceType element.
diff --git a/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc b/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc index 00cfcc2..05ce28ca 100644 --- a/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc +++ b/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc
@@ -326,6 +326,57 @@ << "Removing the matching element should hide the page action again."; } +// Test that adds two rules pointing to single action instance. +// Regression test for http://crbug.com/574149. +IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, ReusedActionInstance) { + ext_dir_.WriteManifest(kDeclarativeContentManifest); + ext_dir_.WriteFile( + FILE_PATH_LITERAL("background.js"), + "var declarative = chrome.declarative;\n" + "\n" + "var PageStateMatcher = chrome.declarativeContent.PageStateMatcher;\n" + "var ShowPageAction = chrome.declarativeContent.ShowPageAction;\n" + "var actionInstance = new ShowPageAction();\n" + "\n" + "var rule1 = {\n" + " conditions: [new PageStateMatcher({\n" + " pageUrl: {hostPrefix: \"test1\"}})],\n" + " actions: [actionInstance]\n" + "};\n" + "var rule2 = {\n" + " conditions: [new PageStateMatcher({\n" + " pageUrl: {hostPrefix: \"test\"}})],\n" + " actions: [actionInstance]\n" + "};\n" + "\n" + "var testEvent = chrome.declarativeContent.onPageChanged;\n" + "\n" + "testEvent.removeRules(undefined, function() {\n" + " testEvent.addRules([rule1, rule2], function() {\n" + " chrome.test.sendMessage(\"ready\");\n" + " });\n" + "});\n"); + ExtensionTestMessageListener ready("ready", false); + const Extension* extension = LoadExtension(ext_dir_.unpacked_path()); + ASSERT_TRUE(extension); + const ExtensionAction* page_action = + ExtensionActionManager::Get(browser()->profile()) + ->GetPageAction(*extension); + ASSERT_TRUE(page_action); + + ASSERT_TRUE(ready.WaitUntilSatisfied()); + content::WebContents* const tab = + browser()->tab_strip_model()->GetWebContentsAt(0); + const int tab_id = ExtensionTabUtil::GetTabId(tab); + + // This navigation matches both rules. + NavigateInRenderer(tab, GURL("http://test1/")); + + // Because the declarative rules were reusing action instance, addRules will + // fail and the page action won't be visible. + EXPECT_FALSE(page_action->GetIsVisible(tab_id)); +} + // Tests that the rules are evaluated at the time they are added or removed. IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, RulesEvaluatedOnAddRemove) { ext_dir_.WriteManifest(kDeclarativeContentManifest);
diff --git a/chrome/browser/extensions/api/tabs/tabs_event_router.cc b/chrome/browser/extensions/api/tabs/tabs_event_router.cc index 455ce42..5c430ef 100644 --- a/chrome/browser/extensions/api/tabs/tabs_event_router.cc +++ b/chrome/browser/extensions/api/tabs/tabs_event_router.cc
@@ -471,8 +471,10 @@ int index, TabChangeType change_type) { TabEntry* entry = GetTabEntry(contents); - CHECK(entry); - TabUpdated(entry, entry->UpdateLoadState()); + // TabClosingAt() may have already removed the entry for |contents| even + // though the tab has not yet been detached. + if (entry) + TabUpdated(entry, entry->UpdateLoadState()); } void TabsEventRouter::TabReplacedAt(TabStripModel* tab_strip_model,
diff --git a/chrome/browser/extensions/api/webrtc_logging_private/webrtc_event_log_apitest.cc b/chrome/browser/extensions/api/webrtc_logging_private/webrtc_event_log_apitest.cc index b621e23..726a8d9 100644 --- a/chrome/browser/extensions/api/webrtc_logging_private/webrtc_event_log_apitest.cc +++ b/chrome/browser/extensions/api/webrtc_logging_private/webrtc_event_log_apitest.cc
@@ -127,12 +127,13 @@ scoped_refptr<WebrtcLoggingPrivateStartWebRtcEventLoggingFunction> start_function(CreateExtensionFunction< WebrtcLoggingPrivateStartWebRtcEventLoggingFunction>()); - scoped_ptr<base::Value> start_result(utils::RunFunctionAndReturnSingleResult( - start_function.get(), ParamsToString(start_params), browser())); + std::unique_ptr<base::Value> start_result( + utils::RunFunctionAndReturnSingleResult( + start_function.get(), ParamsToString(start_params), browser())); ASSERT_TRUE(start_result.get()); // Get the file name. - scoped_ptr<extensions::api::webrtc_logging_private::RecordingInfo> + std::unique_ptr<extensions::api::webrtc_logging_private::RecordingInfo> recordings_info_start( extensions::api::webrtc_logging_private::RecordingInfo::FromValue( *start_result.get())); @@ -152,11 +153,12 @@ scoped_refptr<WebrtcLoggingPrivateStopWebRtcEventLoggingFunction> stop_function(CreateExtensionFunction< WebrtcLoggingPrivateStopWebRtcEventLoggingFunction>()); - scoped_ptr<base::Value> stop_result(utils::RunFunctionAndReturnSingleResult( - stop_function.get(), ParamsToString(stop_params), browser())); + std::unique_ptr<base::Value> stop_result( + utils::RunFunctionAndReturnSingleResult( + stop_function.get(), ParamsToString(stop_params), browser())); // Get the file name. - scoped_ptr<extensions::api::webrtc_logging_private::RecordingInfo> + std::unique_ptr<extensions::api::webrtc_logging_private::RecordingInfo> recordings_info_stop( extensions::api::webrtc_logging_private::RecordingInfo::FromValue( *stop_result.get())); @@ -218,12 +220,13 @@ scoped_refptr<WebrtcLoggingPrivateStartWebRtcEventLoggingFunction> start_function(CreateExtensionFunction< WebrtcLoggingPrivateStartWebRtcEventLoggingFunction>()); - scoped_ptr<base::Value> start_result(utils::RunFunctionAndReturnSingleResult( - start_function.get(), ParamsToString(start_params), browser())); + std::unique_ptr<base::Value> start_result( + utils::RunFunctionAndReturnSingleResult( + start_function.get(), ParamsToString(start_params), browser())); ASSERT_TRUE(start_result.get()); // Get the file name. - scoped_ptr<extensions::api::webrtc_logging_private::RecordingInfo> + std::unique_ptr<extensions::api::webrtc_logging_private::RecordingInfo> recordings_info_start( extensions::api::webrtc_logging_private::RecordingInfo::FromValue( *start_result.get()));
diff --git a/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc b/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc index 291e7da..bd0d7f3 100644 --- a/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc +++ b/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc
@@ -456,7 +456,7 @@ return false; } - scoped_ptr<StartWebRtcEventLogging::Params> params( + std::unique_ptr<StartWebRtcEventLogging::Params> params( StartWebRtcEventLogging::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -491,7 +491,7 @@ return false; } - scoped_ptr<StopWebRtcEventLogging::Params> params( + std::unique_ptr<StopWebRtcEventLogging::Params> params( StopWebRtcEventLogging::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get());
diff --git a/chrome/browser/favicon/content_favicon_driver_browsertest.cc b/chrome/browser/favicon/content_favicon_driver_browsertest.cc index 12101ba..eb782f3 100644 --- a/chrome/browser/favicon/content_favicon_driver_browsertest.cc +++ b/chrome/browser/favicon/content_favicon_driver_browsertest.cc
@@ -210,7 +210,7 @@ GURL url = embedded_test_server()->GetURL("/favicon/page_with_favicon.html"); GURL icon_url = embedded_test_server()->GetURL("/favicon/icon.png"); - scoped_ptr<TestResourceDispatcherHostDelegate> delegate( + std::unique_ptr<TestResourceDispatcherHostDelegate> delegate( new TestResourceDispatcherHostDelegate(icon_url)); content::ResourceDispatcherHost::Get()->SetDelegate(delegate.get());
diff --git a/chrome/browser/favicon/favicon_service_factory.cc b/chrome/browser/favicon/favicon_service_factory.cc index c15ba95..d1717cb 100644 --- a/chrome/browser/favicon/favicon_service_factory.cc +++ b/chrome/browser/favicon/favicon_service_factory.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/favicon/favicon_service_factory.h" +#include "base/memory/ptr_util.h" #include "base/memory/singleton.h" #include "chrome/browser/favicon/chrome_favicon_client.h" #include "chrome/browser/history/history_service_factory.h" @@ -15,10 +16,11 @@ namespace { -scoped_ptr<KeyedService> BuildFaviconService(content::BrowserContext* context) { +std::unique_ptr<KeyedService> BuildFaviconService( + content::BrowserContext* context) { Profile* profile = Profile::FromBrowserContext(context); - return make_scoped_ptr(new favicon::FaviconService( - make_scoped_ptr(new ChromeFaviconClient(profile)), + return base::WrapUnique(new favicon::FaviconService( + base::WrapUnique(new ChromeFaviconClient(profile)), HistoryServiceFactory::GetForProfile( profile, ServiceAccessType::EXPLICIT_ACCESS))); }
diff --git a/chrome/browser/feedback/system_logs/log_sources/chrome_internal_log_source.cc b/chrome/browser/feedback/system_logs/log_sources/chrome_internal_log_source.cc index c2cccc16..804875e 100644 --- a/chrome/browser/feedback/system_logs/log_sources/chrome_internal_log_source.cc +++ b/chrome/browser/feedback/system_logs/log_sources/chrome_internal_log_source.cc
@@ -112,7 +112,7 @@ ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile); - scoped_ptr<base::DictionaryValue> sync_logs( + std::unique_ptr<base::DictionaryValue> sync_logs( sync_driver::sync_ui_util::ConstructAboutInformation( service, service->signin(), chrome::GetChannel()));
diff --git a/chrome/browser/feedback/system_logs/log_sources/memory_details_log_source.cc b/chrome/browser/feedback/system_logs/log_sources/memory_details_log_source.cc index ecaf6b7..bdcfd7f 100644 --- a/chrome/browser/feedback/system_logs/log_sources/memory_details_log_source.cc +++ b/chrome/browser/feedback/system_logs/log_sources/memory_details_log_source.cc
@@ -21,7 +21,7 @@ void OnDetailsAvailable() override { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - scoped_ptr<SystemLogsResponse> response(new SystemLogsResponse); + std::unique_ptr<SystemLogsResponse> response(new SystemLogsResponse); (*response)["mem_usage"] = ToLogString(); callback_.Run(response.get()); }
diff --git a/chrome/browser/feedback/system_logs/system_logs_fetcher_base.h b/chrome/browser/feedback/system_logs/system_logs_fetcher_base.h index 349c448..9526da1 100644 --- a/chrome/browser/feedback/system_logs/system_logs_fetcher_base.h +++ b/chrome/browser/feedback/system_logs/system_logs_fetcher_base.h
@@ -8,11 +8,11 @@ #include <stddef.h> #include <map> +#include <memory> #include <string> #include "base/callback.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/memory/weak_ptr.h" @@ -25,7 +25,7 @@ SysLogsSourceCallback; // Callback that the SystemLogsFetcherBase uses to return data. -typedef base::Callback<void(scoped_ptr<SystemLogsResponse> response)> +typedef base::Callback<void(std::unique_ptr<SystemLogsResponse> response)> SysLogsFetcherCallback; // The SystemLogsSource provides a interface for the data sources that @@ -86,7 +86,7 @@ ScopedVector<SystemLogsSource> data_sources_; SysLogsFetcherCallback callback_; - scoped_ptr<SystemLogsResponse> response_; // The actual response data. + std::unique_ptr<SystemLogsResponse> response_; // The actual response data. size_t num_pending_requests_; // The number of callbacks it should get. private:
diff --git a/chrome/browser/file_select_helper.cc b/chrome/browser/file_select_helper.cc index 046a310..5ea49d7 100644 --- a/chrome/browser/file_select_helper.cc +++ b/chrome/browser/file_select_helper.cc
@@ -12,6 +12,7 @@ #include "base/bind.h" #include "base/files/file_enumerator.h" #include "base/files/file_util.h" +#include "base/memory/ptr_util.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -89,8 +90,8 @@ struct FileSelectHelper::ActiveDirectoryEnumeration { ActiveDirectoryEnumeration() : rvh_(NULL) {} - scoped_ptr<DirectoryListerDispatchDelegate> delegate_; - scoped_ptr<net::DirectoryLister> lister_; + std::unique_ptr<DirectoryListerDispatchDelegate> delegate_; + std::unique_ptr<net::DirectoryLister> lister_; RenderViewHost* rvh_; std::vector<base::FilePath> results_; }; @@ -199,7 +200,8 @@ void FileSelectHelper::StartNewEnumeration(const base::FilePath& path, int request_id, RenderViewHost* render_view_host) { - scoped_ptr<ActiveDirectoryEnumeration> entry(new ActiveDirectoryEnumeration); + std::unique_ptr<ActiveDirectoryEnumeration> entry( + new ActiveDirectoryEnumeration); entry->rvh_ = render_view_host; entry->delegate_.reset(new DirectoryListerDispatchDelegate(this, request_id)); entry->lister_.reset(new net::DirectoryLister( @@ -229,7 +231,8 @@ void FileSelectHelper::OnListDone(int id, int error) { // This entry needs to be cleaned up when this function is done. - scoped_ptr<ActiveDirectoryEnumeration> entry(directory_enumerations_[id]); + std::unique_ptr<ActiveDirectoryEnumeration> entry( + directory_enumerations_[id]); directory_enumerations_.erase(id); if (!entry->rvh_) return; @@ -316,16 +319,16 @@ } } -scoped_ptr<ui::SelectFileDialog::FileTypeInfo> +std::unique_ptr<ui::SelectFileDialog::FileTypeInfo> FileSelectHelper::GetFileTypesFromAcceptType( const std::vector<base::string16>& accept_types) { - scoped_ptr<ui::SelectFileDialog::FileTypeInfo> base_file_type( + std::unique_ptr<ui::SelectFileDialog::FileTypeInfo> base_file_type( new ui::SelectFileDialog::FileTypeInfo()); if (accept_types.empty()) return base_file_type; // Create FileTypeInfo and pre-allocate for the first extension list. - scoped_ptr<ui::SelectFileDialog::FileTypeInfo> file_type( + std::unique_ptr<ui::SelectFileDialog::FileTypeInfo> file_type( new ui::SelectFileDialog::FileTypeInfo(*base_file_type)); file_type->include_all_files = true; file_type->extensions.resize(1); @@ -393,7 +396,7 @@ new FileSelectHelper(profile)); file_select_helper->RunFileChooser( tab->GetRenderViewHost(), tab, - make_scoped_ptr(new content::FileChooserParams(params))); + base::WrapUnique(new content::FileChooserParams(params))); } // static @@ -408,9 +411,10 @@ request_id, tab->GetRenderViewHost(), path); } -void FileSelectHelper::RunFileChooser(RenderViewHost* render_view_host, - content::WebContents* web_contents, - scoped_ptr<FileChooserParams> params) { +void FileSelectHelper::RunFileChooser( + RenderViewHost* render_view_host, + content::WebContents* web_contents, + std::unique_ptr<FileChooserParams> params) { DCHECK(!render_view_host_); DCHECK(!web_contents_); DCHECK(params->default_file_name.empty() || @@ -442,7 +446,7 @@ } void FileSelectHelper::GetFileTypesOnFileThread( - scoped_ptr<FileChooserParams> params) { + std::unique_ptr<FileChooserParams> params) { select_file_types_ = GetFileTypesFromAcceptType(params->accept_types); select_file_types_->allowed_paths = params->need_local_path ? ui::SelectFileDialog::FileTypeInfo::NATIVE_PATH @@ -455,7 +459,7 @@ } void FileSelectHelper::GetSanitizedFilenameOnUIThread( - scoped_ptr<FileChooserParams> params) { + std::unique_ptr<FileChooserParams> params) { base::FilePath default_file_path = profile_->last_selected_directory().Append( GetSanitizedFileName(params->default_file_name)); @@ -487,7 +491,7 @@ #if defined(FULL_SAFE_BROWSING) void FileSelectHelper::ApplyUnverifiedDownloadPolicy( const base::FilePath& default_path, - scoped_ptr<FileChooserParams> params, + std::unique_ptr<FileChooserParams> params, safe_browsing::UnverifiedDownloadPolicy policy) { DCHECK(params); if (policy == safe_browsing::UnverifiedDownloadPolicy::DISALLOWED) { @@ -501,7 +505,7 @@ void FileSelectHelper::RunFileChooserOnUIThread( const base::FilePath& default_file_path, - scoped_ptr<FileChooserParams> params) { + std::unique_ptr<FileChooserParams> params) { DCHECK(params); if (!render_view_host_ || !web_contents_ || !IsValidProfile(profile_) || !render_view_host_->GetWidget()->GetView()) {
diff --git a/chrome/browser/file_select_helper.h b/chrome/browser/file_select_helper.h index 3011f13f..531ce927 100644 --- a/chrome/browser/file_select_helper.h +++ b/chrome/browser/file_select_helper.h
@@ -6,12 +6,12 @@ #define CHROME_BROWSER_FILE_SELECT_HELPER_H_ #include <map> +#include <memory> #include <vector> #include "base/compiler_specific.h" #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "build/build_config.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_observer.h" @@ -95,18 +95,20 @@ void RunFileChooser(content::RenderViewHost* render_view_host, content::WebContents* web_contents, - scoped_ptr<content::FileChooserParams> params); - void GetFileTypesOnFileThread(scoped_ptr<content::FileChooserParams> params); + std::unique_ptr<content::FileChooserParams> params); + void GetFileTypesOnFileThread( + std::unique_ptr<content::FileChooserParams> params); void GetSanitizedFilenameOnUIThread( - scoped_ptr<content::FileChooserParams> params); + std::unique_ptr<content::FileChooserParams> params); #if defined(FULL_SAFE_BROWSING) void ApplyUnverifiedDownloadPolicy( const base::FilePath& default_path, - scoped_ptr<content::FileChooserParams> params, + std::unique_ptr<content::FileChooserParams> params, safe_browsing::UnverifiedDownloadPolicy policy); #endif - void RunFileChooserOnUIThread(const base::FilePath& default_path, - scoped_ptr<content::FileChooserParams> params); + void RunFileChooserOnUIThread( + const base::FilePath& default_path, + std::unique_ptr<content::FileChooserParams> params); // Cleans up and releases this instance. This must be called after the last // callback is received from the file chooser dialog. @@ -194,9 +196,8 @@ // http://whatwg.org/html/number-state.html#attr-input-accept // |accept_types| contains only valid lowercased MIME types or file extensions // beginning with a period (.). - static scoped_ptr<ui::SelectFileDialog::FileTypeInfo> - GetFileTypesFromAcceptType( - const std::vector<base::string16>& accept_types); + static std::unique_ptr<ui::SelectFileDialog::FileTypeInfo> + GetFileTypesFromAcceptType(const std::vector<base::string16>& accept_types); // Check the accept type is valid. It is expected to be all lower case with // no whitespace. @@ -228,7 +229,7 @@ // Dialog box used for choosing files to upload from file form fields. scoped_refptr<ui::SelectFileDialog> select_file_dialog_; - scoped_ptr<ui::SelectFileDialog::FileTypeInfo> select_file_types_; + std::unique_ptr<ui::SelectFileDialog::FileTypeInfo> select_file_types_; // The type of file dialog last shown. ui::SelectFileDialog::Type dialog_type_;
diff --git a/chrome/browser/first_run/first_run.cc b/chrome/browser/first_run/first_run.cc index dbe86066..e2fa0b8 100644 --- a/chrome/browser/first_run/first_run.cc +++ b/chrome/browser/first_run/first_run.cc
@@ -282,7 +282,7 @@ // Imports settings from the first profile in |importer_list|. void ImportSettings(Profile* profile, - scoped_ptr<ImporterList> importer_list, + std::unique_ptr<ImporterList> importer_list, int items_to_import) { const importer::SourceProfile& source_profile = importer_list->GetSourceProfileAt(0); @@ -724,7 +724,8 @@ MasterPrefs* out_prefs) { DCHECK(!user_data_dir.empty()); - scoped_ptr<installer::MasterPreferences> install_prefs(LoadMasterPrefs()); + std::unique_ptr<installer::MasterPreferences> install_prefs( + LoadMasterPrefs()); // Default value in case master preferences is missing or corrupt, or // ping_delay is missing. @@ -760,7 +761,7 @@ // It may be possible to do the if block below asynchronously. In which case, // get rid of this RunLoop. http://crbug.com/366116. base::RunLoop run_loop; - scoped_ptr<ImporterList> importer_list(new ImporterList()); + std::unique_ptr<ImporterList> importer_list(new ImporterList()); importer_list->DetectSourceProfiles( g_browser_process->GetApplicationLocale(), false, // include_interactive_profiles?
diff --git a/chrome/browser/first_run/first_run_browsertest.cc b/chrome/browser/first_run/first_run_browsertest.cc index 519edab1..90250a4 100644 --- a/chrome/browser/first_run/first_run_browsertest.cc +++ b/chrome/browser/first_run/first_run_browsertest.cc
@@ -119,7 +119,7 @@ private: base::FilePath prefs_file_; - scoped_ptr<std::string> text_; + std::unique_ptr<std::string> text_; DISALLOW_COPY_AND_ASSIGN(FirstRunMasterPrefsBrowserTestBase); }; @@ -145,7 +145,7 @@ // bot configurations do not have another profile (browser) to import from and // thus the import must not be expected to have occurred. int MaskExpectedImportState(int expected_import_state) { - scoped_ptr<ImporterList> importer_list(new ImporterList()); + std::unique_ptr<ImporterList> importer_list(new ImporterList()); base::RunLoop run_loop; importer_list->DetectSourceProfiles( g_browser_process->GetApplicationLocale(),
diff --git a/chrome/browser/geolocation/geolocation_browsertest.cc b/chrome/browser/geolocation/geolocation_browsertest.cc index b3ec172..d440c861 100644 --- a/chrome/browser/geolocation/geolocation_browsertest.cc +++ b/chrome/browser/geolocation/geolocation_browsertest.cc
@@ -738,7 +738,7 @@ ASSERT_NO_FATAL_FAILURE(Initialize(INITIALIZATION_DEFAULT)); base::SimpleTestClock* clock_ = new base::SimpleTestClock(); GetHostContentSettingsMap()->SetPrefClockForTesting( - scoped_ptr<base::Clock>(clock_)); + std::unique_ptr<base::Clock>(clock_)); clock_->SetNow(base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(10)); // Setting the permission should trigger the last usage.
diff --git a/chrome/browser/geolocation/geolocation_infobar_delegate_android.cc b/chrome/browser/geolocation/geolocation_infobar_delegate_android.cc index 523f08c2..a4b18a6 100644 --- a/chrome/browser/geolocation/geolocation_infobar_delegate_android.cc +++ b/chrome/browser/geolocation/geolocation_infobar_delegate_android.cc
@@ -18,8 +18,8 @@ const GURL& requesting_frame, const PermissionSetCallback& callback) { return infobar_service->AddInfoBar(infobar_service->CreateConfirmInfoBar( - scoped_ptr<ConfirmInfoBarDelegate>(new GeolocationInfoBarDelegateAndroid( - requesting_frame, callback)))); + std::unique_ptr<ConfirmInfoBarDelegate>( + new GeolocationInfoBarDelegateAndroid(requesting_frame, callback)))); } GeolocationInfoBarDelegateAndroid::GeolocationInfoBarDelegateAndroid(
diff --git a/chrome/browser/geolocation/geolocation_permission_context_android.cc b/chrome/browser/geolocation/geolocation_permission_context_android.cc index 57fa1df..cabc47409 100644 --- a/chrome/browser/geolocation/geolocation_permission_context_android.cc +++ b/chrome/browser/geolocation/geolocation_permission_context_android.cc
@@ -92,6 +92,6 @@ } void GeolocationPermissionContextAndroid::SetLocationSettingsForTesting( - scoped_ptr<LocationSettings> settings) { + std::unique_ptr<LocationSettings> settings) { location_settings_ = std::move(settings); }
diff --git a/chrome/browser/geolocation/geolocation_permission_context_android.h b/chrome/browser/geolocation/geolocation_permission_context_android.h index 012839f8..443352f 100644 --- a/chrome/browser/geolocation/geolocation_permission_context_android.h +++ b/chrome/browser/geolocation/geolocation_permission_context_android.h
@@ -20,8 +20,9 @@ // infobars, etc.). // // Otherwise the permission is already decided. +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/geolocation/geolocation_permission_context.h" @@ -63,9 +64,10 @@ // Overrides the LocationSettings object used to determine whether // system and Chrome-wide location permissions are enabled. - void SetLocationSettingsForTesting(scoped_ptr<LocationSettings> settings); + void SetLocationSettingsForTesting( + std::unique_ptr<LocationSettings> settings); - scoped_ptr<LocationSettings> location_settings_; + std::unique_ptr<LocationSettings> location_settings_; // This is owned by the InfoBarService (owner of the InfoBar). infobars::InfoBar* permission_update_infobar_;
diff --git a/chrome/browser/geolocation/geolocation_permission_context_unittest.cc b/chrome/browser/geolocation/geolocation_permission_context_unittest.cc index 1360fd14..e62eb4b5 100644 --- a/chrome/browser/geolocation/geolocation_permission_context_unittest.cc +++ b/chrome/browser/geolocation/geolocation_permission_context_unittest.cc
@@ -16,6 +16,7 @@ #include "base/containers/hash_tables.h" #include "base/gtest_prod_util.h" #include "base/id_map.h" +#include "base/memory/ptr_util.h" #include "base/synchronization/waitable_event.h" #include "base/test/simple_test_clock.h" #include "base/time/clock.h" @@ -164,9 +165,9 @@ // owned by the browser context GeolocationPermissionContext* geolocation_permission_context_; ClosedInfoBarTracker closed_infobar_tracker_; - std::vector<scoped_ptr<content::WebContents>> extra_tabs_; + std::vector<std::unique_ptr<content::WebContents>> extra_tabs_; #if !BUILDFLAG(ANDROID_JAVA_UI) - std::vector<scoped_ptr<MockPermissionBubbleFactory>> + std::vector<std::unique_ptr<MockPermissionBubbleFactory>> mock_permission_bubble_factories_; #endif @@ -254,7 +255,7 @@ SetupBubbleManager(new_tab); #endif - extra_tabs_.push_back(make_scoped_ptr(new_tab)); + extra_tabs_.push_back(base::WrapUnique(new_tab)); } void GeolocationPermissionContextTests::CheckTabContentsState( @@ -289,7 +290,7 @@ static_cast<GeolocationPermissionContextAndroid*>( geolocation_permission_context_) ->SetLocationSettingsForTesting( - scoped_ptr<LocationSettings>(new MockLocationSettings())); + std::unique_ptr<LocationSettings>(new MockLocationSettings())); MockLocationSettings::SetLocationStatus(true, true); #else SetupBubbleManager(web_contents()); @@ -313,7 +314,7 @@ PermissionBubbleManager::FromWebContents(web_contents); // Create a MockPermissionBubbleFactory for the PermissionBubbleManager. - mock_permission_bubble_factories_.push_back(make_scoped_ptr( + mock_permission_bubble_factories_.push_back(base::WrapUnique( new MockPermissionBubbleFactory(false, permission_bubble_manager))); // Prepare the PermissionBubbleManager to display a mock bubble. @@ -857,7 +858,7 @@ HostContentSettingsMap* map = HostContentSettingsMapFactory::GetForProfile(profile()); - map->SetPrefClockForTesting(scoped_ptr<base::Clock>(test_clock)); + map->SetPrefClockForTesting(std::unique_ptr<base::Clock>(test_clock)); // The permission shouldn't have been used yet. EXPECT_EQ(map->GetLastUsage(requesting_frame.GetOrigin(), @@ -895,7 +896,7 @@ HostContentSettingsMap* map = HostContentSettingsMapFactory::GetForProfile(profile()); - map->SetPrefClockForTesting(scoped_ptr<base::Clock>(test_clock)); + map->SetPrefClockForTesting(std::unique_ptr<base::Clock>(test_clock)); GURL requesting_frame_0("https://www.example.com/geolocation"); GURL requesting_frame_1("https://www.example-2.com/geolocation");
diff --git a/chrome/browser/geolocation/geolocation_settings_state_unittest.cc b/chrome/browser/geolocation/geolocation_settings_state_unittest.cc index 947b46f..20c79b4 100644 --- a/chrome/browser/geolocation/geolocation_settings_state_unittest.cc +++ b/chrome/browser/geolocation/geolocation_settings_state_unittest.cc
@@ -35,7 +35,7 @@ GeolocationSettingsState state(&profile); GURL url_0("http://www.example.com"); - scoped_ptr<NavigationEntry> entry(NavigationEntry::Create()); + std::unique_ptr<NavigationEntry> entry(NavigationEntry::Create()); entry->SetURL(url_0); content::LoadCommittedDetails load_committed_details; load_committed_details.entry = entry.get(); @@ -136,7 +136,7 @@ GeolocationSettingsState state(&profile); GURL url_0("http://www.example.com"); - scoped_ptr<NavigationEntry> entry(NavigationEntry::Create()); + std::unique_ptr<NavigationEntry> entry(NavigationEntry::Create()); entry->SetURL(url_0); content::LoadCommittedDetails load_committed_details; load_committed_details.entry = entry.get();
diff --git a/chrome/browser/google/google_url_tracker_factory.cc b/chrome/browser/google/google_url_tracker_factory.cc index 1485681..d7ed50e 100644 --- a/chrome/browser/google/google_url_tracker_factory.cc +++ b/chrome/browser/google/google_url_tracker_factory.cc
@@ -41,7 +41,7 @@ static_cast<Profile*>(context)->GetOriginalProfile()->GetPrefs()->ClearPref( prefs::kLastPromptedGoogleURL); - scoped_ptr<GoogleURLTrackerClient> client( + std::unique_ptr<GoogleURLTrackerClient> client( new ChromeGoogleURLTrackerClient(Profile::FromBrowserContext(context))); return new GoogleURLTracker(std::move(client), GoogleURLTracker::NORMAL_MODE); }
diff --git a/chrome/browser/gpu/three_d_api_observer.cc b/chrome/browser/gpu/three_d_api_observer.cc index 2fa88038..1992cc3 100644 --- a/chrome/browser/gpu/three_d_api_observer.cc +++ b/chrome/browser/gpu/three_d_api_observer.cc
@@ -66,8 +66,8 @@ content::ThreeDAPIType requester) { if (!infobar_service) return; // NULL for apps. - infobar_service->AddInfoBar( - infobar_service->CreateConfirmInfoBar(scoped_ptr<ConfirmInfoBarDelegate>( + infobar_service->AddInfoBar(infobar_service->CreateConfirmInfoBar( + std::unique_ptr<ConfirmInfoBarDelegate>( new ThreeDAPIInfoBarDelegate(url, requester)))); }
diff --git a/chrome/browser/guest_view/app_view/chrome_app_view_guest_delegate.cc b/chrome/browser/guest_view/app_view/chrome_app_view_guest_delegate.cc index d7a27b2..09c811da 100644 --- a/chrome/browser/guest_view/app_view/chrome_app_view_guest_delegate.cc +++ b/chrome/browser/guest_view/app_view/chrome_app_view_guest_delegate.cc
@@ -25,7 +25,7 @@ ContextMenuDelegate::FromWebContents(web_contents); DCHECK(menu_delegate); - scoped_ptr<RenderViewContextMenuBase> menu = + std::unique_ptr<RenderViewContextMenuBase> menu = menu_delegate->BuildMenu(web_contents, params); menu_delegate->ShowMenu(std::move(menu)); return true;
diff --git a/chrome/browser/guest_view/extension_options/chrome_extension_options_guest_delegate.cc b/chrome/browser/guest_view/extension_options/chrome_extension_options_guest_delegate.cc index d21ceb9..087013a 100644 --- a/chrome/browser/guest_view/extension_options/chrome_extension_options_guest_delegate.cc +++ b/chrome/browser/guest_view/extension_options/chrome_extension_options_guest_delegate.cc
@@ -28,7 +28,7 @@ extension_options_guest()->web_contents()); DCHECK(menu_delegate); - scoped_ptr<RenderViewContextMenuBase> menu = menu_delegate->BuildMenu( + std::unique_ptr<RenderViewContextMenuBase> menu = menu_delegate->BuildMenu( extension_options_guest()->web_contents(), params); menu_delegate->ShowMenu(std::move(menu)); return true;
diff --git a/chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_guest_delegate.cc b/chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_guest_delegate.cc index 224efb1..e22f0b4 100644 --- a/chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_guest_delegate.cc +++ b/chrome/browser/guest_view/mime_handler_view/chrome_mime_handler_view_guest_delegate.cc
@@ -24,7 +24,7 @@ ContextMenuDelegate::FromWebContents(web_contents); DCHECK(menu_delegate); - scoped_ptr<RenderViewContextMenuBase> menu = + std::unique_ptr<RenderViewContextMenuBase> menu = menu_delegate->BuildMenu(web_contents, params); menu_delegate->ShowMenu(std::move(menu)); return true;
diff --git a/chrome/browser/guest_view/web_view/chrome_web_view_guest_delegate.cc b/chrome/browser/guest_view/web_view/chrome_web_view_guest_delegate.cc index 32a0088..5d3dee9 100644 --- a/chrome/browser/guest_view/web_view/chrome_web_view_guest_delegate.cc +++ b/chrome/browser/guest_view/web_view/chrome_web_view_guest_delegate.cc
@@ -7,6 +7,7 @@ #include <utility> +#include "base/memory/ptr_util.h" #include "build/build_config.h" #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h" #include "chrome/browser/favicon/favicon_utils.h" @@ -62,12 +63,12 @@ // Pass it to embedder. int request_id = ++pending_context_menu_request_id_; - scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue()); - scoped_ptr<base::ListValue> items = + std::unique_ptr<base::DictionaryValue> args(new base::DictionaryValue()); + std::unique_ptr<base::ListValue> items = MenuModelToValue(pending_menu_->menu_model()); args->Set(webview::kContextMenuItems, items.release()); args->SetInteger(webview::kRequestId, request_id); - web_view_guest()->DispatchEventToView(make_scoped_ptr( + web_view_guest()->DispatchEventToView(base::WrapUnique( new GuestViewEvent(webview::kEventContextMenuShow, std::move(args)))); return true; } @@ -84,9 +85,9 @@ } // static -scoped_ptr<base::ListValue> ChromeWebViewGuestDelegate::MenuModelToValue( +std::unique_ptr<base::ListValue> ChromeWebViewGuestDelegate::MenuModelToValue( const ui::SimpleMenuModel& menu_model) { - scoped_ptr<base::ListValue> items(new base::ListValue()); + std::unique_ptr<base::ListValue> items(new base::ListValue()); for (int i = 0; i < menu_model.GetItemCount(); ++i) { base::DictionaryValue* item_value = new base::DictionaryValue(); // TODO(lazyboy): We need to expose some kind of enum equivalent of
diff --git a/chrome/browser/guest_view/web_view/chrome_web_view_guest_delegate.h b/chrome/browser/guest_view/web_view/chrome_web_view_guest_delegate.h index e9f31086..3419de7 100644 --- a/chrome/browser/guest_view/web_view/chrome_web_view_guest_delegate.h +++ b/chrome/browser/guest_view/web_view/chrome_web_view_guest_delegate.h
@@ -44,7 +44,7 @@ void SetContextMenuPosition(const gfx::Point& position) override; // Returns the top level items (ignoring submenus) as Value. - static scoped_ptr<base::ListValue> MenuModelToValue( + static std::unique_ptr<base::ListValue> MenuModelToValue( const ui::SimpleMenuModel& menu_model); void InjectChromeVoxIfNeeded(content::RenderViewHost* render_view_host); @@ -64,17 +64,17 @@ // Holds the RenderViewContextMenuBase that has been built but yet to be // shown. This is .reset() after ShowContextMenu(). - scoped_ptr<RenderViewContextMenuBase> pending_menu_; + std::unique_ptr<RenderViewContextMenuBase> pending_menu_; #if defined(OS_CHROMEOS) // Subscription to receive notifications on changes to a11y settings. - scoped_ptr<chromeos::AccessibilityStatusSubscription> + std::unique_ptr<chromeos::AccessibilityStatusSubscription> accessibility_subscription_; #endif WebViewGuest* const web_view_guest_; - scoped_ptr<gfx::Point> context_menu_position_; + std::unique_ptr<gfx::Point> context_menu_position_; // This is used to ensure pending tasks will not fire after this object is // destroyed.
diff --git a/chrome/browser/icon_loader.h b/chrome/browser/icon_loader.h index a25532f..33301ac 100644 --- a/chrome/browser/icon_loader.h +++ b/chrome/browser/icon_loader.h
@@ -5,15 +5,14 @@ #ifndef CHROME_BROWSER_ICON_LOADER_H_ #define CHROME_BROWSER_ICON_LOADER_H_ -#include "build/build_config.h" - +#include <memory> #include <string> #include "base/files/file_path.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/single_thread_task_runner.h" +#include "build/build_config.h" #include "content/public/browser/browser_thread.h" #include "ui/gfx/image/image.h" @@ -96,7 +95,7 @@ IconSize icon_size_; - scoped_ptr<gfx::Image> image_; + std::unique_ptr<gfx::Image> image_; Delegate* delegate_;
diff --git a/chrome/browser/icon_loader_win.cc b/chrome/browser/icon_loader_win.cc index f12050a1..9378295 100644 --- a/chrome/browser/icon_loader_win.cc +++ b/chrome/browser/icon_loader_win.cc
@@ -58,8 +58,8 @@ if (SHGetFileInfo(group_.c_str(), FILE_ATTRIBUTE_NORMAL, &file_info, sizeof(SHFILEINFO), SHGFI_ICON | size | SHGFI_USEFILEATTRIBUTES)) { - scoped_ptr<SkBitmap> bitmap(IconUtil::CreateSkBitmapFromHICON( - file_info.hIcon)); + std::unique_ptr<SkBitmap> bitmap( + IconUtil::CreateSkBitmapFromHICON(file_info.hIcon)); if (bitmap.get()) { gfx::ImageSkia image_skia(gfx::ImageSkiaRep(*bitmap, gfx::GetDPIScale())); image_skia.MakeThreadSafe();
diff --git a/chrome/browser/icon_manager.cc b/chrome/browser/icon_manager.cc index 0b43141..e0c8ce1a 100644 --- a/chrome/browser/icon_manager.cc +++ b/chrome/browser/icon_manager.cc
@@ -4,10 +4,10 @@ #include "chrome/browser/icon_manager.h" +#include <memory> #include <tuple> #include "base/bind.h" -#include "base/memory/scoped_ptr.h" #include "base/stl_util.h" #include "base/task_runner.h" #include "third_party/skia/include/core/SkBitmap.h"
diff --git a/chrome/browser/image_decoder.h b/chrome/browser/image_decoder.h index e9c3526b..5e2845d 100644 --- a/chrome/browser/image_decoder.h +++ b/chrome/browser/image_decoder.h
@@ -13,7 +13,6 @@ #include "base/lazy_instance.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/sequence_checker.h" #include "base/sequenced_task_runner.h" #include "base/synchronization/lock.h"
diff --git a/chrome/browser/image_decoder_browsertest.cc b/chrome/browser/image_decoder_browsertest.cc index 3541734e..f2fdf53 100644 --- a/chrome/browser/image_decoder_browsertest.cc +++ b/chrome/browser/image_decoder_browsertest.cc
@@ -230,7 +230,7 @@ IN_PROC_BROWSER_TEST_F(ImageDecoderBrowserTest, StartAndDestroy) { scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner; - scoped_ptr<TestImageRequest> test_request( + std::unique_ptr<TestImageRequest> test_request( new TestImageRequest(runner->QuitClosure())); ImageDecoder::Start(test_request.get(), std::string()); test_request.reset();
diff --git a/chrome/browser/importer/external_process_importer_host.h b/chrome/browser/importer/external_process_importer_host.h index 2c3c689..b41717c1 100644 --- a/chrome/browser/importer/external_process_importer_host.h +++ b/chrome/browser/importer/external_process_importer_host.h
@@ -7,10 +7,11 @@ #include <stdint.h> +#include <memory> + #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/importer/importer_progress_observer.h" #include "chrome/browser/importer/profile_writer.h" @@ -124,7 +125,7 @@ importer::ImporterProgressObserver* observer_; // Firefox profile lock. - scoped_ptr<FirefoxProfileLock> firefox_lock_; + std::unique_ptr<FirefoxProfileLock> firefox_lock_; // Profile we're importing from. Profile* profile_; @@ -134,7 +135,8 @@ // May contain a Subscription waiting for the TemplateURLService to finish // loading. - scoped_ptr<TemplateURLService::Subscription> template_service_subscription_; + std::unique_ptr<TemplateURLService::Subscription> + template_service_subscription_; // Have we installed a listener on the bookmark model? bool installed_bookmark_observer_;
diff --git a/chrome/browser/importer/firefox_profile_lock_unittest.cc b/chrome/browser/importer/firefox_profile_lock_unittest.cc index 4b1df9a..b3a5985 100644 --- a/chrome/browser/importer/firefox_profile_lock_unittest.cc +++ b/chrome/browser/importer/firefox_profile_lock_unittest.cc
@@ -2,12 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/importer/firefox_profile_lock.h" + +#include <memory> + #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string_util.h" #include "build/build_config.h" -#include "chrome/browser/importer/firefox_profile_lock.h" #include "chrome/common/chrome_paths.h" #include "testing/gtest/include/gtest/gtest.h" @@ -34,7 +36,7 @@ base::FilePath lock_file_path = test_path.Append(FirefoxProfileLock::kLockFileName); - scoped_ptr<FirefoxProfileLock> lock; + std::unique_ptr<FirefoxProfileLock> lock; EXPECT_EQ(static_cast<FirefoxProfileLock*>(NULL), lock.get()); EXPECT_FALSE(base::PathExists(lock_file_path)); lock.reset(new FirefoxProfileLock(test_path)); @@ -73,7 +75,7 @@ base::CloseFile(lock_file); EXPECT_TRUE(base::PathExists(lock_file_path)); - scoped_ptr<FirefoxProfileLock> lock; + std::unique_ptr<FirefoxProfileLock> lock; EXPECT_EQ(static_cast<FirefoxProfileLock*>(NULL), lock.get()); lock.reset(new FirefoxProfileLock(test_path)); EXPECT_TRUE(lock->HasAcquired()); @@ -88,12 +90,12 @@ TEST_F(FirefoxProfileLockTest, ProfileLockContention) { base::FilePath test_path = temp_dir_.path(); - scoped_ptr<FirefoxProfileLock> lock1; + std::unique_ptr<FirefoxProfileLock> lock1; EXPECT_EQ(static_cast<FirefoxProfileLock*>(NULL), lock1.get()); lock1.reset(new FirefoxProfileLock(test_path)); EXPECT_TRUE(lock1->HasAcquired()); - scoped_ptr<FirefoxProfileLock> lock2; + std::unique_ptr<FirefoxProfileLock> lock2; EXPECT_EQ(static_cast<FirefoxProfileLock*>(NULL), lock2.get()); lock2.reset(new FirefoxProfileLock(test_path)); EXPECT_FALSE(lock2->HasAcquired());
diff --git a/chrome/browser/infobars/infobar_service.h b/chrome/browser/infobars/infobar_service.h index e2064b0a3..a18e157 100644 --- a/chrome/browser/infobars/infobar_service.h +++ b/chrome/browser/infobars/infobar_service.h
@@ -5,10 +5,10 @@ #ifndef CHROME_BROWSER_INFOBARS_INFOBAR_SERVICE_H_ #define CHROME_BROWSER_INFOBARS_INFOBAR_SERVICE_H_ +#include <memory> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "components/infobars/core/infobar_manager.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" @@ -50,8 +50,8 @@ // InfoBarManager: // TODO(sdefresne): Change clients to invoke this on infobars::InfoBarManager // and turn the method override private. - scoped_ptr<infobars::InfoBar> CreateConfirmInfoBar( - scoped_ptr<ConfirmInfoBarDelegate> delegate) override; + std::unique_ptr<infobars::InfoBar> CreateConfirmInfoBar( + std::unique_ptr<ConfirmInfoBarDelegate> delegate) override; void OpenURL(const GURL& url, WindowOpenDisposition disposition) override; private:
diff --git a/chrome/browser/infobars/infobars_browsertest.cc b/chrome/browser/infobars/infobars_browsertest.cc index d439d34..f1fea55 100644 --- a/chrome/browser/infobars/infobars_browsertest.cc +++ b/chrome/browser/infobars/infobars_browsertest.cc
@@ -41,7 +41,7 @@ extensions::TestExtensionRegistryObserver observer( extensions::ExtensionRegistry::Get(browser()->profile())); - scoped_ptr<ExtensionInstallPrompt> client(new ExtensionInstallPrompt( + std::unique_ptr<ExtensionInstallPrompt> client(new ExtensionInstallPrompt( browser()->tab_strip_model()->GetActiveWebContents())); scoped_refptr<extensions::CrxInstaller> installer( extensions::CrxInstaller::Create(service, std::move(client)));
diff --git a/chrome/browser/infobars/insecure_content_infobar_delegate.cc b/chrome/browser/infobars/insecure_content_infobar_delegate.cc index 8af7856..85cc4e0 100644 --- a/chrome/browser/infobars/insecure_content_infobar_delegate.cc +++ b/chrome/browser/infobars/insecure_content_infobar_delegate.cc
@@ -27,9 +27,10 @@ UMA_HISTOGRAM_ENUMERATION("InsecureContentInfoBarDelegateV2", DISPLAY_INFOBAR_SHOWN, NUM_EVENTS); - scoped_ptr<infobars::InfoBar> new_infobar( - infobar_service->CreateConfirmInfoBar(scoped_ptr<ConfirmInfoBarDelegate>( - new InsecureContentInfoBarDelegate()))); + std::unique_ptr<infobars::InfoBar> new_infobar( + infobar_service->CreateConfirmInfoBar( + std::unique_ptr<ConfirmInfoBarDelegate>( + new InsecureContentInfoBarDelegate()))); for (size_t i = 0; i < infobar_service->infobar_count(); ++i) { infobars::InfoBar* old_infobar = infobar_service->infobar_at(i);
diff --git a/chrome/browser/install_verification/win/module_list.cc b/chrome/browser/install_verification/win/module_list.cc index 7a31bf1..fc3461e 100644 --- a/chrome/browser/install_verification/win/module_list.cc +++ b/chrome/browser/install_verification/win/module_list.cc
@@ -24,9 +24,9 @@ std::for_each(modules_.begin(), modules_.end(), &CheckFreeLibrary); } -scoped_ptr<ModuleList> ModuleList::FromLoadedModuleSnapshot( +std::unique_ptr<ModuleList> ModuleList::FromLoadedModuleSnapshot( const std::vector<HMODULE>& snapshot) { - scoped_ptr<ModuleList> instance(new ModuleList); + std::unique_ptr<ModuleList> instance(new ModuleList); for (size_t i = 0; i < snapshot.size(); ++i) { HMODULE module = NULL;
diff --git a/chrome/browser/install_verification/win/module_list.h b/chrome/browser/install_verification/win/module_list.h index 3497abe..f4b28e4 100644 --- a/chrome/browser/install_verification/win/module_list.h +++ b/chrome/browser/install_verification/win/module_list.h
@@ -5,14 +5,14 @@ #ifndef CHROME_BROWSER_INSTALL_VERIFICATION_WIN_MODULE_LIST_H_ #define CHROME_BROWSER_INSTALL_VERIFICATION_WIN_MODULE_LIST_H_ -#include <stddef.h> #include <Windows.h> +#include <stddef.h> +#include <memory> #include <set> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" struct ModuleInfo; @@ -26,7 +26,7 @@ // AddRef'd HMODULEs will be inserted in the returned ModuleList. // // This method _always_ returns a valid ModuleList instance. - static scoped_ptr<ModuleList> FromLoadedModuleSnapshot( + static std::unique_ptr<ModuleList> FromLoadedModuleSnapshot( const std::vector<HMODULE>& snapshot); // Retrieves name and address information for the module list.
diff --git a/chrome/browser/install_verification/win/module_list_unittest.cc b/chrome/browser/install_verification/win/module_list_unittest.cc index a4c81c6..cca65a6a 100644 --- a/chrome/browser/install_verification/win/module_list_unittest.cc +++ b/chrome/browser/install_verification/win/module_list_unittest.cc
@@ -4,13 +4,15 @@ #include "chrome/browser/install_verification/win/module_list.h" -#include <stddef.h> #include <Windows.h> +#include <stddef.h> + +#include <memory> #include <vector> + #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback_helpers.h" -#include "base/memory/scoped_ptr.h" #include "base/win/win_util.h" #include "testing/gtest/include/gtest/gtest.h" @@ -18,7 +20,7 @@ std::vector<HMODULE> snapshot; ASSERT_TRUE( base::win::GetLoadedModulesSnapshot(::GetCurrentProcess(), &snapshot)); - scoped_ptr<ModuleList> module_list( + std::unique_ptr<ModuleList> module_list( ModuleList::FromLoadedModuleSnapshot(snapshot)); // Lookup the number of loaded modules.
diff --git a/chrome/browser/interests/android/interests_service.cc b/chrome/browser/interests/android/interests_service.cc index ad65e29..84d67d5 100644 --- a/chrome/browser/interests/android/interests_service.cc +++ b/chrome/browser/interests/android/interests_service.cc
@@ -25,7 +25,7 @@ ScopedJavaLocalRef<jobjectArray> ConvertInterestsToJava( JNIEnv* env, - scoped_ptr<std::vector<InterestsFetcher::Interest>> interests) { + std::unique_ptr<std::vector<InterestsFetcher::Interest>> interests) { if (!interests) return ScopedJavaLocalRef<jobjectArray>(); @@ -64,7 +64,7 @@ const JavaParamRef<jobject>& j_callback_obj) { ScopedJavaGlobalRef<jobject> j_callback(env, j_callback_obj); - scoped_ptr<InterestsFetcher> fetcher = + std::unique_ptr<InterestsFetcher> fetcher = InterestsFetcher::CreateFromProfile(profile_); InterestsFetcher* fetcher_raw_ptr = fetcher.get(); @@ -81,9 +81,9 @@ } void InterestsService::OnObtainedInterests( - scoped_ptr<InterestsFetcher> fetcher, + std::unique_ptr<InterestsFetcher> fetcher, const ScopedJavaGlobalRef<jobject>& j_callback, - scoped_ptr<std::vector<InterestsFetcher::Interest>> interests) { + std::unique_ptr<std::vector<InterestsFetcher::Interest>> interests) { JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobjectArray> j_interests = ConvertInterestsToJava(env, std::move(interests));
diff --git a/chrome/browser/interests/android/interests_service.h b/chrome/browser/interests/android/interests_service.h index 2e39fe4..888942af 100644 --- a/chrome/browser/interests/android/interests_service.h +++ b/chrome/browser/interests/android/interests_service.h
@@ -7,9 +7,10 @@ #include <jni.h> +#include <memory> + #include "base/android/scoped_java_ref.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/interests/interests_fetcher.h" @@ -29,9 +30,9 @@ private: void OnObtainedInterests( - scoped_ptr<InterestsFetcher> fetcher, + std::unique_ptr<InterestsFetcher> fetcher, const base::android::ScopedJavaGlobalRef<jobject>& j_callback, - scoped_ptr<std::vector<InterestsFetcher::Interest>> interests); + std::unique_ptr<std::vector<InterestsFetcher::Interest>> interests); Profile* profile_;
diff --git a/chrome/browser/interests/interests_fetcher.cc b/chrome/browser/interests/interests_fetcher.cc index c9c7ca54..49ba04d 100644 --- a/chrome/browser/interests/interests_fetcher.cc +++ b/chrome/browser/interests/interests_fetcher.cc
@@ -7,6 +7,7 @@ #include "base/command_line.h" #include "base/json/json_reader.h" #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/strings/stringprintf.h" #include "base/values.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" @@ -65,17 +66,16 @@ InterestsFetcher::~InterestsFetcher() {} // static -scoped_ptr<InterestsFetcher> InterestsFetcher::CreateFromProfile( +std::unique_ptr<InterestsFetcher> InterestsFetcher::CreateFromProfile( Profile* profile) { ProfileOAuth2TokenService* token_service = ProfileOAuth2TokenServiceFactory::GetForProfile(profile); SigninManagerBase* signin = SigninManagerFactory::GetForProfile(profile); - return make_scoped_ptr(new InterestsFetcher( - token_service, - signin->GetAuthenticatedAccountId(), - profile->GetRequestContext())); + return base::WrapUnique( + new InterestsFetcher(token_service, signin->GetAuthenticatedAccountId(), + profile->GetRequestContext())); } void InterestsFetcher::FetchInterests( @@ -159,14 +159,14 @@ return scopes; } -scoped_ptr<net::URLFetcher> InterestsFetcher::CreateFetcher() { +std::unique_ptr<net::URLFetcher> InterestsFetcher::CreateFetcher() { return net::URLFetcher::Create(0, GetInterestsURL(), net::URLFetcher::GET, this); } -scoped_ptr<std::vector<InterestsFetcher::Interest>> +std::unique_ptr<std::vector<InterestsFetcher::Interest>> InterestsFetcher::ExtractInterests(const std::string& response) { - scoped_ptr<base::Value> value = base::JSONReader::Read(response); + std::unique_ptr<base::Value> value = base::JSONReader::Read(response); DVLOG(2) << response; const base::DictionaryValue* dict = nullptr; @@ -181,7 +181,7 @@ return nullptr; } - scoped_ptr<std::vector<Interest>> res(new std::vector<Interest>()); + std::unique_ptr<std::vector<Interest>> res(new std::vector<Interest>()); for (const base::Value* entry : *interests_list) { const base::DictionaryValue* interest_dict = nullptr; if (!entry->GetAsDictionary(&interest_dict)) {
diff --git a/chrome/browser/interests/interests_fetcher.h b/chrome/browser/interests/interests_fetcher.h index 38e1f0f..584e83c 100644 --- a/chrome/browser/interests/interests_fetcher.h +++ b/chrome/browser/interests/interests_fetcher.h
@@ -5,13 +5,13 @@ #ifndef CHROME_BROWSER_INTERESTS_INTERESTS_FETCHER_H_ #define CHROME_BROWSER_INTERESTS_INTERESTS_FETCHER_H_ +#include <memory> #include <string> #include <vector> #include "base/callback.h" #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/profiles/profile.h" #include "components/signin/core/browser/signin_manager.h" #include "google_apis/gaia/oauth2_token_service.h" @@ -46,7 +46,7 @@ }; using InterestsCallback = - base::Callback<void(scoped_ptr<std::vector<Interest>>)>; + base::Callback<void(std::unique_ptr<std::vector<Interest>>)>; InterestsFetcher(OAuth2TokenService* oauth2_token_service, const std::string& account_id, @@ -54,7 +54,7 @@ ~InterestsFetcher() override; - static scoped_ptr<InterestsFetcher> CreateFromProfile(Profile* profile); + static std::unique_ptr<InterestsFetcher> CreateFromProfile(Profile* profile); void FetchInterests(const InterestsCallback& callback); @@ -71,20 +71,20 @@ void StartOAuth2Request(); OAuth2TokenService::ScopeSet GetApiScopes(); - scoped_ptr<net::URLFetcher> CreateFetcher(); + std::unique_ptr<net::URLFetcher> CreateFetcher(); // Parse the json response. - scoped_ptr<std::vector<Interest>> - ExtractInterests(const std::string& response); + std::unique_ptr<std::vector<Interest>> ExtractInterests( + const std::string& response); InterestsCallback callback_; - scoped_ptr<net::URLFetcher> fetcher_; + std::unique_ptr<net::URLFetcher> fetcher_; std::string account_id_; net::URLRequestContextGetter* url_request_context_; bool access_token_expired_; std::string access_token_; - scoped_ptr<OAuth2TokenService::Request> oauth_request_; + std::unique_ptr<OAuth2TokenService::Request> oauth_request_; OAuth2TokenService* token_service_; DISALLOW_COPY_AND_ASSIGN(InterestsFetcher);
diff --git a/chrome/browser/interests/interests_fetcher_unittest.cc b/chrome/browser/interests/interests_fetcher_unittest.cc index ec67a18b..04274f1 100644 --- a/chrome/browser/interests/interests_fetcher_unittest.cc +++ b/chrome/browser/interests/interests_fetcher_unittest.cc
@@ -83,7 +83,7 @@ MOCK_METHOD0(OnFailedResponse, void()); void OnReceivedInterests( - scoped_ptr<std::vector<InterestsFetcher::Interest>> interests) { + std::unique_ptr<std::vector<InterestsFetcher::Interest>> interests) { if (!interests) { OnFailedResponse(); return; @@ -150,8 +150,8 @@ base::MessageLoop message_loop_; FakeProfileOAuth2TokenService token_service_; scoped_refptr<net::TestURLRequestContextGetter> request_context_; - scoped_ptr<net::TestURLFetcherFactory> url_fetcher_factory_; - scoped_ptr<InterestsFetcher> request_; + std::unique_ptr<net::TestURLFetcherFactory> url_fetcher_factory_; + std::unique_ptr<InterestsFetcher> request_; }; TEST_F(InterestsFetcherTest, EmptyResponse) {
diff --git a/chrome/browser/internal_auth.cc b/chrome/browser/internal_auth.cc index a520add..42da3ff 100644 --- a/chrome/browser/internal_auth.cc +++ b/chrome/browser/internal_auth.cc
@@ -10,11 +10,11 @@ #include <algorithm> #include <deque> #include <limits> +#include <memory> #include "base/base64.h" #include "base/lazy_instance.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/rand_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" @@ -251,7 +251,7 @@ if (key.size() != kKeySizeInBytes) return; - scoped_ptr<crypto::HMAC> new_engine( + std::unique_ptr<crypto::HMAC> new_engine( new crypto::HMAC(crypto::HMAC::SHA256)); if (!new_engine->Init(key)) return; @@ -302,8 +302,8 @@ std::string old_key_; // Corresponding HMAC engines. - scoped_ptr<crypto::HMAC> engine_; - scoped_ptr<crypto::HMAC> old_engine_; + std::unique_ptr<crypto::HMAC> engine_; + std::unique_ptr<crypto::HMAC> old_engine_; // Tick at a time of recent key regeneration. int64_t key_change_tick_; @@ -341,7 +341,8 @@ void GenerateNewKey() { DCHECK(CalledOnValidThread()); - scoped_ptr<crypto::HMAC> new_engine(new crypto::HMAC(crypto::HMAC::SHA256)); + std::unique_ptr<crypto::HMAC> new_engine( + new crypto::HMAC(crypto::HMAC::SHA256)); std::string key = base::RandBytesAsString(kKeySizeInBytes); if (!new_engine->Init(key)) return; @@ -420,7 +421,7 @@ return InternalAuthVerification::get_verification_window_ticks(); } - scoped_ptr<crypto::HMAC> engine_; + std::unique_ptr<crypto::HMAC> engine_; int64_t key_regeneration_tick_; std::deque<int64_t> used_ticks_;
diff --git a/chrome/browser/interstitials/chrome_metrics_helper.h b/chrome/browser/interstitials/chrome_metrics_helper.h index 5206a9e..9b80931 100644 --- a/chrome/browser/interstitials/chrome_metrics_helper.h +++ b/chrome/browser/interstitials/chrome_metrics_helper.h
@@ -50,10 +50,10 @@ const GURL request_url_; const std::string sampling_event_name_; #if defined(ENABLE_EXTENSIONS) - scoped_ptr<extensions::ExperienceSamplingEvent> sampling_event_; + std::unique_ptr<extensions::ExperienceSamplingEvent> sampling_event_; #endif #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION) - scoped_ptr<CaptivePortalMetricsRecorder> captive_portal_recorder_; + std::unique_ptr<CaptivePortalMetricsRecorder> captive_portal_recorder_; #endif DISALLOW_COPY_AND_ASSIGN(ChromeMetricsHelper);
diff --git a/chrome/browser/intranet_redirect_detector.cc b/chrome/browser/intranet_redirect_detector.cc index 86e277e..99848090 100644 --- a/chrome/browser/intranet_redirect_detector.cc +++ b/chrome/browser/intranet_redirect_detector.cc
@@ -104,7 +104,7 @@ Fetchers::iterator fetcher = fetchers_.find( const_cast<net::URLFetcher*>(source)); DCHECK(fetcher != fetchers_.end()); - scoped_ptr<net::URLFetcher> clean_up_fetcher(*fetcher); + std::unique_ptr<net::URLFetcher> clean_up_fetcher(*fetcher); fetchers_.erase(fetcher); // If any two fetches result in the same domain/host, we set the redirect
diff --git a/chrome/browser/invalidation/profile_invalidation_provider_factory.cc b/chrome/browser/invalidation/profile_invalidation_provider_factory.cc index 1292e59..f561650 100644 --- a/chrome/browser/invalidation/profile_invalidation_provider_factory.cc +++ b/chrome/browser/invalidation/profile_invalidation_provider_factory.cc
@@ -4,9 +4,9 @@ #include "chrome/browser/invalidation/profile_invalidation_provider_factory.h" +#include <memory> #include <utility> -#include "base/memory/scoped_ptr.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" @@ -101,11 +101,11 @@ return testing_factory_(context).release(); #if defined(OS_ANDROID) - return new ProfileInvalidationProvider(scoped_ptr<InvalidationService>( + return new ProfileInvalidationProvider(std::unique_ptr<InvalidationService>( new InvalidationServiceAndroid(base::android::GetApplicationContext()))); #else - scoped_ptr<IdentityProvider> identity_provider; + std::unique_ptr<IdentityProvider> identity_provider; #if defined(OS_CHROMEOS) policy::BrowserPolicyConnectorChromeOS* connector = @@ -126,13 +126,13 @@ LoginUIServiceFactory::GetShowLoginPopupCallbackForProfile(profile))); } - scoped_ptr<TiclInvalidationService> service(new TiclInvalidationService( + std::unique_ptr<TiclInvalidationService> service(new TiclInvalidationService( GetUserAgent(), std::move(identity_provider), - scoped_ptr<TiclSettingsProvider>( + std::unique_ptr<TiclSettingsProvider>( new TiclProfileSettingsProvider(profile->GetPrefs())), gcm::GCMProfileServiceFactory::GetForProfile(profile)->driver(), profile->GetRequestContext())); - service->Init(scoped_ptr<syncer::InvalidationStateTracker>( + service->Init(std::unique_ptr<syncer::InvalidationStateTracker>( new InvalidatorStorage(profile->GetPrefs()))); return new ProfileInvalidationProvider(std::move(service));
diff --git a/chrome/browser/io_thread.cc b/chrome/browser/io_thread.cc index 33d6ba4..99a914c8 100644 --- a/chrome/browser/io_thread.cc +++ b/chrome/browser/io_thread.cc
@@ -17,6 +17,7 @@ #include "base/files/file_path.h" #include "base/logging.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" #include "base/profiler/scoped_tracker.h" #include "base/stl_util.h" @@ -203,7 +204,7 @@ LOG(WARNING) << "ssl-key-log-file argument missing"; } - scoped_ptr<base::Environment> env(base::Environment::Create()); + std::unique_ptr<base::Environment> env(base::Environment::Create()); std::string path_str; env->GetVar("SSLKEYLOGFILE", &path_str); #if defined(OS_WIN) @@ -232,7 +233,8 @@ } }; -scoped_ptr<net::HostResolver> CreateGlobalHostResolver(net::NetLog* net_log) { +std::unique_ptr<net::HostResolver> CreateGlobalHostResolver( + net::NetLog* net_log) { TRACE_EVENT0("startup", "IOThread::CreateGlobalHostResolver"); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); @@ -252,7 +254,7 @@ } } - scoped_ptr<net::HostResolver> global_host_resolver; + std::unique_ptr<net::HostResolver> global_host_resolver; #if defined OS_CHROMEOS global_host_resolver = chromeos::HostResolverImplChromeOS::CreateSystemResolver(options, @@ -268,7 +270,7 @@ if (!command_line.HasSwitch(switches::kHostResolverRules)) return global_host_resolver; - scoped_ptr<net::MappedHostResolver> remapped_resolver( + std::unique_ptr<net::MappedHostResolver> remapped_resolver( new net::MappedHostResolver(std::move(global_host_resolver))); remapped_resolver->SetRulesFromString( command_line.GetSwitchValueASCII(switches::kHostResolverRules)); @@ -600,13 +602,13 @@ extension_event_router_forwarder_; #endif - scoped_ptr<data_usage::DataUseAmortizer> data_use_amortizer; + std::unique_ptr<data_usage::DataUseAmortizer> data_use_amortizer; #if BUILDFLAG(ANDROID_JAVA_UI) data_use_amortizer.reset(new data_usage::android::TrafficStatsAmortizer()); #endif globals_->data_use_aggregator.reset(new data_usage::DataUseAggregator( - scoped_ptr<data_usage::DataUseAnnotator>( + std::unique_ptr<data_usage::DataUseAnnotator>( new chrome_browser_data_usage::TabIdAnnotator()), std::move(data_use_amortizer))); @@ -615,7 +617,7 @@ tracked_objects::ScopedTracker tracking_profile3( FROM_HERE_WITH_EXPLICIT_FUNCTION( "466432 IOThread::InitAsync::ChromeNetworkDelegate")); - scoped_ptr<ChromeNetworkDelegate> chrome_network_delegate( + std::unique_ptr<ChromeNetworkDelegate> chrome_network_delegate( new ChromeNetworkDelegate(extension_event_router_forwarder(), &system_enable_referrers_, metrics_data_use_forwarder_)); @@ -644,7 +646,7 @@ variations::GetVariationParams(kNetworkQualityEstimatorFieldTrialName, &network_quality_estimator_params); - scoped_ptr<net::ExternalEstimateProvider> external_estimate_provider; + std::unique_ptr<net::ExternalEstimateProvider> external_estimate_provider; #if BUILDFLAG(ANDROID_JAVA_UI) external_estimate_provider.reset( new chrome::android::ExternalEstimateProviderAndroid()); @@ -1746,14 +1748,14 @@ context->set_http_transaction_factory( globals->proxy_script_fetcher_http_transaction_factory.get()); - scoped_ptr<net::URLRequestJobFactoryImpl> job_factory( + std::unique_ptr<net::URLRequestJobFactoryImpl> job_factory( new net::URLRequestJobFactoryImpl()); job_factory->SetProtocolHandler( - url::kDataScheme, make_scoped_ptr(new net::DataProtocolHandler())); + url::kDataScheme, base::WrapUnique(new net::DataProtocolHandler())); job_factory->SetProtocolHandler( url::kFileScheme, - make_scoped_ptr(new net::FileProtocolHandler( + base::WrapUnique(new net::FileProtocolHandler( content::BrowserThread::GetBlockingPool() ->GetTaskRunnerWithShutdownBehavior( base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)))); @@ -1762,7 +1764,7 @@ new net::FtpNetworkLayer(globals->host_resolver.get())); job_factory->SetProtocolHandler( url::kFtpScheme, - make_scoped_ptr(new net::FtpProtocolHandler( + base::WrapUnique(new net::FtpProtocolHandler( globals->proxy_script_fetcher_ftp_transaction_factory.get()))); #endif globals->proxy_script_fetcher_url_request_job_factory =
diff --git a/chrome/browser/io_thread.h b/chrome/browser/io_thread.h index 34987fbe..7a3fdada 100644 --- a/chrome/browser/io_thread.h +++ b/chrome/browser/io_thread.h
@@ -9,6 +9,7 @@ #include <stdint.h> #include <map> +#include <memory> #include <set> #include <string> #include <unordered_set> @@ -17,7 +18,6 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/strings/string_piece.h" #include "base/time/time.h" @@ -121,67 +121,68 @@ // Global aggregator of data use. It must outlive the // |system_network_delegate|. - scoped_ptr<data_usage::DataUseAggregator> data_use_aggregator; + std::unique_ptr<data_usage::DataUseAggregator> data_use_aggregator; #if BUILDFLAG(ANDROID_JAVA_UI) // An external observer of data use. - scoped_ptr<chrome::android::ExternalDataUseObserver> + std::unique_ptr<chrome::android::ExternalDataUseObserver> external_data_use_observer; #endif // BUILDFLAG(ANDROID_JAVA_UI) // The "system" NetworkDelegate, used for Profile-agnostic network events. - scoped_ptr<net::NetworkDelegate> system_network_delegate; - scoped_ptr<net::HostResolver> host_resolver; - scoped_ptr<net::CertVerifier> cert_verifier; + std::unique_ptr<net::NetworkDelegate> system_network_delegate; + std::unique_ptr<net::HostResolver> host_resolver; + std::unique_ptr<net::CertVerifier> cert_verifier; // The ChannelIDService must outlive the HttpTransactionFactory. - scoped_ptr<net::ChannelIDService> system_channel_id_service; + std::unique_ptr<net::ChannelIDService> system_channel_id_service; // This TransportSecurityState doesn't load or save any state. It's only // used to enforce pinning for system requests and will only use built-in // pins. - scoped_ptr<net::TransportSecurityState> transport_security_state; + std::unique_ptr<net::TransportSecurityState> transport_security_state; std::vector<scoped_refptr<const net::CTLogVerifier>> ct_logs; - scoped_ptr<net::CTVerifier> cert_transparency_verifier; - scoped_ptr<net::CTPolicyEnforcer> ct_policy_enforcer; + std::unique_ptr<net::CTVerifier> cert_transparency_verifier; + std::unique_ptr<net::CTPolicyEnforcer> ct_policy_enforcer; scoped_refptr<net::SSLConfigService> ssl_config_service; - scoped_ptr<net::HttpAuthHandlerFactory> http_auth_handler_factory; - scoped_ptr<net::HttpServerProperties> http_server_properties; - scoped_ptr<net::ProxyService> proxy_script_fetcher_proxy_service; - scoped_ptr<net::HttpNetworkSession> + std::unique_ptr<net::HttpAuthHandlerFactory> http_auth_handler_factory; + std::unique_ptr<net::HttpServerProperties> http_server_properties; + std::unique_ptr<net::ProxyService> proxy_script_fetcher_proxy_service; + std::unique_ptr<net::HttpNetworkSession> proxy_script_fetcher_http_network_session; - scoped_ptr<net::HttpTransactionFactory> + std::unique_ptr<net::HttpTransactionFactory> proxy_script_fetcher_http_transaction_factory; - scoped_ptr<net::FtpTransactionFactory> + std::unique_ptr<net::FtpTransactionFactory> proxy_script_fetcher_ftp_transaction_factory; - scoped_ptr<net::URLRequestJobFactory> + std::unique_ptr<net::URLRequestJobFactory> proxy_script_fetcher_url_request_job_factory; - scoped_ptr<net::URLRequestBackoffManager> url_request_backoff_manager; - scoped_ptr<net::HttpAuthPreferences> http_auth_preferences; + std::unique_ptr<net::URLRequestBackoffManager> url_request_backoff_manager; + std::unique_ptr<net::HttpAuthPreferences> http_auth_preferences; // TODO(willchan): Remove proxy script fetcher context since it's not // necessary now that I got rid of refcounting URLRequestContexts. // // The first URLRequestContext is |system_url_request_context|. We introduce // |proxy_script_fetcher_context| for the second context. It has a direct // ProxyService, since we always directly connect to fetch the PAC script. - scoped_ptr<net::URLRequestContext> proxy_script_fetcher_context; - scoped_ptr<net::ProxyService> system_proxy_service; - scoped_ptr<net::HttpNetworkSession> system_http_network_session; - scoped_ptr<net::HttpTransactionFactory> system_http_transaction_factory; - scoped_ptr<net::URLRequestJobFactory> system_url_request_job_factory; - scoped_ptr<net::URLRequestContext> system_request_context; + std::unique_ptr<net::URLRequestContext> proxy_script_fetcher_context; + std::unique_ptr<net::ProxyService> system_proxy_service; + std::unique_ptr<net::HttpNetworkSession> system_http_network_session; + std::unique_ptr<net::HttpTransactionFactory> + system_http_transaction_factory; + std::unique_ptr<net::URLRequestJobFactory> system_url_request_job_factory; + std::unique_ptr<net::URLRequestContext> system_request_context; SystemRequestContextLeakChecker system_request_context_leak_checker; // |system_cookie_store| and |system_channel_id_service| are shared // between |proxy_script_fetcher_context| and |system_request_context|. - scoped_ptr<net::CookieStore> system_cookie_store; + std::unique_ptr<net::CookieStore> system_cookie_store; #if defined(ENABLE_EXTENSIONS) scoped_refptr<extensions::EventRouterForwarder> extension_event_router_forwarder; #endif - scoped_ptr<net::HostMappingRules> host_mapping_rules; - scoped_ptr<net::HttpUserAgentSettings> http_user_agent_settings; - scoped_ptr<net::NetworkQualityEstimator> network_quality_estimator; + std::unique_ptr<net::HostMappingRules> host_mapping_rules; + std::unique_ptr<net::HttpUserAgentSettings> http_user_agent_settings; + std::unique_ptr<net::NetworkQualityEstimator> network_quality_estimator; // NetErrorTabHelper uses |dns_probe_service| to send DNS probes when a // main frame load fails with a DNS error in order to provide more useful // information to the renderer so it can show a more specific error page. - scoped_ptr<chrome_browser_net::DnsProbeService> dns_probe_service; + std::unique_ptr<chrome_browser_net::DnsProbeService> dns_probe_service; }; // Helper class to configure HttpNetworkSession::Params and @@ -520,7 +521,7 @@ // Observer that logs network changes to the ChromeNetLog. class LoggingNetworkChangeObserver; - scoped_ptr<LoggingNetworkChangeObserver> network_change_observer_; + std::unique_ptr<LoggingNetworkChangeObserver> network_change_observer_; BooleanPrefMember system_enable_referrers_; @@ -549,13 +550,14 @@ // This is an instance of the default SSLConfigServiceManager for the current // platform and it gets SSL preferences from local_state object. - scoped_ptr<ssl_config::SSLConfigServiceManager> ssl_config_service_manager_; + std::unique_ptr<ssl_config::SSLConfigServiceManager> + ssl_config_service_manager_; // These member variables are initialized by a task posted to the IO thread, // which gets posted by calling certain member functions of IOThread. - scoped_ptr<net::ProxyConfigService> system_proxy_config_service_; + std::unique_ptr<net::ProxyConfigService> system_proxy_config_service_; - scoped_ptr<PrefProxyConfigTracker> pref_proxy_config_tracker_; + std::unique_ptr<PrefProxyConfigTracker> pref_proxy_config_tracker_; scoped_refptr<net::URLRequestContextGetter> system_url_request_context_getter_;
diff --git a/chrome/browser/io_thread_unittest.cc b/chrome/browser/io_thread_unittest.cc index f00aacb..13753dc 100644 --- a/chrome/browser/io_thread_unittest.cc +++ b/chrome/browser/io_thread_unittest.cc
@@ -75,7 +75,7 @@ bool is_spdy_allowed_by_policy_; bool is_quic_allowed_by_policy_; - scoped_ptr<base::FieldTrialList> field_trial_list_; + std::unique_ptr<base::FieldTrialList> field_trial_list_; net::HttpNetworkSession::Params params_; private: @@ -810,7 +810,7 @@ // TestBrowserThreadBundle's destructor is responsible for calling // CleanUp(), the IOThread must be declared before the bundle, so that // the bundle is deleted first. - scoped_ptr<IOThread> io_thread_; + std::unique_ptr<IOThread> io_thread_; content::TestBrowserThreadBundle thread_bundle_; };
diff --git a/chrome/browser/jumplist_win.h b/chrome/browser/jumplist_win.h index 0447cd4..16c319ac 100644 --- a/chrome/browser/jumplist_win.h +++ b/chrome/browser/jumplist_win.h
@@ -165,8 +165,8 @@ Profile* profile_; // Lives on the UI thread. - scoped_ptr<content::NotificationRegistrar> registrar_; - scoped_ptr<PrefChangeRegistrar> pref_change_registrar_; + std::unique_ptr<content::NotificationRegistrar> registrar_; + std::unique_ptr<PrefChangeRegistrar> pref_change_registrar_; // App id to associate with the jump list. std::wstring app_id_;
diff --git a/chrome/browser/lifetime/application_lifetime.cc b/chrome/browser/lifetime/application_lifetime.cc index 4caf166..4daeff4 100644 --- a/chrome/browser/lifetime/application_lifetime.cc +++ b/chrome/browser/lifetime/application_lifetime.cc
@@ -4,9 +4,10 @@ #include "chrome/browser/lifetime/application_lifetime.h" +#include <memory> + #include "base/bind.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/process/process.h" #include "base/process/process_handle.h"
diff --git a/chrome/browser/lifetime/browser_close_manager_browsertest.cc b/chrome/browser/lifetime/browser_close_manager_browsertest.cc index a1aeac6..fa9d7b9 100644 --- a/chrome/browser/lifetime/browser_close_manager_browsertest.cc +++ b/chrome/browser/lifetime/browser_close_manager_browsertest.cc
@@ -756,7 +756,7 @@ SetDownloadPathForProfile(browser()->profile()); // Set up the fake delegate that forces the download to be malicious. - scoped_ptr<TestDownloadManagerDelegate> test_delegate( + std::unique_ptr<TestDownloadManagerDelegate> test_delegate( new TestDownloadManagerDelegate(browser()->profile())); DownloadServiceFactory::GetForBrowserContext(browser()->profile()) ->SetDownloadManagerDelegateForTesting(std::move(test_delegate)); @@ -952,7 +952,7 @@ void SetUpOnMainThread() override { BrowserCloseManagerBrowserTest::SetUpOnMainThread(); g_browser_process->set_background_mode_manager_for_test( - scoped_ptr<BackgroundModeManager>(new FakeBackgroundModeManager)); + std::unique_ptr<BackgroundModeManager>(new FakeBackgroundModeManager)); } bool IsBackgroundModeSuspended() { @@ -971,7 +971,7 @@ IN_PROC_BROWSER_TEST_P(BrowserCloseManagerWithBackgroundModeBrowserTest, CloseAllBrowsersWithBackgroundMode) { EXPECT_FALSE(IsBackgroundModeSuspended()); - scoped_ptr<ScopedKeepAlive> tmp_keep_alive; + std::unique_ptr<ScopedKeepAlive> tmp_keep_alive; Profile* profile = browser()->profile(); { RepeatedNotificationObserver close_observer(
diff --git a/chrome/browser/lifetime/keep_alive_registry.cc b/chrome/browser/lifetime/keep_alive_registry.cc index 270005a..7a749b0 100644 --- a/chrome/browser/lifetime/keep_alive_registry.cc +++ b/chrome/browser/lifetime/keep_alive_registry.cc
@@ -113,7 +113,7 @@ OnKeepAliveRestartStateChanged(new_restart_allowed)); } -#ifndef NDEBUG +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) std::ostream& operator<<(std::ostream& out, const KeepAliveRegistry& registry) { out << "{registered_count_=" << registry.registered_count_ << ", restart_allowed_count_=" << registry.restart_allowed_count_ @@ -127,4 +127,4 @@ out << "]}"; return out; } -#endif // ndef NDEBUG +#endif
diff --git a/chrome/browser/lifetime/keep_alive_registry.h b/chrome/browser/lifetime/keep_alive_registry.h index 57ab7967..332b3d6 100644 --- a/chrome/browser/lifetime/keep_alive_registry.h +++ b/chrome/browser/lifetime/keep_alive_registry.h
@@ -40,10 +40,10 @@ friend struct base::DefaultSingletonTraits<KeepAliveRegistry>; // Friend to be able to use Register/Unregister friend class ScopedKeepAlive; -#ifndef NDEBUG +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) friend std::ostream& operator<<(std::ostream& out, const KeepAliveRegistry& registry); -#endif // NDEBUG +#endif KeepAliveRegistry(); ~KeepAliveRegistry(); @@ -71,8 +71,8 @@ DISALLOW_COPY_AND_ASSIGN(KeepAliveRegistry); }; -#ifndef NDEBUG +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) std::ostream& operator<<(std::ostream& out, const KeepAliveRegistry& registry); -#endif // ndef NDEBUG +#endif #endif // CHROME_BROWSER_LIFETIME_KEEP_ALIVE_REGISTRY_H_
diff --git a/chrome/browser/lifetime/keep_alive_registry_unittest.cc b/chrome/browser/lifetime/keep_alive_registry_unittest.cc index e634bbd..e20a778 100644 --- a/chrome/browser/lifetime/keep_alive_registry_unittest.cc +++ b/chrome/browser/lifetime/keep_alive_registry_unittest.cc
@@ -4,7 +4,8 @@ #include "chrome/browser/lifetime/keep_alive_registry.h" -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/lifetime/keep_alive_state_observer.h" #include "chrome/browser/lifetime/keep_alive_types.h" @@ -82,7 +83,7 @@ TEST_F(KeepAliveRegistryTest, DoubleKeepAliveTest) { EXPECT_EQ(0, start_keep_alive_call_count_); EXPECT_EQ(0, stop_keep_alive_call_count_); - scoped_ptr<ScopedKeepAlive> keep_alive_1, keep_alive_2; + std::unique_ptr<ScopedKeepAlive> keep_alive_1, keep_alive_2; keep_alive_1.reset(new ScopedKeepAlive(KeepAliveOrigin::CHROME_APP_DELEGATE, KeepAliveRestartOption::DISABLED)); @@ -109,7 +110,7 @@ // Test the IsKeepingAlive state and when we interact with the browser with // more than one KeepAlive registered. TEST_F(KeepAliveRegistryTest, RestartOptionTest) { - scoped_ptr<ScopedKeepAlive> keep_alive, keep_alive_restart; + std::unique_ptr<ScopedKeepAlive> keep_alive, keep_alive_restart; EXPECT_EQ(0, on_restart_allowed_call_count_); EXPECT_EQ(0, on_restart_forbidden_call_count_);
diff --git a/chrome/browser/lifetime/keep_alive_types.cc b/chrome/browser/lifetime/keep_alive_types.cc index 13a40e0..173f417 100644 --- a/chrome/browser/lifetime/keep_alive_types.cc +++ b/chrome/browser/lifetime/keep_alive_types.cc
@@ -5,7 +5,7 @@ #include "chrome/browser/lifetime/keep_alive_types.h" #include "base/logging.h" -#ifndef NDEBUG +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) std::ostream& operator<<(std::ostream& out, const KeepAliveOrigin& origin) { switch (origin) { case KeepAliveOrigin::APP_CONTROLLER: @@ -59,4 +59,4 @@ return out << static_cast<int>(restart); } -#endif // ndef NDEBUG +#endif
diff --git a/chrome/browser/lifetime/keep_alive_types.h b/chrome/browser/lifetime/keep_alive_types.h index fe6273df..3475aec5 100644 --- a/chrome/browser/lifetime/keep_alive_types.h +++ b/chrome/browser/lifetime/keep_alive_types.h
@@ -43,10 +43,10 @@ // restarts enum class KeepAliveRestartOption { DISABLED, ENABLED }; -#ifndef NDEBUG +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) std::ostream& operator<<(std::ostream& out, const KeepAliveOrigin& origin); std::ostream& operator<<(std::ostream& out, const KeepAliveRestartOption& restart); -#endif // ndef NDEBUG +#endif #endif // CHROME_BROWSER_LIFETIME_KEEP_ALIVE_TYPES_H_
diff --git a/chrome/browser/locale_tests_browsertest.cc b/chrome/browser/locale_tests_browsertest.cc index 66472d9..26b82d11 100644 --- a/chrome/browser/locale_tests_browsertest.cc +++ b/chrome/browser/locale_tests_browsertest.cc
@@ -7,6 +7,7 @@ #include "base/command_line.h" #include "base/environment.h" #include "base/macros.h" +#include "base/memory/scoped_ptr.h" #include "build/build_config.h" #include "chrome/test/base/in_process_browser_test.h" #include "ui/base/ui_base_switches.h" @@ -45,7 +46,7 @@ ~ScopedLocale() { #if defined(OS_LINUX) - scoped_ptr<base::Environment> env(base::Environment::Create()); + std::unique_ptr<base::Environment> env(base::Environment::Create()); if (old_locale_) { env->SetVar("LC_ALL", old_locale_); } else {
diff --git a/chrome/browser/logging_chrome_unittest.cc b/chrome/browser/logging_chrome_unittest.cc index dcc0dce..236b4b4d 100644 --- a/chrome/browser/logging_chrome_unittest.cc +++ b/chrome/browser/logging_chrome_unittest.cc
@@ -2,9 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> + #include "base/environment.h" #include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" #include "chrome/common/env_vars.h" #include "chrome/common/logging_chrome.h" #include "testing/gtest/include/gtest/gtest.h" @@ -14,7 +15,7 @@ // Stores the current value of the log file name environment // variable and sets the variable to new_value. void SaveEnvironmentVariable(const std::string& new_value) { - scoped_ptr<base::Environment> env(base::Environment::Create()); + std::unique_ptr<base::Environment> env(base::Environment::Create()); if (!env->GetVar(env_vars::kLogFileName, &environment_filename_)) environment_filename_ = ""; @@ -24,7 +25,7 @@ // Restores the value of the log file nave environment variable // previously saved by SaveEnvironmentVariable(). void RestoreEnvironmentVariable() { - scoped_ptr<base::Environment> env(base::Environment::Create()); + std::unique_ptr<base::Environment> env(base::Environment::Create()); env->SetVar(env_vars::kLogFileName, environment_filename_); }
diff --git a/chrome/browser/media/android/remote/remote_media_player_manager.cc b/chrome/browser/media/android/remote/remote_media_player_manager.cc index 90b70ea6..f6e15c59 100644 --- a/chrome/browser/media/android/remote/remote_media_player_manager.cc +++ b/chrome/browser/media/android/remote/remote_media_player_manager.cc
@@ -142,23 +142,32 @@ return player; } -void RemoteMediaPlayerManager::SwapCurrentPlayer(int player_id) { - // Find the remote player +bool RemoteMediaPlayerManager::SwapCurrentPlayer(int player_id) { + // Find the alternative player to swap the current one with. auto it = GetAlternativePlayer(player_id); if (it == alternative_players_.end()) - return; + return false; + MediaPlayerAndroid* new_player = *it; std::unique_ptr<MediaPlayerAndroid> old_player = SwapPlayer(player_id, new_player); + if (!old_player) { + // There's no player to swap with, destroy the alternative player and exit. + alternative_players_.erase(it); + return false; + } + alternative_players_.weak_erase(it); alternative_players_.push_back(old_player.release()); + return true; } void RemoteMediaPlayerManager::SwitchToRemotePlayer( int player_id, const std::string& casting_message) { DCHECK(!IsPlayingRemotely(player_id)); - SwapCurrentPlayer(player_id); + if (!SwapCurrentPlayer(player_id)) + return; players_playing_remotely_.insert(player_id); Send(new MediaPlayerMsg_DidMediaPlayerPlay(RoutingID(), player_id)); Send(new MediaPlayerMsg_ConnectedToRemoteDevice(RoutingID(), player_id,
diff --git a/chrome/browser/media/android/remote/remote_media_player_manager.h b/chrome/browser/media/android/remote/remote_media_player_manager.h index 3f09b9e..0e5173c 100644 --- a/chrome/browser/media/android/remote/remote_media_player_manager.h +++ b/chrome/browser/media/android/remote/remote_media_player_manager.h
@@ -104,7 +104,7 @@ // playing remotely. RemoteMediaPlayerBridge* GetRemotePlayer(int player_id); - void SwapCurrentPlayer(int player_id); + bool SwapCurrentPlayer(int player_id); void FetchPosterBitmap(int player_id);
diff --git a/chrome/browser/media/android/router/media_router_android.cc b/chrome/browser/media/android/router/media_router_android.cc index 76face5..fdb0013 100644 --- a/chrome/browser/media/android/router/media_router_android.cc +++ b/chrome/browser/media/android/router/media_router_android.cc
@@ -88,10 +88,7 @@ return; } - // TODO(avayvod): unify presentation id generation code between platforms. - // https://crbug.com/522239 - std::string presentation_id("mr_"); - presentation_id += base::GenerateGUID(); + std::string presentation_id = MediaRouterBase::CreatePresentationId(); int tab_id = -1; TabAndroid* tab = web_contents @@ -118,8 +115,6 @@ ScopedJavaLocalRef<jstring> jorigin = base::android::ConvertUTF8ToJavaString(env, origin.spec()); - // TODO(avayvod): Pass the off_the_record flag to Android. - // https://bugs.chromium.org/p/chromium/issues/detail?id=588239 Java_ChromeMediaRouter_createRoute( env, java_media_router_.obj(), @@ -439,6 +434,23 @@ FOR_EACH_OBSERVER(MediaRoutesObserver, routes_observers_, OnRoutesUpdated(active_routes_, std::vector<MediaRoute::Id>())); + NotifyPresentationConnectionStateChange( + route_id, content::PRESENTATION_CONNECTION_STATE_TERMINATED); +} + +void MediaRouterAndroid::OnRouteClosedWithError( + JNIEnv* env, + const JavaParamRef<jobject>& obj, + const JavaParamRef<jstring>& jmedia_route_id, + const JavaParamRef<jstring>& jmessage) { + MediaRoute::Id route_id = ConvertJavaStringToUTF8(env, jmedia_route_id); + std::string message = ConvertJavaStringToUTF8(env, jmessage); + NotifyPresentationConnectionClose( + route_id, + content::PRESENTATION_CONNECTION_CLOSE_REASON_CONNECTION_ERROR, + message); + + OnRouteClosed(env, obj, jmedia_route_id); } void MediaRouterAndroid::OnMessageSentResult(JNIEnv* env,
diff --git a/chrome/browser/media/android/router/media_router_android.h b/chrome/browser/media/android/router/media_router_android.h index 416c2d7..14be17f 100644 --- a/chrome/browser/media/android/router/media_router_android.h +++ b/chrome/browser/media/android/router/media_router_android.h
@@ -99,6 +99,13 @@ const base::android::JavaParamRef<jobject>& obj, const base::android::JavaParamRef<jstring>& jmedia_route_id); + // Notifies the media router when the route was closed with an error. + void OnRouteClosedWithError( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj, + const base::android::JavaParamRef<jstring>& jmedia_route_id, + const base::android::JavaParamRef<jstring>& jmessage); + // Notifies the media router about the result of sending a message. void OnMessageSentResult(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj,
diff --git a/chrome/browser/media/router/media_router_base.cc b/chrome/browser/media/router/media_router_base.cc index cea5fcd..21de578 100644 --- a/chrome/browser/media/router/media_router_base.cc +++ b/chrome/browser/media/router/media_router_base.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/media/router/media_router_base.h" #include "base/bind.h" +#include "base/guid.h" #include "base/memory/ptr_util.h" #include "base/stl_util.h" #include "chrome/browser/chrome_notification_types.h" @@ -50,6 +51,11 @@ } } +// static +std::string MediaRouterBase::CreatePresentationId() { + return "mr_" + base::GenerateGUID(); +} + void MediaRouterBase::NotifyPresentationConnectionStateChange( const MediaRoute::Id& route_id, content::PresentationConnectionState state) {
diff --git a/chrome/browser/media/router/media_router_base.h b/chrome/browser/media/router/media_router_base.h index be2a854..e95fa177 100644 --- a/chrome/browser/media/router/media_router_base.h +++ b/chrome/browser/media/router/media_router_base.h
@@ -39,6 +39,9 @@ FRIEND_TEST_ALL_PREFIXES(MediaRouterMojoImplTest, PresentationConnectionStateChangedCallbackRemoved); + // Generates a unique presentation id. Shared between Android and desktop. + static std::string CreatePresentationId(); + void NotifyPresentationConnectionStateChange( const MediaRoute::Id& route_id, content::PresentationConnectionState state);
diff --git a/chrome/browser/media/router/mojo/media_router_mojo_impl.cc b/chrome/browser/media/router/mojo/media_router_mojo_impl.cc index c2cacff..af1fe22 100644 --- a/chrome/browser/media/router/mojo/media_router_mojo_impl.cc +++ b/chrome/browser/media/router/mojo/media_router_mojo_impl.cc
@@ -604,8 +604,7 @@ const std::vector<MediaRouteResponseCallback>& callbacks, base::TimeDelta timeout, bool off_the_record) { - std::string presentation_id("mr_"); - presentation_id += base::GenerateGUID(); + std::string presentation_id = MediaRouterBase::CreatePresentationId(); DVLOG_WITH_INSTANCE(1) << "DoCreateRoute " << source_id << "=>" << sink_id << ", presentation ID: " << presentation_id; @@ -644,8 +643,7 @@ const std::vector<MediaRouteResponseCallback>& callbacks, base::TimeDelta timeout, bool off_the_record) { - std::string presentation_id("mr_"); - presentation_id += base::GenerateGUID(); + std::string presentation_id = MediaRouterBase::CreatePresentationId(); DVLOG_WITH_INSTANCE(1) << "DoConnectRouteByRouteId " << source_id << ", route ID: " << route_id << ", presentation ID: " << presentation_id;
diff --git a/chrome/browser/memory/tab_manager.h b/chrome/browser/memory/tab_manager.h index b856c9fd..1614cc7 100644 --- a/chrome/browser/memory/tab_manager.h +++ b/chrome/browser/memory/tab_manager.h
@@ -7,6 +7,7 @@ #include <stdint.h> +#include <memory> #include <set> #include <string> #include <utility> @@ -17,7 +18,6 @@ #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/memory_pressure_listener.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/strings/string16.h" #include "base/task_runner.h" @@ -248,7 +248,7 @@ base::RepeatingTimer recent_tab_discard_timer_; // A listener to global memory pressure events. - scoped_ptr<base::MemoryPressureListener> memory_pressure_listener_; + std::unique_ptr<base::MemoryPressureListener> memory_pressure_listener_; // Wall-clock time when the priority manager started running. base::TimeTicks start_time_; @@ -276,7 +276,7 @@ base::TimeDelta minimum_protection_time_; #if defined(OS_CHROMEOS) - scoped_ptr<TabManagerDelegate> delegate_; + std::unique_ptr<TabManagerDelegate> delegate_; #endif // Responsible for automatically registering this class as an observer of all
diff --git a/chrome/browser/memory/tab_manager_browsertest.cc b/chrome/browser/memory/tab_manager_browsertest.cc index a6d63a07..4b0dbed 100644 --- a/chrome/browser/memory/tab_manager_browsertest.cc +++ b/chrome/browser/memory/tab_manager_browsertest.cc
@@ -373,7 +373,7 @@ MediaCaptureDevicesDispatcher* dispatcher = MediaCaptureDevicesDispatcher::GetInstance(); dispatcher->SetTestVideoCaptureDevices(video_devices); - scoped_ptr<content::MediaStreamUI> video_stream_ui = + std::unique_ptr<content::MediaStreamUI> video_stream_ui = dispatcher->GetMediaStreamCaptureIndicator()->RegisterMediaStream( tab, video_devices); video_stream_ui->OnStarted(base::Closure());
diff --git a/chrome/browser/memory/tab_manager_web_contents_data_unittest.cc b/chrome/browser/memory/tab_manager_web_contents_data_unittest.cc index 0aa9e05c..25f1108 100644 --- a/chrome/browser/memory/tab_manager_web_contents_data_unittest.cc +++ b/chrome/browser/memory/tab_manager_web_contents_data_unittest.cc
@@ -39,7 +39,7 @@ base::SimpleTestTickClock& test_clock() { return test_clock_; } TabManager::WebContentsData* CreateWebContentsAndTabData( - scoped_ptr<WebContents>* web_contents) { + std::unique_ptr<WebContents>* web_contents) { web_contents->reset( WebContents::Create(WebContents::CreateParams(profile()))); TabManager::WebContentsData::CreateForWebContents(web_contents->get()); @@ -47,7 +47,7 @@ } private: - scoped_ptr<WebContents> web_contents_; + std::unique_ptr<WebContents> web_contents_; TabManager::WebContentsData* tab_data_; base::SimpleTestTickClock test_clock_; }; @@ -93,7 +93,7 @@ } TEST_F(TabManagerWebContentsDataTest, CopyState) { - scoped_ptr<WebContents> web_contents2; + std::unique_ptr<WebContents> web_contents2; auto tab_data2 = CreateWebContentsAndTabData(&web_contents2); EXPECT_EQ(tab_data()->tab_data_, tab_data2->tab_data_);
diff --git a/chrome/browser/memory_details.cc b/chrome/browser/memory_details.cc index 24479bdb..1dbb8522 100644 --- a/chrome/browser/memory_details.cc +++ b/chrome/browser/memory_details.cc
@@ -217,7 +217,7 @@ // First pass, collate the widgets by process ID. std::map<base::ProcessId, std::vector<RenderWidgetHost*>> widgets_by_pid; - scoped_ptr<content::RenderWidgetHostIterator> widget_it( + std::unique_ptr<content::RenderWidgetHostIterator> widget_it( RenderWidgetHost::GetRenderWidgetHosts()); while (content::RenderWidgetHost* widget = widget_it->GetNextHost()) { // Ignore processes that don't have a connection, such as crashed tabs.
diff --git a/chrome/browser/memory_details_android.cc b/chrome/browser/memory_details_android.cc index 1bceee0..8fa12e5 100644 --- a/chrome/browser/memory_details_android.cc +++ b/chrome/browser/memory_details_android.cc
@@ -4,12 +4,12 @@ #include "chrome/browser/memory_details.h" +#include <memory> #include <set> #include <string> #include <vector> #include "base/bind.h" -#include "base/memory/scoped_ptr.h" #include "base/process/process_iterator.h" #include "base/strings/utf_string_conversions.h" #include "chrome/common/chrome_constants.h" @@ -59,7 +59,7 @@ else pmi.process_type = content::PROCESS_TYPE_UNKNOWN; - scoped_ptr<base::ProcessMetrics> metrics( + std::unique_ptr<base::ProcessMetrics> metrics( base::ProcessMetrics::CreateProcessMetrics(*i)); metrics->GetWorkingSetKBytes(&pmi.working_set);
diff --git a/chrome/browser/memory_details_linux.cc b/chrome/browser/memory_details_linux.cc index cbcc36c2..a863109 100644 --- a/chrome/browser/memory_details_linux.cc +++ b/chrome/browser/memory_details_linux.cc
@@ -9,11 +9,11 @@ #include <unistd.h> #include <map> +#include <memory> #include <set> #include "base/bind.h" #include "base/files/file_util.h" -#include "base/memory/scoped_ptr.h" #include "base/process/process_iterator.h" #include "base/process/process_metrics.h" #include "base/strings/string_number_conversions.h" @@ -67,7 +67,7 @@ else pmi.process_type = content::PROCESS_TYPE_UNKNOWN; - scoped_ptr<base::ProcessMetrics> metrics( + std::unique_ptr<base::ProcessMetrics> metrics( base::ProcessMetrics::CreateProcessMetrics(pid)); metrics->GetWorkingSetKBytes(&pmi.working_set);
diff --git a/chrome/browser/memory_details_mac.cc b/chrome/browser/memory_details_mac.cc index 23a1ed9..08ca920 100644 --- a/chrome/browser/memory_details_mac.cc +++ b/chrome/browser/memory_details_mac.cc
@@ -6,6 +6,7 @@ #include <stddef.h> +#include <memory> #include <set> #include <string> @@ -13,7 +14,6 @@ #include "base/file_version_info.h" #include "base/files/file_path.h" #include "base/mac/foundation_util.h" -#include "base/memory/scoped_ptr.h" #include "base/process/process_iterator.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -57,7 +57,7 @@ } } - scoped_ptr<base::ProcessMetrics> metrics; + std::unique_ptr<base::ProcessMetrics> metrics; metrics.reset(base::ProcessMetrics::CreateProcessMetrics( pid, content::BrowserChildProcessHost::GetPortProvider())); metrics->GetCommittedAndWorkingSetKBytes(&info.committed, &info.working_set);
diff --git a/chrome/browser/memory_details_win.cc b/chrome/browser/memory_details_win.cc index b29fa70..7452134 100644 --- a/chrome/browser/memory_details_win.cc +++ b/chrome/browser/memory_details_win.cc
@@ -8,10 +8,11 @@ #include <stddef.h> #include <TlHelp32.h> +#include <memory> + #include "base/bind.h" #include "base/file_version_info.h" #include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -80,7 +81,7 @@ else info.process_type = content::PROCESS_TYPE_UNKNOWN; - scoped_ptr<base::ProcessMetrics> metrics; + std::unique_ptr<base::ProcessMetrics> metrics; metrics.reset( base::ProcessMetrics::CreateProcessMetrics(process_handle.Get())); metrics->GetCommittedKBytes(&info.committed);
diff --git a/chrome/browser/metrics/android_metrics_provider.cc b/chrome/browser/metrics/android_metrics_provider.cc index cc6d1961..f5ec3085 100644 --- a/chrome/browser/metrics/android_metrics_provider.cc +++ b/chrome/browser/metrics/android_metrics_provider.cc
@@ -57,6 +57,9 @@ UMA_HISTOGRAM_BOOLEAN( "MemoryAndroid.LowRamDevice", base::SysInfo::IsLowEndDevice()); + UMA_HISTOGRAM_BOOLEAN( + "Android.MultiWindowMode.Active", + chrome::android::GetIsInMultiWindowModeValue()); } void AndroidMetricsProvider::OnForegroundActivityChanged(
diff --git a/chrome/browser/mod_pagespeed/mod_pagespeed_metrics_unittest.cc b/chrome/browser/mod_pagespeed/mod_pagespeed_metrics_unittest.cc index 38ef0cb..c809da8e 100644 --- a/chrome/browser/mod_pagespeed/mod_pagespeed_metrics_unittest.cc +++ b/chrome/browser/mod_pagespeed/mod_pagespeed_metrics_unittest.cc
@@ -5,10 +5,10 @@ #include "chrome/browser/mod_pagespeed/mod_pagespeed_metrics.h" #include <algorithm> +#include <memory> #include <string> #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/histogram.h" #include "base/metrics/histogram_samples.h" #include "base/metrics/statistics_recorder.h" @@ -37,8 +37,8 @@ int num_bucket_30 = 0; // 1.2.24.1 bucket int num_bucket_33 = 0; // 1.3.25.2 bucket - scoped_ptr<base::HistogramSamples> server_samples; - scoped_ptr<base::HistogramSamples> version_samples; + std::unique_ptr<base::HistogramSamples> server_samples; + std::unique_ptr<base::HistogramSamples> version_samples; // No PageSpeed header. The VersionCounts histogram isn't created yet. RecordMetrics(content::RESOURCE_TYPE_MAIN_FRAME, url, headers.get());
diff --git a/chrome/browser/nacl_host/nacl_infobar_delegate.cc b/chrome/browser/nacl_host/nacl_infobar_delegate.cc index 3bb7131..3ed05126 100644 --- a/chrome/browser/nacl_host/nacl_infobar_delegate.cc +++ b/chrome/browser/nacl_host/nacl_infobar_delegate.cc
@@ -28,7 +28,7 @@ InfoBarService::FromWebContents(web_contents); if (infobar_service) { infobar_service->AddInfoBar(infobar_service->CreateConfirmInfoBar( - scoped_ptr<ConfirmInfoBarDelegate>(new NaClInfoBarDelegate()))); + std::unique_ptr<ConfirmInfoBarDelegate>(new NaClInfoBarDelegate()))); } }
diff --git a/chrome/browser/nacl_host/test/gdb_debug_stub_browsertest.cc b/chrome/browser/nacl_host/test/gdb_debug_stub_browsertest.cc index 0f036d6..2fc111a 100644 --- a/chrome/browser/nacl_host/test/gdb_debug_stub_browsertest.cc +++ b/chrome/browser/nacl_host/test/gdb_debug_stub_browsertest.cc
@@ -53,7 +53,7 @@ void NaClGdbDebugStubTest::RunDebugStubTest(const std::string& nacl_module, const std::string& test_name) { base::Process test_script; - scoped_ptr<base::Environment> env(base::Environment::Create()); + std::unique_ptr<base::Environment> env(base::Environment::Create()); nacl::NaClBrowser::GetInstance()->SetGdbDebugStubPortListener( base::Bind(&NaClGdbDebugStubTest::StartTestScript, base::Unretained(this), &test_script, test_name));
diff --git a/chrome/browser/nacl_host/test/mock_nacl_gdb.cc b/chrome/browser/nacl_host/test/mock_nacl_gdb.cc index a61c47b..cb98b3a 100644 --- a/chrome/browser/nacl_host/test/mock_nacl_gdb.cc +++ b/chrome/browser/nacl_host/test/mock_nacl_gdb.cc
@@ -4,12 +4,12 @@ #include <cstdio> #include <cstring> +#include <memory> #include "base/command_line.h" #include "base/environment.h" #include "base/files/file_util.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" static const char kEvalCommand[] = "--eval-command"; static const char kCommand[] = "--command"; @@ -18,7 +18,7 @@ static const char kAttach[] = "target remote :4014"; int main(int argc, char** argv) { - scoped_ptr<base::Environment> env(base::Environment::Create()); + std::unique_ptr<base::Environment> env(base::Environment::Create()); std::string mock_nacl_gdb_file; env->GetVar("MOCK_NACL_GDB", &mock_nacl_gdb_file); CHECK_GE(argc, 5);
diff --git a/chrome/browser/nacl_host/test/nacl_gdb_browsertest.cc b/chrome/browser/nacl_host/test/nacl_gdb_browsertest.cc index 860c228..d498d950 100644 --- a/chrome/browser/nacl_host/test/nacl_gdb_browsertest.cc +++ b/chrome/browser/nacl_host/test/nacl_gdb_browsertest.cc
@@ -5,6 +5,7 @@ #include "base/command_line.h" #include "base/environment.h" #include "base/files/file_util.h" +#include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/win/windows_version.h" #include "build/build_config.h" @@ -37,7 +38,7 @@ void RunWithNaClGdb(const std::string& test_name) { base::FilePath mock_nacl_gdb_file; - scoped_ptr<base::Environment> env(base::Environment::Create()); + std::unique_ptr<base::Environment> env(base::Environment::Create()); std::string content; // TODO(halyavin): Make this test work on Windows 32-bit. Currently this // is not possible because NaCl doesn't work without sandbox since 1Gb of
diff --git a/chrome/browser/notifications/extension_welcome_notification.cc b/chrome/browser/notifications/extension_welcome_notification.cc index d790d38..19afb42 100644 --- a/chrome/browser/notifications/extension_welcome_notification.cc +++ b/chrome/browser/notifications/extension_welcome_notification.cc
@@ -183,7 +183,7 @@ PrefServiceSyncableFromProfile(profile_); if (pref_service_syncable->IsSyncing()) { pref_service_syncable->RemoveObserver(this); - scoped_ptr<Notification> previous_notification( + std::unique_ptr<Notification> previous_notification( delayed_notification_.release()); ShowWelcomeNotificationIfNecessary(*(previous_notification.get())); } @@ -259,7 +259,7 @@ welcome_notification_id_ = base::GenerateGUID(); if (!welcome_notification_id_.empty()) { - scoped_ptr<message_center::Notification> message_center_notification( + std::unique_ptr<message_center::Notification> message_center_notification( new message_center::Notification( message_center::NOTIFICATION_TYPE_BASE_FORMAT, welcome_notification_id_,
diff --git a/chrome/browser/notifications/extension_welcome_notification.h b/chrome/browser/notifications/extension_welcome_notification.h index ef79acf0..41bb428 100644 --- a/chrome/browser/notifications/extension_welcome_notification.h +++ b/chrome/browser/notifications/extension_welcome_notification.h
@@ -5,10 +5,10 @@ #ifndef CHROME_BROWSER_NOTIFICATIONS_EXTENSION_WELCOME_NOTIFICATION_H_ #define CHROME_BROWSER_NOTIFICATIONS_EXTENSION_WELCOME_NOTIFICATION_H_ +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/timer/timer.h" #include "components/keyed_service/core/keyed_service.h" #include "components/prefs/pref_member.h" @@ -149,15 +149,15 @@ // Simplifying Assumption: The delayed notification has passed the // extension ID check. This means we do not need to store all of the // notifications that may also show a welcome notification. - scoped_ptr<Notification> delayed_notification_; + std::unique_ptr<Notification> delayed_notification_; // If the welcome notification is shown, this timer tracks when to hide the // welcome notification. - scoped_ptr<base::OneShotTimer> expiration_timer_; + std::unique_ptr<base::OneShotTimer> expiration_timer_; // Delegate for Chrome global calls like base::Time::GetTime() for // testability. - scoped_ptr<Delegate> delegate_; + std::unique_ptr<Delegate> delegate_; DISALLOW_COPY_AND_ASSIGN(ExtensionWelcomeNotification); };
diff --git a/chrome/browser/notifications/extension_welcome_notification_unittest.cc b/chrome/browser/notifications/extension_welcome_notification_unittest.cc index ae862a3..942eec8 100644 --- a/chrome/browser/notifications/extension_welcome_notification_unittest.cc +++ b/chrome/browser/notifications/extension_welcome_notification_unittest.cc
@@ -6,10 +6,10 @@ #include <stdint.h> +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/test/test_simple_task_runner.h" @@ -51,7 +51,7 @@ } void AddNotification( - scoped_ptr<message_center::Notification> notification) override { + std::unique_ptr<message_center::Notification> notification) override { EXPECT_FALSE(last_notification.get()); last_notification.swap(notification); add_notification_calls_++; @@ -72,7 +72,7 @@ } private: - scoped_ptr<message_center::Notification> last_notification; + std::unique_ptr<message_center::Notification> last_notification; int add_notification_calls_; int remove_notification_calls_; int notifications_with_shown_as_popup_; @@ -119,7 +119,7 @@ private: const base::Time start_time_; base::TimeDelta elapsed_time_; - scoped_ptr<MockMessageCenter> message_center_; + std::unique_ptr<MockMessageCenter> message_center_; base::Closure pending_task_; DISALLOW_COPY_AND_ASSIGN(WelcomeNotificationDelegate); @@ -155,11 +155,10 @@ void StartPreferenceSyncing() const { PrefServiceSyncableFromProfile(profile_.get()) ->GetSyncableService(syncer::PREFERENCES) - ->MergeDataAndStartSyncing(syncer::PREFERENCES, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( + ->MergeDataAndStartSyncing(syncer::PREFERENCES, syncer::SyncDataList(), + std::unique_ptr<syncer::SyncChangeProcessor>( new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>( + std::unique_ptr<syncer::SyncErrorFactory>( new syncer::SyncErrorFactoryMock())); } @@ -235,11 +234,11 @@ } scoped_refptr<base::TestSimpleTaskRunner> task_runner_; - scoped_ptr<base::ThreadTaskRunnerHandle> thread_task_runner_handle_; - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<base::ThreadTaskRunnerHandle> thread_task_runner_handle_; + std::unique_ptr<TestingProfile> profile_; // Weak Ref owned by welcome_notification_ WelcomeNotificationDelegate* delegate_; - scoped_ptr<ExtensionWelcomeNotification> welcome_notification_; + std::unique_ptr<ExtensionWelcomeNotification> welcome_notification_; DISALLOW_COPY_AND_ASSIGN(ExtensionWelcomeNotificationTest); };
diff --git a/chrome/browser/notifications/login_state_notification_blocker_chromeos_browsertest.cc b/chrome/browser/notifications/login_state_notification_blocker_chromeos_browsertest.cc index a720c80..92cc81f 100644 --- a/chrome/browser/notifications/login_state_notification_blocker_chromeos_browsertest.cc +++ b/chrome/browser/notifications/login_state_notification_blocker_chromeos_browsertest.cc
@@ -46,7 +46,7 @@ void OnUserAddingStarted() override { finished_ = false; } private: - scoped_ptr<base::RunLoop> run_loop_; + std::unique_ptr<base::RunLoop> run_loop_; bool finished_ = false; // True if OnUserAddingFinished() has been called // before WaitUntilUserAddingFinishedOrCancelled(). DISALLOW_COPY_AND_ASSIGN(UserAddingFinishObserver); @@ -101,7 +101,7 @@ private: int state_changed_count_; - scoped_ptr<message_center::NotificationBlocker> blocker_; + std::unique_ptr<message_center::NotificationBlocker> blocker_; DISALLOW_COPY_AND_ASSIGN(LoginStateNotificationBlockerChromeOSBrowserTest); };
diff --git a/chrome/browser/notifications/login_state_notification_blocker_chromeos_unittest.cc b/chrome/browser/notifications/login_state_notification_blocker_chromeos_unittest.cc index 32d8e5f..dd52c0c 100644 --- a/chrome/browser/notifications/login_state_notification_blocker_chromeos_unittest.cc +++ b/chrome/browser/notifications/login_state_notification_blocker_chromeos_unittest.cc
@@ -2,13 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/notifications/login_state_notification_blocker_chromeos.h" + +#include <memory> + #include "ash/shell.h" #include "ash/system/system_notifier.h" #include "ash/test/ash_test_base.h" #include "base/command_line.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" -#include "chrome/browser/notifications/login_state_notification_blocker_chromeos.h" #include "chromeos/login/login_state.h" #include "ui/message_center/message_center.h" #include "ui/message_center/notification.h" @@ -57,7 +59,7 @@ private: int state_changed_count_; - scoped_ptr<message_center::NotificationBlocker> blocker_; + std::unique_ptr<message_center::NotificationBlocker> blocker_; DISALLOW_COPY_AND_ASSIGN(LoginStateNotificationBlockerChromeOSTest); };
diff --git a/chrome/browser/notifications/message_center_notification_manager.cc b/chrome/browser/notifications/message_center_notification_manager.cc index da307bb..b004ccf 100644 --- a/chrome/browser/notifications/message_center_notification_manager.cc +++ b/chrome/browser/notifications/message_center_notification_manager.cc
@@ -4,10 +4,11 @@ #include "chrome/browser/notifications/message_center_notification_manager.h" +#include <memory> #include <utility> #include "base/logging.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "build/build_config.h" @@ -55,7 +56,7 @@ MessageCenterNotificationManager::MessageCenterNotificationManager( message_center::MessageCenter* message_center, - scoped_ptr<message_center::NotifierSettingsProvider> settings_provider) + std::unique_ptr<message_center::NotifierSettingsProvider> settings_provider) : message_center_(message_center), settings_provider_(std::move(settings_provider)), system_observer_(this), @@ -65,14 +66,14 @@ message_center_->SetNotifierSettingsProvider(settings_provider_.get()); #if defined(OS_CHROMEOS) - blockers_.push_back(make_scoped_ptr( + blockers_.push_back(base::WrapUnique( new LoginStateNotificationBlockerChromeOS(message_center))); #else - blockers_.push_back(make_scoped_ptr( - new ScreenLockNotificationBlocker(message_center))); + blockers_.push_back( + base::WrapUnique(new ScreenLockNotificationBlocker(message_center))); #endif - blockers_.push_back(make_scoped_ptr( - new FullscreenNotificationBlocker(message_center))); + blockers_.push_back( + base::WrapUnique(new FullscreenNotificationBlocker(message_center))); #if defined(OS_WIN) || defined(OS_MACOSX) \ || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) @@ -124,7 +125,7 @@ AddNotificationToAlternateProvider(profile_notification->notification(), profile, extension_id); - message_center_->AddNotification(make_scoped_ptr( + message_center_->AddNotification(base::WrapUnique( new message_center::Notification(profile_notification->notification()))); } @@ -167,9 +168,8 @@ // center via the notification within a ProfileNotification object or the // profile ID will not be correctly set for ChromeOS. message_center_->UpdateNotification( - old_id, - make_scoped_ptr(new message_center::Notification( - new_notification->notification()))); + old_id, base::WrapUnique(new message_center::Notification( + new_notification->notification()))); return true; }
diff --git a/chrome/browser/notifications/message_center_notification_manager.h b/chrome/browser/notifications/message_center_notification_manager.h index 40a5b61..8b153db 100644 --- a/chrome/browser/notifications/message_center_notification_manager.h +++ b/chrome/browser/notifications/message_center_notification_manager.h
@@ -6,12 +6,12 @@ #define CHROME_BROWSER_NOTIFICATIONS_MESSAGE_CENTER_NOTIFICATION_MANAGER_H_ #include <map> +#include <memory> #include <string> #include <vector> #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "base/timer/timer.h" @@ -43,7 +43,8 @@ public: MessageCenterNotificationManager( message_center::MessageCenter* message_center, - scoped_ptr<message_center::NotifierSettingsProvider> settings_provider); + std::unique_ptr<message_center::NotifierSettingsProvider> + settings_provider); ~MessageCenterNotificationManager() override; // NotificationUIManager @@ -88,7 +89,7 @@ FRIEND_TEST_ALL_PREFIXES(message_center::WebNotificationTrayTest, ManuallyCloseMessageCenter); - scoped_ptr<message_center::MessageCenterTrayDelegate> tray_; + std::unique_ptr<message_center::MessageCenterTrayDelegate> tray_; message_center::MessageCenter* message_center_; // Weak, global. // Use a map by notification_id since this mapping is the most often used. @@ -108,10 +109,10 @@ // Chorme Notification Center. std::string GetExtensionTakingOverNotifications(Profile* profile); - scoped_ptr<message_center::NotifierSettingsProvider> settings_provider_; + std::unique_ptr<message_center::NotifierSettingsProvider> settings_provider_; // To own the blockers. - std::vector<scoped_ptr<message_center::NotificationBlocker>> blockers_; + std::vector<std::unique_ptr<message_center::NotificationBlocker>> blockers_; NotificationSystemObserver system_observer_;
diff --git a/chrome/browser/notifications/message_center_notifications_unittest.cc b/chrome/browser/notifications/message_center_notifications_unittest.cc index a0bf676c..7420313 100644 --- a/chrome/browser/notifications/message_center_notifications_unittest.cc +++ b/chrome/browser/notifications/message_center_notifications_unittest.cc
@@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "base/strings/utf_string_conversions.h" #include "base/test/test_timeouts.h" #include "base/values.h" @@ -93,7 +94,7 @@ } private: - scoped_ptr<TestingProfileManager> profile_manager_; + std::unique_ptr<TestingProfileManager> profile_manager_; MessageCenter* message_center_; FakeMessageCenterTrayDelegate* delegate_; }; @@ -124,10 +125,9 @@ chrome::MultiUserWindowManager::SetInstanceForTest( multi_user_window_manager, chrome::MultiUserWindowManager::MULTI_PROFILE_MODE_SEPARATED); - scoped_ptr<MultiUserNotificationBlockerChromeOS> blocker( + std::unique_ptr<MultiUserNotificationBlockerChromeOS> blocker( new MultiUserNotificationBlockerChromeOS( - message_center::MessageCenter::Get(), - active_user_id)); + message_center::MessageCenter::Get(), active_user_id)); EXPECT_EQ(0u, message_center()->NotificationCount()); notification_manager()->Add(GetANotification("test"), &profile); EXPECT_EQ(1u, message_center()->NotificationCount());
diff --git a/chrome/browser/notifications/message_center_settings_controller.cc b/chrome/browser/notifications/message_center_settings_controller.cc index f0e14e7..e1a85df 100644 --- a/chrome/browser/notifications/message_center_settings_controller.cc +++ b/chrome/browser/notifications/message_center_settings_controller.cc
@@ -292,8 +292,8 @@ #endif UErrorCode error = U_ZERO_ERROR; - scoped_ptr<icu::Collator> collator(icu::Collator::createInstance(error)); - scoped_ptr<NotifierComparator> comparator( + std::unique_ptr<icu::Collator> collator(icu::Collator::createInstance(error)); + std::unique_ptr<NotifierComparator> comparator( new NotifierComparator(U_SUCCESS(error) ? collator.get() : NULL)); std::sort(notifiers->begin(), notifiers->end(), *comparator); @@ -411,9 +411,9 @@ Profile* profile = notifier_groups_[current_notifier_group_]->profile(); extensions::EventRouter* event_router = extensions::EventRouter::Get(profile); - scoped_ptr<base::ListValue> args(new base::ListValue()); + std::unique_ptr<base::ListValue> args(new base::ListValue()); - scoped_ptr<extensions::Event> event(new extensions::Event( + std::unique_ptr<extensions::Event> event(new extensions::Event( extensions::events::NOTIFICATIONS_ON_SHOW_SETTINGS, extensions::api::notifications::OnShowSettings::kEventName, std::move(args))); @@ -493,11 +493,10 @@ chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe(user); DCHECK(profile); - scoped_ptr<message_center::ProfileNotifierGroup> group( - new message_center::ProfileNotifierGroup(gfx::Image(user->GetImage()), - user->GetDisplayName(), - user->GetDisplayName(), - profile)); + std::unique_ptr<message_center::ProfileNotifierGroup> group( + new message_center::ProfileNotifierGroup( + gfx::Image(user->GetImage()), user->GetDisplayName(), + user->GetDisplayName(), profile)); notifier_groups_.push_back(std::move(group)); @@ -514,11 +513,9 @@ std::vector<ProfileAttributesEntry*> entries = profile_attributes_storage_.GetAllProfilesAttributes(); for (const auto entry : entries) { - scoped_ptr<message_center::ProfileNotifierGroup> group( + std::unique_ptr<message_center::ProfileNotifierGroup> group( new message_center::ProfileNotifierGroup( - entry->GetAvatarIcon(), - entry->GetName(), - entry->GetUserName(), + entry->GetAvatarIcon(), entry->GetName(), entry->GetUserName(), entry->GetPath())); if (group->profile() == NULL) continue;
diff --git a/chrome/browser/notifications/message_center_settings_controller.h b/chrome/browser/notifications/message_center_settings_controller.h index ae2f4f1..a65da5e 100644 --- a/chrome/browser/notifications/message_center_settings_controller.h +++ b/chrome/browser/notifications/message_center_settings_controller.h
@@ -8,10 +8,10 @@ #include <stddef.h> #include <map> +#include <memory> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "build/build_config.h" @@ -121,16 +121,16 @@ base::ObserverList<message_center::NotifierSettingsObserver> observers_; // The task tracker for loading favicons. - scoped_ptr<base::CancelableTaskTracker> favicon_tracker_; + std::unique_ptr<base::CancelableTaskTracker> favicon_tracker_; - scoped_ptr<AppIconLoader> app_icon_loader_; + std::unique_ptr<AppIconLoader> app_icon_loader_; std::map<base::string16, ContentSettingsPattern> patterns_; // The list of all configurable notifier groups. This is each profile that is // loaded (and in the ProfileAttributesStorage - so no incognito profiles go // here). - std::vector<scoped_ptr<message_center::ProfileNotifierGroup>> + std::vector<std::unique_ptr<message_center::ProfileNotifierGroup>> notifier_groups_; size_t current_notifier_group_;
diff --git a/chrome/browser/notifications/message_center_settings_controller_unittest.cc b/chrome/browser/notifications/message_center_settings_controller_unittest.cc index 770b31c..0dd7c285 100644 --- a/chrome/browser/notifications/message_center_settings_controller_unittest.cc +++ b/chrome/browser/notifications/message_center_settings_controller_unittest.cc
@@ -62,7 +62,7 @@ private: content::TestBrowserThreadBundle thread_bundle_; TestingProfileManager testing_profile_manager_; - scoped_ptr<MessageCenterSettingsController> controller_; + std::unique_ptr<MessageCenterSettingsController> controller_; DISALLOW_COPY_AND_ASSIGN(MessageCenterSettingsControllerBaseTest); }; @@ -108,7 +108,7 @@ user_manager::UserManager::Get()); } - scoped_ptr<chromeos::ScopedUserManagerEnabler> user_manager_enabler_; + std::unique_ptr<chromeos::ScopedUserManagerEnabler> user_manager_enabler_; DISALLOW_COPY_AND_ASSIGN(MessageCenterSettingsControllerChromeOSTest); };
diff --git a/chrome/browser/notifications/notification.h b/chrome/browser/notifications/notification.h index 99b9072..6c7b9f205 100644 --- a/chrome/browser/notifications/notification.h +++ b/chrome/browser/notifications/notification.h
@@ -5,9 +5,9 @@ #ifndef CHROME_BROWSER_NOTIFICATIONS_NOTIFICATION_H_ #define CHROME_BROWSER_NOTIFICATIONS_NOTIFICATION_H_ +#include <memory> #include <string> -#include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "base/values.h" #include "chrome/browser/notifications/notification_delegate.h"
diff --git a/chrome/browser/notifications/notification_browsertest.cc b/chrome/browser/notifications/notification_browsertest.cc index 6362499a..454830e 100644 --- a/chrome/browser/notifications/notification_browsertest.cc +++ b/chrome/browser/notifications/notification_browsertest.cc
@@ -739,7 +739,7 @@ HostContentSettingsMap* settings_map = HostContentSettingsMapFactory::GetForProfile(browser()->profile()); base::SimpleTestClock* clock = new base::SimpleTestClock(); - settings_map->SetPrefClockForTesting(scoped_ptr<base::Clock>(clock)); + settings_map->SetPrefClockForTesting(std::unique_ptr<base::Clock>(clock)); clock->SetNow(base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(10)); // Creates a simple notification.
diff --git a/chrome/browser/notifications/notification_conversion_helper.cc b/chrome/browser/notifications/notification_conversion_helper.cc index c470a66d..f11b363b 100644 --- a/chrome/browser/notifications/notification_conversion_helper.cc +++ b/chrome/browser/notifications/notification_conversion_helper.cc
@@ -7,12 +7,12 @@ #include <stddef.h> #include <stdint.h> +#include <memory> #include <string> #include <utility> #include <vector> #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/utf_string_conversions.h" #include "chrome/common/extensions/api/notification_provider.h" #include "chrome/common/extensions/api/notifications/notification_style.h" @@ -28,7 +28,7 @@ options->type = extensions::api::notifications::ParseTemplateType(type); if (!notification.icon().IsEmpty()) { - scoped_ptr<extensions::api::notifications::NotificationBitmap> icon( + std::unique_ptr<extensions::api::notifications::NotificationBitmap> icon( new extensions::api::notifications::NotificationBitmap()); GfxImageToNotificationBitmap(¬ification.icon(), icon.get()); options->icon_bitmap = std::move(icon); @@ -44,8 +44,8 @@ ¬ification.rich_notification_data(); if (!rich_data->small_image.IsEmpty()) { - scoped_ptr<extensions::api::notifications::NotificationBitmap> icon_mask( - new extensions::api::notifications::NotificationBitmap()); + std::unique_ptr<extensions::api::notifications::NotificationBitmap> + icon_mask(new extensions::api::notifications::NotificationBitmap()); GfxImageToNotificationBitmap(&rich_data->small_image, icon_mask.get()); options->app_icon_mask_bitmap = std::move(icon_mask); } @@ -68,8 +68,8 @@ button.title = base::UTF16ToUTF8(button_info.title); if (!button_info.icon.IsEmpty()) { - scoped_ptr<extensions::api::notifications::NotificationBitmap> icon( - new extensions::api::notifications::NotificationBitmap()); + std::unique_ptr<extensions::api::notifications::NotificationBitmap> + icon(new extensions::api::notifications::NotificationBitmap()); GfxImageToNotificationBitmap(&button_info.icon, icon.get()); button.icon_bitmap = std::move(icon); } @@ -79,7 +79,7 @@ // Only image type notifications should have images. if (type == "image" && !rich_data->image.IsEmpty()) { - scoped_ptr<extensions::api::notifications::NotificationBitmap> image( + std::unique_ptr<extensions::api::notifications::NotificationBitmap> image( new extensions::api::notifications::NotificationBitmap()); GfxImageToNotificationBitmap(¬ification.image(), image.get()); options->image_bitmap = std::move(image); @@ -122,7 +122,7 @@ uint32_t* bitmap_pixels = sk_bitmap.getAddr32(0, 0); const unsigned char* bitmap = reinterpret_cast<const unsigned char*>(bitmap_pixels); - scoped_ptr<std::vector<char>> rgba_bitmap_data( + std::unique_ptr<std::vector<char>> rgba_bitmap_data( new std::vector<char>(pixel_count * BYTES_PER_PIXEL)); gfx::ConvertSkiaToRGBA(bitmap, pixel_count, reinterpret_cast<unsigned char*>(
diff --git a/chrome/browser/notifications/notification_conversion_helper_unittest.cc b/chrome/browser/notifications/notification_conversion_helper_unittest.cc index e5072949..d26ab6d 100644 --- a/chrome/browser/notifications/notification_conversion_helper_unittest.cc +++ b/chrome/browser/notifications/notification_conversion_helper_unittest.cc
@@ -24,7 +24,7 @@ void TearDown() override {} protected: - scoped_ptr<Notification> CreateNotification( + std::unique_ptr<Notification> CreateNotification( message_center::NotificationType type) { message_center::RichNotificationData optional_fields; optional_fields.priority = 1; @@ -57,7 +57,7 @@ bitmap.eraseColor(SkColorSetRGB(1, 2, 3)); gfx::Image icon = gfx::Image::CreateFrom1xBitmap(bitmap); - scoped_ptr<Notification> notification(new Notification( + std::unique_ptr<Notification> notification(new Notification( type, base::UTF8ToUTF16("Title"), base::UTF8ToUTF16("This is a message."), icon, message_center::NotifierId(message_center::NotifierId::APPLICATION, @@ -74,9 +74,9 @@ TEST_F(NotificationConversionHelperTest, NotificationToNotificationOptions) { // Create a notification of image type - scoped_ptr<Notification> notification1 = + std::unique_ptr<Notification> notification1 = CreateNotification(message_center::NOTIFICATION_TYPE_IMAGE); - scoped_ptr<extensions::api::notifications::NotificationOptions> options1( + std::unique_ptr<extensions::api::notifications::NotificationOptions> options1( new extensions::api::notifications::NotificationOptions()); NotificationConversionHelper::NotificationToNotificationOptions( *(notification1), options1.get()); @@ -96,9 +96,9 @@ EXPECT_EQ(options1->icon_bitmap->height, 1); // Create a notification of progress type - scoped_ptr<Notification> notification2 = + std::unique_ptr<Notification> notification2 = CreateNotification(message_center::NOTIFICATION_TYPE_PROGRESS); - scoped_ptr<extensions::api::notifications::NotificationOptions> options2( + std::unique_ptr<extensions::api::notifications::NotificationOptions> options2( new extensions::api::notifications::NotificationOptions()); NotificationConversionHelper::NotificationToNotificationOptions( *(notification2), options2.get()); @@ -107,9 +107,9 @@ EXPECT_EQ(*(options2->progress), 50); // Create a notification of multiple type - scoped_ptr<Notification> notification3 = + std::unique_ptr<Notification> notification3 = CreateNotification(message_center::NOTIFICATION_TYPE_MULTIPLE); - scoped_ptr<extensions::api::notifications::NotificationOptions> options3( + std::unique_ptr<extensions::api::notifications::NotificationOptions> options3( new extensions::api::notifications::NotificationOptions()); NotificationConversionHelper::NotificationToNotificationOptions( *(notification3), options3.get());
diff --git a/chrome/browser/notifications/notification_object_proxy.cc b/chrome/browser/notifications/notification_object_proxy.cc index cef1b00..15a57b3d 100644 --- a/chrome/browser/notifications/notification_object_proxy.cc +++ b/chrome/browser/notifications/notification_object_proxy.cc
@@ -13,7 +13,7 @@ NotificationObjectProxy::NotificationObjectProxy( content::BrowserContext* browser_context, - scoped_ptr<content::DesktopNotificationDelegate> delegate) + std::unique_ptr<content::DesktopNotificationDelegate> delegate) : browser_context_(browser_context), delegate_(std::move(delegate)), displayed_(false),
diff --git a/chrome/browser/notifications/notification_object_proxy.h b/chrome/browser/notifications/notification_object_proxy.h index 1de7447..e09bfff 100644 --- a/chrome/browser/notifications/notification_object_proxy.h +++ b/chrome/browser/notifications/notification_object_proxy.h
@@ -5,10 +5,10 @@ #ifndef CHROME_BROWSER_NOTIFICATIONS_NOTIFICATION_OBJECT_PROXY_H_ #define CHROME_BROWSER_NOTIFICATIONS_NOTIFICATION_OBJECT_PROXY_H_ +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/notifications/notification_delegate.h" namespace content { @@ -26,7 +26,7 @@ // will take ownership of |delegate|. NotificationObjectProxy( content::BrowserContext* browser_context, - scoped_ptr<content::DesktopNotificationDelegate> delegate); + std::unique_ptr<content::DesktopNotificationDelegate> delegate); // NotificationDelegate implementation. void Display() override; @@ -42,7 +42,7 @@ private: content::BrowserContext* browser_context_; - scoped_ptr<content::DesktopNotificationDelegate> delegate_; + std::unique_ptr<content::DesktopNotificationDelegate> delegate_; bool displayed_; std::string id_;
diff --git a/chrome/browser/notifications/notification_permission_context.cc b/chrome/browser/notifications/notification_permission_context.cc index c156dac..499c115 100644 --- a/chrome/browser/notifications/notification_permission_context.cc +++ b/chrome/browser/notifications/notification_permission_context.cc
@@ -59,7 +59,7 @@ bool is_visible_; struct Task { - Task(const PermissionRequestID& id, scoped_ptr<base::Timer> timer) + Task(const PermissionRequestID& id, std::unique_ptr<base::Timer> timer) : id(id), timer(std::move(timer)) {} Task& operator=(Task&& other) { @@ -69,7 +69,7 @@ } PermissionRequestID id; - scoped_ptr<base::Timer> timer; + std::unique_ptr<base::Timer> timer; private: DISALLOW_COPY_AND_ASSIGN(Task); @@ -107,7 +107,7 @@ // Safe to use Unretained, as destroying this will destroy task_queue_, hence // cancelling all timers. - scoped_ptr<base::Timer> timer(new base::Timer( + std::unique_ptr<base::Timer> timer(new base::Timer( from_here, visible_delay, base::Bind(&VisibilityTimerTabHelper::RunTask, base::Unretained(this), task), false /* is_repeating */));
diff --git a/chrome/browser/notifications/notification_permission_infobar_delegate.cc b/chrome/browser/notifications/notification_permission_infobar_delegate.cc index 46b5a5c7..39a1f39 100644 --- a/chrome/browser/notifications/notification_permission_infobar_delegate.cc +++ b/chrome/browser/notifications/notification_permission_infobar_delegate.cc
@@ -18,7 +18,7 @@ const GURL& requesting_frame, const base::Callback<void(bool, bool)>& callback) { return infobar_service->AddInfoBar(infobar_service->CreateConfirmInfoBar( - scoped_ptr<ConfirmInfoBarDelegate>( + std::unique_ptr<ConfirmInfoBarDelegate>( new NotificationPermissionInfobarDelegate(requesting_frame, callback)))); }
diff --git a/chrome/browser/notifications/notification_ui_manager_desktop.cc b/chrome/browser/notifications/notification_ui_manager_desktop.cc index 7de03bb5..d1fc804 100644 --- a/chrome/browser/notifications/notification_ui_manager_desktop.cc +++ b/chrome/browser/notifications/notification_ui_manager_desktop.cc
@@ -4,9 +4,9 @@ #include "chrome/browser/notifications/notification_ui_manager.h" +#include <memory> #include <utility> -#include "base/memory/scoped_ptr.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/notifications/message_center_notification_manager.h" #include "chrome/browser/notifications/message_center_settings_controller.h" @@ -19,7 +19,7 @@ if (!profile_manager) return nullptr; - scoped_ptr<message_center::NotifierSettingsProvider> settings_provider( + std::unique_ptr<message_center::NotifierSettingsProvider> settings_provider( new MessageCenterSettingsController( profile_manager->GetProfileAttributesStorage())); return new MessageCenterNotificationManager(
diff --git a/chrome/browser/notifications/notifier_state_tracker.cc b/chrome/browser/notifications/notifier_state_tracker.cc index 4b70c00..dcf9015e 100644 --- a/chrome/browser/notifications/notifier_state_tracker.cc +++ b/chrome/browser/notifications/notifier_state_tracker.cc
@@ -107,7 +107,7 @@ bool add_new_item = false; const char* pref_name = NULL; - scoped_ptr<base::StringValue> id; + std::unique_ptr<base::StringValue> id; switch (notifier_id.type) { case NotifierId::APPLICATION: pref_name = prefs::kMessageCenterDisabledExtensionIds; @@ -176,10 +176,10 @@ extensions::api::notifications::PermissionLevel permission = enabled ? extensions::api::notifications::PERMISSION_LEVEL_GRANTED : extensions::api::notifications::PERMISSION_LEVEL_DENIED; - scoped_ptr<base::ListValue> args(new base::ListValue()); + std::unique_ptr<base::ListValue> args(new base::ListValue()); args->Append(new base::StringValue( extensions::api::notifications::ToString(permission))); - scoped_ptr<extensions::Event> event(new extensions::Event( + std::unique_ptr<extensions::Event> event(new extensions::Event( extensions::events::NOTIFICATIONS_ON_PERMISSION_LEVEL_CHANGED, extensions::api::notifications::OnPermissionLevelChanged::kEventName, std::move(args)));
diff --git a/chrome/browser/notifications/platform_notification_service_browsertest.cc b/chrome/browser/notifications/platform_notification_service_browsertest.cc index c52b8e70..2258bba 100644 --- a/chrome/browser/notifications/platform_notification_service_browsertest.cc +++ b/chrome/browser/notifications/platform_notification_service_browsertest.cc
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> #include <string> #include <vector> #include "base/command_line.h" #include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" @@ -93,8 +93,8 @@ const base::FilePath server_root_; const std::string test_page_url_; - scoped_ptr<StubNotificationUIManager> ui_manager_; - scoped_ptr<net::EmbeddedTestServer> https_server_; + std::unique_ptr<StubNotificationUIManager> ui_manager_; + std::unique_ptr<net::EmbeddedTestServer> https_server_; }; // -----------------------------------------------------------------------------
diff --git a/chrome/browser/notifications/platform_notification_service_impl.cc b/chrome/browser/notifications/platform_notification_service_impl.cc index dc4cf99..7a5b8bb 100644 --- a/chrome/browser/notifications/platform_notification_service_impl.cc +++ b/chrome/browser/notifications/platform_notification_service_impl.cc
@@ -316,7 +316,7 @@ const GURL& origin, const content::PlatformNotificationData& notification_data, const content::NotificationResources& notification_resources, - scoped_ptr<content::DesktopNotificationDelegate> delegate, + std::unique_ptr<content::DesktopNotificationDelegate> delegate, base::Closure* cancel_callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI);
diff --git a/chrome/browser/notifications/platform_notification_service_impl.h b/chrome/browser/notifications/platform_notification_service_impl.h index 28bbbed2..b26aa2ab3 100644 --- a/chrome/browser/notifications/platform_notification_service_impl.h +++ b/chrome/browser/notifications/platform_notification_service_impl.h
@@ -6,14 +6,15 @@ #define CHROME_BROWSER_NOTIFICATIONS_PLATFORM_NOTIFICATION_SERVICE_IMPL_H_ #include <stdint.h> + #include <map> +#include <memory> #include <set> #include <string> #include <unordered_set> #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/strings/string16.h" #include "chrome/browser/notifications/notification.h" @@ -98,7 +99,7 @@ const GURL& origin, const content::PlatformNotificationData& notification_data, const content::NotificationResources& notification_resources, - scoped_ptr<content::DesktopNotificationDelegate> delegate, + std::unique_ptr<content::DesktopNotificationDelegate> delegate, base::Closure* cancel_callback) override; void DisplayPersistentNotification( content::BrowserContext* browser_context, @@ -146,7 +147,7 @@ // Platforms that display native notification interact with them through this // object. - scoped_ptr<NotificationUIManager> native_notification_ui_manager_; + std::unique_ptr<NotificationUIManager> native_notification_ui_manager_; // Weak reference. Ownership maintains with the test. NotificationUIManager* notification_ui_manager_for_tests_;
diff --git a/chrome/browser/notifications/platform_notification_service_unittest.cc b/chrome/browser/notifications/platform_notification_service_unittest.cc index 282ed67..d9bf4090b3 100644 --- a/chrome/browser/notifications/platform_notification_service_unittest.cc +++ b/chrome/browser/notifications/platform_notification_service_unittest.cc
@@ -7,6 +7,7 @@ #include <utility> #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/platform_thread.h" #include "base/time/time.h" @@ -114,7 +115,7 @@ service()->DisplayNotification(profile(), GURL("https://chrome.com/"), notification_data, NotificationResources(), - make_scoped_ptr(delegate), close_closure); + base::WrapUnique(delegate), close_closure); return delegate; } @@ -131,8 +132,8 @@ StubNotificationUIManager* ui_manager() const { return ui_manager_.get(); } private: - scoped_ptr<StubNotificationUIManager> ui_manager_; - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<StubNotificationUIManager> ui_manager_; + std::unique_ptr<TestingProfile> profile_; content::TestBrowserThreadBundle thread_bundle_; }; @@ -200,7 +201,7 @@ = new MockDesktopNotificationDelegate(); service()->DisplayNotification(profile(), GURL("https://chrome.com/"), notification_data, NotificationResources(), - make_scoped_ptr(delegate), nullptr); + base::WrapUnique(delegate), nullptr); ASSERT_EQ(1u, ui_manager()->GetNotificationCount());
diff --git a/chrome/browser/ntp_snippets/ntp_snippets_service_factory.cc b/chrome/browser/ntp_snippets/ntp_snippets_service_factory.cc index 1f2cb4a0..779cc2d5 100644 --- a/chrome/browser/ntp_snippets/ntp_snippets_service_factory.cc +++ b/chrome/browser/ntp_snippets/ntp_snippets_service_factory.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/ntp_snippets/ntp_snippets_service_factory.h" +#include "base/memory/ptr_util.h" #include "base/memory/singleton.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" @@ -73,7 +74,7 @@ return new ntp_snippets::NTPSnippetsService( profile->GetPrefs(), suggestions_service, task_runner, g_browser_process->GetApplicationLocale(), scheduler, - make_scoped_ptr(new ntp_snippets::NTPSnippetsFetcher( + base::WrapUnique(new ntp_snippets::NTPSnippetsFetcher( task_runner, request_context, chrome::GetChannel() == version_info::Channel::STABLE)), base::Bind(&safe_json::SafeJsonParser::Parse));
diff --git a/chrome/browser/ntp_snippets/ntp_snippets_service_factory.h b/chrome/browser/ntp_snippets/ntp_snippets_service_factory.h index 5a6bb54..a5ca837 100644 --- a/chrome/browser/ntp_snippets/ntp_snippets_service_factory.h +++ b/chrome/browser/ntp_snippets/ntp_snippets_service_factory.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_NTP_SNIPPETS_NTP_SNIPPETS_SERVICE_FACTORY_H_ #define CHROME_BROWSER_NTP_SNIPPETS_NTP_SNIPPETS_SERVICE_FACTORY_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" class Profile;
diff --git a/chrome/browser/page_load_metrics/observers/aborts_page_load_metrics_observer_unittest.cc b/chrome/browser/page_load_metrics/observers/aborts_page_load_metrics_observer_unittest.cc index 67959ce..812fb06 100644 --- a/chrome/browser/page_load_metrics/observers/aborts_page_load_metrics_observer_unittest.cc +++ b/chrome/browser/page_load_metrics/observers/aborts_page_load_metrics_observer_unittest.cc
@@ -3,13 +3,15 @@ // found in the LICENSE file. #include "chrome/browser/page_load_metrics/observers/aborts_page_load_metrics_observer.h" + +#include "base/memory/ptr_util.h" #include "chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.h" class AbortsPageLoadMetricsObserverTest : public page_load_metrics::PageLoadMetricsObserverTestHarness { protected: void RegisterObservers(page_load_metrics::PageLoadTracker* tracker) override { - tracker->AddObserver(make_scoped_ptr(new AbortsPageLoadMetricsObserver())); + tracker->AddObserver(base::WrapUnique(new AbortsPageLoadMetricsObserver())); } void SimulateTimingWithoutPaint() {
diff --git a/chrome/browser/page_load_metrics/observers/core_page_load_metrics_observer.cc b/chrome/browser/page_load_metrics/observers/core_page_load_metrics_observer.cc index af2778d..36b111a 100644 --- a/chrome/browser/page_load_metrics/observers/core_page_load_metrics_observer.cc +++ b/chrome/browser/page_load_metrics/observers/core_page_load_metrics_observer.cc
@@ -376,7 +376,7 @@ info)) { return; } - scoped_ptr<rappor::Sample> sample = + std::unique_ptr<rappor::Sample> sample = rappor_service->CreateSample(rappor::UMA_RAPPOR_TYPE); sample->SetStringField( "Domain", rappor::GetDomainAndRegistrySampleFromGURL(info.committed_url));
diff --git a/chrome/browser/page_load_metrics/observers/core_page_load_metrics_observer_unittest.cc b/chrome/browser/page_load_metrics/observers/core_page_load_metrics_observer_unittest.cc index fdcefd5..922fa56 100644 --- a/chrome/browser/page_load_metrics/observers/core_page_load_metrics_observer_unittest.cc +++ b/chrome/browser/page_load_metrics/observers/core_page_load_metrics_observer_unittest.cc
@@ -3,6 +3,8 @@ // found in the LICENSE file. #include "chrome/browser/page_load_metrics/observers/core_page_load_metrics_observer.h" + +#include "base/memory/ptr_util.h" #include "chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.h" #include "chrome/test/base/testing_browser_process.h" #include "components/rappor/rappor_utils.h" @@ -20,7 +22,7 @@ : public page_load_metrics::PageLoadMetricsObserverTestHarness { protected: void RegisterObservers(page_load_metrics::PageLoadTracker* tracker) override { - tracker->AddObserver(make_scoped_ptr(new CorePageLoadMetricsObserver())); + tracker->AddObserver(base::WrapUnique(new CorePageLoadMetricsObserver())); } void AssertNoHistogramsLogged() {
diff --git a/chrome/browser/page_load_metrics/observers/document_write_page_load_metrics_observer_unittest.cc b/chrome/browser/page_load_metrics/observers/document_write_page_load_metrics_observer_unittest.cc index 9c57d49..9f0a6279 100644 --- a/chrome/browser/page_load_metrics/observers/document_write_page_load_metrics_observer_unittest.cc +++ b/chrome/browser/page_load_metrics/observers/document_write_page_load_metrics_observer_unittest.cc
@@ -3,6 +3,8 @@ // found in the LICENSE file. #include "chrome/browser/page_load_metrics/observers/document_write_page_load_metrics_observer.h" + +#include "base/memory/ptr_util.h" #include "chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.h" #include "chrome/test/base/testing_browser_process.h" #include "third_party/WebKit/public/platform/WebLoadingBehaviorFlag.h" @@ -12,7 +14,7 @@ protected: void RegisterObservers(page_load_metrics::PageLoadTracker* tracker) override { tracker->AddObserver( - make_scoped_ptr(new DocumentWritePageLoadMetricsObserver())); + base::WrapUnique(new DocumentWritePageLoadMetricsObserver())); } void AssertNoHistogramsLogged() { histogram_tester().ExpectTotalCount(
diff --git a/chrome/browser/page_load_metrics/observers/from_gws_page_load_metrics_observer_unittest.cc b/chrome/browser/page_load_metrics/observers/from_gws_page_load_metrics_observer_unittest.cc index ae25b65..9fc0d336 100644 --- a/chrome/browser/page_load_metrics/observers/from_gws_page_load_metrics_observer_unittest.cc +++ b/chrome/browser/page_load_metrics/observers/from_gws_page_load_metrics_observer_unittest.cc
@@ -2,8 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/macros.h" #include "chrome/browser/page_load_metrics/observers/from_gws_page_load_metrics_observer.h" + +#include "base/macros.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.h" namespace { @@ -35,7 +37,7 @@ public: void RegisterObservers(page_load_metrics::PageLoadTracker* tracker) override { tracker->AddObserver( - make_scoped_ptr(new TestFromGWSPageLoadMetricsObserver(referrer_))); + base::WrapUnique(new TestFromGWSPageLoadMetricsObserver(referrer_))); } // Inject this referrer to FromGWS observers.
diff --git a/chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.cc b/chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.cc index 5de79a2..26a700d 100644 --- a/chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.cc +++ b/chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.cc
@@ -4,8 +4,10 @@ #include "chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.h" +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "components/page_load_metrics/common/page_load_metrics_messages.h" namespace page_load_metrics { @@ -84,10 +86,9 @@ ChromeRenderViewHostTestHarness::SetUp(); SetContents(CreateTestWebContents()); NavigateAndCommit(GURL("http://www.google.com")); - observer_ = - MetricsWebContentsObserver::CreateForWebContents( - web_contents(), - make_scoped_ptr(new TestPageLoadMetricsEmbedderInterface(this))); + observer_ = MetricsWebContentsObserver::CreateForWebContents( + web_contents(), + base::WrapUnique(new TestPageLoadMetricsEmbedderInterface(this))); web_contents()->WasShown(); }
diff --git a/chrome/browser/page_load_metrics/page_load_metrics_initialize.cc b/chrome/browser/page_load_metrics/page_load_metrics_initialize.cc index 95c1f04..58f6beb 100644 --- a/chrome/browser/page_load_metrics/page_load_metrics_initialize.cc +++ b/chrome/browser/page_load_metrics/page_load_metrics_initialize.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/page_load_metrics/page_load_metrics_initialize.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/page_load_metrics/observers/aborts_page_load_metrics_observer.h" #include "chrome/browser/page_load_metrics/observers/core_page_load_metrics_observer.h" #include "chrome/browser/page_load_metrics/observers/document_write_page_load_metrics_observer.h" @@ -20,7 +21,7 @@ void InitializePageLoadMetricsForWebContents( content::WebContents* web_contents) { page_load_metrics::MetricsWebContentsObserver::CreateForWebContents( - web_contents, make_scoped_ptr(new PageLoadMetricsEmbedder())); + web_contents, base::WrapUnique(new PageLoadMetricsEmbedder())); } PageLoadMetricsEmbedder::~PageLoadMetricsEmbedder() {} @@ -28,16 +29,16 @@ void PageLoadMetricsEmbedder::RegisterObservers( page_load_metrics::PageLoadTracker* tracker) { // These classes are owned by the metrics. - tracker->AddObserver(make_scoped_ptr(new AbortsPageLoadMetricsObserver())); - tracker->AddObserver(make_scoped_ptr(new CorePageLoadMetricsObserver())); - tracker->AddObserver(make_scoped_ptr(new FromGWSPageLoadMetricsObserver())); + tracker->AddObserver(base::WrapUnique(new AbortsPageLoadMetricsObserver())); + tracker->AddObserver(base::WrapUnique(new CorePageLoadMetricsObserver())); + tracker->AddObserver(base::WrapUnique(new FromGWSPageLoadMetricsObserver())); tracker->AddObserver( - make_scoped_ptr(new google_captcha_observer::GoogleCaptchaObserver())); + base::WrapUnique(new google_captcha_observer::GoogleCaptchaObserver())); // TODO(ricea): Remove this in April 2016 or before. crbug.com/348877 tracker->AddObserver( - make_scoped_ptr(new chrome::StaleWhileRevalidateMetricsObserver())); + base::WrapUnique(new chrome::StaleWhileRevalidateMetricsObserver())); tracker->AddObserver( - make_scoped_ptr(new DocumentWritePageLoadMetricsObserver())); + base::WrapUnique(new DocumentWritePageLoadMetricsObserver())); } bool PageLoadMetricsEmbedder::IsPrerendering(
diff --git a/chrome/browser/pepper_broker_infobar_delegate.cc b/chrome/browser/pepper_broker_infobar_delegate.cc index a8db641a..a607c38 100644 --- a/chrome/browser/pepper_broker_infobar_delegate.cc +++ b/chrome/browser/pepper_broker_infobar_delegate.cc
@@ -55,9 +55,9 @@ InfoBarService* infobar_service = InfoBarService::FromWebContents(web_contents); infobar_service->AddInfoBar(infobar_service->CreateConfirmInfoBar( - scoped_ptr<ConfirmInfoBarDelegate>(new PepperBrokerInfoBarDelegate( - url, plugin_path, content_settings, tab_content_settings, - callback)))); + std::unique_ptr<ConfirmInfoBarDelegate>( + new PepperBrokerInfoBarDelegate(url, plugin_path, content_settings, + tab_content_settings, callback)))); return; } @@ -103,7 +103,7 @@ content::WebPluginInfo plugin; bool success = plugin_service->GetPluginInfoByPath(plugin_path_, &plugin); DCHECK(success); - scoped_ptr<PluginMetadata> plugin_metadata( + std::unique_ptr<PluginMetadata> plugin_metadata( PluginFinder::GetInstance()->GetPluginMetadata(plugin)); return l10n_util::GetStringFUTF16( IDS_PEPPER_BROKER_MESSAGE, plugin_metadata->name(),
diff --git a/chrome/browser/pepper_flash_settings_manager.cc b/chrome/browser/pepper_flash_settings_manager.cc index 4f5dca1a..9cf779f 100644 --- a/chrome/browser/pepper_flash_settings_manager.cc +++ b/chrome/browser/pepper_flash_settings_manager.cc
@@ -187,7 +187,7 @@ // The channel is NULL until we have opened a connection to the broker // process. Used only on the I/O thread. - scoped_ptr<IPC::Channel> channel_; + std::unique_ptr<IPC::Channel> channel_; // Used only on the I/O thread. State state_;
diff --git a/chrome/browser/performance_monitor/performance_monitor.cc b/chrome/browser/performance_monitor/performance_monitor.cc index 8473997..6b648e9 100644 --- a/chrome/browser/performance_monitor/performance_monitor.cc +++ b/chrome/browser/performance_monitor/performance_monitor.cc
@@ -144,7 +144,7 @@ int current_update_sequence) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - scoped_ptr<std::vector<ProcessMetricsMetadata>> process_data_list( + std::unique_ptr<std::vector<ProcessMetricsMetadata>> process_data_list( new std::vector<ProcessMetricsMetadata>()); // Find all child processes (does not include renderers), which has to be @@ -176,7 +176,7 @@ } void PerformanceMonitor::MarkProcessesAsAliveOnUIThread( - scoped_ptr<std::vector<ProcessMetricsMetadata>> process_data_list, + std::unique_ptr<std::vector<ProcessMetricsMetadata>> process_data_list, int current_update_sequence) { DCHECK_CURRENTLY_ON(BrowserThread::UI); for (size_t i = 0; i < process_data_list->size(); ++i) {
diff --git a/chrome/browser/performance_monitor/performance_monitor.h b/chrome/browser/performance_monitor/performance_monitor.h index 89b5434..24c7c1e4 100644 --- a/chrome/browser/performance_monitor/performance_monitor.h +++ b/chrome/browser/performance_monitor/performance_monitor.h
@@ -6,10 +6,10 @@ #define CHROME_BROWSER_PERFORMANCE_MONITOR_PERFORMANCE_MONITOR_H_ #include <map> +#include <memory> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/process/process_handle.h" #include "base/timer/timer.h" #include "chrome/browser/performance_monitor/process_metrics_history.h" @@ -54,7 +54,7 @@ void MarkProcessAsAlive(const ProcessMetricsMetadata& process_data, int current_update_sequence); void MarkProcessesAsAliveOnUIThread( - scoped_ptr<std::vector<ProcessMetricsMetadata>> process_data_list, + std::unique_ptr<std::vector<ProcessMetricsMetadata>> process_data_list, int current_update_sequence); // Updates the ProcessMetrics map with the current list of processes and
diff --git a/chrome/browser/permissions/chooser_context_base.cc b/chrome/browser/permissions/chooser_context_base.cc index eddb03f..af7b37e 100644 --- a/chrome/browser/permissions/chooser_context_base.cc +++ b/chrome/browser/permissions/chooser_context_base.cc
@@ -6,6 +6,7 @@ #include <utility> +#include "base/memory/ptr_util.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "components/content_settings/core/browser/host_content_settings_map.h" @@ -36,20 +37,20 @@ ChooserContextBase::Object::~Object() = default; -std::vector<scoped_ptr<base::DictionaryValue>> +std::vector<std::unique_ptr<base::DictionaryValue>> ChooserContextBase::GetGrantedObjects(const GURL& requesting_origin, const GURL& embedding_origin) { DCHECK_EQ(requesting_origin, requesting_origin.GetOrigin()); DCHECK_EQ(embedding_origin, embedding_origin.GetOrigin()); - std::vector<scoped_ptr<base::DictionaryValue>> results; - scoped_ptr<base::DictionaryValue> setting = + std::vector<std::unique_ptr<base::DictionaryValue>> results; + std::unique_ptr<base::DictionaryValue> setting = GetWebsiteSetting(requesting_origin, embedding_origin); - scoped_ptr<base::Value> objects; + std::unique_ptr<base::Value> objects; if (!setting->Remove(kObjectListKey, &objects)) return results; - scoped_ptr<base::ListValue> object_list = + std::unique_ptr<base::ListValue> object_list = base::ListValue::From(std::move(objects)); if (!object_list) return results; @@ -57,10 +58,10 @@ for (base::ListValue::iterator it = object_list->begin(); it != object_list->end(); ++it) { // Steal ownership of |object| from |object_list|. - scoped_ptr<base::Value> object(*it); + std::unique_ptr<base::Value> object(*it); *it = nullptr; - scoped_ptr<base::DictionaryValue> object_dict = + std::unique_ptr<base::DictionaryValue> object_dict = base::DictionaryValue::From(std::move(object)); if (object_dict && IsValidObject(*object_dict)) results.push_back(std::move(object_dict)); @@ -68,20 +69,20 @@ return results; } -std::vector<scoped_ptr<ChooserContextBase::Object>> +std::vector<std::unique_ptr<ChooserContextBase::Object>> ChooserContextBase::GetAllGrantedObjects() { ContentSettingsForOneType content_settings; host_content_settings_map_->GetSettingsForOneType( data_content_settings_type_, std::string(), &content_settings); - std::vector<scoped_ptr<Object>> results; + std::vector<std::unique_ptr<Object>> results; for (const ContentSettingPatternSource& content_setting : content_settings) { GURL requesting_origin(content_setting.primary_pattern.ToString()); GURL embedding_origin(content_setting.secondary_pattern.ToString()); if (!requesting_origin.is_valid() || !embedding_origin.is_valid()) continue; - scoped_ptr<base::DictionaryValue> setting = + std::unique_ptr<base::DictionaryValue> setting = GetWebsiteSetting(requesting_origin, embedding_origin); base::ListValue* object_list; if (!setting->GetList(kObjectListKey, &object_list)) @@ -94,7 +95,7 @@ continue; } - results.push_back(make_scoped_ptr( + results.push_back(base::WrapUnique( new Object(requesting_origin, embedding_origin, object_dict, content_setting.source, content_setting.incognito))); } @@ -106,12 +107,12 @@ void ChooserContextBase::GrantObjectPermission( const GURL& requesting_origin, const GURL& embedding_origin, - scoped_ptr<base::DictionaryValue> object) { + std::unique_ptr<base::DictionaryValue> object) { DCHECK_EQ(requesting_origin, requesting_origin.GetOrigin()); DCHECK_EQ(embedding_origin, embedding_origin.GetOrigin()); DCHECK(object); DCHECK(IsValidObject(*object)); - scoped_ptr<base::DictionaryValue> setting = + std::unique_ptr<base::DictionaryValue> setting = GetWebsiteSetting(requesting_origin, embedding_origin); base::ListValue* object_list; if (!setting->GetList(kObjectListKey, &object_list)) { @@ -129,7 +130,7 @@ DCHECK_EQ(requesting_origin, requesting_origin.GetOrigin()); DCHECK_EQ(embedding_origin, embedding_origin.GetOrigin()); DCHECK(IsValidObject(object)); - scoped_ptr<base::DictionaryValue> setting = + std::unique_ptr<base::DictionaryValue> setting = GetWebsiteSetting(requesting_origin, embedding_origin); base::ListValue* object_list; if (!setting->GetList(kObjectListKey, &object_list)) @@ -138,10 +139,10 @@ SetWebsiteSetting(requesting_origin, embedding_origin, std::move(setting)); } -scoped_ptr<base::DictionaryValue> ChooserContextBase::GetWebsiteSetting( +std::unique_ptr<base::DictionaryValue> ChooserContextBase::GetWebsiteSetting( const GURL& requesting_origin, const GURL& embedding_origin) { - scoped_ptr<base::DictionaryValue> value = + std::unique_ptr<base::DictionaryValue> value = base::DictionaryValue::From(host_content_settings_map_->GetWebsiteSetting( requesting_origin, embedding_origin, data_content_settings_type_, std::string(), nullptr)); @@ -153,7 +154,7 @@ void ChooserContextBase::SetWebsiteSetting(const GURL& requesting_origin, const GURL& embedding_origin, - scoped_ptr<base::Value> value) { + std::unique_ptr<base::Value> value) { host_content_settings_map_->SetWebsiteSettingDefaultScope( requesting_origin, embedding_origin, data_content_settings_type_, std::string(), value.release());
diff --git a/chrome/browser/permissions/chooser_context_base.h b/chrome/browser/permissions/chooser_context_base.h index 1fdb222..5bf4460 100644 --- a/chrome/browser/permissions/chooser_context_base.h +++ b/chrome/browser/permissions/chooser_context_base.h
@@ -5,10 +5,10 @@ #ifndef CHROME_BROWSER_PERMISSIONS_CHOOSER_CONTEXT_BASE_H_ #define CHROME_BROWSER_PERMISSIONS_CHOOSER_CONTEXT_BASE_H_ +#include <memory> #include <string> #include <vector> -#include "base/memory/scoped_ptr.h" #include "base/values.h" #include "components/content_settings/core/common/content_settings_types.h" #include "components/keyed_service/core/keyed_service.h" @@ -47,7 +47,7 @@ // // This method may be extended by a subclass to return objects not stored in // |host_content_settings_map_|. - virtual std::vector<scoped_ptr<base::DictionaryValue>> GetGrantedObjects( + virtual std::vector<std::unique_ptr<base::DictionaryValue>> GetGrantedObjects( const GURL& requesting_origin, const GURL& embedding_origin); @@ -56,13 +56,13 @@ // // This method may be extended by a subclass to return objects not stored in // |host_content_settings_map_|. - virtual std::vector<scoped_ptr<Object>> GetAllGrantedObjects(); + virtual std::vector<std::unique_ptr<Object>> GetAllGrantedObjects(); // Grants |requesting_origin| access to |object| when embedded within // |embedding_origin| by writing it into |host_content_settings_map_|. void GrantObjectPermission(const GURL& requesting_origin, const GURL& embedding_origin, - scoped_ptr<base::DictionaryValue> object); + std::unique_ptr<base::DictionaryValue> object); // Revokes |requesting_origin|'s permission to access |object| when embedded // within |embedding_origin|. @@ -79,12 +79,12 @@ virtual bool IsValidObject(const base::DictionaryValue& object) = 0; private: - scoped_ptr<base::DictionaryValue> GetWebsiteSetting( + std::unique_ptr<base::DictionaryValue> GetWebsiteSetting( const GURL& requesting_origin, const GURL& embedding_origin); void SetWebsiteSetting(const GURL& requesting_origin, const GURL& embedding_origin, - scoped_ptr<base::Value> value); + std::unique_ptr<base::Value> value); HostContentSettingsMap* const host_content_settings_map_; const ContentSettingsType data_content_settings_type_;
diff --git a/chrome/browser/permissions/chooser_context_base_unittest.cc b/chrome/browser/permissions/chooser_context_base_unittest.cc index 50f7e95..0385f82 100644 --- a/chrome/browser/permissions/chooser_context_base_unittest.cc +++ b/chrome/browser/permissions/chooser_context_base_unittest.cc
@@ -57,7 +57,7 @@ context_.GrantObjectPermission(origin1_, origin1_, object1_.CreateDeepCopy()); context_.GrantObjectPermission(origin1_, origin1_, object2_.CreateDeepCopy()); - std::vector<scoped_ptr<base::DictionaryValue>> objects = + std::vector<std::unique_ptr<base::DictionaryValue>> objects = context_.GetGrantedObjects(origin1_, origin1_); EXPECT_EQ(2u, objects.size()); EXPECT_TRUE(object1_.Equals(objects[0].get())); @@ -76,7 +76,7 @@ context_.GrantObjectPermission(origin1_, origin1_, object1_.CreateDeepCopy()); context_.GrantObjectPermission(origin1_, origin1_, object1_.CreateDeepCopy()); - std::vector<scoped_ptr<base::DictionaryValue>> objects = + std::vector<std::unique_ptr<base::DictionaryValue>> objects = context_.GetGrantedObjects(origin1_, origin1_); EXPECT_EQ(1u, objects.size()); EXPECT_TRUE(object1_.Equals(objects[0].get())); @@ -89,7 +89,7 @@ TEST_F(ChooserContextBaseTest, GrantObjectPermissionEmbedded) { context_.GrantObjectPermission(origin1_, origin2_, object1_.CreateDeepCopy()); - std::vector<scoped_ptr<base::DictionaryValue>> objects = + std::vector<std::unique_ptr<base::DictionaryValue>> objects = context_.GetGrantedObjects(origin1_, origin2_); EXPECT_EQ(1u, objects.size()); EXPECT_TRUE(object1_.Equals(objects[0].get())); @@ -107,7 +107,7 @@ context_.GrantObjectPermission(origin1_, origin1_, object1_.CreateDeepCopy()); context_.GrantObjectPermission(origin2_, origin2_, object2_.CreateDeepCopy()); - std::vector<scoped_ptr<ChooserContextBase::Object>> objects = + std::vector<std::unique_ptr<ChooserContextBase::Object>> objects = context_.GetAllGrantedObjects(); EXPECT_EQ(2u, objects.size()); bool found_one = false;
diff --git a/chrome/browser/permissions/permission_context_base.cc b/chrome/browser/permissions/permission_context_base.cc index 715a7b8..74691a4 100644 --- a/chrome/browser/permissions/permission_context_base.cc +++ b/chrome/browser/permissions/permission_context_base.cc
@@ -174,7 +174,7 @@ // prevent crashes. See crbug.com/457091. if (!bubble_manager) return; - scoped_ptr<PermissionBubbleRequest> request_ptr( + std::unique_ptr<PermissionBubbleRequest> request_ptr( new PermissionBubbleRequestImpl( requesting_origin, permission_type_, base::Bind(&PermissionContextBase::PermissionDecided,
diff --git a/chrome/browser/permissions/permission_context_base.h b/chrome/browser/permissions/permission_context_base.h index 89ff58c..e7257edd 100644 --- a/chrome/browser/permissions/permission_context_base.h +++ b/chrome/browser/permissions/permission_context_base.h
@@ -5,10 +5,11 @@ #ifndef CHROME_BROWSER_PERMISSIONS_PERMISSION_CONTEXT_BASE_H_ #define CHROME_BROWSER_PERMISSIONS_PERMISSION_CONTEXT_BASE_H_ +#include <memory> + #include "base/callback.h" #include "base/containers/scoped_ptr_hash_map.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "build/build_config.h" #include "chrome/browser/ui/website_settings/permission_bubble_request.h" @@ -161,9 +162,9 @@ const content::PermissionType permission_type_; const ContentSettingsType content_settings_type_; #if defined(OS_ANDROID) - scoped_ptr<PermissionQueueController> permission_queue_controller_; + std::unique_ptr<PermissionQueueController> permission_queue_controller_; #endif - base::ScopedPtrHashMap<std::string, scoped_ptr<PermissionBubbleRequest>> + base::ScopedPtrHashMap<std::string, std::unique_ptr<PermissionBubbleRequest>> pending_bubbles_; // Must be the last member, to ensure that it will be
diff --git a/chrome/browser/permissions/permission_context_base_unittest.cc b/chrome/browser/permissions/permission_context_base_unittest.cc index 8c052ba..87a84bc 100644 --- a/chrome/browser/permissions/permission_context_base_unittest.cc +++ b/chrome/browser/permissions/permission_context_base_unittest.cc
@@ -101,7 +101,7 @@ private: std::vector<ContentSetting> decisions_; bool tab_context_updated_; - scoped_ptr<base::FieldTrialList> field_trial_list_; + std::unique_ptr<base::FieldTrialList> field_trial_list_; }; class PermissionContextBaseTests : public ChromeRenderViewHostTestHarness {
diff --git a/chrome/browser/permissions/permission_manager.h b/chrome/browser/permissions/permission_manager.h index bae5ed1..b160fa26 100644 --- a/chrome/browser/permissions/permission_manager.h +++ b/chrome/browser/permissions/permission_manager.h
@@ -110,7 +110,7 @@ SubscriptionsMap subscriptions_; std::unordered_map<content::PermissionType, - scoped_ptr<PermissionContextBase>, + std::unique_ptr<PermissionContextBase>, PermissionTypeHash> permission_contexts_;
diff --git a/chrome/browser/permissions/permission_uma_util.cc b/chrome/browser/permissions/permission_uma_util.cc index b27935e..1195256 100644 --- a/chrome/browser/permissions/permission_uma_util.cc +++ b/chrome/browser/permissions/permission_uma_util.cc
@@ -158,7 +158,7 @@ if (!rappor_service || permission_str.empty()) return; - scoped_ptr<rappor::Sample> sample = + std::unique_ptr<rappor::Sample> sample = rappor_service->CreateSample(rappor::SAFEBROWSING_RAPPOR_TYPE); sample->SetStringField("Scheme", requesting_origin.scheme()); sample->SetStringField("Host", requesting_origin.host());
diff --git a/chrome/browser/permissions/permission_update_infobar_delegate_android.cc b/chrome/browser/permissions/permission_update_infobar_delegate_android.cc index 4e6d6c6..453bc8c 100644 --- a/chrome/browser/permissions/permission_update_infobar_delegate_android.cc +++ b/chrome/browser/permissions/permission_update_infobar_delegate_android.cc
@@ -4,9 +4,10 @@ #include "chrome/browser/permissions/permission_update_infobar_delegate_android.h" +#include <memory> + #include "base/android/jni_array.h" #include "base/callback_helpers.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/android/preferences/pref_service_bridge.h" #include "chrome/browser/infobars/infobar_service.h" #include "chrome/grit/chromium_strings.h" @@ -79,8 +80,9 @@ } return infobar_service->AddInfoBar(infobar_service->CreateConfirmInfoBar( - scoped_ptr<ConfirmInfoBarDelegate>(new PermissionUpdateInfoBarDelegate( - web_contents, android_permissions, permission_msg_id, callback)))); + std::unique_ptr<ConfirmInfoBarDelegate>( + new PermissionUpdateInfoBarDelegate(web_contents, android_permissions, + permission_msg_id, callback)))); } // static
diff --git a/chrome/browser/platform_util_unittest.cc b/chrome/browser/platform_util_unittest.cc index 1fd8eb8a..2b48709 100644 --- a/chrome/browser/platform_util_unittest.cc +++ b/chrome/browser/platform_util_unittest.cc
@@ -4,12 +4,13 @@ #include "chrome/browser/platform_util.h" +#include <memory> + #include "base/bind.h" #include "base/callback.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "build/build_config.h" #include "chrome/browser/platform_util_internal.h" @@ -94,7 +95,7 @@ " }" "}"; JSONStringValueDeserializer json_string_deserializer(json_manifest); - scoped_ptr<base::Value> manifest = + std::unique_ptr<base::Value> manifest = json_string_deserializer.Deserialize(&error_code, &error); base::DictionaryValue* manifest_dictionary; @@ -122,7 +123,7 @@ } private: - scoped_ptr<content::ContentBrowserClient> content_browser_client_; + std::unique_ptr<content::ContentBrowserClient> content_browser_client_; content::ContentBrowserClient* old_content_browser_client_ = nullptr; }; @@ -190,7 +191,7 @@ base::ScopedTempDir directory_; private: - scoped_ptr<base::RunLoop> run_loop_; + std::unique_ptr<base::RunLoop> run_loop_; static void OnOpenOperationDone(const base::Closure& closure, OpenOperationResult* store_result,
diff --git a/chrome/browser/plugins/chrome_content_browser_client_plugins_part.cc b/chrome/browser/plugins/chrome_content_browser_client_plugins_part.cc index 8d49cba7a..d0caa3f6 100644 --- a/chrome/browser/plugins/chrome_content_browser_client_plugins_part.cc +++ b/chrome/browser/plugins/chrome_content_browser_client_plugins_part.cc
@@ -147,7 +147,7 @@ void ChromeContentBrowserClientPluginsPart::DidCreatePpapiPlugin( content::BrowserPpapiHost* browser_host) { browser_host->GetPpapiHost()->AddHostFactoryFilter( - scoped_ptr<ppapi::host::HostFactory>( + std::unique_ptr<ppapi::host::HostFactory>( new ChromeBrowserPepperHostFactory(browser_host))); }
diff --git a/chrome/browser/plugins/plugin_finder.cc b/chrome/browser/plugins/plugin_finder.cc index 23fe235..2279de0 100644 --- a/chrome/browser/plugins/plugin_finder.cc +++ b/chrome/browser/plugins/plugin_finder.cc
@@ -175,7 +175,7 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // Load the built-in plugin list first. If we have a newer version stored // locally or download one, we will replace this one with it. - scoped_ptr<base::DictionaryValue> plugin_list(LoadBuiltInPluginList()); + std::unique_ptr<base::DictionaryValue> plugin_list(LoadBuiltInPluginList()); // Gracefully handle the case where we couldn't parse the built-in plugin list // for some reason (https://crbug.com/388560). TODO(bauerb): Change back to a @@ -193,7 +193,7 @@ IDR_PLUGIN_DB_JSON)); std::string error_str; int error_code = base::JSONReader::JSON_NO_ERROR; - scoped_ptr<base::Value> value = base::JSONReader::ReadAndReturnError( + std::unique_ptr<base::Value> value = base::JSONReader::ReadAndReturnError( json_resource, base::JSON_PARSE_RFC, &error_code, &error_str); if (!value) { DLOG(ERROR) << error_str; @@ -257,7 +257,7 @@ const std::string& mime_type, const std::string& language, PluginInstaller** installer, - scoped_ptr<PluginMetadata>* plugin_metadata) { + std::unique_ptr<PluginMetadata>* plugin_metadata) { if (g_browser_process->local_state()->GetBoolean(prefs::kDisablePluginFinder)) return false; @@ -281,7 +281,7 @@ bool PluginFinder::FindPluginWithIdentifier( const std::string& identifier, PluginInstaller** installer, - scoped_ptr<PluginMetadata>* plugin_metadata) { + std::unique_ptr<PluginMetadata>* plugin_metadata) { base::AutoLock lock(mutex_); PluginMap::const_iterator metadata_it = identifier_plugin_.find(identifier); if (metadata_it == identifier_plugin_.end()) @@ -328,7 +328,7 @@ } } -scoped_ptr<PluginMetadata> PluginFinder::GetPluginMetadata( +std::unique_ptr<PluginMetadata> PluginFinder::GetPluginMetadata( const content::WebPluginInfo& plugin) { base::AutoLock lock(mutex_); for (PluginMap::const_iterator it = identifier_plugin_.begin();
diff --git a/chrome/browser/plugins/plugin_finder.h b/chrome/browser/plugins/plugin_finder.h index 77be58f6..07c9695 100644 --- a/chrome/browser/plugins/plugin_finder.h +++ b/chrome/browser/plugins/plugin_finder.h
@@ -6,12 +6,12 @@ #define CHROME_BROWSER_PLUGINS_PLUGIN_FINDER_H_ #include <map> +#include <memory> #include <string> #include "base/callback.h" #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/strings/string16.h" #include "base/synchronization/lock.h" @@ -51,18 +51,19 @@ bool FindPlugin(const std::string& mime_type, const std::string& language, PluginInstaller** installer, - scoped_ptr<PluginMetadata>* plugin_metadata); + std::unique_ptr<PluginMetadata>* plugin_metadata); // Finds the plugin with the given identifier. If found, sets |installer| // to the corresponding PluginInstaller and |plugin_metadata| to a copy // of the corresponding PluginMetadata. |installer| may be NULL. - bool FindPluginWithIdentifier(const std::string& identifier, - PluginInstaller** installer, - scoped_ptr<PluginMetadata>* plugin_metadata); + bool FindPluginWithIdentifier( + const std::string& identifier, + PluginInstaller** installer, + std::unique_ptr<PluginMetadata>* plugin_metadata); #endif // Gets plugin metadata using |plugin|. - scoped_ptr<PluginMetadata> GetPluginMetadata( + std::unique_ptr<PluginMetadata> GetPluginMetadata( const content::WebPluginInfo& plugin); private:
diff --git a/chrome/browser/plugins/plugin_finder_unittest.cc b/chrome/browser/plugins/plugin_finder_unittest.cc index 904d176..0d6a711 100644 --- a/chrome/browser/plugins/plugin_finder_unittest.cc +++ b/chrome/browser/plugins/plugin_finder_unittest.cc
@@ -12,10 +12,10 @@ using base::ListValue; TEST(PluginFinderTest, JsonSyntax) { - scoped_ptr<base::DictionaryValue> plugin_list( - PluginFinder::LoadBuiltInPluginList()); + std::unique_ptr<base::DictionaryValue> plugin_list( + PluginFinder::LoadBuiltInPluginList()); ASSERT_TRUE(plugin_list.get()); - scoped_ptr<base::Value> version; + std::unique_ptr<base::Value> version; ASSERT_TRUE(plugin_list->Remove("x-version", &version)); EXPECT_EQ(base::Value::TYPE_INTEGER, version->GetType());
diff --git a/chrome/browser/plugins/plugin_info_message_filter.cc b/chrome/browser/plugins/plugin_info_message_filter.cc index 789082a0..6f8879f 100644 --- a/chrome/browser/plugins/plugin_info_message_filter.cc +++ b/chrome/browser/plugins/plugin_info_message_filter.cc
@@ -5,10 +5,11 @@ #include "chrome/browser/plugins/plugin_info_message_filter.h" #include <stddef.h> + +#include <memory> #include <utility> #include "base/bind.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/histogram.h" #include "base/strings/utf_string_conversions.h" #include "base/thread_task_runner_handle.h" @@ -252,7 +253,7 @@ const std::vector<WebPluginInfo>& plugins) { ChromeViewHostMsg_GetPluginInfo_Output output; // This also fills in |actual_mime_type|. - scoped_ptr<PluginMetadata> plugin_metadata; + std::unique_ptr<PluginMetadata> plugin_metadata; if (context_.FindEnabledPlugin(params.render_frame_id, params.url, params.top_origin_url, params.mime_type, &output.status, &output.plugin, @@ -416,7 +417,7 @@ ChromeViewHostMsg_GetPluginInfo_Status* status, WebPluginInfo* plugin, std::string* actual_mime_type, - scoped_ptr<PluginMetadata>* plugin_metadata) const { + std::unique_ptr<PluginMetadata>* plugin_metadata) const { *status = ChromeViewHostMsg_GetPluginInfo_Status::kAllowed; bool allow_wildcard = true; @@ -467,7 +468,7 @@ ContentSetting* setting, bool* uses_default_content_setting, bool* is_managed) const { - scoped_ptr<base::Value> value; + std::unique_ptr<base::Value> value; content_settings::SettingInfo info; bool uses_plugin_specific_setting = false; if (ShouldUseJavaScriptSettingForPlugin(plugin)) { @@ -479,21 +480,15 @@ &info); } else { content_settings::SettingInfo specific_info; - scoped_ptr<base::Value> specific_setting = + std::unique_ptr<base::Value> specific_setting = host_content_settings_map_->GetWebsiteSetting( - policy_url, - plugin_url, - CONTENT_SETTINGS_TYPE_PLUGINS, - resource, + policy_url, plugin_url, CONTENT_SETTINGS_TYPE_PLUGINS, resource, &specific_info); content_settings::SettingInfo general_info; - scoped_ptr<base::Value> general_setting = + std::unique_ptr<base::Value> general_setting = host_content_settings_map_->GetWebsiteSetting( - policy_url, - plugin_url, - CONTENT_SETTINGS_TYPE_PLUGINS, - std::string(), - &general_info); + policy_url, plugin_url, CONTENT_SETTINGS_TYPE_PLUGINS, + std::string(), &general_info); // If there is a plugin-specific setting, we use it, unless the general // setting was set by policy, in which case it takes precedence.
diff --git a/chrome/browser/plugins/plugin_info_message_filter.h b/chrome/browser/plugins/plugin_info_message_filter.h index 4105283..ece5308 100644 --- a/chrome/browser/plugins/plugin_info_message_filter.h +++ b/chrome/browser/plugins/plugin_info_message_filter.h
@@ -52,14 +52,15 @@ const content::WebPluginInfo& plugin, const PluginMetadata* plugin_metadata, ChromeViewHostMsg_GetPluginInfo_Status* status) const; - bool FindEnabledPlugin(int render_frame_id, - const GURL& url, - const GURL& top_origin_url, - const std::string& mime_type, - ChromeViewHostMsg_GetPluginInfo_Status* status, - content::WebPluginInfo* plugin, - std::string* actual_mime_type, - scoped_ptr<PluginMetadata>* plugin_metadata) const; + bool FindEnabledPlugin( + int render_frame_id, + const GURL& url, + const GURL& top_origin_url, + const std::string& mime_type, + ChromeViewHostMsg_GetPluginInfo_Status* status, + content::WebPluginInfo* plugin, + std::string* actual_mime_type, + std::unique_ptr<PluginMetadata>* plugin_metadata) const; void GetPluginContentSetting(const content::WebPluginInfo& plugin, const GURL& policy_url, const GURL& plugin_url,
diff --git a/chrome/browser/plugins/plugin_infobar_delegates.cc b/chrome/browser/plugins/plugin_infobar_delegates.cc index 09df300..4b8c0a3 100644 --- a/chrome/browser/plugins/plugin_infobar_delegates.cc +++ b/chrome/browser/plugins/plugin_infobar_delegates.cc
@@ -49,12 +49,12 @@ void OutdatedPluginInfoBarDelegate::Create( InfoBarService* infobar_service, PluginInstaller* installer, - scoped_ptr<PluginMetadata> plugin_metadata) { + std::unique_ptr<PluginMetadata> plugin_metadata) { // Copy the name out of |plugin_metadata| now, since the Pass() call below // will make it impossible to get at. base::string16 name(plugin_metadata->name()); infobar_service->AddInfoBar(infobar_service->CreateConfirmInfoBar( - scoped_ptr<ConfirmInfoBarDelegate>(new OutdatedPluginInfoBarDelegate( + std::unique_ptr<ConfirmInfoBarDelegate>(new OutdatedPluginInfoBarDelegate( installer, std::move(plugin_metadata), l10n_util::GetStringFUTF16( (installer->state() == PluginInstaller::INSTALLER_STATE_IDLE) @@ -65,7 +65,7 @@ OutdatedPluginInfoBarDelegate::OutdatedPluginInfoBarDelegate( PluginInstaller* installer, - scoped_ptr<PluginMetadata> plugin_metadata, + std::unique_ptr<PluginMetadata> plugin_metadata, const base::string16& message) : ConfirmInfoBarDelegate(), WeakPluginInstallerObserver(installer), @@ -200,14 +200,14 @@ void OutdatedPluginInfoBarDelegate::Replace( infobars::InfoBar* infobar, PluginInstaller* installer, - scoped_ptr<PluginMetadata> plugin_metadata, + std::unique_ptr<PluginMetadata> plugin_metadata, const base::string16& message) { DCHECK(infobar->owner()); infobar->owner()->ReplaceInfoBar( - infobar, - infobar->owner()->CreateConfirmInfoBar( - scoped_ptr<ConfirmInfoBarDelegate>(new OutdatedPluginInfoBarDelegate( - installer, std::move(plugin_metadata), message)))); + infobar, infobar->owner()->CreateConfirmInfoBar( + std::unique_ptr<ConfirmInfoBarDelegate>( + new OutdatedPluginInfoBarDelegate( + installer, std::move(plugin_metadata), message)))); } #endif // defined(ENABLE_PLUGIN_INSTALLATION)
diff --git a/chrome/browser/plugins/plugin_infobar_delegates.h b/chrome/browser/plugins/plugin_infobar_delegates.h index a5cedd8..7bad0c6 100644 --- a/chrome/browser/plugins/plugin_infobar_delegates.h +++ b/chrome/browser/plugins/plugin_infobar_delegates.h
@@ -32,18 +32,18 @@ // |infobar_service|. static void Create(InfoBarService* infobar_service, PluginInstaller* installer, - scoped_ptr<PluginMetadata> metadata); + std::unique_ptr<PluginMetadata> metadata); // Replaces |infobar|, which must currently be owned, with an infobar asking // the user to update a particular plugin. static void Replace(infobars::InfoBar* infobar, PluginInstaller* installer, - scoped_ptr<PluginMetadata> plugin_metadata, + std::unique_ptr<PluginMetadata> plugin_metadata, const base::string16& message); private: OutdatedPluginInfoBarDelegate(PluginInstaller* installer, - scoped_ptr<PluginMetadata> metadata, + std::unique_ptr<PluginMetadata> metadata, const base::string16& message); ~OutdatedPluginInfoBarDelegate() override; @@ -73,7 +73,7 @@ std::string identifier_; - scoped_ptr<PluginMetadata> plugin_metadata_; + std::unique_ptr<PluginMetadata> plugin_metadata_; base::string16 message_;
diff --git a/chrome/browser/plugins/plugin_installer.cc b/chrome/browser/plugins/plugin_installer.cc index 3c6204b..837be684 100644 --- a/chrome/browser/plugins/plugin_installer.cc +++ b/chrome/browser/plugins/plugin_installer.cc
@@ -103,7 +103,7 @@ DCHECK_EQ(INSTALLER_STATE_IDLE, state_); state_ = INSTALLER_STATE_DOWNLOADING; FOR_EACH_OBSERVER(PluginInstallerObserver, observers_, DownloadStarted()); - scoped_ptr<content::DownloadUrlParameters> download_parameters( + std::unique_ptr<content::DownloadUrlParameters> download_parameters( content::DownloadUrlParameters::FromWebContents(web_contents, plugin_url)); download_parameters->set_callback(
diff --git a/chrome/browser/plugins/plugin_installer_unittest.cc b/chrome/browser/plugins/plugin_installer_unittest.cc index 6938e24..48e2d829 100644 --- a/chrome/browser/plugins/plugin_installer_unittest.cc +++ b/chrome/browser/plugins/plugin_installer_unittest.cc
@@ -4,7 +4,8 @@ #include "chrome/browser/plugins/plugin_installer.h" -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "base/run_loop.h" #include "chrome/browser/plugins/plugin_installer_observer.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" @@ -26,10 +27,10 @@ PluginInstaller* installer() { return installer_.get(); } - scoped_ptr<content::MockDownloadItem> CreateMockDownloadItem(); + std::unique_ptr<content::MockDownloadItem> CreateMockDownloadItem(); private: - scoped_ptr<PluginInstaller> installer_; + std::unique_ptr<PluginInstaller> installer_; }; PluginInstallerTest::PluginInstallerTest() { @@ -45,9 +46,9 @@ content::RenderViewHostTestHarness::TearDown(); } -scoped_ptr<content::MockDownloadItem> +std::unique_ptr<content::MockDownloadItem> PluginInstallerTest::CreateMockDownloadItem() { - scoped_ptr<content::MockDownloadItem> mock_download_item( + std::unique_ptr<content::MockDownloadItem> mock_download_item( new testing::StrictMock<content::MockDownloadItem>()); ON_CALL(*mock_download_item, GetState()) .WillByDefault(testing::Return(content::DownloadItem::IN_PROGRESS)); @@ -101,7 +102,8 @@ TEST_F(PluginInstallerTest, StartInstalling_SuccessfulDownload) { content::MockDownloadManager mock_download_manager; base::RunLoop run_loop; - scoped_ptr<content::MockDownloadItem> download_item(CreateMockDownloadItem()); + std::unique_ptr<content::MockDownloadItem> download_item( + CreateMockDownloadItem()); EXPECT_CALL(mock_download_manager, DownloadUrlMock(testing::Property( @@ -131,7 +133,8 @@ TEST_F(PluginInstallerTest, StartInstalling_FailedStart) { content::MockDownloadManager mock_download_manager; base::RunLoop run_loop; - scoped_ptr<content::MockDownloadItem> download_item(CreateMockDownloadItem()); + std::unique_ptr<content::MockDownloadItem> download_item( + CreateMockDownloadItem()); EXPECT_CALL(mock_download_manager, DownloadUrlMock(testing::Property( @@ -158,7 +161,8 @@ TEST_F(PluginInstallerTest, StartInstalling_Interrupted) { content::MockDownloadManager mock_download_manager; base::RunLoop run_loop; - scoped_ptr<content::MockDownloadItem> download_item(CreateMockDownloadItem()); + std::unique_ptr<content::MockDownloadItem> download_item( + CreateMockDownloadItem()); EXPECT_CALL(mock_download_manager, DownloadUrlMock(testing::Property(
diff --git a/chrome/browser/plugins/plugin_metadata.cc b/chrome/browser/plugins/plugin_metadata.cc index 0c42dde..256a86c6 100644 --- a/chrome/browser/plugins/plugin_metadata.cc +++ b/chrome/browser/plugins/plugin_metadata.cc
@@ -9,6 +9,7 @@ #include <algorithm> #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/strings/pattern.h" #include "base/strings/string_util.h" #include "content/public/common/webplugininfo.h" @@ -126,7 +127,7 @@ return lhs.CompareTo(rhs) > 0; } -scoped_ptr<PluginMetadata> PluginMetadata::Clone() const { +std::unique_ptr<PluginMetadata> PluginMetadata::Clone() const { PluginMetadata* copy = new PluginMetadata(identifier_, name_, url_for_display_, @@ -135,5 +136,5 @@ group_name_matcher_, language_); copy->versions_ = versions_; - return make_scoped_ptr(copy); + return base::WrapUnique(copy); }
diff --git a/chrome/browser/plugins/plugin_metadata.h b/chrome/browser/plugins/plugin_metadata.h index 726853e..d54afd07f 100644 --- a/chrome/browser/plugins/plugin_metadata.h +++ b/chrome/browser/plugins/plugin_metadata.h
@@ -6,9 +6,9 @@ #define CHROME_BROWSER_PLUGINS_PLUGIN_METADATA_H_ #include <map> +#include <memory> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "base/version.h" #include "url/gurl.h" @@ -87,7 +87,7 @@ // considered out-of-date, etc.) SecurityStatus GetSecurityStatus(const content::WebPluginInfo& plugin) const; - scoped_ptr<PluginMetadata> Clone() const; + std::unique_ptr<PluginMetadata> Clone() const; private: struct VersionComparator {
diff --git a/chrome/browser/plugins/plugin_observer.cc b/chrome/browser/plugins/plugin_observer.cc index e3846d1..605ca81f 100644 --- a/chrome/browser/plugins/plugin_observer.cc +++ b/chrome/browser/plugins/plugin_observer.cc
@@ -64,7 +64,7 @@ public: ConfirmInstallDialogDelegate(content::WebContents* web_contents, PluginInstaller* installer, - scoped_ptr<PluginMetadata> plugin_metadata); + std::unique_ptr<PluginMetadata> plugin_metadata); // TabModalConfirmDialogDelegate methods: base::string16 GetTitle() override; @@ -79,13 +79,13 @@ private: content::WebContents* web_contents_; - scoped_ptr<PluginMetadata> plugin_metadata_; + std::unique_ptr<PluginMetadata> plugin_metadata_; }; ConfirmInstallDialogDelegate::ConfirmInstallDialogDelegate( content::WebContents* web_contents, PluginInstaller* installer, - scoped_ptr<PluginMetadata> plugin_metadata) + std::unique_ptr<PluginMetadata> plugin_metadata) : TabModalConfirmDialogDelegate(web_contents), WeakPluginInstallerObserver(installer), web_contents_(web_contents), @@ -153,8 +153,8 @@ InfoBarService* infobar_service, content::NavigationController* controller, const base::string16& message) { - infobar_service->AddInfoBar( - infobar_service->CreateConfirmInfoBar(scoped_ptr<ConfirmInfoBarDelegate>( + infobar_service->AddInfoBar(infobar_service->CreateConfirmInfoBar( + std::unique_ptr<ConfirmInfoBarDelegate>( new ReloadPluginInfoBarDelegate(controller, message)))); } @@ -342,7 +342,7 @@ PluginFinder* finder = PluginFinder::GetInstance(); // Find plugin to update. PluginInstaller* installer = NULL; - scoped_ptr<PluginMetadata> plugin; + std::unique_ptr<PluginMetadata> plugin; if (finder->FindPluginWithIdentifier(identifier, &installer, &plugin)) { plugin_placeholders_[placeholder_id] = new PluginPlaceholderHost( this, placeholder_id, plugin->name(), installer);
diff --git a/chrome/browser/plugins/plugin_observer.h b/chrome/browser/plugins/plugin_observer.h index dfe8ad0..172b06d 100644 --- a/chrome/browser/plugins/plugin_observer.h +++ b/chrome/browser/plugins/plugin_observer.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_PLUGINS_PLUGIN_OBSERVER_H_ #define CHROME_BROWSER_PLUGINS_PLUGIN_OBSERVER_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h"
diff --git a/chrome/browser/plugins/plugin_power_saver_browsertest.cc b/chrome/browser/plugins/plugin_power_saver_browsertest.cc index 4ab99ea..b517e54 100644 --- a/chrome/browser/plugins/plugin_power_saver_browsertest.cc +++ b/chrome/browser/plugins/plugin_power_saver_browsertest.cc
@@ -147,10 +147,10 @@ EXPECT_TRUE(PluginLoaded(contents, element_id)); } -scoped_ptr<net::test_server::HttpResponse> RespondWithHTML( +std::unique_ptr<net::test_server::HttpResponse> RespondWithHTML( const std::string& html, const net::test_server::HttpRequest& request) { - scoped_ptr<net::test_server::BasicHttpResponse> response( + std::unique_ptr<net::test_server::BasicHttpResponse> response( new net::test_server::BasicHttpResponse()); response->set_content_type("text/html"); response->set_content(html);
diff --git a/chrome/browser/plugins/plugin_prefs.cc b/chrome/browser/plugins/plugin_prefs.cc index e822886f..dbe1b0a3 100644 --- a/chrome/browser/plugins/plugin_prefs.cc +++ b/chrome/browser/plugins/plugin_prefs.cc
@@ -6,12 +6,12 @@ #include <stddef.h> +#include <memory> #include <string> #include "base/bind.h" #include "base/command_line.h" #include "base/location.h" -#include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/single_thread_task_runner.h" #include "base/strings/pattern.h" @@ -128,7 +128,8 @@ // Update the state for all plugins in the group. for (size_t i = 0; i < plugins.size(); ++i) { - scoped_ptr<PluginMetadata> plugin(finder->GetPluginMetadata(plugins[i])); + std::unique_ptr<PluginMetadata> plugin( + finder->GetPluginMetadata(plugins[i])); if (group_name != plugin->name()) continue; plugin_state_.Set(plugins[i].path, enabled); @@ -147,7 +148,7 @@ content::WebPluginInfo plugin; bool can_enable = true; if (PluginService::GetInstance()->GetPluginInfoByPath(path, &plugin)) { - scoped_ptr<PluginMetadata> plugin_metadata( + std::unique_ptr<PluginMetadata> plugin_metadata( finder->GetPluginMetadata(plugin)); PolicyStatus plugin_status = PolicyStatusForPlugin(plugin.name); PolicyStatus group_status = PolicyStatusForPlugin(plugin_metadata->name()); @@ -188,7 +189,7 @@ base::string16 group_name; for (size_t i = 0; i < plugins.size(); ++i) { if (plugins[i].path == path) { - scoped_ptr<PluginMetadata> plugin_metadata( + std::unique_ptr<PluginMetadata> plugin_metadata( plugin_finder->GetPluginMetadata(plugins[i])); // set the group name for this plugin. group_name = plugin_metadata->name(); @@ -199,7 +200,7 @@ bool all_disabled = true; for (size_t i = 0; i < plugins.size(); ++i) { - scoped_ptr<PluginMetadata> plugin_metadata( + std::unique_ptr<PluginMetadata> plugin_metadata( plugin_finder->GetPluginMetadata(plugins[i])); DCHECK(!plugin_metadata->name().empty()); if (group_name == plugin_metadata->name()) { @@ -235,7 +236,7 @@ } bool PluginPrefs::IsPluginEnabled(const content::WebPluginInfo& plugin) const { - scoped_ptr<PluginMetadata> plugin_metadata( + std::unique_ptr<PluginMetadata> plugin_metadata( PluginFinder::GetInstance()->GetPluginMetadata(plugin)); base::string16 group_name = plugin_metadata->name(); @@ -490,7 +491,7 @@ summary->SetBoolean("enabled", enabled); plugins_list->Append(summary); - scoped_ptr<PluginMetadata> plugin_metadata( + std::unique_ptr<PluginMetadata> plugin_metadata( finder->GetPluginMetadata(plugins[i])); // Insert into a set of all group names. group_names.insert(plugin_metadata->name());
diff --git a/chrome/browser/power/process_power_collector.cc b/chrome/browser/power/process_power_collector.cc index 0d776af..d0129b1 100644 --- a/chrome/browser/power/process_power_collector.cc +++ b/chrome/browser/power/process_power_collector.cc
@@ -32,7 +32,7 @@ } ProcessPowerCollector::PerProcessData::PerProcessData( - scoped_ptr<base::ProcessMetrics> metrics, + std::unique_ptr<base::ProcessMetrics> metrics, const GURL& origin, Profile* profile) : metrics_(std::move(metrics)), @@ -201,14 +201,13 @@ if (metrics_map_.find(handle) == metrics_map_.end()) { metrics_map_[handle] = linked_ptr<PerProcessData>(new PerProcessData( #if defined(OS_MACOSX) - scoped_ptr<base::ProcessMetrics>( + std::unique_ptr<base::ProcessMetrics>( base::ProcessMetrics::CreateProcessMetrics(handle, NULL)), #else - scoped_ptr<base::ProcessMetrics>( + std::unique_ptr<base::ProcessMetrics>( base::ProcessMetrics::CreateProcessMetrics(handle)), #endif - origin, - Profile::FromBrowserContext(rph->GetBrowserContext()))); + origin, Profile::FromBrowserContext(rph->GetBrowserContext()))); } linked_ptr<PerProcessData>& process_data = metrics_map_[handle];
diff --git a/chrome/browser/power/process_power_collector.h b/chrome/browser/power/process_power_collector.h index f1c88d6..6755695 100644 --- a/chrome/browser/power/process_power_collector.h +++ b/chrome/browser/power/process_power_collector.h
@@ -41,7 +41,7 @@ public: class PerProcessData { public: - PerProcessData(scoped_ptr<base::ProcessMetrics> metrics, + PerProcessData(std::unique_ptr<base::ProcessMetrics> metrics, const GURL& origin, Profile* profile); PerProcessData(); @@ -57,7 +57,7 @@ private: // |metrics_| holds the ProcessMetrics information for the given process. - scoped_ptr<base::ProcessMetrics> metrics_; + std::unique_ptr<base::ProcessMetrics> metrics_; // |profile| is the profile that is visiting the |last_origin_|. // It is not owned by PerProcessData.
diff --git a/chrome/browser/power/process_power_collector_unittest.cc b/chrome/browser/power/process_power_collector_unittest.cc index 695334e1..dffe11ac 100644 --- a/chrome/browser/power/process_power_collector_unittest.cc +++ b/chrome/browser/power/process_power_collector_unittest.cc
@@ -73,19 +73,19 @@ ->GetProcess()); } - scoped_ptr<base::ProcessHandle> MakeProcessHandle(int process_id) { - scoped_ptr<base::ProcessHandle> proc_handle(new base::ProcessHandle( + std::unique_ptr<base::ProcessHandle> MakeProcessHandle(int process_id) { + std::unique_ptr<base::ProcessHandle> proc_handle(new base::ProcessHandle( #if defined(OS_WIN) reinterpret_cast<HANDLE>(process_id)) #else process_id) #endif - ); + ); return proc_handle; } - scoped_ptr<ProcessPowerCollector> collector; - scoped_ptr<TestingProfileManager> profile_manager_; + std::unique_ptr<ProcessPowerCollector> collector; + std::unique_ptr<TestingProfileManager> profile_manager_; }; TEST_F(BrowserProcessPowerTest, NoSite) { @@ -121,9 +121,9 @@ GURL url1("http://www.google.com"); GURL url2("http://www.example.com"); GURL url3("https://www.google.com"); - scoped_ptr<Browser> browser2( + std::unique_ptr<Browser> browser2( chrome::CreateBrowserWithTestWindowForParams(&native_params)); - scoped_ptr<Browser> browser3( + std::unique_ptr<Browser> browser3( chrome::CreateBrowserWithTestWindowForParams(&native_params)); AddTab(browser(), url1); AddTab(browser2.get(), url2); @@ -166,7 +166,7 @@ TEST_F(BrowserProcessPowerTest, IncognitoDoesntRecordPowerUsage) { Browser::CreateParams native_params(profile()->GetOffTheRecordProfile()); - scoped_ptr<Browser> incognito_browser( + std::unique_ptr<Browser> incognito_browser( chrome::CreateBrowserWithTestWindowForParams(&native_params)); GURL url("http://www.google.com"); AddTab(browser(), url); @@ -201,9 +201,9 @@ } TEST_F(BrowserProcessPowerTest, MultipleProfilesRecordSeparately) { - scoped_ptr<Profile> other_profile(CreateProfile()); + std::unique_ptr<Profile> other_profile(CreateProfile()); Browser::CreateParams native_params(other_profile.get()); - scoped_ptr<Browser> other_user( + std::unique_ptr<Browser> other_user( chrome::CreateBrowserWithTestWindowForParams(&native_params)); GURL url("http://www.google.com"); @@ -272,7 +272,7 @@ current_profile, content::SiteInstance::CreateForURL(current_profile, url)))); window->SetAppWindowContentsForTesting( - scoped_ptr<extensions::AppWindowContents>( + std::unique_ptr<extensions::AppWindowContents>( new extensions::TestAppWindowContents(web_contents))); extensions::AppWindowRegistry* app_registry = extensions::AppWindowRegistry::Get(current_profile);
diff --git a/chrome/browser/predictors/autocomplete_action_predictor.cc b/chrome/browser/predictors/autocomplete_action_predictor.cc index f31d763b..db8a6bc 100644 --- a/chrome/browser/predictors/autocomplete_action_predictor.cc +++ b/chrome/browser/predictors/autocomplete_action_predictor.cc
@@ -153,7 +153,7 @@ const gfx::Size& size) { // Only cancel the old prerender after starting the new one, so if the URLs // are the same, the underlying prerender will be reused. - scoped_ptr<prerender::PrerenderHandle> old_prerender_handle( + std::unique_ptr<prerender::PrerenderHandle> old_prerender_handle( prerender_handle_.release()); if (prerender::PrerenderManager* prerender_manager = prerender::PrerenderManagerFactory::GetForProfile(profile_)) {
diff --git a/chrome/browser/predictors/autocomplete_action_predictor.h b/chrome/browser/predictors/autocomplete_action_predictor.h index 5362bba..e2df03d 100644 --- a/chrome/browser/predictors/autocomplete_action_predictor.h +++ b/chrome/browser/predictors/autocomplete_action_predictor.h
@@ -6,11 +6,11 @@ #define CHROME_BROWSER_PREDICTORS_AUTOCOMPLETE_ACTION_PREDICTOR_H_ #include <map> +#include <memory> #include <tuple> #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" #include "base/strings/string16.h" @@ -248,7 +248,7 @@ // This is cleared after every Omnibox navigation. std::vector<TransitionalMatch> transitional_matches_; - scoped_ptr<prerender::PrerenderHandle> prerender_handle_; + std::unique_ptr<prerender::PrerenderHandle> prerender_handle_; // This allows us to predict the effect of confidence threshold changes on // accuracy. This is cleared after every omnibox navigation.
diff --git a/chrome/browser/predictors/autocomplete_action_predictor_table_unittest.cc b/chrome/browser/predictors/autocomplete_action_predictor_table_unittest.cc index 0c96659b..d48e8ee 100644 --- a/chrome/browser/predictors/autocomplete_action_predictor_table_unittest.cc +++ b/chrome/browser/predictors/autocomplete_action_predictor_table_unittest.cc
@@ -56,7 +56,7 @@ private: base::MessageLoop loop_; TestingProfile profile_; - scoped_ptr<PredictorDatabase> db_; + std::unique_ptr<PredictorDatabase> db_; content::TestBrowserThread db_thread_; };
diff --git a/chrome/browser/predictors/autocomplete_action_predictor_unittest.cc b/chrome/browser/predictors/autocomplete_action_predictor_unittest.cc index d89cd8c..025a149 100644 --- a/chrome/browser/predictors/autocomplete_action_predictor_unittest.cc +++ b/chrome/browser/predictors/autocomplete_action_predictor_unittest.cc
@@ -220,8 +220,8 @@ content::TestBrowserThread ui_thread_; content::TestBrowserThread db_thread_; content::TestBrowserThread file_thread_; - scoped_ptr<TestingProfile> profile_; - scoped_ptr<AutocompleteActionPredictor> predictor_; + std::unique_ptr<TestingProfile> profile_; + std::unique_ptr<AutocompleteActionPredictor> predictor_; };
diff --git a/chrome/browser/predictors/predictor_database.cc b/chrome/browser/predictors/predictor_database.cc index 2e65853..8fcdddf 100644 --- a/chrome/browser/predictors/predictor_database.cc +++ b/chrome/browser/predictors/predictor_database.cc
@@ -55,7 +55,7 @@ bool is_resource_prefetch_predictor_enabled_; base::FilePath db_path_; - scoped_ptr<sql::Connection> db_; + std::unique_ptr<sql::Connection> db_; // TODO(shishir): These tables may not need to be refcounted. Maybe move them // to using a WeakPtr instead.
diff --git a/chrome/browser/predictors/resource_prefetch_common_unittest.cc b/chrome/browser/predictors/resource_prefetch_common_unittest.cc index 92a5dbf8..4eed917 100644 --- a/chrome/browser/predictors/resource_prefetch_common_unittest.cc +++ b/chrome/browser/predictors/resource_prefetch_common_unittest.cc
@@ -95,10 +95,10 @@ protected: base::MessageLoop loop_; content::TestBrowserThread ui_thread_; - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<TestingProfile> profile_; private: - scoped_ptr<base::FieldTrialList> field_trial_list_; + std::unique_ptr<base::FieldTrialList> field_trial_list_; }; ResourcePrefetchCommonTest::ResourcePrefetchCommonTest() @@ -297,22 +297,26 @@ // Set preference to WIFI_ONLY: prefetch when not on cellular. SetPreference(NetworkPredictionOptions::NETWORK_PREDICTION_WIFI_ONLY); { - scoped_ptr<NetworkChangeNotifier> mock(new MockNetworkChangeNotifierWIFI); + std::unique_ptr<NetworkChangeNotifier> mock( + new MockNetworkChangeNotifierWIFI); TestIsPrefetchEnabled(config); } { - scoped_ptr<NetworkChangeNotifier> mock(new MockNetworkChangeNotifier4G); + std::unique_ptr<NetworkChangeNotifier> mock( + new MockNetworkChangeNotifier4G); TestIsPrefetchLearning(config); } // Set preference to NEVER: never prefetch. SetPreference(NetworkPredictionOptions::NETWORK_PREDICTION_NEVER); { - scoped_ptr<NetworkChangeNotifier> mock(new MockNetworkChangeNotifierWIFI); + std::unique_ptr<NetworkChangeNotifier> mock( + new MockNetworkChangeNotifierWIFI); TestIsPrefetchLearning(config); } { - scoped_ptr<NetworkChangeNotifier> mock(new MockNetworkChangeNotifier4G); + std::unique_ptr<NetworkChangeNotifier> mock( + new MockNetworkChangeNotifier4G); TestIsPrefetchLearning(config); } }
diff --git a/chrome/browser/predictors/resource_prefetch_predictor.cc b/chrome/browser/predictors/resource_prefetch_predictor.cc index 4186282..bc941c5a 100644 --- a/chrome/browser/predictors/resource_prefetch_predictor.cc +++ b/chrome/browser/predictors/resource_prefetch_predictor.cc
@@ -175,7 +175,7 @@ int visit_count_; NavigationID navigation_id_; - scoped_ptr<std::vector<URLRequestSummary> > requests_; + std::unique_ptr<std::vector<URLRequestSummary>> requests_; VisitInfoCallback callback_; DISALLOW_COPY_AND_ASSIGN(GetUrlVisitCountTask); @@ -423,7 +423,7 @@ ResourcePrefetcher::RequestVector* requests) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - scoped_ptr<Result> result(new Result(key_type, requests)); + std::unique_ptr<Result> result(new Result(key_type, requests)); // Add the results to the results map. if (!results_map_.insert(std::make_pair(navigation_id, std::move(result))) .second) @@ -552,7 +552,7 @@ PREFETCH_KEY_TYPE_URL); } } else { - scoped_ptr<ResourcePrefetcher::RequestVector> requests( + std::unique_ptr<ResourcePrefetcher::RequestVector> requests( new ResourcePrefetcher::RequestVector); PrefetchKeyType key_type; if (GetPrefetchData(navigation_id, requests.get(), &key_type)) { @@ -575,12 +575,10 @@ ServiceAccessType::EXPLICIT_ACCESS); DCHECK(history_service); history_service->ScheduleDBTask( - scoped_ptr<history::HistoryDBTask>( - new GetUrlVisitCountTask( - navigation_id, - requests, - base::Bind(&ResourcePrefetchPredictor::OnVisitCountLookup, - AsWeakPtr()))), + std::unique_ptr<history::HistoryDBTask>(new GetUrlVisitCountTask( + navigation_id, requests, + base::Bind(&ResourcePrefetchPredictor::OnVisitCountLookup, + AsWeakPtr()))), &history_lookup_consumer_); return plt; @@ -647,7 +645,7 @@ return; // Prefer URL based data first. - scoped_ptr<ResourcePrefetcher::RequestVector> requests( + std::unique_ptr<ResourcePrefetcher::RequestVector> requests( new ResourcePrefetcher::RequestVector); PrefetchKeyType key_type; if (!GetPrefetchData(navigation_id, requests.get(), &key_type)) { @@ -682,8 +680,8 @@ initialization_state_ = INITIALIZING; // Create local caches using the database as loaded. - scoped_ptr<PrefetchDataMap> url_data_map(new PrefetchDataMap()); - scoped_ptr<PrefetchDataMap> host_data_map(new PrefetchDataMap()); + std::unique_ptr<PrefetchDataMap> url_data_map(new PrefetchDataMap()); + std::unique_ptr<PrefetchDataMap> host_data_map(new PrefetchDataMap()); PrefetchDataMap* url_data_ptr = url_data_map.get(); PrefetchDataMap* host_data_ptr = host_data_map.get(); @@ -696,8 +694,8 @@ } void ResourcePrefetchPredictor::CreateCaches( - scoped_ptr<PrefetchDataMap> url_data_map, - scoped_ptr<PrefetchDataMap> host_data_map) { + std::unique_ptr<PrefetchDataMap> url_data_map, + std::unique_ptr<PrefetchDataMap> host_data_map) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_EQ(INITIALIZING, initialization_state_);
diff --git a/chrome/browser/predictors/resource_prefetch_predictor.h b/chrome/browser/predictors/resource_prefetch_predictor.h index a0c9409..a4212412 100644 --- a/chrome/browser/predictors/resource_prefetch_predictor.h +++ b/chrome/browser/predictors/resource_prefetch_predictor.h
@@ -8,13 +8,13 @@ #include <stddef.h> #include <map> +#include <memory> #include <string> #include <vector> #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/linked_ptr.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" #include "base/task/cancelable_task_tracker.h" @@ -160,7 +160,7 @@ ~Result(); PrefetchKeyType key_type; - scoped_ptr<ResourcePrefetcher::RequestVector> requests; + std::unique_ptr<ResourcePrefetcher::RequestVector> requests; private: DISALLOW_COPY_AND_ASSIGN(Result); @@ -172,7 +172,7 @@ typedef ResourcePrefetchPredictorTables::PrefetchDataMap PrefetchDataMap; typedef std::map<NavigationID, linked_ptr<std::vector<URLRequestSummary> > > NavigationMap; - typedef std::map<NavigationID, scoped_ptr<Result>> ResultsMap; + typedef std::map<NavigationID, std::unique_ptr<Result>> ResultsMap; // Returns true if the main page request is supported for prediction. static bool IsHandledMainPage(net::URLRequest* request); @@ -224,8 +224,8 @@ // Callback for task to read predictor database. Takes ownership of // |url_data_map| and |host_data_map|. - void CreateCaches(scoped_ptr<PrefetchDataMap> url_data_map, - scoped_ptr<PrefetchDataMap> host_data_map); + void CreateCaches(std::unique_ptr<PrefetchDataMap> url_data_map, + std::unique_ptr<PrefetchDataMap> host_data_map); // Called during initialization when history is read and the predictor // database has been read. @@ -319,8 +319,8 @@ NavigationMap inflight_navigations_; // Copy of the data in the predictor tables. - scoped_ptr<PrefetchDataMap> url_table_cache_; - scoped_ptr<PrefetchDataMap> host_table_cache_; + std::unique_ptr<PrefetchDataMap> url_table_cache_; + std::unique_ptr<PrefetchDataMap> host_table_cache_; ResultsMap results_map_;
diff --git a/chrome/browser/predictors/resource_prefetch_predictor_tables_unittest.cc b/chrome/browser/predictors/resource_prefetch_predictor_tables_unittest.cc index 9cc50e5..c5455d2 100644 --- a/chrome/browser/predictors/resource_prefetch_predictor_tables_unittest.cc +++ b/chrome/browser/predictors/resource_prefetch_predictor_tables_unittest.cc
@@ -34,7 +34,7 @@ base::MessageLoop loop_; content::TestBrowserThread db_thread_; TestingProfile profile_; - scoped_ptr<PredictorDatabase> db_; + std::unique_ptr<PredictorDatabase> db_; scoped_refptr<ResourcePrefetchPredictorTables> tables_; private:
diff --git a/chrome/browser/predictors/resource_prefetch_predictor_unittest.cc b/chrome/browser/predictors/resource_prefetch_predictor_unittest.cc index ae8f29e..c00d66ad 100644 --- a/chrome/browser/predictors/resource_prefetch_predictor_unittest.cc +++ b/chrome/browser/predictors/resource_prefetch_predictor_unittest.cc
@@ -2,14 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/predictors/resource_prefetch_predictor.h" + #include <iostream> +#include <memory> + #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/time/time.h" #include "chrome/browser/history/history_service_factory.h" -#include "chrome/browser/predictors/resource_prefetch_predictor.h" #include "chrome/browser/predictors/resource_prefetch_predictor_tables.h" #include "chrome/test/base/testing_profile.h" #include "components/history/core/browser/history_service.h" @@ -156,9 +158,9 @@ base::MessageLoop loop_; content::TestBrowserThread ui_thread_; content::TestBrowserThread db_thread_; - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<TestingProfile> profile_; - scoped_ptr<ResourcePrefetchPredictor> predictor_; + std::unique_ptr<ResourcePrefetchPredictor> predictor_; scoped_refptr<StrictMock<MockResourcePrefetchPredictorTables> > mock_tables_; PrefetchDataMap test_url_data_;
diff --git a/chrome/browser/predictors/resource_prefetcher.cc b/chrome/browser/predictors/resource_prefetcher.cc index 63c9e24..b9b0154 100644 --- a/chrome/browser/predictors/resource_prefetcher.cc +++ b/chrome/browser/predictors/resource_prefetcher.cc
@@ -41,7 +41,7 @@ const ResourcePrefetchPredictorConfig& config, const NavigationID& navigation_id, PrefetchKeyType key_type, - scoped_ptr<RequestVector> requests) + std::unique_ptr<RequestVector> requests) : state_(INITIALIZED), delegate_(delegate), config_(config),
diff --git a/chrome/browser/predictors/resource_prefetcher.h b/chrome/browser/predictors/resource_prefetcher.h index 6ce3a45..43dbc8a 100644 --- a/chrome/browser/predictors/resource_prefetcher.h +++ b/chrome/browser/predictors/resource_prefetcher.h
@@ -9,10 +9,10 @@ #include <list> #include <map> +#include <memory> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/threading/thread_checker.h" #include "chrome/browser/predictors/resource_prefetch_common.h" @@ -90,7 +90,7 @@ const ResourcePrefetchPredictorConfig& config, const NavigationID& navigation_id, PrefetchKeyType key_type, - scoped_ptr<RequestVector> requests); + std::unique_ptr<RequestVector> requests); ~ResourcePrefetcher() override; void Start(); // Kicks off the prefetching. Can only be called once. @@ -152,7 +152,7 @@ ResourcePrefetchPredictorConfig const config_; NavigationID navigation_id_; PrefetchKeyType key_type_; - scoped_ptr<RequestVector> request_vector_; + std::unique_ptr<RequestVector> request_vector_; std::map<net::URLRequest*, Request*> inflight_requests_; std::list<Request*> request_queue_;
diff --git a/chrome/browser/predictors/resource_prefetcher_manager.cc b/chrome/browser/predictors/resource_prefetcher_manager.cc index bf2a0a7..822935ea 100644 --- a/chrome/browser/predictors/resource_prefetcher_manager.cc +++ b/chrome/browser/predictors/resource_prefetcher_manager.cc
@@ -53,7 +53,7 @@ void ResourcePrefetcherManager::MaybeAddPrefetch( const NavigationID& navigation_id, PrefetchKeyType key_type, - scoped_ptr<ResourcePrefetcher::RequestVector> requests) { + std::unique_ptr<ResourcePrefetcher::RequestVector> requests) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); // Don't add a duplicate prefetch for the same host or URL. @@ -95,7 +95,7 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::IO); // |predictor_| can only be accessed from the UI thread. - scoped_ptr<ResourcePrefetcher::RequestVector> scoped_requests(requests); + std::unique_ptr<ResourcePrefetcher::RequestVector> scoped_requests(requests); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&ResourcePrefetcherManager::ResourcePrefetcherFinishedOnUI, this, @@ -117,7 +117,7 @@ void ResourcePrefetcherManager::ResourcePrefetcherFinishedOnUI( const NavigationID& navigation_id, PrefetchKeyType key_type, - scoped_ptr<ResourcePrefetcher::RequestVector> requests) { + std::unique_ptr<ResourcePrefetcher::RequestVector> requests) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // |predictor_| may have been set to NULL if the predictor is shutting down.
diff --git a/chrome/browser/predictors/resource_prefetcher_manager.h b/chrome/browser/predictors/resource_prefetcher_manager.h index 8724975a..d706df3 100644 --- a/chrome/browser/predictors/resource_prefetcher_manager.h +++ b/chrome/browser/predictors/resource_prefetcher_manager.h
@@ -46,9 +46,10 @@ // Will create a new ResourcePrefetcher for the main frame url of the input // navigation if there isn't one already for the same URL or host (for host // based). - void MaybeAddPrefetch(const NavigationID& navigation_id, - PrefetchKeyType key_type, - scoped_ptr<ResourcePrefetcher::RequestVector> requests); + void MaybeAddPrefetch( + const NavigationID& navigation_id, + PrefetchKeyType key_type, + std::unique_ptr<ResourcePrefetcher::RequestVector> requests); // Stops the ResourcePrefetcher for the input navigation, if one was in // progress. @@ -72,7 +73,7 @@ void ResourcePrefetcherFinishedOnUI( const NavigationID& navigation_id, PrefetchKeyType key_type, - scoped_ptr<ResourcePrefetcher::RequestVector> requests); + std::unique_ptr<ResourcePrefetcher::RequestVector> requests); ResourcePrefetchPredictor* predictor_; const ResourcePrefetchPredictorConfig config_;
diff --git a/chrome/browser/predictors/resource_prefetcher_unittest.cc b/chrome/browser/predictors/resource_prefetcher_unittest.cc index ff3fe44c..e97d8e6 100644 --- a/chrome/browser/predictors/resource_prefetcher_unittest.cc +++ b/chrome/browser/predictors/resource_prefetcher_unittest.cc
@@ -5,11 +5,12 @@ #include "chrome/browser/predictors/resource_prefetcher.h" #include <stddef.h> + +#include <memory> #include <utility> #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "chrome/browser/predictors/resource_prefetcher_manager.h" #include "chrome/test/base/testing_profile.h" @@ -34,7 +35,7 @@ const ResourcePrefetchPredictorConfig& config, const NavigationID& navigation_id, PrefetchKeyType key_type, - scoped_ptr<RequestVector> requests) + std::unique_ptr<RequestVector> requests) : ResourcePrefetcher(delegate, config, navigation_id, @@ -143,7 +144,7 @@ content::TestBrowserThread io_thread_; ResourcePrefetchPredictorConfig config_; TestResourcePrefetcherDelegate prefetcher_delegate_; - scoped_ptr<TestResourcePrefetcher> prefetcher_; + std::unique_ptr<TestResourcePrefetcher> prefetcher_; private: DISALLOW_COPY_AND_ASSIGN(ResourcePrefetcherTest); @@ -161,7 +162,7 @@ } TEST_F(ResourcePrefetcherTest, TestPrefetcherFinishes) { - scoped_ptr<ResourcePrefetcher::RequestVector> requests( + std::unique_ptr<ResourcePrefetcher::RequestVector> requests( new ResourcePrefetcher::RequestVector); requests->push_back(new ResourcePrefetcher::Request(GURL( "http://www.google.com/resource1.html"))); @@ -294,7 +295,7 @@ } TEST_F(ResourcePrefetcherTest, TestPrefetcherStopped) { - scoped_ptr<ResourcePrefetcher::RequestVector> requests( + std::unique_ptr<ResourcePrefetcher::RequestVector> requests( new ResourcePrefetcher::RequestVector); requests->push_back(new ResourcePrefetcher::Request(GURL( "http://www.google.com/resource1.html")));
diff --git a/chrome/browser/prefetch/prefetch_browsertest.cc b/chrome/browser/prefetch/prefetch_browsertest.cc index 5ade239..9adb78d 100644 --- a/chrome/browser/prefetch/prefetch_browsertest.cc +++ b/chrome/browser/prefetch/prefetch_browsertest.cc
@@ -101,27 +101,31 @@ // the network type. IN_PROC_BROWSER_TEST_F(PrefetchBrowserTestPrediction, PreferenceWorks) { // Set real NetworkChangeNotifier singleton aside. - scoped_ptr<NetworkChangeNotifier::DisableForTest> disable_for_test( + std::unique_ptr<NetworkChangeNotifier::DisableForTest> disable_for_test( new NetworkChangeNotifier::DisableForTest); // Preference defaults to ALWAYS. { - scoped_ptr<NetworkChangeNotifier> mock(new MockNetworkChangeNotifierWIFI); + std::unique_ptr<NetworkChangeNotifier> mock( + new MockNetworkChangeNotifierWIFI); EXPECT_TRUE(RunPrefetchExperiment(true, browser())); } { - scoped_ptr<NetworkChangeNotifier> mock(new MockNetworkChangeNotifier4G); + std::unique_ptr<NetworkChangeNotifier> mock( + new MockNetworkChangeNotifier4G); EXPECT_TRUE(RunPrefetchExperiment(true, browser())); } // Set preference to NEVER: prefetch should be unaffected. SetPreference(NetworkPredictionOptions::NETWORK_PREDICTION_NEVER); { - scoped_ptr<NetworkChangeNotifier> mock(new MockNetworkChangeNotifierWIFI); + std::unique_ptr<NetworkChangeNotifier> mock( + new MockNetworkChangeNotifierWIFI); EXPECT_TRUE(RunPrefetchExperiment(true, browser())); } { - scoped_ptr<NetworkChangeNotifier> mock(new MockNetworkChangeNotifier4G); + std::unique_ptr<NetworkChangeNotifier> mock( + new MockNetworkChangeNotifier4G); EXPECT_TRUE(RunPrefetchExperiment(true, browser())); } }
diff --git a/chrome/browser/prefs/chrome_pref_service_factory.cc b/chrome/browser/prefs/chrome_pref_service_factory.cc index 4e3874e..0c7a9f5 100644 --- a/chrome/browser/prefs/chrome_pref_service_factory.cc +++ b/chrome/browser/prefs/chrome_pref_service_factory.cc
@@ -13,6 +13,7 @@ #include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram_macros.h" #include "base/threading/sequenced_worker_pool.h" @@ -390,7 +391,7 @@ } } -scoped_ptr<ProfilePrefStoreManager> CreateProfilePrefStoreManager( +std::unique_ptr<ProfilePrefStoreManager> CreateProfilePrefStoreManager( const base::FilePath& profile_path) { std::string device_id; #if defined(OS_WIN) && defined(ENABLE_RLZ) @@ -407,13 +408,9 @@ seed = ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_PREF_HASH_SEED_BIN).as_string(); #endif - return make_scoped_ptr(new ProfilePrefStoreManager( - profile_path, - GetTrackingConfiguration(), - kTrackedPrefsReportingIDsCount, - seed, - device_id, - g_browser_process->local_state())); + return base::WrapUnique(new ProfilePrefStoreManager( + profile_path, GetTrackingConfiguration(), kTrackedPrefsReportingIDsCount, + seed, device_id, g_browser_process->local_state())); } void PrepareFactory( @@ -467,25 +464,23 @@ } // namespace internals -scoped_ptr<PrefService> CreateLocalState( +std::unique_ptr<PrefService> CreateLocalState( const base::FilePath& pref_filename, base::SequencedTaskRunner* pref_io_task_runner, policy::PolicyService* policy_service, const scoped_refptr<PrefRegistry>& pref_registry, bool async) { syncable_prefs::PrefServiceSyncableFactory factory; - PrepareFactory( - &factory, - policy_service, - NULL, // supervised_user_settings - new JsonPrefStore( - pref_filename, pref_io_task_runner, scoped_ptr<PrefFilter>()), - NULL, // extension_prefs - async); + PrepareFactory(&factory, policy_service, + NULL, // supervised_user_settings + new JsonPrefStore(pref_filename, pref_io_task_runner, + std::unique_ptr<PrefFilter>()), + NULL, // extension_prefs + async); return factory.Create(pref_registry.get()); } -scoped_ptr<syncable_prefs::PrefServiceSyncable> CreateProfilePrefs( +std::unique_ptr<syncable_prefs::PrefServiceSyncable> CreateProfilePrefs( const base::FilePath& profile_path, base::SequencedTaskRunner* pref_io_task_runner, TrackedPreferenceValidationDelegate* validation_delegate, @@ -519,7 +514,7 @@ user_pref_store, extension_prefs, async); - scoped_ptr<syncable_prefs::PrefServiceSyncable> pref_service = + std::unique_ptr<syncable_prefs::PrefServiceSyncable> pref_service = factory.CreateSyncable(pref_registry.get()); ConfigureDefaultSearchPrefMigrationToDictionaryValue(pref_service.get());
diff --git a/chrome/browser/prefs/chrome_pref_service_factory.h b/chrome/browser/prefs/chrome_pref_service_factory.h index 30e6bff..9dea6e5e 100644 --- a/chrome/browser/prefs/chrome_pref_service_factory.h +++ b/chrome/browser/prefs/chrome_pref_service_factory.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_PREFS_CHROME_PREF_SERVICE_FACTORY_H_ #define CHROME_BROWSER_PREFS_CHROME_PREF_SERVICE_FACTORY_H_ +#include <memory> + #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" namespace base { class DictionaryValue; @@ -64,14 +65,14 @@ // guaranteed that in asynchronous version initialization happens after this // function returned. -scoped_ptr<PrefService> CreateLocalState( +std::unique_ptr<PrefService> CreateLocalState( const base::FilePath& pref_filename, base::SequencedTaskRunner* pref_io_task_runner, policy::PolicyService* policy_service, const scoped_refptr<PrefRegistry>& pref_registry, bool async); -scoped_ptr<syncable_prefs::PrefServiceSyncable> CreateProfilePrefs( +std::unique_ptr<syncable_prefs::PrefServiceSyncable> CreateProfilePrefs( const base::FilePath& pref_filename, base::SequencedTaskRunner* pref_io_task_runner, TrackedPreferenceValidationDelegate* validation_delegate,
diff --git a/chrome/browser/prefs/chrome_pref_service_unittest.cc b/chrome/browser/prefs/chrome_pref_service_unittest.cc index 687e7b4..595226ea 100644 --- a/chrome/browser/prefs/chrome_pref_service_unittest.cc +++ b/chrome/browser/prefs/chrome_pref_service_unittest.cc
@@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> + #include "base/command_line.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" -#include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h"
diff --git a/chrome/browser/prefs/command_line_pref_store.cc b/chrome/browser/prefs/command_line_pref_store.cc index 1f08ea76..042430c 100644 --- a/chrome/browser/prefs/command_line_pref_store.cc +++ b/chrome/browser/prefs/command_line_pref_store.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/prefs/command_line_pref_store.h" #include <stddef.h> + #include <string> #include <utility> #include <vector> @@ -13,6 +14,7 @@ #include "base/files/file_path.h" #include "base/logging.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/values.h" @@ -115,7 +117,7 @@ for (size_t i = 0; i < arraysize(string_switch_map_); ++i) { if (command_line_->HasSwitch(string_switch_map_[i].switch_name)) { SetValue(string_switch_map_[i].preference_path, - make_scoped_ptr( + base::WrapUnique( new base::StringValue(command_line_->GetSwitchValueASCII( string_switch_map_[i].switch_name))), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); @@ -126,7 +128,7 @@ if (command_line_->HasSwitch(path_switch_map_[i].switch_name)) { SetValue( path_switch_map_[i].preference_path, - make_scoped_ptr(new base::StringValue( + base::WrapUnique(new base::StringValue( command_line_->GetSwitchValuePath(path_switch_map_[i].switch_name) .value())), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); @@ -145,7 +147,7 @@ continue; } SetValue(integer_switch_map_[i].preference_path, - make_scoped_ptr(new base::FundamentalValue(int_value)), + base::WrapUnique(new base::FundamentalValue(int_value)), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); } } @@ -153,7 +155,7 @@ for (size_t i = 0; i < arraysize(boolean_switch_map_); ++i) { if (command_line_->HasSwitch(boolean_switch_map_[i].switch_name)) { SetValue(boolean_switch_map_[i].preference_path, - make_scoped_ptr(new base::FundamentalValue( + base::WrapUnique(new base::FundamentalValue( boolean_switch_map_[i].set_value)), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); } @@ -163,18 +165,18 @@ void CommandLinePrefStore::ApplyProxyMode() { if (command_line_->HasSwitch(switches::kNoProxyServer)) { SetValue(proxy_config::prefs::kProxy, - make_scoped_ptr(ProxyConfigDictionary::CreateDirect()), + base::WrapUnique(ProxyConfigDictionary::CreateDirect()), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); } else if (command_line_->HasSwitch(switches::kProxyPacUrl)) { std::string pac_script_url = command_line_->GetSwitchValueASCII(switches::kProxyPacUrl); SetValue(proxy_config::prefs::kProxy, - make_scoped_ptr( + base::WrapUnique( ProxyConfigDictionary::CreatePacScript(pac_script_url, false)), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); } else if (command_line_->HasSwitch(switches::kProxyAutoDetect)) { SetValue(proxy_config::prefs::kProxy, - make_scoped_ptr(ProxyConfigDictionary::CreateAutoDetect()), + base::WrapUnique(ProxyConfigDictionary::CreateAutoDetect()), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); } else if (command_line_->HasSwitch(switches::kProxyServer)) { std::string proxy_server = @@ -182,7 +184,7 @@ std::string bypass_list = command_line_->GetSwitchValueASCII(switches::kProxyBypassList); SetValue(proxy_config::prefs::kProxy, - make_scoped_ptr(ProxyConfigDictionary::CreateFixedServers( + base::WrapUnique(ProxyConfigDictionary::CreateFixedServers( proxy_server, bypass_list)), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); } @@ -190,7 +192,7 @@ void CommandLinePrefStore::ApplySSLSwitches() { if (command_line_->HasSwitch(switches::kCipherSuiteBlacklist)) { - scoped_ptr<base::ListValue> list_value(new base::ListValue()); + std::unique_ptr<base::ListValue> list_value(new base::ListValue()); list_value->AppendStrings(base::SplitString( command_line_->GetSwitchValueASCII(switches::kCipherSuiteBlacklist), ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)); @@ -202,7 +204,7 @@ void CommandLinePrefStore::ApplyBackgroundModeSwitches() { if (command_line_->HasSwitch(switches::kDisableExtensions)) { SetValue(prefs::kBackgroundModeEnabled, - make_scoped_ptr(new base::FundamentalValue(false)), + base::WrapUnique(new base::FundamentalValue(false)), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); } }
diff --git a/chrome/browser/prefs/command_line_pref_store_proxy_unittest.cc b/chrome/browser/prefs/command_line_pref_store_proxy_unittest.cc index a8d61323..4b2fef7 100644 --- a/chrome/browser/prefs/command_line_pref_store_proxy_unittest.cc +++ b/chrome/browser/prefs/command_line_pref_store_proxy_unittest.cc
@@ -181,7 +181,7 @@ private: base::CommandLine command_line_; - scoped_ptr<PrefService> pref_service_; + std::unique_ptr<PrefService> pref_service_; net::ProxyConfig proxy_config_; };
diff --git a/chrome/browser/prefs/command_line_pref_store_ssl_manager_unittest.cc b/chrome/browser/prefs/command_line_pref_store_ssl_manager_unittest.cc index d47a914..2ab907b 100644 --- a/chrome/browser/prefs/command_line_pref_store_ssl_manager_unittest.cc +++ b/chrome/browser/prefs/command_line_pref_store_ssl_manager_unittest.cc
@@ -43,11 +43,11 @@ factory.set_user_prefs(local_state_store); factory.set_command_line_prefs(new CommandLinePrefStore(&command_line)); scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple; - scoped_ptr<PrefService> local_state(factory.Create(registry.get())); + std::unique_ptr<PrefService> local_state(factory.Create(registry.get())); SSLConfigServiceManager::RegisterPrefs(registry.get()); - scoped_ptr<SSLConfigServiceManager> config_manager( + std::unique_ptr<SSLConfigServiceManager> config_manager( SSLConfigServiceManager::CreateDefaultManager( local_state.get(), base::ThreadTaskRunnerHandle::Get())); ASSERT_TRUE(config_manager.get());
diff --git a/chrome/browser/prefs/pref_functional_browsertest.cc b/chrome/browser/prefs/pref_functional_browsertest.cc index b449b607..87bbec16 100644 --- a/chrome/browser/prefs/pref_functional_browsertest.cc +++ b/chrome/browser/prefs/pref_functional_browsertest.cc
@@ -4,6 +4,7 @@ #include <string> +#include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/download/download_prefs.h" #include "chrome/browser/net/prediction_options.h" @@ -34,8 +35,9 @@ protected: // Create a DownloadTestObserverTerminal that will wait for the // specified number of downloads to finish. - scoped_ptr<content::DownloadTestObserver> CreateWaiter(Browser* browser, - int num_downloads) { + std::unique_ptr<content::DownloadTestObserver> CreateWaiter( + Browser* browser, + int num_downloads) { DownloadManager* download_manager = BrowserContext::GetDownloadManager(browser->profile()); @@ -44,7 +46,7 @@ download_manager, num_downloads, content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL); - return make_scoped_ptr(downloads_observer); + return base::WrapUnique(downloads_observer); } }; @@ -61,7 +63,7 @@ prefs::kDownloadDefaultDirectory, new_download_dir.path()); // Create a downloads observer. - scoped_ptr<content::DownloadTestObserver> downloads_observer( + std::unique_ptr<content::DownloadTestObserver> downloads_observer( CreateWaiter(browser(), 1)); ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL("/downloads/a_zip_file.zip"));
diff --git a/chrome/browser/prefs/pref_metrics_service.h b/chrome/browser/prefs/pref_metrics_service.h index b185f43..7627e48 100644 --- a/chrome/browser/prefs/pref_metrics_service.h +++ b/chrome/browser/prefs/pref_metrics_service.h
@@ -6,10 +6,10 @@ #define CHROME_BROWSER_PREFS_PREF_METRICS_SERVICE_H_ #include <map> +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/profiles/profile.h" @@ -84,7 +84,7 @@ PrefService* prefs_; PrefService* local_state_; - scoped_ptr<syncable_prefs::SyncedPrefChangeRegistrar> + std::unique_ptr<syncable_prefs::SyncedPrefChangeRegistrar> synced_pref_change_registrar_; base::WeakPtrFactory<PrefMetricsService> weak_factory_;
diff --git a/chrome/browser/prefs/pref_service_browsertest.cc b/chrome/browser/prefs/pref_service_browsertest.cc index 35ea009f..8f6994c 100644 --- a/chrome/browser/prefs/pref_service_browsertest.cc +++ b/chrome/browser/prefs/pref_service_browsertest.cc
@@ -102,7 +102,7 @@ // The window should open with the new reference profile, with window // placement values stored in the user data directory. JSONFileValueDeserializer deserializer(original_pref_file_); - scoped_ptr<base::Value> root = deserializer.Deserialize(NULL, NULL); + std::unique_ptr<base::Value> root = deserializer.Deserialize(NULL, NULL); ASSERT_TRUE(root.get()); ASSERT_TRUE(root->IsType(base::Value::TYPE_DICTIONARY));
diff --git a/chrome/browser/prefs/profile_pref_store_manager.cc b/chrome/browser/prefs/profile_pref_store_manager.cc index d694d5f..d1cca84 100644 --- a/chrome/browser/prefs/profile_pref_store_manager.cc +++ b/chrome/browser/prefs/profile_pref_store_manager.cc
@@ -92,11 +92,11 @@ const scoped_refptr<base::SequencedTaskRunner>& io_task_runner, const base::Closure& on_reset_on_load, TrackedPreferenceValidationDelegate* validation_delegate) { - scoped_ptr<PrefFilter> pref_filter; + std::unique_ptr<PrefFilter> pref_filter; if (!kPlatformSupportsPreferenceTracking) { return new JsonPrefStore(profile_path_.Append(chrome::kPreferencesFilename), io_task_runner.get(), - scoped_ptr<PrefFilter>()); + std::unique_ptr<PrefFilter>()); } std::vector<PrefHashFilter::TrackedPreferenceMetadata> @@ -118,20 +118,13 @@ } } - scoped_ptr<PrefHashFilter> unprotected_pref_hash_filter( - new PrefHashFilter(GetPrefHashStore(false), - unprotected_configuration, - base::Closure(), - validation_delegate, - reporting_ids_count_, - false)); - scoped_ptr<PrefHashFilter> protected_pref_hash_filter( - new PrefHashFilter(GetPrefHashStore(true), - protected_configuration, - on_reset_on_load, - validation_delegate, - reporting_ids_count_, - true)); + std::unique_ptr<PrefHashFilter> unprotected_pref_hash_filter( + new PrefHashFilter(GetPrefHashStore(false), unprotected_configuration, + base::Closure(), validation_delegate, + reporting_ids_count_, false)); + std::unique_ptr<PrefHashFilter> protected_pref_hash_filter(new PrefHashFilter( + GetPrefHashStore(true), protected_configuration, on_reset_on_load, + validation_delegate, reporting_ids_count_, true)); PrefHashFilter* raw_unprotected_pref_hash_filter = unprotected_pref_hash_filter.get(); @@ -157,7 +150,7 @@ base::Bind(&JsonPrefStore::RegisterOnNextSuccessfulWriteCallback, protected_pref_store->AsWeakPtr()), GetPrefHashStore(false), GetPrefHashStore(true), - scoped_ptr<HashStoreContents>(new PrefServiceHashStoreContents( + std::unique_ptr<HashStoreContents>(new PrefServiceHashStoreContents( profile_path_.AsUTF8Unsafe(), local_state_)), raw_unprotected_pref_hash_filter, raw_protected_pref_hash_filter); @@ -173,7 +166,7 @@ return false; const base::DictionaryValue* to_serialize = &master_prefs; - scoped_ptr<base::DictionaryValue> copy; + std::unique_ptr<base::DictionaryValue> copy; if (kPlatformSupportsPreferenceTracking) { copy.reset(master_prefs.DeepCopy()); @@ -205,12 +198,12 @@ PersistentPrefStore* ProfilePrefStoreManager::CreateDeprecatedCombinedProfilePrefStore( const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) { - scoped_ptr<PrefFilter> pref_filter; + std::unique_ptr<PrefFilter> pref_filter; if (kPlatformSupportsPreferenceTracking) { - scoped_ptr<PrefHashStoreImpl> pref_hash_store_impl( + std::unique_ptr<PrefHashStoreImpl> pref_hash_store_impl( new PrefHashStoreImpl(seed_, device_id_, true)); pref_hash_store_impl->set_legacy_hash_store_contents( - scoped_ptr<HashStoreContents>(new PrefServiceHashStoreContents( + std::unique_ptr<HashStoreContents>(new PrefServiceHashStoreContents( profile_path_.AsUTF8Unsafe(), local_state_))); pref_filter.reset(new PrefHashFilter( std::move(pref_hash_store_impl), tracking_configuration_, @@ -220,12 +213,10 @@ io_task_runner.get(), std::move(pref_filter)); } -scoped_ptr<PrefHashStore> ProfilePrefStoreManager::GetPrefHashStore( +std::unique_ptr<PrefHashStore> ProfilePrefStoreManager::GetPrefHashStore( bool use_super_mac) { DCHECK(kPlatformSupportsPreferenceTracking); - return scoped_ptr<PrefHashStore>(new PrefHashStoreImpl( - seed_, - device_id_, - use_super_mac)); + return std::unique_ptr<PrefHashStore>( + new PrefHashStoreImpl(seed_, device_id_, use_super_mac)); }
diff --git a/chrome/browser/prefs/profile_pref_store_manager.h b/chrome/browser/prefs/profile_pref_store_manager.h index a6223fed..adaba7be 100644 --- a/chrome/browser/prefs/profile_pref_store_manager.h +++ b/chrome/browser/prefs/profile_pref_store_manager.h
@@ -7,13 +7,13 @@ #include <stddef.h> +#include <memory> #include <string> #include <vector> #include "base/files/file_path.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "components/user_prefs/tracked/pref_hash_filter.h" class PersistentPrefStore; @@ -103,7 +103,7 @@ // whether the returned object will calculate, store, and validate super MACs // (and, by extension, accept non-null newly protected preferences as // TrustedInitialized). - scoped_ptr<PrefHashStore> GetPrefHashStore(bool use_super_mac); + std::unique_ptr<PrefHashStore> GetPrefHashStore(bool use_super_mac); const base::FilePath profile_path_; const std::vector<PrefHashFilter::TrackedPreferenceMetadata>
diff --git a/chrome/browser/prefs/profile_pref_store_manager_unittest.cc b/chrome/browser/prefs/profile_pref_store_manager_unittest.cc index bfd5e3670..7e0d6dc 100644 --- a/chrome/browser/prefs/profile_pref_store_manager_unittest.cc +++ b/chrome/browser/prefs/profile_pref_store_manager_unittest.cc
@@ -6,6 +6,7 @@ #include <stddef.h> +#include <memory> #include <vector> #include "base/compiler_specific.h" @@ -13,8 +14,8 @@ #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "base/strings/string_util.h" #include "base/values.h" @@ -147,7 +148,7 @@ PrefServiceFactory pref_service_factory; pref_service_factory.set_user_prefs(pref_store_); - scoped_ptr<PrefService> pref_service( + std::unique_ptr<PrefService> pref_service( pref_service_factory.Create(profile_pref_registry_.get())); EXPECT_EQ( @@ -161,7 +162,7 @@ PrefServiceFactory pref_service_factory; pref_service_factory.set_user_prefs(pref_store_); - scoped_ptr<PrefService> pref_service( + std::unique_ptr<PrefService> pref_service( pref_service_factory.Create(profile_pref_registry_.get())); ProfilePrefStoreManager::ClearResetTime(pref_service.get()); @@ -211,13 +212,13 @@ PersistentPrefStore::PrefReadError error = pref_store->ReadPrefs(); EXPECT_EQ(PersistentPrefStore::PREF_READ_ERROR_NO_FILE, error); pref_store->SetValue(kTrackedAtomic, - make_scoped_ptr(new base::StringValue(kFoobar)), + base::WrapUnique(new base::StringValue(kFoobar)), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); pref_store->SetValue(kProtectedAtomic, - make_scoped_ptr(new base::StringValue(kHelloWorld)), + base::WrapUnique(new base::StringValue(kHelloWorld)), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); pref_store->SetValue(kUnprotectedPref, - make_scoped_ptr(new base::StringValue(kFoobar)), + base::WrapUnique(new base::StringValue(kFoobar)), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); pref_store->RemoveObserver(®istry_verifier_); pref_store->CommitPendingWrite(); @@ -279,7 +280,7 @@ scoped_refptr<user_prefs::PrefRegistrySyncable> profile_pref_registry_; RegistryVerifier registry_verifier_; MockValidationDelegate mock_validation_delegate_; - scoped_ptr<ProfilePrefStoreManager> manager_; + std::unique_ptr<ProfilePrefStoreManager> manager_; scoped_refptr<PersistentPrefStore> pref_store_; std::string seed_; @@ -571,7 +572,7 @@ // Trigger the logic that migrates it back to the unprotected preferences // file. pref_store_->SetValue(kProtectedAtomic, - make_scoped_ptr(new base::StringValue(kGoodbyeWorld)), + base::WrapUnique(new base::StringValue(kGoodbyeWorld)), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); LoadExistingPrefs(); ExpectStringValueEquals(kProtectedAtomic, kGoodbyeWorld);
diff --git a/chrome/browser/prefs/proxy_policy_unittest.cc b/chrome/browser/prefs/proxy_policy_unittest.cc index fb078bf..367d2e8 100644 --- a/chrome/browser/prefs/proxy_policy_unittest.cc +++ b/chrome/browser/prefs/proxy_policy_unittest.cc
@@ -100,7 +100,7 @@ void TearDown() override { provider_.Shutdown(); } - scoped_ptr<PrefService> CreatePrefService(bool with_managed_policies) { + std::unique_ptr<PrefService> CreatePrefService(bool with_managed_policies) { syncable_prefs::PrefServiceMockFactory factory; factory.set_command_line_prefs(new CommandLinePrefStore(&command_line_)); if (with_managed_policies) { @@ -110,7 +110,7 @@ scoped_refptr<user_prefs::PrefRegistrySyncable> registry( new user_prefs::PrefRegistrySyncable); - scoped_ptr<syncable_prefs::PrefServiceSyncable> prefs = + std::unique_ptr<syncable_prefs::PrefServiceSyncable> prefs = factory.CreateSyncable(registry.get()); chrome::RegisterUserProfilePrefs(registry.get()); return std::move(prefs); @@ -119,7 +119,7 @@ content::TestBrowserThreadBundle thread_bundle_; base::CommandLine command_line_; MockConfigurationPolicyProvider provider_; - scoped_ptr<PolicyServiceImpl> policy_service_; + std::unique_ptr<PolicyServiceImpl> policy_service_; }; TEST_F(ProxyPolicyTest, OverridesCommandLineOptions) { @@ -146,7 +146,7 @@ // First verify that command-line options are set correctly when // there is no policy in effect. - scoped_ptr<PrefService> prefs(CreatePrefService(false)); + std::unique_ptr<PrefService> prefs(CreatePrefService(false)); ProxyConfigDictionary dict(prefs->GetDictionary(proxy_config::prefs::kProxy)); assertProxyMode(dict, ProxyPrefs::MODE_FIXED_SERVERS); assertProxyServer(dict, "789"); @@ -177,7 +177,7 @@ // First verify that command-line options are set correctly when // there is no policy in effect. - scoped_ptr<PrefService> prefs = CreatePrefService(false); + std::unique_ptr<PrefService> prefs = CreatePrefService(false); ProxyConfigDictionary dict(prefs->GetDictionary(proxy_config::prefs::kProxy)); assertProxyMode(dict, ProxyPrefs::MODE_FIXED_SERVERS); assertProxyServer(dict, "789"); @@ -205,7 +205,7 @@ // First verify that command-line options are set correctly when // there is no policy in effect. - scoped_ptr<PrefService> prefs = CreatePrefService(false); + std::unique_ptr<PrefService> prefs = CreatePrefService(false); ProxyConfigDictionary dict(prefs->GetDictionary(proxy_config::prefs::kProxy)); assertProxyModeWithoutParams(dict, ProxyPrefs::MODE_DIRECT); @@ -229,7 +229,7 @@ // First verify that the auto-detect is set if there is no managed // PrefStore. - scoped_ptr<PrefService> prefs = CreatePrefService(false); + std::unique_ptr<PrefService> prefs = CreatePrefService(false); ProxyConfigDictionary dict(prefs->GetDictionary(proxy_config::prefs::kProxy)); assertProxyModeWithoutParams(dict, ProxyPrefs::MODE_AUTO_DETECT);
diff --git a/chrome/browser/prefs/session_startup_pref_unittest.cc b/chrome/browser/prefs/session_startup_pref_unittest.cc index 31385b4..e84a44a8 100644 --- a/chrome/browser/prefs/session_startup_pref_unittest.cc +++ b/chrome/browser/prefs/session_startup_pref_unittest.cc
@@ -22,7 +22,7 @@ return pref_service_->registry(); } - scoped_ptr<syncable_prefs::TestingPrefServiceSyncable> pref_service_; + std::unique_ptr<syncable_prefs::TestingPrefServiceSyncable> pref_service_; }; TEST_F(SessionStartupPrefTest, URLListIsFixedUp) {
diff --git a/chrome/browser/prefs/synced_pref_change_registrar_browsertest.cc b/chrome/browser/prefs/synced_pref_change_registrar_browsertest.cc index b467183..7dedec0 100644 --- a/chrome/browser/prefs/synced_pref_change_registrar_browsertest.cc +++ b/chrome/browser/prefs/synced_pref_change_registrar_browsertest.cc
@@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> #include <string> #include "base/json/json_string_value_serializer.h" -#include "base/memory/scoped_ptr.h" #include "base/time/time.h" #include "base/values.h" #include "chrome/browser/prefs/pref_service_syncable_util.h" @@ -101,11 +101,11 @@ prefs_ = PrefServiceSyncableFromProfile(browser()->profile()); syncer_ = prefs_->GetSyncableService(syncer::PREFERENCES); syncer_->MergeDataAndStartSyncing( - syncer::PREFERENCES, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( + syncer::PREFERENCES, syncer::SyncDataList(), + std::unique_ptr<syncer::SyncChangeProcessor>( new syncer::FakeSyncChangeProcessor), - scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock)); + std::unique_ptr<syncer::SyncErrorFactory>( + new syncer::SyncErrorFactoryMock)); registrar_.reset(new syncable_prefs::SyncedPrefChangeRegistrar(prefs_)); } @@ -115,7 +115,7 @@ syncer::SyncableService* syncer_; int next_sync_data_id_; - scoped_ptr<syncable_prefs::SyncedPrefChangeRegistrar> registrar_; + std::unique_ptr<syncable_prefs::SyncedPrefChangeRegistrar> registrar_; policy::MockConfigurationPolicyProvider policy_provider_; };
diff --git a/chrome/browser/prefs/tracked/pref_hash_browsertest.cc b/chrome/browser/prefs/tracked/pref_hash_browsertest.cc index 5fcf5e7..7562c75 100644 --- a/chrome/browser/prefs/tracked/pref_hash_browsertest.cc +++ b/chrome/browser/prefs/tracked/pref_hash_browsertest.cc
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> #include <string> #include "base/base_switches.h" @@ -9,7 +10,6 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/json/json_file_value_serializer.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/histogram_base.h" #include "base/metrics/histogram_samples.h" #include "base/metrics/statistics_recorder.h" @@ -69,7 +69,7 @@ if (!histogram) return 0; - scoped_ptr<base::HistogramSamples> samples(histogram->SnapshotSamples()); + std::unique_ptr<base::HistogramSamples> samples(histogram->SnapshotSamples()); int sum = 0; for (int i = 0; i < 100; ++i) { int count_for_id = samples->GetCount(i); @@ -84,22 +84,22 @@ return sum; } -scoped_ptr<base::DictionaryValue> ReadPrefsDictionary( +std::unique_ptr<base::DictionaryValue> ReadPrefsDictionary( const base::FilePath& pref_file) { JSONFileValueDeserializer deserializer(pref_file); int error_code = JSONFileValueDeserializer::JSON_NO_ERROR; std::string error_str; - scoped_ptr<base::Value> prefs = + std::unique_ptr<base::Value> prefs = deserializer.Deserialize(&error_code, &error_str); if (!prefs || error_code != JSONFileValueDeserializer::JSON_NO_ERROR) { ADD_FAILURE() << "Error #" << error_code << ": " << error_str; - return scoped_ptr<base::DictionaryValue>(); + return std::unique_ptr<base::DictionaryValue>(); } if (!prefs->IsType(base::Value::TYPE_DICTIONARY)) { ADD_FAILURE(); - return scoped_ptr<base::DictionaryValue>(); + return std::unique_ptr<base::DictionaryValue>(); } - return scoped_ptr<base::DictionaryValue>( + return std::unique_ptr<base::DictionaryValue>( static_cast<base::DictionaryValue*>(prefs.release())); } @@ -199,12 +199,12 @@ EXPECT_EQ(protection_level_ > PROTECTION_DISABLED_ON_PLATFORM, base::PathExists(protected_pref_file)); - scoped_ptr<base::DictionaryValue> unprotected_preferences( + std::unique_ptr<base::DictionaryValue> unprotected_preferences( ReadPrefsDictionary(unprotected_pref_file)); if (!unprotected_preferences) return false; - scoped_ptr<base::DictionaryValue> protected_preferences; + std::unique_ptr<base::DictionaryValue> protected_preferences; if (protection_level_ > PROTECTION_DISABLED_ON_PLATFORM) { protected_preferences = ReadPrefsDictionary(protected_pref_file); if (!protected_preferences)
diff --git a/chrome/browser/prerender/external_prerender_handler_android.h b/chrome/browser/prerender/external_prerender_handler_android.h index 3b1ef82..fafe0f1 100644 --- a/chrome/browser/prerender/external_prerender_handler_android.h +++ b/chrome/browser/prerender/external_prerender_handler_android.h
@@ -7,9 +7,10 @@ #include <jni.h> +#include <memory> + #include "base/android/scoped_java_ref.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" class GURL; class Profile; @@ -60,7 +61,7 @@ private: virtual ~ExternalPrerenderHandlerAndroid(); - scoped_ptr<prerender::PrerenderHandle> prerender_handle_; + std::unique_ptr<prerender::PrerenderHandle> prerender_handle_; DISALLOW_COPY_AND_ASSIGN(ExternalPrerenderHandlerAndroid); };
diff --git a/chrome/browser/prerender/prerender_browsertest.cc b/chrome/browser/prerender/prerender_browsertest.cc index 3087005..630f239 100644 --- a/chrome/browser/prerender/prerender_browsertest.cc +++ b/chrome/browser/prerender/prerender_browsertest.cc
@@ -442,7 +442,7 @@ private: content::WindowedNotificationObserver new_tab_observer_; - scoped_ptr<NavigationOrSwapObserver> swap_observer_; + std::unique_ptr<NavigationOrSwapObserver> swap_observer_; }; // PrerenderContents that stops the UI message loop on DidStopLoading(). @@ -655,7 +655,7 @@ int number_of_loads_; int expected_number_of_loads_; - scoped_ptr<base::RunLoop> load_waiter_; + std::unique_ptr<base::RunLoop> load_waiter_; base::RunLoop create_loop_; base::RunLoop start_loop_; @@ -673,8 +673,9 @@ EXPECT_TRUE(expected_contents_queue_.empty()); } - scoped_ptr<TestPrerender> ExpectPrerenderContents(FinalStatus final_status) { - scoped_ptr<TestPrerender> handle(new TestPrerender()); + std::unique_ptr<TestPrerender> ExpectPrerenderContents( + FinalStatus final_status) { + std::unique_ptr<TestPrerender> handle(new TestPrerender()); expected_contents_queue_.push_back( ExpectedContents(final_status, handle->AsWeakPtr())); return handle; @@ -903,7 +904,7 @@ void CreateHangingFirstRequestInterceptorOnIO( const GURL& url, const base::FilePath& file, base::Closure callback) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); - scoped_ptr<net::URLRequestInterceptor> never_respond_handler( + std::unique_ptr<net::URLRequestInterceptor> never_respond_handler( new HangingFirstRequestInterceptor(file, callback)); net::URLRequestFilter::GetInstance()->AddUrlInterceptor( url, std::move(never_respond_handler)); @@ -967,7 +968,7 @@ private: int count_; int expected_count_; - scoped_ptr<base::RunLoop> loop_; + std::unique_ptr<base::RunLoop> loop_; }; // Protocol handler which counts the number of requests that start. @@ -1009,7 +1010,7 @@ const base::FilePath& file, const base::WeakPtr<RequestCounter>& counter) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); - scoped_ptr<net::URLRequestInterceptor> request_interceptor( + std::unique_ptr<net::URLRequestInterceptor> request_interceptor( new CountingInterceptor(file, counter)); net::URLRequestFilter::GetInstance()->AddUrlInterceptor( url, std::move(request_interceptor)); @@ -1173,7 +1174,7 @@ } // Overload for a single expected final status - scoped_ptr<TestPrerender> PrerenderTestURL( + std::unique_ptr<TestPrerender> PrerenderTestURL( const std::string& html_file, FinalStatus expected_final_status, int expected_number_of_loads) { @@ -1193,7 +1194,7 @@ expected_number_of_loads); } - scoped_ptr<TestPrerender> PrerenderTestURL( + std::unique_ptr<TestPrerender> PrerenderTestURL( const GURL& url, FinalStatus expected_final_status, int expected_number_of_loads) { @@ -1204,7 +1205,7 @@ expected_final_status_queue, expected_number_of_loads).release(&prerenders); CHECK_EQ(1u, prerenders.size()); - return scoped_ptr<TestPrerender>(prerenders[0]); + return std::unique_ptr<TestPrerender>(prerenders[0]); } void NavigateToDestURL() const { @@ -1449,7 +1450,7 @@ // Returns length of |prerender_manager_|'s history, or -1 on failure. int GetHistoryLength() const { - scoped_ptr<base::DictionaryValue> prerender_dict( + std::unique_ptr<base::DictionaryValue> prerender_dict( static_cast<base::DictionaryValue*>( GetPrerenderManager()->GetAsValue())); if (!prerender_dict.get()) @@ -1536,7 +1537,8 @@ return display_test_result; } - scoped_ptr<TestPrerender> ExpectPrerender(FinalStatus expected_final_status) { + std::unique_ptr<TestPrerender> ExpectPrerender( + FinalStatus expected_final_status) { return prerender_contents_factory_->ExpectPrerenderContents( expected_final_status); } @@ -1702,11 +1704,11 @@ TestPrerenderContentsFactory* prerender_contents_factory_; #if defined(FULL_SAFE_BROWSING) - scoped_ptr<TestSafeBrowsingServiceFactory> safe_browsing_factory_; + std::unique_ptr<TestSafeBrowsingServiceFactory> safe_browsing_factory_; #endif NeverRunsExternalProtocolHandlerDelegate external_protocol_handler_delegate_; GURL dest_url_; - scoped_ptr<net::EmbeddedTestServer> https_src_server_; + std::unique_ptr<net::EmbeddedTestServer> https_src_server_; bool call_javascript_; bool check_load_events_; std::string loader_host_override_; @@ -1765,11 +1767,12 @@ // Checks that pending prerenders launch and receive proper event treatment. IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderPagePending) { - scoped_ptr<TestPrerender> prerender = PrerenderTestURL( + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL( "/prerender/prerender_page_pending.html", FINAL_STATUS_USED, 1); // Navigate to the prerender. - scoped_ptr<TestPrerender> prerender2 = ExpectPrerender(FINAL_STATUS_USED); + std::unique_ptr<TestPrerender> prerender2 = + ExpectPrerender(FINAL_STATUS_USED); NavigateToDestURL(); // Abort early if the original prerender didn't swap, so as not to hang. ASSERT_FALSE(prerender->contents()); @@ -1817,7 +1820,7 @@ } IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderPageRemovingLink) { - scoped_ptr<TestPrerender> prerender = PrerenderTestURL( + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL( "/prerender/prerender_page.html", FINAL_STATUS_CANCELLED, 1); // No ChannelDestructionWatcher is needed here, since prerenders in the @@ -1841,7 +1844,7 @@ GetPrerenderManager()->mutable_config().max_link_concurrency_per_launcher = 2; set_loader_query("links_to_insert=2"); - scoped_ptr<TestPrerender> prerender = PrerenderTestURL( + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL( "/prerender/prerender_page.html", FINAL_STATUS_CANCELLED, 1); EXPECT_TRUE(DidReceivePrerenderStartEventForLinkNumber(0)); EXPECT_FALSE(DidReceivePrerenderStopEventForLinkNumber(0)); @@ -1869,7 +1872,7 @@ GetPrerenderManager()->mutable_config().max_link_concurrency_per_launcher = 2; GURL url = embedded_test_server()->GetURL("/prerender/prerender_page.html"); - scoped_ptr<TestPrerender> prerender = + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL(url, FINAL_STATUS_CANCELLED, 1); // Add a second prerender for the same link. It reuses the prerender, so only @@ -2144,7 +2147,7 @@ // The prerender will not completely load until after the swap, so wait for a // title change before calling DidPrerenderPass. - scoped_ptr<TestPrerender> prerender = + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL(prerender_url, FINAL_STATUS_USED, 1); WaitForASCIITitle(prerender->contents()->prerender_contents(), kReadyTitle); EXPECT_TRUE(DidPrerenderPass(prerender->contents()->prerender_contents())); @@ -2320,7 +2323,7 @@ // Checks that the referrer is set when prerendering is cancelled. IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderCancelReferrer) { - scoped_ptr<TestContentBrowserClient> test_content_browser_client( + std::unique_ptr<TestContentBrowserClient> test_content_browser_client( new TestContentBrowserClient); content::ContentBrowserClient* original_browser_client = content::SetBrowserClientForTesting(test_content_browser_client.get()); @@ -2451,7 +2454,7 @@ const char* const kHtmlFileA = "/prerender/prerender_infinite_a.html"; const char* const kHtmlFileB = "/prerender/prerender_infinite_b.html"; - scoped_ptr<TestPrerender> prerender = + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL(kHtmlFileA, FINAL_STATUS_CANCELLED, 1); ASSERT_TRUE(prerender->contents()); // Assert that the pending prerender is in there already. This relies on the @@ -2618,7 +2621,7 @@ // Checks for correct network events by using a busy sleep the javascript. IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderHTML5VideoNetwork) { DisableJavascriptCalls(); - scoped_ptr<TestPrerender> prerender = PrerenderTestURL( + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL( "/prerender/prerender_html5_video_network.html", FINAL_STATUS_USED, 1); WaitForASCIITitle(prerender->contents()->prerender_contents(), kReadyTitle); EXPECT_TRUE(DidPrerenderPass(prerender->contents()->prerender_contents())); @@ -2637,7 +2640,7 @@ // Checks that prerenderers will terminate when the RenderView crashes. IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderRendererCrash) { - scoped_ptr<TestPrerender> prerender = PrerenderTestURL( + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL( "/prerender/prerender_page.html", FINAL_STATUS_RENDERER_CRASHED, 1); // Navigate to about:crash and then wait for the renderer to crash. @@ -2893,8 +2896,8 @@ } }; -scoped_ptr<net::ClientCertStore> CreateCertStore() { - return scoped_ptr<net::ClientCertStore>(new TestClientCertStore); +std::unique_ptr<net::ClientCertStore> CreateCertStore() { + return std::unique_ptr<net::ClientCertStore>(new TestClientCertStore); } // Checks that a top-level page which would normally request an SSL client @@ -3056,7 +3059,7 @@ // Checks that the favicon is properly loaded on prerender. IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderFavicon) { - scoped_ptr<TestPrerender> prerender = PrerenderTestURL( + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL( "/prerender/prerender_favicon.html", FINAL_STATUS_USED, 1); NavigateToDestURL(); @@ -3111,7 +3114,7 @@ // Checks that when the history is cleared, prerendering is cancelled and // prerendering history is cleared. IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderClearHistory) { - scoped_ptr<TestPrerender> prerender = + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL("/prerender/prerender_page.html", FINAL_STATUS_CACHE_OR_HISTORY_CLEARED, 1); @@ -3125,7 +3128,7 @@ // Checks that when the cache is cleared, prerenders are cancelled but // prerendering history is not cleared. IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderClearCache) { - scoped_ptr<TestPrerender> prerender = + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL("/prerender/prerender_page.html", FINAL_STATUS_CACHE_OR_HISTORY_CLEARED, 1); @@ -3138,7 +3141,7 @@ } IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderCancelAll) { - scoped_ptr<TestPrerender> prerender = PrerenderTestURL( + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL( "/prerender/prerender_page.html", FINAL_STATUS_CANCELLED, 1); GetPrerenderManager()->CancelAllPrerenders(); @@ -3148,7 +3151,7 @@ } IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderEvents) { - scoped_ptr<TestPrerender> prerender = PrerenderTestURL( + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL( "/prerender/prerender_page.html", FINAL_STATUS_CANCELLED, 1); GetPrerenderManager()->CancelAllPrerenders(); @@ -3163,7 +3166,7 @@ // should never be started. IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderCancelPrerenderWithPrerender) { - scoped_ptr<TestPrerender> prerender = PrerenderTestURL( + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL( "/prerender/prerender_infinite_a.html", FINAL_STATUS_CANCELLED, 1); GetPrerenderManager()->CancelAllPrerenders(); @@ -3321,7 +3324,7 @@ // Checks that the referrer policy is used when prerendering is cancelled. IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderCancelReferrerPolicy) { - scoped_ptr<TestContentBrowserClient> test_content_browser_client( + std::unique_ptr<TestContentBrowserClient> test_content_browser_client( new TestContentBrowserClient); content::ContentBrowserClient* original_browser_client = content::SetBrowserClientForTesting(test_content_browser_client.get()); @@ -3647,7 +3650,7 @@ // The prerender will not completely load until after the swap, so wait for a // title change before calling DidPrerenderPass. - scoped_ptr<TestPrerender> prerender = PrerenderTestURL( + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL( "/prerender/prerender_deferred_image.html", FINAL_STATUS_USED, 0); WaitForASCIITitle(prerender->contents()->prerender_contents(), kReadyTitle); EXPECT_EQ(1, GetPrerenderDomContentLoadedEventCountForLinkNumber(0)); @@ -3691,7 +3694,7 @@ // The prerender will not completely load until after the swap, so wait for a // title change before calling DidPrerenderPass. - scoped_ptr<TestPrerender> prerender = PrerenderTestURL( + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL( "/prerender/prerender_deferred_image.html", FINAL_STATUS_USED, 0); WaitForASCIITitle(prerender->contents()->prerender_contents(), kReadyTitle); EXPECT_TRUE(DidPrerenderPass(prerender->contents()->prerender_contents())); @@ -3859,7 +3862,7 @@ // Checks that prerenders are aborted when an incognito profile is closed. IN_PROC_BROWSER_TEST_F(PrerenderIncognitoBrowserTest, PrerenderIncognitoClosed) { - scoped_ptr<TestPrerender> prerender = PrerenderTestURL( + std::unique_ptr<TestPrerender> prerender = PrerenderTestURL( "/prerender/prerender_page.html", FINAL_STATUS_PROFILE_DESTROYED, 1); current_browser()->window()->Close(); prerender->WaitForStop(); @@ -3892,10 +3895,10 @@ profile); } - scoped_ptr<TestPrerender> StartOmniboxPrerender( + std::unique_ptr<TestPrerender> StartOmniboxPrerender( const GURL& url, FinalStatus expected_final_status) { - scoped_ptr<TestPrerender> prerender = + std::unique_ptr<TestPrerender> prerender = ExpectPrerender(expected_final_status); WebContents* web_contents = GetActiveWebContents(); GetAutocompleteActionPredictor()->StartPrerendering( @@ -3912,7 +3915,7 @@ IN_PROC_BROWSER_TEST_F(PrerenderOmniboxBrowserTest, DISABLED_PrerenderOmniboxCancel) { // Fake an omnibox prerender. - scoped_ptr<TestPrerender> prerender = StartOmniboxPrerender( + std::unique_ptr<TestPrerender> prerender = StartOmniboxPrerender( embedded_test_server()->GetURL("/empty.html"), FINAL_STATUS_CANCELLED); // Revert the location bar. This should cancel the prerender. @@ -3938,7 +3941,7 @@ WaitForAutocompleteDone(omnibox_view); // Fake an omnibox prerender for a different URL. - scoped_ptr<TestPrerender> prerender = + std::unique_ptr<TestPrerender> prerender = StartOmniboxPrerender(embedded_test_server()->GetURL("/empty.html?2"), FINAL_STATUS_APP_TERMINATING);
diff --git a/chrome/browser/prerender/prerender_contents.h b/chrome/browser/prerender/prerender_contents.h index 144ee61..907128c 100644 --- a/chrome/browser/prerender/prerender_contents.h +++ b/chrome/browser/prerender/prerender_contents.h
@@ -7,12 +7,12 @@ #include <stdint.h> +#include <memory> #include <string> #include <utility> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/time/time.h" @@ -312,7 +312,7 @@ base::TimeTicks load_start_time_; // The prerendered WebContents; may be null. - scoped_ptr<content::WebContents> prerender_contents_; + std::unique_ptr<content::WebContents> prerender_contents_; // The session storage namespace id for use in matching. We must save it // rather than get it from the RenderViewHost since in the control group @@ -377,9 +377,9 @@ // Process Metrics of the render process associated with the // RenderViewHost for this object. - scoped_ptr<base::ProcessMetrics> process_metrics_; + std::unique_ptr<base::ProcessMetrics> process_metrics_; - scoped_ptr<WebContentsDelegateImpl> web_contents_delegate_; + std::unique_ptr<WebContentsDelegateImpl> web_contents_delegate_; // These are -1 before a RenderView is created. int child_id_;
diff --git a/chrome/browser/prerender/prerender_history_unittest.cc b/chrome/browser/prerender/prerender_history_unittest.cc index 19fef4a..af243d6 100644 --- a/chrome/browser/prerender/prerender_history_unittest.cc +++ b/chrome/browser/prerender/prerender_history_unittest.cc
@@ -2,11 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/prerender/prerender_history.h" + #include <stddef.h> -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "base/values.h" -#include "chrome/browser/prerender/prerender_history.h" #include "testing/gtest/include/gtest/gtest.h" namespace prerender { @@ -50,7 +52,7 @@ } TEST(PrerenderHistoryTest, GetAsValue) { - scoped_ptr<base::Value> entry_value; + std::unique_ptr<base::Value> entry_value; base::ListValue* entry_list = NULL; // Create a history with only 2 values.
diff --git a/chrome/browser/prerender/prerender_link_manager.cc b/chrome/browser/prerender/prerender_link_manager.cc index 94ed907..9b1a232 100644 --- a/chrome/browser/prerender/prerender_link_manager.cc +++ b/chrome/browser/prerender/prerender_link_manager.cc
@@ -6,11 +6,11 @@ #include <functional> #include <limits> +#include <memory> #include <set> #include <string> #include <utility> -#include "base/memory/scoped_ptr.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram.h" #include "chrome/browser/prerender/prerender_contents.h" @@ -87,7 +87,7 @@ void Send(int child_id, IPC::Message* raw_message) { using content::RenderProcessHost; - scoped_ptr<IPC::Message> own_message(raw_message); + std::unique_ptr<IPC::Message> own_message(raw_message); RenderProcessHost* render_process_host = RenderProcessHost::FromID(child_id); if (!render_process_host) @@ -433,7 +433,7 @@ for (std::list<LinkPrerender>::iterator i = prerenders_.begin(); i != prerenders_.end(); ++i) { if (&(*i) == prerender) { - scoped_ptr<PrerenderHandle> own_handle(i->handle); + std::unique_ptr<PrerenderHandle> own_handle(i->handle); i->handle = NULL; prerenders_.erase(i); return; @@ -446,7 +446,7 @@ for (std::list<LinkPrerender>::iterator i = prerenders_.begin(); i != prerenders_.end(); ++i) { if (&(*i) == prerender) { - scoped_ptr<PrerenderHandle> own_handle(i->handle); + std::unique_ptr<PrerenderHandle> own_handle(i->handle); i->handle = NULL; prerenders_.erase(i); if (own_handle)
diff --git a/chrome/browser/prerender/prerender_link_manager.h b/chrome/browser/prerender/prerender_link_manager.h index b99b656c..4a44774 100644 --- a/chrome/browser/prerender/prerender_link_manager.h +++ b/chrome/browser/prerender/prerender_link_manager.h
@@ -169,7 +169,7 @@ // Helper object to manage prerenders which are launched by other prerenders // and must be deferred until the launcher is swapped in. - scoped_ptr<PendingPrerenderManager> pending_prerender_manager_; + std::unique_ptr<PendingPrerenderManager> pending_prerender_manager_; DISALLOW_COPY_AND_ASSIGN(PrerenderLinkManager); };
diff --git a/chrome/browser/prerender/prerender_manager.cc b/chrome/browser/prerender/prerender_manager.cc index 743d117..3bc6d9c 100644 --- a/chrome/browser/prerender/prerender_manager.cc +++ b/chrome/browser/prerender/prerender_manager.cc
@@ -170,7 +170,7 @@ } PrerenderManager* manager_; - scoped_ptr<WebContents> tab_; + std::unique_ptr<WebContents> tab_; bool suppressed_dialog_; DISALLOW_COPY_AND_ASSIGN(OnCloseWebContentsDeleter); @@ -489,8 +489,8 @@ FindIteratorForPrerenderContents(prerender_data->contents()); DCHECK(active_prerenders_.end() != to_erase); DCHECK_EQ(prerender_data, *to_erase); - scoped_ptr<PrerenderContents> - prerender_contents(prerender_data->ReleaseContents()); + std::unique_ptr<PrerenderContents> prerender_contents( + prerender_data->ReleaseContents()); active_prerenders_.erase(to_erase); // Mark prerender as used.
diff --git a/chrome/browser/prerender/prerender_manager.h b/chrome/browser/prerender/prerender_manager.h index c33c5406..692d971 100644 --- a/chrome/browser/prerender/prerender_manager.h +++ b/chrome/browser/prerender/prerender_manager.h
@@ -8,11 +8,11 @@ #include <stdint.h> #include <list> +#include <memory> #include <string> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/memory/weak_ptr.h" #include "base/threading/non_thread_safe.h" @@ -352,7 +352,7 @@ private: PrerenderManager* manager_; - scoped_ptr<PrerenderContents> contents_; + std::unique_ptr<PrerenderContents> contents_; // The number of distinct PrerenderHandles created for |this|, including // ones that have called PrerenderData::OnHandleNavigatedAway(), but not @@ -526,7 +526,7 @@ // navigate_time_. std::list<NavigationRecord> navigations_; - scoped_ptr<PrerenderContents::Factory> prerender_contents_factory_; + std::unique_ptr<PrerenderContents::Factory> prerender_contents_factory_; static PrerenderManagerMode mode_; @@ -545,9 +545,9 @@ ScopedVector<OnCloseWebContentsDeleter> on_close_web_contents_deleters_; - scoped_ptr<PrerenderHistory> prerender_history_; + std::unique_ptr<PrerenderHistory> prerender_history_; - scoped_ptr<PrerenderHistograms> histograms_; + std::unique_ptr<PrerenderHistograms> histograms_; content::NotificationRegistrar notification_registrar_;
diff --git a/chrome/browser/prerender/prerender_message_filter.h b/chrome/browser/prerender/prerender_message_filter.h index 049db7db..f3695a4e 100644 --- a/chrome/browser/prerender/prerender_message_filter.h +++ b/chrome/browser/prerender/prerender_message_filter.h
@@ -66,7 +66,8 @@ PrerenderLinkManager* prerender_link_manager_; - scoped_ptr<KeyedServiceShutdownNotifier::Subscription> shutdown_notifier_; + std::unique_ptr<KeyedServiceShutdownNotifier::Subscription> + shutdown_notifier_; DISALLOW_COPY_AND_ASSIGN(PrerenderMessageFilter); };
diff --git a/chrome/browser/prerender/prerender_resource_throttle_unittest.cc b/chrome/browser/prerender/prerender_resource_throttle_unittest.cc index dcc365fd..aa7fa9a18 100644 --- a/chrome/browser/prerender/prerender_resource_throttle_unittest.cc +++ b/chrome/browser/prerender/prerender_resource_throttle_unittest.cc
@@ -149,7 +149,7 @@ } private: - scoped_ptr<base::RunLoop> run_loop_; + std::unique_ptr<base::RunLoop> run_loop_; PrerenderResourceThrottle* throttle_; bool was_deferred_; bool cancel_called_; @@ -211,10 +211,9 @@ // Fake a request. net::TestURLRequestContext url_request_context; DeferredRedirectDelegate delegate; - scoped_ptr<net::URLRequest> request(url_request_context.CreateRequest( + std::unique_ptr<net::URLRequest> request(url_request_context.CreateRequest( net::URLRequestMockHTTPJob::GetMockUrl("prerender/image-deferred.png"), - net::DEFAULT_PRIORITY, - &delegate)); + net::DEFAULT_PRIORITY, &delegate)); content::ResourceRequestInfo::AllocateForTesting( request.get(), content::RESOURCE_TYPE_IMAGE, @@ -255,10 +254,9 @@ // Fake a request. net::TestURLRequestContext url_request_context; DeferredRedirectDelegate delegate; - scoped_ptr<net::URLRequest> request(url_request_context.CreateRequest( + std::unique_ptr<net::URLRequest> request(url_request_context.CreateRequest( net::URLRequestMockHTTPJob::GetMockUrl("prerender/image-deferred.png"), - net::DEFAULT_PRIORITY, - &delegate)); + net::DEFAULT_PRIORITY, &delegate)); content::ResourceRequestInfo::AllocateForTesting( request.get(), content::RESOURCE_TYPE_MAIN_FRAME, @@ -297,10 +295,9 @@ // Fake a request. net::TestURLRequestContext url_request_context; DeferredRedirectDelegate delegate; - scoped_ptr<net::URLRequest> request(url_request_context.CreateRequest( + std::unique_ptr<net::URLRequest> request(url_request_context.CreateRequest( net::URLRequestMockHTTPJob::GetMockUrl("prerender/image-deferred.png"), - net::DEFAULT_PRIORITY, - &delegate)); + net::DEFAULT_PRIORITY, &delegate)); content::ResourceRequestInfo::AllocateForTesting( request.get(), content::RESOURCE_TYPE_XHR,
diff --git a/chrome/browser/prerender/prerender_tab_helper.h b/chrome/browser/prerender/prerender_tab_helper.h index e672f10..da40e22 100644 --- a/chrome/browser/prerender/prerender_tab_helper.h +++ b/chrome/browser/prerender/prerender_tab_helper.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_PRERENDER_PRERENDER_TAB_HELPER_H_ #define CHROME_BROWSER_PRERENDER_PRERENDER_TAB_HELPER_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "chrome/browser/prerender/prerender_histograms.h"
diff --git a/chrome/browser/prerender/prerender_unittest.cc b/chrome/browser/prerender/prerender_unittest.cc index 499bd53..0db797f2 100644 --- a/chrome/browser/prerender/prerender_unittest.cc +++ b/chrome/browser/prerender/prerender_unittest.cc
@@ -252,7 +252,7 @@ Time time_; TimeTicks time_ticks_; - scoped_ptr<PrerenderContents> next_prerender_contents_; + std::unique_ptr<PrerenderContents> next_prerender_contents_; // PrerenderContents with an |expected_final_status| of FINAL_STATUS_USED, // tracked so they will be automatically deleted. ScopedVector<PrerenderContents> used_prerender_contents_; @@ -401,8 +401,8 @@ base::MessageLoop message_loop_; TestingProfile profile_; content::TestBrowserThread ui_thread_; - scoped_ptr<UnitTestPrerenderManager> prerender_manager_; - scoped_ptr<PrerenderLinkManager> prerender_link_manager_; + std::unique_ptr<UnitTestPrerenderManager> prerender_manager_; + std::unique_ptr<PrerenderLinkManager> prerender_link_manager_; int last_prerender_id_; base::FieldTrialList field_trial_list_; }; @@ -1080,7 +1080,7 @@ TEST_F(PrerenderTest, LinkRelAllowedOnCellular) { EnablePrerender(); GURL url("http://www.example.com"); - scoped_ptr<net::NetworkChangeNotifier> mock( + std::unique_ptr<net::NetworkChangeNotifier> mock( new MockNetworkChangeNotifier4G); EXPECT_TRUE(net::NetworkChangeNotifier::IsConnectionCellular( net::NetworkChangeNotifier::GetConnectionType())); @@ -1094,7 +1094,7 @@ TEST_F(PrerenderTest, PrerenderNotAllowedOnCellularWithExternalOrigin) { EnablePrerender(); - scoped_ptr<net::NetworkChangeNotifier> mock( + std::unique_ptr<net::NetworkChangeNotifier> mock( new MockNetworkChangeNotifier4G); EXPECT_TRUE(net::NetworkChangeNotifier::IsConnectionCellular( net::NetworkChangeNotifier::GetConnectionType())); @@ -1104,7 +1104,7 @@ url, ORIGIN_EXTERNAL_REQUEST, FINAL_STATUS_MANAGER_SHUTDOWN); - scoped_ptr<PrerenderHandle> prerender_handle( + std::unique_ptr<PrerenderHandle> prerender_handle( prerender_manager()->AddPrerenderFromExternalRequest( url, content::Referrer(), nullptr, kSize)); EXPECT_FALSE(prerender_handle); @@ -1113,7 +1113,7 @@ TEST_F(PrerenderTest,PrerenderAllowedOnCellularWithForcedOrigin) { EnablePrerender(); - scoped_ptr<net::NetworkChangeNotifier> mock( + std::unique_ptr<net::NetworkChangeNotifier> mock( new MockNetworkChangeNotifier4G); EXPECT_TRUE(net::NetworkChangeNotifier::IsConnectionCellular( net::NetworkChangeNotifier::GetConnectionType())); @@ -1123,7 +1123,7 @@ url, ORIGIN_EXTERNAL_REQUEST_FORCED_CELLULAR, FINAL_STATUS_USED); - scoped_ptr<PrerenderHandle> prerender_handle( + std::unique_ptr<PrerenderHandle> prerender_handle( prerender_manager()->AddPrerenderOnCellularFromExternalRequest( url, content::Referrer(), nullptr, kSize)); EXPECT_TRUE(prerender_handle); @@ -1651,7 +1651,7 @@ DummyPrerenderContents* prerender_contents = prerender_manager()->CreateNextPrerenderContents(url, ORIGIN_INSTANT, FINAL_STATUS_USED); - scoped_ptr<PrerenderHandle> prerender_handle( + std::unique_ptr<PrerenderHandle> prerender_handle( prerender_manager()->AddPrerenderForInstant(url, NULL, kSize)); CHECK(prerender_handle.get()); EXPECT_TRUE(prerender_handle->IsPrerendering());
diff --git a/chrome/browser/process_singleton_browsertest.cc b/chrome/browser/process_singleton_browsertest.cc index 90b08b5e..ff7a4cb 100644 --- a/chrome/browser/process_singleton_browsertest.cc +++ b/chrome/browser/process_singleton_browsertest.cc
@@ -19,6 +19,7 @@ #include "base/location.h" #include "base/macros.h" #include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/process/launch.h" #include "base/process/process.h" @@ -210,7 +211,7 @@ // The idea is to start chrome from multiple threads all at once. static const size_t kNbThreads = 5; scoped_refptr<ChromeStarter> chrome_starters_[kNbThreads]; - scoped_ptr<base::Thread> chrome_starter_threads_[kNbThreads]; + std::unique_ptr<base::Thread> chrome_starter_threads_[kNbThreads]; // The event that will get all threads to wake up simultaneously and try // to start a chrome process at the same time.
diff --git a/chrome/browser/process_singleton_posix_unittest.cc b/chrome/browser/process_singleton_posix_unittest.cc index d0f68e9..aca5d06b 100644 --- a/chrome/browser/process_singleton_posix_unittest.cc +++ b/chrome/browser/process_singleton_posix_unittest.cc
@@ -13,6 +13,7 @@ #include <sys/wait.h> #include <unistd.h> +#include <memory> #include <string> #include <vector> @@ -22,7 +23,6 @@ #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/location.h" -#include "base/memory/scoped_ptr.h" #include "base/posix/eintr_wrapper.h" #include "base/single_thread_task_runner.h" #include "base/strings/stringprintf.h" @@ -164,7 +164,7 @@ } ProcessSingleton::NotifyResult NotifyOtherProcess(bool override_kill) { - scoped_ptr<TestableProcessSingleton> process_singleton( + std::unique_ptr<TestableProcessSingleton> process_singleton( CreateProcessSingleton()); base::CommandLine command_line( base::CommandLine::ForCurrentProcess()->GetProgram()); @@ -184,7 +184,7 @@ // A helper method to call ProcessSingleton::NotifyOtherProcessOrCreate(). ProcessSingleton::NotifyResult NotifyOtherProcessOrCreate( const std::string& url) { - scoped_ptr<TestableProcessSingleton> process_singleton( + std::unique_ptr<TestableProcessSingleton> process_singleton( CreateProcessSingleton()); base::CommandLine command_line( base::CommandLine::ForCurrentProcess()->GetProgram()); @@ -261,7 +261,7 @@ base::WaitableEvent wait_event_; base::WaitableEvent signal_event_; - scoped_ptr<base::Thread> worker_thread_; + std::unique_ptr<base::Thread> worker_thread_; TestableProcessSingleton* process_singleton_on_thread_; }; @@ -363,7 +363,7 @@ TEST_F(ProcessSingletonPosixTest, CreateFailsWithExistingBrowser) { CreateProcessSingletonOnThread(); - scoped_ptr<TestableProcessSingleton> process_singleton( + std::unique_ptr<TestableProcessSingleton> process_singleton( CreateProcessSingleton()); process_singleton->OverrideCurrentPidForTesting(base::GetCurrentProcId() + 1); EXPECT_FALSE(process_singleton->Create()); @@ -373,7 +373,7 @@ // but with the old socket location. TEST_F(ProcessSingletonPosixTest, CreateChecksCompatibilitySocket) { CreateProcessSingletonOnThread(); - scoped_ptr<TestableProcessSingleton> process_singleton( + std::unique_ptr<TestableProcessSingleton> process_singleton( CreateProcessSingleton()); process_singleton->OverrideCurrentPidForTesting(base::GetCurrentProcId() + 1); @@ -410,7 +410,7 @@ // Test that if there is an existing lock file, and we could not flock() // it, then exit. TEST_F(ProcessSingletonPosixTest, CreateRespectsOldMacLock) { - scoped_ptr<TestableProcessSingleton> process_singleton( + std::unique_ptr<TestableProcessSingleton> process_singleton( CreateProcessSingleton()); base::ScopedFD lock_fd(HANDLE_EINTR( open(lock_path_.value().c_str(), O_RDWR | O_CREAT | O_EXLOCK, 0644))); @@ -425,7 +425,7 @@ // Test that if there is an existing lock file, and it's not locked, we replace // it. TEST_F(ProcessSingletonPosixTest, CreateReplacesOldMacLock) { - scoped_ptr<TestableProcessSingleton> process_singleton( + std::unique_ptr<TestableProcessSingleton> process_singleton( CreateProcessSingleton()); EXPECT_EQ(0, base::WriteFile(lock_path_, "", 0)); EXPECT_TRUE(process_singleton->Create());
diff --git a/chrome/browser/process_singleton_win_unittest.cc b/chrome/browser/process_singleton_win_unittest.cc index dad6dce..d12791d 100644 --- a/chrome/browser/process_singleton_win_unittest.cc +++ b/chrome/browser/process_singleton_win_unittest.cc
@@ -6,6 +6,8 @@ #include <windows.h> +#include <memory> + #include "base/bind.h" #include "base/command_line.h" #include "base/compiler_specific.h" @@ -13,7 +15,6 @@ #include "base/files/scoped_temp_dir.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/process/launch.h" #include "base/process/process.h" #include "base/process/process_handle.h" @@ -246,7 +247,7 @@ base::Process browser_victim_; base::win::ScopedHandle continue_event_; - scoped_ptr<ProcessSingleton> test_singleton_; + std::unique_ptr<ProcessSingleton> test_singleton_; base::TimeDelta old_notification_timeout_; bool should_kill_called_;
diff --git a/chrome/browser/profile_resetter/brandcode_config_fetcher.h b/chrome/browser/profile_resetter/brandcode_config_fetcher.h index 2388499..b56454c 100644 --- a/chrome/browser/profile_resetter/brandcode_config_fetcher.h +++ b/chrome/browser/profile_resetter/brandcode_config_fetcher.h
@@ -5,11 +5,11 @@ #ifndef CHROME_BROWSER_PROFILE_RESETTER_BRANDCODE_CONFIG_FETCHER_H_ #define CHROME_BROWSER_PROFILE_RESETTER_BRANDCODE_CONFIG_FETCHER_H_ +#include <memory> #include <utility> #include "base/callback.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/timer/timer.h" #include "net/url_request/url_fetcher_delegate.h" @@ -29,7 +29,7 @@ bool IsActive() const { return !!config_fetcher_; } - scoped_ptr<BrandcodedDefaultSettings> GetSettings() { + std::unique_ptr<BrandcodedDefaultSettings> GetSettings() { return std::move(default_settings_); } @@ -50,10 +50,10 @@ FetchCallback fetch_callback_; // Helper to fetch the online config file. - scoped_ptr<net::URLFetcher> config_fetcher_; + std::unique_ptr<net::URLFetcher> config_fetcher_; // Fetched settings. - scoped_ptr<BrandcodedDefaultSettings> default_settings_; + std::unique_ptr<BrandcodedDefaultSettings> default_settings_; DISALLOW_COPY_AND_ASSIGN(BrandcodeConfigFetcher); };
diff --git a/chrome/browser/profile_resetter/brandcoded_default_settings.cc b/chrome/browser/profile_resetter/brandcoded_default_settings.cc index 20145fb..7e600f8 100644 --- a/chrome/browser/profile_resetter/brandcoded_default_settings.cc +++ b/chrome/browser/profile_resetter/brandcoded_default_settings.cc
@@ -18,7 +18,7 @@ if (!prefs.empty()) { JSONStringValueDeserializer json(prefs); std::string error; - scoped_ptr<base::Value> root(json.Deserialize(NULL, &error)); + std::unique_ptr<base::Value> root(json.Deserialize(NULL, &error)); if (!root.get()) { VLOG(1) << "Failed to parse brandcode prefs file: " << error; return; @@ -36,7 +36,7 @@ BrandcodedDefaultSettings::~BrandcodedDefaultSettings() { } -scoped_ptr<base::ListValue> +std::unique_ptr<base::ListValue> BrandcodedDefaultSettings::GetSearchProviderOverrides() const { return ExtractList(prefs::kSearchProviderOverrides); } @@ -86,18 +86,18 @@ restore_on_startup); } -scoped_ptr<base::ListValue> +std::unique_ptr<base::ListValue> BrandcodedDefaultSettings::GetUrlsToRestoreOnStartup() const { return ExtractList(prefs::kURLsToRestoreOnStartup); } -scoped_ptr<base::ListValue> BrandcodedDefaultSettings::ExtractList( +std::unique_ptr<base::ListValue> BrandcodedDefaultSettings::ExtractList( const char* pref_name) const { const base::ListValue* value = NULL; if (master_dictionary_ && master_dictionary_->GetList(pref_name, &value) && !value->empty()) { - return scoped_ptr<base::ListValue>(value->DeepCopy()); + return std::unique_ptr<base::ListValue>(value->DeepCopy()); } - return scoped_ptr<base::ListValue>(); + return std::unique_ptr<base::ListValue>(); }
diff --git a/chrome/browser/profile_resetter/brandcoded_default_settings.h b/chrome/browser/profile_resetter/brandcoded_default_settings.h index 5365083..905833c 100644 --- a/chrome/browser/profile_resetter/brandcoded_default_settings.h +++ b/chrome/browser/profile_resetter/brandcoded_default_settings.h
@@ -5,11 +5,11 @@ #ifndef CHROME_BROWSER_PROFILE_RESETTER_BRANDCODED_DEFAULT_SETTINGS_H_ #define CHROME_BROWSER_PROFILE_RESETTER_BRANDCODED_DEFAULT_SETTINGS_H_ +#include <memory> #include <string> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/values.h" // BrandcodedDefaultSettings provides a set of default settings @@ -25,7 +25,7 @@ // provided for given setting. // After the call return_value contains a list of default engines. // |return_value[0]| is default one. - scoped_ptr<base::ListValue> GetSearchProviderOverrides() const; + std::unique_ptr<base::ListValue> GetSearchProviderOverrides() const; bool GetHomepage(std::string* homepage) const; bool GetHomepageIsNewTab(bool* homepage_is_ntp) const; @@ -35,12 +35,12 @@ bool GetExtensions(std::vector<std::string>* extension_ids) const; bool GetRestoreOnStartup(int* restore_on_startup) const; - scoped_ptr<base::ListValue> GetUrlsToRestoreOnStartup() const; + std::unique_ptr<base::ListValue> GetUrlsToRestoreOnStartup() const; private: - scoped_ptr<base::ListValue> ExtractList(const char* pref_name) const; + std::unique_ptr<base::ListValue> ExtractList(const char* pref_name) const; - scoped_ptr<base::DictionaryValue> master_dictionary_; + std::unique_ptr<base::DictionaryValue> master_dictionary_; DISALLOW_COPY_AND_ASSIGN(BrandcodedDefaultSettings); };
diff --git a/chrome/browser/profile_resetter/profile_resetter.cc b/chrome/browser/profile_resetter/profile_resetter.cc index bf10109..84a667d 100644 --- a/chrome/browser/profile_resetter/profile_resetter.cc +++ b/chrome/browser/profile_resetter/profile_resetter.cc
@@ -88,7 +88,7 @@ void ProfileResetter::Reset( ProfileResetter::ResettableFlags resettable_flags, - scoped_ptr<BrandcodedDefaultSettings> master_settings, + std::unique_ptr<BrandcodedDefaultSettings> master_settings, const base::Closure& callback) { DCHECK(CalledOnValidThread()); DCHECK(master_settings); @@ -168,7 +168,7 @@ DCHECK(prefs); TemplateURLPrepopulateData::ClearPrepopulatedEnginesInPrefs( profile_->GetPrefs()); - scoped_ptr<base::ListValue> search_engines( + std::unique_ptr<base::ListValue> search_engines( master_settings_->GetSearchProviderOverrides()); if (search_engines) { // This Chrome distribution channel provides a custom search engine. We @@ -279,7 +279,7 @@ DCHECK(CalledOnValidThread()); PrefService* prefs = profile_->GetPrefs(); DCHECK(prefs); - scoped_ptr<base::ListValue> url_list( + std::unique_ptr<base::ListValue> url_list( master_settings_->GetUrlsToRestoreOnStartup()); if (url_list) ListPrefUpdate(prefs, prefs::kURLsToRestoreOnStartup)->Swap(url_list.get());
diff --git a/chrome/browser/profile_resetter/profile_resetter.h b/chrome/browser/profile_resetter/profile_resetter.h index fad3dd6..f7226ee 100644 --- a/chrome/browser/profile_resetter/profile_resetter.h +++ b/chrome/browser/profile_resetter/profile_resetter.h
@@ -7,6 +7,7 @@ #include <stdint.h> +#include <memory> #include <utility> #include <vector> @@ -14,7 +15,6 @@ #include "base/files/file_path.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/strings/string16.h" #include "base/threading/non_thread_safe.h" @@ -64,7 +64,7 @@ // completion. |default_settings| allows the caller to specify some default // settings. |default_settings| shouldn't be NULL. virtual void Reset(ResettableFlags resettable_flags, - scoped_ptr<BrandcodedDefaultSettings> master_settings, + std::unique_ptr<BrandcodedDefaultSettings> master_settings, const base::Closure& callback); virtual bool IsActive() const; @@ -90,7 +90,7 @@ void OnTemplateURLServiceLoaded(); Profile* const profile_; - scoped_ptr<BrandcodedDefaultSettings> master_settings_; + std::unique_ptr<BrandcodedDefaultSettings> master_settings_; TemplateURLService* template_url_service_; // Flags of a Resetable indicating which reset operations we are still waiting @@ -104,7 +104,7 @@ // of deleting itself when done. BrowsingDataRemover* cookies_remover_; - scoped_ptr<TemplateURLService::Subscription> template_url_service_sub_; + std::unique_ptr<TemplateURLService::Subscription> template_url_service_sub_; base::WeakPtrFactory<ProfileResetter> weak_ptr_factory_;
diff --git a/chrome/browser/profile_resetter/profile_resetter_test_base.cc b/chrome/browser/profile_resetter/profile_resetter_test_base.cc index cccd6049..ab329670 100644 --- a/chrome/browser/profile_resetter/profile_resetter_test_base.cc +++ b/chrome/browser/profile_resetter/profile_resetter_test_base.cc
@@ -32,7 +32,7 @@ void ProfileResetterTestBase::ResetAndWait( ProfileResetter::ResettableFlags resettable_flags) { - scoped_ptr<BrandcodedDefaultSettings> master_settings( + std::unique_ptr<BrandcodedDefaultSettings> master_settings( new BrandcodedDefaultSettings); resetter_->Reset(resettable_flags, std::move(master_settings), base::Bind(&ProfileResetterMockObject::StopLoop, @@ -43,7 +43,7 @@ void ProfileResetterTestBase::ResetAndWait( ProfileResetter::ResettableFlags resettable_flags, const std::string& prefs) { - scoped_ptr<BrandcodedDefaultSettings> master_settings( + std::unique_ptr<BrandcodedDefaultSettings> master_settings( new BrandcodedDefaultSettings(prefs)); resetter_->Reset(resettable_flags, std::move(master_settings), base::Bind(&ProfileResetterMockObject::StopLoop,
diff --git a/chrome/browser/profile_resetter/profile_resetter_test_base.h b/chrome/browser/profile_resetter/profile_resetter_test_base.h index 29322d1..0cb6a76 100644 --- a/chrome/browser/profile_resetter/profile_resetter_test_base.h +++ b/chrome/browser/profile_resetter/profile_resetter_test_base.h
@@ -46,7 +46,7 @@ const std::string& prefs); protected: testing::StrictMock<ProfileResetterMockObject> mock_object_; - scoped_ptr<ProfileResetter> resetter_; + std::unique_ptr<ProfileResetter> resetter_; private: DISALLOW_COPY_AND_ASSIGN(ProfileResetterTestBase);
diff --git a/chrome/browser/profile_resetter/profile_resetter_unittest.cc b/chrome/browser/profile_resetter/profile_resetter_unittest.cc index 566b7884b..96a2c09 100644 --- a/chrome/browser/profile_resetter/profile_resetter_unittest.cc +++ b/chrome/browser/profile_resetter/profile_resetter_unittest.cc
@@ -5,10 +5,12 @@ #include "chrome/browser/profile_resetter/profile_resetter.h" #include <stddef.h> + +#include <memory> #include <utility> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_path_override.h" #include "build/build_config.h" @@ -117,7 +119,7 @@ TestingProfile* profile() { return profile_.get(); } - static scoped_ptr<KeyedService> CreateTemplateURLService( + static std::unique_ptr<KeyedService> CreateTemplateURLService( content::BrowserContext* context); private: @@ -154,15 +156,16 @@ } // static -scoped_ptr<KeyedService> ProfileResetterTest::CreateTemplateURLService( +std::unique_ptr<KeyedService> ProfileResetterTest::CreateTemplateURLService( content::BrowserContext* context) { Profile* profile = static_cast<Profile*>(context); - return make_scoped_ptr(new TemplateURLService( + return base::WrapUnique(new TemplateURLService( profile->GetPrefs(), - scoped_ptr<SearchTermsData>(new UIThreadSearchTermsData(profile)), + std::unique_ptr<SearchTermsData>(new UIThreadSearchTermsData(profile)), WebDataServiceFactory::GetKeywordWebDataForProfile( profile, ServiceAccessType::EXPLICIT_ACCESS), - scoped_ptr<TemplateURLServiceClient>(), NULL, NULL, base::Closure())); + std::unique_ptr<TemplateURLServiceClient>(), NULL, NULL, + base::Closure())); } @@ -221,12 +224,12 @@ ConfigParserTest(); virtual ~ConfigParserTest(); - scoped_ptr<BrandcodeConfigFetcher> WaitForRequest(const GURL& url); + std::unique_ptr<BrandcodeConfigFetcher> WaitForRequest(const GURL& url); net::FakeURLFetcherFactory& factory() { return factory_; } private: - scoped_ptr<net::FakeURLFetcher> CreateFakeURLFetcher( + std::unique_ptr<net::FakeURLFetcher> CreateFakeURLFetcher( const GURL& url, net::URLFetcherDelegate* fetcher_delegate, const std::string& response_data, @@ -251,14 +254,12 @@ ConfigParserTest::~ConfigParserTest() {} -scoped_ptr<BrandcodeConfigFetcher> ConfigParserTest::WaitForRequest( +std::unique_ptr<BrandcodeConfigFetcher> ConfigParserTest::WaitForRequest( const GURL& url) { EXPECT_CALL(*this, Callback()); - scoped_ptr<BrandcodeConfigFetcher> fetcher( - new BrandcodeConfigFetcher(base::Bind(&ConfigParserTest::Callback, - base::Unretained(this)), - url, - "ABCD")); + std::unique_ptr<BrandcodeConfigFetcher> fetcher(new BrandcodeConfigFetcher( + base::Bind(&ConfigParserTest::Callback, base::Unretained(this)), url, + "ABCD")); base::MessageLoop::current()->RunUntilIdle(); EXPECT_FALSE(fetcher->IsActive()); // Look for the brand code in the request. @@ -266,16 +267,15 @@ return fetcher; } -scoped_ptr<net::FakeURLFetcher> ConfigParserTest::CreateFakeURLFetcher( +std::unique_ptr<net::FakeURLFetcher> ConfigParserTest::CreateFakeURLFetcher( const GURL& url, net::URLFetcherDelegate* fetcher_delegate, const std::string& response_data, net::HttpStatusCode response_code, net::URLRequestStatus::Status status) { request_listener_.real_delegate = fetcher_delegate; - scoped_ptr<net::FakeURLFetcher> fetcher( - new net::FakeURLFetcher( - url, &request_listener_, response_data, response_code, status)); + std::unique_ptr<net::FakeURLFetcher> fetcher(new net::FakeURLFetcher( + url, &request_listener_, response_data, response_code, status)); scoped_refptr<net::HttpResponseHeaders> download_headers = new net::HttpResponseHeaders(""); download_headers->AddHeader("Content-Type: text/xml"); @@ -727,10 +727,10 @@ } TEST_F(PinnedTabsResetTest, ResetPinnedTabs) { - scoped_ptr<content::WebContents> contents1(CreateWebContents()); - scoped_ptr<content::WebContents> contents2(CreateWebContents()); - scoped_ptr<content::WebContents> contents3(CreateWebContents()); - scoped_ptr<content::WebContents> contents4(CreateWebContents()); + std::unique_ptr<content::WebContents> contents1(CreateWebContents()); + std::unique_ptr<content::WebContents> contents2(CreateWebContents()); + std::unique_ptr<content::WebContents> contents3(CreateWebContents()); + std::unique_ptr<content::WebContents> contents4(CreateWebContents()); TabStripModel* tab_strip_model = browser()->tab_strip_model(); tab_strip_model->AppendWebContents(contents4.get(), true); @@ -782,7 +782,7 @@ factory().SetFakeResponse(url, "", net::HTTP_INTERNAL_SERVER_ERROR, net::URLRequestStatus::FAILED); - scoped_ptr<BrandcodeConfigFetcher> fetcher = WaitForRequest(GURL(url)); + std::unique_ptr<BrandcodeConfigFetcher> fetcher = WaitForRequest(GURL(url)); EXPECT_FALSE(fetcher->GetSettings()); } @@ -797,8 +797,8 @@ factory().SetFakeResponse(url, xml_config, net::HTTP_OK, net::URLRequestStatus::SUCCESS); - scoped_ptr<BrandcodeConfigFetcher> fetcher = WaitForRequest(GURL(url)); - scoped_ptr<BrandcodedDefaultSettings> settings = fetcher->GetSettings(); + std::unique_ptr<BrandcodeConfigFetcher> fetcher = WaitForRequest(GURL(url)); + std::unique_ptr<BrandcodedDefaultSettings> settings = fetcher->GetSettings(); ASSERT_TRUE(settings); std::vector<std::string> extension_ids; @@ -810,7 +810,7 @@ EXPECT_TRUE(settings->GetHomepage(&homepage)); EXPECT_EQ("http://www.foo.com", homepage); - scoped_ptr<base::ListValue> startup_list( + std::unique_ptr<base::ListValue> startup_list( settings->GetUrlsToRestoreOnStartup()); EXPECT_TRUE(startup_list); std::vector<std::string> startup_pages; @@ -941,7 +941,7 @@ "this test needs to be expanded"); for (int field_mask = 0; field_mask <= ResettableSettingsSnapshot::ALL_FIELDS; ++field_mask) { - scoped_ptr<reset_report::ChromeResetReport> report = + std::unique_ptr<reset_report::ChromeResetReport> report = SerializeSettingsReportToProto(nonorganic_snap, field_mask); EXPECT_EQ(!!(field_mask & ResettableSettingsSnapshot::STARTUP_MODE), @@ -977,7 +977,7 @@ MOCK_METHOD0(OnUpdatedList, void(void)); - scoped_ptr<base::ListValue> list_; + std::unique_ptr<base::ListValue> list_; }; // Make sure GetReadableFeedback handles non-ascii letters. @@ -1020,7 +1020,7 @@ ::testing::Mock::VerifyAndClearExpectations(&capture); // The homepage and the startup page are in punycode. They are unreadable. // Trying to find the extension name. - scoped_ptr<base::ListValue> list = std::move(capture.list_); + std::unique_ptr<base::ListValue> list = std::move(capture.list_); ASSERT_TRUE(list); bool checked_extensions = false; bool checked_shortcuts = false; @@ -1048,7 +1048,7 @@ TEST_F(ProfileResetterTest, DestroySnapshotFast) { FeedbackCapture capture; - scoped_ptr<ResettableSettingsSnapshot> deleted_snapshot( + std::unique_ptr<ResettableSettingsSnapshot> deleted_snapshot( new ResettableSettingsSnapshot(profile())); deleted_snapshot->RequestShortcuts(base::Bind(&FeedbackCapture::Fail, base::Unretained(&capture)));
diff --git a/chrome/browser/profile_resetter/resettable_settings_snapshot.cc b/chrome/browser/profile_resetter/resettable_settings_snapshot.cc index 42c0187..f676734 100644 --- a/chrome/browser/profile_resetter/resettable_settings_snapshot.cc +++ b/chrome/browser/profile_resetter/resettable_settings_snapshot.cc
@@ -151,11 +151,11 @@ callback.Run(); } -scoped_ptr<reset_report::ChromeResetReport> SerializeSettingsReportToProto( +std::unique_ptr<reset_report::ChromeResetReport> SerializeSettingsReportToProto( const ResettableSettingsSnapshot& snapshot, int field_mask) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - scoped_ptr<reset_report::ChromeResetReport> report( + std::unique_ptr<reset_report::ChromeResetReport> report( new reset_report::ChromeResetReport()); if (field_mask & ResettableSettingsSnapshot::STARTUP_MODE) { @@ -213,12 +213,12 @@ ->DispatchReport(report); } -scoped_ptr<base::ListValue> GetReadableFeedbackForSnapshot( +std::unique_ptr<base::ListValue> GetReadableFeedbackForSnapshot( Profile* profile, const ResettableSettingsSnapshot& snapshot) { DCHECK(profile); DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - scoped_ptr<base::ListValue> list(new base::ListValue); + std::unique_ptr<base::ListValue> list(new base::ListValue); AddPair(list.get(), l10n_util::GetStringUTF16(IDS_RESET_PROFILE_SETTINGS_LOCALE), g_browser_process->GetApplicationLocale());
diff --git a/chrome/browser/profile_resetter/resettable_settings_snapshot.h b/chrome/browser/profile_resetter/resettable_settings_snapshot.h index fecaa4b..d857fa2 100644 --- a/chrome/browser/profile_resetter/resettable_settings_snapshot.h +++ b/chrome/browser/profile_resetter/resettable_settings_snapshot.h
@@ -5,12 +5,12 @@ #ifndef CHROME_BROWSER_PROFILE_RESETTER_RESETTABLE_SETTINGS_SNAPSHOT_H_ #define CHROME_BROWSER_PROFILE_RESETTER_RESETTABLE_SETTINGS_SNAPSHOT_H_ +#include <memory> #include <string> #include <utility> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/strings/string_split.h" #include "chrome/browser/prefs/session_startup_pref.h" @@ -125,7 +125,7 @@ // Serializes specified |snapshot| members to a protobuf. |field_mask| is a bit // mask of ResettableSettingsSnapshot::Field values. -scoped_ptr<reset_report::ChromeResetReport> SerializeSettingsReportToProto( +std::unique_ptr<reset_report::ChromeResetReport> SerializeSettingsReportToProto( const ResettableSettingsSnapshot& snapshot, int field_mask); @@ -136,7 +136,7 @@ // Returns list of key/value pairs for all available reported information // from the |profile| and some additional fields. -scoped_ptr<base::ListValue> GetReadableFeedbackForSnapshot( +std::unique_ptr<base::ListValue> GetReadableFeedbackForSnapshot( Profile* profile, const ResettableSettingsSnapshot& snapshot);
diff --git a/chrome/browser/profile_resetter/triggered_profile_resetter_win_unittest.cc b/chrome/browser/profile_resetter/triggered_profile_resetter_win_unittest.cc index 8ff5ef7..0d1780f 100644 --- a/chrome/browser/profile_resetter/triggered_profile_resetter_win_unittest.cc +++ b/chrome/browser/profile_resetter/triggered_profile_resetter_win_unittest.cc
@@ -6,8 +6,9 @@ #include <stdint.h> +#include <memory> + #include "base/bit_cast.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/field_trial.h" #include "base/test/test_reg_util_win.h" #include "base/win/registry.h" @@ -55,7 +56,7 @@ private: registry_util::RegistryOverrideManager override_manager_; - scoped_ptr<base::FieldTrialList> field_trial_list_; + std::unique_ptr<base::FieldTrialList> field_trial_list_; }; TEST_F(TriggeredProfileResetterTest, HasResetTriggerAndClear) {
diff --git a/chrome/browser/push_messaging/push_messaging_browsertest.cc b/chrome/browser/push_messaging/push_messaging_browsertest.cc index ba9a28e..2501473 100644 --- a/chrome/browser/push_messaging/push_messaging_browsertest.cc +++ b/chrome/browser/push_messaging/push_messaging_browsertest.cc
@@ -241,12 +241,12 @@ virtual Browser* GetBrowser() const { return browser(); } private: - scoped_ptr<net::EmbeddedTestServer> https_server_; + std::unique_ptr<net::EmbeddedTestServer> https_server_; gcm::FakeGCMProfileService* gcm_service_; PushMessagingServiceImpl* push_service_; #if defined(ENABLE_NOTIFICATIONS) - scoped_ptr<StubNotificationUIManager> notification_manager_; + std::unique_ptr<StubNotificationUIManager> notification_manager_; #endif DISALLOW_COPY_AND_ASSIGN(PushMessagingBrowserTest);
diff --git a/chrome/browser/push_messaging/push_messaging_service_factory.cc b/chrome/browser/push_messaging/push_messaging_service_factory.cc index 44e1424..24d667d 100644 --- a/chrome/browser/push_messaging/push_messaging_service_factory.cc +++ b/chrome/browser/push_messaging/push_messaging_service_factory.cc
@@ -4,7 +4,8 @@ #include "chrome/browser/push_messaging/push_messaging_service_factory.h" -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/permissions/permission_manager_factory.h" #include "chrome/browser/profiles/incognito_helpers.h" @@ -47,7 +48,7 @@ void PushMessagingServiceFactory::RestoreFactoryForTests( content::BrowserContext* context) { SetTestingFactory(context, [](content::BrowserContext* context) { - return scoped_ptr<KeyedService>( + return std::unique_ptr<KeyedService>( GetInstance()->BuildServiceInstanceFor(context)); }); }
diff --git a/chrome/browser/push_messaging/push_messaging_service_impl.h b/chrome/browser/push_messaging/push_messaging_service_impl.h index 34354806..2b0a3b7 100644 --- a/chrome/browser/push_messaging/push_messaging_service_impl.h +++ b/chrome/browser/push_messaging/push_messaging_service_impl.h
@@ -6,6 +6,8 @@ #define CHROME_BROWSER_PUSH_MESSAGING_PUSH_MESSAGING_SERVICE_IMPL_H_ #include <stdint.h> + +#include <memory> #include <set> #include <vector> @@ -13,7 +15,6 @@ #include "base/compiler_specific.h" #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/background/background_trigger.h" #include "components/content_settings/core/browser/content_settings_observer.h" @@ -240,7 +241,8 @@ MessageDispatchedCallback message_dispatched_callback_for_testing_; - scoped_ptr<PushMessagingServiceObserver> push_messaging_service_observer_; + std::unique_ptr<PushMessagingServiceObserver> + push_messaging_service_observer_; base::WeakPtrFactory<PushMessagingServiceImpl> weak_factory_;
diff --git a/chrome/browser/push_messaging/push_messaging_service_observer.cc b/chrome/browser/push_messaging/push_messaging_service_observer.cc index 5c5c23cf..bcd4ed0cc 100644 --- a/chrome/browser/push_messaging/push_messaging_service_observer.cc +++ b/chrome/browser/push_messaging/push_messaging_service_observer.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/push_messaging/push_messaging_service_observer.h" +#include "base/memory/ptr_util.h" #include "build/build_config.h" #if defined(OS_ANDROID) @@ -11,10 +12,10 @@ #endif // static -scoped_ptr<PushMessagingServiceObserver> +std::unique_ptr<PushMessagingServiceObserver> PushMessagingServiceObserver::Create() { #if defined(OS_ANDROID) - return make_scoped_ptr(new PushMessagingServiceObserverAndroid()); + return base::WrapUnique(new PushMessagingServiceObserverAndroid()); #endif return nullptr; }
diff --git a/chrome/browser/push_messaging/push_messaging_service_observer.h b/chrome/browser/push_messaging/push_messaging_service_observer.h index 80d841d9..0d1ed78c 100644 --- a/chrome/browser/push_messaging/push_messaging_service_observer.h +++ b/chrome/browser/push_messaging/push_messaging_service_observer.h
@@ -5,13 +5,13 @@ #ifndef CHROME_BROWSER_PUSH_MESSAGING_PUSH_MESSAGING_SERVICE_OBSERVER_H_ #define CHROME_BROWSER_PUSH_MESSAGING_PUSH_MESSAGING_SERVICE_OBSERVER_H_ -#include "base/memory/scoped_ptr.h" +#include <memory> // Observes events and changes in the PushMessagingService. class PushMessagingServiceObserver { public: // Creates a new PushMessagingServiceObserver. - static scoped_ptr<PushMessagingServiceObserver> Create(); + static std::unique_ptr<PushMessagingServiceObserver> Create(); // Called when a push message has been fully handled. virtual void OnMessageHandled() = 0;
diff --git a/chrome/browser/push_messaging/push_messaging_service_unittest.cc b/chrome/browser/push_messaging/push_messaging_service_unittest.cc index 303966f4..fb3e4e3 100644 --- a/chrome/browser/push_messaging/push_messaging_service_unittest.cc +++ b/chrome/browser/push_messaging/push_messaging_service_unittest.cc
@@ -75,8 +75,7 @@ DISALLOW_COPY_AND_ASSIGN(PushMessagingTestingProfile); }; - -scoped_ptr<KeyedService> BuildFakeGCMProfileService( +std::unique_ptr<KeyedService> BuildFakeGCMProfileService( content::BrowserContext* context) { return gcm::FakeGCMProfileService::Build(static_cast<Profile*>(context)); }
diff --git a/chrome/browser/referrer_policy_browsertest.cc b/chrome/browser/referrer_policy_browsertest.cc index 5a43346..7f343250 100644 --- a/chrome/browser/referrer_policy_browsertest.cc +++ b/chrome/browser/referrer_policy_browsertest.cc
@@ -491,7 +491,7 @@ GetExpectedTitle(start_url, EXPECT_ORIGIN_AS_REFERRER); content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); - scoped_ptr<content::TitleWatcher> title_watcher( + std::unique_ptr<content::TitleWatcher> title_watcher( new content::TitleWatcher(tab, expected_title)); // Watch for all possible outcomes to avoid timeouts if something breaks. @@ -547,7 +547,7 @@ content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); base::string16 expected_title(base::ASCIIToUTF16("loaded")); - scoped_ptr<content::TitleWatcher> title_watcher( + std::unique_ptr<content::TitleWatcher> title_watcher( new content::TitleWatcher(tab, expected_title)); // Load a page that loads an iframe.
diff --git a/chrome/browser/renderer_context_menu/context_menu_content_type_unittest.cc b/chrome/browser/renderer_context_menu/context_menu_content_type_unittest.cc index 92ef86dc..8982777 100644 --- a/chrome/browser/renderer_context_menu/context_menu_content_type_unittest.cc +++ b/chrome/browser/renderer_context_menu/context_menu_content_type_unittest.cc
@@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "base/strings/utf_string_conversions.h" -#include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h" #include "chrome/browser/renderer_context_menu/context_menu_content_type_factory.h" +#include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "components/renderer_context_menu/context_menu_content_type.h" #include "testing/gtest/include/gtest/gtest.h" @@ -66,8 +67,8 @@ TEST_F(ContextMenuContentTypeTest, CheckTypes) { { content::ContextMenuParams params = CreateParams(MenuItem::LINK); - scoped_ptr<ContextMenuContentType> content_type(Create(web_contents(), - params)); + std::unique_ptr<ContextMenuContentType> content_type( + Create(web_contents(), params)); EXPECT_TRUE(content_type->SupportsGroup( ContextMenuContentType::ITEM_GROUP_LINK)); EXPECT_TRUE(content_type->SupportsGroup( @@ -78,8 +79,8 @@ { content::ContextMenuParams params = CreateParams(MenuItem::SELECTION); - scoped_ptr<ContextMenuContentType> content_type(Create(web_contents(), - params)); + std::unique_ptr<ContextMenuContentType> content_type( + Create(web_contents(), params)); EXPECT_FALSE(content_type->SupportsGroup( ContextMenuContentType::ITEM_GROUP_LINK)); EXPECT_TRUE(content_type->SupportsGroup( @@ -92,8 +93,8 @@ { content::ContextMenuParams params = CreateParams(MenuItem::EDITABLE); - scoped_ptr<ContextMenuContentType> content_type(Create(web_contents(), - params)); + std::unique_ptr<ContextMenuContentType> content_type( + Create(web_contents(), params)); EXPECT_FALSE(content_type->SupportsGroup( ContextMenuContentType::ITEM_GROUP_LINK)); EXPECT_FALSE(content_type->SupportsGroup( @@ -104,8 +105,8 @@ { content::ContextMenuParams params = CreateParams(MenuItem::IMAGE); - scoped_ptr<ContextMenuContentType> content_type(Create(web_contents(), - params)); + std::unique_ptr<ContextMenuContentType> content_type( + Create(web_contents(), params)); EXPECT_TRUE(content_type->SupportsGroup( ContextMenuContentType::ITEM_GROUP_MEDIA_IMAGE)); EXPECT_TRUE(content_type->SupportsGroup( @@ -123,8 +124,8 @@ { content::ContextMenuParams params = CreateParams(MenuItem::VIDEO); - scoped_ptr<ContextMenuContentType> content_type(Create(web_contents(), - params)); + std::unique_ptr<ContextMenuContentType> content_type( + Create(web_contents(), params)); EXPECT_TRUE(content_type->SupportsGroup( ContextMenuContentType::ITEM_GROUP_MEDIA_VIDEO)); @@ -138,8 +139,8 @@ { content::ContextMenuParams params = CreateParams(MenuItem::AUDIO); - scoped_ptr<ContextMenuContentType> content_type(Create(web_contents(), - params)); + std::unique_ptr<ContextMenuContentType> content_type( + Create(web_contents(), params)); EXPECT_TRUE(content_type->SupportsGroup( ContextMenuContentType::ITEM_GROUP_MEDIA_AUDIO)); @@ -153,8 +154,8 @@ { content::ContextMenuParams params = CreateParams(MenuItem::FRAME); - scoped_ptr<ContextMenuContentType> content_type(Create(web_contents(), - params)); + std::unique_ptr<ContextMenuContentType> content_type( + Create(web_contents(), params)); EXPECT_TRUE(content_type->SupportsGroup( ContextMenuContentType::ITEM_GROUP_FRAME)); EXPECT_TRUE(content_type->SupportsGroup(
diff --git a/chrome/browser/renderer_context_menu/mock_render_view_context_menu.h b/chrome/browser/renderer_context_menu/mock_render_view_context_menu.h index a8f8a7b..c172e245 100644 --- a/chrome/browser/renderer_context_menu/mock_render_view_context_menu.h +++ b/chrome/browser/renderer_context_menu/mock_render_view_context_menu.h
@@ -6,10 +6,10 @@ #define CHROME_BROWSER_RENDERER_CONTEXT_MENU_MOCK_RENDER_VIEW_CONTEXT_MENU_H_ #include <cstddef> +#include <memory> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "components/renderer_context_menu/render_view_context_menu_proxy.h" #include "ui/base/models/simple_menu_model.h" @@ -85,7 +85,7 @@ // A dummy profile used in this test. Call GetPrefs() when a test needs to // change this profile and use PrefService methods. - scoped_ptr<TestingProfile> original_profile_; + std::unique_ptr<TestingProfile> original_profile_; // Either |original_profile_| or its incognito profile. Profile* profile_;
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu.cc b/chrome/browser/renderer_context_menu/render_view_context_menu.cc index 85082a5f..fb8c862 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu.cc
@@ -1805,7 +1805,7 @@ content::Referrer referrer = CreateReferrer(url, params_); DownloadManager* dlm = BrowserContext::GetDownloadManager(browser_context_); - scoped_ptr<DownloadUrlParameters> dl_params( + std::unique_ptr<DownloadUrlParameters> dl_params( DownloadUrlParameters::FromWebContents(source_web_contents_, url)); dl_params->set_referrer(referrer); dl_params->set_referrer_encoding(params_.frame_charset); @@ -2075,7 +2075,7 @@ translate::TranslateDownloadManager::GetLanguageCode(target_lang); // Since the user decided to translate for that language and site, clears // any preferences for not translating them. - scoped_ptr<translate::TranslatePrefs> prefs( + std::unique_ptr<translate::TranslatePrefs> prefs( ChromeTranslateClient::CreateTranslatePrefs( GetPrefs(browser_context_))); prefs->UnblockLanguage(original_lang);
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu.h b/chrome/browser/renderer_context_menu/render_view_context_menu.h index 43b95e5..6e09d73 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu.h +++ b/chrome/browser/renderer_context_menu/render_view_context_menu.h
@@ -6,11 +6,11 @@ #define CHROME_BROWSER_RENDERER_CONTEXT_MENU_RENDER_VIEW_CONTEXT_MENU_H_ #include <map> +#include <memory> #include <string> #include <vector> #include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" #include "base/observer_list.h" #include "base/strings/string16.h" #include "chrome/browser/custom_handlers/protocol_handler_registry.h" @@ -184,17 +184,18 @@ // An observer that handles spelling suggestions, "Add to dictionary", and // "Ask Google for suggestions" items. - scoped_ptr<SpellingMenuObserver> spelling_suggestions_menu_observer_; + std::unique_ptr<SpellingMenuObserver> spelling_suggestions_menu_observer_; #if !defined(OS_MACOSX) // An observer that handles the submenu for showing spelling options. This // submenu lets users select the spelling language, for example. - scoped_ptr<SpellingOptionsSubMenuObserver> spelling_options_submenu_observer_; + std::unique_ptr<SpellingOptionsSubMenuObserver> + spelling_options_submenu_observer_; #endif #if defined(ENABLE_PRINT_PREVIEW) // An observer that disables menu items when print preview is active. - scoped_ptr<PrintPreviewContextMenuObserver> print_preview_menu_observer_; + std::unique_ptr<PrintPreviewContextMenuObserver> print_preview_menu_observer_; #endif // In the case of a MimeHandlerView this will point to the WebContents that
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc b/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc index 14e0ed5..6e3270c 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/renderer_context_menu/render_view_context_menu.h" #include <algorithm> +#include <memory> #include <string> #include <utility> #include <vector> @@ -13,7 +14,6 @@ #include "base/command_line.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -65,7 +65,7 @@ ContextMenuBrowserTest() {} protected: - scoped_ptr<TestRenderViewContextMenu> CreateContextMenuMediaTypeNone( + std::unique_ptr<TestRenderViewContextMenu> CreateContextMenuMediaTypeNone( const GURL& unfiltered_url, const GURL& url) { return CreateContextMenu(unfiltered_url, url, base::string16(), @@ -73,14 +73,14 @@ ui::MENU_SOURCE_NONE); } - scoped_ptr<TestRenderViewContextMenu> CreateContextMenuMediaTypeImage( + std::unique_ptr<TestRenderViewContextMenu> CreateContextMenuMediaTypeImage( const GURL& url) { return CreateContextMenu(GURL(), url, base::string16(), blink::WebContextMenuData::MediaTypeImage, ui::MENU_SOURCE_NONE); } - scoped_ptr<TestRenderViewContextMenu> CreateContextMenu( + std::unique_ptr<TestRenderViewContextMenu> CreateContextMenu( const GURL& unfiltered_url, const GURL& url, const base::string16& link_text, @@ -101,7 +101,7 @@ params.writing_direction_left_to_right = 0; params.writing_direction_right_to_left = 0; #endif // OS_MACOSX - scoped_ptr<TestRenderViewContextMenu> menu( + std::unique_ptr<TestRenderViewContextMenu> menu( new TestRenderViewContextMenu(web_contents->GetMainFrame(), params)); menu->Init(); return menu; @@ -119,8 +119,9 @@ IN_PROC_BROWSER_TEST_F(ContextMenuBrowserTest, OpenEntryPresentForNormalURLs) { - scoped_ptr<TestRenderViewContextMenu> menu = CreateContextMenuMediaTypeNone( - GURL("http://www.google.com/"), GURL("http://www.google.com/")); + std::unique_ptr<TestRenderViewContextMenu> menu = + CreateContextMenuMediaTypeNone(GURL("http://www.google.com/"), + GURL("http://www.google.com/")); ASSERT_TRUE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKNEWTAB)); ASSERT_TRUE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKNEWWINDOW)); @@ -132,7 +133,7 @@ IN_PROC_BROWSER_TEST_F(ContextMenuBrowserTest, OpenEntryAbsentForFilteredURLs) { - scoped_ptr<TestRenderViewContextMenu> menu = + std::unique_ptr<TestRenderViewContextMenu> menu = CreateContextMenuMediaTypeNone(GURL("chrome://history"), GURL()); ASSERT_FALSE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKNEWTAB)); @@ -157,7 +158,7 @@ } IN_PROC_BROWSER_TEST_F(ContextMenuBrowserTest, CopyLinkTextMouse) { - scoped_ptr<TestRenderViewContextMenu> menu = CreateContextMenu( + std::unique_ptr<TestRenderViewContextMenu> menu = CreateContextMenu( GURL("http://www.google.com/"), GURL("http://www.google.com/"), base::ASCIIToUTF16("Google"), blink::WebContextMenuData::MediaTypeNone, ui::MENU_SOURCE_MOUSE); @@ -166,7 +167,7 @@ } IN_PROC_BROWSER_TEST_F(ContextMenuBrowserTest, CopyLinkTextTouchNoText) { - scoped_ptr<TestRenderViewContextMenu> menu = CreateContextMenu( + std::unique_ptr<TestRenderViewContextMenu> menu = CreateContextMenu( GURL("http://www.google.com/"), GURL("http://www.google.com/"), base::ASCIIToUTF16(""), blink::WebContextMenuData::MediaTypeNone, ui::MENU_SOURCE_TOUCH); @@ -175,7 +176,7 @@ } IN_PROC_BROWSER_TEST_F(ContextMenuBrowserTest, CopyLinkTextTouchTextOnly) { - scoped_ptr<TestRenderViewContextMenu> menu = CreateContextMenu( + std::unique_ptr<TestRenderViewContextMenu> menu = CreateContextMenu( GURL("http://www.google.com/"), GURL("http://www.google.com/"), base::ASCIIToUTF16("Google"), blink::WebContextMenuData::MediaTypeNone, ui::MENU_SOURCE_TOUCH); @@ -184,7 +185,7 @@ } IN_PROC_BROWSER_TEST_F(ContextMenuBrowserTest, CopyLinkTextTouchTextImage) { - scoped_ptr<TestRenderViewContextMenu> menu = CreateContextMenu( + std::unique_ptr<TestRenderViewContextMenu> menu = CreateContextMenu( GURL("http://www.google.com/"), GURL("http://www.google.com/"), base::ASCIIToUTF16("Google"), blink::WebContextMenuData::MediaTypeImage, ui::MENU_SOURCE_TOUCH); @@ -394,7 +395,7 @@ command_line->AppendSwitch( data_reduction_proxy::switches::kEnableDataReductionProxy); - scoped_ptr<TestRenderViewContextMenu> menu = + std::unique_ptr<TestRenderViewContextMenu> menu = CreateContextMenuMediaTypeImage(GURL("http://url.com/image.png")); ASSERT_FALSE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENIMAGENEWTAB)); @@ -408,7 +409,7 @@ command_line->AppendSwitch( data_reduction_proxy::switches::kEnableDataReductionProxy); - scoped_ptr<TestRenderViewContextMenu> menu = + std::unique_ptr<TestRenderViewContextMenu> menu = CreateContextMenuMediaTypeImage(GURL("https://url.com/image.png")); ASSERT_FALSE( @@ -417,7 +418,7 @@ } IN_PROC_BROWSER_TEST_F(ContextMenuBrowserTest, OpenImageInNewTab) { - scoped_ptr<TestRenderViewContextMenu> menu = + std::unique_ptr<TestRenderViewContextMenu> menu = CreateContextMenuMediaTypeImage(GURL("http://url.com/image.png")); ASSERT_FALSE( menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPEN_ORIGINAL_IMAGE_NEW_TAB)); @@ -428,8 +429,9 @@ #if !defined(OS_CHROMEOS) IN_PROC_BROWSER_TEST_F(ContextMenuBrowserTest, OpenLinkInProfileEntryPresent) { { - scoped_ptr<TestRenderViewContextMenu> menu(CreateContextMenuMediaTypeNone( - GURL("http://www.google.com/"), GURL("http://www.google.com/"))); + std::unique_ptr<TestRenderViewContextMenu> menu( + CreateContextMenuMediaTypeNone(GURL("http://www.google.com/"), + GURL("http://www.google.com/"))); ASSERT_TRUE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKNEWTAB)); ASSERT_TRUE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKNEWWINDOW)); @@ -445,8 +447,9 @@ CreateSecondaryProfile(1); { - scoped_ptr<TestRenderViewContextMenu> menu(CreateContextMenuMediaTypeNone( - GURL("http://www.google.com/"), GURL("http://www.google.com/"))); + std::unique_ptr<TestRenderViewContextMenu> menu( + CreateContextMenuMediaTypeNone(GURL("http://www.google.com/"), + GURL("http://www.google.com/"))); ASSERT_TRUE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKNEWTAB)); ASSERT_TRUE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKNEWWINDOW)); @@ -460,8 +463,9 @@ CreateSecondaryProfile(2); { - scoped_ptr<TestRenderViewContextMenu> menu(CreateContextMenuMediaTypeNone( - GURL("http://www.google.com/"), GURL("http://www.google.com/"))); + std::unique_ptr<TestRenderViewContextMenu> menu( + CreateContextMenuMediaTypeNone(GURL("http://www.google.com/"), + GURL("http://www.google.com/"))); ASSERT_TRUE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKNEWTAB)); ASSERT_TRUE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_OPENLINKNEWWINDOW)); @@ -522,7 +526,7 @@ ASSERT_TRUE(embedded_test_server()->Start()); GURL url(embedded_test_server()->GetURL("/")); - scoped_ptr<TestRenderViewContextMenu> menu( + std::unique_ptr<TestRenderViewContextMenu> menu( CreateContextMenuMediaTypeNone(url, url)); // Verify that the size of the menu is correct. @@ -697,7 +701,7 @@ menu_observer_.reset(); } - scoped_ptr<ContextMenuNotificationObserver> menu_observer_; + std::unique_ptr<ContextMenuNotificationObserver> menu_observer_; }; IN_PROC_BROWSER_TEST_F(SearchByImageBrowserTest, ImageSearchWithValidImage) { @@ -787,7 +791,7 @@ // These are only used on the UI thread. int num_requests_; int requests_to_wait_for_; - scoped_ptr<base::RunLoop> run_loop_; + std::unique_ptr<base::RunLoop> run_loop_; // This prevents any risk of flake if any test doesn't wait for a request // it sent. Mutable so it can be accessed from a const function. @@ -809,7 +813,7 @@ void AddLoadImageInterceptor(const std::string& image_path) { interceptor_ = new LoadImageRequestInterceptor(); - scoped_ptr<net::URLRequestInterceptor> owned_interceptor(interceptor_); + std::unique_ptr<net::URLRequestInterceptor> owned_interceptor(interceptor_); content::BrowserThread::PostTask( content::BrowserThread::IO, FROM_HERE, base::Bind(&LoadImageBrowserTest::AddInterceptorForURL, @@ -830,7 +834,8 @@ } void AddInterceptorForURL( - const GURL& url, scoped_ptr<net::URLRequestInterceptor> handler) { + const GURL& url, + std::unique_ptr<net::URLRequestInterceptor> handler) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); net::URLRequestFilter::GetInstance()->AddUrlInterceptor(url, std::move(handler)); @@ -839,7 +844,7 @@ LoadImageRequestInterceptor* interceptor_; private: - scoped_ptr<ContextMenuNotificationObserver> menu_observer_; + std::unique_ptr<ContextMenuNotificationObserver> menu_observer_; }; IN_PROC_BROWSER_TEST_F(LoadImageBrowserTest, LoadImage) {
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu_unittest.cc b/chrome/browser/renderer_context_menu/render_view_context_menu_unittest.cc index d841f65..87df18b 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu_unittest.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu_unittest.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/renderer_context_menu/render_view_context_menu.h" +#include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/thread_task_runner_handle.h" @@ -30,7 +31,6 @@ #include "content/public/browser/web_contents.h" #include "content/public/test/test_renderer_host.h" #include "content/public/test/web_contents_tester.h" - #include "extensions/browser/extension_prefs.h" #include "extensions/common/url_pattern.h" #include "testing/gtest/include/gtest/gtest.h" @@ -84,13 +84,13 @@ } // Returns a test context menu. -scoped_ptr<TestRenderViewContextMenu> CreateContextMenu( +std::unique_ptr<TestRenderViewContextMenu> CreateContextMenu( content::WebContents* web_contents, ProtocolHandlerRegistry* registry) { content::ContextMenuParams params = CreateParams(MenuItem::LINK); params.unfiltered_link_url = params.link_url; - scoped_ptr<TestRenderViewContextMenu> menu(new TestRenderViewContextMenu( - web_contents->GetMainFrame(), params)); + std::unique_ptr<TestRenderViewContextMenu> menu( + new TestRenderViewContextMenu(web_contents->GetMainFrame(), params)); menu->set_protocol_handler_registry(registry); menu->Init(); return menu; @@ -321,7 +321,7 @@ protected: extensions::TestExtensionEnvironment environment_; - scoped_ptr<ProtocolHandlerRegistry> registry_; + std::unique_ptr<ProtocolHandlerRegistry> registry_; DISALLOW_COPY_AND_ASSIGN(RenderViewContextMenuExtensionsTest); }; @@ -345,8 +345,8 @@ MenuItem* item2 = CreateTestItem(extension2, 2); ASSERT_TRUE(menu_manager->AddContextItem(extension2, item2)); - scoped_ptr<content::WebContents> web_contents = environment().MakeTab(); - scoped_ptr<TestRenderViewContextMenu> menu( + std::unique_ptr<content::WebContents> web_contents = environment().MakeTab(); + std::unique_ptr<TestRenderViewContextMenu> menu( CreateContextMenu(web_contents.get(), registry_.get())); const ui::MenuModel& model = menu->menu_model(); @@ -375,7 +375,7 @@ ChromeRenderViewHostTestHarness::TearDown(); } - scoped_ptr<TestRenderViewContextMenu> CreateContextMenu() { + std::unique_ptr<TestRenderViewContextMenu> CreateContextMenu() { return ::CreateContextMenu(web_contents(), registry_.get()); } @@ -411,7 +411,7 @@ settings->InitDataReductionProxySettings( drp_test_context_->io_data(), drp_test_context_->pref_service(), drp_test_context_->request_context_getter(), - make_scoped_ptr(new data_reduction_proxy::DataStore()), + base::WrapUnique(new data_reduction_proxy::DataStore()), base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get()); } @@ -427,11 +427,11 @@ } protected: - scoped_ptr<data_reduction_proxy::DataReductionProxyTestContext> + std::unique_ptr<data_reduction_proxy::DataReductionProxyTestContext> drp_test_context_; private: - scoped_ptr<ProtocolHandlerRegistry> registry_; + std::unique_ptr<ProtocolHandlerRegistry> registry_; DISALLOW_COPY_AND_ASSIGN(RenderViewContextMenuPrefsTest); }; @@ -440,7 +440,7 @@ // Open Link in Incognito Window link in the context menu is disabled. TEST_F(RenderViewContextMenuPrefsTest, DisableOpenInIncognitoWindowWhenIncognitoIsDisabled) { - scoped_ptr<TestRenderViewContextMenu> menu(CreateContextMenu()); + std::unique_ptr<TestRenderViewContextMenu> menu(CreateContextMenu()); // Initially the Incognito mode is be enabled. So is the Open Link in // Incognito Window link. @@ -461,7 +461,7 @@ // cause DCHECK failure. TEST_F(RenderViewContextMenuPrefsTest, IsCustomCommandIdEnabled) { - scoped_ptr<TestRenderViewContextMenu> menu(CreateContextMenu()); + std::unique_ptr<TestRenderViewContextMenu> menu(CreateContextMenu()); EXPECT_FALSE(menu->IsCommandIdEnabled(IDC_CONTENT_CONTEXT_CUSTOM_FIRST)); } @@ -475,7 +475,7 @@ content::ContextMenuParams params = CreateParams(MenuItem::IMAGE); params.unfiltered_link_url = params.link_url; content::WebContents* wc = web_contents(); - scoped_ptr<TestRenderViewContextMenu> menu( + std::unique_ptr<TestRenderViewContextMenu> menu( new TestRenderViewContextMenu(wc->GetMainFrame(), params)); menu->ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS, 0); @@ -496,7 +496,7 @@ content::ContextMenuParams params = CreateParams(MenuItem::IMAGE); params.unfiltered_link_url = params.link_url; content::WebContents* wc = web_contents(); - scoped_ptr<TestRenderViewContextMenu> menu( + std::unique_ptr<TestRenderViewContextMenu> menu( new TestRenderViewContextMenu(wc->GetMainFrame(), params)); menu->ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS, 0); @@ -518,7 +518,7 @@ data_reduction_proxy::chrome_proxy_lo_fi_directive(); params.unfiltered_link_url = params.link_url; content::WebContents* wc = web_contents(); - scoped_ptr<TestRenderViewContextMenu> menu( + std::unique_ptr<TestRenderViewContextMenu> menu( new TestRenderViewContextMenu(wc->GetMainFrame(), params)); AppendImageItems(menu.get());
diff --git a/chrome/browser/renderer_context_menu/spelling_menu_observer.cc b/chrome/browser/renderer_context_menu/spelling_menu_observer.cc index 9838234f..b0c5757 100644 --- a/chrome/browser/renderer_context_menu/spelling_menu_observer.cc +++ b/chrome/browser/renderer_context_menu/spelling_menu_observer.cc
@@ -286,7 +286,7 @@ if (!integrate_spelling_service_.GetValue()) { content::RenderViewHost* rvh = proxy_->GetRenderViewHost(); gfx::Rect rect = rvh->GetWidget()->GetView()->GetViewBounds(); - scoped_ptr<SpellingBubbleModel> model( + std::unique_ptr<SpellingBubbleModel> model( new SpellingBubbleModel(profile, proxy_->GetWebContents())); chrome::ShowConfirmBubble( proxy_->GetWebContents()->GetTopLevelNativeWindow(),
diff --git a/chrome/browser/renderer_context_menu/spelling_menu_observer.h b/chrome/browser/renderer_context_menu/spelling_menu_observer.h index dac20994..0b4cc0a 100644 --- a/chrome/browser/renderer_context_menu/spelling_menu_observer.h +++ b/chrome/browser/renderer_context_menu/spelling_menu_observer.h
@@ -8,11 +8,11 @@ #include <stddef.h> #include <stdint.h> +#include <memory> #include <vector> #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "base/timer/timer.h" #include "chrome/browser/spellchecker/spelling_service_client.h" @@ -105,7 +105,7 @@ base::string16 result_; // The URLFetcher object used for sending a JSON-RPC request. - scoped_ptr<SpellingServiceClient> client_; + std::unique_ptr<SpellingServiceClient> client_; // A timer used for loading animation. base::RepeatingTimer animation_timer_;
diff --git a/chrome/browser/renderer_context_menu/spelling_menu_observer_browsertest.cc b/chrome/browser/renderer_context_menu/spelling_menu_observer_browsertest.cc index ffde1c0c..700fb55 100644 --- a/chrome/browser/renderer_context_menu/spelling_menu_observer_browsertest.cc +++ b/chrome/browser/renderer_context_menu/spelling_menu_observer_browsertest.cc
@@ -65,8 +65,8 @@ MockRenderViewContextMenu* menu() { return menu_.get(); } SpellingMenuObserver* observer() { return observer_.get(); } private: - scoped_ptr<SpellingMenuObserver> observer_; - scoped_ptr<MockRenderViewContextMenu> menu_; + std::unique_ptr<SpellingMenuObserver> observer_; + std::unique_ptr<MockRenderViewContextMenu> menu_; DISALLOW_COPY_AND_ASSIGN(SpellingMenuObserverTest); };
diff --git a/chrome/browser/renderer_context_menu/spelling_options_submenu_observer_browsertest.cc b/chrome/browser/renderer_context_menu/spelling_options_submenu_observer_browsertest.cc index efa14de..5166a59 100644 --- a/chrome/browser/renderer_context_menu/spelling_options_submenu_observer_browsertest.cc +++ b/chrome/browser/renderer_context_menu/spelling_options_submenu_observer_browsertest.cc
@@ -4,7 +4,8 @@ #include "chrome/browser/renderer_context_menu/spelling_options_submenu_observer.h" -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "base/values.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/renderer_context_menu/mock_render_view_context_menu.h" @@ -62,8 +63,8 @@ SpellingOptionsSubMenuObserver* observer() { return observer_.get(); } private: - scoped_ptr<MockRenderViewContextMenu> menu_; - scoped_ptr<SpellingOptionsSubMenuObserver> observer_; + std::unique_ptr<MockRenderViewContextMenu> menu_; + std::unique_ptr<SpellingOptionsSubMenuObserver> observer_; DISALLOW_COPY_AND_ASSIGN(SpellingOptionsSubMenuObserverTest); };
diff --git a/chrome/browser/renderer_host/chrome_extension_message_filter.cc b/chrome/browser/renderer_host/chrome_extension_message_filter.cc index 59412fc..1b00ed43 100644 --- a/chrome/browser/renderer_host/chrome_extension_message_filter.cc +++ b/chrome/browser/renderer_host/chrome_extension_message_filter.cc
@@ -10,6 +10,7 @@ #include "base/bind_helpers.h" #include "base/files/file_path.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" @@ -276,7 +277,7 @@ const extensions::ExtensionSet& extension_set = extension_info_map_->extensions(); - scoped_ptr<extensions::MessageBundle::SubstitutionMap> dictionary_map( + std::unique_ptr<extensions::MessageBundle::SubstitutionMap> dictionary_map( extensions::file_util::LoadMessageBundleSubstitutionMapWithImports( extension_id, extension_set)); @@ -291,7 +292,7 @@ scoped_refptr<extensions::Action> action = new extensions::Action( extension_id, base::Time::Now(), extensions::Action::ACTION_API_CALL, params.api_call); - action->set_args(make_scoped_ptr(params.arguments.DeepCopy())); + action->set_args(base::WrapUnique(params.arguments.DeepCopy())); if (!params.extra.empty()) { action->mutable_other()->SetString( activity_log_constants::kActionExtra, params.extra); @@ -305,7 +306,7 @@ scoped_refptr<extensions::Action> action = new extensions::Action( extension_id, base::Time::Now(), extensions::Action::ACTION_DOM_ACCESS, params.api_call); - action->set_args(make_scoped_ptr(params.arguments.DeepCopy())); + action->set_args(base::WrapUnique(params.arguments.DeepCopy())); action->set_page_url(params.url); action->set_page_title(base::UTF16ToUTF8(params.url_title)); action->mutable_other()->SetInteger(activity_log_constants::kActionDomVerb, @@ -319,7 +320,7 @@ scoped_refptr<extensions::Action> action = new extensions::Action( extension_id, base::Time::Now(), extensions::Action::ACTION_API_EVENT, params.api_call); - action->set_args(make_scoped_ptr(params.arguments.DeepCopy())); + action->set_args(base::WrapUnique(params.arguments.DeepCopy())); if (!params.extra.empty()) { action->mutable_other()->SetString(activity_log_constants::kActionExtra, params.extra);
diff --git a/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_delegate.h b/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_delegate.h index 048446c..1f4f5fa 100644 --- a/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_delegate.h +++ b/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_delegate.h
@@ -7,8 +7,9 @@ #import <Cocoa/Cocoa.h> +#include <memory> + #include "base/mac/scoped_nsobject.h" -#include "base/memory/scoped_ptr.h" #import "content/public/browser/render_widget_host_view_mac_delegate.h" namespace content { @@ -24,7 +25,8 @@ : NSObject<RenderWidgetHostViewMacDelegate> { @private content::RenderWidgetHost* renderWidgetHost_; // weak - scoped_ptr<ChromeRenderWidgetHostViewMacDelegateInternal::SpellCheckObserver> + std::unique_ptr< + ChromeRenderWidgetHostViewMacDelegateInternal::SpellCheckObserver> spellingObserver_; // Used for continuous spell checking.
diff --git a/chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.cc b/chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.cc index b1ee028..d42d630 100644 --- a/chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.cc +++ b/chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.cc
@@ -170,13 +170,14 @@ } #if defined(ENABLE_EXTENSIONS) -void SendExecuteMimeTypeHandlerEvent(scoped_ptr<content::StreamInfo> stream, - int64_t expected_content_size, - int render_process_id, - int render_frame_id, - const std::string& extension_id, - const std::string& view_id, - bool embedded) { +void SendExecuteMimeTypeHandlerEvent( + std::unique_ptr<content::StreamInfo> stream, + int64_t expected_content_size, + int render_process_id, + int render_frame_id, + const std::string& extension_id, + const std::string& view_id, + bool embedded) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::WebContents* web_contents = @@ -510,7 +511,7 @@ extensions::ExtensionThrottleManager* extension_throttle_manager = io_data->GetExtensionThrottleManager(); if (extension_throttle_manager) { - scoped_ptr<content::ResourceThrottle> extension_throttle = + std::unique_ptr<content::ResourceThrottle> extension_throttle = extension_throttle_manager->MaybeCreateThrottle(request); if (extension_throttle) throttles->push_back(extension_throttle.release()); @@ -595,7 +596,7 @@ void ChromeResourceDispatcherHostDelegate::OnStreamCreated( net::URLRequest* request, - scoped_ptr<content::StreamInfo> stream) { + std::unique_ptr<content::StreamInfo> stream) { #if defined(ENABLE_EXTENSIONS) const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request); std::map<net::URLRequest*, StreamTargetInfo>::iterator ix =
diff --git a/chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h b/chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h index c20a3ee..3b58056 100644 --- a/chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h +++ b/chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h
@@ -6,12 +6,12 @@ #define CHROME_BROWSER_RENDERER_HOST_CHROME_RESOURCE_DISPATCHER_HOST_DELEGATE_H_ #include <map> +#include <memory> #include <set> #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/external_protocol/external_protocol_handler.h" #include "content/public/browser/resource_dispatcher_host_delegate.h" @@ -73,7 +73,7 @@ GURL* origin, std::string* payload) override; void OnStreamCreated(net::URLRequest* request, - scoped_ptr<content::StreamInfo> stream) override; + std::unique_ptr<content::StreamInfo> stream) override; void OnResponseStarted(net::URLRequest* request, content::ResourceContext* resource_context, content::ResourceResponse* response,
diff --git a/chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate_browsertest.cc b/chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate_browsertest.cc index 68b6fde..1026d5c 100644 --- a/chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate_browsertest.cc +++ b/chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate_browsertest.cc
@@ -33,7 +33,7 @@ static const char kTestPolicyHeader[] = "test_header"; static const char kServerRedirectUrl[] = "/server-redirect"; -scoped_ptr<net::test_server::HttpResponse> HandleTestRequest( +std::unique_ptr<net::test_server::HttpResponse> HandleTestRequest( const net::test_server::HttpRequest& request) { if (base::StartsWith(request.relative_url, kServerRedirectUrl, base::CompareCase::SENSITIVE)) { @@ -42,13 +42,13 @@ std::string redirect_target = request.relative_url.substr(query_string_pos + 1); - scoped_ptr<net::test_server::BasicHttpResponse> http_response( + std::unique_ptr<net::test_server::BasicHttpResponse> http_response( new net::test_server::BasicHttpResponse); http_response->set_code(net::HTTP_MOVED_PERMANENTLY); http_response->AddCustomHeader("Location", redirect_target); return std::move(http_response); } else { - scoped_ptr<net::test_server::BasicHttpResponse> http_response( + std::unique_ptr<net::test_server::BasicHttpResponse> http_response( new net::test_server::BasicHttpResponse); http_response->set_code(net::HTTP_OK); http_response->set_content("Success"); @@ -138,7 +138,7 @@ protected: // The fake URL for DMServer we are using. GURL dm_url_; - scoped_ptr<TestDispatcherHostDelegate> dispatcher_host_delegate_; + std::unique_ptr<TestDispatcherHostDelegate> dispatcher_host_delegate_; private: DISALLOW_COPY_AND_ASSIGN(ChromeResourceDispatcherHostDelegateBrowserTest);
diff --git a/chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.cc b/chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.cc index 72a97456..98934dab 100644 --- a/chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.cc +++ b/chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.cc
@@ -29,7 +29,8 @@ ChromeBrowserPepperHostFactory::~ChromeBrowserPepperHostFactory() {} -scoped_ptr<ResourceHost> ChromeBrowserPepperHostFactory::CreateResourceHost( +std::unique_ptr<ResourceHost> +ChromeBrowserPepperHostFactory::CreateResourceHost( ppapi::host::PpapiHost* host, PP_Resource resource, PP_Instance instance, @@ -38,7 +39,7 @@ // Make sure the plugin is giving us a valid instance for this resource. if (!host_->IsValidInstance(instance)) - return scoped_ptr<ResourceHost>(); + return std::unique_ptr<ResourceHost>(); // Private interfaces. if (host_->GetPpapiHost()->permissions().HasPermission( @@ -47,7 +48,7 @@ case PpapiHostMsg_Broker_Create::ID: { scoped_refptr<ResourceMessageFilter> broker_filter( new chrome::PepperBrokerMessageFilter(instance, host_)); - return scoped_ptr<ResourceHost>(new MessageFilterHost( + return std::unique_ptr<ResourceHost>(new MessageFilterHost( host_->GetPpapiHost(), instance, resource, broker_filter)); } #if defined(OS_CHROMEOS) @@ -55,7 +56,7 @@ scoped_refptr<ResourceMessageFilter> pv_filter( new chrome::PepperPlatformVerificationMessageFilter(host_, instance)); - return scoped_ptr<ResourceHost>(new MessageFilterHost( + return std::unique_ptr<ResourceHost>(new MessageFilterHost( host_->GetPpapiHost(), instance, resource, pv_filter)); } #endif @@ -63,7 +64,7 @@ case PpapiHostMsg_OutputProtection_Create::ID: { scoped_refptr<ResourceMessageFilter> output_protection_filter( new chrome::PepperOutputProtectionMessageFilter(host_, instance)); - return scoped_ptr<ResourceHost>( + return std::unique_ptr<ResourceHost>( new MessageFilterHost(host_->GetPpapiHost(), instance, resource, output_protection_filter)); } @@ -76,16 +77,16 @@ ppapi::PERMISSION_FLASH)) { switch (message.type()) { case PpapiHostMsg_Flash_Create::ID: - return scoped_ptr<ResourceHost>( + return std::unique_ptr<ResourceHost>( new chrome::PepperFlashBrowserHost(host_, instance, resource)); case PpapiHostMsg_FlashClipboard_Create::ID: { scoped_refptr<ResourceMessageFilter> clipboard_filter( new chrome::PepperFlashClipboardMessageFilter); - return scoped_ptr<ResourceHost>(new MessageFilterHost( + return std::unique_ptr<ResourceHost>(new MessageFilterHost( host_->GetPpapiHost(), instance, resource, clipboard_filter)); } case PpapiHostMsg_FlashDRM_Create::ID: - return scoped_ptr<ResourceHost>( + return std::unique_ptr<ResourceHost>( new chrome::PepperFlashDRMHost(host_, instance, resource)); } } @@ -100,10 +101,10 @@ chrome::PepperIsolatedFileSystemMessageFilter* isolated_fs_filter = chrome::PepperIsolatedFileSystemMessageFilter::Create(instance, host_); if (!isolated_fs_filter) - return scoped_ptr<ResourceHost>(); - return scoped_ptr<ResourceHost>( + return std::unique_ptr<ResourceHost>(); + return std::unique_ptr<ResourceHost>( new MessageFilterHost(host, instance, resource, isolated_fs_filter)); } - return scoped_ptr<ResourceHost>(); + return std::unique_ptr<ResourceHost>(); }
diff --git a/chrome/browser/renderer_host/render_process_host_chrome_browsertest.cc b/chrome/browser/renderer_host/render_process_host_chrome_browsertest.cc index fa089eee..5f5a1c7 100644 --- a/chrome/browser/renderer_host/render_process_host_chrome_browsertest.cc +++ b/chrome/browser/renderer_host/render_process_host_chrome_browsertest.cc
@@ -51,7 +51,7 @@ } WebContents* FindFirstDevToolsContents() { - scoped_ptr<content::RenderWidgetHostIterator> widgets( + std::unique_ptr<content::RenderWidgetHostIterator> widgets( RenderWidgetHost::GetRenderWidgetHosts()); while (content::RenderWidgetHost* widget = widgets->GetNextHost()) { if (!widget->GetProcess()->HasConnection())
diff --git a/chrome/browser/renderer_host/safe_browsing_resource_throttle.cc b/chrome/browser/renderer_host/safe_browsing_resource_throttle.cc index 891ee98..bc07dc3b 100644 --- a/chrome/browser/renderer_host/safe_browsing_resource_throttle.cc +++ b/chrome/browser/renderer_host/safe_browsing_resource_throttle.cc
@@ -42,13 +42,14 @@ // Return a dictionary with "url"=|url-spec| and optionally // |name|=|value| (if not null), for netlogging. // This will also add a reference to the original request's net_log ID. -scoped_ptr<base::Value> NetLogUrlCallback( +std::unique_ptr<base::Value> NetLogUrlCallback( const net::URLRequest* request, const GURL& url, const char* name, const char* value, net::NetLogCaptureMode /* capture_mode */) { - scoped_ptr<base::DictionaryValue> event_params(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> event_params( + new base::DictionaryValue()); event_params->SetString("url", url.spec()); if (name && value) event_params->SetString(name, value); @@ -57,11 +58,11 @@ } // Return a dictionary with |name|=|value|, for netlogging. -scoped_ptr<base::Value> NetLogStringCallback( - const char* name, - const char* value, - net::NetLogCaptureMode) { - scoped_ptr<base::DictionaryValue> event_params(new base::DictionaryValue()); +std::unique_ptr<base::Value> NetLogStringCallback(const char* name, + const char* value, + net::NetLogCaptureMode) { + std::unique_ptr<base::DictionaryValue> event_params( + new base::DictionaryValue()); if (name && value) event_params->SetString(name, value); return std::move(event_params);
diff --git a/chrome/browser/resources/chromeos/keyboard_overlay_data.js b/chrome/browser/resources/chromeos/keyboard_overlay_data.js index ce6e4a04..b24eb4c0 100644 --- a/chrome/browser/resources/chromeos/keyboard_overlay_data.js +++ b/chrome/browser/resources/chromeos/keyboard_overlay_data.js
@@ -15861,6 +15861,7 @@ 'f4<>SEARCH': 'keyboardOverlayFullScreenKeyLabel', 'f5<>CTRL<>SEARCH': 'keyboardOverlayTakeScreenshot', 'f5<>CTRL<>SEARCH<>SHIFT': 'keyboardOverlayScreenshotRegion', + 'f5<>ALT<>CTRL<>SEARCH' : 'keyboardOverlayScreenshotWindow', 'f5<>SEARCH': 'keyboardOverlaySwitchWinKeyLabel', 'f6<>ALT<>SEARCH': 'keyboardOverlayDecreaseKeyBrightness', 'f6<>ALT<>CTRL<>SEARCH': 'keyboardOverlayMagnifierDecreaseZoom',
diff --git a/chrome/browser/resources/md_history/history.html b/chrome/browser/resources/md_history/history.html index 3004055..f633828 100644 --- a/chrome/browser/resources/md_history/history.html +++ b/chrome/browser/resources/md_history/history.html
@@ -24,18 +24,6 @@ flex: 0 0 56px; } - #toolbar:unresolved { - align-items: center; - background: rgb(63, 85, 102); - color: #fff; - display: flex; - flex-direction: row; - font-size: 16px; - font-weight: 400; - height: 56px; - padding-left: 24px; - } - #history-list { flex: 1 0 0; overflow: auto; @@ -51,17 +39,32 @@ overflow: hidden; } + /* Minimal styling required to display app shim. */ .loading #main-container, - #loading-message { + .loading history-toolbar, + .app-shim { display: none; } + .loading .app-shim { + display: flex; + font-size: 123%; + } + + .loading #loading-toolbar { + -webkit-padding-start: 24px; + align-items: center; + background: rgb(63, 85, 102); + color: #fff; + flex-direction: row; + font-weight: 400; + height: 56px; + } + .loading #loading-message { align-items: center; color: #b4b4b4; - display: flex; flex: 1; - font-size: 16px; font-weight: 500; justify-content: center; } @@ -69,16 +72,16 @@ </head> <body class="loading"> - <history-toolbar class="paper-header" id="toolbar"> - $i18n{title} - </history-toolbar> + <history-toolbar class="paper-header" id="toolbar"></history-toolbar> <div id="main-container"> <history-side-bar id="history-side-bar"></history-side-bar> <history-list id="history-list"></history-list> <history-synced-device-manager id="history-synced-device-manager" hidden> </history-synced-device-manager> </div> - <span id="loading-message">$i18n{loading}</span> + + <span class="app-shim" id="loading-toolbar">$i18n{title}</span> + <span class="app-shim" id="loading-message">$i18n{loading}</span> <link rel="import" href="chrome://resources/html/cr.html"> <link rel="import" href="chrome://resources/html/util.html">
diff --git a/chrome/browser/resources/md_history/history.js b/chrome/browser/resources/md_history/history.js index 72aecaf..333b022 100644 --- a/chrome/browser/resources/md_history/history.js +++ b/chrome/browser/resources/md_history/history.js
@@ -128,8 +128,10 @@ waitForUpgrade(syncedDeviceElem).then(function() { var syncedDeviceManager = /** @type {HistorySyncedDeviceManagerElement} */(syncedDeviceElem); - if (isTabSyncEnabled) + if (isTabSyncEnabled) { syncedDeviceManager.setSyncedHistory(sessionList); + /** @type {HistoryToolbarElement} */($('toolbar')).hasSidebar = true; + } }); }
diff --git a/chrome/browser/resources/md_history/history_item.html b/chrome/browser/resources/md_history/history_item.html index 6d15c1d..1806eef5 100644 --- a/chrome/browser/resources/md_history/history_item.html +++ b/chrome/browser/resources/md_history/history_item.html
@@ -10,12 +10,11 @@ <dom-module id="history-item"> <template> - <style include="shared-style"></style> - <style> + <style include="shared-style"> :host { @apply(--layout-center); @apply(--layout-vertical); - padding: 0 24px; + padding: 0 var(--card-padding-side); } #main-container {
diff --git a/chrome/browser/resources/md_history/history_list.html b/chrome/browser/resources/md_history/history_list.html index 9d38f3d8..173a09e 100644 --- a/chrome/browser/resources/md_history/history_list.html +++ b/chrome/browser/resources/md_history/history_list.html
@@ -8,8 +8,7 @@ <dom-module id="history-list"> <template> - <style include="shared-style"></style> - <style> + <style include="shared-style"> :host { display: flex; flex-direction: column;
diff --git a/chrome/browser/resources/md_history/history_toolbar.html b/chrome/browser/resources/md_history/history_toolbar.html index ea78ae25..08ce517 100644 --- a/chrome/browser/resources/md_history/history_toolbar.html +++ b/chrome/browser/resources/md_history/history_toolbar.html
@@ -7,8 +7,7 @@ <dom-module id="history-toolbar"> <template> - <style include="shared-style"></style> - <style> + <style include="shared-style"> :host { background: rgb(63, 85, 102); color: #fff; @@ -17,7 +16,8 @@ } :host, - #items, + #overlay-buttons, + #overlay-wrapper, #main-content, #button-container, #toolbar-container { @@ -32,18 +32,37 @@ h1 { @apply(--layout-flex); - font-size: 16px; + -webkit-padding-start: 24px; + font-size: 123%; font-weight: 400; - padding-left: 24px; + } + + #left-content, + #right-content { + flex: 1 0 0; + } + + :host([has-sidebar]) #left-content { + flex: 1 0 var(--side-bar-width); + } + + #centered-buttons { + flex: 0 1 var(--card-max-width); + padding: 0 var(--card-padding-side); } #search-input { -webkit-padding-end: 20px; } - #items { + #overlay-buttons { margin: 0 auto; max-width: var(--card-max-width); + padding: 0 var(--card-padding-side); + } + + :host([has-sidebar]) #overlay-wrapper { + -webkit-margin-start: var(--side-bar-width); } #number-selected { @@ -51,68 +70,49 @@ } paper-icon-button { + -webkit-margin-end: 24px; + -webkit-margin-start: 2px; height: 36px; - margin: 0 24px 0 2px; min-width: 36px; width: 36px; } - #centered-buttons { - flex: 0 1 var(--card-max-width); - } - paper-button { pointer-events: auto; } - - .toolbar-overlay { - height: inherit; - left: 0; - pointer-events: none; - position: absolute; - top: 0; - } - - #front-padding { - flex: 1 1 0; - min-width: 100px; - } - - #back-padding { - flex: 1 1 0; - } </style> <div id="toolbar-container"> <div id="main-content" hidden$="[[itemsSelected_]]"> - <h1 id="title">$i18n{title}</h1> - <cr-search-field id="search-input" label="$i18n{search}" - clear-label="$i18n{clearSearch}"> - </cr-search-field> + <div id="left-content"> + <h1 id="title">$i18n{title}</h1> + </div> + <div id="centered-buttons"> + <paper-button on-tap="onClearBrowsingDataTap_" + id="clear-browsing-data-button"> + $i18n{clearBrowsingData} + </paper-button> + </div> + <div id="right-content"> + <cr-search-field id="search-input" label="$i18n{search}" + clear-label="$i18n{clearSearch}"> + </cr-search-field> + </div> </div> - <div id="items" hidden$="[[!itemsSelected_]]"> - <paper-icon-button icon="clear" id="cancel-icon-button" - on-tap="onClearSelectionTap_"></paper-icon-button> - <div id="number-selected">[[numberOfItemsSelected_(count)]]</div> - <paper-button id="cancel-button" on-tap="onClearSelectionTap_"> - $i18n{cancel} - </paper-button> - <paper-button id="delete-button" on-tap="onDeleteTap_"> - $i18n{delete} - </paper-button> + <div id="overlay-wrapper" hidden$="[[!itemsSelected_]]"> + <div id="overlay-buttons"> + <paper-icon-button icon="clear" id="cancel-icon-button" + on-tap="onClearSelectionTap_"></paper-icon-button> + <div id="number-selected">[[numberOfItemsSelected_(count)]]</div> + <paper-button id="cancel-button" on-tap="onClearSelectionTap_"> + $i18n{cancel} + </paper-button> + <paper-button id="delete-button" on-tap="onDeleteTap_"> + $i18n{delete} + </paper-button> + </div> </div> </div> - - <div id="button-container" class="toolbar-overlay"> - <div id="front-padding"></div> - <div id="centered-buttons" hidden$="[[itemsSelected_]]"> - <paper-button on-tap="onClearBrowsingDataTap_" - id="clear-browsing-data-button"> - $i18n{clearBrowsingData} - </paper-button> - </div> - <div id="back-padding"></div> - </div> </template> <script src="chrome://history/history_toolbar.js"></script> </dom-module>
diff --git a/chrome/browser/resources/md_history/history_toolbar.js b/chrome/browser/resources/md_history/history_toolbar.js index 48189b89..6c2dd40 100644 --- a/chrome/browser/resources/md_history/history_toolbar.js +++ b/chrome/browser/resources/md_history/history_toolbar.js
@@ -41,6 +41,14 @@ searchTerm: { type: String, value: '' + }, + + // True if the page has a sidebar that we need to account for when + // positioning toolbar items. + hasSidebar: { + type: Boolean, + value: false, + reflectToAttribute: true } },
diff --git a/chrome/browser/resources/md_history/shared_style.html b/chrome/browser/resources/md_history/shared_style.html index a18de8d..9334ea2a 100644 --- a/chrome/browser/resources/md_history/shared_style.html +++ b/chrome/browser/resources/md_history/shared_style.html
@@ -5,7 +5,9 @@ --card-border-color: rgba(0, 0, 0, 0.14); --card-max-width: 960px; --card-min-width: 500px; + --card-padding-side: 24px; --first-card-padding-top: 40px; + --side-bar-width: 200px; } [hidden] {
diff --git a/chrome/browser/resources/md_history/side_bar.html b/chrome/browser/resources/md_history/side_bar.html index f9a6faa..fc26be4 100644 --- a/chrome/browser/resources/md_history/side_bar.html +++ b/chrome/browser/resources/md_history/side_bar.html
@@ -4,13 +4,14 @@ <link rel="import" href="chrome://resources/polymer/v1_0/paper-listbox/paper-listbox.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-ripple/paper-ripple.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/color.html"> +<link rel="import" href="chrome://history/shared_style.html"> <dom-module id="history-side-bar"> <template> - <style> + <style include="shared-style"> :host { padding-top: 5px; - width: 200px; + width: var(--side-bar-width); } paper-item {
diff --git a/chrome/browser/resources/md_history/synced_device_card.html b/chrome/browser/resources/md_history/synced_device_card.html index ee526bb1..e63eee06 100644 --- a/chrome/browser/resources/md_history/synced_device_card.html +++ b/chrome/browser/resources/md_history/synced_device_card.html
@@ -9,12 +9,11 @@ <dom-module id="history-synced-device-card"> <template> - <style include="shared-style"></style> - <style> + <style include="shared-style"> :host { @apply(--layout-center); @apply(--layout-vertical); - padding: 0 24px 20px; + padding: 0 var(--card-padding-side) 20px; } #card-heading {
diff --git a/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.html b/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.html index 3e995b695..28baa3d 100644 --- a/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.html +++ b/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.html
@@ -86,7 +86,8 @@ </template> <template is="dom-if" if="[[!computeRouteDetailsHidden_(currentView_, issue)]]"> - <route-details id="route-details" route="[[currentRoute_]]" + <route-details id="route-details" is-off-the-record="[[isOffTheRecord]]" + route="[[currentRoute_]]" on-close-route-click="onCloseRouteClick_"> </route-details> </template>
diff --git a/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.js b/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.js index 5cdbb30e..d700f4c2 100644 --- a/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.js +++ b/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.js
@@ -121,6 +121,15 @@ }, /** + * Whether the browser is currently incognito. + * @type {boolean} + */ + isOffTheRecord: { + type: Boolean, + value: false, + }, + + /** * Whether the search input is currently focused. This is used to prevent * window focus/blur events from interfering with input-focus-dependent * operations.
diff --git a/chrome/browser/resources/media_router/elements/route_details/route_details.js b/chrome/browser/resources/media_router/elements/route_details/route_details.js index 2689de1a..f38468c 100644 --- a/chrome/browser/resources/media_router/elements/route_details/route_details.js +++ b/chrome/browser/resources/media_router/elements/route_details/route_details.js
@@ -18,6 +18,15 @@ }, /** + * Whether the browser is currently incognito. + * @type {boolean} + */ + isOffTheRecord: { + type: Boolean, + value: false, + }, + + /** * The route to show. * @type {?media_router.Route} */ @@ -76,7 +85,8 @@ this.route.description) : ''; - if (!this.route || !this.route.customControllerPath) { + if (!this.route || !this.route.customControllerPath || + this.isOffTheRecord) { this.isCustomControllerHidden_ = true; return; }
diff --git a/chrome/browser/resources/media_router/media_router_ui_interface.js b/chrome/browser/resources/media_router/media_router_ui_interface.js index 6b23d2b3..a7d81d8 100644 --- a/chrome/browser/resources/media_router/media_router_ui_interface.js +++ b/chrome/browser/resources/media_router/media_router_ui_interface.js
@@ -88,17 +88,20 @@ * showDomain: boolean * }, * routes: !Array<!media_router.Route>, - * castModes: !Array<!media_router.CastMode>}} data + * castModes: !Array<!media_router.CastMode>, + * isOffTheRecord: boolean}} data * Parameters in data: * deviceMissingUrl - url to be opened on "Device missing?" clicked. * sinksAndIdentity - list of sinks to be displayed and user identity. * routes - list of routes that are associated with the sinks. * castModes - list of available cast modes. + * isOffTheRecord - whether or not the browser is currently incognito. */ function setInitialData(data) { container.deviceMissingUrl = data['deviceMissingUrl']; container.castModeList = data['castModes']; this.setSinkListAndIdentity(data['sinksAndIdentity']); + container.isOffTheRecord = data['isOffTheRecord']; container.routeList = data['routes']; container.maybeShowRouteDetailsOnOpen(); media_router.browserApi.onInitialDataReceived();
diff --git a/chrome/browser/resources/options/password_manager.js b/chrome/browser/resources/options/password_manager.js index b577701..0cf7d22 100644 --- a/chrome/browser/resources/options/password_manager.js +++ b/chrome/browser/resources/options/password_manager.js
@@ -287,6 +287,7 @@ $('manage-passwords-span').hidden = !visible; }, + /** @private */ showImportExportButton_: function() { $('password-manager-import').hidden = false; $('password-manager-export').hidden = false;
diff --git a/chrome/browser/resources/settings/languages_page/languages.js b/chrome/browser/resources/settings/languages_page/languages.js index 97720e6..190b261 100644 --- a/chrome/browser/resources/settings/languages_page/languages.js +++ b/chrome/browser/resources/settings/languages_page/languages.js
@@ -140,7 +140,7 @@ Promise.all(promises).then(function(results) { this.createModel_(results[1], results[2]); - this.resolver_.resolve(undefined /* unused */); + this.resolver_.resolve(); }.bind(this)); },
diff --git a/chrome/browser/resources/settings/people_page/compiled_resources2.gyp b/chrome/browser/resources/settings/people_page/compiled_resources2.gyp index 2d63ef94..41a7cf2 100644 --- a/chrome/browser/resources/settings/people_page/compiled_resources2.gyp +++ b/chrome/browser/resources/settings/people_page/compiled_resources2.gyp
@@ -75,11 +75,19 @@ '../settings_page/compiled_resources2.gyp:settings_animated_pages', 'easy_unlock_browser_proxy', 'easy_unlock_turn_off_dialog', + 'profile_info_browser_proxy', 'sync_private_api', ], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], }, { + 'target_name': 'profile_info_browser_proxy', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { 'target_name': 'sync_page', 'dependencies': [ '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
diff --git a/chrome/browser/resources/settings/people_page/people_page.html b/chrome/browser/resources/settings/people_page/people_page.html index 9ca6f77..bd5d9ef 100644 --- a/chrome/browser/resources/settings/people_page/people_page.html +++ b/chrome/browser/resources/settings/people_page/people_page.html
@@ -1,12 +1,13 @@ -<link rel="import" href="chrome://resources/html/i18n_behavior.html"> <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html"> <link rel="import" href="chrome://resources/polymer/v1_0/neon-animation/neon-animatable.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-checkbox/paper-checkbox.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-dialog/paper-dialog.html"> +<link rel="import" href="chrome://md-settings/i18n_setup.html"> <link rel="import" href="chrome://md-settings/controls/settings_checkbox.html"> <link rel="import" href="chrome://md-settings/people_page/sync_page.html"> +<link rel="import" href="chrome://md-settings/people_page/profile_info_browser_proxy.html"> <link rel="import" href="chrome://md-settings/people_page/sync_private_api.html"> <link rel="import" href="chrome://md-settings/settings_page/settings_animated_pages.html"> <link rel="import" href="chrome://md-settings/settings_page/settings_subpage.html"> @@ -25,7 +26,7 @@ <dom-module id="settings-people-page"> <template> <style include="settings-shared"> - #account-picture { + #profile-icon { -webkit-margin-end: 4px; border-radius: 20px; height: 40px; @@ -34,7 +35,7 @@ width: 40px; } - #account-picture:hover { + #profile-icon:hover { cursor: pointer; } @@ -48,7 +49,7 @@ section="people"> <neon-animatable id="main"> <div class="settings-box first two-line"> - <img id="account-picture" src="[[profileIconUrl_]]" + <img id="profile-icon" src="[[profileIconUrl_]]" on-tap="onPictureTap_"> <div class="middle"> <if expr="chromeos">
diff --git a/chrome/browser/resources/settings/people_page/people_page.js b/chrome/browser/resources/settings/people_page/people_page.js index 88d3616..cc1e9b41 100644 --- a/chrome/browser/resources/settings/people_page/people_page.js +++ b/chrome/browser/resources/settings/people_page/people_page.js
@@ -56,7 +56,7 @@ <if expr="chromeos"> /** @private {!settings.EasyUnlockBrowserProxyImpl} */ - browserProxy_: { + easyUnlockBrowserProxy_: { type: Object, value: function() { return settings.EasyUnlockBrowserProxyImpl.getInstance(); @@ -100,7 +100,11 @@ /** @override */ attached: function() { - settings.SyncPrivateApi.getProfileInfo(this.handleProfileInfo_.bind(this)); + settings.ProfileInfoBrowserProxyImpl.getInstance().getProfileInfo().then( + this.handleProfileInfo_.bind(this)); + this.addWebUIListener('profile-info-changed', + this.handleProfileInfo_.bind(this)); + settings.SyncPrivateApi.getSyncStatus( this.handleSyncStatusFetched_.bind(this)); @@ -109,7 +113,7 @@ this.addWebUIListener( 'easy-unlock-enabled-status', this.handleEasyUnlockEnabledStatusChanged_.bind(this)); - this.browserProxy_.getEnabledStatus().then( + this.easyUnlockBrowserProxy_.getEnabledStatus().then( this.handleEasyUnlockEnabledStatusChanged_.bind(this)); } </if> @@ -118,12 +122,11 @@ /** * Handler for when the profile's icon and name is updated. * @private - * @param {!string} name - * @param {!string} iconUrl + * @param {!settings.ProfileInfo} info */ - handleProfileInfo_: function(name, iconUrl) { - this.profileName_ = name; - this.profileIconUrl_ = iconUrl; + handleProfileInfo_: function(info) { + this.profileName_ = info.name; + this.profileIconUrl_ = info.iconUrl; }, /** @@ -196,7 +199,7 @@ <if expr="chromeos"> /** @private */ onEasyUnlockSetupTap_: function() { - this.browserProxy_.startTurnOnFlow(); + this.easyUnlockBrowserProxy_.startTurnOnFlow(); }, /** @private */
diff --git a/chrome/browser/resources/settings/people_page/profile_info_browser_proxy.html b/chrome/browser/resources/settings/people_page/profile_info_browser_proxy.html new file mode 100644 index 0000000..4db4d19 --- /dev/null +++ b/chrome/browser/resources/settings/people_page/profile_info_browser_proxy.html
@@ -0,0 +1,2 @@ +<link rel="import" href="chrome://resources/html/cr.html"> +<script src="chrome://md-settings/people_page/profile_info_browser_proxy.js"></script>
diff --git a/chrome/browser/resources/settings/people_page/profile_info_browser_proxy.js b/chrome/browser/resources/settings/people_page/profile_info_browser_proxy.js new file mode 100644 index 0000000..fda3cd48 --- /dev/null +++ b/chrome/browser/resources/settings/people_page/profile_info_browser_proxy.js
@@ -0,0 +1,50 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/** + * @fileoverview A helper object used from the the People section to get the + * profile info, which consists of the profile name and icon. Used for both + * Chrome browser and ChromeOS. + */ +cr.exportPath('settings'); + +/** + * An object describing the profile. + * @typedef {{ + * name: string, + * iconUrl: string + * }} + */ +settings.ProfileInfo; + +cr.define('settings', function() { + /** @interface */ + function ProfileInfoBrowserProxy() {} + + ProfileInfoBrowserProxy.prototype = { + /** + * Returns a Promise for the profile info. + * @return {!Promise<!settings.ProfileInfo>} + */ + getProfileInfo: function() {}, + }; + + /** + * @constructor + * @implements {ProfileInfoBrowserProxy} + */ + function ProfileInfoBrowserProxyImpl() {} + cr.addSingletonGetter(ProfileInfoBrowserProxyImpl); + + ProfileInfoBrowserProxyImpl.prototype = { + /** @override */ + getProfileInfo: function() { + return cr.sendWithPromise('getProfileInfo'); + }, + }; + + return { + ProfileInfoBrowserProxyImpl: ProfileInfoBrowserProxyImpl, + }; +});
diff --git a/chrome/browser/resources/settings/people_page/sync_private_api.js b/chrome/browser/resources/settings/people_page/sync_private_api.js index 17e4752..10aa3001 100644 --- a/chrome/browser/resources/settings/people_page/sync_private_api.js +++ b/chrome/browser/resources/settings/people_page/sync_private_api.js
@@ -90,9 +90,6 @@ */ function SyncPrivateApi() {} - /** @private {?function(!string, !string)} */ - SyncPrivateApi.getProfileInfoCallback_ = null; - /** @private {?function(settings.SyncPrefs)} */ SyncPrivateApi.syncPrefsCallback_ = null; @@ -100,25 +97,6 @@ SyncPrivateApi.setPageStatusCallback_ = null; /** - * Called from JavaScript. Gets the current profile name and icon. - * @param {?function(!string, !string)} callback - */ - SyncPrivateApi.getProfileInfo = function(callback) { - SyncPrivateApi.getProfileInfoCallback_ = callback; - chrome.send('getProfileInfo'); - }; - - /** - * Called from C++ as a response to getIconsAndNames. - * @param {!string} name The current profile name. - * @param {!string} iconUrl The current profile icon's URL. Can be a data URL. - */ - SyncPrivateApi.receiveProfileInfo = function(name, iconUrl) { - if (SyncPrivateApi.getProfileInfoCallback_) - SyncPrivateApi.getProfileInfoCallback_(name, iconUrl); - }; - - /** * Starts the signin process for the user. Does nothing if the user is * already signed in. * @private
diff --git a/chrome/browser/resources/settings/settings_dialog.html b/chrome/browser/resources/settings/settings_dialog.html index df72a0d..c58286a 100644 --- a/chrome/browser/resources/settings/settings_dialog.html +++ b/chrome/browser/resources/settings/settings_dialog.html
@@ -9,8 +9,10 @@ <style include="paper-dialog-shared-styles"></style> <style> .body-content { + display: flex; + flex-direction: column; font-size: 1em; - margin: 20px 0; + min-height: 120px; } .dialog-content { @@ -27,28 +29,37 @@ .top-row { align-items: center; - border-bottom: 1px solid var(--paper-grey-300); + border-bottom: 1px solid rgba(0, 0, 0, 0.14); display: flex; - padding-bottom: 5px; - padding-top: 5px; + min-height: 52px; + } + + paper-icon-button { + height: 20px; + margin: 16px; + padding: 0; + width: 20px; } :host { max-width: 800px; - min-width: 500px; + min-width: 512px; overflow: auto; } :host ::content .body { - margin-bottom: 35px; + flex: 1; + margin: 12px 0 24px 0; } :host ::content .button-container { display: flex; justify-content: flex-end; + margin-bottom: 12px; } :host ::content .button-container .cancel-button { + -webkit-margin-end: 8px; color: var(--paper-grey-600); font-weight: 500; } @@ -71,7 +82,7 @@ :host ::content .title { flex: 1; - font-size: 1.13em; + font-size: 114.28%; /* (16px / 14px) * 100 */ } :host ::content .title,
diff --git a/chrome/browser/resources/settings/settings_resources.grd b/chrome/browser/resources/settings/settings_resources.grd index 6941880..668820c3 100644 --- a/chrome/browser/resources/settings/settings_resources.grd +++ b/chrome/browser/resources/settings/settings_resources.grd
@@ -467,13 +467,17 @@ type="chrome_html" /> <structure name="IDR_SETTINGS_PEOPLE_PAGE_MANAGE_PROFILE_BROWSER_PROXY_HTML" file="people_page/manage_profile_browser_proxy.html" - type="chrome_html" - flattenhtml="true" - allowexternalscript="true" /> + type="chrome_html" /> <structure name="IDR_SETTINGS_PEOPLE_PAGE_MANAGE_PROFILE_BROWSER_PROXY_JS" file="people_page/manage_profile_browser_proxy.js" type="chrome_html" /> </if> + <structure name="IDR_SETTINGS_PEOPLE_PAGE_PROFILE_INFO_BROWSER_PROXY_HTML" + file="people_page/profile_info_browser_proxy.html" + type="chrome_html" /> + <structure name="IDR_SETTINGS_PEOPLE_PAGE_PROFILE_INFO_BROWSER_PROXY_JS" + file="people_page/profile_info_browser_proxy.js" + type="chrome_html" /> <structure name="IDR_SETTINGS_PREF_UTIL_HTML" file="prefs/pref_util.html" type="chrome_html" />
diff --git a/chrome/browser/resources/settings/settings_shared_css.html b/chrome/browser/resources/settings/settings_shared_css.html index 8c5d18e..eb2c8f58 100644 --- a/chrome/browser/resources/settings/settings_shared_css.html +++ b/chrome/browser/resources/settings/settings_shared_css.html
@@ -55,7 +55,6 @@ paper-button { margin: 0; - min-width: auto; } paper-button[toggles][active] {
diff --git a/chrome/browser/resources/snippets_internals.css b/chrome/browser/resources/snippets_internals.css new file mode 100644 index 0000000..40d8997c --- /dev/null +++ b/chrome/browser/resources/snippets_internals.css
@@ -0,0 +1,78 @@ +/* Copyright 2016 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. */ + +html { + font-size: 20px; +} + +#info > div { + width: 100%; +} + +#info h2 { + color: rgb(74, 142, 230); + font-size: 100%; + margin-bottom: 0.3em; + margin-top: 1em; +} + +#info .section { + display: inline-block; + margin-left: auto; + margin-right: auto; +} + +.section-details { + width: 100%; +} + +.section-details .detail, +.section-details .value { + width: 50%; +} + +td.title-link { + padding-bottom: 0.5em; + padding-top: 0.5em; +} + +.expiry { + color: gray; + font-size: 80%; +} + +.date { + white-space: nowrap; +} + +.url { + display: inline-block; + font-size: 80%; + word-break: break-all; +} + +.snippet-detail { + font-size: 90%; +} + +.snippet-hidden { + display: none; +} + +table.section-details > tbody > tr:nth-child(odd) { + background: rgb(239, 243, 255); +} + +.detail { + color: gray; + font-weight: normal; +} + +.forms { + margin-top: 0.3em; +} + +#submit-clear { + margin-bottom: 0.5em; +} \ No newline at end of file
diff --git a/chrome/browser/resources/snippets_internals.html b/chrome/browser/resources/snippets_internals.html new file mode 100644 index 0000000..c34a0d90 --- /dev/null +++ b/chrome/browser/resources/snippets_internals.html
@@ -0,0 +1,127 @@ +<!-- +Copyright 2016 The Chromium Authors. All rights reserved. +Use of this source code is governed by a BSD-style license that can be +found in the LICENSE file. +--> +<!DOCTYPE html> +<meta charset="utf-8"> +<if expr="is_android or is_ios"> +<meta name="viewport" content="width=device-width, initial-scale=1.0, + maximum-scale=1.0, user-scalable=no"> +</if> +<title>Snippets Internals</title> +<link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> +<link rel="stylesheet" href="snippets_internals.css"> +<script src="chrome://resources/js/cr.js"></script> +<script src="chrome://resources/js/jstemplate_compiled.js"></script> +<script src="chrome://resources/js/util.js"></script> +<script src="snippets_internals.js"></script> + +<div id="info"> + <div class="section"> + <h2>Properties</h2> + <table class="section-details"> + <tr> + <td class="name">Snippets enabled + <td id="flag-snippets" class="value"> + <tr> + <td class="name">Snippets restricted to hosts + <td id="switch-restrict-to-hosts" class="value"> + </table> + </div> + + <div id="snippets" class="section"> + <h2>Snippets <span class="detail">(click for details)</span></h2> + <table class="section-details"> + <tr jsselect="list" style="display:none"> + <td class="title-link"> + <span class="snippet-title" jsvalues="snippet-id:id"> + <span jscontent="title"></span>>></span> + <div jsvalues="id:id" class="snippet-detail snippet-hidden"> + <table> + <tr> + <td>Validity + <td class="expiry"> + <span class="date" jscontent="published"></span> – + <span class="date" jscontent="expires"></span> + <tr> + <td>Site title + <td jscontent="siteTitle"> + <tr> + <td>Text + <td jscontent="snippet"> + <tr> + <td>URL + <td><a class="url" jsvalues="href:url" jscontent="url"></a> + <tr> + <td>Favicon + <td><a class="url" jsvalues="href:faviconUrl" + jscontent="faviconUrl"></a> + <tr> + <td>Salient image + <td><a class="url" jsvalues="href:salientImageUrl" + jscontent="salientImageUrl"></a> + </table> + </div> + </table> + <div class="detail" id="snippets-empty"></div> + <div class="forms"> + <input id="submit-clear" type="submit" value="Clear the list"> + </div> + <div class="forms"> + <input id="submit-download" type="submit" value="Add snippets"> + from hosts <input id="hosts-input" type="text" placeholder= + "www.wired.com www.bbc.co.uk"> + <div id="hosts-help" class="detail"></div> + </div> + </div> + + <div id="discarded-snippets" class="section"> + <h2>Discarded snippets <span class="detail">(click for details)</span></h2> + <table class="section-details"> + <tr jsselect="list" style="display:none"> + <td class="title-link"> + <span class="discarded-snippet-title" jsvalues="snippet-id:id"> + <span jscontent="title"></span> >></span> + <div jsvalues="id:id" class="snippet-detail snippet-hidden"> + <table> + <tr> + <td>Validity + <td class="expiry"> + <span class="date" jscontent="published"></span> – + <span class="date" jscontent="expires"></span> + <tr> + <td>Site title + <td jscontent="siteTitle"> + <tr> + <td>Text + <td jscontent="snippet"> + <tr> + <td>URL + <td><a class="url" jsvalues="href:url" jscontent="url"></a> + <tr> + <td>Favicon + <td><a class="url" jsvalues="href:faviconUrl" + jscontent="faviconUrl"></a> + <tr> + <td>Salient image + <td><a class="url" jsvalues="href:salientImageUrl" + jscontent="salientImageUrl"></a> + </table> + </div> + </table> + <div class="detail" id="discarded-snippets-empty"></div> + <div class="forms"> + <input id="discarded-snippets-clear" type="submit" value="Clear list"> + </div> + </div> + + <div id="hosts" class="section"> + <h2>Suggestion hosts</h2> + <table class="section-details"> + <tr jsselect="list"> + <td jscontent="url"> + </table> + <div class="detail" id="hosts-empty"></div> + </div> +</div> \ No newline at end of file
diff --git a/chrome/browser/resources/snippets_internals.js b/chrome/browser/resources/snippets_internals.js new file mode 100644 index 0000000..e49205b6 --- /dev/null +++ b/chrome/browser/resources/snippets_internals.js
@@ -0,0 +1,94 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +cr.define('chrome.SnippetsInternals', function() { + 'use strict'; + + function initialize() { + function submitDownload(event) { + chrome.send('download', [$('hosts-input').value]); + event.preventDefault(); + } + + $('submit-download').addEventListener('click', submitDownload); + + function submitClear(event) { + chrome.send('clear'); + event.preventDefault(); + } + + $('submit-clear').addEventListener('click', submitClear); + + function submitClearDiscarded(event) { + chrome.send('clearDiscarded'); + event.preventDefault(); + } + + $('discarded-snippets-clear').addEventListener('click', + submitClearDiscarded); + + chrome.send('loaded'); + } + + function receiveProperty(propertyId, value) { + $(propertyId).textContent = value; + } + + function receiveHosts(hosts) { + displayList(hosts, 'hosts'); + + $('hosts-input').value = hosts.list.map(host => host.url).join(' '); + } + + function receiveSnippets(snippets) { + displayList(snippets, 'snippets', 'snippet-title'); + } + + function receiveDiscardedSnippets(discardedSnippets) { + displayList(discardedSnippets, 'discarded-snippets', + 'discarded-snippet-title'); + } + + function displayList(object, domId, titleClass) { + jstProcess(new JsEvalContext(object), $(domId)); + + var text; + var display; + + if (object.list.length > 0) { + text = ''; + display = 'inline'; + } else { + text = 'The list is empty.'; + display = 'none'; + } + + if ($(domId + '-empty')) $(domId + '-empty').textContent = text; + if ($(domId + '-clear')) $(domId + '-clear').style.display = display; + + function trigger(event) { + // The id of the snippet is stored to 'snippet-id' attribute of the link. + var id = event.currentTarget.getAttribute('snippet-id'); + $(id).classList.toggle('snippet-hidden'); + event.preventDefault(); + } + + var links = document.getElementsByClassName(titleClass); + for (var link of links) { + link.addEventListener('click', trigger); + } + } + + // Return an object with all of the exports. + return { + initialize: initialize, + receiveProperty: receiveProperty, + receiveHosts: receiveHosts, + receiveSnippets: receiveSnippets, + receiveDiscardedSnippets: receiveDiscardedSnippets, + }; +}); + +document.addEventListener('DOMContentLoaded', + chrome.SnippetsInternals.initialize);
diff --git a/chrome/browser/rlz/chrome_rlz_tracker_delegate.h b/chrome/browser/rlz/chrome_rlz_tracker_delegate.h index 0e48175f0..1fdc71a 100644 --- a/chrome/browser/rlz/chrome_rlz_tracker_delegate.h +++ b/chrome/browser/rlz/chrome_rlz_tracker_delegate.h
@@ -56,7 +56,7 @@ // Subscription for receiving callbacks that a URL was opened from the // omnibox. - scoped_ptr<base::CallbackList<void(OmniboxLog*)>::Subscription> + std::unique_ptr<base::CallbackList<void(OmniboxLog*)>::Subscription> omnibox_url_opened_subscription_; DISALLOW_COPY_AND_ASSIGN(ChromeRLZTrackerDelegate);
diff --git a/chrome/browser/rlz/chrome_rlz_tracker_delegate_unittest.cc b/chrome/browser/rlz/chrome_rlz_tracker_delegate_unittest.cc index fd7d6e00..d300626 100644 --- a/chrome/browser/rlz/chrome_rlz_tracker_delegate_unittest.cc +++ b/chrome/browser/rlz/chrome_rlz_tracker_delegate_unittest.cc
@@ -4,7 +4,8 @@ #include "chrome/browser/rlz/chrome_rlz_tracker_delegate.h" -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "chrome/browser/chrome_notification_types.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" @@ -28,13 +29,13 @@ } private: - scoped_ptr<ChromeRLZTrackerDelegate> delegate_; + std::unique_ptr<ChromeRLZTrackerDelegate> delegate_; }; TEST_F(ChromeRLZTrackerDelegateTest, ObserveHandlesBadArgs) { - scoped_ptr<content::LoadCommittedDetails> details( + std::unique_ptr<content::LoadCommittedDetails> details( new content::LoadCommittedDetails()); - scoped_ptr<content::NavigationEntry> entry( + std::unique_ptr<content::NavigationEntry> entry( content::NavigationEntry::Create()); details->entry = entry.get(); details->entry->SetPageID(0);
diff --git a/chrome/browser/safe_browsing/download_protection_service.cc b/chrome/browser/safe_browsing/download_protection_service.cc index 48c798a5..ea264ac 100644 --- a/chrome/browser/safe_browsing/download_protection_service.cc +++ b/chrome/browser/safe_browsing/download_protection_service.cc
@@ -342,7 +342,31 @@ item_->GetTargetFilePath().MatchesExtension( FILE_PATH_LITERAL(".iso")) || item_->GetTargetFilePath().MatchesExtension( - FILE_PATH_LITERAL(".smi"))) { + FILE_PATH_LITERAL(".smi")) || + item_->GetTargetFilePath().MatchesExtension( + FILE_PATH_LITERAL(".cdr")) || + item_->GetTargetFilePath().MatchesExtension( + FILE_PATH_LITERAL(".dart")) || + item_->GetTargetFilePath().MatchesExtension( + FILE_PATH_LITERAL(".dc42")) || + item_->GetTargetFilePath().MatchesExtension( + FILE_PATH_LITERAL(".diskcopy42")) || + item_->GetTargetFilePath().MatchesExtension( + FILE_PATH_LITERAL(".dmgpart")) || + item_->GetTargetFilePath().MatchesExtension( + FILE_PATH_LITERAL(".dvdr")) || + item_->GetTargetFilePath().MatchesExtension( + FILE_PATH_LITERAL(".imgpart")) || + item_->GetTargetFilePath().MatchesExtension( + FILE_PATH_LITERAL(".ndif")) || + item_->GetTargetFilePath().MatchesExtension( + FILE_PATH_LITERAL(".sparsebundle")) || + item_->GetTargetFilePath().MatchesExtension( + FILE_PATH_LITERAL(".sparseimage")) || + item_->GetTargetFilePath().MatchesExtension( + FILE_PATH_LITERAL(".toast")) || + item_->GetTargetFilePath().MatchesExtension( + FILE_PATH_LITERAL(".udif"))) { StartExtractDmgFeatures(); #endif } else {
diff --git a/chrome/browser/safe_json_parser_browsertest.cc b/chrome/browser/safe_json_parser_browsertest.cc index ec45551..b378730 100644 --- a/chrome/browser/safe_json_parser_browsertest.cc +++ b/chrome/browser/safe_json_parser_browsertest.cc
@@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> + #include "base/bind.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" -#include "base/memory/scoped_ptr.h" #include "base/values.h" #include "chrome/test/base/in_process_browser_test.h" #include "components/safe_json/safe_json_parser.h" @@ -37,7 +38,7 @@ message_loop_runner_ = new content::MessageLoopRunner; std::string error; - scoped_ptr<base::Value> value = base::JSONReader::ReadAndReturnError( + std::unique_ptr<base::Value> value = base::JSONReader::ReadAndReturnError( json, base::JSON_PARSE_RFC, nullptr, &error); SafeJsonParser::SuccessCallback success_callback; @@ -61,8 +62,8 @@ } private: - void ExpectValue(scoped_ptr<base::Value> expected_value, - scoped_ptr<base::Value> actual_value) { + void ExpectValue(std::unique_ptr<base::Value> expected_value, + std::unique_ptr<base::Value> actual_value) { EXPECT_TRUE(base::Value::Equals(actual_value.get(), expected_value.get())) << "Expected: " << MaybeToJson(expected_value.get()) << " Actual: " << MaybeToJson(actual_value.get()); @@ -75,7 +76,7 @@ message_loop_runner_->Quit(); } - void FailWithValue(scoped_ptr<base::Value> value) { + void FailWithValue(std::unique_ptr<base::Value> value) { ADD_FAILURE() << MaybeToJson(value.get()); message_loop_runner_->Quit(); }
diff --git a/chrome/browser/search/hotword_installer_browsertest.cc b/chrome/browser/search/hotword_installer_browsertest.cc index 94a02da..6fbe83c 100644 --- a/chrome/browser/search/hotword_installer_browsertest.cc +++ b/chrome/browser/search/hotword_installer_browsertest.cc
@@ -2,8 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/webstore_startup_installer.h" #include "chrome/browser/profiles/profile.h" @@ -69,9 +71,9 @@ base::WeakPtrFactory<MockHotwordService> weak_factory_; }; -scoped_ptr<KeyedService> BuildMockHotwordService( +std::unique_ptr<KeyedService> BuildMockHotwordService( content::BrowserContext* context) { - return make_scoped_ptr( + return base::WrapUnique( new MockHotwordService(static_cast<Profile*>(context))); }
diff --git a/chrome/browser/search/hotword_service.h b/chrome/browser/search/hotword_service.h index c90ea7b..cc4f2eb 100644 --- a/chrome/browser/search/hotword_service.h +++ b/chrome/browser/search/hotword_service.h
@@ -214,7 +214,7 @@ extensions::ExtensionRegistryObserver> extension_registry_observer_; - scoped_ptr<HotwordAudioHistoryHandler> audio_history_handler_; + std::unique_ptr<HotwordAudioHistoryHandler> audio_history_handler_; bool microphone_available_; @@ -228,7 +228,7 @@ bool reinstall_pending_; // Whether we are currently in the process of training the speaker model. bool training_; - scoped_ptr<HotwordUserSessionStateObserver> session_observer_; + std::unique_ptr<HotwordUserSessionStateObserver> session_observer_; // Stores the launch mode for the Hotword Audio Verification App. LaunchMode hotword_audio_verification_launch_mode_;
diff --git a/chrome/browser/search/hotword_service_unittest.cc b/chrome/browser/search/hotword_service_unittest.cc index e5887df..bff640f 100644 --- a/chrome/browser/search/hotword_service_unittest.cc +++ b/chrome/browser/search/hotword_service_unittest.cc
@@ -4,10 +4,11 @@ #include "chrome/browser/search/hotword_service.h" +#include <memory> #include <utility> #include "base/command_line.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" #include "base/test/test_simple_task_runner.h" #include "build/build_config.h" @@ -64,7 +65,7 @@ private: int get_audio_history_calls_; - scoped_ptr<history::WebHistoryService> web_history_; + std::unique_ptr<history::WebHistoryService> web_history_; }; class MockHotwordService : public HotwordService { @@ -80,12 +81,12 @@ } void InstallHotwordExtensionFromWebstore(int num_tries) override { - scoped_ptr<base::DictionaryValue> manifest = + std::unique_ptr<base::DictionaryValue> manifest = extensions::DictionaryBuilder() - .Set("name", "Hotword Test Extension") - .Set("version", "1.0") - .Set("manifest_version", 2) - .Build(); + .Set("name", "Hotword Test Extension") + .Set("version", "1.0") + .Set("manifest_version", 2) + .Build(); scoped_refptr<extensions::Extension> extension = extensions::ExtensionBuilder() .SetManifest(std::move(manifest)) @@ -114,9 +115,9 @@ std::string extension_id_; }; -scoped_ptr<KeyedService> BuildMockHotwordService( +std::unique_ptr<KeyedService> BuildMockHotwordService( content::BrowserContext* context) { - return make_scoped_ptr( + return base::WrapUnique( new MockHotwordService(static_cast<Profile*>(context))); } @@ -166,7 +167,7 @@ // Disabled due to http://crbug.com/503963. TEST_P(HotwordServiceTest, DISABLED_IsHotwordAllowedLocale) { TestingProfile::Builder profile_builder; - scoped_ptr<TestingProfile> profile = profile_builder.Build(); + std::unique_ptr<TestingProfile> profile = profile_builder.Build(); #if defined(ENABLE_HOTWORDING) bool hotwording_enabled = true;
diff --git a/chrome/browser/search/iframe_source_unittest.cc b/chrome/browser/search/iframe_source_unittest.cc index ceaeeafe..9a87bd31 100644 --- a/chrome/browser/search/iframe_source_unittest.cc +++ b/chrome/browser/search/iframe_source_unittest.cc
@@ -4,9 +4,10 @@ #include "chrome/browser/search/iframe_source.h" +#include <memory> + #include "base/bind.h" #include "base/memory/ref_counted_memory.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "chrome/browser/search/instant_io_context.h" #include "content/public/browser/browser_thread.h" @@ -89,16 +90,13 @@ return ""; } - scoped_ptr<net::URLRequest> MockRequest( - const std::string& url, - bool allocate_info, - int render_process_id, - int render_frame_id) { - scoped_ptr<net::URLRequest> request( + std::unique_ptr<net::URLRequest> MockRequest(const std::string& url, + bool allocate_info, + int render_process_id, + int render_frame_id) { + std::unique_ptr<net::URLRequest> request( resource_context_.GetRequestContext()->CreateRequest( - GURL(url), - net::DEFAULT_PRIORITY, - NULL)); + GURL(url), net::DEFAULT_PRIORITY, NULL)); if (allocate_info) { content::ResourceRequestInfo::AllocateForTesting( request.get(), @@ -150,14 +148,14 @@ net::TestURLRequestContext test_url_request_context_; content::MockResourceContext resource_context_; - scoped_ptr<TestIframeSource> source_; + std::unique_ptr<TestIframeSource> source_; content::URLDataSource::GotDataCallback callback_; scoped_refptr<InstantIOContext> instant_io_context_; scoped_refptr<base::RefCountedMemory> response_; }; TEST_F(IframeSourceTest, ShouldServiceRequest) { - scoped_ptr<net::URLRequest> request; + std::unique_ptr<net::URLRequest> request; request = MockRequest("http://test/loader.js", true, kNonInstantRendererPID, 0); EXPECT_FALSE(source()->ShouldServiceRequest(request.get()));
diff --git a/chrome/browser/search/instant_service.h b/chrome/browser/search/instant_service.h index dccf4e7c..b48c844 100644 --- a/chrome/browser/search/instant_service.h +++ b/chrome/browser/search/instant_service.h
@@ -5,12 +5,12 @@ #ifndef CHROME_BROWSER_SEARCH_INSTANT_SERVICE_H_ #define CHROME_BROWSER_SEARCH_INSTANT_SERVICE_H_ +#include <memory> #include <set> #include <vector> #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "components/history/core/browser/history_types.h" @@ -166,7 +166,7 @@ std::vector<InstantMostVisitedItem> suggestions_items_; // Theme-related data for NTP overlay to adopt themes. - scoped_ptr<ThemeBackgroundInfo> theme_info_; + std::unique_ptr<ThemeBackgroundInfo> theme_info_; base::ObserverList<InstantServiceObserver> observers_; @@ -175,18 +175,18 @@ scoped_refptr<InstantIOContext> instant_io_context_; // Set to NULL if the default search provider does not support Instant. - scoped_ptr<InstantSearchPrerenderer> instant_prerenderer_; + std::unique_ptr<InstantSearchPrerenderer> instant_prerenderer_; // Used to check whether notifications from TemplateURLService indicate a // change that affects the default search provider. - scoped_ptr<TemplateURLData> previous_default_search_provider_; + std::unique_ptr<TemplateURLData> previous_default_search_provider_; GURL previous_google_base_url_; // Suggestions Service to fetch server suggestions. suggestions::SuggestionsService* suggestions_service_; // Subscription to the SuggestionsService. - scoped_ptr< + std::unique_ptr< suggestions::SuggestionsService::ResponseCallbackList::Subscription> suggestions_subscription_;
diff --git a/chrome/browser/search/instant_service_unittest.cc b/chrome/browser/search/instant_service_unittest.cc index 92d88bc3b..82fbd37 100644 --- a/chrome/browser/search/instant_service_unittest.cc +++ b/chrome/browser/search/instant_service_unittest.cc
@@ -2,15 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/search/instant_service.h" + +#include <memory> #include <string> #include <tuple> #include <vector> -#include "base/memory/scoped_ptr.h" #include "base/metrics/field_trial.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" -#include "chrome/browser/search/instant_service.h" #include "chrome/browser/search/instant_service_observer.h" #include "chrome/browser/search/instant_unittest_base.h" #include "chrome/browser/search/search.h" @@ -58,7 +59,7 @@ return instant_service_->suggestions_items_; } - scoped_ptr<MockInstantServiceObserver> instant_service_observer_; + std::unique_ptr<MockInstantServiceObserver> instant_service_observer_; }; class InstantServiceEnabledTest : public InstantServiceTest { @@ -100,7 +101,7 @@ } TEST_F(InstantServiceEnabledTest, SendsSearchURLsToRenderer) { - scoped_ptr<content::MockRenderProcessHost> rph( + std::unique_ptr<content::MockRenderProcessHost> rph( new content::MockRenderProcessHost(profile())); rph->sink().ClearMessages(); instant_service_->Observe(
diff --git a/chrome/browser/search/instant_unittest_base.h b/chrome/browser/search/instant_unittest_base.h index 1a13a107..e6bebf5 100644 --- a/chrome/browser/search/instant_unittest_base.h +++ b/chrome/browser/search/instant_unittest_base.h
@@ -47,7 +47,7 @@ InstantService* instant_service_; TemplateURLService* template_url_service_; - scoped_ptr<base::FieldTrialList> field_trial_list_; + std::unique_ptr<base::FieldTrialList> field_trial_list_; private: // BrowserWithTestWindowTest override:
diff --git a/chrome/browser/search/local_files_ntp_source.cc b/chrome/browser/search/local_files_ntp_source.cc index 4c14167..5cce98f 100644 --- a/chrome/browser/search/local_files_ntp_source.cc +++ b/chrome/browser/search/local_files_ntp_source.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/search/local_files_ntp_source.h" +#include <memory> + #if !defined(GOOGLE_CHROME_BUILD) #include "base/bind.h" @@ -11,7 +13,6 @@ #include "base/files/file_util.h" #include "base/location.h" #include "base/memory/ref_counted_memory.h" -#include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/threading/thread_restrictions.h"
diff --git a/chrome/browser/search/local_ntp_source.cc b/chrome/browser/search/local_ntp_source.cc index 108e6279..bf6bfa99 100644 --- a/chrome/browser/search/local_ntp_source.cc +++ b/chrome/browser/search/local_ntp_source.cc
@@ -6,12 +6,13 @@ #include <stddef.h> +#include <memory> + #include "base/command_line.h" #include "base/json/json_string_value_serializer.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/ref_counted_memory.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/field_trial.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" @@ -124,8 +125,8 @@ // Populates |translated_strings| dictionary for the local NTP. |is_google| // indicates that this page is the Google Local NTP. -scoped_ptr<base::DictionaryValue> GetTranslatedStrings(bool is_google) { - scoped_ptr<base::DictionaryValue> translated_strings( +std::unique_ptr<base::DictionaryValue> GetTranslatedStrings(bool is_google) { + std::unique_ptr<base::DictionaryValue> translated_strings( new base::DictionaryValue()); AddString(translated_strings.get(), "thumbnailRemovedNotification",
diff --git a/chrome/browser/search/search_unittest.cc b/chrome/browser/search/search_unittest.cc index 4108dfd..3d96e1e 100644 --- a/chrome/browser/search/search_unittest.cc +++ b/chrome/browser/search/search_unittest.cc
@@ -111,7 +111,7 @@ contents->GetRenderProcessHost()->GetID()); } - scoped_ptr<base::FieldTrialList> field_trial_list_; + std::unique_ptr<base::FieldTrialList> field_trial_list_; }; struct SearchTestCase {
diff --git a/chrome/browser/search/suggestions/image_fetcher_impl_browsertest.cc b/chrome/browser/search/suggestions/image_fetcher_impl_browsertest.cc index 2388f4e..04e9b3fb 100644 --- a/chrome/browser/search/suggestions/image_fetcher_impl_browsertest.cc +++ b/chrome/browser/search/suggestions/image_fetcher_impl_browsertest.cc
@@ -4,10 +4,11 @@ #include "chrome/browser/search/suggestions/image_fetcher_impl.h" +#include <memory> + #include "base/bind.h" #include "base/files/file_path.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" @@ -87,7 +88,7 @@ } void StartOrQueueNetworkRequestHelper(const GURL& image_url) { - scoped_ptr<ImageFetcherImpl> image_fetcher_(CreateImageFetcher()); + std::unique_ptr<ImageFetcherImpl> image_fetcher_(CreateImageFetcher()); base::RunLoop run_loop; image_fetcher_->StartOrQueueNetworkRequest(
diff --git a/chrome/browser/search/suggestions/suggestions_service_factory.cc b/chrome/browser/search/suggestions/suggestions_service_factory.cc index 4edfcfa4..34db255 100644 --- a/chrome/browser/search/suggestions/suggestions_service_factory.cc +++ b/chrome/browser/search/suggestions/suggestions_service_factory.cc
@@ -4,9 +4,9 @@ #include "chrome/browser/search/suggestions/suggestions_service_factory.h" +#include <memory> #include <utility> -#include "base/memory/scoped_ptr.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/suggestions/image_fetcher_impl.h" @@ -71,23 +71,22 @@ ProfileSyncService* sync_service = ProfileSyncServiceFactory::GetForProfile(profile); - scoped_ptr<SuggestionsStore> suggestions_store( + std::unique_ptr<SuggestionsStore> suggestions_store( new SuggestionsStore(profile->GetPrefs())); - scoped_ptr<BlacklistStore> blacklist_store( + std::unique_ptr<BlacklistStore> blacklist_store( new BlacklistStore(profile->GetPrefs())); - scoped_ptr<leveldb_proto::ProtoDatabaseImpl<ImageData> > db( + std::unique_ptr<leveldb_proto::ProtoDatabaseImpl<ImageData>> db( new leveldb_proto::ProtoDatabaseImpl<ImageData>(background_task_runner)); base::FilePath database_dir( profile->GetPath().Append(FILE_PATH_LITERAL("Thumbnails"))); - scoped_ptr<ImageFetcherImpl> image_fetcher( + std::unique_ptr<ImageFetcherImpl> image_fetcher( new ImageFetcherImpl(profile->GetRequestContext())); - scoped_ptr<ImageManager> thumbnail_manager( - new ImageManager( - std::move(image_fetcher), std::move(db), database_dir, - BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB))); + std::unique_ptr<ImageManager> thumbnail_manager(new ImageManager( + std::move(image_fetcher), std::move(db), database_dir, + BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB))); return new SuggestionsService( signin_manager, token_service, sync_service, profile->GetRequestContext(), std::move(suggestions_store), std::move(thumbnail_manager),
diff --git a/chrome/browser/search/suggestions/suggestions_source.cc b/chrome/browser/search/suggestions/suggestions_source.cc index e8804f7..7c237d1 100644 --- a/chrome/browser/search/suggestions/suggestions_source.cc +++ b/chrome/browser/search/suggestions/suggestions_source.cc
@@ -188,7 +188,7 @@ } void SuggestionsSource::OnThumbnailsFetched(RequestContext* context) { - scoped_ptr<RequestContext> context_deleter(context); + std::unique_ptr<RequestContext> context_deleter(context); std::string output = RenderOutputHtml(context->is_refresh, context->suggestions_profile,
diff --git a/chrome/browser/search/thumbnail_source.h b/chrome/browser/search/thumbnail_source.h index f9c9dae..9e645c5 100644 --- a/chrome/browser/search/thumbnail_source.h +++ b/chrome/browser/search/thumbnail_source.h
@@ -5,11 +5,11 @@ #ifndef CHROME_BROWSER_SEARCH_THUMBNAIL_SOURCE_H_ #define CHROME_BROWSER_SEARCH_THUMBNAIL_SOURCE_H_ +#include <memory> #include <string> #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "content/public/browser/url_data_source.h" #include "url/gurl.h" @@ -71,7 +71,7 @@ scoped_refptr<thumbnails::ThumbnailService> thumbnail_service_; // ImageFetcher. - scoped_ptr<suggestions::ImageFetcher> image_fetcher_; + std::unique_ptr<suggestions::ImageFetcher> image_fetcher_; // Indicate that, when a URL for which we don't have a thumbnail is requested // from this source, then Chrome should capture a thumbnail next time it
diff --git a/chrome/browser/search/thumbnail_source_unittest.cc b/chrome/browser/search/thumbnail_source_unittest.cc index 923b4bf..31183733 100644 --- a/chrome/browser/search/thumbnail_source_unittest.cc +++ b/chrome/browser/search/thumbnail_source_unittest.cc
@@ -27,7 +27,7 @@ private: content::TestBrowserThreadBundle thread_bundle_; - scoped_ptr<TestingProfileManager> profile_manager_; + std::unique_ptr<TestingProfileManager> profile_manager_; TestingProfile* profile_; // Owned by TestingProfileManager. };
diff --git a/chrome/browser/service_process/service_process_control.cc b/chrome/browser/service_process/service_process_control.cc index 533f765c..606f629 100644 --- a/chrome/browser/service_process/service_process_control.cc +++ b/chrome/browser/service_process/service_process_control.cc
@@ -58,7 +58,8 @@ BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO).get())); } -void ServiceProcessControl::SetChannel(scoped_ptr<IPC::ChannelProxy> channel) { +void ServiceProcessControl::SetChannel( + std::unique_ptr<IPC::ChannelProxy> channel) { channel_ = std::move(channel); } @@ -118,7 +119,8 @@ UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents", SERVICE_EVENT_LAUNCH, SERVICE_EVENT_MAX); - scoped_ptr<base::CommandLine> cmd_line(CreateServiceProcessCommandLine()); + std::unique_ptr<base::CommandLine> cmd_line( + CreateServiceProcessCommandLine()); // And then start the process asynchronously. launcher_ = new Launcher(std::move(cmd_line)); launcher_->Run(base::Bind(&ServiceProcessControl::OnProcessLaunched, @@ -324,7 +326,7 @@ } ServiceProcessControl::Launcher::Launcher( - scoped_ptr<base::CommandLine> cmd_line) + std::unique_ptr<base::CommandLine> cmd_line) : cmd_line_(std::move(cmd_line)), launched_(false), retry_count_(0) {} // Execute the command line to start the process asynchronously.
diff --git a/chrome/browser/service_process/service_process_control.h b/chrome/browser/service_process/service_process_control.h index 80e18b6b..9fc7e019 100644 --- a/chrome/browser/service_process/service_process_control.h +++ b/chrome/browser/service_process/service_process_control.h
@@ -7,6 +7,7 @@ #include <stdint.h> +#include <memory> #include <queue> #include <set> #include <string> @@ -15,7 +16,6 @@ #include "base/callback.h" #include "base/cancelable_callback.h" #include "base/id_map.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/process/process.h" #include "build/build_config.h" @@ -147,7 +147,7 @@ class Launcher : public base::RefCountedThreadSafe<ServiceProcessControl::Launcher> { public: - explicit Launcher(scoped_ptr<base::CommandLine> cmd_line); + explicit Launcher(std::unique_ptr<base::CommandLine> cmd_line); // Execute the command line to start the process asynchronously. After the // command is executed |task| is called with the process handle on the UI // thread. @@ -165,7 +165,7 @@ void DoRun(); void Notify(); - scoped_ptr<base::CommandLine> cmd_line_; + std::unique_ptr<base::CommandLine> cmd_line_; base::Closure notify_task_; bool launched_; uint32_t retry_count_; @@ -201,12 +201,12 @@ void ConnectInternal(); // Takes ownership of the pointer. Split out for testing. - void SetChannel(scoped_ptr<IPC::ChannelProxy> channel); + void SetChannel(std::unique_ptr<IPC::ChannelProxy> channel); static void RunAllTasksHelper(TaskList* task_list); // IPC channel to the service process. - scoped_ptr<IPC::ChannelProxy> channel_; + std::unique_ptr<IPC::ChannelProxy> channel_; // Service process launcher. scoped_refptr<Launcher> launcher_;
diff --git a/chrome/browser/services/gcm/fake_gcm_profile_service.cc b/chrome/browser/services/gcm/fake_gcm_profile_service.cc index ba20c64..bb68fb5 100644 --- a/chrome/browser/services/gcm/fake_gcm_profile_service.cc +++ b/chrome/browser/services/gcm/fake_gcm_profile_service.cc
@@ -119,10 +119,11 @@ } // namespace // static -scoped_ptr<KeyedService> FakeGCMProfileService::Build( +std::unique_ptr<KeyedService> FakeGCMProfileService::Build( content::BrowserContext* context) { Profile* profile = static_cast<Profile*>(context); - scoped_ptr<FakeGCMProfileService> service(new FakeGCMProfileService(profile)); + std::unique_ptr<FakeGCMProfileService> service( + new FakeGCMProfileService(profile)); service->SetDriverForTesting(new CustomFakeGCMDriver(service.get())); return std::move(service); }
diff --git a/chrome/browser/services/gcm/fake_gcm_profile_service.h b/chrome/browser/services/gcm/fake_gcm_profile_service.h index 57d114a..aabba5e5 100644 --- a/chrome/browser/services/gcm/fake_gcm_profile_service.h +++ b/chrome/browser/services/gcm/fake_gcm_profile_service.h
@@ -6,10 +6,10 @@ #define CHROME_BROWSER_SERVICES_GCM_FAKE_GCM_PROFILE_SERVICE_H_ #include <list> +#include <memory> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "components/gcm_driver/gcm_driver.h" #include "components/gcm_driver/gcm_profile_service.h" @@ -28,7 +28,7 @@ // Helper function to be used with // KeyedService::SetTestingFactory(). - static scoped_ptr<KeyedService> Build(content::BrowserContext* context); + static std::unique_ptr<KeyedService> Build(content::BrowserContext* context); explicit FakeGCMProfileService(Profile* profile); ~FakeGCMProfileService() override;
diff --git a/chrome/browser/services/gcm/gcm_profile_service_factory.cc b/chrome/browser/services/gcm/gcm_profile_service_factory.cc index 7e506fe..1ea2058 100644 --- a/chrome/browser/services/gcm/gcm_profile_service_factory.cc +++ b/chrome/browser/services/gcm/gcm_profile_service_factory.cc
@@ -4,7 +4,8 @@ #include "chrome/browser/services/gcm/gcm_profile_service_factory.h" -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "build/build_config.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" @@ -71,11 +72,11 @@ return new GCMProfileService( profile->GetPrefs(), profile->GetPath(), profile->GetRequestContext(), chrome::GetChannel(), - scoped_ptr<ProfileIdentityProvider>(new ProfileIdentityProvider( + std::unique_ptr<ProfileIdentityProvider>(new ProfileIdentityProvider( SigninManagerFactory::GetForProfile(profile), ProfileOAuth2TokenServiceFactory::GetForProfile(profile), LoginUIServiceFactory::GetShowLoginPopupCallbackForProfile(profile))), - scoped_ptr<GCMClientFactory>(new GCMClientFactory), + std::unique_ptr<GCMClientFactory>(new GCMClientFactory), content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::UI), content::BrowserThread::GetMessageLoopProxyForThread(
diff --git a/chrome/browser/services/gcm/gcm_profile_service_unittest.cc b/chrome/browser/services/gcm/gcm_profile_service_unittest.cc index 33a68cd..3247467 100644 --- a/chrome/browser/services/gcm/gcm_profile_service_unittest.cc +++ b/chrome/browser/services/gcm/gcm_profile_service_unittest.cc
@@ -2,15 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/gcm_driver/gcm_profile_service.h" - +#include <memory> #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "build/build_config.h" #include "chrome/browser/services/gcm/gcm_profile_service_factory.h" @@ -19,6 +18,7 @@ #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/common/channel_info.h" #include "chrome/test/base/testing_profile.h" +#include "components/gcm_driver/gcm_profile_service.h" #if defined(OS_CHROMEOS) #include "chromeos/dbus/dbus_thread_manager.h" #endif @@ -42,7 +42,7 @@ const char kTestAppID[] = "TestApp"; const char kUserID[] = "user"; -scoped_ptr<KeyedService> BuildGCMProfileService( +std::unique_ptr<KeyedService> BuildGCMProfileService( content::BrowserContext* context) { Profile* profile = Profile::FromBrowserContext(context); base::SequencedWorkerPool* worker_pool = @@ -51,14 +51,14 @@ worker_pool->GetSequencedTaskRunnerWithShutdownBehavior( worker_pool->GetSequenceToken(), base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)); - return make_scoped_ptr(new gcm::GCMProfileService( + return base::WrapUnique(new gcm::GCMProfileService( profile->GetPrefs(), profile->GetPath(), profile->GetRequestContext(), chrome::GetChannel(), - scoped_ptr<ProfileIdentityProvider>(new ProfileIdentityProvider( + std::unique_ptr<ProfileIdentityProvider>(new ProfileIdentityProvider( SigninManagerFactory::GetForProfile(profile), ProfileOAuth2TokenServiceFactory::GetForProfile(profile), LoginUIServiceFactory::GetShowLoginPopupCallbackForProfile(profile))), - scoped_ptr<gcm::GCMClientFactory>(new gcm::FakeGCMClientFactory( + std::unique_ptr<gcm::GCMClientFactory>(new gcm::FakeGCMClientFactory( content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::UI), content::BrowserThread::GetMessageLoopProxyForThread( @@ -109,9 +109,9 @@ private: content::TestBrowserThreadBundle thread_bundle_; - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<TestingProfile> profile_; GCMProfileService* gcm_profile_service_; - scoped_ptr<FakeGCMAppHandler> gcm_app_handler_; + std::unique_ptr<FakeGCMAppHandler> gcm_app_handler_; std::string registration_id_; GCMClient::Result registration_result_;
diff --git a/chrome/browser/services/gcm/instance_id/instance_id_profile_service.h b/chrome/browser/services/gcm/instance_id/instance_id_profile_service.h index c243378..ff83531 100644 --- a/chrome/browser/services/gcm/instance_id/instance_id_profile_service.h +++ b/chrome/browser/services/gcm/instance_id/instance_id_profile_service.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_SERVICES_GCM_INSTANCE_ID_INSTANCE_ID_PROFILE_SERVICE_H_ #define CHROME_BROWSER_SERVICES_GCM_INSTANCE_ID_INSTANCE_ID_PROFILE_SERVICE_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "components/keyed_service/core/keyed_service.h" class Profile; @@ -27,7 +28,7 @@ InstanceIDDriver* driver() const { return driver_.get(); } private: - scoped_ptr<InstanceIDDriver> driver_; + std::unique_ptr<InstanceIDDriver> driver_; DISALLOW_COPY_AND_ASSIGN(InstanceIDProfileService); };
diff --git a/chrome/browser/services/gcm/instance_id/instance_id_profile_service_factory.cc b/chrome/browser/services/gcm/instance_id/instance_id_profile_service_factory.cc index 1bc848f4..408c1e9 100644 --- a/chrome/browser/services/gcm/instance_id/instance_id_profile_service_factory.cc +++ b/chrome/browser/services/gcm/instance_id/instance_id_profile_service_factory.cc
@@ -4,7 +4,8 @@ #include "chrome/browser/services/gcm/instance_id/instance_id_profile_service_factory.h" -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/services/gcm/gcm_profile_service_factory.h"
diff --git a/chrome/browser/sessions/better_session_restore_browsertest.cc b/chrome/browser/sessions/better_session_restore_browsertest.cc index 7723014cc..07a97238 100644 --- a/chrome/browser/sessions/better_session_restore_browsertest.cc +++ b/chrome/browser/sessions/better_session_restore_browsertest.cc
@@ -102,7 +102,7 @@ const net::UploadDataStream* upload_data = request->get_upload(); last_upload_bytes_.clear(); if (upload_data) { - const std::vector<scoped_ptr<net::UploadElementReader>>* readers = + const std::vector<std::unique_ptr<net::UploadElementReader>>* readers = upload_data->GetElementReaders(); if (readers) { for (size_t i = 0; i < readers->size(); ++i) { @@ -187,13 +187,13 @@ CHECK(base::ReadFileToString(path, &contents)); net::URLRequestFilter::GetInstance()->AddUrlInterceptor( GURL(fake_server_address_ + test_path_ + *it), - scoped_ptr<net::URLRequestInterceptor>( + std::unique_ptr<net::URLRequestInterceptor>( new URLRequestFakerInterceptor(contents))); } post_interceptor_ = new URLRequestFakerForPostRequestsInterceptor(); net::URLRequestFilter::GetInstance()->AddUrlInterceptor( GURL(fake_server_address_ + test_path_ + "posted.php"), - scoped_ptr<net::URLRequestInterceptor>(post_interceptor_)); + std::unique_ptr<net::URLRequestInterceptor>(post_interceptor_)); } protected: @@ -203,7 +203,7 @@ helper.SetForceBrowserNotAliveWithNoWindows(true); helper.ReleaseService(); g_browser_process->set_background_mode_manager_for_test( - scoped_ptr<BackgroundModeManager>(new FakeBackgroundModeManager)); + std::unique_ptr<BackgroundModeManager>(new FakeBackgroundModeManager)); } void StoreDataWithPage(const std::string& filename) {
diff --git a/chrome/browser/sessions/persistent_tab_restore_service_unittest.cc b/chrome/browser/sessions/persistent_tab_restore_service_unittest.cc index 17e99a1..2e0825b4 100644 --- a/chrome/browser/sessions/persistent_tab_restore_service_unittest.cc +++ b/chrome/browser/sessions/persistent_tab_restore_service_unittest.cc
@@ -5,11 +5,13 @@ #include "components/sessions/core/persistent_tab_restore_service.h" #include <stddef.h> + #include <string> #include <utility> #include "base/compiler_specific.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -84,10 +86,10 @@ // testing::Test: void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); - live_tab_ = make_scoped_ptr(new sessions::ContentLiveTab(web_contents())); + live_tab_ = base::WrapUnique(new sessions::ContentLiveTab(web_contents())); time_factory_ = new PersistentTabRestoreTimeFactory(); service_.reset(new sessions::PersistentTabRestoreService( - make_scoped_ptr(new ChromeTabRestoreServiceClient(profile())), + base::WrapUnique(new ChromeTabRestoreServiceClient(profile())), time_factory_)); } @@ -127,7 +129,7 @@ content::RunAllBlockingPoolTasksUntilIdle(); service_.reset(); service_.reset(new sessions::PersistentTabRestoreService( - make_scoped_ptr(new ChromeTabRestoreServiceClient(profile())), + base::WrapUnique(new ChromeTabRestoreServiceClient(profile())), time_factory_)); SynchronousLoadTabsFromLastSession(); } @@ -158,7 +160,8 @@ // way of AddWindowWithOneTabToSessionService. If |pinned| is true, the // tab is marked as pinned in the session service. void CreateSessionServiceWithOneWindow(bool pinned) { - scoped_ptr<SessionService> session_service(new SessionService(profile())); + std::unique_ptr<SessionService> session_service( + new SessionService(profile())); SessionServiceFactory::SetForTestProfile(profile(), std::move(session_service)); @@ -180,8 +183,8 @@ GURL url2_; GURL url3_; std::string user_agent_override_; - scoped_ptr<sessions::LiveTab> live_tab_; - scoped_ptr<sessions::PersistentTabRestoreService> service_; + std::unique_ptr<sessions::LiveTab> live_tab_; + std::unique_ptr<sessions::PersistentTabRestoreService> service_; PersistentTabRestoreTimeFactory* time_factory_; };
diff --git a/chrome/browser/sessions/restore_on_startup_policy_handler_unittest.cc b/chrome/browser/sessions/restore_on_startup_policy_handler_unittest.cc index 9833a89..d9d3d2a 100644 --- a/chrome/browser/sessions/restore_on_startup_policy_handler_unittest.cc +++ b/chrome/browser/sessions/restore_on_startup_policy_handler_unittest.cc
@@ -2,15 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/sessions/restore_on_startup_policy_handler.h" + +#include <memory> #include <string> #include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/prefs/session_startup_pref.h" -#include "chrome/browser/sessions/restore_on_startup_policy_handler.h" #include "chrome/common/pref_names.h" #include "components/policy/core/browser/configuration_policy_handler.h" #include "components/policy/core/browser/policy_error_map.h" @@ -102,7 +103,7 @@ SetPolicyValue( key::kRestoreOnStartup, new base::FundamentalValue(SessionStartupPref::kPrefValueLast)); - scoped_ptr<base::ListValue> urls(new base::ListValue); + std::unique_ptr<base::ListValue> urls(new base::ListValue); urls->AppendString("http://foo.com"); SetPolicyValue(key::kCookiesSessionOnlyForUrls, urls.release()); // Checking should succeed but add an error to the error map.
diff --git a/chrome/browser/sessions/session_restore.cc b/chrome/browser/sessions/session_restore.cc index ada8811e..19abe46125 100644 --- a/chrome/browser/sessions/session_restore.cc +++ b/chrome/browser/sessions/session_restore.cc
@@ -8,6 +8,7 @@ #include <algorithm> #include <list> +#include <memory> #include <set> #include <string> @@ -17,7 +18,6 @@ #include "base/command_line.h" #include "base/debug/alias.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram.h" @@ -719,7 +719,7 @@ // When asynchronous it's possible for there to be no windows. To make sure // Chrome doesn't prematurely exit we register a KeepAlive for the lifetime // of this object. - scoped_ptr<ScopedKeepAlive> keep_alive_; + std::unique_ptr<ScopedKeepAlive> keep_alive_; // The time we started the restore. base::TimeTicks restore_started_;
diff --git a/chrome/browser/sessions/session_restore.h b/chrome/browser/sessions/session_restore.h index 5f9c901..c37666a 100644 --- a/chrome/browser/sessions/session_restore.h +++ b/chrome/browser/sessions/session_restore.h
@@ -46,7 +46,7 @@ // Used by objects calling RegisterOnSessionRestoredCallback() to de-register // themselves when they are destroyed. using CallbackSubscription = - scoped_ptr<base::CallbackList<void(int)>::Subscription>; + std::unique_ptr<base::CallbackList<void(int)>::Subscription>; // Restores the last session. |behavior| is a bitmask of Behaviors, see it // for details. If |browser| is non-null the tabs for the first window are
diff --git a/chrome/browser/sessions/session_restore_android.cc b/chrome/browser/sessions/session_restore_android.cc index 0c4d42c..812d85b 100644 --- a/chrome/browser/sessions/session_restore_android.cc +++ b/chrome/browser/sessions/session_restore_android.cc
@@ -30,7 +30,7 @@ Profile* profile = Profile::FromBrowserContext(context); TabModel* tab_model = TabModelList::GetTabModelForWebContents(web_contents); DCHECK(tab_model); - std::vector<scoped_ptr<content::NavigationEntry>> entries = + std::vector<std::unique_ptr<content::NavigationEntry>> entries = sessions::ContentSerializedNavigationBuilder::ToNavigationEntries( session_tab.navigations, profile); content::WebContents* new_web_contents = content::WebContents::Create(
diff --git a/chrome/browser/sessions/session_restore_browsertest.cc b/chrome/browser/sessions/session_restore_browsertest.cc index 35277ad..a40d9bf9 100644 --- a/chrome/browser/sessions/session_restore_browsertest.cc +++ b/chrome/browser/sessions/session_restore_browsertest.cc
@@ -129,7 +129,7 @@ Profile* profile = browser->profile(); // Close the browser. - scoped_ptr<ScopedKeepAlive> keep_alive(new ScopedKeepAlive( + std::unique_ptr<ScopedKeepAlive> keep_alive(new ScopedKeepAlive( KeepAliveOrigin::SESSION_RESTORE, KeepAliveRestartOption::DISABLED)); CloseBrowserSynchronously(browser); @@ -1361,15 +1361,15 @@ content::SessionStorageNamespaceMap session_storage_namespace_map; session_storage_namespace_map[std::string()] = controller->GetDefaultSessionStorageNamespace(); - scoped_ptr<content::WebContents> web_contents( + std::unique_ptr<content::WebContents> web_contents( content::WebContents::CreateWithSessionStorage( content::WebContents::CreateParams(browser()->profile()), session_storage_namespace_map)); TabStripModel* tab_strip_model = browser()->tab_strip_model(); - scoped_ptr<content::WebContents> old_web_contents( - tab_strip_model->ReplaceWebContentsAt( - tab_strip_model->active_index(), web_contents.release())); + std::unique_ptr<content::WebContents> old_web_contents( + tab_strip_model->ReplaceWebContentsAt(tab_strip_model->active_index(), + web_contents.release())); // Navigate with the new tab. ui_test_utils::NavigateToURL(browser(), url2_); // old_web_contents goes out of scope. @@ -1408,7 +1408,7 @@ browser()->tab_strip_model()->ActivateTabAt(i, true); // Close the browser. - scoped_ptr<ScopedKeepAlive> keep_alive(new ScopedKeepAlive( + std::unique_ptr<ScopedKeepAlive> keep_alive(new ScopedKeepAlive( KeepAliveOrigin::SESSION_RESTORE, KeepAliveRestartOption::DISABLED)); CloseBrowserSynchronously(browser()); @@ -1452,7 +1452,7 @@ // Close the browser that gets opened automatically so we can track the order // of loading of the tabs. - scoped_ptr<ScopedKeepAlive> keep_alive(new ScopedKeepAlive( + std::unique_ptr<ScopedKeepAlive> keep_alive(new ScopedKeepAlive( KeepAliveOrigin::SESSION_RESTORE, KeepAliveRestartOption::DISABLED)); CloseBrowserSynchronously(browser()); // We have an extra tab that is added when the test starts, which gets ignored
diff --git a/chrome/browser/sessions/session_restore_stats_collector.cc b/chrome/browser/sessions/session_restore_stats_collector.cc index 41c0397..0231062 100644 --- a/chrome/browser/sessions/session_restore_stats_collector.cc +++ b/chrome/browser/sessions/session_restore_stats_collector.cc
@@ -111,7 +111,7 @@ SessionRestoreStatsCollector::SessionRestoreStatsCollector( const base::TimeTicks& restore_started, - scoped_ptr<StatsReportingDelegate> reporting_delegate) + std::unique_ptr<StatsReportingDelegate> reporting_delegate) : done_tracking_non_deferred_tabs_(false), got_first_foreground_load_(false), got_first_paint_(false),
diff --git a/chrome/browser/sessions/session_restore_stats_collector.h b/chrome/browser/sessions/session_restore_stats_collector.h index dbcb69f..e7e3a883 100644 --- a/chrome/browser/sessions/session_restore_stats_collector.h +++ b/chrome/browser/sessions/session_restore_stats_collector.h
@@ -119,7 +119,7 @@ // Constructs a SessionRestoreStatsCollector. SessionRestoreStatsCollector( const base::TimeTicks& restore_started, - scoped_ptr<StatsReportingDelegate> reporting_delegate); + std::unique_ptr<StatsReportingDelegate> reporting_delegate); // Adds new tabs to the list of tracked tabs. void TrackTabs(const std::vector<SessionRestoreDelegate::RestoredTab>& tabs); @@ -186,7 +186,7 @@ void ReleaseIfDoneTracking(); // Testing seam for configuring the tick clock in use. - void set_tick_clock(scoped_ptr<base::TickClock> tick_clock) { + void set_tick_clock(std::unique_ptr<base::TickClock> tick_clock) { tick_clock_ = std::move(tick_clock); } @@ -225,10 +225,10 @@ // The source of ticks used for taking timing information. This is // configurable as a testing seam. Defaults to using base::DefaultTickClock, // which in turn uses base::TimeTicks. - scoped_ptr<base::TickClock> tick_clock_; + std::unique_ptr<base::TickClock> tick_clock_; // The reporting delegate used to report gathered statistics. - scoped_ptr<StatsReportingDelegate> reporting_delegate_; + std::unique_ptr<StatsReportingDelegate> reporting_delegate_; // For keeping SessionRestoreStatsCollector alive while it is still working // even if no TabLoader references it. The object only lives on if it still
diff --git a/chrome/browser/sessions/session_restore_stats_collector_unittest.cc b/chrome/browser/sessions/session_restore_stats_collector_unittest.cc index 45d1c0c..26e25db 100644 --- a/chrome/browser/sessions/session_restore_stats_collector_unittest.cc +++ b/chrome/browser/sessions/session_restore_stats_collector_unittest.cc
@@ -160,8 +160,8 @@ using SessionRestoreStatsCollector::Observe; TestSessionRestoreStatsCollector( - scoped_ptr<base::TickClock> tick_clock, - scoped_ptr<StatsReportingDelegate> reporting_delegate) + std::unique_ptr<base::TickClock> tick_clock, + std::unique_ptr<StatsReportingDelegate> reporting_delegate) : SessionRestoreStatsCollector(tick_clock->NowTicks(), std::move(reporting_delegate)) { set_tick_clock(std::move(tick_clock)); @@ -203,8 +203,8 @@ // its job, and will clean itself up when done. scoped_refptr<TestSessionRestoreStatsCollector> stats_collector = new TestSessionRestoreStatsCollector( - scoped_ptr<base::TickClock>(test_tick_clock_), - scoped_ptr<StatsReportingDelegate>( + std::unique_ptr<base::TickClock>(test_tick_clock_), + std::unique_ptr<StatsReportingDelegate>( passthrough_reporting_delegate_)); stats_collector_ = stats_collector.get(); stats_collector = nullptr; @@ -301,7 +301,7 @@ // A new web contents factory is generated per test. This automatically cleans // up any tabs created by previous tests. - scoped_ptr<content::TestWebContentsFactory> test_web_contents_factory_; + std::unique_ptr<content::TestWebContentsFactory> test_web_contents_factory_; // These are recreated for each test. The reporting delegate allows the test // to observe the behaviour of the SessionRestoreStatsCollector under test.
diff --git a/chrome/browser/sessions/session_restore_test_helper.h b/chrome/browser/sessions/session_restore_test_helper.h index 26f32d9..b72f1b8 100644 --- a/chrome/browser/sessions/session_restore_test_helper.h +++ b/chrome/browser/sessions/session_restore_test_helper.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_SESSIONS_SESSION_RESTORE_TEST_HELPER_H_ #define CHROME_BROWSER_SESSIONS_SESSION_RESTORE_TEST_HELPER_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/sessions/session_restore.h"
diff --git a/chrome/browser/sessions/session_service.cc b/chrome/browser/sessions/session_service.cc index 43ed6e3..74fcfae 100644 --- a/chrome/browser/sessions/session_service.cc +++ b/chrome/browser/sessions/session_service.cc
@@ -869,7 +869,7 @@ } void SessionService::ScheduleCommand( - scoped_ptr<sessions::SessionCommand> command) { + std::unique_ptr<sessions::SessionCommand> command) { DCHECK(command); if (ReplacePendingCommand(base_session_service_.get(), &command)) return;
diff --git a/chrome/browser/sessions/session_service.h b/chrome/browser/sessions/session_service.h index 0986a6e76..3653df1 100644 --- a/chrome/browser/sessions/session_service.h +++ b/chrome/browser/sessions/session_service.h
@@ -293,7 +293,7 @@ void ScheduleResetCommands(); // Schedules the specified command. - void ScheduleCommand(scoped_ptr<sessions::SessionCommand> command); + void ScheduleCommand(std::unique_ptr<sessions::SessionCommand> command); // Converts all pending tab/window closes to commands and schedules them. void CommitPendingCloses(); @@ -342,7 +342,7 @@ bool should_use_delayed_save_; // The owned BaseSessionService. - scoped_ptr<sessions::BaseSessionService> base_session_service_; + std::unique_ptr<sessions::BaseSessionService> base_session_service_; content::NotificationRegistrar registrar_;
diff --git a/chrome/browser/sessions/session_service_factory.h b/chrome/browser/sessions/session_service_factory.h index 852a955..0be6e27e 100644 --- a/chrome/browser/sessions/session_service_factory.h +++ b/chrome/browser/sessions/session_service_factory.h
@@ -48,7 +48,7 @@ // For test use: force setting of the session service for a given profile. // This will delete a previous session service for this profile if it exists. static void SetForTestProfile(Profile* profile, - scoped_ptr<SessionService> service) { + std::unique_ptr<SessionService> service) { GetInstance()->BrowserContextShutdown(profile); GetInstance()->BrowserContextDestroyed(profile); GetInstance()->Associate(profile, std::move(service));
diff --git a/chrome/browser/sessions/session_service_test_helper.h b/chrome/browser/sessions/session_service_test_helper.h index 036e9a41..8ecd405 100644 --- a/chrome/browser/sessions/session_service_test_helper.h +++ b/chrome/browser/sessions/session_service_test_helper.h
@@ -7,11 +7,11 @@ #include <stddef.h> +#include <memory> #include <string> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "components/sessions/core/session_id.h" @@ -84,7 +84,7 @@ const base::Closure& task); private: - scoped_ptr<SessionService> service_; + std::unique_ptr<SessionService> service_; DISALLOW_COPY_AND_ASSIGN(SessionServiceTestHelper); };
diff --git a/chrome/browser/sessions/session_service_unittest.cc b/chrome/browser/sessions/session_service_unittest.cc index dfa5f3b..661b652b 100644 --- a/chrome/browser/sessions/session_service_unittest.cc +++ b/chrome/browser/sessions/session_service_unittest.cc
@@ -2,14 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/sessions/session_service.h" + #include <stddef.h> +#include <memory> + #include "base/bind.h" #include "base/bind_helpers.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/location.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" @@ -25,7 +28,6 @@ #include "chrome/browser/profiles/profile_attributes_entry.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_manager.h" -#include "chrome/browser/sessions/session_service.h" #include "chrome/browser/sessions/session_service_test_helper.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/url_constants.h" @@ -185,7 +187,7 @@ base::FilePath path_; SessionServiceTestHelper helper_; - scoped_ptr<TestingProfileManager> profile_manager_; + std::unique_ptr<TestingProfileManager> profile_manager_; }; TEST_F(SessionServiceTest, Basic) {
diff --git a/chrome/browser/sessions/tab_loader.cc b/chrome/browser/sessions/tab_loader.cc index 676db80..5f47db8 100644 --- a/chrome/browser/sessions/tab_loader.cc +++ b/chrome/browser/sessions/tab_loader.cc
@@ -8,6 +8,7 @@ #include <string> #include "base/memory/memory_pressure_monitor.h" +#include "base/memory/ptr_util.h" #include "base/metrics/histogram.h" #include "base/strings/stringprintf.h" #include "build/build_config.h" @@ -83,7 +84,7 @@ restore_started_(restore_started) { stats_collector_ = new SessionRestoreStatsCollector( restore_started, - make_scoped_ptr( + base::WrapUnique( new SessionRestoreStatsCollector::UmaStatsReportingDelegate())); shared_tab_loader_ = this; this_retainer_ = this;
diff --git a/chrome/browser/sessions/tab_loader.h b/chrome/browser/sessions/tab_loader.h index 8a064481..1ae274c 100644 --- a/chrome/browser/sessions/tab_loader.h +++ b/chrome/browser/sessions/tab_loader.h
@@ -8,11 +8,11 @@ #include <stddef.h> #include <list> +#include <memory> #include <set> #include "base/macros.h" #include "base/memory/memory_pressure_listener.h" -#include "base/memory/scoped_ptr.h" #include "base/timer/timer.h" #include "chrome/browser/sessions/session_restore_delegate.h" #include "chrome/browser/sessions/tab_loader_delegate.h" @@ -111,7 +111,7 @@ void OnMemoryPressure( base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level); - scoped_ptr<TabLoaderDelegate> delegate_; + std::unique_ptr<TabLoaderDelegate> delegate_; // Listens for system under memory pressure notifications and stops loading // of tabs when we start running out of memory.
diff --git a/chrome/browser/sessions/tab_loader_delegate.cc b/chrome/browser/sessions/tab_loader_delegate.cc index 598996e4..72ba8ddd 100644 --- a/chrome/browser/sessions/tab_loader_delegate.cc +++ b/chrome/browser/sessions/tab_loader_delegate.cc
@@ -82,8 +82,8 @@ } // namespace // static -scoped_ptr<TabLoaderDelegate> TabLoaderDelegate::Create( +std::unique_ptr<TabLoaderDelegate> TabLoaderDelegate::Create( TabLoaderCallback* callback) { - return scoped_ptr<TabLoaderDelegate>( + return std::unique_ptr<TabLoaderDelegate>( new TabLoaderDelegateImpl(callback)); }
diff --git a/chrome/browser/sessions/tab_loader_delegate.h b/chrome/browser/sessions/tab_loader_delegate.h index e396ac5..19837ab 100644 --- a/chrome/browser/sessions/tab_loader_delegate.h +++ b/chrome/browser/sessions/tab_loader_delegate.h
@@ -5,7 +5,8 @@ #ifndef CHROME_BROWSER_SESSIONS_TAB_LOADER_DELEGATE_H_ #define CHROME_BROWSER_SESSIONS_TAB_LOADER_DELEGATE_H_ -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "base/time/time.h" class TabLoaderCallback { @@ -25,7 +26,7 @@ // Create a tab loader delegate. |TabLoaderCallback::SetTabLoadingEnabled| can // get called to disable / enable tab loading. // The callback object is valid as long as this object exists. - static scoped_ptr<TabLoaderDelegate> Create(TabLoaderCallback* callback); + static std::unique_ptr<TabLoaderDelegate> Create(TabLoaderCallback* callback); // Returns the default timeout time after which the first non-visible tab // gets loaded if the first (visible) tab did not finish loading.
diff --git a/chrome/browser/sessions/tab_restore_service_factory.cc b/chrome/browser/sessions/tab_restore_service_factory.cc index 8ccb1ff..44ea403 100644 --- a/chrome/browser/sessions/tab_restore_service_factory.cc +++ b/chrome/browser/sessions/tab_restore_service_factory.cc
@@ -58,7 +58,7 @@ content::BrowserContext* browser_context) const { Profile* profile = Profile::FromBrowserContext(browser_context); DCHECK(!profile->IsOffTheRecord()); - scoped_ptr<sessions::TabRestoreServiceClient> client( + std::unique_ptr<sessions::TabRestoreServiceClient> client( new ChromeTabRestoreServiceClient(profile)); #if defined(OS_ANDROID)
diff --git a/chrome/browser/shell_integration_linux.cc b/chrome/browser/shell_integration_linux.cc index 020c33a..d6f5c65 100644 --- a/chrome/browser/shell_integration_linux.cc +++ b/chrome/browser/shell_integration_linux.cc
@@ -7,6 +7,8 @@ #include <fcntl.h> #include <stddef.h> +#include <memory> + #if defined(USE_GLIB) #include <glib.h> #endif @@ -28,7 +30,6 @@ #include "base/files/scoped_temp_dir.h" #include "base/i18n/file_util_icu.h" #include "base/memory/ref_counted_memory.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/nix/xdg_util.h" #include "base/path_service.h" @@ -137,7 +138,7 @@ #if defined(OS_CHROMEOS) return true; #else - scoped_ptr<base::Environment> env(base::Environment::Create()); + std::unique_ptr<base::Environment> env(base::Environment::Create()); std::vector<std::string> argv; argv.push_back(kXdgSettings); @@ -171,7 +172,7 @@ #else base::ThreadRestrictions::AssertIOAllowed(); - scoped_ptr<base::Environment> env(base::Environment::Create()); + std::unique_ptr<base::Environment> env(base::Environment::Create()); std::vector<std::string> argv; argv.push_back(kXdgSettings); @@ -528,7 +529,7 @@ // never happen. base::FilePath GetChromeExePath() { // Try to get the name of the wrapper script that launched Chrome. - scoped_ptr<base::Environment> environment(base::Environment::Create()); + std::unique_ptr<base::Environment> environment(base::Environment::Create()); std::string wrapper_script; if (environment->GetVar("CHROME_WRAPPER", &wrapper_script)) return base::FilePath(wrapper_script); @@ -570,7 +571,7 @@ } std::string GetProgramClassName() { - scoped_ptr<base::Environment> env(base::Environment::Create()); + std::unique_ptr<base::Environment> env(base::Environment::Create()); std::string desktop_file(GetDesktopName(env.get())); std::size_t last = desktop_file.find(".desktop"); if (last != std::string::npos) @@ -1031,7 +1032,7 @@ void DeleteAllDesktopShortcuts(const base::FilePath& profile_path) { DCHECK_CURRENTLY_ON(BrowserThread::FILE); - scoped_ptr<base::Environment> env(base::Environment::Create()); + std::unique_ptr<base::Environment> env(base::Environment::Create()); // Delete shortcuts from Desktop. base::FilePath desktop_path;
diff --git a/chrome/browser/shell_integration_win.cc b/chrome/browser/shell_integration_win.cc index e4fecf5..a23aaa42 100644 --- a/chrome/browser/shell_integration_win.cc +++ b/chrome/browser/shell_integration_win.cc
@@ -19,6 +19,7 @@ #include "base/files/file_enumerator.h" #include "base/files/file_util.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" #include "base/message_loop/message_loop.h" #include "base/metrics/histogram_macros.h" @@ -304,7 +305,7 @@ // Helper function to create a registry watcher for a given |key_path|. Do // nothing on initialization failure. void AddRegistryKeyWatcher(const wchar_t* key_path) { - auto reg_key = make_scoped_ptr( + auto reg_key = base::WrapUnique( new base::win::RegKey(HKEY_CURRENT_USER, key_path, KEY_NOTIFY)); if (reg_key->Valid() && @@ -325,7 +326,7 @@ // There can be multiple registry key watchers as some settings modify // multiple protocol associations. e.g. Changing the default browser modifies // the http and https associations. - std::vector<scoped_ptr<base::win::RegKey>> registry_key_watchers_; + std::vector<std::unique_ptr<base::win::RegKey>> registry_key_watchers_; base::OneShotTimer timer_;
diff --git a/chrome/browser/signin/account_reconcilor_unittest.cc b/chrome/browser/signin/account_reconcilor_unittest.cc index 9e06da4..35e10e5 100644 --- a/chrome/browser/signin/account_reconcilor_unittest.cc +++ b/chrome/browser/signin/account_reconcilor_unittest.cc
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <memory> #include <utility> #include "base/command_line.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/test/histogram_tester.h" @@ -47,7 +47,7 @@ class MockAccountReconcilor : public testing::StrictMock<AccountReconcilor> { public: - static scoped_ptr<KeyedService> Build(content::BrowserContext* context); + static std::unique_ptr<KeyedService> Build(content::BrowserContext* context); MockAccountReconcilor(ProfileOAuth2TokenService* token_service, SigninManagerBase* signin_manager, @@ -60,10 +60,10 @@ }; // static -scoped_ptr<KeyedService> MockAccountReconcilor::Build( +std::unique_ptr<KeyedService> MockAccountReconcilor::Build( content::BrowserContext* context) { Profile* profile = Profile::FromBrowserContext(context); - scoped_ptr<AccountReconcilor> reconcilor(new MockAccountReconcilor( + std::unique_ptr<AccountReconcilor> reconcilor(new MockAccountReconcilor( ProfileOAuth2TokenServiceFactory::GetForProfile(profile), SigninManagerFactory::GetForProfile(profile), ChromeSigninClientFactory::GetForProfile(profile), @@ -141,7 +141,7 @@ FakeGaiaCookieManagerService* cookie_manager_service_; MockAccountReconcilor* mock_reconcilor_; net::FakeURLFetcherFactory url_fetcher_factory_; - scoped_ptr<TestingProfileManager> testing_profile_manager_; + std::unique_ptr<TestingProfileManager> testing_profile_manager_; base::HistogramTester histogram_tester_; GURL get_check_connection_info_url_; @@ -186,10 +186,9 @@ factories.push_back(std::make_pair(AccountReconcilorFactory::GetInstance(), MockAccountReconcilor::Build)); - profile_ = testing_profile_manager_.get()->CreateTestingProfile("name", - scoped_ptr<syncable_prefs::PrefServiceSyncable>(), - base::UTF8ToUTF16("name"), 0, std::string(), - factories); + profile_ = testing_profile_manager_.get()->CreateTestingProfile( + "name", std::unique_ptr<syncable_prefs::PrefServiceSyncable>(), + base::UTF8ToUTF16("name"), 0, std::string(), factories); test_signin_client_ = static_cast<TestSigninClient*>( @@ -473,8 +472,8 @@ AccountReconcilorFactory::GetForProfile(profile()); ASSERT_TRUE(reconcilor); - scoped_ptr<ContentSettingsPattern::BuilderInterface> - builder(ContentSettingsPattern::CreateBuilder(false)); + std::unique_ptr<ContentSettingsPattern::BuilderInterface> builder( + ContentSettingsPattern::CreateBuilder(false)); builder->Invalid(); SimulateCookieContentSettingsChanged(reconcilor, builder->Build());
diff --git a/chrome/browser/signin/account_tracker_service_factory.cc b/chrome/browser/signin/account_tracker_service_factory.cc index 2b2a359..bb9784f 100644 --- a/chrome/browser/signin/account_tracker_service_factory.cc +++ b/chrome/browser/signin/account_tracker_service_factory.cc
@@ -4,7 +4,8 @@ #include "chrome/browser/signin/account_tracker_service_factory.h" -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/chrome_signin_client_factory.h" #include "components/keyed_service/content/browser_context_dependency_manager.h"
diff --git a/chrome/browser/signin/chrome_proximity_auth_client.cc b/chrome/browser/signin/chrome_proximity_auth_client.cc index ed40a709..caa128b 100644 --- a/chrome/browser/signin/chrome_proximity_auth_client.cc +++ b/chrome/browser/signin/chrome_proximity_auth_client.cc
@@ -7,6 +7,7 @@ #include <stdint.h> #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/sys_info.h" #include "base/version.h" #include "build/build_config.h" @@ -93,18 +94,18 @@ return profile_->GetPrefs(); } -scoped_ptr<proximity_auth::SecureMessageDelegate> +std::unique_ptr<proximity_auth::SecureMessageDelegate> ChromeProximityAuthClient::CreateSecureMessageDelegate() { #if defined(OS_CHROMEOS) - return make_scoped_ptr(new chromeos::SecureMessageDelegateChromeOS()); + return base::WrapUnique(new chromeos::SecureMessageDelegateChromeOS()); #else return nullptr; #endif } -scoped_ptr<proximity_auth::CryptAuthClientFactory> +std::unique_ptr<proximity_auth::CryptAuthClientFactory> ChromeProximityAuthClient::CreateCryptAuthClientFactory() { - return make_scoped_ptr(new proximity_auth::CryptAuthClientFactoryImpl( + return base::WrapUnique(new proximity_auth::CryptAuthClientFactoryImpl( ProfileOAuth2TokenServiceFactory::GetForProfile(profile_), GetAccountId(), profile_->GetRequestContext(), GetDeviceClassifier())); }
diff --git a/chrome/browser/signin/chrome_proximity_auth_client.h b/chrome/browser/signin/chrome_proximity_auth_client.h index 0380d3f..e0c6e051 100644 --- a/chrome/browser/signin/chrome_proximity_auth_client.h +++ b/chrome/browser/signin/chrome_proximity_auth_client.h
@@ -24,9 +24,9 @@ void UpdateScreenlockState(proximity_auth::ScreenlockState state) override; void FinalizeUnlock(bool success) override; PrefService* GetPrefService() override; - scoped_ptr<proximity_auth::SecureMessageDelegate> + std::unique_ptr<proximity_auth::SecureMessageDelegate> CreateSecureMessageDelegate() override; - scoped_ptr<proximity_auth::CryptAuthClientFactory> + std::unique_ptr<proximity_auth::CryptAuthClientFactory> CreateCryptAuthClientFactory() override; cryptauth::DeviceClassifier GetDeviceClassifier() override; std::string GetAccountId() override;
diff --git a/chrome/browser/signin/chrome_signin_client.cc b/chrome/browser/signin/chrome_signin_client.cc index a49ebed..ea632b0 100644 --- a/chrome/browser/signin/chrome_signin_client.cc +++ b/chrome/browser/signin/chrome_signin_client.cc
@@ -223,7 +223,7 @@ ->RemoveObserver(observer); } -scoped_ptr<SigninClient::CookieChangedSubscription> +std::unique_ptr<SigninClient::CookieChangedSubscription> ChromeSigninClient::AddCookieChangedCallback( const GURL& url, const std::string& name, @@ -231,7 +231,7 @@ scoped_refptr<net::URLRequestContextGetter> context_getter = profile_->GetRequestContext(); DCHECK(context_getter.get()); - scoped_ptr<SigninCookieChangedSubscription> subscription( + std::unique_ptr<SigninCookieChangedSubscription> subscription( new SigninCookieChangedSubscription(context_getter, url, name, callback)); return std::move(subscription); } @@ -275,7 +275,7 @@ } void ChromeSigninClient::OnGetTokenInfoResponse( - scoped_ptr<base::DictionaryValue> token_info) { + std::unique_ptr<base::DictionaryValue> token_info) { if (!token_info->HasKey("error")) { std::string handle; if (token_info->GetString("token_handle", &handle)) {
diff --git a/chrome/browser/signin/chrome_signin_client.h b/chrome/browser/signin/chrome_signin_client.h index cbf3c606..5f9e089 100644 --- a/chrome/browser/signin/chrome_signin_client.h +++ b/chrome/browser/signin/chrome_signin_client.h
@@ -66,7 +66,7 @@ // <Build Info> <OS> <Version number> (<Last change>)<channel or "-devel"> // If version information is unavailable, returns "invalid." std::string GetProductVersion() override; - scoped_ptr<CookieChangedSubscription> AddCookieChangedCallback( + std::unique_ptr<CookieChangedSubscription> AddCookieChangedCallback( const GURL& url, const std::string& name, const net::CookieStore::CookieChangedCallback& callback) override; @@ -83,7 +83,7 @@ // gaia::GaiaOAuthClient::Delegate implementation. void OnGetTokenInfoResponse( - scoped_ptr<base::DictionaryValue> token_info) override; + std::unique_ptr<base::DictionaryValue> token_info) override; void OnOAuthError() override; void OnNetworkError(int response_code) override; @@ -110,8 +110,8 @@ std::list<base::Closure> delayed_callbacks_; #endif - scoped_ptr<gaia::GaiaOAuthClient> oauth_client_; - scoped_ptr<OAuth2TokenService::Request> oauth_request_; + std::unique_ptr<gaia::GaiaOAuthClient> oauth_client_; + std::unique_ptr<OAuth2TokenService::Request> oauth_request_; DISALLOW_COPY_AND_ASSIGN(ChromeSigninClient); };
diff --git a/chrome/browser/signin/chrome_signin_client_unittest.cc b/chrome/browser/signin/chrome_signin_client_unittest.cc index c39cd4b..b9ab35b 100644 --- a/chrome/browser/signin/chrome_signin_client_unittest.cc +++ b/chrome/browser/signin/chrome_signin_client_unittest.cc
@@ -79,7 +79,7 @@ SigninClient* signin_client() { return signin_client_; } private: - scoped_ptr<Profile> profile_; + std::unique_ptr<Profile> profile_; SigninClient* signin_client_; content::TestBrowserThreadBundle thread_bundle_; }; @@ -93,8 +93,8 @@ } TEST_F(ChromeSigninClientTest, DelayNetworkCallRunsImmediatelyWithNetwork) { - scoped_ptr<net::NetworkChangeNotifier> - mock(new MockNetworkChangeNotifierNeverOffline); + std::unique_ptr<net::NetworkChangeNotifier> mock( + new MockNetworkChangeNotifierNeverOffline); CallbackTester tester; signin_client()->DelayNetworkCall(base::Bind(&CallbackTester::Increment, base::Unretained(&tester))); @@ -102,8 +102,8 @@ } TEST_F(ChromeSigninClientTest, DelayNetworkCallRunsAfterNetworkFound) { - scoped_ptr<MockNetworkChangeNotifierOfflineUntilChange> - mock(new MockNetworkChangeNotifierOfflineUntilChange()); + std::unique_ptr<MockNetworkChangeNotifierOfflineUntilChange> mock( + new MockNetworkChangeNotifierOfflineUntilChange()); // Install a SigninClient after the NetworkChangeNotifier's created. SetUp();
diff --git a/chrome/browser/signin/chrome_signin_status_metrics_provider_delegate_unittest.cc b/chrome/browser/signin/chrome_signin_status_metrics_provider_delegate_unittest.cc index 2f5aecc..962c98f 100644 --- a/chrome/browser/signin/chrome_signin_status_metrics_provider_delegate_unittest.cc +++ b/chrome/browser/signin/chrome_signin_status_metrics_provider_delegate_unittest.cc
@@ -16,10 +16,10 @@ UpdateStatusWhenBrowserAdded) { content::TestBrowserThreadBundle thread_bundle; - scoped_ptr<ChromeSigninStatusMetricsProviderDelegate> delegate( + std::unique_ptr<ChromeSigninStatusMetricsProviderDelegate> delegate( new ChromeSigninStatusMetricsProviderDelegate); ChromeSigninStatusMetricsProviderDelegate* raw_delegate = delegate.get(); - scoped_ptr<SigninStatusMetricsProvider> metrics_provider( + std::unique_ptr<SigninStatusMetricsProvider> metrics_provider( SigninStatusMetricsProvider::CreateInstance(std::move(delegate))); // Initial status is all signed in and then a signed-in browser is opened.
diff --git a/chrome/browser/signin/cross_device_promo.h b/chrome/browser/signin/cross_device_promo.h index 5990a94..e49bf05 100644 --- a/chrome/browser/signin/cross_device_promo.h +++ b/chrome/browser/signin/cross_device_promo.h
@@ -195,7 +195,7 @@ PrefService* prefs_; SigninClient* signin_client_; - scoped_ptr<DeviceActivityFetcher> device_activity_fetcher_; + std::unique_ptr<DeviceActivityFetcher> device_activity_fetcher_; base::ObserverList<CrossDevicePromo::Observer> observer_list_; // Initialized from the |kParamMinutesMaxContextSwitchDuration| field trial
diff --git a/chrome/browser/signin/cross_device_promo_unittest.cc b/chrome/browser/signin/cross_device_promo_unittest.cc index 39eff0a47..1d7fdd8 100644 --- a/chrome/browser/signin/cross_device_promo_unittest.cc +++ b/chrome/browser/signin/cross_device_promo_unittest.cc
@@ -11,6 +11,7 @@ #include <vector> #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" #include "base/run_loop.h" #include "base/test/histogram_tester.h" @@ -112,9 +113,9 @@ FakeSigninManagerForTesting* signin_manager_; FakeGaiaCookieManagerService* cookie_manager_service_; syncable_prefs::TestingPrefServiceSyncable* pref_service_; - scoped_ptr<TestingProfileManager> testing_profile_manager_; + std::unique_ptr<TestingProfileManager> testing_profile_manager_; base::HistogramTester histogram_tester_; - scoped_ptr<base::FieldTrialList> field_trial_list_; + std::unique_ptr<base::FieldTrialList> field_trial_list_; net::FakeURLFetcherFactory fake_url_fetcher_factory_; DISALLOW_COPY_AND_ASSIGN(CrossDevicePromoTest); @@ -143,7 +144,7 @@ profile_ = testing_profile_manager_.get()->CreateTestingProfile( "name", - make_scoped_ptr<syncable_prefs::PrefServiceSyncable>(pref_service_), + base::WrapUnique<syncable_prefs::PrefServiceSyncable>(pref_service_), base::UTF8ToUTF16("name"), 0, std::string(), factories); cookie_manager_service_ = static_cast<FakeGaiaCookieManagerService*>(
diff --git a/chrome/browser/signin/easy_unlock_app_manager.cc b/chrome/browser/signin/easy_unlock_app_manager.cc index 062b3a7..a3c59c9 100644 --- a/chrome/browser/signin/easy_unlock_app_manager.cc +++ b/chrome/browser/signin/easy_unlock_app_manager.cc
@@ -165,10 +165,10 @@ info.logged_in = is_logged_in; info.data_ready = data_ready; - scoped_ptr<base::ListValue> args(new base::ListValue()); + std::unique_ptr<base::ListValue> args(new base::ListValue()); args->Append(info.ToValue().release()); - scoped_ptr<extensions::Event> event( + std::unique_ptr<extensions::Event> event( new extensions::Event(histogram_value, event_name, std::move(args))); event_router->DispatchEventToExtension(app_id_, std::move(event)); @@ -194,10 +194,10 @@ } // static -scoped_ptr<EasyUnlockAppManager> EasyUnlockAppManager::Create( +std::unique_ptr<EasyUnlockAppManager> EasyUnlockAppManager::Create( extensions::ExtensionSystem* extension_system, int manifest_id, const base::FilePath& app_path) { - return scoped_ptr<EasyUnlockAppManager>( + return std::unique_ptr<EasyUnlockAppManager>( new EasyUnlockAppManagerImpl(extension_system, manifest_id, app_path)); }
diff --git a/chrome/browser/signin/easy_unlock_app_manager.h b/chrome/browser/signin/easy_unlock_app_manager.h index ba6bb4c..42372e9e 100644 --- a/chrome/browser/signin/easy_unlock_app_manager.h +++ b/chrome/browser/signin/easy_unlock_app_manager.h
@@ -5,12 +5,12 @@ #ifndef CHROME_BROWSER_SIGNIN_EASY_UNLOCK_APP_MANAGER_H_ #define CHROME_BROWSER_SIGNIN_EASY_UNLOCK_APP_MANAGER_H_ +#include <memory> #include <string> #include "base/callback.h" #include "base/files/file_path.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" namespace extensions { class ExtensionSystem; @@ -24,7 +24,7 @@ virtual ~EasyUnlockAppManager(); // Creates EasyUnlockAppManager object that should be used in production. - static scoped_ptr<EasyUnlockAppManager> Create( + static std::unique_ptr<EasyUnlockAppManager> Create( extensions::ExtensionSystem* extension_system, int manifest_id, const base::FilePath& app_path);
diff --git a/chrome/browser/signin/easy_unlock_app_manager_unittest.cc b/chrome/browser/signin/easy_unlock_app_manager_unittest.cc index 51113a1..eb3a02e5 100644 --- a/chrome/browser/signin/easy_unlock_app_manager_unittest.cc +++ b/chrome/browser/signin/easy_unlock_app_manager_unittest.cc
@@ -6,11 +6,12 @@ #include <stddef.h> +#include <memory> #include <string> #include "base/command_line.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "build/build_config.h" #include "chrome/browser/extensions/api/screenlock_private/screenlock_private_api.h" @@ -74,14 +75,15 @@ DISALLOW_COPY_AND_ASSIGN(TestProcessManager); }; -scoped_ptr<KeyedService> CreateTestProcessManager( +std::unique_ptr<KeyedService> CreateTestProcessManager( content::BrowserContext* context) { - return make_scoped_ptr(new TestProcessManager(context)); + return base::WrapUnique(new TestProcessManager(context)); } -scoped_ptr<KeyedService> CreateScreenlockPrivateEventRouter( +std::unique_ptr<KeyedService> CreateScreenlockPrivateEventRouter( content::BrowserContext* context) { - return make_scoped_ptr(new extensions::ScreenlockPrivateEventRouter(context)); + return base::WrapUnique( + new extensions::ScreenlockPrivateEventRouter(context)); } // Observes extension registry for unload and load events (in that order) of an @@ -248,15 +250,16 @@ ~TestEventRouter() override {} // extensions::EventRouter implementation: - void BroadcastEvent(scoped_ptr<extensions::Event> event) override { + void BroadcastEvent(std::unique_ptr<extensions::Event> event) override { ASSERT_EQ(screenlock_private_api::OnAuthAttempted::kEventName, event->event_name); EXPECT_TRUE(event_consumer_->ConsumeEvent(event->event_name, event->event_args.get())); } - void DispatchEventToExtension(const std::string& extension_id, - scoped_ptr<extensions::Event> event) override { + void DispatchEventToExtension( + const std::string& extension_id, + std::unique_ptr<extensions::Event> event) override { ASSERT_EQ(extension_misc::kEasyUnlockAppId, extension_id); EXPECT_TRUE(event_consumer_->ConsumeEvent(event->event_name, event->event_args.get())); @@ -273,9 +276,9 @@ }; // TestEventRouter factory function -scoped_ptr<KeyedService> TestEventRouterFactoryFunction( +std::unique_ptr<KeyedService> TestEventRouterFactoryFunction( content::BrowserContext* context) { - return make_scoped_ptr( + return base::WrapUnique( new TestEventRouter(static_cast<Profile*>(context), extensions::ExtensionPrefs::Get(context))); } @@ -337,7 +340,7 @@ } protected: - scoped_ptr<EasyUnlockAppManager> app_manager_; + std::unique_ptr<EasyUnlockAppManager> app_manager_; // Needed by extension system. content::TestBrowserThreadBundle thread_bundle_;
diff --git a/chrome/browser/signin/easy_unlock_auth_attempt.cc b/chrome/browser/signin/easy_unlock_auth_attempt.cc index c15bafb..345e1d1 100644 --- a/chrome/browser/signin/easy_unlock_auth_attempt.cc +++ b/chrome/browser/signin/easy_unlock_auth_attempt.cc
@@ -29,8 +29,8 @@ return std::string(); // Import the key structure. - scoped_ptr<crypto::SymmetricKey> key( - crypto::SymmetricKey::Import(crypto::SymmetricKey::AES, raw_key)); + std::unique_ptr<crypto::SymmetricKey> key( + crypto::SymmetricKey::Import(crypto::SymmetricKey::AES, raw_key)); if (!key) return std::string();
diff --git a/chrome/browser/signin/easy_unlock_auth_attempt_unittest.cc b/chrome/browser/signin/easy_unlock_auth_attempt_unittest.cc index f7971f5..9affe469 100644 --- a/chrome/browser/signin/easy_unlock_auth_attempt_unittest.cc +++ b/chrome/browser/signin/easy_unlock_auth_attempt_unittest.cc
@@ -232,9 +232,9 @@ lock_handler_.get()); } - scoped_ptr<EasyUnlockAuthAttempt> auth_attempt_; - scoped_ptr<FakeAppManager> app_manager_; - scoped_ptr<TestLockHandler> lock_handler_; + std::unique_ptr<EasyUnlockAuthAttempt> auth_attempt_; + std::unique_ptr<FakeAppManager> app_manager_; + std::unique_ptr<TestLockHandler> lock_handler_; const AccountId test_account_id1_ = AccountId::FromUserEmail(kTestUser1); const AccountId test_account_id2_ = AccountId::FromUserEmail(kTestUser2); @@ -390,9 +390,9 @@ lock_handler_.get()); } - scoped_ptr<EasyUnlockAuthAttempt> auth_attempt_; - scoped_ptr<FakeAppManager> app_manager_; - scoped_ptr<TestLockHandler> lock_handler_; + std::unique_ptr<EasyUnlockAuthAttempt> auth_attempt_; + std::unique_ptr<FakeAppManager> app_manager_; + std::unique_ptr<TestLockHandler> lock_handler_; const AccountId test_account_id1_ = AccountId::FromUserEmail(kTestUser1); const AccountId test_account_id2_ = AccountId::FromUserEmail(kTestUser2);
diff --git a/chrome/browser/signin/easy_unlock_screenlock_state_handler_unittest.cc b/chrome/browser/signin/easy_unlock_screenlock_state_handler_unittest.cc index 4a449b1..f12f19ad 100644 --- a/chrome/browser/signin/easy_unlock_screenlock_state_handler_unittest.cc +++ b/chrome/browser/signin/easy_unlock_screenlock_state_handler_unittest.cc
@@ -203,7 +203,7 @@ // The last icon set using |SetUserPodCustomIcon|. Call to // |HideUserPodcustomIcon| resets it. - scoped_ptr<base::DictionaryValue> last_custom_icon_; + std::unique_ptr<base::DictionaryValue> last_custom_icon_; size_t show_icon_count_; // Auth type and value set using |SetAuthType|. @@ -239,14 +239,14 @@ protected: // The state handler that is being tested. - scoped_ptr<EasyUnlockScreenlockStateHandler> state_handler_; + std::unique_ptr<EasyUnlockScreenlockStateHandler> state_handler_; // The user associated with |state_handler_|. const AccountId account_id_ = AccountId::FromUserEmail("test_user@gmail.com"); // Faked lock handler given to proximity_auth::ScreenlockBridge during the // test. Abstracts the screen lock UI. - scoped_ptr<TestLockHandler> lock_handler_; + std::unique_ptr<TestLockHandler> lock_handler_; }; TEST_F(EasyUnlockScreenlockStateHandlerTest, AuthenticatedTrialRun) {
diff --git a/chrome/browser/signin/easy_unlock_service.cc b/chrome/browser/signin/easy_unlock_service.cc index 57bbe8c..233174a3 100644 --- a/chrome/browser/signin/easy_unlock_service.cc +++ b/chrome/browser/signin/easy_unlock_service.cc
@@ -364,7 +364,7 @@ } void EasyUnlockService::Initialize( - scoped_ptr<EasyUnlockAppManager> app_manager) { + std::unique_ptr<EasyUnlockAppManager> app_manager) { app_manager_ = std::move(app_manager); app_manager_->EnsureReady( base::Bind(&EasyUnlockService::InitializeOnAppManagerReady,
diff --git a/chrome/browser/signin/easy_unlock_service.h b/chrome/browser/signin/easy_unlock_service.h index e59977d..e32c6e4 100644 --- a/chrome/browser/signin/easy_unlock_service.h +++ b/chrome/browser/signin/easy_unlock_service.h
@@ -5,12 +5,12 @@ #ifndef CHROME_BROWSER_SIGNIN_EASY_UNLOCK_SERVICE_H_ #define CHROME_BROWSER_SIGNIN_EASY_UNLOCK_SERVICE_H_ +#include <memory> #include <set> #include <string> #include "base/callback_forward.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "build/build_config.h" @@ -150,7 +150,7 @@ virtual void SetAutoPairingResult(bool success, const std::string& error) = 0; // Sets the service up and schedules service initialization. - void Initialize(scoped_ptr<EasyUnlockAppManager> app_manager); + void Initialize(std::unique_ptr<EasyUnlockAppManager> app_manager); // Whether easy unlock is allowed to be used. If the controlling preference // is set (from policy), this returns the preference value. Otherwise, it is @@ -343,17 +343,17 @@ ChromeProximityAuthClient proximity_auth_client_; - scoped_ptr<EasyUnlockAppManager> app_manager_; + std::unique_ptr<EasyUnlockAppManager> app_manager_; // Created lazily in |GetScreenlockStateHandler|. - scoped_ptr<EasyUnlockScreenlockStateHandler> screenlock_state_handler_; + std::unique_ptr<EasyUnlockScreenlockStateHandler> screenlock_state_handler_; // The handler for the current auth attempt. Set iff an auth attempt is in // progress. - scoped_ptr<EasyUnlockAuthAttempt> auth_attempt_; + std::unique_ptr<EasyUnlockAuthAttempt> auth_attempt_; // Detects when the system Bluetooth adapter status changes. - scoped_ptr<BluetoothDetector> bluetooth_detector_; + std::unique_ptr<BluetoothDetector> bluetooth_detector_; // Handles connecting, authenticating, and updating the UI on the lock/sign-in // screen. After a |RemoteDevice| instance is provided, this object will @@ -361,12 +361,12 @@ // TODO(tengs): This object is intended as a replacement of the background // page of the easy_unlock Chrome app. We are in the process of removing the // app in favor of |proximity_auth_system_|. - scoped_ptr<proximity_auth::ProximityAuthSystem> proximity_auth_system_; + std::unique_ptr<proximity_auth::ProximityAuthSystem> proximity_auth_system_; #if defined(OS_CHROMEOS) // Monitors suspend and wake state of ChromeOS. class PowerMonitor; - scoped_ptr<PowerMonitor> power_monitor_; + std::unique_ptr<PowerMonitor> power_monitor_; #endif // Whether the service has been shut down.
diff --git a/chrome/browser/signin/easy_unlock_service_regular.cc b/chrome/browser/signin/easy_unlock_service_regular.cc index 85e60da0..81367b8 100644 --- a/chrome/browser/signin/easy_unlock_service_regular.cc +++ b/chrome/browser/signin/easy_unlock_service_regular.cc
@@ -5,12 +5,14 @@ #include "chrome/browser/signin/easy_unlock_service_regular.h" #include <stdint.h> + #include <utility> #include "base/base64url.h" #include "base/bind.h" #include "base/command_line.h" #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/sys_info.h" #include "base/time/default_clock.h" #include "base/values.h" @@ -125,9 +127,9 @@ // We need to store a copy of |remote devices_| in the TPM, so it can be // retrieved on the sign-in screen when a user session has not been started // yet. - scoped_ptr<base::ListValue> device_list(new base::ListValue()); + std::unique_ptr<base::ListValue> device_list(new base::ListValue()); for (const auto& device : remote_devices) { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); std::string b64_public_key, b64_psk; base::Base64UrlEncode(device.public_key, base::Base64UrlEncodePolicy::INCLUDE_PADDING, @@ -343,7 +345,7 @@ SetTurnOffFlowStatus(PENDING); - scoped_ptr<proximity_auth::CryptAuthClientFactory> factory = + std::unique_ptr<proximity_auth::CryptAuthClientFactory> factory = proximity_auth_client()->CreateCryptAuthClientFactory(); cryptauth_client_ = factory->CreateInstance(); @@ -398,8 +400,8 @@ auto_pairing_callback_ = callback; - scoped_ptr<base::ListValue> args(new base::ListValue()); - scoped_ptr<extensions::Event> event(new extensions::Event( + std::unique_ptr<base::ListValue> args(new base::ListValue()); + std::unique_ptr<extensions::Event> event(new extensions::Event( extensions::events::EASY_UNLOCK_PRIVATE_ON_START_AUTO_PAIRING, extensions::api::easy_unlock_private::OnStartAutoPairing::kEventName, std::move(args))); @@ -589,7 +591,7 @@ // Create the dictionary of Easy Unlock preferences for the current user. The // items in the dictionary are the same profile prefs used for Easy Unlock. - scoped_ptr<base::DictionaryValue> user_prefs_dict( + std::unique_ptr<base::DictionaryValue> user_prefs_dict( new base::DictionaryValue()); user_prefs_dict->SetBooleanWithoutPathExpansion( prefs::kEasyUnlockProximityRequired, @@ -659,8 +661,8 @@ // Initialize enrollment manager. cryptauth::GcmDeviceInfo device_info; enrollment_manager_.reset(new proximity_auth::CryptAuthEnrollmentManager( - make_scoped_ptr(new base::DefaultClock()), - make_scoped_ptr(new proximity_auth::CryptAuthEnrollerFactoryImpl( + base::WrapUnique(new base::DefaultClock()), + base::WrapUnique(new proximity_auth::CryptAuthEnrollerFactoryImpl( proximity_auth_client())), proximity_auth_client()->CreateSecureMessageDelegate(), GetGcmDeviceInfo(), gcm_manager_.get(), @@ -668,7 +670,7 @@ // Initialize device manager. device_manager_.reset(new proximity_auth::CryptAuthDeviceManager( - make_scoped_ptr(new base::DefaultClock()), + base::WrapUnique(new base::DefaultClock()), proximity_auth_client()->CreateCryptAuthClientFactory(), gcm_manager_.get(), proximity_auth_client()->GetPrefService()));
diff --git a/chrome/browser/signin/easy_unlock_service_regular.h b/chrome/browser/signin/easy_unlock_service_regular.h index fba8813..d69787c6 100644 --- a/chrome/browser/signin/easy_unlock_service_regular.h +++ b/chrome/browser/signin/easy_unlock_service_regular.h
@@ -5,11 +5,11 @@ #ifndef CHROME_BROWSER_SIGNIN_EASY_UNLOCK_SERVICE_REGULAR_H_ #define CHROME_BROWSER_SIGNIN_EASY_UNLOCK_SERVICE_REGULAR_H_ +#include <memory> #include <string> #include "base/callback.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/time/time.h" #include "build/build_config.h" #include "chrome/browser/signin/easy_unlock_service.h" @@ -144,7 +144,7 @@ // Initializes the managers that communicate with CryptAuth. void InitializeCryptAuth(); - scoped_ptr<chromeos::ShortLivedUserContext> short_lived_user_context_; + std::unique_ptr<chromeos::ShortLivedUserContext> short_lived_user_context_; #endif // Updates local state with the preference from the user's profile, so they @@ -158,7 +158,7 @@ PrefChangeRegistrar registrar_; TurnOffFlowStatus turn_off_flow_status_; - scoped_ptr<proximity_auth::CryptAuthClient> cryptauth_client_; + std::unique_ptr<proximity_auth::CryptAuthClient> cryptauth_client_; AutoPairingResultCallback auto_pairing_callback_; @@ -175,15 +175,16 @@ // Managers responsible for handling syncing and communications with // CryptAuth. - scoped_ptr<proximity_auth::CryptAuthGCMManager> gcm_manager_; - scoped_ptr<proximity_auth::CryptAuthEnrollmentManager> enrollment_manager_; - scoped_ptr<proximity_auth::CryptAuthDeviceManager> device_manager_; + std::unique_ptr<proximity_auth::CryptAuthGCMManager> gcm_manager_; + std::unique_ptr<proximity_auth::CryptAuthEnrollmentManager> + enrollment_manager_; + std::unique_ptr<proximity_auth::CryptAuthDeviceManager> device_manager_; // Manager responsible for handling the prefs used by proximity_auth classes. - scoped_ptr<proximity_auth::ProximityAuthPrefManager> pref_manager_; + std::unique_ptr<proximity_auth::ProximityAuthPrefManager> pref_manager_; // Loads the RemoteDevice instances from CryptAuth and local data. - scoped_ptr<proximity_auth::RemoteDeviceLoader> remote_device_loader_; + std::unique_ptr<proximity_auth::RemoteDeviceLoader> remote_device_loader_; // If a new RemoteDevice was synced while the screen is locked, we defer // loading the RemoteDevice until the screen is unlocked. For security,
diff --git a/chrome/browser/signin/easy_unlock_service_signin_chromeos.h b/chrome/browser/signin/easy_unlock_service_signin_chromeos.h index 9496f89..ad997cd 100644 --- a/chrome/browser/signin/easy_unlock_service_signin_chromeos.h +++ b/chrome/browser/signin/easy_unlock_service_signin_chromeos.h
@@ -6,10 +6,10 @@ #define CHROME_BROWSER_SIGNIN_EASY_UNLOCK_SERVICE_SIGNIN_CHROMEOS_H_ #include <map> +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "base/values.h" @@ -147,7 +147,7 @@ base::TimeTicks user_pod_last_focused_timestamp_; // Handles wrapping the user's challenge with the TPM. - scoped_ptr<chromeos::EasyUnlockChallengeWrapper> challenge_wrapper_; + std::unique_ptr<chromeos::EasyUnlockChallengeWrapper> challenge_wrapper_; base::WeakPtrFactory<EasyUnlockServiceSignin> weak_ptr_factory_;
diff --git a/chrome/browser/signin/easy_unlock_service_unittest_chromeos.cc b/chrome/browser/signin/easy_unlock_service_unittest_chromeos.cc index 7305084..fdc0e44 100644 --- a/chrome/browser/signin/easy_unlock_service_unittest_chromeos.cc +++ b/chrome/browser/signin/easy_unlock_service_unittest_chromeos.cc
@@ -5,12 +5,13 @@ #include "chrome/browser/signin/easy_unlock_service.h" #include <stddef.h> + #include <map> +#include <memory> #include <string> #include <utility> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "base/values.h" #include "chrome/browser/chromeos/login/users/mock_user_manager.h" @@ -143,10 +144,10 @@ // Creates a TestAppManager for the provided browser context. If a // TestAppManager was already created for the context, returns NULL. - scoped_ptr<TestAppManager> Create(content::BrowserContext* context) { + std::unique_ptr<TestAppManager> Create(content::BrowserContext* context) { if (Find(context)) - return scoped_ptr<TestAppManager>(); - scoped_ptr<TestAppManager> app_manager(new TestAppManager()); + return std::unique_ptr<TestAppManager>(); + std::unique_ptr<TestAppManager> app_manager(new TestAppManager()); mapping_[context] = app_manager.get(); return app_manager; } @@ -176,19 +177,19 @@ // EasyUnlockService factory function injected into testing profiles. // It creates an EasyUnlockService with test AppManager. -scoped_ptr<KeyedService> CreateEasyUnlockServiceForTest( +std::unique_ptr<KeyedService> CreateEasyUnlockServiceForTest( content::BrowserContext* context) { EXPECT_TRUE(app_manager_factory); if (!app_manager_factory) return nullptr; - scoped_ptr<EasyUnlockAppManager> app_manager = + std::unique_ptr<EasyUnlockAppManager> app_manager = app_manager_factory->Create(context); EXPECT_TRUE(app_manager.get()); if (!app_manager.get()) return nullptr; - scoped_ptr<EasyUnlockServiceRegular> service( + std::unique_ptr<EasyUnlockServiceRegular> service( new EasyUnlockServiceRegular(Profile::FromBrowserContext(context))); service->Initialize(std::move(app_manager)); return std::move(service); @@ -212,11 +213,11 @@ .WillRepeatedly(testing::Invoke( this, &EasyUnlockServiceTest::is_bluetooth_adapter_present)); - scoped_ptr<DBusThreadManagerSetter> dbus_setter = + std::unique_ptr<DBusThreadManagerSetter> dbus_setter = chromeos::DBusThreadManager::GetSetterForTesting(); power_manager_client_ = new FakePowerManagerClient; dbus_setter->SetPowerManagerClient( - scoped_ptr<PowerManagerClient>(power_manager_client_)); + std::unique_ptr<PowerManagerClient>(power_manager_client_)); ON_CALL(*mock_user_manager_, Shutdown()).WillByDefault(Return()); ON_CALL(*mock_user_manager_, IsLoggedInAsUserWithGaiaAccount()) @@ -276,7 +277,7 @@ private: // Sets up a test profile with a user id. - void SetUpProfile(scoped_ptr<TestingProfile>* profile, + void SetUpProfile(std::unique_ptr<TestingProfile>* profile, const AccountId& account_id) { ASSERT_TRUE(profile); ASSERT_FALSE(profile->get()); @@ -296,8 +297,8 @@ } protected: - scoped_ptr<TestingProfile> profile_; - scoped_ptr<TestingProfile> secondary_profile_; + std::unique_ptr<TestingProfile> profile_; + std::unique_ptr<TestingProfile> secondary_profile_; chromeos::MockUserManager* mock_user_manager_; private:
diff --git a/chrome/browser/signin/fake_account_fetcher_service_builder.cc b/chrome/browser/signin/fake_account_fetcher_service_builder.cc index d1f492b..36605c8 100644 --- a/chrome/browser/signin/fake_account_fetcher_service_builder.cc +++ b/chrome/browser/signin/fake_account_fetcher_service_builder.cc
@@ -12,12 +12,12 @@ #include "components/signin/core/browser/profile_oauth2_token_service.h" // static -scoped_ptr<KeyedService> FakeAccountFetcherServiceBuilder::BuildForTests( +std::unique_ptr<KeyedService> FakeAccountFetcherServiceBuilder::BuildForTests( content::BrowserContext* context) { FakeAccountFetcherService* service = new FakeAccountFetcherService(); Profile* profile = Profile::FromBrowserContext(context); service->Initialize(ChromeSigninClientFactory::GetForProfile(profile), ProfileOAuth2TokenServiceFactory::GetForProfile(profile), AccountTrackerServiceFactory::GetForProfile(profile)); - return scoped_ptr<KeyedService>(service); + return std::unique_ptr<KeyedService>(service); }
diff --git a/chrome/browser/signin/fake_account_fetcher_service_builder.h b/chrome/browser/signin/fake_account_fetcher_service_builder.h index 243a018..4a399a6 100644 --- a/chrome/browser/signin/fake_account_fetcher_service_builder.h +++ b/chrome/browser/signin/fake_account_fetcher_service_builder.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_SIGNIN_FAKE_ACCOUNT_FETCHER_SERVICE_BUILDER_H_ #define CHROME_BROWSER_SIGNIN_FAKE_ACCOUNT_FETCHER_SERVICE_BUILDER_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" namespace content { class BrowserContext; @@ -15,7 +16,7 @@ class FakeAccountFetcherServiceBuilder { public: - static scoped_ptr<KeyedService> BuildForTests( + static std::unique_ptr<KeyedService> BuildForTests( content::BrowserContext* context); private:
diff --git a/chrome/browser/signin/fake_gaia_cookie_manager_service.cc b/chrome/browser/signin/fake_gaia_cookie_manager_service.cc index 304e40fc..51844388 100644 --- a/chrome/browser/signin/fake_gaia_cookie_manager_service.cc +++ b/chrome/browser/signin/fake_gaia_cookie_manager_service.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/signin/fake_gaia_cookie_manager_service.h" +#include "base/memory/ptr_util.h" #include "base/strings/stringprintf.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/chrome_signin_client_factory.h" @@ -115,10 +116,10 @@ } // static -scoped_ptr<KeyedService> FakeGaiaCookieManagerService::Build( +std::unique_ptr<KeyedService> FakeGaiaCookieManagerService::Build( content::BrowserContext* context) { Profile* profile = Profile::FromBrowserContext(context); - return make_scoped_ptr(new FakeGaiaCookieManagerService( + return base::WrapUnique(new FakeGaiaCookieManagerService( ProfileOAuth2TokenServiceFactory::GetForProfile(profile), GaiaConstants::kChromeSource, ChromeSigninClientFactory::GetForProfile(profile)));
diff --git a/chrome/browser/signin/fake_gaia_cookie_manager_service.h b/chrome/browser/signin/fake_gaia_cookie_manager_service.h index fbb7c79..3f152bf0 100644 --- a/chrome/browser/signin/fake_gaia_cookie_manager_service.h +++ b/chrome/browser/signin/fake_gaia_cookie_manager_service.h
@@ -6,8 +6,9 @@ #include "components/signin/core/browser/gaia_cookie_manager_service.h" +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/url_request/test_url_fetcher_factory.h" namespace content { @@ -40,7 +41,7 @@ bool account2_expired); // Helper function to be used with KeyedService::SetTestingFactory(). - static scoped_ptr<KeyedService> Build(content::BrowserContext* context); + static std::unique_ptr<KeyedService> Build(content::BrowserContext* context); private: // Provide a fake response for calls to /ListAccounts.
diff --git a/chrome/browser/signin/fake_profile_oauth2_token_service_builder.cc b/chrome/browser/signin/fake_profile_oauth2_token_service_builder.cc index 4f978955..f47f1c9 100644 --- a/chrome/browser/signin/fake_profile_oauth2_token_service_builder.cc +++ b/chrome/browser/signin/fake_profile_oauth2_token_service_builder.cc
@@ -9,16 +9,16 @@ #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" // TODO(blundell): Should these be namespaced? -scoped_ptr<KeyedService> BuildFakeProfileOAuth2TokenService( +std::unique_ptr<KeyedService> BuildFakeProfileOAuth2TokenService( content::BrowserContext* context) { - scoped_ptr<FakeProfileOAuth2TokenService> service( + std::unique_ptr<FakeProfileOAuth2TokenService> service( new FakeProfileOAuth2TokenService()); return std::move(service); } -scoped_ptr<KeyedService> BuildAutoIssuingFakeProfileOAuth2TokenService( +std::unique_ptr<KeyedService> BuildAutoIssuingFakeProfileOAuth2TokenService( content::BrowserContext* context) { - scoped_ptr<FakeProfileOAuth2TokenService> service( + std::unique_ptr<FakeProfileOAuth2TokenService> service( new FakeProfileOAuth2TokenService()); service->set_auto_post_fetch_response_on_message_loop(true); return std::move(service);
diff --git a/chrome/browser/signin/fake_profile_oauth2_token_service_builder.h b/chrome/browser/signin/fake_profile_oauth2_token_service_builder.h index d9cd4bd..7cb1d0d1 100644 --- a/chrome/browser/signin/fake_profile_oauth2_token_service_builder.h +++ b/chrome/browser/signin/fake_profile_oauth2_token_service_builder.h
@@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_SIGNIN_FAKE_PROFILE_OAUTH2_TOKEN_SERVICE_BUILDER_H_ #define CHROME_BROWSER_SIGNIN_FAKE_PROFILE_OAUTH2_TOKEN_SERVICE_BUILDER_H_ -#include "base/memory/scoped_ptr.h" +#include <memory> class KeyedService; @@ -16,14 +16,14 @@ // Helper function to be used with // BrowserContextKeyedServiceFactory::SetTestingFactory() that returns a // FakeProfileOAuth2TokenService object. -scoped_ptr<KeyedService> BuildFakeProfileOAuth2TokenService( +std::unique_ptr<KeyedService> BuildFakeProfileOAuth2TokenService( content::BrowserContext* context); // Helper function to be used with // BrowserContextKeyedServiceFactory::SetTestingFactory() that creates a // FakeProfileOAuth2TokenService object that posts fetch responses on the // current message loop. -scoped_ptr<KeyedService> BuildAutoIssuingFakeProfileOAuth2TokenService( +std::unique_ptr<KeyedService> BuildAutoIssuingFakeProfileOAuth2TokenService( content::BrowserContext* context); #endif // CHROME_BROWSER_SIGNIN_FAKE_PROFILE_OAUTH2_TOKEN_SERVICE_BUILDER_H_
diff --git a/chrome/browser/signin/fake_signin_manager_builder.cc b/chrome/browser/signin/fake_signin_manager_builder.cc index b3937550..256a5855 100644 --- a/chrome/browser/signin/fake_signin_manager_builder.cc +++ b/chrome/browser/signin/fake_signin_manager_builder.cc
@@ -14,9 +14,9 @@ #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" -scoped_ptr<KeyedService> BuildFakeSigninManagerBase( +std::unique_ptr<KeyedService> BuildFakeSigninManagerBase( content::BrowserContext* context) { - scoped_ptr<SigninManagerBase> manager; + std::unique_ptr<SigninManagerBase> manager; Profile* profile = static_cast<Profile*>(context); manager.reset(new FakeSigninManagerForTesting(profile)); manager->Initialize(nullptr);
diff --git a/chrome/browser/signin/fake_signin_manager_builder.h b/chrome/browser/signin/fake_signin_manager_builder.h index 31ee5cb4..a7f59ef2b 100644 --- a/chrome/browser/signin/fake_signin_manager_builder.h +++ b/chrome/browser/signin/fake_signin_manager_builder.h
@@ -5,10 +5,9 @@ #ifndef CHROME_BROWSER_SIGNIN_FAKE_SIGNIN_MANAGER_BUILDER_H_ #define CHROME_BROWSER_SIGNIN_FAKE_SIGNIN_MANAGER_BUILDER_H_ +#include <memory> #include <string> -#include "base/memory/scoped_ptr.h" - #include "build/build_config.h" #include "components/signin/core/browser/fake_signin_manager.h" @@ -23,7 +22,7 @@ // In order to match the API of SigninManagerFactory::GetForProfile(), returns a // FakeSigninManagerBase* on ChromeOS, and a FakeSigninManager* on all other // platforms. The returned instance is initialized. -scoped_ptr<KeyedService> BuildFakeSigninManagerBase( +std::unique_ptr<KeyedService> BuildFakeSigninManagerBase( content::BrowserContext* context); class FakeSigninManagerForTesting
diff --git a/chrome/browser/signin/local_auth.cc b/chrome/browser/signin/local_auth.cc index 5ddb1e6..3e8ce70 100644 --- a/chrome/browser/signin/local_auth.cc +++ b/chrome/browser/signin/local_auth.cc
@@ -4,10 +4,11 @@ #include "chrome/browser/signin/local_auth.h" +#include <memory> + #include "base/base64.h" #include "base/files/file_path.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/histogram.h" #include "base/strings/string_util.h" #include "chrome/browser/browser_process.h" @@ -103,11 +104,10 @@ base::Time start_time = base::Time::Now(); // Library call to create secure password hash as SymmetricKey (uses PBKDF2). - scoped_ptr<crypto::SymmetricKey> password_key( + std::unique_ptr<crypto::SymmetricKey> password_key( crypto::SymmetricKey::DeriveKeyFromPassword( - crypto::SymmetricKey::AES, - password, salt, - encoding.iteration_count, encoding.hash_bits)); + crypto::SymmetricKey::AES, password, salt, encoding.iteration_count, + encoding.hash_bits)); std::string password_hash; const bool success = password_key->GetRawKey(&password_hash); DCHECK(success);
diff --git a/chrome/browser/signin/mutable_profile_oauth2_token_service_delegate_unittest.cc b/chrome/browser/signin/mutable_profile_oauth2_token_service_delegate_unittest.cc index 10f210c..66c0760b5 100644 --- a/chrome/browser/signin/mutable_profile_oauth2_token_service_delegate_unittest.cc +++ b/chrome/browser/signin/mutable_profile_oauth2_token_service_delegate_unittest.cc
@@ -150,8 +150,9 @@ protected: base::MessageLoop message_loop_; net::FakeURLFetcherFactory factory_; - scoped_ptr<TestSigninClient> client_; - scoped_ptr<MutableProfileOAuth2TokenServiceDelegate> oauth2_service_delegate_; + std::unique_ptr<TestSigninClient> client_; + std::unique_ptr<MutableProfileOAuth2TokenServiceDelegate> + oauth2_service_delegate_; TestingOAuth2TokenServiceConsumer consumer_; SigninErrorController signin_error_controller_; TestingPrefServiceSimple pref_service_; @@ -380,7 +381,7 @@ EXPECT_EQ(0, access_token_failure_count_); std::vector<std::string> scope_list; scope_list.push_back("scope"); - scoped_ptr<OAuth2AccessTokenFetcher> fetcher( + std::unique_ptr<OAuth2AccessTokenFetcher> fetcher( oauth2_service_delegate_->CreateAccessTokenFetcher( kEmail, oauth2_service_delegate_->GetRequestContext(), this)); fetcher->Start("foo", "bar", scope_list); @@ -409,7 +410,7 @@ EXPECT_EQ(0, access_token_failure_count_); std::vector<std::string> scope_list; scope_list.push_back("scope"); - scoped_ptr<OAuth2AccessTokenFetcher> fetcher1( + std::unique_ptr<OAuth2AccessTokenFetcher> fetcher1( oauth2_service_delegate_->CreateAccessTokenFetcher( kEmail, oauth2_service_delegate_->GetRequestContext(), this)); fetcher1->Start("foo", "bar", scope_list); @@ -423,7 +424,7 @@ // Pretend that backoff has expired and try again. oauth2_service_delegate_->backoff_entry_.SetCustomReleaseTime( base::TimeTicks()); - scoped_ptr<OAuth2AccessTokenFetcher> fetcher2( + std::unique_ptr<OAuth2AccessTokenFetcher> fetcher2( oauth2_service_delegate_->CreateAccessTokenFetcher( kEmail, oauth2_service_delegate_->GetRequestContext(), this)); fetcher2->Start("foo", "bar", scope_list); @@ -452,7 +453,7 @@ EXPECT_EQ(0, access_token_failure_count_); std::vector<std::string> scope_list; scope_list.push_back("scope"); - scoped_ptr<OAuth2AccessTokenFetcher> fetcher1( + std::unique_ptr<OAuth2AccessTokenFetcher> fetcher1( oauth2_service_delegate_->CreateAccessTokenFetcher( kEmail, oauth2_service_delegate_->GetRequestContext(), this)); fetcher1->Start("foo", "bar", scope_list); @@ -463,7 +464,7 @@ // Notify of network change and ensure that request now runs. oauth2_service_delegate_->OnNetworkChanged( net::NetworkChangeNotifier::CONNECTION_WIFI); - scoped_ptr<OAuth2AccessTokenFetcher> fetcher2( + std::unique_ptr<OAuth2AccessTokenFetcher> fetcher2( oauth2_service_delegate_->CreateAccessTokenFetcher( kEmail, oauth2_service_delegate_->GetRequestContext(), this)); fetcher2->Start("foo", "bar", scope_list);
diff --git a/chrome/browser/signin/oauth2_token_service_delegate_android.cc b/chrome/browser/signin/oauth2_token_service_delegate_android.cc index 5d8f0f8..9508b3e 100644 --- a/chrome/browser/signin/oauth2_token_service_delegate_android.cc +++ b/chrome/browser/signin/oauth2_token_service_delegate_android.cc
@@ -87,7 +87,7 @@ ScopedJavaLocalRef<jstring> j_username = ConvertUTF8ToJavaString(env, account_id_); ScopedJavaLocalRef<jstring> j_scope = ConvertUTF8ToJavaString(env, scope); - scoped_ptr<FetchOAuth2TokenCallback> heap_callback( + std::unique_ptr<FetchOAuth2TokenCallback> heap_callback( new FetchOAuth2TokenCallback( base::Bind(&AndroidAccessTokenFetcher::OnAccessTokenResponse, weak_factory_.GetWeakPtr()))); @@ -563,7 +563,7 @@ std::string token; if (authToken) token = ConvertJavaStringToUTF8(env, authToken); - scoped_ptr<FetchOAuth2TokenCallback> heap_callback( + std::unique_ptr<FetchOAuth2TokenCallback> heap_callback( reinterpret_cast<FetchOAuth2TokenCallback*>(nativeCallback)); GoogleServiceAuthError err(authToken
diff --git a/chrome/browser/signin/oauth2_token_service_delegate_android.h b/chrome/browser/signin/oauth2_token_service_delegate_android.h index dc098347..e7b34fb 100644 --- a/chrome/browser/signin/oauth2_token_service_delegate_android.h +++ b/chrome/browser/signin/oauth2_token_service_delegate_android.h
@@ -6,14 +6,15 @@ #define CHROME_BROWSER_SIGNIN_OAUTH2_TOKEN_SERVICE_DELEGATE_ANDROID_H_ #include <jni.h> + #include <map> +#include <memory> #include <string> #include "base/android/jni_weak_ref.h" #include "base/android/scoped_java_ref.h" #include "base/callback.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/time/time.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/profile_oauth2_token_service.h"
diff --git a/chrome/browser/signin/signin_error_notifier_ash_unittest.cc b/chrome/browser/signin/signin_error_notifier_ash_unittest.cc index 8fe2d437..322195a 100644 --- a/chrome/browser/signin/signin_error_notifier_ash_unittest.cc +++ b/chrome/browser/signin/signin_error_notifier_ash_unittest.cc
@@ -6,9 +6,10 @@ #include <stddef.h> +#include <memory> + #include "ash/test/ash_test_base.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/notifications/notification.h" @@ -96,10 +97,10 @@ } #if defined(OS_WIN) - scoped_ptr<gfx::Screen> test_screen_; + std::unique_ptr<gfx::Screen> test_screen_; #endif - scoped_ptr<TestingProfileManager> profile_manager_; - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<TestingProfileManager> profile_manager_; + std::unique_ptr<TestingProfile> profile_; SigninErrorController* error_controller_; NotificationUIManager* notification_ui_manager_; };
diff --git a/chrome/browser/signin/signin_global_error_unittest.cc b/chrome/browser/signin/signin_global_error_unittest.cc index ae4fc48..610273a 100644 --- a/chrome/browser/signin/signin_global_error_unittest.cc +++ b/chrome/browser/signin/signin_global_error_unittest.cc
@@ -6,10 +6,10 @@ #include <stddef.h> +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/utf_string_conversions.h" #include "base/test/histogram_tester.h" #include "chrome/browser/profiles/profile_attributes_entry.h" @@ -56,7 +56,7 @@ testing_factories.push_back(std::make_pair( SigninManagerFactory::GetInstance(), BuildFakeSigninManagerBase)); profile_ = profile_manager_.CreateTestingProfile( - "Person 1", scoped_ptr<syncable_prefs::PrefServiceSyncable>(), + "Person 1", std::unique_ptr<syncable_prefs::PrefServiceSyncable>(), base::UTF8ToUTF16("Person 1"), 0, std::string(), testing_factories); SigninManagerFactory::GetForProfile(profile()) @@ -86,7 +86,7 @@ }; TEST_F(SigninGlobalErrorTest, NoErrorAuthStatusProviders) { - scoped_ptr<FakeAuthStatusProvider> provider; + std::unique_ptr<FakeAuthStatusProvider> provider; ASSERT_FALSE(global_error()->HasMenuItem()); @@ -100,8 +100,8 @@ } TEST_F(SigninGlobalErrorTest, ErrorAuthStatusProvider) { - scoped_ptr<FakeAuthStatusProvider> provider; - scoped_ptr<FakeAuthStatusProvider> error_provider; + std::unique_ptr<FakeAuthStatusProvider> provider; + std::unique_ptr<FakeAuthStatusProvider> error_provider; provider.reset(new FakeAuthStatusProvider(error_controller())); ASSERT_FALSE(global_error()->HasMenuItem());
diff --git a/chrome/browser/signin/signin_manager_unittest.cc b/chrome/browser/signin/signin_manager_unittest.cc index 7e17107..a8b3e88 100644 --- a/chrome/browser/signin/signin_manager_unittest.cc +++ b/chrome/browser/signin/signin_manager_unittest.cc
@@ -4,13 +4,13 @@ #include "components/signin/core/browser/signin_manager.h" +#include <memory> #include <utility> #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "base/strings/stringprintf.h" #include "chrome/browser/browser_process.h" @@ -54,9 +54,10 @@ namespace { -scoped_ptr<KeyedService> SigninManagerBuild(content::BrowserContext* context) { +std::unique_ptr<KeyedService> SigninManagerBuild( + content::BrowserContext* context) { Profile* profile = static_cast<Profile*>(context); - scoped_ptr<SigninManager> service(new SigninManager( + std::unique_ptr<SigninManager> service(new SigninManager( ChromeSigninClientFactory::GetInstance()->GetForProfile(profile), ProfileOAuth2TokenServiceFactory::GetForProfile(profile), AccountTrackerServiceFactory::GetForProfile(profile), @@ -218,12 +219,12 @@ content::TestBrowserThreadBundle thread_bundle_; net::TestURLFetcherFactory factory_; - scoped_ptr<SigninManager> naked_manager_; + std::unique_ptr<SigninManager> naked_manager_; SigninManager* manager_; TestSigninManagerObserver test_observer_; - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<TestingProfile> profile_; std::vector<std::string> oauth_tokens_fetched_; - scoped_ptr<TestingPrefServiceSimple> prefs_; + std::unique_ptr<TestingPrefServiceSimple> prefs_; std::vector<std::string> cookies_; };
diff --git a/chrome/browser/signin/signin_tracker_factory.cc b/chrome/browser/signin/signin_tracker_factory.cc index 0e1a5372..c7f4ddf5 100644 --- a/chrome/browser/signin/signin_tracker_factory.cc +++ b/chrome/browser/signin/signin_tracker_factory.cc
@@ -14,13 +14,12 @@ SigninTrackerFactory::~SigninTrackerFactory() {} // static -scoped_ptr<SigninTracker> SigninTrackerFactory::CreateForProfile( +std::unique_ptr<SigninTracker> SigninTrackerFactory::CreateForProfile( Profile* profile, SigninTracker::Observer* observer) { - return scoped_ptr<SigninTracker>(new SigninTracker( + return std::unique_ptr<SigninTracker>(new SigninTracker( ProfileOAuth2TokenServiceFactory::GetForProfile(profile), SigninManagerFactory::GetForProfile(profile), GaiaCookieManagerServiceFactory::GetForProfile(profile), - ChromeSigninClientFactory::GetForProfile(profile), - observer)); + ChromeSigninClientFactory::GetForProfile(profile), observer)); }
diff --git a/chrome/browser/signin/signin_tracker_factory.h b/chrome/browser/signin/signin_tracker_factory.h index c159e879..b3d6c9f 100644 --- a/chrome/browser/signin/signin_tracker_factory.h +++ b/chrome/browser/signin/signin_tracker_factory.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_SIGNIN_SIGNIN_TRACKER_FACTORY_H_ #define CHROME_BROWSER_SIGNIN_SIGNIN_TRACKER_FACTORY_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "components/signin/core/browser/signin_tracker.h" class Profile; @@ -17,7 +18,7 @@ // Creates a SigninTracker instance that tracks signin for |profile| on // behalf of |observer|. - static scoped_ptr<SigninTracker> CreateForProfile( + static std::unique_ptr<SigninTracker> CreateForProfile( Profile* profile, SigninTracker::Observer* observer);
diff --git a/chrome/browser/signin/signin_tracker_unittest.cc b/chrome/browser/signin/signin_tracker_unittest.cc index 0f72fb9..c1b69175 100644 --- a/chrome/browser/signin/signin_tracker_unittest.cc +++ b/chrome/browser/signin/signin_tracker_unittest.cc
@@ -89,8 +89,8 @@ } content::TestBrowserThreadBundle thread_bundle_; - scoped_ptr<SigninTracker> tracker_; - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<SigninTracker> tracker_; + std::unique_ptr<TestingProfile> profile_; FakeSigninManagerForTesting* mock_signin_manager_; FakeProfileOAuth2TokenService* fake_oauth2_token_service_; MockObserver observer_;
diff --git a/chrome/browser/signin/test_signin_client_builder.cc b/chrome/browser/signin/test_signin_client_builder.cc index ef66af9..890abef 100644 --- a/chrome/browser/signin/test_signin_client_builder.cc +++ b/chrome/browser/signin/test_signin_client_builder.cc
@@ -4,14 +4,15 @@ #include "chrome/browser/signin/test_signin_client_builder.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/profiles/profile.h" #include "components/signin/core/browser/test_signin_client.h" namespace signin { -scoped_ptr<KeyedService> BuildTestSigninClient( +std::unique_ptr<KeyedService> BuildTestSigninClient( content::BrowserContext* context) { - return make_scoped_ptr( + return base::WrapUnique( new TestSigninClient(static_cast<Profile*>(context)->GetPrefs())); }
diff --git a/chrome/browser/signin/test_signin_client_builder.h b/chrome/browser/signin/test_signin_client_builder.h index 54bb6eb..3863c51 100644 --- a/chrome/browser/signin/test_signin_client_builder.h +++ b/chrome/browser/signin/test_signin_client_builder.h
@@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_SIGNIN_TEST_SIGNIN_CLIENT_BUILDER_H_ #define CHROME_BROWSER_SIGNIN_TEST_SIGNIN_CLIENT_BUILDER_H_ -#include "base/memory/scoped_ptr.h" +#include <memory> class KeyedService; @@ -17,7 +17,7 @@ // Method to be used by the |ChromeSigninClientFactory| to create a test version // of the SigninClient -scoped_ptr<KeyedService> BuildTestSigninClient( +std::unique_ptr<KeyedService> BuildTestSigninClient( content::BrowserContext* context); } // namespace signin
diff --git a/chrome/browser/site_details_browsertest.cc b/chrome/browser/site_details_browsertest.cc index 2c9ebf9..bfade00 100644 --- a/chrome/browser/site_details_browsertest.cc +++ b/chrome/browser/site_details_browsertest.cc
@@ -92,7 +92,7 @@ base::MessageLoop::current()->QuitWhenIdle(); } - scoped_ptr<base::HistogramTester> uma_; + std::unique_ptr<base::HistogramTester> uma_; DISALLOW_COPY_AND_ASSIGN(TestMemoryDetails); }; @@ -185,7 +185,7 @@ // resources and, optionally, a background process. const Extension* CreateExtension(const std::string& name, bool has_background_process) { - scoped_ptr<TestExtensionDir> dir(new TestExtensionDir); + std::unique_ptr<TestExtensionDir> dir(new TestExtensionDir); DictionaryBuilder manifest; manifest.Set("name", name) @@ -243,7 +243,7 @@ const Extension* CreateHostedApp(const std::string& name, const GURL& app_url) { - scoped_ptr<TestExtensionDir> dir(new TestExtensionDir); + std::unique_ptr<TestExtensionDir> dir(new TestExtensionDir); DictionaryBuilder manifest; manifest.Set("name", name)
diff --git a/chrome/browser/speech/extension_api/tts_engine_extension_api.cc b/chrome/browser/speech/extension_api/tts_engine_extension_api.cc index a33835120c..3e8bb90 100644 --- a/chrome/browser/speech/extension_api/tts_engine_extension_api.cc +++ b/chrome/browser/speech/extension_api/tts_engine_extension_api.cc
@@ -145,13 +145,13 @@ // utterance now. bool sends_end_event = voice.events.find(TTS_EVENT_END) != voice.events.end(); - scoped_ptr<base::ListValue> args(new base::ListValue()); + std::unique_ptr<base::ListValue> args(new base::ListValue()); args->AppendString(utterance->text()); // Pass through most options to the speech engine, but remove some // that are handled internally. - scoped_ptr<base::DictionaryValue> options(static_cast<base::DictionaryValue*>( - utterance->options()->DeepCopy())); + std::unique_ptr<base::DictionaryValue> options( + static_cast<base::DictionaryValue*>(utterance->options()->DeepCopy())); if (options->HasKey(constants::kRequiredEventTypesKey)) options->Remove(constants::kRequiredEventTypesKey, NULL); if (options->HasKey(constants::kDesiredEventTypesKey)) @@ -195,7 +195,7 @@ std::string json; base::JSONWriter::Write(*args, &json); - scoped_ptr<extensions::Event> event( + std::unique_ptr<extensions::Event> event( new extensions::Event(extensions::events::TTS_ENGINE_ON_SPEAK, tts_engine_events::kOnSpeak, std::move(args))); Profile* profile = Profile::FromBrowserContext(utterance->browser_context()); @@ -205,8 +205,8 @@ } void TtsExtensionEngine::Stop(Utterance* utterance) { - scoped_ptr<base::ListValue> args(new base::ListValue()); - scoped_ptr<extensions::Event> event( + std::unique_ptr<base::ListValue> args(new base::ListValue()); + std::unique_ptr<extensions::Event> event( new extensions::Event(extensions::events::TTS_ENGINE_ON_STOP, tts_engine_events::kOnStop, std::move(args))); Profile* profile = Profile::FromBrowserContext(utterance->browser_context()); @@ -216,8 +216,8 @@ } void TtsExtensionEngine::Pause(Utterance* utterance) { - scoped_ptr<base::ListValue> args(new base::ListValue()); - scoped_ptr<extensions::Event> event( + std::unique_ptr<base::ListValue> args(new base::ListValue()); + std::unique_ptr<extensions::Event> event( new extensions::Event(extensions::events::TTS_ENGINE_ON_PAUSE, tts_engine_events::kOnPause, std::move(args))); Profile* profile = Profile::FromBrowserContext(utterance->browser_context()); @@ -229,8 +229,8 @@ } void TtsExtensionEngine::Resume(Utterance* utterance) { - scoped_ptr<base::ListValue> args(new base::ListValue()); - scoped_ptr<extensions::Event> event( + std::unique_ptr<base::ListValue> args(new base::ListValue()); + std::unique_ptr<extensions::Event> event( new extensions::Event(extensions::events::TTS_ENGINE_ON_RESUME, tts_engine_events::kOnResume, std::move(args))); Profile* profile = Profile::FromBrowserContext(utterance->browser_context());
diff --git a/chrome/browser/speech/extension_api/tts_extension_api.cc b/chrome/browser/speech/extension_api/tts_extension_api.cc index 410b672..be3eabfd 100644 --- a/chrome/browser/speech/extension_api/tts_extension_api.cc +++ b/chrome/browser/speech/extension_api/tts_extension_api.cc
@@ -124,7 +124,7 @@ } const char *event_type_string = TtsEventTypeToString(event_type); - scoped_ptr<base::DictionaryValue> details(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> details(new base::DictionaryValue()); if (char_index >= 0) details->SetInteger(constants::kCharIndexKey, char_index); details->SetString(constants::kEventTypeKey, event_type_string); @@ -134,10 +134,10 @@ details->SetInteger(constants::kSrcIdKey, utterance->src_id()); details->SetBoolean(constants::kIsFinalEventKey, utterance->finished()); - scoped_ptr<base::ListValue> arguments(new base::ListValue()); + std::unique_ptr<base::ListValue> arguments(new base::ListValue()); arguments->Set(0, details.release()); - scoped_ptr<extensions::Event> event( + std::unique_ptr<extensions::Event> event( new extensions::Event(::extensions::events::TTS_ON_EVENT, ::events::kOnEvent, std::move(arguments))); event->restrict_to_browser_context = utterance->browser_context(); @@ -157,7 +157,7 @@ return false; } - scoped_ptr<base::DictionaryValue> options(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> options(new base::DictionaryValue()); if (args_->GetSize() >= 2) { base::DictionaryValue* temp_options = NULL; if (args_->GetDictionary(1, &temp_options)) @@ -317,7 +317,7 @@ std::vector<VoiceData> voices; TtsController::GetInstance()->GetVoices(GetProfile(), &voices); - scoped_ptr<base::ListValue> result_voices(new base::ListValue()); + std::unique_ptr<base::ListValue> result_voices(new base::ListValue()); for (size_t i = 0; i < voices.size(); ++i) { const VoiceData& voice = voices[i]; base::DictionaryValue* result_voice = new base::DictionaryValue();
diff --git a/chrome/browser/speech/speech_recognition_browsertest.cc b/chrome/browser/speech/speech_recognition_browsertest.cc index d110ebd..3e7a0eb 100644 --- a/chrome/browser/speech/speech_recognition_browsertest.cc +++ b/chrome/browser/speech/speech_recognition_browsertest.cc
@@ -45,7 +45,7 @@ } protected: - scoped_ptr<content::FakeSpeechRecognitionManager> + std::unique_ptr<content::FakeSpeechRecognitionManager> fake_speech_recognition_manager_; private: @@ -90,7 +90,7 @@ embedded_test_server()->GetURL("/speech/web_speech_test.html"); GURL https_url(https_server.GetURL("/speech/web_speech_test.html")); - scoped_ptr<ChromeSpeechRecognitionManagerDelegate> delegate( + std::unique_ptr<ChromeSpeechRecognitionManagerDelegate> delegate( new ChromeSpeechRecognitionManagerDelegate()); static_cast<content::FakeSpeechRecognitionManager*>( fake_speech_recognition_manager_.get())->SetDelegate(delegate.get());
diff --git a/chrome/browser/speech/tts_controller.h b/chrome/browser/speech/tts_controller.h index 087045d..9ae2f32 100644 --- a/chrome/browser/speech/tts_controller.h +++ b/chrome/browser/speech/tts_controller.h
@@ -5,12 +5,12 @@ #ifndef CHROME_BROWSER_SPEECH_TTS_CONTROLLER_H_ #define CHROME_BROWSER_SPEECH_TTS_CONTROLLER_H_ +#include <memory> #include <queue> #include <set> #include <string> #include <vector> -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/memory/weak_ptr.h" #include "url/gurl.h" @@ -239,7 +239,7 @@ // The full options arg passed to tts.speak, which may include fields // other than the ones we explicitly parse, below. - scoped_ptr<base::Value> options_; + std::unique_ptr<base::Value> options_; // The source extension's ID of this utterance, so that it can associate // events with the appropriate callback.
diff --git a/chrome/browser/speech/tts_controller_impl.h b/chrome/browser/speech/tts_controller_impl.h index 23bb86c..b63df09 100644 --- a/chrome/browser/speech/tts_controller_impl.h +++ b/chrome/browser/speech/tts_controller_impl.h
@@ -5,13 +5,13 @@ #ifndef CHROME_BROWSER_SPEECH_TTS_CONTROLLER_IMPL_H_ #define CHROME_BROWSER_SPEECH_TTS_CONTROLLER_IMPL_H_ +#include <memory> #include <queue> #include <set> #include <string> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "chrome/browser/speech/tts_controller.h" #include "url/gurl.h"
diff --git a/chrome/browser/speech/tts_linux.cc b/chrome/browser/speech/tts_linux.cc index 93803d1..416c897 100644 --- a/chrome/browser/speech/tts_linux.cc +++ b/chrome/browser/speech/tts_linux.cc
@@ -6,17 +6,16 @@ #include <stddef.h> #include <map> +#include <memory> #include "base/command_line.h" #include "base/debug/leak_annotations.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/synchronization/lock.h" #include "chrome/browser/speech/tts_platform.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_switches.h" - #include "library_loaders/libspeechd.h" using content::BrowserThread; @@ -83,7 +82,7 @@ // Map a string composed of a voicename and module to the voicename. Used to // uniquely identify a voice across all available modules. - scoped_ptr<std::map<std::string, SPDChromeVoice> > all_native_voices_; + std::unique_ptr<std::map<std::string, SPDChromeVoice>> all_native_voices_; friend struct base::DefaultSingletonTraits<TtsPlatformImplLinux>;
diff --git a/chrome/browser/speech/tts_message_filter.cc b/chrome/browser/speech/tts_message_filter.cc index 3b398fc..013c7a9 100644 --- a/chrome/browser/speech/tts_message_filter.cc +++ b/chrome/browser/speech/tts_message_filter.cc
@@ -115,7 +115,7 @@ if (!browser_context_) return; - scoped_ptr<Utterance> utterance(new Utterance(browser_context_)); + std::unique_ptr<Utterance> utterance(new Utterance(browser_context_)); utterance->set_src_id(request.id); utterance->set_text(request.text); utterance->set_lang(request.lang);
diff --git a/chrome/browser/ssl/bad_clock_blocking_page.cc b/chrome/browser/ssl/bad_clock_blocking_page.cc index dcdfae4..105c52e 100644 --- a/chrome/browser/ssl/bad_clock_blocking_page.cc +++ b/chrome/browser/ssl/bad_clock_blocking_page.cc
@@ -55,21 +55,20 @@ const GURL& request_url, const base::Time& time_triggered, ssl_errors::ClockState clock_state, - scoped_ptr<SSLCertReporter> ssl_cert_reporter, + std::unique_ptr<SSLCertReporter> ssl_cert_reporter, const base::Callback<void(bool)>& callback) : SecurityInterstitialPage(web_contents, request_url), callback_(callback), ssl_info_(ssl_info), time_triggered_(time_triggered), controller_(new ChromeControllerClient(web_contents)) { - // Set up the metrics helper for the BadClockUI. security_interstitials::MetricsHelper::ReportDetails reporting_info; reporting_info.metric_prefix = kMetricsName; ChromeMetricsHelper* chrome_metrics_helper = new ChromeMetricsHelper( web_contents, request_url, reporting_info, kMetricsName); chrome_metrics_helper->StartRecordingCaptivePortalMetrics(false); - scoped_ptr<security_interstitials::MetricsHelper> metrics_helper( + std::unique_ptr<security_interstitials::MetricsHelper> metrics_helper( chrome_metrics_helper); controller_->set_metrics_helper(std::move(metrics_helper)); @@ -131,7 +130,7 @@ } void BadClockBlockingPage::SetSSLCertReporterForTesting( - scoped_ptr<SSLCertReporter> ssl_cert_reporter) { + std::unique_ptr<SSLCertReporter> ssl_cert_reporter) { cert_report_helper_->SetSSLCertReporterForTesting( std::move(ssl_cert_reporter)); }
diff --git a/chrome/browser/ssl/bad_clock_blocking_page.h b/chrome/browser/ssl/bad_clock_blocking_page.h index 27d0ced9..ee5edfb0 100644 --- a/chrome/browser/ssl/bad_clock_blocking_page.h +++ b/chrome/browser/ssl/bad_clock_blocking_page.h
@@ -9,6 +9,7 @@ #include "base/callback.h" #include "base/macros.h" +#include "base/memory/scoped_ptr.h" #include "base/time/time.h" #include "chrome/browser/interstitials/security_interstitial_page.h" #include "chrome/browser/ssl/ssl_cert_reporter.h" @@ -40,7 +41,7 @@ const GURL& request_url, const base::Time& time_triggered, ssl_errors::ClockState clock_state, - scoped_ptr<SSLCertReporter> ssl_cert_reporter, + std::unique_ptr<SSLCertReporter> ssl_cert_reporter, const base::Callback<void(bool)>& callback); ~BadClockBlockingPage() override; @@ -49,7 +50,7 @@ InterstitialPageDelegate::TypeID GetTypeForTesting() const override; void SetSSLCertReporterForTesting( - scoped_ptr<SSLCertReporter> ssl_cert_reporter); + std::unique_ptr<SSLCertReporter> ssl_cert_reporter); protected: // InterstitialPageDelegate implementation: @@ -70,10 +71,10 @@ base::Callback<void(bool)> callback_; const net::SSLInfo ssl_info_; const base::Time time_triggered_; - scoped_ptr<ChromeControllerClient> controller_; + std::unique_ptr<ChromeControllerClient> controller_; - scoped_ptr<security_interstitials::BadClockUI> bad_clock_ui_; - scoped_ptr<CertReportHelper> cert_report_helper_; + std::unique_ptr<security_interstitials::BadClockUI> bad_clock_ui_; + std::unique_ptr<CertReportHelper> cert_report_helper_; DISALLOW_COPY_AND_ASSIGN(BadClockBlockingPage); };
diff --git a/chrome/browser/ssl/captive_portal_blocking_page.cc b/chrome/browser/ssl/captive_portal_blocking_page.cc index 27c08db..cf610aa4 100644 --- a/chrome/browser/ssl/captive_portal_blocking_page.cc +++ b/chrome/browser/ssl/captive_portal_blocking_page.cc
@@ -52,7 +52,7 @@ content::WebContents* web_contents, const GURL& request_url, const GURL& login_url, - scoped_ptr<SSLCertReporter> ssl_cert_reporter, + std::unique_ptr<SSLCertReporter> ssl_cert_reporter, const net::SSLInfo& ssl_info, const base::Callback<void(bool)>& callback) : SecurityInterstitialPage(web_contents, request_url), @@ -92,7 +92,7 @@ // Linux so |net::GetWifiSSID| is used instead. std::string ssid; #if defined(OS_WIN) || defined(OS_MACOSX) - scoped_ptr<wifi::WiFiService> wifi_service(wifi::WiFiService::Create()); + std::unique_ptr<wifi::WiFiService> wifi_service(wifi::WiFiService::Create()); wifi_service->Initialize(nullptr); std::string error; wifi_service->GetConnectedNetworkSSID(&ssid, &error);
diff --git a/chrome/browser/ssl/captive_portal_blocking_page.h b/chrome/browser/ssl/captive_portal_blocking_page.h index ec7e0cb..ce185d9a 100644 --- a/chrome/browser/ssl/captive_portal_blocking_page.h +++ b/chrome/browser/ssl/captive_portal_blocking_page.h
@@ -5,11 +5,11 @@ #ifndef CHROME_BROWSER_SSL_CAPTIVE_PORTAL_BLOCKING_PAGE_H_ #define CHROME_BROWSER_SSL_CAPTIVE_PORTAL_BLOCKING_PAGE_H_ +#include <memory> #include <string> #include "base/callback.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/interstitials/security_interstitial_page.h" #include "url/gurl.h" @@ -43,7 +43,7 @@ CaptivePortalBlockingPage(content::WebContents* web_contents, const GURL& request_url, const GURL& login_url, - scoped_ptr<SSLCertReporter> ssl_cert_reporter, + std::unique_ptr<SSLCertReporter> ssl_cert_reporter, const net::SSLInfo& ssl_info, const base::Callback<void(bool)>& callback); ~CaptivePortalBlockingPage() override; @@ -71,7 +71,7 @@ private: // URL of the login page, opened when the user clicks the "Connect" button. const GURL login_url_; - scoped_ptr<CertReportHelper> cert_report_helper_; + std::unique_ptr<CertReportHelper> cert_report_helper_; base::Callback<void(bool)> callback_; DISALLOW_COPY_AND_ASSIGN(CaptivePortalBlockingPage);
diff --git a/chrome/browser/ssl/captive_portal_blocking_page_browsertest.cc b/chrome/browser/ssl/captive_portal_blocking_page_browsertest.cc index e913d42..555b1e4f 100644 --- a/chrome/browser/ssl/captive_portal_blocking_page_browsertest.cc +++ b/chrome/browser/ssl/captive_portal_blocking_page_browsertest.cc
@@ -63,7 +63,7 @@ content::WebContents* web_contents, const GURL& request_url, const GURL& login_url, - scoped_ptr<SSLCertReporter> ssl_cert_reporter, + std::unique_ptr<SSLCertReporter> ssl_cert_reporter, const net::SSLInfo& ssl_info, const base::Callback<void(bool)>& callback, bool is_wifi, @@ -95,7 +95,7 @@ ExpectWiFi expect_wifi, ExpectWiFiSSID expect_wifi_ssid, ExpectLoginURL expect_login_url, - scoped_ptr<SSLCertReporter> ssl_cert_reporter, + std::unique_ptr<SSLCertReporter> ssl_cert_reporter, const std::string& expected_login_hostname); void TestInterstitial(bool is_wifi_connection, @@ -111,7 +111,7 @@ ExpectWiFi expect_wifi, ExpectWiFiSSID expect_wifi_ssid, ExpectLoginURL expect_login_url, - scoped_ptr<SSLCertReporter> ssl_cert_reporter); + std::unique_ptr<SSLCertReporter> ssl_cert_reporter); void TestCertReporting(certificate_reporting_test_utils::OptIn opt_in); @@ -126,7 +126,7 @@ ExpectWiFi expect_wifi, ExpectWiFiSSID expect_wifi_ssid, ExpectLoginURL expect_login_url, - scoped_ptr<SSLCertReporter> ssl_cert_reporter, + std::unique_ptr<SSLCertReporter> ssl_cert_reporter, const std::string& expected_login_hostname) { content::WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -180,7 +180,7 @@ ExpectWiFi expect_wifi, ExpectWiFiSSID expect_wifi_ssid, ExpectLoginURL expect_login_url, - scoped_ptr<SSLCertReporter> ssl_cert_reporter) { + std::unique_ptr<SSLCertReporter> ssl_cert_reporter) { TestInterstitial(is_wifi_connection, wifi_ssid, login_url, expect_wifi, expect_wifi_ssid, expect_login_url, std::move(ssl_cert_reporter), login_url.host()); @@ -192,7 +192,7 @@ certificate_reporting_test_utils::SetCertReportingOptIn(browser(), opt_in); base::RunLoop run_loop; - scoped_ptr<SSLCertReporter> ssl_cert_reporter = + std::unique_ptr<SSLCertReporter> ssl_cert_reporter = certificate_reporting_test_utils::SetUpMockSSLCertReporter( &run_loop, opt_in == certificate_reporting_test_utils::EXTENDED_REPORTING_OPT_IN
diff --git a/chrome/browser/ssl/cert_report_helper.cc b/chrome/browser/ssl/cert_report_helper.cc index 49cc741..08d5771 100644 --- a/chrome/browser/ssl/cert_report_helper.cc +++ b/chrome/browser/ssl/cert_report_helper.cc
@@ -34,7 +34,7 @@ const char CertReportHelper::kFinchParamName[] = "sendingThreshold"; CertReportHelper::CertReportHelper( - scoped_ptr<SSLCertReporter> ssl_cert_reporter, + std::unique_ptr<SSLCertReporter> ssl_cert_reporter, content::WebContents* web_contents, const GURL& request_url, const net::SSLInfo& ssl_info, @@ -112,7 +112,7 @@ } void CertReportHelper::SetSSLCertReporterForTesting( - scoped_ptr<SSLCertReporter> ssl_cert_reporter) { + std::unique_ptr<SSLCertReporter> ssl_cert_reporter) { ssl_cert_reporter_ = std::move(ssl_cert_reporter); }
diff --git a/chrome/browser/ssl/cert_report_helper.h b/chrome/browser/ssl/cert_report_helper.h index a9b15355..868a3c9 100644 --- a/chrome/browser/ssl/cert_report_helper.h +++ b/chrome/browser/ssl/cert_report_helper.h
@@ -37,7 +37,7 @@ static const char kFinchGroupDontShowDontSend[]; static const char kFinchParamName[]; - CertReportHelper(scoped_ptr<SSLCertReporter> ssl_cert_reporter, + CertReportHelper(std::unique_ptr<SSLCertReporter> ssl_cert_reporter, content::WebContents* web_contents, const GURL& request_url, const net::SSLInfo& ssl_info, @@ -60,7 +60,7 @@ // Allows tests to inject a mock reporter. void SetSSLCertReporterForTesting( - scoped_ptr<SSLCertReporter> ssl_cert_reporter); + std::unique_ptr<SSLCertReporter> ssl_cert_reporter); private: // Checks whether a checkbox should be shown on the page that allows @@ -76,7 +76,7 @@ bool IsPrefEnabled(const char* pref); // Handles reports of invalid SSL certificates. - scoped_ptr<SSLCertReporter> ssl_cert_reporter_; + std::unique_ptr<SSLCertReporter> ssl_cert_reporter_; // The WebContents for which this helper sends reports. content::WebContents* web_contents_; // The URL for which this helper sends reports.
diff --git a/chrome/browser/ssl/cert_verifier_browser_test.h b/chrome/browser/ssl/cert_verifier_browser_test.h index d5d977cc..38ddcdf 100644 --- a/chrome/browser/ssl/cert_verifier_browser_test.h +++ b/chrome/browser/ssl/cert_verifier_browser_test.h
@@ -5,7 +5,8 @@ #ifndef CHROME_BROWSER_SSL_CERT_VERIFIER_BROWSER_TEST_H_ #define CHROME_BROWSER_SSL_CERT_VERIFIER_BROWSER_TEST_H_ -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "chrome/test/base/in_process_browser_test.h" namespace net { @@ -31,7 +32,7 @@ net::MockCertVerifier* mock_cert_verifier(); private: - scoped_ptr<net::MockCertVerifier> mock_cert_verifier_; + std::unique_ptr<net::MockCertVerifier> mock_cert_verifier_; }; #endif // CHROME_BROWSER_SSL_CERT_VERIFIER_BROWSER_TEST_H_
diff --git a/chrome/browser/ssl/certificate_reporting_test_utils.cc b/chrome/browser/ssl/certificate_reporting_test_utils.cc index 82b78b64..013cdf26 100644 --- a/chrome/browser/ssl/certificate_reporting_test_utils.cc +++ b/chrome/browser/ssl/certificate_reporting_test_utils.cc
@@ -37,7 +37,7 @@ void SetMockReporter( SafeBrowsingService* safe_browsing_service, - scoped_ptr<certificate_reporting::ErrorReporter> reporter) { + std::unique_ptr<certificate_reporting::ErrorReporter> reporter) { safe_browsing_service->ping_manager()->SetCertificateErrorReporterForTesting( std::move(reporter)); } @@ -140,9 +140,10 @@ content::BrowserThread::PostTask( content::BrowserThread::IO, FROM_HERE, - base::Bind(SetMockReporter, base::RetainedRef(safe_browsing_service), - base::Passed(scoped_ptr<certificate_reporting::ErrorReporter>( - reporter_)))); + base::Bind( + SetMockReporter, base::RetainedRef(safe_browsing_service), + base::Passed(std::unique_ptr<certificate_reporting::ErrorReporter>( + reporter_)))); } const std::string& CertificateReportingTest::GetLatestHostnameReported() const { @@ -155,7 +156,7 @@ opt_in == EXTENDED_REPORTING_OPT_IN); } -scoped_ptr<SSLCertReporter> SetUpMockSSLCertReporter( +std::unique_ptr<SSLCertReporter> SetUpMockSSLCertReporter( base::RunLoop* run_loop, ExpectReport expect_report) { // Set up a MockSSLCertReporter to keep track of when the blocking @@ -165,10 +166,11 @@ if (!sb_service) return nullptr; - scoped_ptr<MockSSLCertReporter> ssl_cert_reporter(new MockSSLCertReporter( - sb_service->ui_manager(), expect_report == CERT_REPORT_EXPECTED - ? run_loop->QuitClosure() - : base::Bind(&base::DoNothing))); + std::unique_ptr<MockSSLCertReporter> ssl_cert_reporter( + new MockSSLCertReporter(sb_service->ui_manager(), + expect_report == CERT_REPORT_EXPECTED + ? run_loop->QuitClosure() + : base::Bind(&base::DoNothing))); ssl_cert_reporter->set_expect_report(expect_report == CERT_REPORT_EXPECTED); return std::move(ssl_cert_reporter); }
diff --git a/chrome/browser/ssl/certificate_reporting_test_utils.h b/chrome/browser/ssl/certificate_reporting_test_utils.h index 29cd62b1..1136c5d 100644 --- a/chrome/browser/ssl/certificate_reporting_test_utils.h +++ b/chrome/browser/ssl/certificate_reporting_test_utils.h
@@ -7,6 +7,7 @@ #include <string> +#include "base/memory/scoped_ptr.h" #include "chrome/test/base/in_process_browser_test.h" class Browser; @@ -48,7 +49,7 @@ // be owned by the caller. The mock SSLCertReporter will call // |run_loop|'s QuitClosure when a report is sent. It also checks that a // report is sent or not sent according to |expect_report|. -scoped_ptr<SSLCertReporter> SetUpMockSSLCertReporter( +std::unique_ptr<SSLCertReporter> SetUpMockSSLCertReporter( base::RunLoop* run_loop, ExpectReport expect_report);
diff --git a/chrome/browser/ssl/chrome_expect_ct_reporter.cc b/chrome/browser/ssl/chrome_expect_ct_reporter.cc index 983a2cad..3fb0789 100644 --- a/chrome/browser/ssl/chrome_expect_ct_reporter.cc +++ b/chrome/browser/ssl/chrome_expect_ct_reporter.cc
@@ -10,6 +10,7 @@ #include "base/command_line.h" #include "base/feature_list.h" #include "base/json/json_writer.h" +#include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/sparse_histogram.h" #include "base/strings/string_number_conversions.h" @@ -29,16 +30,16 @@ exploded.millisecond); } -scoped_ptr<base::ListValue> GetPEMEncodedChainAsList( +std::unique_ptr<base::ListValue> GetPEMEncodedChainAsList( const net::X509Certificate* cert_chain) { if (!cert_chain) - return make_scoped_ptr(new base::ListValue()); + return base::WrapUnique(new base::ListValue()); - scoped_ptr<base::ListValue> result(new base::ListValue()); + std::unique_ptr<base::ListValue> result(new base::ListValue()); std::vector<std::string> pem_encoded_chain; cert_chain->GetPEMEncodedChain(&pem_encoded_chain); for (const std::string& cert : pem_encoded_chain) - result->Append(make_scoped_ptr(new base::StringValue(cert))); + result->Append(base::WrapUnique(new base::StringValue(cert))); return result; } @@ -61,7 +62,7 @@ void AddUnknownSCT( const net::SignedCertificateTimestampAndStatus& sct_and_status, base::ListValue* list) { - scoped_ptr<base::DictionaryValue> list_item(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> list_item(new base::DictionaryValue()); list_item->SetString("origin", SCTOriginToString(sct_and_status.sct->origin)); list->Append(std::move(list_item)); } @@ -69,7 +70,7 @@ void AddInvalidSCT( const net::SignedCertificateTimestampAndStatus& sct_and_status, base::ListValue* list) { - scoped_ptr<base::DictionaryValue> list_item(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> list_item(new base::DictionaryValue()); list_item->SetString("origin", SCTOriginToString(sct_and_status.sct->origin)); std::string log_id; base::Base64Encode(sct_and_status.sct->log_id, &log_id); @@ -79,12 +80,12 @@ void AddValidSCT(const net::SignedCertificateTimestampAndStatus& sct_and_status, base::ListValue* list) { - scoped_ptr<base::DictionaryValue> list_item(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> list_item(new base::DictionaryValue()); list_item->SetString("origin", SCTOriginToString(sct_and_status.sct->origin)); // The structure of the SCT object is defined in // http://tools.ietf.org/html/rfc6962#section-4.1. - scoped_ptr<base::DictionaryValue> sct(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> sct(new base::DictionaryValue()); sct->SetInteger("sct_version", sct_and_status.sct->version); std::string log_id; base::Base64Encode(sct_and_status.sct->log_id, &log_id); @@ -142,9 +143,9 @@ report.Set("validated-certificate-chain", GetPEMEncodedChainAsList(ssl_info.cert.get())); - scoped_ptr<base::ListValue> unknown_scts(new base::ListValue()); - scoped_ptr<base::ListValue> invalid_scts(new base::ListValue()); - scoped_ptr<base::ListValue> valid_scts(new base::ListValue()); + std::unique_ptr<base::ListValue> unknown_scts(new base::ListValue()); + std::unique_ptr<base::ListValue> invalid_scts(new base::ListValue()); + std::unique_ptr<base::ListValue> valid_scts(new base::ListValue()); for (const auto& sct_and_status : ssl_info.signed_certificate_timestamps) { switch (sct_and_status.status) {
diff --git a/chrome/browser/ssl/chrome_expect_ct_reporter.h b/chrome/browser/ssl/chrome_expect_ct_reporter.h index 7ceb441c..e5be865 100644 --- a/chrome/browser/ssl/chrome_expect_ct_reporter.h +++ b/chrome/browser/ssl/chrome_expect_ct_reporter.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_SSL_CHROME_EXPECT_CT_REPORTER_H_ #define CHROME_BROWSER_SSL_CHROME_EXPECT_CT_REPORTER_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/http/transport_security_state.h" namespace net { @@ -34,7 +35,7 @@ FRIEND_TEST_ALL_PREFIXES(ChromeExpectCTReporterTest, EmptyReportURI); FRIEND_TEST_ALL_PREFIXES(ChromeExpectCTReporterTest, SendReport); - scoped_ptr<net::CertificateReportSender> report_sender_; + std::unique_ptr<net::CertificateReportSender> report_sender_; DISALLOW_COPY_AND_ASSIGN(ChromeExpectCTReporter); };
diff --git a/chrome/browser/ssl/chrome_expect_ct_reporter_unittest.cc b/chrome/browser/ssl/chrome_expect_ct_reporter_unittest.cc index bebe06f..6ca03f55 100644 --- a/chrome/browser/ssl/chrome_expect_ct_reporter_unittest.cc +++ b/chrome/browser/ssl/chrome_expect_ct_reporter_unittest.cc
@@ -217,7 +217,7 @@ void CheckExpectCTReport(const std::string& serialized_report, const net::HostPortPair& host_port, const net::SSLInfo& ssl_info) { - scoped_ptr<base::Value> value(base::JSONReader::Read(serialized_report)); + std::unique_ptr<base::Value> value(base::JSONReader::Read(serialized_report)); ASSERT_TRUE(value); ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
diff --git a/chrome/browser/ssl/chrome_security_state_model_client.h b/chrome/browser/ssl/chrome_security_state_model_client.h index 1c3296f..4ea5279 100644 --- a/chrome/browser/ssl/chrome_security_state_model_client.h +++ b/chrome/browser/ssl/chrome_security_state_model_client.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_SSL_CHROME_SECURITY_STATE_MODEL_CLIENT_H_ #define CHROME_BROWSER_SSL_CHROME_SECURITY_STATE_MODEL_CLIENT_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "components/security_state/security_state_model.h" #include "components/security_state/security_state_model_client.h" #include "content/public/browser/web_contents_user_data.h" @@ -38,7 +39,7 @@ friend class content::WebContentsUserData<ChromeSecurityStateModelClient>; content::WebContents* web_contents_; - scoped_ptr<security_state::SecurityStateModel> security_state_model_; + std::unique_ptr<security_state::SecurityStateModel> security_state_model_; DISALLOW_COPY_AND_ASSIGN(ChromeSecurityStateModelClient); };
diff --git a/chrome/browser/ssl/chrome_security_state_model_client_browser_tests.cc b/chrome/browser/ssl/chrome_security_state_model_client_browser_tests.cc index fc46b36..d2c41d7 100644 --- a/chrome/browser/ssl/chrome_security_state_model_client_browser_tests.cc +++ b/chrome/browser/ssl/chrome_security_state_model_client_browser_tests.cc
@@ -458,7 +458,7 @@ net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); filter->AddHostnameInterceptor( "http", host, - scoped_ptr<net::URLRequestInterceptor>(new PendingJobInterceptor())); + std::unique_ptr<net::URLRequestInterceptor>(new PendingJobInterceptor())); } class SecurityStateModelLoadingTest
diff --git a/chrome/browser/ssl/chrome_ssl_host_state_delegate.cc b/chrome/browser/ssl/chrome_ssl_host_state_delegate.cc index 30a0ce36..e45257f 100644 --- a/chrome/browser/ssl/chrome_ssl_host_state_delegate.cc +++ b/chrome/browser/ssl/chrome_ssl_host_state_delegate.cc
@@ -118,7 +118,7 @@ // Pull out the value of the old-format setting. Only do this if the // patterns are as we expect them to be, otherwise the setting will just // be removed for safety. - scoped_ptr<base::Value> value; + std::unique_ptr<base::Value> value; if (setting.primary_pattern == setting.secondary_pattern && url.is_valid()) { value = map->GetWebsiteSetting(url, url, @@ -283,7 +283,7 @@ GURL url = GetSecureGURLForHost(host); HostContentSettingsMap* map = HostContentSettingsMapFactory::GetForProfile(profile_); - scoped_ptr<base::Value> value(map->GetWebsiteSetting( + std::unique_ptr<base::Value> value(map->GetWebsiteSetting( url, url, CONTENT_SETTINGS_TYPE_SSL_CERT_DECISIONS, std::string(), NULL)); if (!value.get() || !value->IsType(base::Value::TYPE_DICTIONARY)) @@ -326,7 +326,7 @@ HostContentSettingsMap* map = HostContentSettingsMapFactory::GetForProfile(profile_); GURL url = GetSecureGURLForHost(host); - scoped_ptr<base::Value> value(map->GetWebsiteSetting( + std::unique_ptr<base::Value> value(map->GetWebsiteSetting( url, url, CONTENT_SETTINGS_TYPE_SSL_CERT_DECISIONS, std::string(), NULL)); // Set a default value in case this method is short circuited and doesn't do a @@ -414,7 +414,7 @@ HostContentSettingsMap* map = HostContentSettingsMapFactory::GetForProfile(profile_); - scoped_ptr<base::Value> value(map->GetWebsiteSetting( + std::unique_ptr<base::Value> value(map->GetWebsiteSetting( url, url, CONTENT_SETTINGS_TYPE_SSL_CERT_DECISIONS, std::string(), NULL)); if (!value.get() || !value->IsType(base::Value::TYPE_DICTIONARY)) @@ -444,6 +444,6 @@ int pid) const { return !!ran_insecure_content_hosts_.count(BrokenHostEntry(host, pid)); } -void ChromeSSLHostStateDelegate::SetClock(scoped_ptr<base::Clock> clock) { +void ChromeSSLHostStateDelegate::SetClock(std::unique_ptr<base::Clock> clock) { clock_.reset(clock.release()); }
diff --git a/chrome/browser/ssl/chrome_ssl_host_state_delegate.h b/chrome/browser/ssl/chrome_ssl_host_state_delegate.h index 374403a9..8a01205 100644 --- a/chrome/browser/ssl/chrome_ssl_host_state_delegate.h +++ b/chrome/browser/ssl/chrome_ssl_host_state_delegate.h
@@ -5,9 +5,10 @@ #ifndef CHROME_BROWSER_SSL_CHROME_SSL_HOST_STATE_DELEGATE_H_ #define CHROME_BROWSER_SSL_CHROME_SSL_HOST_STATE_DELEGATE_H_ +#include <memory> + #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/time/time.h" #include "content/public/browser/ssl_host_state_delegate.h" @@ -58,7 +59,7 @@ protected: // SetClock takes ownership of the passed in clock. - void SetClock(scoped_ptr<base::Clock> clock); + void SetClock(std::unique_ptr<base::Clock> clock); private: FRIEND_TEST_ALL_PREFIXES(DefaultMemorySSLHostStateDelegateTest, AfterRestart); @@ -101,7 +102,7 @@ CreateDictionaryEntriesDisposition create_entries, bool* expired_previous_decision); - scoped_ptr<base::Clock> clock_; + std::unique_ptr<base::Clock> clock_; RememberSSLExceptionDecisionsDisposition should_remember_ssl_decisions_; Profile* profile_;
diff --git a/chrome/browser/ssl/chrome_ssl_host_state_delegate_factory.cc b/chrome/browser/ssl/chrome_ssl_host_state_delegate_factory.cc index f4567402..b2aa1d6 100644 --- a/chrome/browser/ssl/chrome_ssl_host_state_delegate_factory.cc +++ b/chrome/browser/ssl/chrome_ssl_host_state_delegate_factory.cc
@@ -4,8 +4,9 @@ #include "chrome/browser/ssl/chrome_ssl_host_state_delegate_factory.h" +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ssl/chrome_ssl_host_state_delegate.h" @@ -25,7 +26,7 @@ void Shutdown() override {} private: - scoped_ptr<ChromeSSLHostStateDelegate> decisions_; + std::unique_ptr<ChromeSSLHostStateDelegate> decisions_; DISALLOW_COPY_AND_ASSIGN(Service); };
diff --git a/chrome/browser/ssl/chrome_ssl_host_state_delegate_test.cc b/chrome/browser/ssl/chrome_ssl_host_state_delegate_test.cc index c3f99e8f..2db96c9e 100644 --- a/chrome/browser/ssl/chrome_ssl_host_state_delegate_test.cc +++ b/chrome/browser/ssl/chrome_ssl_host_state_delegate_test.cc
@@ -232,7 +232,7 @@ HostContentSettingsMap* map = HostContentSettingsMapFactory::GetForProfile(profile); GURL url(std::string("https://") + kWWWGoogleHost); - scoped_ptr<base::Value> new_format = + std::unique_ptr<base::Value> new_format = map->GetWebsiteSetting(url, url, CONTENT_SETTINGS_TYPE_SSL_CERT_DECISIONS, std::string(), nullptr); // Delete the new-format setting. @@ -254,7 +254,7 @@ // Trigger the migration code that happens on construction. { - scoped_ptr<ChromeSSLHostStateDelegate> temp_delegate( + std::unique_ptr<ChromeSSLHostStateDelegate> temp_delegate( new ChromeSSLHostStateDelegate(profile)); } @@ -361,7 +361,7 @@ // in the incognito profile. state->AllowCert(kWWWGoogleHost, *cert, net::CERT_STATUS_DATE_INVALID); - scoped_ptr<Profile> incognito(profile->CreateOffTheRecordProfile()); + std::unique_ptr<Profile> incognito(profile->CreateOffTheRecordProfile()); content::SSLHostStateDelegate* incognito_state = incognito->GetSSLHostStateDelegate(); @@ -401,7 +401,7 @@ state->QueryPolicy(kWWWGoogleHost, *cert, net::CERT_STATUS_DATE_INVALID, &unused_value)); - scoped_ptr<Profile> incognito(profile->CreateOffTheRecordProfile()); + std::unique_ptr<Profile> incognito(profile->CreateOffTheRecordProfile()); content::SSLHostStateDelegate* incognito_state = incognito->GetSSLHostStateDelegate(); @@ -444,7 +444,7 @@ base::SimpleTestClock* clock = new base::SimpleTestClock(); ChromeSSLHostStateDelegate* chrome_state = static_cast<ChromeSSLHostStateDelegate*>(state); - chrome_state->SetClock(scoped_ptr<base::Clock>(clock)); + chrome_state->SetClock(std::unique_ptr<base::Clock>(clock)); // Start the clock at standard system time. clock->SetNow(base::Time::NowFromSystemTime()); @@ -493,7 +493,7 @@ base::SimpleTestClock* clock = new base::SimpleTestClock(); ChromeSSLHostStateDelegate* chrome_state = static_cast<ChromeSSLHostStateDelegate*>(state); - chrome_state->SetClock(scoped_ptr<base::Clock>(clock)); + chrome_state->SetClock(std::unique_ptr<base::Clock>(clock)); // Start the clock at standard system time but do not advance at all to // emphasize that instant forget works.
diff --git a/chrome/browser/ssl/common_name_mismatch_handler.h b/chrome/browser/ssl/common_name_mismatch_handler.h index 95801d2..f1567c2 100644 --- a/chrome/browser/ssl/common_name_mismatch_handler.h +++ b/chrome/browser/ssl/common_name_mismatch_handler.h
@@ -5,10 +5,11 @@ #ifndef CHROME_BROWSER_SSL_COMMON_NAME_MISMATCH_HANDLER_H_ #define CHROME_BROWSER_SSL_COMMON_NAME_MISMATCH_HANDLER_H_ +#include <memory> + #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/threading/non_thread_safe.h" #include "base/time/time.h" #include "net/url_request/url_fetcher.h" @@ -82,7 +83,7 @@ const GURL request_url_; scoped_refptr<net::URLRequestContextGetter> request_context_; CheckUrlCallback check_url_callback_; - scoped_ptr<net::URLFetcher> url_fetcher_; + std::unique_ptr<net::URLFetcher> url_fetcher_; DISALLOW_COPY_AND_ASSIGN(CommonNameMismatchHandler); };
diff --git a/chrome/browser/ssl/ssl_add_certificate.cc b/chrome/browser/ssl/ssl_add_certificate.cc index a038873..67452ce 100644 --- a/chrome/browser/ssl/ssl_add_certificate.cc +++ b/chrome/browser/ssl/ssl_add_certificate.cc
@@ -64,7 +64,7 @@ void SSLAddCertificateInfoBarDelegate::Create(InfoBarService* infobar_service, net::X509Certificate* cert) { infobar_service->AddInfoBar(infobar_service->CreateConfirmInfoBar( - scoped_ptr<ConfirmInfoBarDelegate>( + std::unique_ptr<ConfirmInfoBarDelegate>( new SSLAddCertificateInfoBarDelegate(cert)))); }
diff --git a/chrome/browser/ssl/ssl_blocking_page.cc b/chrome/browser/ssl/ssl_blocking_page.cc index 19b5c80..0d27556 100644 --- a/chrome/browser/ssl/ssl_blocking_page.cc +++ b/chrome/browser/ssl/ssl_blocking_page.cc
@@ -9,6 +9,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback_helpers.h" +#include "base/memory/ptr_util.h" #include "base/metrics/histogram.h" #include "base/strings/string_number_conversions.h" #include "base/time/time.h" @@ -106,14 +107,15 @@ // Note that we always create a navigation entry with SSL errors. // No error happening loading a sub-resource triggers an interstitial so far. -SSLBlockingPage::SSLBlockingPage(content::WebContents* web_contents, - int cert_error, - const net::SSLInfo& ssl_info, - const GURL& request_url, - int options_mask, - const base::Time& time_triggered, - scoped_ptr<SSLCertReporter> ssl_cert_reporter, - const base::Callback<void(bool)>& callback) +SSLBlockingPage::SSLBlockingPage( + content::WebContents* web_contents, + int cert_error, + const net::SSLInfo& ssl_info, + const GURL& request_url, + int options_mask, + const base::Time& time_triggered, + std::unique_ptr<SSLCertReporter> ssl_cert_reporter, + const base::Callback<void(bool)>& callback) : SecurityInterstitialPage(web_contents, request_url), callback_(callback), ssl_info_(ssl_info), @@ -145,7 +147,7 @@ new ChromeMetricsHelper(web_contents, request_url, reporting_info, GetSamplingEventName(overridable_, cert_error)); chrome_metrics_helper->StartRecordingCaptivePortalMetrics(overridable_); - controller_->set_metrics_helper(make_scoped_ptr(chrome_metrics_helper)); + controller_->set_metrics_helper(base::WrapUnique(chrome_metrics_helper)); cert_report_helper_.reset(new CertReportHelper( std::move(ssl_cert_reporter), web_contents, request_url, ssl_info, @@ -210,7 +212,7 @@ } void SSLBlockingPage::SetSSLCertReporterForTesting( - scoped_ptr<SSLCertReporter> ssl_cert_reporter) { + std::unique_ptr<SSLCertReporter> ssl_cert_reporter) { cert_report_helper_->SetSSLCertReporterForTesting( std::move(ssl_cert_reporter)); }
diff --git a/chrome/browser/ssl/ssl_blocking_page.h b/chrome/browser/ssl/ssl_blocking_page.h index f3906ac..f60a66f 100644 --- a/chrome/browser/ssl/ssl_blocking_page.h +++ b/chrome/browser/ssl/ssl_blocking_page.h
@@ -58,7 +58,7 @@ const GURL& request_url, int options_mask, const base::Time& time_triggered, - scoped_ptr<SSLCertReporter> ssl_cert_reporter, + std::unique_ptr<SSLCertReporter> ssl_cert_reporter, const base::Callback<void(bool)>& callback); // InterstitialPageDelegate method: @@ -69,7 +69,7 @@ static bool IsOverridable(int options_mask, const Profile* const profile); void SetSSLCertReporterForTesting( - scoped_ptr<SSLCertReporter> ssl_cert_reporter); + std::unique_ptr<SSLCertReporter> ssl_cert_reporter); protected: friend class policy::PolicyTest_SSLErrorOverridingDisallowed_Test; @@ -99,9 +99,9 @@ // expired. const bool expired_but_previously_allowed_; - scoped_ptr<ChromeControllerClient> controller_; - scoped_ptr<security_interstitials::SSLErrorUI> ssl_error_ui_; - scoped_ptr<CertReportHelper> cert_report_helper_; + std::unique_ptr<ChromeControllerClient> controller_; + std::unique_ptr<security_interstitials::SSLErrorUI> ssl_error_ui_; + std::unique_ptr<CertReportHelper> cert_report_helper_; DISALLOW_COPY_AND_ASSIGN(SSLBlockingPage); };
diff --git a/chrome/browser/ssl/ssl_browser_tests.cc b/chrome/browser/ssl/ssl_browser_tests.cc index 218fe3f..ec6d2fc 100644 --- a/chrome/browser/ssl/ssl_browser_tests.cc +++ b/chrome/browser/ssl/ssl_browser_tests.cc
@@ -248,7 +248,7 @@ const content::WebContents* web_contents_; SSLErrorHandler::TimerStartedCallback callback_; - scoped_ptr<base::RunLoop> message_loop_runner_; + std::unique_ptr<base::RunLoop> message_loop_runner_; DISALLOW_COPY_AND_ASSIGN(SSLInterstitialTimerObserver); }; @@ -479,7 +479,7 @@ CheckAuthenticationBrokenState(tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL); - scoped_ptr<SSLCertReporter> ssl_cert_reporter = + std::unique_ptr<SSLCertReporter> ssl_cert_reporter = certificate_reporting_test_utils::SetUpMockSSLCertReporter( &run_loop, expect_report); @@ -541,7 +541,7 @@ CheckAuthenticationBrokenState(tab, net::CERT_STATUS_DATE_INVALID, AuthState::SHOWING_INTERSTITIAL); - scoped_ptr<SSLCertReporter> ssl_cert_reporter = + std::unique_ptr<SSLCertReporter> ssl_cert_reporter = certificate_reporting_test_utils::SetUpMockSSLCertReporter( &run_loop, expect_report); @@ -904,7 +904,8 @@ ASSERT_TRUE(https_server_expired_.Start()); // Set up the build and current clock times to be more than a year apart. - scoped_ptr<base::SimpleTestClock> mock_clock(new base::SimpleTestClock()); + std::unique_ptr<base::SimpleTestClock> mock_clock( + new base::SimpleTestClock()); mock_clock->SetNow(base::Time::NowFromSystemTime()); mock_clock->Advance(base::TimeDelta::FromDays(367)); SSLErrorHandler::SetClockForTest(mock_clock.get()); @@ -1286,7 +1287,7 @@ // cert selection. Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext()); DCHECK(profile); - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetString("ISSUER.CN", "pywebsocket"); HostContentSettingsMapFactory::GetForProfile(profile) ->SetWebsiteSettingDefaultScope(
diff --git a/chrome/browser/ssl/ssl_client_auth_observer.cc b/chrome/browser/ssl/ssl_client_auth_observer.cc index fd9fa66b..e071c68 100644 --- a/chrome/browser/ssl/ssl_client_auth_observer.cc +++ b/chrome/browser/ssl/ssl_client_auth_observer.cc
@@ -22,7 +22,7 @@ SSLClientAuthObserver::SSLClientAuthObserver( const content::BrowserContext* browser_context, const scoped_refptr<net::SSLCertRequestInfo>& cert_request_info, - scoped_ptr<content::ClientCertificateDelegate> delegate) + std::unique_ptr<content::ClientCertificateDelegate> delegate) : browser_context_(browser_context), cert_request_info_(cert_request_info), delegate_(std::move(delegate)) {}
diff --git a/chrome/browser/ssl/ssl_client_auth_observer.h b/chrome/browser/ssl/ssl_client_auth_observer.h index e62992d2..96f1930 100644 --- a/chrome/browser/ssl/ssl_client_auth_observer.h +++ b/chrome/browser/ssl/ssl_client_auth_observer.h
@@ -5,10 +5,11 @@ #ifndef CHROME_BROWSER_SSL_SSL_CLIENT_AUTH_OBSERVER_H_ #define CHROME_BROWSER_SSL_SSL_CLIENT_AUTH_OBSERVER_H_ +#include <memory> + #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" @@ -31,7 +32,7 @@ SSLClientAuthObserver( const content::BrowserContext* browser_context, const scoped_refptr<net::SSLCertRequestInfo>& cert_request_info, - scoped_ptr<content::ClientCertificateDelegate> delegate); + std::unique_ptr<content::ClientCertificateDelegate> delegate); ~SSLClientAuthObserver() override; // UI should implement this to close the dialog. @@ -67,7 +68,7 @@ const content::BrowserContext* browser_context_; scoped_refptr<net::SSLCertRequestInfo> cert_request_info_; - scoped_ptr<content::ClientCertificateDelegate> delegate_; + std::unique_ptr<content::ClientCertificateDelegate> delegate_; content::NotificationRegistrar notification_registrar_; DISALLOW_COPY_AND_ASSIGN(SSLClientAuthObserver);
diff --git a/chrome/browser/ssl/ssl_client_auth_requestor_mock.cc b/chrome/browser/ssl/ssl_client_auth_requestor_mock.cc index ef114b4..d0d1da5 100644 --- a/chrome/browser/ssl/ssl_client_auth_requestor_mock.cc +++ b/chrome/browser/ssl/ssl_client_auth_requestor_mock.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/ssl/ssl_client_auth_requestor_mock.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "content/public/browser/client_certificate_delegate.h" #include "net/ssl/ssl_cert_request_info.h" #include "net/url_request/url_request.h" @@ -44,7 +45,7 @@ SSLClientAuthRequestorMock::~SSLClientAuthRequestorMock() {} -scoped_ptr<content::ClientCertificateDelegate> +std::unique_ptr<content::ClientCertificateDelegate> SSLClientAuthRequestorMock::CreateDelegate() { - return make_scoped_ptr(new FakeClientCertificateDelegate(this)); + return base::WrapUnique(new FakeClientCertificateDelegate(this)); }
diff --git a/chrome/browser/ssl/ssl_client_auth_requestor_mock.h b/chrome/browser/ssl/ssl_client_auth_requestor_mock.h index 6801d1a..115f2ad 100644 --- a/chrome/browser/ssl/ssl_client_auth_requestor_mock.h +++ b/chrome/browser/ssl/ssl_client_auth_requestor_mock.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_SSL_SSL_CLIENT_AUTH_REQUESTOR_MOCK_H_ #define CHROME_BROWSER_SSL_SSL_CLIENT_AUTH_REQUESTOR_MOCK_H_ +#include <memory> + #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "testing/gmock/include/gmock/gmock.h" namespace content { @@ -27,7 +28,7 @@ net::URLRequest* request, const scoped_refptr<net::SSLCertRequestInfo>& cert_request_info); - scoped_ptr<content::ClientCertificateDelegate> CreateDelegate(); + std::unique_ptr<content::ClientCertificateDelegate> CreateDelegate(); MOCK_METHOD1(CertificateSelected, void(net::X509Certificate* cert)); MOCK_METHOD0(CancelCertificateSelection, void());
diff --git a/chrome/browser/ssl/ssl_client_certificate_selector.h b/chrome/browser/ssl/ssl_client_certificate_selector.h index 7c73479d..fcbb624 100644 --- a/chrome/browser/ssl/ssl_client_certificate_selector.h +++ b/chrome/browser/ssl/ssl_client_certificate_selector.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_SSL_SSL_CLIENT_CERTIFICATE_SELECTOR_H_ #define CHROME_BROWSER_SSL_SSL_CLIENT_CERTIFICATE_SELECTOR_H_ +#include <memory> + #include "base/callback_forward.h" -#include "base/memory/scoped_ptr.h" namespace content { class ClientCertificateDelegate; @@ -27,7 +28,7 @@ void ShowSSLClientCertificateSelector( content::WebContents* contents, net::SSLCertRequestInfo* cert_request_info, - scoped_ptr<content::ClientCertificateDelegate> delegate); + std::unique_ptr<content::ClientCertificateDelegate> delegate); } // namespace chrome
diff --git a/chrome/browser/ssl/ssl_client_certificate_selector_test.cc b/chrome/browser/ssl/ssl_client_certificate_selector_test.cc index e61b34f..5f045f9 100644 --- a/chrome/browser/ssl/ssl_client_certificate_selector_test.cc +++ b/chrome/browser/ssl/ssl_client_certificate_selector_test.cc
@@ -93,10 +93,10 @@ io_loop_finished_event_.Signal(); } -scoped_ptr<net::URLRequest> +std::unique_ptr<net::URLRequest> SSLClientCertificateSelectorTestBase::MakeURLRequest( net::URLRequestContextGetter* context_getter) { - scoped_ptr<net::URLRequest> request = + std::unique_ptr<net::URLRequest> request = context_getter->GetURLRequestContext()->CreateRequest( GURL("https://example"), net::DEFAULT_PRIORITY, NULL); return request;
diff --git a/chrome/browser/ssl/ssl_client_certificate_selector_test.h b/chrome/browser/ssl/ssl_client_certificate_selector_test.h index d646c49f..98f2527 100644 --- a/chrome/browser/ssl/ssl_client_certificate_selector_test.h +++ b/chrome/browser/ssl/ssl_client_certificate_selector_test.h
@@ -5,7 +5,8 @@ #ifndef CHROME_BROWSER_SSL_SSL_CLIENT_CERTIFICATE_SELECTOR_TEST_H_ #define CHROME_BROWSER_SSL_SSL_CLIENT_CERTIFICATE_SELECTOR_TEST_H_ -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "base/synchronization/waitable_event.h" #include "chrome/browser/ssl/ssl_client_auth_requestor_mock.h" #include "chrome/test/base/in_process_browser_test.h" @@ -29,7 +30,7 @@ virtual void TearDownOnIOThread(); protected: - scoped_ptr<net::URLRequest> MakeURLRequest( + std::unique_ptr<net::URLRequest> MakeURLRequest( net::URLRequestContextGetter* context_getter); base::WaitableEvent io_loop_finished_event_;
diff --git a/chrome/browser/ssl/ssl_error_handler.cc b/chrome/browser/ssl/ssl_error_handler.cc index 079ab87..4f58013 100644 --- a/chrome/browser/ssl/ssl_error_handler.cc +++ b/chrome/browser/ssl/ssl_error_handler.cc
@@ -154,7 +154,7 @@ const net::SSLInfo& ssl_info, const GURL& request_url, int options_mask, - scoped_ptr<SSLCertReporter> ssl_cert_reporter, + std::unique_ptr<SSLCertReporter> ssl_cert_reporter, const base::Callback<void(bool)>& callback) { DCHECK(!FromWebContents(web_contents)); SSLErrorHandler* error_handler = @@ -181,13 +181,14 @@ g_testing_clock = testing_clock; } -SSLErrorHandler::SSLErrorHandler(content::WebContents* web_contents, - int cert_error, - const net::SSLInfo& ssl_info, - const GURL& request_url, - int options_mask, - scoped_ptr<SSLCertReporter> ssl_cert_reporter, - const base::Callback<void(bool)>& callback) +SSLErrorHandler::SSLErrorHandler( + content::WebContents* web_contents, + int cert_error, + const net::SSLInfo& ssl_info, + const GURL& request_url, + int options_mask, + std::unique_ptr<SSLCertReporter> ssl_cert_reporter, + const base::Callback<void(bool)>& callback) : content::WebContentsObserver(web_contents), web_contents_(web_contents), cert_error_(cert_error),
diff --git a/chrome/browser/ssl/ssl_error_handler.h b/chrome/browser/ssl/ssl_error_handler.h index dd69364..f86c487 100644 --- a/chrome/browser/ssl/ssl_error_handler.h +++ b/chrome/browser/ssl/ssl_error_handler.h
@@ -61,7 +61,7 @@ const net::SSLInfo& ssl_info, const GURL& request_url, int options_mask, - scoped_ptr<SSLCertReporter> ssl_cert_reporter, + std::unique_ptr<SSLCertReporter> ssl_cert_reporter, const base::Callback<void(bool)>& callback); // Testing methods. @@ -78,7 +78,7 @@ const net::SSLInfo& ssl_info, const GURL& request_url, int options_mask, - scoped_ptr<SSLCertReporter> ssl_cert_reporter, + std::unique_ptr<SSLCertReporter> ssl_cert_reporter, const base::Callback<void(bool)>& callback); ~SSLErrorHandler() override; @@ -138,9 +138,9 @@ content::NotificationRegistrar registrar_; base::OneShotTimer timer_; - scoped_ptr<CommonNameMismatchHandler> common_name_mismatch_handler_; + std::unique_ptr<CommonNameMismatchHandler> common_name_mismatch_handler_; - scoped_ptr<SSLCertReporter> ssl_cert_reporter_; + std::unique_ptr<SSLCertReporter> ssl_cert_reporter_; DISALLOW_COPY_AND_ASSIGN(SSLErrorHandler); };
diff --git a/chrome/browser/ssl/ssl_error_handler_unittest.cc b/chrome/browser/ssl/ssl_error_handler_unittest.cc index 21f5830..e09d521 100644 --- a/chrome/browser/ssl/ssl_error_handler_unittest.cc +++ b/chrome/browser/ssl/ssl_error_handler_unittest.cc
@@ -159,7 +159,7 @@ private: net::SSLInfo ssl_info_; - scoped_ptr<SSLErrorHandlerForTest> error_handler_; + std::unique_ptr<SSLErrorHandlerForTest> error_handler_; base::FieldTrialList field_trial_list_; };
diff --git a/chrome/browser/status_icons/desktop_notification_balloon.h b/chrome/browser/status_icons/desktop_notification_balloon.h index cd04be05..5164be1 100644 --- a/chrome/browser/status_icons/desktop_notification_balloon.h +++ b/chrome/browser/status_icons/desktop_notification_balloon.h
@@ -5,9 +5,10 @@ #ifndef CHROME_BROWSER_STATUS_ICONS_DESKTOP_NOTIFICATION_BALLOON_H_ #define CHROME_BROWSER_STATUS_ICONS_DESKTOP_NOTIFICATION_BALLOON_H_ +#include <memory> + #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" class Notification;
diff --git a/chrome/browser/status_icons/status_icon.cc b/chrome/browser/status_icons/status_icon.cc index 5722639..a05a88e6 100644 --- a/chrome/browser/status_icons/status_icon.cc +++ b/chrome/browser/status_icons/status_icon.cc
@@ -39,10 +39,11 @@ void StatusIcon::ForceVisible() {} -void StatusIcon::SetContextMenu(scoped_ptr<StatusIconMenuModel> menu) { +void StatusIcon::SetContextMenu(std::unique_ptr<StatusIconMenuModel> menu) { // The UI may been showing a menu for the current model, don't destroy it // until we've notified the UI of the change. - scoped_ptr<StatusIconMenuModel> old_menu = std::move(context_menu_contents_); + std::unique_ptr<StatusIconMenuModel> old_menu = + std::move(context_menu_contents_); context_menu_contents_ = std::move(menu); UpdatePlatformContextMenu(context_menu_contents_.get()); }
diff --git a/chrome/browser/status_icons/status_icon.h b/chrome/browser/status_icons/status_icon.h index 13985cc..0eaaf24 100644 --- a/chrome/browser/status_icons/status_icon.h +++ b/chrome/browser/status_icons/status_icon.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_STATUS_ICONS_STATUS_ICON_H_ #define CHROME_BROWSER_STATUS_ICONS_STATUS_ICON_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/observer_list.h" #include "base/strings/string16.h" #include "build/build_config.h" @@ -46,7 +47,7 @@ // Set the context menu for this icon. The icon takes ownership of the passed // context menu. Passing NULL results in no menu at all. - void SetContextMenu(scoped_ptr<StatusIconMenuModel> menu); + void SetContextMenu(std::unique_ptr<StatusIconMenuModel> menu); // Adds/Removes an observer for clicks on the status icon. If an observer is // registered, then left clicks on the status icon will result in the observer @@ -81,7 +82,7 @@ base::ObserverList<StatusIconObserver> observers_; // Context menu, if any. - scoped_ptr<StatusIconMenuModel> context_menu_contents_; + std::unique_ptr<StatusIconMenuModel> context_menu_contents_; DISALLOW_COPY_AND_ASSIGN(StatusIcon); };
diff --git a/chrome/browser/status_icons/status_icon_menu_model_unittest.cc b/chrome/browser/status_icons/status_icon_menu_model_unittest.cc index 19b9c757..f6dbaa1 100644 --- a/chrome/browser/status_icons/status_icon_menu_model_unittest.cc +++ b/chrome/browser/status_icons/status_icon_menu_model_unittest.cc
@@ -38,7 +38,7 @@ private: void OnMenuStateChanged() override { ++changed_count_; } - scoped_ptr<StatusIconMenuModel> menu_; + std::unique_ptr<StatusIconMenuModel> menu_; int changed_count_; };
diff --git a/chrome/browser/tab_contents/navigation_metrics_recorder.cc b/chrome/browser/tab_contents/navigation_metrics_recorder.cc index 8ee3fdd8..f507858 100644 --- a/chrome/browser/tab_contents/navigation_metrics_recorder.cc +++ b/chrome/browser/tab_contents/navigation_metrics_recorder.cc
@@ -7,8 +7,11 @@ #include "base/metrics/histogram_macros.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/tab_contents/origins_seen_service.h" +#include "chrome/browser/tab_contents/origins_seen_service_factory.h" #include "components/navigation_metrics/navigation_metrics.h" #include "components/rappor/rappor_utils.h" +#include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" @@ -17,6 +20,7 @@ #include "content/public/browser/render_widget_host_view.h" #include "content/public/common/frame_navigate_params.h" #include "url/gurl.h" +#include "url/origin.h" #if defined(OS_WIN) #include "base/win/windows_version.h" @@ -36,8 +40,17 @@ const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - navigation_metrics::RecordMainFrameNavigation(details.entry->GetVirtualURL(), - details.is_in_page); + + content::BrowserContext* context = web_contents()->GetBrowserContext(); + OriginsSeenService* service = + OriginsSeenServiceFactory::GetForBrowserContext(context); + const url::Origin origin(details.entry->GetVirtualURL()); + bool have_already_seen_origin = service->Insert(origin); + + navigation_metrics::RecordMainFrameNavigation( + details.entry->GetVirtualURL(), details.is_in_page, + context->IsOffTheRecord(), have_already_seen_origin); + // Record the domain and registry of the URL that resulted in a navigation to // a |data:| URL, either by redirects or user clicking a link. if (details.entry->GetVirtualURL().SchemeIs(url::kDataScheme) &&
diff --git a/chrome/browser/tab_contents/origins_seen_service.cc b/chrome/browser/tab_contents/origins_seen_service.cc new file mode 100644 index 0000000..7d373665 --- /dev/null +++ b/chrome/browser/tab_contents/origins_seen_service.cc
@@ -0,0 +1,20 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/tab_contents/origins_seen_service.h" + +namespace { +const size_t kDefaultMRUCacheSize = 1000; +} // namespace + +OriginsSeenService::OriginsSeenService() + : origins_seen_(kDefaultMRUCacheSize) {} + +OriginsSeenService::~OriginsSeenService() {} + +bool OriginsSeenService::Insert(const url::Origin& origin) { + bool seen = origins_seen_.Peek(origin) != origins_seen_.end(); + origins_seen_.Put(origin, true); + return seen; +}
diff --git a/chrome/browser/tab_contents/origins_seen_service.h b/chrome/browser/tab_contents/origins_seen_service.h new file mode 100644 index 0000000..55c417d --- /dev/null +++ b/chrome/browser/tab_contents/origins_seen_service.h
@@ -0,0 +1,29 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_TAB_CONTENTS_ORIGINS_SEEN_SERVICE_H_ +#define CHROME_BROWSER_TAB_CONTENTS_ORIGINS_SEEN_SERVICE_H_ + +#include "base/containers/mru_cache.h" +#include "components/keyed_service/core/keyed_service.h" +#include "url/origin.h" + +class OriginsSeenService : public KeyedService { + public: + OriginsSeenService(); + ~OriginsSeenService() override; + + // Used when deciding whether or not to record + // Navigation.SchemePerUniqueOrigin[OTR]. Inserts a copy of |origin| into the + // set |origins_seen_|, and returns whether or not |origin| was already in the + // set. + bool Insert(const url::Origin& origin); + + private: + // Used by |HaveAlreadySeenOrigin|. This cache is in volatile storage because + // Off The Record Profiles also use this Service. + base::MRUCache<url::Origin, bool> origins_seen_; +}; + +#endif // CHROME_BROWSER_TAB_CONTENTS_ORIGINS_SEEN_SERVICE_H_
diff --git a/chrome/browser/tab_contents/origins_seen_service_factory.cc b/chrome/browser/tab_contents/origins_seen_service_factory.cc new file mode 100644 index 0000000..67f00f9 --- /dev/null +++ b/chrome/browser/tab_contents/origins_seen_service_factory.cc
@@ -0,0 +1,43 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/tab_contents/origins_seen_service_factory.h" + +#include "chrome/browser/profiles/incognito_helpers.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" + +// static +OriginsSeenService* OriginsSeenServiceFactory::GetForBrowserContext( + content::BrowserContext* context) { + return static_cast<OriginsSeenService*>( + GetInstance()->GetServiceForBrowserContext(context, true)); +} + +// static +OriginsSeenServiceFactory* OriginsSeenServiceFactory::GetInstance() { + return base::Singleton<OriginsSeenServiceFactory>::get(); +} + +// static +KeyedService* OriginsSeenServiceFactory::BuildInstanceFor( + content::BrowserContext* context) { + return new OriginsSeenService(); +} + +OriginsSeenServiceFactory::OriginsSeenServiceFactory() + : BrowserContextKeyedServiceFactory( + "OriginsSeenService", + BrowserContextDependencyManager::GetInstance()) {} + +OriginsSeenServiceFactory::~OriginsSeenServiceFactory() {} + +content::BrowserContext* OriginsSeenServiceFactory::GetBrowserContextToUse( + content::BrowserContext* context) const { + return chrome::GetBrowserContextOwnInstanceInIncognito(context); +} + +KeyedService* OriginsSeenServiceFactory::BuildServiceInstanceFor( + content::BrowserContext* context) const { + return BuildInstanceFor(context); +}
diff --git a/chrome/browser/tab_contents/origins_seen_service_factory.h b/chrome/browser/tab_contents/origins_seen_service_factory.h new file mode 100644 index 0000000..6f1fab19 --- /dev/null +++ b/chrome/browser/tab_contents/origins_seen_service_factory.h
@@ -0,0 +1,37 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_TAB_CONTENTS_ORIGINS_SEEN_SERVICE_FACTORY_H_ +#define CHROME_BROWSER_TAB_CONTENTS_ORIGINS_SEEN_SERVICE_FACTORY_H_ + +#include "base/memory/singleton.h" +#include "chrome/browser/tab_contents/origins_seen_service.h" +#include "components/keyed_service/content/browser_context_keyed_service_factory.h" + +class OriginsSeenService; + +class OriginsSeenServiceFactory : public BrowserContextKeyedServiceFactory { + public: + static OriginsSeenService* GetForBrowserContext( + content::BrowserContext* context); + + static OriginsSeenServiceFactory* GetInstance(); + + // Used to create instances for testing. + static KeyedService* BuildInstanceFor(content::BrowserContext* context); + + private: + friend struct base::DefaultSingletonTraits<OriginsSeenServiceFactory>; + + OriginsSeenServiceFactory(); + ~OriginsSeenServiceFactory() override; + + // BrowserContextKeyedServiceFactory: + content::BrowserContext* GetBrowserContextToUse( + content::BrowserContext* context) const override; + KeyedService* BuildServiceInstanceFor( + content::BrowserContext* context) const override; +}; + +#endif // CHROME_BROWSER_TAB_CONTENTS_ORIGINS_SEEN_SERVICE_FACTORY_H_
diff --git a/chrome/browser/task_management/providers/arc/arc_process_task_provider.cc b/chrome/browser/task_management/providers/arc/arc_process_task_provider.cc index 5e40838..9169ef3 100644 --- a/chrome/browser/task_management/providers/arc/arc_process_task_provider.cc +++ b/chrome/browser/task_management/providers/arc/arc_process_task_provider.cc
@@ -61,7 +61,7 @@ for (const auto& it : processes) { if (nspid_to_remove.erase(it.nspid) == 0) { // New arc process. - scoped_ptr<ArcProcessTask>& task = nspid_to_task_[it.nspid]; + std::unique_ptr<ArcProcessTask>& task = nspid_to_task_[it.nspid]; // After calling NotifyObserverTaskAdded(), the raw pointer of |task| is // remebered somewhere else. One should not (implicitly) delete the // referenced object before calling NotifyObserverTaskRemoved() first
diff --git a/chrome/browser/task_management/providers/arc/arc_process_task_provider.h b/chrome/browser/task_management/providers/arc/arc_process_task_provider.h index 70c1d7d..49aea04 100644 --- a/chrome/browser/task_management/providers/arc/arc_process_task_provider.h +++ b/chrome/browser/task_management/providers/arc/arc_process_task_provider.h
@@ -6,12 +6,12 @@ #define CHROME_BROWSER_TASK_MANAGEMENT_PROVIDERS_ARC_ARC_PROCESS_TASK_PROVIDER_H_ #include <map> +#include <memory> #include <set> #include <string> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/process/process.h" #include "chrome/browser/chromeos/arc/arc_process.h" @@ -51,7 +51,7 @@ void ScheduleNextRequest(); - std::map<base::ProcessId, scoped_ptr<ArcProcessTask>> nspid_to_task_; + std::map<base::ProcessId, std::unique_ptr<ArcProcessTask>> nspid_to_task_; // Whether to continue the periodical polling. bool is_updating_;
diff --git a/chrome/browser/task_management/providers/child_process_task.h b/chrome/browser/task_management/providers/child_process_task.h index c8be4a5ec..e64be51 100644 --- a/chrome/browser/task_management/providers/child_process_task.h +++ b/chrome/browser/task_management/providers/child_process_task.h
@@ -7,8 +7,9 @@ #include <stdint.h> +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/task_management/providers/task.h" class ProcessResourceUsage; @@ -41,7 +42,7 @@ private: // The Mojo service wrapper that will provide us with the V8 memory usage of // the browser child process represented by this object. - scoped_ptr<ProcessResourceUsage> process_resources_sampler_; + std::unique_ptr<ProcessResourceUsage> process_resources_sampler_; // The allocated and used V8 memory (in bytes). int64_t v8_memory_allocated_;
diff --git a/chrome/browser/task_management/providers/child_process_task_provider.cc b/chrome/browser/task_management/providers/child_process_task_provider.cc index a6202d7..884310b 100644 --- a/chrome/browser/task_management/providers/child_process_task_provider.cc +++ b/chrome/browser/task_management/providers/child_process_task_provider.cc
@@ -22,11 +22,11 @@ // Collects and returns the child processes data on the IO thread to get all the // pre-existing child process before we start observing // |BrowserChildProcessObserver|. -scoped_ptr<std::vector<ChildProcessData>> CollectChildProcessData() { +std::unique_ptr<std::vector<ChildProcessData>> CollectChildProcessData() { // The |BrowserChildProcessHostIterator| must only be used on the IO thread. DCHECK_CURRENTLY_ON(BrowserThread::IO); - scoped_ptr<std::vector<ChildProcessData>> child_processes( + std::unique_ptr<std::vector<ChildProcessData>> child_processes( new std::vector<ChildProcessData>()); for (BrowserChildProcessHostIterator itr; !itr.Done(); ++itr) { const ChildProcessData& process_data = itr.GetData(); @@ -109,7 +109,8 @@ } void ChildProcessTaskProvider::ChildProcessDataCollected( - scoped_ptr<const std::vector<content::ChildProcessData>> child_processes) { + std::unique_ptr<const std::vector<content::ChildProcessData>> + child_processes) { DCHECK_CURRENTLY_ON(BrowserThread::UI); for (const auto& process_data : *child_processes)
diff --git a/chrome/browser/task_management/providers/child_process_task_provider.h b/chrome/browser/task_management/providers/child_process_task_provider.h index c367308..0c61b68 100644 --- a/chrome/browser/task_management/providers/child_process_task_provider.h +++ b/chrome/browser/task_management/providers/child_process_task_provider.h
@@ -6,10 +6,10 @@ #define CHROME_BROWSER_TASK_MANAGEMENT_PROVIDERS_CHILD_PROCESS_TASK_PROVIDER_H_ #include <map> +#include <memory> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/task_management/providers/task_provider.h" #include "content/public/browser/browser_child_process_observer.h" @@ -53,7 +53,8 @@ // When that is done, we will be notified on the UI thread by receiving a call // to this method. void ChildProcessDataCollected( - scoped_ptr<const std::vector<content::ChildProcessData>> child_processes); + std::unique_ptr<const std::vector<content::ChildProcessData>> + child_processes); // Creates a ChildProcessTask from the given |data| and notifies the observer // of its addition.
diff --git a/chrome/browser/task_management/providers/web_contents/extension_task.h b/chrome/browser/task_management/providers/web_contents/extension_task.h index d233352..cf7a818a 100644 --- a/chrome/browser/task_management/providers/web_contents/extension_task.h +++ b/chrome/browser/task_management/providers/web_contents/extension_task.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_TASK_MANAGEMENT_PROVIDERS_WEB_CONTENTS_EXTENSION_TASK_H_ #define CHROME_BROWSER_TASK_MANAGEMENT_PROVIDERS_WEB_CONTENTS_EXTENSION_TASK_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/task_management/providers/web_contents/renderer_task.h" #include "extensions/browser/extension_icon_image.h" #include "extensions/common/view_type.h" @@ -48,7 +49,7 @@ void LoadExtensionIcon(const extensions::Extension* extension); // The favicon of the extension represented by this task. - scoped_ptr<extensions::IconImage> extension_icon_; + std::unique_ptr<extensions::IconImage> extension_icon_; DISALLOW_COPY_AND_ASSIGN(ExtensionTask); };
diff --git a/chrome/browser/task_management/providers/web_contents/renderer_task.h b/chrome/browser/task_management/providers/web_contents/renderer_task.h index 1dac950..71693b9 100644 --- a/chrome/browser/task_management/providers/web_contents/renderer_task.h +++ b/chrome/browser/task_management/providers/web_contents/renderer_task.h
@@ -7,8 +7,9 @@ #include <stdint.h> +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/task_management/providers/task.h" #include "components/favicon/core/favicon_driver_observer.h" #include "content/public/browser/navigation_entry.h" @@ -110,7 +111,7 @@ // The Mojo service wrapper that will provide us with the V8 memory usage and // the WebCache resource stats of the render process represented by this // object. - scoped_ptr<ProcessResourceUsage> renderer_resources_sampler_; + std::unique_ptr<ProcessResourceUsage> renderer_resources_sampler_; // The unique ID of the RenderProcessHost. const int render_process_id_;
diff --git a/chrome/browser/task_management/sampling/task_group_sampler.h b/chrome/browser/task_management/sampling/task_group_sampler.h index 4b3b9450..718119e 100644 --- a/chrome/browser/task_management/sampling/task_group_sampler.h +++ b/chrome/browser/task_management/sampling/task_group_sampler.h
@@ -7,10 +7,11 @@ #include <stdint.h> +#include <memory> + #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/process/process.h" #include "base/process/process_handle.h" #include "base/process/process_metrics.h" @@ -81,7 +82,7 @@ // creating the ProcessMetrics. base::Process process_; - scoped_ptr<base::ProcessMetrics> process_metrics_; + std::unique_ptr<base::ProcessMetrics> process_metrics_; // The specific blocking pool SequencedTaskRunner that will be used to post // the refresh tasks onto serially.
diff --git a/chrome/browser/task_management/sampling/task_manager_impl.h b/chrome/browser/task_management/sampling/task_manager_impl.h index 109ab68..5dd5d2e 100644 --- a/chrome/browser/task_management/sampling/task_manager_impl.h +++ b/chrome/browser/task_management/sampling/task_manager_impl.h
@@ -133,7 +133,7 @@ // The manager of the IO thread helper used to handle network bytes // notifications on IO thread. The manager itself lives on the UI thread, but // the IO thread helper lives entirely on the IO thread. - scoped_ptr<IoThreadHelperManager> io_thread_helper_manager_; + std::unique_ptr<IoThreadHelperManager> io_thread_helper_manager_; // The list of the task providers that are owned and observed by this task // manager implementation.
diff --git a/chrome/browser/task_management/task_manager_interface.h b/chrome/browser/task_management/task_manager_interface.h index 4eccc70..b35145c 100644 --- a/chrome/browser/task_management/task_manager_interface.h +++ b/chrome/browser/task_management/task_manager_interface.h
@@ -7,10 +7,11 @@ #include <stddef.h> #include <stdint.h> + +#include <memory> #include <utility> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/observer_list.h" #include "base/process/kill.h" #include "base/process/process_handle.h" @@ -217,7 +218,7 @@ int64_t enabled_resources_flags() const { return enabled_resources_flags_; } - void set_timer_for_testing(scoped_ptr<base::Timer> timer) { + void set_timer_for_testing(std::unique_ptr<base::Timer> timer) { refresh_timer_ = std::move(timer); } @@ -242,7 +243,7 @@ base::ObserverList<TaskManagerObserver> observers_; // The timer that will be used to schedule the successive refreshes. - scoped_ptr<base::Timer> refresh_timer_; + std::unique_ptr<base::Timer> refresh_timer_; // The flags containing the enabled resources types calculations. int64_t enabled_resources_flags_;
diff --git a/chrome/browser/task_management/test_task_manager.cc b/chrome/browser/task_management/test_task_manager.cc index 5a27ab9..7626d0d 100644 --- a/chrome/browser/task_management/test_task_manager.cc +++ b/chrome/browser/task_management/test_task_manager.cc
@@ -9,8 +9,8 @@ TestTaskManager::TestTaskManager() : handle_(base::kNullProcessHandle), pid_(base::kNullProcessId) { - set_timer_for_testing(scoped_ptr<base::Timer>(new base::MockTimer(true, - true))); + set_timer_for_testing( + std::unique_ptr<base::Timer>(new base::MockTimer(true, true))); } TestTaskManager::~TestTaskManager() {
diff --git a/chrome/browser/task_manager/background_information.cc b/chrome/browser/task_manager/background_information.cc index a1b5d86..c68aa40 100644 --- a/chrome/browser/task_manager/background_information.cc +++ b/chrome/browser/task_manager/background_information.cc
@@ -143,7 +143,7 @@ } } -scoped_ptr<RendererResource> BackgroundInformation::MakeResource( +std::unique_ptr<RendererResource> BackgroundInformation::MakeResource( WebContents* web_contents) { Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); @@ -165,12 +165,12 @@ extensions_set.GetByID(base::UTF16ToUTF8(application_id)); if (extension) application_name = base::UTF8ToUTF16(extension->name()); - return scoped_ptr<RendererResource>( + return std::unique_ptr<RendererResource>( new BackgroundContentsResource(*iterator, application_name)); } } NOTREACHED(); - return scoped_ptr<RendererResource>(); + return std::unique_ptr<RendererResource>(); } } // namespace task_manager
diff --git a/chrome/browser/task_manager/background_information.h b/chrome/browser/task_manager/background_information.h index 929eb7df..1de6fe5 100644 --- a/chrome/browser/task_manager/background_information.h +++ b/chrome/browser/task_manager/background_information.h
@@ -20,7 +20,7 @@ // WebContentsInformation implementation. bool CheckOwnership(content::WebContents* web_contents) override; void GetAll(const NewWebContentsCallback& callback) override; - scoped_ptr<RendererResource> MakeResource( + std::unique_ptr<RendererResource> MakeResource( content::WebContents* web_contents) override; private:
diff --git a/chrome/browser/task_manager/child_process_resource_provider.cc b/chrome/browser/task_manager/child_process_resource_provider.cc index 5f37428e..b9d28890 100644 --- a/chrome/browser/task_manager/child_process_resource_provider.cc +++ b/chrome/browser/task_manager/child_process_resource_provider.cc
@@ -74,7 +74,7 @@ int unique_process_id_; mutable base::string16 title_; bool network_usage_support_; - scoped_ptr<ProcessResourceUsage> resource_usage_; + std::unique_ptr<ProcessResourceUsage> resource_usage_; // The icon painted for the child processs. // TODO(jcampan): we should have plugin specific icons for well-known
diff --git a/chrome/browser/task_manager/extension_information.cc b/chrome/browser/task_manager/extension_information.cc index 66e39d02..06eeac5 100644 --- a/chrome/browser/task_manager/extension_information.cc +++ b/chrome/browser/task_manager/extension_information.cc
@@ -159,14 +159,14 @@ view_type != extensions::VIEW_TYPE_PANEL); } -scoped_ptr<RendererResource> ExtensionInformation::MakeResource( +std::unique_ptr<RendererResource> ExtensionInformation::MakeResource( WebContents* web_contents) { const Extension* extension = GetExtensionForWebContents(web_contents); if (!extension) { NOTREACHED(); - return scoped_ptr<RendererResource>(); + return std::unique_ptr<RendererResource>(); } - return scoped_ptr<RendererResource>(new ExtensionProcessResource( + return std::unique_ptr<RendererResource>(new ExtensionProcessResource( extension, web_contents->GetRenderViewHost())); }
diff --git a/chrome/browser/task_manager/extension_information.h b/chrome/browser/task_manager/extension_information.h index fc2e768..c186825 100644 --- a/chrome/browser/task_manager/extension_information.h +++ b/chrome/browser/task_manager/extension_information.h
@@ -23,7 +23,7 @@ // WebContentsInformation implementation. bool CheckOwnership(content::WebContents* web_contents) override; void GetAll(const NewWebContentsCallback& callback) override; - scoped_ptr<RendererResource> MakeResource( + std::unique_ptr<RendererResource> MakeResource( content::WebContents* web_contents) override; private:
diff --git a/chrome/browser/task_manager/guest_information.cc b/chrome/browser/task_manager/guest_information.cc index 6299c66..ad0cbd3 100644 --- a/chrome/browser/task_manager/guest_information.cc +++ b/chrome/browser/task_manager/guest_information.cc
@@ -106,7 +106,7 @@ } void GuestInformation::GetAll(const NewWebContentsCallback& callback) { - scoped_ptr<content::RenderWidgetHostIterator> widgets( + std::unique_ptr<content::RenderWidgetHostIterator> widgets( content::RenderWidgetHost::GetRenderWidgetHosts()); while (content::RenderWidgetHost* widget = widgets->GetNextHost()) { content::RenderViewHost* rvh = content::RenderViewHost::From(widget); @@ -116,9 +116,9 @@ } } -scoped_ptr<RendererResource> GuestInformation::MakeResource( +std::unique_ptr<RendererResource> GuestInformation::MakeResource( WebContents* web_contents) { - return scoped_ptr<RendererResource>( + return std::unique_ptr<RendererResource>( new GuestResource(web_contents->GetRenderViewHost())); }
diff --git a/chrome/browser/task_manager/guest_information.h b/chrome/browser/task_manager/guest_information.h index 0d47cdf..01c5737 100644 --- a/chrome/browser/task_manager/guest_information.h +++ b/chrome/browser/task_manager/guest_information.h
@@ -21,7 +21,7 @@ // WebContentsInformation implementation. bool CheckOwnership(content::WebContents* web_contents) override; void GetAll(const NewWebContentsCallback& callback) override; - scoped_ptr<RendererResource> MakeResource( + std::unique_ptr<RendererResource> MakeResource( content::WebContents* web_contents) override; private:
diff --git a/chrome/browser/task_manager/panel_information.cc b/chrome/browser/task_manager/panel_information.cc index 262c842..3711ca0 100644 --- a/chrome/browser/task_manager/panel_information.cc +++ b/chrome/browser/task_manager/panel_information.cc
@@ -123,16 +123,16 @@ callback.Run(panels[i]->GetWebContents()); } -scoped_ptr<RendererResource> PanelInformation::MakeResource( +std::unique_ptr<RendererResource> PanelInformation::MakeResource( WebContents* web_contents) { std::vector<Panel*> panels = PanelManager::GetInstance()->panels(); for (size_t i = 0; i < panels.size(); ++i) { if (panels[i]->GetWebContents() == web_contents) { - return scoped_ptr<RendererResource>(new PanelResource(panels[i])); + return std::unique_ptr<RendererResource>(new PanelResource(panels[i])); } } NOTREACHED(); - return scoped_ptr<RendererResource>(); + return std::unique_ptr<RendererResource>(); } } // namespace task_manager
diff --git a/chrome/browser/task_manager/panel_information.h b/chrome/browser/task_manager/panel_information.h index 38b4f26..d17274ec 100644 --- a/chrome/browser/task_manager/panel_information.h +++ b/chrome/browser/task_manager/panel_information.h
@@ -21,7 +21,7 @@ // WebContentsInformation implementation. bool CheckOwnership(content::WebContents* web_contents) override; void GetAll(const NewWebContentsCallback& callback) override; - scoped_ptr<RendererResource> MakeResource( + std::unique_ptr<RendererResource> MakeResource( content::WebContents* web_contents) override; private:
diff --git a/chrome/browser/task_manager/printing_information.cc b/chrome/browser/task_manager/printing_information.cc index 01fb7f90..4256e4e 100644 --- a/chrome/browser/task_manager/printing_information.cc +++ b/chrome/browser/task_manager/printing_information.cc
@@ -109,9 +109,9 @@ callback); } -scoped_ptr<RendererResource> PrintingInformation::MakeResource( +std::unique_ptr<RendererResource> PrintingInformation::MakeResource( WebContents* web_contents) { - return scoped_ptr<RendererResource>(new PrintingResource(web_contents)); + return std::unique_ptr<RendererResource>(new PrintingResource(web_contents)); } } // namespace task_manager
diff --git a/chrome/browser/task_manager/printing_information.h b/chrome/browser/task_manager/printing_information.h index 41b58fe7..a520cc8 100644 --- a/chrome/browser/task_manager/printing_information.h +++ b/chrome/browser/task_manager/printing_information.h
@@ -23,7 +23,7 @@ bool CheckOwnership(content::WebContents* web_contents) override; void GetAll(const NewWebContentsCallback& callback) override; - scoped_ptr<RendererResource> MakeResource( + std::unique_ptr<RendererResource> MakeResource( content::WebContents* web_contents) override; private:
diff --git a/chrome/browser/task_manager/renderer_resource.h b/chrome/browser/task_manager/renderer_resource.h index 8c3ee00..e2de894 100644 --- a/chrome/browser/task_manager/renderer_resource.h +++ b/chrome/browser/task_manager/renderer_resource.h
@@ -7,8 +7,9 @@ #include <stddef.h> +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/task_manager/resource_provider.h" class ProcessResourceUsage; @@ -57,7 +58,7 @@ // RenderViewHost we use to fetch stats. content::RenderViewHost* render_view_host_; - scoped_ptr<ProcessResourceUsage> process_resource_usage_; + std::unique_ptr<ProcessResourceUsage> process_resource_usage_; DISALLOW_COPY_AND_ASSIGN(RendererResource); };
diff --git a/chrome/browser/task_manager/tab_contents_information.cc b/chrome/browser/task_manager/tab_contents_information.cc index 90700e4..757d4a2 100644 --- a/chrome/browser/task_manager/tab_contents_information.cc +++ b/chrome/browser/task_manager/tab_contents_information.cc
@@ -173,9 +173,10 @@ } } -scoped_ptr<RendererResource> TabContentsInformation::MakeResource( +std::unique_ptr<RendererResource> TabContentsInformation::MakeResource( content::WebContents* web_contents) { - return scoped_ptr<RendererResource>(new TabContentsResource(web_contents)); + return std::unique_ptr<RendererResource>( + new TabContentsResource(web_contents)); } } // namespace task_manager
diff --git a/chrome/browser/task_manager/tab_contents_information.h b/chrome/browser/task_manager/tab_contents_information.h index fefc8ad..c616a4e 100644 --- a/chrome/browser/task_manager/tab_contents_information.h +++ b/chrome/browser/task_manager/tab_contents_information.h
@@ -23,7 +23,7 @@ // WebContentsInformation implementation. bool CheckOwnership(content::WebContents* web_contents) override; void GetAll(const NewWebContentsCallback& callback) override; - scoped_ptr<RendererResource> MakeResource( + std::unique_ptr<RendererResource> MakeResource( content::WebContents* web_contents) override; private:
diff --git a/chrome/browser/task_manager/task_manager.cc b/chrome/browser/task_manager/task_manager.cc index f179f70..aac1308 100644 --- a/chrome/browser/task_manager/task_manager.cc +++ b/chrome/browser/task_manager/task_manager.cc
@@ -257,33 +257,27 @@ AddResourceProvider( new task_manager::BrowserProcessResourceProvider(task_manager)); AddResourceProvider(new task_manager::WebContentsResourceProvider( - task_manager, - scoped_ptr<WebContentsInformation>( - new task_manager::BackgroundInformation()))); + task_manager, std::unique_ptr<WebContentsInformation>( + new task_manager::BackgroundInformation()))); AddResourceProvider(new task_manager::WebContentsResourceProvider( - task_manager, - scoped_ptr<WebContentsInformation>( - new task_manager::TabContentsInformation()))); + task_manager, std::unique_ptr<WebContentsInformation>( + new task_manager::TabContentsInformation()))); #if defined(ENABLE_PRINT_PREVIEW) AddResourceProvider(new task_manager::WebContentsResourceProvider( - task_manager, - scoped_ptr<WebContentsInformation>( - new task_manager::PrintingInformation()))); + task_manager, std::unique_ptr<WebContentsInformation>( + new task_manager::PrintingInformation()))); #endif // ENABLE_PRINT_PREVIEW AddResourceProvider(new task_manager::WebContentsResourceProvider( - task_manager, - scoped_ptr<WebContentsInformation>( - new task_manager::PanelInformation()))); + task_manager, std::unique_ptr<WebContentsInformation>( + new task_manager::PanelInformation()))); AddResourceProvider( new task_manager::ChildProcessResourceProvider(task_manager)); AddResourceProvider(new task_manager::WebContentsResourceProvider( - task_manager, - scoped_ptr<WebContentsInformation>( - new task_manager::ExtensionInformation()))); + task_manager, std::unique_ptr<WebContentsInformation>( + new task_manager::ExtensionInformation()))); AddResourceProvider(new task_manager::WebContentsResourceProvider( - task_manager, - scoped_ptr<WebContentsInformation>( - new task_manager::GuestInformation()))); + task_manager, std::unique_ptr<WebContentsInformation>( + new task_manager::GuestInformation()))); #if defined(OS_WIN) working_set_snapshot_.reset(new PrivateWorkingSetSnapshot); working_set_snapshot_->AddToMonitorList("chrome");
diff --git a/chrome/browser/task_manager/task_manager.h b/chrome/browser/task_manager/task_manager.h index 71c0257..a8178cb1 100644 --- a/chrome/browser/task_manager/task_manager.h +++ b/chrome/browser/task_manager/task_manager.h
@@ -9,13 +9,13 @@ #include <stdint.h> #include <map> +#include <memory> #include <vector> #include "base/callback_forward.h" #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/observer_list.h" #include "base/strings/string16.h" @@ -516,7 +516,7 @@ // An observer waiting for video memory usage stats updates from the GPU // process - scoped_ptr<TaskManagerModelGpuDataManagerObserver> + std::unique_ptr<TaskManagerModelGpuDataManagerObserver> video_memory_usage_stats_observer_; base::ObserverList<TaskManagerModelObserver> observer_list_; @@ -543,7 +543,7 @@ std::vector<base::Closure> on_data_ready_callbacks_; #if defined(OS_WIN) - scoped_ptr<PrivateWorkingSetSnapshot> working_set_snapshot_; + std::unique_ptr<PrivateWorkingSetSnapshot> working_set_snapshot_; #endif // All per-Resource values are stored here.
diff --git a/chrome/browser/task_manager/web_contents_information.h b/chrome/browser/task_manager/web_contents_information.h index a1fcdc1..cfa5076 100644 --- a/chrome/browser/task_manager/web_contents_information.h +++ b/chrome/browser/task_manager/web_contents_information.h
@@ -5,9 +5,10 @@ #ifndef CHROME_BROWSER_TASK_MANAGER_WEB_CONTENTS_INFORMATION_H_ #define CHROME_BROWSER_TASK_MANAGER_WEB_CONTENTS_INFORMATION_H_ +#include <memory> + #include "base/callback.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" @@ -46,7 +47,7 @@ virtual void StopObservingCreation() = 0; // Create a new task manager resource for the given WebContents instance. - virtual scoped_ptr<RendererResource> MakeResource( + virtual std::unique_ptr<RendererResource> MakeResource( content::WebContents* web_contents) = 0; private:
diff --git a/chrome/browser/task_manager/web_contents_resource_provider.cc b/chrome/browser/task_manager/web_contents_resource_provider.cc index e19a8aa..5b3b3cb 100644 --- a/chrome/browser/task_manager/web_contents_resource_provider.cc +++ b/chrome/browser/task_manager/web_contents_resource_provider.cc
@@ -235,7 +235,7 @@ (existing_resource_range.first != existing_resource_range.second); bool is_main_frame = (render_frame_host == web_contents()->GetMainFrame()); bool site_instance_is_main = (site_instance == main_frame_site_instance_); - scoped_ptr<RendererResource> new_resource; + std::unique_ptr<RendererResource> new_resource; if (!existing_resource || (is_main_frame && !site_instance_is_main)) { if (is_main_frame) { new_resource = info()->MakeResource(web_contents()); @@ -326,7 +326,7 @@ WebContentsResourceProvider::WebContentsResourceProvider( TaskManager* task_manager, - scoped_ptr<WebContentsInformation> info) + std::unique_ptr<WebContentsInformation> info) : task_manager_(task_manager), info_(std::move(info)) {} WebContentsResourceProvider::~WebContentsResourceProvider() {} @@ -384,7 +384,7 @@ // are already observing this WebContents and just ignore it. return; } - scoped_ptr<TaskManagerWebContentsEntry> entry( + std::unique_ptr<TaskManagerWebContentsEntry> entry( new TaskManagerWebContentsEntry(web_contents, this)); entry->CreateAllResources(); entries_[web_contents] = entry.release();
diff --git a/chrome/browser/task_manager/web_contents_resource_provider.h b/chrome/browser/task_manager/web_contents_resource_provider.h index ea0e262a..4956511 100644 --- a/chrome/browser/task_manager/web_contents_resource_provider.h +++ b/chrome/browser/task_manager/web_contents_resource_provider.h
@@ -6,9 +6,9 @@ #define CHROME_BROWSER_TASK_MANAGER_WEB_CONTENTS_RESOURCE_PROVIDER_H_ #include <map> +#include <memory> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/task_manager/renderer_resource.h" #include "chrome/browser/task_manager/resource_provider.h" @@ -35,7 +35,7 @@ class WebContentsResourceProvider : public ResourceProvider { public: WebContentsResourceProvider(TaskManager* task_manager, - scoped_ptr<WebContentsInformation> info); + std::unique_ptr<WebContentsInformation> info); // ResourceProvider implementation. RendererResource* GetResource(int origin_pid, @@ -71,7 +71,7 @@ // The WebContentsInformation that informs us when a new WebContents* is // created, and which serves as a RendererResource factory for our type. - scoped_ptr<WebContentsInformation> info_; + std::unique_ptr<WebContentsInformation> info_; DISALLOW_COPY_AND_ASSIGN(WebContentsResourceProvider); };
diff --git a/chrome/browser/task_profiler/task_profiler_data_serializer.cc b/chrome/browser/task_profiler/task_profiler_data_serializer.cc index 34d9ed0..c9f3b5e 100644 --- a/chrome/browser/task_profiler/task_profiler_data_serializer.cc +++ b/chrome/browser/task_profiler/task_profiler_data_serializer.cc
@@ -4,10 +4,11 @@ #include "chrome/browser/task_profiler/task_profiler_data_serializer.h" +#include <memory> + #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/json/json_string_value_serializer.h" -#include "base/memory/scoped_ptr.h" #include "base/time/time.h" #include "base/tracked_objects.h" #include "chrome/common/chrome_content_client.h" @@ -44,7 +45,8 @@ base::DictionaryValue* dictionary) { DCHECK(!prefix.empty()); - scoped_ptr<base::DictionaryValue> location_value(new base::DictionaryValue); + std::unique_ptr<base::DictionaryValue> location_value( + new base::DictionaryValue); LocationSnapshotToValue(birth.location, location_value.get()); dictionary->Set(prefix + "_location", location_value.release()); @@ -68,7 +70,7 @@ base::DictionaryValue* dictionary) { BirthOnThreadSnapshotToValue(snapshot.birth, "birth", dictionary); - scoped_ptr<base::DictionaryValue> death_data(new base::DictionaryValue); + std::unique_ptr<base::DictionaryValue> death_data(new base::DictionaryValue); DeathDataSnapshotToValue(snapshot.death_data, death_data.get()); dictionary->Set("death_data", death_data.release()); @@ -120,9 +122,9 @@ base::ProcessId process_id, metrics::ProfilerEventProto::TrackedObject::ProcessType process_type, base::DictionaryValue* dictionary) { - scoped_ptr<base::ListValue> tasks_list(new base::ListValue); + std::unique_ptr<base::ListValue> tasks_list(new base::ListValue); for (const auto& task : process_data_phase.tasks) { - scoped_ptr<base::DictionaryValue> snapshot(new base::DictionaryValue); + std::unique_ptr<base::DictionaryValue> snapshot(new base::DictionaryValue); TaskSnapshotToValue(task, snapshot.get()); tasks_list->Append(snapshot.release()); }
diff --git a/chrome/browser/themes/browser_theme_pack.cc b/chrome/browser/themes/browser_theme_pack.cc index 7741d5a6..61301e2 100644 --- a/chrome/browser/themes/browser_theme_pack.cc +++ b/chrome/browser/themes/browser_theme_pack.cc
@@ -8,11 +8,11 @@ #include <stddef.h> #include <limits> +#include <memory> #include "base/files/file.h" #include "base/macros.h" #include "base/memory/ref_counted_memory.h" -#include "base/memory/scoped_ptr.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" @@ -229,7 +229,7 @@ size_t scales_size = static_cast<size_t>(input.size() / sizeof(float)); if (scales_size != expected.size()) return false; - scoped_ptr<float[]> scales(new float[scales_size]); + std::unique_ptr<float[]> scales(new float[scales_size]); // Do a memcpy to avoid misaligned memory access. memcpy(scales.get(), input.data(), input.size()); for (size_t index = 0; index < scales_size; ++index) { @@ -242,7 +242,7 @@ // Returns |scale_factors| as a string to be written to disk. std::string GetScaleFactorsAsString( const std::vector<ui::ScaleFactor>& scale_factors) { - scoped_ptr<float[]> scales(new float[scale_factors.size()]); + std::unique_ptr<float[]> scales(new float[scale_factors.size()]); for (size_t i = 0; i < scale_factors.size(); ++i) scales[i] = ui::GetScaleForScaleFactor(scale_factors[i]); std::string out_string = std::string(
diff --git a/chrome/browser/themes/browser_theme_pack.h b/chrome/browser/themes/browser_theme_pack.h index b7f567eb..5d5d092 100644 --- a/chrome/browser/themes/browser_theme_pack.h +++ b/chrome/browser/themes/browser_theme_pack.h
@@ -8,11 +8,11 @@ #include <stdint.h> #include <map> +#include <memory> #include <string> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/sequenced_task_runner_helpers.h" #include "chrome/browser/themes/custom_theme_supplier.h" #include "extensions/common/extension.h" @@ -211,7 +211,7 @@ void GenerateRawImageForAllSupportedScales(int prs_id); // Data pack, if we have one. - scoped_ptr<ui::DataPack> data_pack_; + std::unique_ptr<ui::DataPack> data_pack_; // All structs written to disk need to be packed; no alignment tricks here, // please.
diff --git a/chrome/browser/themes/browser_theme_pack_unittest.cc b/chrome/browser/themes/browser_theme_pack_unittest.cc index f80f50e..c79c6c2 100644 --- a/chrome/browser/themes/browser_theme_pack_unittest.cc +++ b/chrome/browser/themes/browser_theme_pack_unittest.cc
@@ -98,7 +98,7 @@ } void LoadColorJSON(const std::string& json) { - scoped_ptr<base::Value> value = base::JSONReader::Read(json); + std::unique_ptr<base::Value> value = base::JSONReader::Read(json); ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY)); LoadColorDictionary(static_cast<base::DictionaryValue*>(value.get())); } @@ -108,7 +108,7 @@ } void LoadTintJSON(const std::string& json) { - scoped_ptr<base::Value> value = base::JSONReader::Read(json); + std::unique_ptr<base::Value> value = base::JSONReader::Read(json); ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY)); LoadTintDictionary(static_cast<base::DictionaryValue*>(value.get())); } @@ -118,7 +118,7 @@ } void LoadDisplayPropertiesJSON(const std::string& json) { - scoped_ptr<base::Value> value = base::JSONReader::Read(json); + std::unique_ptr<base::Value> value = base::JSONReader::Read(json); ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY)); LoadDisplayPropertiesDictionary( static_cast<base::DictionaryValue*>(value.get())); @@ -130,7 +130,7 @@ void ParseImageNamesJSON(const std::string& json, TestFilePathMap* out_file_paths) { - scoped_ptr<base::Value> value = base::JSONReader::Read(json); + std::unique_ptr<base::Value> value = base::JSONReader::Read(json); ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY)); ParseImageNamesDictionary(static_cast<base::DictionaryValue*>(value.get()), out_file_paths); @@ -159,7 +159,7 @@ extension_path.AppendASCII("manifest.json"); std::string error; JSONFileValueDeserializer deserializer(manifest_path); - scoped_ptr<base::DictionaryValue> valid_value = + std::unique_ptr<base::DictionaryValue> valid_value = base::DictionaryValue::From(deserializer.Deserialize(NULL, &error)); EXPECT_EQ("", error); ASSERT_TRUE(valid_value.get()); @@ -364,7 +364,7 @@ content::TestBrowserThread fake_ui_thread; content::TestBrowserThread fake_file_thread; - typedef scoped_ptr<ui::test::ScopedSetSupportedScaleFactors> + typedef std::unique_ptr<ui::test::ScopedSetSupportedScaleFactors> ScopedSetSupportedScaleFactors; ScopedSetSupportedScaleFactors scoped_set_supported_scale_factors_; scoped_refptr<BrowserThemePack> theme_pack_;
diff --git a/chrome/browser/themes/theme_properties.cc b/chrome/browser/themes/theme_properties.cc index 8d5a8ef..9bcb6419 100644 --- a/chrome/browser/themes/theme_properties.cc +++ b/chrome/browser/themes/theme_properties.cc
@@ -4,8 +4,9 @@ #include "chrome/browser/themes/theme_properties.h" +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "build/build_config.h"
diff --git a/chrome/browser/themes/theme_service.cc b/chrome/browser/themes/theme_service.cc index a8be088..11e8f17 100644 --- a/chrome/browser/themes/theme_service.cc +++ b/chrome/browser/themes/theme_service.cc
@@ -355,7 +355,7 @@ std::string current_theme = GetThemeID(); std::vector<std::string> remove_list; - scoped_ptr<const extensions::ExtensionSet> extensions( + std::unique_ptr<const extensions::ExtensionSet> extensions( extensions::ExtensionRegistry::Get(profile_) ->GenerateInstalledExtensionsSet()); extensions::ExtensionPrefs* prefs = extensions::ExtensionPrefs::Get(profile_);
diff --git a/chrome/browser/themes/theme_service.h b/chrome/browser/themes/theme_service.h index 1916389..d8e0226 100644 --- a/chrome/browser/themes/theme_service.h +++ b/chrome/browser/themes/theme_service.h
@@ -6,6 +6,7 @@ #define CHROME_BROWSER_THEMES_THEME_SERVICE_H_ #include <map> +#include <memory> #include <set> #include <string> #include <utility> @@ -13,7 +14,6 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/threading/non_thread_safe.h" #include "build/build_config.h" @@ -315,11 +315,11 @@ content::NotificationRegistrar registrar_; - scoped_ptr<ThemeSyncableService> theme_syncable_service_; + std::unique_ptr<ThemeSyncableService> theme_syncable_service_; #if defined(ENABLE_EXTENSIONS) class ThemeObserver; - scoped_ptr<ThemeObserver> theme_observer_; + std::unique_ptr<ThemeObserver> theme_observer_; #endif BrowserThemeProvider original_theme_provider_;
diff --git a/chrome/browser/themes/theme_service_win.h b/chrome/browser/themes/theme_service_win.h index 0f0473d..a702f38 100644 --- a/chrome/browser/themes/theme_service_win.h +++ b/chrome/browser/themes/theme_service_win.h
@@ -28,7 +28,7 @@ // Registry key containing the params that determine the DWM frame color. // This is only initialized on Windows 10. - scoped_ptr<base::win::RegKey> dwm_key_; + std::unique_ptr<base::win::RegKey> dwm_key_; // The DWM frame color, if available; white otherwise. SkColor dwm_frame_color_;
diff --git a/chrome/browser/themes/theme_syncable_service.cc b/chrome/browser/themes/theme_syncable_service.cc index 1bbaaae..79b0e27 100644 --- a/chrome/browser/themes/theme_syncable_service.cc +++ b/chrome/browser/themes/theme_syncable_service.cc
@@ -59,8 +59,8 @@ syncer::SyncMergeResult ThemeSyncableService::MergeDataAndStartSyncing( syncer::ModelType type, const syncer::SyncDataList& initial_sync_data, - scoped_ptr<syncer::SyncChangeProcessor> sync_processor, - scoped_ptr<syncer::SyncErrorFactory> error_handler) { + std::unique_ptr<syncer::SyncChangeProcessor> sync_processor, + std::unique_ptr<syncer::SyncErrorFactory> error_handler) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!sync_processor_.get()); DCHECK(sync_processor.get());
diff --git a/chrome/browser/themes/theme_syncable_service.h b/chrome/browser/themes/theme_syncable_service.h index f2ead919..8b94e372 100644 --- a/chrome/browser/themes/theme_syncable_service.h +++ b/chrome/browser/themes/theme_syncable_service.h
@@ -5,9 +5,10 @@ #ifndef CHROME_BROWSER_THEMES_THEME_SYNCABLE_SERVICE_H_ #define CHROME_BROWSER_THEMES_THEME_SYNCABLE_SERVICE_H_ +#include <memory> + #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/threading/thread_checker.h" #include "sync/api/sync_change.h" #include "sync/api/sync_data.h" @@ -38,8 +39,8 @@ syncer::SyncMergeResult MergeDataAndStartSyncing( syncer::ModelType type, const syncer::SyncDataList& initial_sync_data, - scoped_ptr<syncer::SyncChangeProcessor> sync_processor, - scoped_ptr<syncer::SyncErrorFactory> error_handler) override; + std::unique_ptr<syncer::SyncChangeProcessor> sync_processor, + std::unique_ptr<syncer::SyncErrorFactory> error_handler) override; void StopSyncing(syncer::ModelType type) override; syncer::SyncDataList GetAllSyncData(syncer::ModelType type) const override; syncer::SyncError ProcessSyncChanges( @@ -78,8 +79,8 @@ Profile* const profile_; ThemeService* const theme_service_; - scoped_ptr<syncer::SyncChangeProcessor> sync_processor_; - scoped_ptr<syncer::SyncErrorFactory> sync_error_handler_; + std::unique_ptr<syncer::SyncChangeProcessor> sync_processor_; + std::unique_ptr<syncer::SyncErrorFactory> sync_error_handler_; // Persist use_system_theme_by_default for platforms that use it, even if // we're not on one.
diff --git a/chrome/browser/themes/theme_syncable_service_unittest.cc b/chrome/browser/themes/theme_syncable_service_unittest.cc index cab0fc95..e8714d9 100644 --- a/chrome/browser/themes/theme_syncable_service_unittest.cc +++ b/chrome/browser/themes/theme_syncable_service_unittest.cc
@@ -4,10 +4,12 @@ #include "chrome/browser/themes/theme_syncable_service.h" +#include <memory> + #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/time/time.h" #include "build/build_config.h" #include "chrome/browser/extensions/extension_service.h" @@ -125,9 +127,9 @@ bool is_dirty_; }; -scoped_ptr<KeyedService> BuildMockThemeService( +std::unique_ptr<KeyedService> BuildMockThemeService( content::BrowserContext* profile) { - return make_scoped_ptr(new FakeThemeService); + return base::WrapUnique(new FakeThemeService); } scoped_refptr<extensions::Extension> MakeThemeExtension( @@ -240,11 +242,11 @@ chromeos::ScopedTestUserManager test_user_manager_; #endif - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<TestingProfile> profile_; FakeThemeService* fake_theme_service_; scoped_refptr<extensions::Extension> theme_extension_; - scoped_ptr<ThemeSyncableService> theme_sync_service_; - scoped_ptr<syncer::FakeSyncChangeProcessor> fake_change_processor_; + std::unique_ptr<ThemeSyncableService> theme_sync_service_; + std::unique_ptr<syncer::FakeSyncChangeProcessor> fake_change_processor_; }; class PolicyInstalledThemeTest : public ThemeSyncableServiceTest { @@ -309,13 +311,12 @@ syncer::SyncError error = theme_sync_service_ ->MergeDataAndStartSyncing( - syncer::THEMES, - MakeThemeDataList(sync_pb::ThemeSpecifics()), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::SyncChangeProcessorWrapperForTest( - fake_change_processor_.get())), - scoped_ptr<syncer::SyncErrorFactory>( - new syncer::SyncErrorFactoryMock())) + syncer::THEMES, MakeThemeDataList(sync_pb::ThemeSpecifics()), + std::unique_ptr<syncer::SyncChangeProcessor>( + new syncer::SyncChangeProcessorWrapperForTest( + fake_change_processor_.get())), + std::unique_ptr<syncer::SyncErrorFactory>( + new syncer::SyncErrorFactoryMock())) .error(); EXPECT_FALSE(error.IsSet()) << error.message(); EXPECT_FALSE(fake_theme_service_->UsingDefaultTheme()); @@ -331,13 +332,12 @@ syncer::SyncError error = theme_sync_service_ ->MergeDataAndStartSyncing( - syncer::THEMES, - MakeThemeDataList(theme_specifics), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::SyncChangeProcessorWrapperForTest( - fake_change_processor_.get())), - scoped_ptr<syncer::SyncErrorFactory>( - new syncer::SyncErrorFactoryMock())) + syncer::THEMES, MakeThemeDataList(theme_specifics), + std::unique_ptr<syncer::SyncChangeProcessor>( + new syncer::SyncChangeProcessorWrapperForTest( + fake_change_processor_.get())), + std::unique_ptr<syncer::SyncErrorFactory>( + new syncer::SyncErrorFactoryMock())) .error(); EXPECT_FALSE(error.IsSet()) << error.message(); EXPECT_FALSE(fake_theme_service_->UsingSystemTheme()); @@ -356,13 +356,12 @@ syncer::SyncError error = theme_sync_service_ ->MergeDataAndStartSyncing( - syncer::THEMES, - MakeThemeDataList(theme_specifics), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::SyncChangeProcessorWrapperForTest( - fake_change_processor_.get())), - scoped_ptr<syncer::SyncErrorFactory>( - new syncer::SyncErrorFactoryMock())) + syncer::THEMES, MakeThemeDataList(theme_specifics), + std::unique_ptr<syncer::SyncChangeProcessor>( + new syncer::SyncChangeProcessorWrapperForTest( + fake_change_processor_.get())), + std::unique_ptr<syncer::SyncErrorFactory>( + new syncer::SyncErrorFactoryMock())) .error(); EXPECT_FALSE(error.IsSet()) << error.message(); EXPECT_EQ(fake_theme_service_->theme_extension(), theme_extension_.get()); @@ -375,13 +374,12 @@ syncer::SyncError error = theme_sync_service_ ->MergeDataAndStartSyncing( - syncer::THEMES, - MakeThemeDataList(sync_pb::ThemeSpecifics()), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::SyncChangeProcessorWrapperForTest( - fake_change_processor_.get())), - scoped_ptr<syncer::SyncErrorFactory>( - new syncer::SyncErrorFactoryMock())) + syncer::THEMES, MakeThemeDataList(sync_pb::ThemeSpecifics()), + std::unique_ptr<syncer::SyncChangeProcessor>( + new syncer::SyncChangeProcessorWrapperForTest( + fake_change_processor_.get())), + std::unique_ptr<syncer::SyncErrorFactory>( + new syncer::SyncErrorFactoryMock())) .error(); EXPECT_FALSE(error.IsSet()) << error.message(); EXPECT_FALSE(fake_theme_service_->is_dirty()); @@ -394,13 +392,12 @@ syncer::SyncError error = theme_sync_service_ ->MergeDataAndStartSyncing( - syncer::THEMES, - syncer::SyncDataList(), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::SyncChangeProcessorWrapperForTest( - fake_change_processor_.get())), - scoped_ptr<syncer::SyncErrorFactory>( - new syncer::SyncErrorFactoryMock())) + syncer::THEMES, syncer::SyncDataList(), + std::unique_ptr<syncer::SyncChangeProcessor>( + new syncer::SyncChangeProcessorWrapperForTest( + fake_change_processor_.get())), + std::unique_ptr<syncer::SyncErrorFactory>( + new syncer::SyncErrorFactoryMock())) .error(); EXPECT_FALSE(error.IsSet()) << error.message(); const syncer::SyncChangeList& changes = fake_change_processor_->changes(); @@ -446,13 +443,12 @@ syncer::SyncError error = theme_sync_service_ ->MergeDataAndStartSyncing( - syncer::THEMES, - MakeThemeDataList(sync_pb::ThemeSpecifics()), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::SyncChangeProcessorWrapperForTest( - fake_change_processor_.get())), - scoped_ptr<syncer::SyncErrorFactory>( - new syncer::SyncErrorFactoryMock())) + syncer::THEMES, MakeThemeDataList(sync_pb::ThemeSpecifics()), + std::unique_ptr<syncer::SyncChangeProcessor>( + new syncer::SyncChangeProcessorWrapperForTest( + fake_change_processor_.get())), + std::unique_ptr<syncer::SyncErrorFactory>( + new syncer::SyncErrorFactoryMock())) .error(); EXPECT_FALSE(error.IsSet()) << error.message(); // Don't expect theme change initially because specifics are equal. @@ -489,13 +485,12 @@ syncer::SyncError error = theme_sync_service_ ->MergeDataAndStartSyncing( - syncer::THEMES, - MakeThemeDataList(sync_pb::ThemeSpecifics()), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::SyncChangeProcessorWrapperForTest( - fake_change_processor_.get())), - scoped_ptr<syncer::SyncErrorFactory>( - new syncer::SyncErrorFactoryMock())) + syncer::THEMES, MakeThemeDataList(sync_pb::ThemeSpecifics()), + std::unique_ptr<syncer::SyncChangeProcessor>( + new syncer::SyncChangeProcessorWrapperForTest( + fake_change_processor_.get())), + std::unique_ptr<syncer::SyncErrorFactory>( + new syncer::SyncErrorFactoryMock())) .error(); EXPECT_FALSE(error.IsSet()) << error.message(); const syncer::SyncChangeList& changes = fake_change_processor_->changes(); @@ -523,13 +518,12 @@ syncer::SyncError error = theme_sync_service_ ->MergeDataAndStartSyncing( - syncer::THEMES, - MakeThemeDataList(sync_pb::ThemeSpecifics()), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::SyncChangeProcessorWrapperForTest( - fake_change_processor_.get())), - scoped_ptr<syncer::SyncErrorFactory>( - new syncer::SyncErrorFactoryMock())) + syncer::THEMES, MakeThemeDataList(sync_pb::ThemeSpecifics()), + std::unique_ptr<syncer::SyncChangeProcessor>( + new syncer::SyncChangeProcessorWrapperForTest( + fake_change_processor_.get())), + std::unique_ptr<syncer::SyncErrorFactory>( + new syncer::SyncErrorFactoryMock())) .error(); EXPECT_FALSE(error.IsSet()) << error.message(); const syncer::SyncChangeList& changes = fake_change_processor_->changes(); @@ -559,13 +553,12 @@ syncer::SyncError error = theme_sync_service_ ->MergeDataAndStartSyncing( - syncer::THEMES, - MakeThemeDataList(theme_specifics), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::SyncChangeProcessorWrapperForTest( - fake_change_processor_.get())), - scoped_ptr<syncer::SyncErrorFactory>( - new syncer::SyncErrorFactoryMock())) + syncer::THEMES, MakeThemeDataList(theme_specifics), + std::unique_ptr<syncer::SyncChangeProcessor>( + new syncer::SyncChangeProcessorWrapperForTest( + fake_change_processor_.get())), + std::unique_ptr<syncer::SyncErrorFactory>( + new syncer::SyncErrorFactoryMock())) .error(); // Change to custom theme and notify theme_sync_service_. @@ -590,13 +583,12 @@ syncer::SyncError error = theme_sync_service_ ->MergeDataAndStartSyncing( - syncer::THEMES, - MakeThemeDataList(theme_specifics), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::SyncChangeProcessorWrapperForTest( - fake_change_processor_.get())), - scoped_ptr<syncer::SyncErrorFactory>( - new syncer::SyncErrorFactoryMock())) + syncer::THEMES, MakeThemeDataList(theme_specifics), + std::unique_ptr<syncer::SyncChangeProcessor>( + new syncer::SyncChangeProcessorWrapperForTest( + fake_change_processor_.get())), + std::unique_ptr<syncer::SyncErrorFactory>( + new syncer::SyncErrorFactoryMock())) .error(); EXPECT_FALSE(fake_theme_service_->is_dirty()); @@ -641,13 +633,12 @@ syncer::SyncError error = theme_sync_service_ ->MergeDataAndStartSyncing( - syncer::THEMES, - MakeThemeDataList(theme_specifics), - scoped_ptr<syncer::SyncChangeProcessor>( - new syncer::SyncChangeProcessorWrapperForTest( - fake_change_processor_.get())), - scoped_ptr<syncer::SyncErrorFactory>( - new syncer::SyncErrorFactoryMock())) + syncer::THEMES, MakeThemeDataList(theme_specifics), + std::unique_ptr<syncer::SyncChangeProcessor>( + new syncer::SyncChangeProcessorWrapperForTest( + fake_change_processor_.get())), + std::unique_ptr<syncer::SyncErrorFactory>( + new syncer::SyncErrorFactoryMock())) .error(); EXPECT_EQ(fake_theme_service_->theme_extension(), theme_extension_.get());
diff --git a/chrome/browser/thumbnails/content_analysis_unittest.cc b/chrome/browser/thumbnails/content_analysis_unittest.cc index 23161efd..96c223a6 100644 --- a/chrome/browser/thumbnails/content_analysis_unittest.cc +++ b/chrome/browser/thumbnails/content_analysis_unittest.cc
@@ -12,10 +12,10 @@ #include <cstdlib> #include <functional> #include <limits> +#include <memory> #include <numeric> #include <vector> -#include "base/memory/scoped_ptr.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h"
diff --git a/chrome/browser/tracing/background_tracing_field_trial.cc b/chrome/browser/tracing/background_tracing_field_trial.cc index 2e0549d..970cfdd 100644 --- a/chrome/browser/tracing/background_tracing_field_trial.cc +++ b/chrome/browser/tracing/background_tracing_field_trial.cc
@@ -38,7 +38,7 @@ void UploadCallback(const std::string& upload_url, const scoped_refptr<base::RefCountedString>& file_contents, - scoped_ptr<const base::DictionaryValue> metadata, + std::unique_ptr<const base::DictionaryValue> metadata, base::Closure callback) { TraceCrashServiceUploader* uploader = new TraceCrashServiceUploader( g_browser_process->system_request_context()); @@ -70,7 +70,7 @@ if (g_config_text_filter_for_testing) (*g_config_text_filter_for_testing)(&config_text); - scoped_ptr<base::Value> value = base::JSONReader::Read(config_text); + std::unique_ptr<base::Value> value = base::JSONReader::Read(config_text); if (!value) return; @@ -78,7 +78,7 @@ if (!value->GetAsDictionary(&dict)) return; - scoped_ptr<content::BackgroundTracingConfig> config = + std::unique_ptr<content::BackgroundTracingConfig> config = content::BackgroundTracingConfig::FromDict(dict); if (!config) return;
diff --git a/chrome/browser/tracing/chrome_tracing_delegate.cc b/chrome/browser/tracing/chrome_tracing_delegate.cc index 7544b7253..0b85007b 100644 --- a/chrome/browser/tracing/chrome_tracing_delegate.cc +++ b/chrome/browser/tracing/chrome_tracing_delegate.cc
@@ -49,9 +49,9 @@ incognito_launched_ = true; } -scoped_ptr<content::TraceUploader> ChromeTracingDelegate::GetTraceUploader( +std::unique_ptr<content::TraceUploader> ChromeTracingDelegate::GetTraceUploader( net::URLRequestContextGetter* request_context) { - return scoped_ptr<content::TraceUploader>( + return std::unique_ptr<content::TraceUploader>( new TraceCrashServiceUploader(request_context)); } @@ -148,7 +148,7 @@ std::vector<std::string> variations; variations::GetFieldTrialActiveGroupIdsAsStrings(&variations); - scoped_ptr<base::ListValue> variations_list(new base::ListValue()); + std::unique_ptr<base::ListValue> variations_list(new base::ListValue()); for (const auto& it : variations) variations_list->Append(new base::StringValue(it));
diff --git a/chrome/browser/tracing/chrome_tracing_delegate.h b/chrome/browser/tracing/chrome_tracing_delegate.h index d745eff..d1b933a 100644 --- a/chrome/browser/tracing/chrome_tracing_delegate.h +++ b/chrome/browser/tracing/chrome_tracing_delegate.h
@@ -5,7 +5,8 @@ #ifndef CHROME_BROWSER_TRACING_CHROME_TRACING_DELEGATE_H_ #define CHROME_BROWSER_TRACING_CHROME_TRACING_DELEGATE_H_ -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "chrome/browser/ui/browser_list_observer.h" #include "content/public/browser/tracing_delegate.h" @@ -19,7 +20,7 @@ static void RegisterPrefs(PrefRegistrySimple* registry); - scoped_ptr<content::TraceUploader> GetTraceUploader( + std::unique_ptr<content::TraceUploader> GetTraceUploader( net::URLRequestContextGetter* request_context) override; bool IsAllowedToBeginBackgroundScenario(
diff --git a/chrome/browser/tracing/chrome_tracing_delegate_browsertest.cc b/chrome/browser/tracing/chrome_tracing_delegate_browsertest.cc index a61d164..316fe0f 100644 --- a/chrome/browser/tracing/chrome_tracing_delegate_browsertest.cc +++ b/chrome/browser/tracing/chrome_tracing_delegate_browsertest.cc
@@ -50,16 +50,17 @@ dict.SetString("mode", "PREEMPTIVE_TRACING_MODE"); dict.SetString("category", "BENCHMARK"); - scoped_ptr<base::ListValue> rules_list(new base::ListValue()); + std::unique_ptr<base::ListValue> rules_list(new base::ListValue()); { - scoped_ptr<base::DictionaryValue> rules_dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> rules_dict( + new base::DictionaryValue()); rules_dict->SetString("rule", "MONITOR_AND_DUMP_WHEN_TRIGGER_NAMED"); rules_dict->SetString("trigger_name", "test"); rules_list->Append(std::move(rules_dict)); } dict.Set("configs", std::move(rules_list)); - scoped_ptr<content::BackgroundTracingConfig> config( + std::unique_ptr<content::BackgroundTracingConfig> config( content::BackgroundTracingConfig::FromDict(&dict)); DCHECK(config); @@ -96,7 +97,7 @@ private: void OnUpload(const scoped_refptr<base::RefCountedString>& file_contents, - scoped_ptr<const base::DictionaryValue> metadata, + std::unique_ptr<const base::DictionaryValue> metadata, base::Callback<void()> done_callback) { receive_count_ += 1;
diff --git a/chrome/browser/tracing/crash_service_uploader.cc b/chrome/browser/tracing/crash_service_uploader.cc index 9f98e99..4aec392 100644 --- a/chrome/browser/tracing/crash_service_uploader.cc +++ b/chrome/browser/tracing/crash_service_uploader.cc
@@ -110,7 +110,7 @@ void TraceCrashServiceUploader::DoUpload( const std::string& file_contents, UploadMode upload_mode, - scoped_ptr<const base::DictionaryValue> metadata, + std::unique_ptr<const base::DictionaryValue> metadata, const UploadProgressCallback& progress_callback, const UploadDoneCallback& done_callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); @@ -126,7 +126,7 @@ const std::string& file_contents, UploadMode upload_mode, const std::string& upload_url, - scoped_ptr<const base::DictionaryValue> metadata, + std::unique_ptr<const base::DictionaryValue> metadata, const UploadProgressCallback& progress_callback, const UploadDoneCallback& done_callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); @@ -174,7 +174,7 @@ std::string compressed_contents; if (upload_mode == COMPRESSED_UPLOAD) { - scoped_ptr<char[]> compressed_buffer(new char[kMaxUploadBytes]); + std::unique_ptr<char[]> compressed_buffer(new char[kMaxUploadBytes]); int compressed_bytes; if (!Compress(file_contents, kMaxUploadBytes, compressed_buffer.get(), &compressed_bytes)) { @@ -212,7 +212,7 @@ void TraceCrashServiceUploader::SetupMultipart( const std::string& product, const std::string& version, - scoped_ptr<const base::DictionaryValue> metadata, + std::unique_ptr<const base::DictionaryValue> metadata, const std::string& trace_filename, const std::string& trace_contents, std::string* post_data) {
diff --git a/chrome/browser/tracing/crash_service_uploader.h b/chrome/browser/tracing/crash_service_uploader.h index 55d3204..cfff0933 100644 --- a/chrome/browser/tracing/crash_service_uploader.h +++ b/chrome/browser/tracing/crash_service_uploader.h
@@ -7,12 +7,12 @@ #include <stdint.h> +#include <memory> #include <string> #include <vector> #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" #include "content/public/browser/trace_uploader.h" @@ -42,22 +42,23 @@ // content::TraceUploader void DoUpload(const std::string& file_contents, UploadMode upload_mode, - scoped_ptr<const base::DictionaryValue> metadata, + std::unique_ptr<const base::DictionaryValue> metadata, const UploadProgressCallback& progress_callback, const UploadDoneCallback& done_callback) override; private: - void DoUploadOnFileThread(const std::string& file_contents, - UploadMode upload_mode, - const std::string& upload_url, - scoped_ptr<const base::DictionaryValue> metadata, - const UploadProgressCallback& progress_callback, - const UploadDoneCallback& done_callback); + void DoUploadOnFileThread( + const std::string& file_contents, + UploadMode upload_mode, + const std::string& upload_url, + std::unique_ptr<const base::DictionaryValue> metadata, + const UploadProgressCallback& progress_callback, + const UploadDoneCallback& done_callback); // Sets up a multipart body to be uploaded. The body is produced according // to RFC 2046. void SetupMultipart(const std::string& product, const std::string& version, - scoped_ptr<const base::DictionaryValue> metadata, + std::unique_ptr<const base::DictionaryValue> metadata, const std::string& trace_filename, const std::string& trace_contents, std::string* post_data); @@ -73,7 +74,7 @@ const std::string& post_data); void OnUploadError(const std::string& error_message); - scoped_ptr<net::URLFetcher> url_fetcher_; + std::unique_ptr<net::URLFetcher> url_fetcher_; UploadProgressCallback progress_callback_; UploadDoneCallback done_callback_;
diff --git a/chrome/browser/tracing/navigation_tracing.cc b/chrome/browser/tracing/navigation_tracing.cc index 07ee42e8..197ecc2 100644 --- a/chrome/browser/tracing/navigation_tracing.cc +++ b/chrome/browser/tracing/navigation_tracing.cc
@@ -36,7 +36,7 @@ } void UploadCallback(const scoped_refptr<base::RefCountedString>& file_contents, - scoped_ptr<const base::DictionaryValue> metadata, + std::unique_ptr<const base::DictionaryValue> metadata, base::Closure callback) { TraceCrashServiceUploader* uploader = new TraceCrashServiceUploader( g_browser_process->system_request_context()); @@ -61,9 +61,10 @@ base::DictionaryValue dict; dict.SetString("mode", "REACTIVE_TRACING_MODE"); - scoped_ptr<base::ListValue> rules_list(new base::ListValue()); + std::unique_ptr<base::ListValue> rules_list(new base::ListValue()); { - scoped_ptr<base::DictionaryValue> rules_dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> rules_dict( + new base::DictionaryValue()); rules_dict->SetString("rule", "TRACE_ON_NAVIGATION_UNTIL_TRIGGER_OR_FULL"); rules_dict->SetString("trigger_name", kNavigationTracingConfig); rules_dict->SetString("category", "BENCHMARK_DEEP"); @@ -71,7 +72,7 @@ } dict.Set("configs", std::move(rules_list)); - scoped_ptr<content::BackgroundTracingConfig> config( + std::unique_ptr<content::BackgroundTracingConfig> config( content::BackgroundTracingConfig::FromDict(&dict)); DCHECK(config);
diff --git a/chrome/browser/translate/chrome_translate_client.cc b/chrome/browser/translate/chrome_translate_client.cc index d43dab0..ce32fe0 100644 --- a/chrome/browser/translate/chrome_translate_client.cc +++ b/chrome/browser/translate/chrome_translate_client.cc
@@ -92,14 +92,14 @@ } // static -scoped_ptr<translate::TranslatePrefs> +std::unique_ptr<translate::TranslatePrefs> ChromeTranslateClient::CreateTranslatePrefs(PrefService* prefs) { #if defined(OS_CHROMEOS) const char* preferred_languages_prefs = prefs::kLanguagePreferredLanguages; #else const char* preferred_languages_prefs = NULL; #endif - scoped_ptr<translate::TranslatePrefs> translate_prefs( + std::unique_ptr<translate::TranslatePrefs> translate_prefs( new translate::TranslatePrefs(prefs, prefs::kAcceptLanguages, preferred_languages_prefs)); @@ -153,7 +153,7 @@ Profile::FromBrowserContext(web_contents->GetBrowserContext()); Profile* original_profile = profile->GetOriginalProfile(); PrefService* prefs = original_profile->GetPrefs(); - scoped_ptr<translate::TranslatePrefs> translate_prefs = + std::unique_ptr<translate::TranslatePrefs> translate_prefs = CreateTranslatePrefs(prefs); if (!web_contents->GetBrowserContext()->IsOffTheRecord()) { std::string auto_translate_language = @@ -228,7 +228,7 @@ return profile->GetOriginalProfile()->GetPrefs(); } -scoped_ptr<translate::TranslatePrefs> +std::unique_ptr<translate::TranslatePrefs> ChromeTranslateClient::GetTranslatePrefs() { DCHECK(web_contents()); Profile* profile =
diff --git a/chrome/browser/translate/chrome_translate_client.h b/chrome/browser/translate/chrome_translate_client.h index 2bf67d0..d216295 100644 --- a/chrome/browser/translate/chrome_translate_client.h +++ b/chrome/browser/translate/chrome_translate_client.h
@@ -5,10 +5,10 @@ #ifndef CHROME_BROWSER_TRANSLATE_CHROME_TRANSLATE_CLIENT_H_ #define CHROME_BROWSER_TRANSLATE_CHROME_TRANSLATE_CLIENT_H_ +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/ui/translate/translate_bubble_model.h" #include "components/translate/content/browser/content_translate_driver.h" #include "components/translate/core/browser/translate_client.h" @@ -53,7 +53,7 @@ } // Helper method to return a new TranslatePrefs instance. - static scoped_ptr<translate::TranslatePrefs> CreateTranslatePrefs( + static std::unique_ptr<translate::TranslatePrefs> CreateTranslatePrefs( PrefService* prefs); // Helper method to return the TranslateAcceptLanguages instance associated @@ -81,12 +81,13 @@ // TranslateClient implementation. translate::TranslateDriver* GetTranslateDriver() override; PrefService* GetPrefs() override; - scoped_ptr<translate::TranslatePrefs> GetTranslatePrefs() override; + std::unique_ptr<translate::TranslatePrefs> GetTranslatePrefs() override; translate::TranslateAcceptLanguages* GetTranslateAcceptLanguages() override; int GetInfobarIconID() const override; #if !defined(USE_AURA) - scoped_ptr<infobars::InfoBar> CreateInfoBar( - scoped_ptr<translate::TranslateInfoBarDelegate> delegate) const override; + std::unique_ptr<infobars::InfoBar> CreateInfoBar( + std::unique_ptr<translate::TranslateInfoBarDelegate> delegate) + const override; #endif void ShowTranslateUI(translate::TranslateStep step, const std::string& source_language, @@ -115,7 +116,7 @@ translate::TranslateErrors::Type error_type); translate::ContentTranslateDriver translate_driver_; - scoped_ptr<translate::TranslateManager> translate_manager_; + std::unique_ptr<translate::TranslateManager> translate_manager_; DISALLOW_COPY_AND_ASSIGN(ChromeTranslateClient); };
diff --git a/chrome/browser/translate/cld_data_harness.cc b/chrome/browser/translate/cld_data_harness.cc index 35ab020a..bc7631e 100644 --- a/chrome/browser/translate/cld_data_harness.cc +++ b/chrome/browser/translate/cld_data_harness.cc
@@ -48,21 +48,18 @@ } // static -scoped_ptr<CldDataHarness> -CldDataHarness::CreateStaticDataHarness() { - return scoped_ptr<CldDataHarness>(new StaticCldDataHarness()); +std::unique_ptr<CldDataHarness> CldDataHarness::CreateStaticDataHarness() { + return std::unique_ptr<CldDataHarness>(new StaticCldDataHarness()); } // static -scoped_ptr<CldDataHarness> -CldDataHarness::CreateStandaloneDataHarness() { - return scoped_ptr<CldDataHarness>(new StandaloneCldDataHarness()); +std::unique_ptr<CldDataHarness> CldDataHarness::CreateStandaloneDataHarness() { + return std::unique_ptr<CldDataHarness>(new StandaloneCldDataHarness()); } // static -scoped_ptr<CldDataHarness> -CldDataHarness::CreateComponentDataHarness() { - return scoped_ptr<CldDataHarness>(new ComponentCldDataHarness()); +std::unique_ptr<CldDataHarness> CldDataHarness::CreateComponentDataHarness() { + return std::unique_ptr<CldDataHarness>(new ComponentCldDataHarness()); } } // namespace test
diff --git a/chrome/browser/translate/cld_data_harness.h b/chrome/browser/translate/cld_data_harness.h index 6a78d78d..da2bc73 100644 --- a/chrome/browser/translate/cld_data_harness.h +++ b/chrome/browser/translate/cld_data_harness.h
@@ -5,9 +5,10 @@ #ifndef CHROME_BROWSER_TRANSLATE_CLD_DATA_HARNESS_H_ #define CHROME_BROWSER_TRANSLATE_CLD_DATA_HARNESS_H_ +#include <memory> + #include "base/files/file_path.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" namespace test { @@ -28,7 +29,7 @@ // Sample usage: // // IN_PROC_BROWSER_TEST_F(BrowserTest, PageLanguageDetection) { -// scoped_ptr<test::CldDataHarness> cld_data_scope = +// std::unique_ptr<test::CldDataHarness> cld_data_scope = // test::CldDataHarnessFactory::Get()->CreateCldDataHarness(); // ASSERT_NO_FATAL_FAILURE(cld_data_scope->Init()); // // ... your code that depends on language detection goes here @@ -51,7 +52,7 @@ // InProcessBrowserTest::SetUpOnMainThread(); // } // private: -// scoped_ptr<test::CldDataHarness> cld_data_scope; +// std::unique_ptr<test::CldDataHarness> cld_data_scope; // }; // class CldDataHarness { @@ -76,19 +77,19 @@ // Create and return a new instance of a data harness whose Init() method // will configure the "static" CldDataSource. - static scoped_ptr<CldDataHarness> CreateStaticDataHarness(); + static std::unique_ptr<CldDataHarness> CreateStaticDataHarness(); // Create and return a new instance of a data harness whose Init() method // will configure the "standalone" CldDataSource. // Unlike NONE() and STATIC(), this data hardness will perform work to allow // CLD to load data from a file. - static scoped_ptr<CldDataHarness> CreateStandaloneDataHarness(); + static std::unique_ptr<CldDataHarness> CreateStandaloneDataHarness(); // Create and return a new instance of a data harness whose Init() method // will configure the "component" CldDataSource. // Unlike NONE() and STATIC(), this data hardness will perform work to allow // CLD to load data from a file. - static scoped_ptr<CldDataHarness> CreateComponentDataHarness(); + static std::unique_ptr<CldDataHarness> CreateComponentDataHarness(); protected: // Returns the version number of the Component Updater "extension" in the
diff --git a/chrome/browser/translate/cld_data_harness_factory.cc b/chrome/browser/translate/cld_data_harness_factory.cc index 6ceafc5..607e941 100644 --- a/chrome/browser/translate/cld_data_harness_factory.cc +++ b/chrome/browser/translate/cld_data_harness_factory.cc
@@ -35,7 +35,7 @@ namespace test { -scoped_ptr<CldDataHarness> CldDataHarnessFactory::CreateCldDataHarness() { +std::unique_ptr<CldDataHarness> CldDataHarnessFactory::CreateCldDataHarness() { // Cheat: Since the three "canned" implementations are all well-known, just // check to see if "this" points to one of the singletons and then return // the right answer. Embedder-provided CldDataHarnessFactory implementations
diff --git a/chrome/browser/translate/cld_data_harness_factory.h b/chrome/browser/translate/cld_data_harness_factory.h index 52e1323..508b97c8 100644 --- a/chrome/browser/translate/cld_data_harness_factory.h +++ b/chrome/browser/translate/cld_data_harness_factory.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_TRANSLATE_CLD_DATA_HARNESS_FACTORY_H_ #define CHROME_BROWSER_TRANSLATE_CLD_DATA_HARNESS_FACTORY_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/translate/cld_data_harness.h" namespace test { @@ -34,7 +35,7 @@ // Create a new CldDataHarness. // The default implementation returns a simple CldDataHarness, which is // likely to be incorrect for most non-static CLD use cases. - virtual scoped_ptr<CldDataHarness> CreateCldDataHarness(); + virtual std::unique_ptr<CldDataHarness> CreateCldDataHarness(); // Unconditionally sets the factory for this process, overwriting any // previously-configured value. Open-source Chromium test code should almost
diff --git a/chrome/browser/translate/translate_manager_browsertest.cc b/chrome/browser/translate/translate_manager_browsertest.cc index 2b83e4d..46e6fdde 100644 --- a/chrome/browser/translate/translate_manager_browsertest.cc +++ b/chrome/browser/translate/translate_manager_browsertest.cc
@@ -4,7 +4,8 @@ #include "components/translate/core/browser/translate_manager.h" -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "build/build_config.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/prefs/session_startup_pref.h" @@ -35,7 +36,7 @@ protected: // InProcessBrowserTest members. void SetUp() override { - scoped_ptr<test::CldDataHarness> cld_data_harness = + std::unique_ptr<test::CldDataHarness> cld_data_harness = test::CldDataHarnessFactory::Get()->CreateCldDataHarness(); ASSERT_NO_FATAL_FAILURE(cld_data_harness->Init()); InProcessBrowserTest::SetUp(); @@ -50,7 +51,7 @@ ui_test_utils::WindowedNotificationObserverWithDetails< translate::LanguageDetectionDetails>; - scoped_ptr<LangageDetectionObserver> language_detected_signal_; + std::unique_ptr<LangageDetectionObserver> language_detected_signal_; }; // Tests that the CLD (Compact Language Detection) works properly.
diff --git a/chrome/browser/translate/translate_manager_render_view_host_unittest.cc b/chrome/browser/translate/translate_manager_render_view_host_unittest.cc index c5f4ac3..aff1aace 100644 --- a/chrome/browser/translate/translate_manager_render_view_host_unittest.cc +++ b/chrome/browser/translate/translate_manager_render_view_host_unittest.cc
@@ -3,7 +3,9 @@ // found in the LICENSE file. #include <stddef.h> + #include <algorithm> +#include <memory> #include <set> #include <tuple> #include <utility> @@ -11,7 +13,6 @@ #include "base/command_line.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/stringprintf.h" #include "build/build_config.h" #include "chrome/app/chrome_command_ids.h" @@ -89,11 +90,10 @@ translate::TranslateDownloadManager::GetLanguageCode( g_browser_process->GetApplicationLocale()); - scoped_ptr<translate::TranslateUIDelegate> ui_delegate( + std::unique_ptr<translate::TranslateUIDelegate> ui_delegate( new translate::TranslateUIDelegate( chrome_translate_client->GetTranslateManager()->GetWeakPtr(), - source_language, - target_language)); + source_language, target_language)); model_.reset(new TranslateBubbleModelImpl(step, std::move(ui_delegate))); } @@ -109,7 +109,7 @@ TranslateBubbleModel* model() { return model_.get(); } private: - scoped_ptr<TranslateBubbleModel> model_; + std::unique_ptr<TranslateBubbleModel> model_; DISALLOW_COPY_AND_ASSIGN(MockTranslateBubbleFactory); }; @@ -490,7 +490,7 @@ // WARNING: the pointers point to deleted objects, use only for comparison. std::set<infobars::InfoBarDelegate*> removed_infobars_; - scoped_ptr<MockTranslateBubbleFactory> bubble_factory_; + std::unique_ptr<MockTranslateBubbleFactory> bubble_factory_; DISALLOW_COPY_AND_ASSIGN(TranslateManagerRenderViewHostTest); }; @@ -732,7 +732,7 @@ ASSERT_TRUE(GetTranslateInfoBar() == NULL); // Translate the page anyway throught the context menu. - scoped_ptr<TestRenderViewContextMenu> menu(CreateContextMenu()); + std::unique_ptr<TestRenderViewContextMenu> menu(CreateContextMenu()); menu->Init(); menu->ExecuteCommand(IDC_CONTENT_CONTEXT_TRANSLATE, 0); @@ -1151,7 +1151,7 @@ EXPECT_TRUE(GetTranslateInfoBar() == NULL); // And the context menu option should be disabled too. - scoped_ptr<TestRenderViewContextMenu> menu(CreateContextMenu()); + std::unique_ptr<TestRenderViewContextMenu> menu(CreateContextMenu()); menu->Init(); EXPECT_TRUE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_TRANSLATE)); EXPECT_FALSE(menu->IsCommandIdEnabled(IDC_CONTENT_CONTEXT_TRANSLATE)); @@ -1247,7 +1247,7 @@ registrar.Init(prefs); registrar.Add(translate::TranslatePrefs::kPrefTranslateBlockedLanguages, pref_callback_); - scoped_ptr<translate::TranslatePrefs> translate_prefs( + std::unique_ptr<translate::TranslatePrefs> translate_prefs( ChromeTranslateClient::CreateTranslatePrefs(prefs)); EXPECT_FALSE(translate_prefs->IsBlockedLanguage("fr")); translate::TranslateAcceptLanguages* accept_languages = @@ -1304,7 +1304,7 @@ registrar.Init(prefs); registrar.Add(translate::TranslatePrefs::kPrefTranslateSiteBlacklist, pref_callback_); - scoped_ptr<translate::TranslatePrefs> translate_prefs( + std::unique_ptr<translate::TranslatePrefs> translate_prefs( ChromeTranslateClient::CreateTranslatePrefs(prefs)); EXPECT_FALSE(translate_prefs->IsSiteBlacklisted(host)); translate::TranslateAcceptLanguages* accept_languages = @@ -1352,7 +1352,7 @@ registrar.Init(prefs); registrar.Add(translate::TranslatePrefs::kPrefTranslateWhitelists, pref_callback_); - scoped_ptr<translate::TranslatePrefs> translate_prefs( + std::unique_ptr<translate::TranslatePrefs> translate_prefs( ChromeTranslateClient::CreateTranslatePrefs(prefs)); SetPrefObserverExpectation( translate::TranslatePrefs::kPrefTranslateWhitelists); @@ -1414,7 +1414,7 @@ GURL url("http://www.google.fr"); Profile* profile = Profile::FromBrowserContext(web_contents()->GetBrowserContext()); - scoped_ptr<translate::TranslatePrefs> translate_prefs( + std::unique_ptr<translate::TranslatePrefs> translate_prefs( ChromeTranslateClient::CreateTranslatePrefs(profile->GetPrefs())); translate_prefs->BlockLanguage("fr"); translate_prefs->BlacklistSite(url.host()); @@ -1424,7 +1424,7 @@ // Simulate navigating to a page in French. The translate menu should show but // should only be enabled when the page language has been received. NavigateAndCommit(url); - scoped_ptr<TestRenderViewContextMenu> menu(CreateContextMenu()); + std::unique_ptr<TestRenderViewContextMenu> menu(CreateContextMenu()); menu->Init(); EXPECT_TRUE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_TRANSLATE)); EXPECT_FALSE(menu->IsCommandIdEnabled(IDC_CONTENT_CONTEXT_TRANSLATE)); @@ -1523,7 +1523,7 @@ Profile* profile = Profile::FromBrowserContext(web_contents()->GetBrowserContext()); - scoped_ptr<translate::TranslatePrefs> translate_prefs( + std::unique_ptr<translate::TranslatePrefs> translate_prefs( ChromeTranslateClient::CreateTranslatePrefs(profile->GetPrefs())); translate_prefs->ResetTranslationAcceptedCount("fr"); translate_prefs->ResetTranslationDeniedCount("fr"); @@ -1607,7 +1607,7 @@ EXPECT_TRUE(GetTranslateInfoBar() == NULL); // The context menu is enabled to allow users to force translation. - scoped_ptr<TestRenderViewContextMenu> menu(CreateContextMenu()); + std::unique_ptr<TestRenderViewContextMenu> menu(CreateContextMenu()); menu->Init(); EXPECT_TRUE(menu->IsItemPresent(IDC_CONTENT_CONTEXT_TRANSLATE)); EXPECT_TRUE(menu->IsCommandIdEnabled(IDC_CONTENT_CONTEXT_TRANSLATE)); @@ -1664,7 +1664,7 @@ return; MockTranslateBubbleFactory* factory = new MockTranslateBubbleFactory; - scoped_ptr<TranslateBubbleFactory> factory_ptr(factory); + std::unique_ptr<TranslateBubbleFactory> factory_ptr(factory); TranslateBubbleFactory::SetFactory(factory); SimulateNavigation(GURL("http://www.google.fr"), "fr", true); @@ -1707,7 +1707,7 @@ return; MockTranslateBubbleFactory* factory = new MockTranslateBubbleFactory; - scoped_ptr<TranslateBubbleFactory> factory_ptr(factory); + std::unique_ptr<TranslateBubbleFactory> factory_ptr(factory); TranslateBubbleFactory::SetFactory(factory); SimulateNavigation(GURL("http://www.google.fr"), "fr", true); @@ -1740,7 +1740,7 @@ return; MockTranslateBubbleFactory* factory = new MockTranslateBubbleFactory; - scoped_ptr<TranslateBubbleFactory> factory_ptr(factory); + std::unique_ptr<TranslateBubbleFactory> factory_ptr(factory); TranslateBubbleFactory::SetFactory(factory); // Simulate navigating to a page ("und" is the string returned by the CLD for @@ -1751,7 +1751,7 @@ ASSERT_TRUE(factory->model() == NULL); // Translate the page anyway throught the context menu. - scoped_ptr<TestRenderViewContextMenu> menu(CreateContextMenu()); + std::unique_ptr<TestRenderViewContextMenu> menu(CreateContextMenu()); menu->Init(); menu->ExecuteCommand(IDC_CONTENT_CONTEXT_TRANSLATE, 0);
diff --git a/chrome/browser/ui/android/autofill/OWNERS b/chrome/browser/ui/android/autofill/OWNERS index 4685e87..1db6b26 100644 --- a/chrome/browser/ui/android/autofill/OWNERS +++ b/chrome/browser/ui/android/autofill/OWNERS
@@ -1,3 +1 @@ -aurimas@chromium.org - per-file password_generation_popup_view_android.*=rouslan@chromium.org
diff --git a/chrome/browser/ui/app_list/app_list_service_mac.mm b/chrome/browser/ui/app_list/app_list_service_mac.mm index a6f351cd..096c9ff 100644 --- a/chrome/browser/ui/app_list/app_list_service_mac.mm +++ b/chrome/browser/ui/app_list/app_list_service_mac.mm
@@ -14,6 +14,7 @@ #include "base/command_line.h" #include "base/files/file_util.h" #include "base/lazy_instance.h" +#import "base/mac/foundation_util.h" #include "base/memory/singleton.h" #include "base/message_loop/message_loop.h" #import "chrome/browser/app_controller_mac.h" @@ -441,7 +442,8 @@ void AppListServiceMac::EnableAppList(Profile* initial_profile, AppListEnableSource enable_source) { AppListServiceImpl::EnableAppList(initial_profile, enable_source); - AppController* controller = [NSApp delegate]; + AppController* controller = + base::mac::ObjCCastStrict<AppController>([NSApp delegate]); [controller initAppShimMenuController]; }
diff --git a/chrome/browser/ui/ash/chrome_launcher_prefs.cc b/chrome/browser/ui/ash/chrome_launcher_prefs.cc index ee0a413..c90b435 100644 --- a/chrome/browser/ui/ash/chrome_launcher_prefs.cc +++ b/chrome/browser/ui/ash/chrome_launcher_prefs.cc
@@ -132,6 +132,10 @@ return kShelfAlignmentLeft; case SHELF_ALIGNMENT_RIGHT: return kShelfAlignmentRight; + case SHELF_ALIGNMENT_BOTTOM_LOCKED: + // This should not be a valid preference option for now. We only want to + // lock the shelf during login or when adding a user. + return nullptr; } NOTREACHED(); return nullptr; @@ -154,8 +158,8 @@ case SHELF_AUTO_HIDE_BEHAVIOR_NEVER: return kShelfAutoHideBehaviorNever; case SHELF_AUTO_HIDE_ALWAYS_HIDDEN: - // This one should not be a valid preference option for now. We only want - // to completely hide it when we run in app mode - or while we temporarily + // This should not be a valid preference option for now. We only want to + // completely hide it when we run in app mode - or while we temporarily // hide the shelf as part of an animation (e.g. the multi user change). return nullptr; } @@ -252,6 +256,9 @@ DCHECK_GE(display_id, 0); const char* value = AlignmentToPref(alignment); + if (!value) + return; + SetPerDisplayPref(prefs, display_id, prefs::kShelfAlignment, value); if (display_id == gfx::Screen::GetScreen()->GetPrimaryDisplay().id()) { // See comment in |kShelfAlignment| as to why we consider two prefs.
diff --git a/chrome/browser/ui/ash/launcher/chrome_launcher_controller.cc b/chrome/browser/ui/ash/launcher/chrome_launcher_controller.cc index bf3579f..b81ad446 100644 --- a/chrome/browser/ui/ash/launcher/chrome_launcher_controller.cc +++ b/chrome/browser/ui/ash/launcher/chrome_launcher_controller.cc
@@ -1029,7 +1029,7 @@ void ChromeLauncherController::OnShelfAlignmentChanged(ash::Shelf* shelf) { ash::SetShelfAlignmentPref(profile_->GetPrefs(), GetDisplayIDForShelf(shelf), - shelf->GetAlignment()); + shelf->alignment()); } void ChromeLauncherController::OnShelfAutoHideBehaviorChanged(
diff --git a/chrome/browser/ui/ash/launcher/chrome_mash_shelf_controller.cc b/chrome/browser/ui/ash/launcher/chrome_mash_shelf_controller.cc index dacf3e822..1a813c6 100644 --- a/chrome/browser/ui/ash/launcher/chrome_mash_shelf_controller.cc +++ b/chrome/browser/ui/ash/launcher/chrome_mash_shelf_controller.cc
@@ -79,7 +79,8 @@ ResourceBundle& rb = ResourceBundle::GetSharedInstance(); const gfx::Image& image = rb.GetImageNamed(IDR_PRODUCT_LOGO_32); item->image = skia::mojom::Bitmap::From(*image.ToSkBitmap()); - scoped_ptr<ChromeShelfItemDelegate> delegate(new ChromeShelfItemDelegate()); + std::unique_ptr<ChromeShelfItemDelegate> delegate( + new ChromeShelfItemDelegate()); shelf_controller_->AddItem(std::move(item), delegate->CreateInterfacePtrInfoAndBind( shelf_controller_.associated_group()));
diff --git a/chrome/browser/ui/ash/launcher/chrome_mash_shelf_controller.h b/chrome/browser/ui/ash/launcher/chrome_mash_shelf_controller.h index 1a10ef28d..b458fa3 100644 --- a/chrome/browser/ui/ash/launcher/chrome_mash_shelf_controller.h +++ b/chrome/browser/ui/ash/launcher/chrome_mash_shelf_controller.h
@@ -6,9 +6,9 @@ #define CHROME_BROWSER_UI_ASH_LAUNCHER_CHROME_MASH_SHELF_CONTROLLER_H_ #include <map> +#include <memory> #include <string> -#include "base/memory/scoped_ptr.h" #include "mash/shelf/public/interfaces/shelf.mojom.h" #include "mojo/public/cpp/bindings/associated_binding.h" @@ -39,7 +39,7 @@ mash::shelf::mojom::ShelfControllerPtr shelf_controller_; mojo::AssociatedBinding<mash::shelf::mojom::ShelfObserver> observer_binding_; - std::map<std::string, scoped_ptr<ChromeShelfItemDelegate>> + std::map<std::string, std::unique_ptr<ChromeShelfItemDelegate>> app_id_to_item_delegate_; DISALLOW_COPY_AND_ASSIGN(ChromeMashShelfController);
diff --git a/chrome/browser/ui/ash/launcher/launcher_context_menu_unittest.cc b/chrome/browser/ui/ash/launcher/launcher_context_menu_unittest.cc index 8d1391fc..fc1b661 100644 --- a/chrome/browser/ui/ash/launcher/launcher_context_menu_unittest.cc +++ b/chrome/browser/ui/ash/launcher/launcher_context_menu_unittest.cc
@@ -146,7 +146,8 @@ // Verifies contextmenu items for Arc app #if defined(OS_CHROMEOS) TEST_F(LauncherContextMenuTest, ArcLauncherContextMenuItemCheck) { - scoped_ptr<LauncherContextMenu> menu(CreateLauncherContextMenuForArcApp()); + std::unique_ptr<LauncherContextMenu> menu( + CreateLauncherContextMenuForArcApp()); EXPECT_TRUE( IsItemPresentInMenu(menu.get(), LauncherContextMenu::MENU_OPEN_NEW)); EXPECT_TRUE(menu->IsCommandIdEnabled(LauncherContextMenu::MENU_OPEN_NEW));
diff --git a/chrome/browser/ui/browser_browsertest.cc b/chrome/browser/ui/browser_browsertest.cc index 1308c25..be237af 100644 --- a/chrome/browser/ui/browser_browsertest.cc +++ b/chrome/browser/ui/browser_browsertest.cc
@@ -106,7 +106,6 @@ #include "extensions/common/extension_set.h" #include "net/base/net_errors.h" #include "net/dns/mock_host_resolver.h" -#include "net/ssl/ssl_connection_status_flags.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/request_handler_util.h" #include "net/test/spawned_test_server/spawned_test_server.h" @@ -3094,27 +3093,6 @@ namespace { -// A URLRequestMockHTTPJob that mocks an SSL connection with an -// obsolete protocol version. -class URLRequestNonsecureConnection : public net::URLRequestMockHTTPJob { - public: - void GetResponseInfo(net::HttpResponseInfo* info) override { - info->ssl_info.connection_status = (net::SSL_CONNECTION_VERSION_TLS1_1 - << net::SSL_CONNECTION_VERSION_SHIFT); - // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 from - // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-4 - const uint16_t ciphersuite = 0xc02f; - net::SSLConnectionStatusSetCipherSuite(ciphersuite, - &info->ssl_info.connection_status); - } - - protected: - ~URLRequestNonsecureConnection() override {} - - private: - DISALLOW_COPY_AND_ASSIGN(URLRequestNonsecureConnection); -}; - class BrowserTestNonsecureURLRequest : public BrowserTest { public: BrowserTestNonsecureURLRequest() : BrowserTest() {} @@ -3124,7 +3102,7 @@ content::BrowserThread::PostTask( content::BrowserThread::IO, FROM_HERE, base::Bind( - &URLRequestNonsecureConnection::AddUrlHandlers, root_http, + &net::URLRequestMockHTTPJob::AddUrlHandlers, root_http, make_scoped_refptr(content::BrowserThread::GetBlockingPool()))); } @@ -3143,7 +3121,7 @@ SecurityStyleTestObserver observer(web_contents); ui_test_utils::NavigateToURL( - browser(), URLRequestNonsecureConnection::GetMockHttpsUrl(std::string())); + browser(), net::URLRequestMockHTTPJob::GetMockHttpsUrl(std::string())); for (const auto& explanation : observer.latest_explanations().secure_explanations) { EXPECT_NE(l10n_util::GetStringUTF8(IDS_SECURE_PROTOCOL_AND_CIPHERSUITE),
diff --git a/chrome/browser/ui/browser_dialogs.h b/chrome/browser/ui/browser_dialogs.h index b2a206eff..ced547eb 100644 --- a/chrome/browser/ui/browser_dialogs.h +++ b/chrome/browser/ui/browser_dialogs.h
@@ -85,6 +85,11 @@ // dialog using one of the functions below, rather than showing a Cocoa dialog. bool ToolkitViewsDialogsEnabled(); +// For Mac, returns true if Chrome should show an equivalent toolkit-views based +// dialog instead of a WebUI-styled Cocoa dialog. ToolkitViewsDialogsEnabled() +// implies ToolkitViewsWebUIDialogsEnabled(). +bool ToolkitViewsWebUIDialogsEnabled(); + // Shows a Views website settings bubble at the given anchor point. void ShowWebsiteSettingsBubbleViewsAtPoint( const gfx::Point& anchor_point,
diff --git a/chrome/browser/ui/browser_dialogs_mac.cc b/chrome/browser/ui/browser_dialogs_mac.cc index cf79ad9..a85fbcb 100644 --- a/chrome/browser/ui/browser_dialogs_mac.cc +++ b/chrome/browser/ui/browser_dialogs_mac.cc
@@ -5,8 +5,13 @@ #include "chrome/browser/ui/browser_dialogs.h" #include "base/command_line.h" +#include "base/feature_list.h" #include "chrome/common/chrome_switches.h" +const base::Feature kMacViewsWebUIDialogs { + "MacViewsWebUIDialogs", base::FEATURE_DISABLED_BY_DEFAULT +}; + namespace chrome { bool ToolkitViewsDialogsEnabled() { @@ -14,4 +19,8 @@ switches::kEnableMacViewsDialogs); } +bool ToolkitViewsWebUIDialogsEnabled() { + return base::FeatureList::IsEnabled(kMacViewsWebUIDialogs); +} + } // namespace chrome
diff --git a/chrome/browser/ui/cocoa/app_menu/app_menu_controller.mm b/chrome/browser/ui/cocoa/app_menu/app_menu_controller.mm index f7c7d57..a76602be 100644 --- a/chrome/browser/ui/cocoa/app_menu/app_menu_controller.mm +++ b/chrome/browser/ui/cocoa/app_menu/app_menu_controller.mm
@@ -387,17 +387,21 @@ // menu is about to be displayed at the start of a tracking session.) zoom_level_observer_.reset(); toolbar_actions_bar_observer_.reset(); + // Make sure to reset() the BrowserActionsController since the view will also + // be destroyed. If a new one's needed, it'll be created when we create the + // model in -menuNeedsUpdate:. + browserActionsController_.reset(); UMA_HISTOGRAM_TIMES("Toolbar.AppMenuTimeToAction", base::TimeTicks::Now() - menuOpenTime_); menuOpenTime_ = base::TimeTicks(); } - (void)menuNeedsUpdate:(NSMenu*)menu { + // We should never have a BrowserActionsController before creating the menu. + DCHECK(!browserActionsController_.get()); + // First empty out the menu and create a new model. [self removeAllItems:menu]; - // Delete the BrowserActionsController; if a new one's needed, it'll be - // created as we add items to the menu. - browserActionsController_.reset(); [self createModel]; [menu setMinimumWidth:0];
diff --git a/chrome/browser/ui/cocoa/applescript/bookmark_node_applescript.mm b/chrome/browser/ui/cocoa/applescript/bookmark_node_applescript.mm index ca63ab2..524f75c 100644 --- a/chrome/browser/ui/cocoa/applescript/bookmark_node_applescript.mm +++ b/chrome/browser/ui/cocoa/applescript/bookmark_node_applescript.mm
@@ -5,6 +5,7 @@ #import "chrome/browser/ui/cocoa/applescript/bookmark_node_applescript.h" #include "base/logging.h" +#import "base/mac/foundation_util.h" #import "base/mac/scoped_nsobject.h" #include "base/strings/sys_string_conversions.h" #import "chrome/browser/app_controller_mac.h" @@ -114,7 +115,8 @@ } - (BookmarkModel*)bookmarkModel { - AppController* appDelegate = [NSApp delegate]; + AppController* appDelegate = + base::mac::ObjCCastStrict<AppController>([NSApp delegate]); Profile* lastProfile = [appDelegate lastProfile]; if (!lastProfile) {
diff --git a/chrome/browser/ui/cocoa/applescript/browsercrapplication+applescript.mm b/chrome/browser/ui/cocoa/applescript/browsercrapplication+applescript.mm index 32d24f75..36e076d 100644 --- a/chrome/browser/ui/cocoa/applescript/browsercrapplication+applescript.mm +++ b/chrome/browser/ui/cocoa/applescript/browsercrapplication+applescript.mm
@@ -5,6 +5,7 @@ #import "chrome/browser/ui/cocoa/applescript/browsercrapplication+applescript.h" #include "base/logging.h" +#import "base/mac/foundation_util.h" #import "base/mac/scoped_nsobject.h" #import "chrome/browser/app_controller_mac.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" @@ -71,7 +72,8 @@ } - (BookmarkFolderAppleScript*)otherBookmarks { - AppController* appDelegate = [NSApp delegate]; + AppController* appDelegate = + base::mac::ObjCCastStrict<AppController>([NSApp delegate]); Profile* lastProfile = [appDelegate lastProfile]; if (!lastProfile) { @@ -94,7 +96,8 @@ } - (BookmarkFolderAppleScript*)bookmarksBar { - AppController* appDelegate = [NSApp delegate]; + AppController* appDelegate = + base::mac::ObjCCastStrict<AppController>([NSApp delegate]); Profile* lastProfile = [appDelegate lastProfile]; if (!lastProfile) {
diff --git a/chrome/browser/ui/cocoa/applescript/window_applescript.mm b/chrome/browser/ui/cocoa/applescript/window_applescript.mm index 6b2ff8d3..216c0e3 100644 --- a/chrome/browser/ui/cocoa/applescript/window_applescript.mm +++ b/chrome/browser/ui/cocoa/applescript/window_applescript.mm
@@ -7,6 +7,7 @@ #include <memory> #include "base/logging.h" +#import "base/mac/foundation_util.h" #import "base/mac/scoped_nsobject.h" #include "base/time/time.h" #import "chrome/browser/app_controller_mac.h" @@ -42,7 +43,8 @@ NSScriptCommand* command = [NSScriptCommand currentCommand]; NSString* mode = [[[command evaluatedArguments] objectForKey:@"KeyDictionary"] objectForKey:@"mode"]; - AppController* appDelegate = [NSApp delegate]; + AppController* appDelegate = + base::mac::ObjCCastStrict<AppController>([NSApp delegate]); Profile* lastProfile = [appDelegate lastProfile];
diff --git a/chrome/browser/ui/cocoa/applescript/window_applescript_test.mm b/chrome/browser/ui/cocoa/applescript/window_applescript_test.mm index 013ce95..abc9348 100644 --- a/chrome/browser/ui/cocoa/applescript/window_applescript_test.mm +++ b/chrome/browser/ui/cocoa/applescript/window_applescript_test.mm
@@ -4,6 +4,7 @@ #import <Cocoa/Cocoa.h> +#import "base/mac/foundation_util.h" #import "base/mac/scoped_nsobject.h" #include "base/strings/sys_string_conversions.h" #import "chrome/browser/app_controller_mac.h" @@ -40,7 +41,9 @@ // Create a window with a particular profile. IN_PROC_BROWSER_TEST_F(WindowAppleScriptTest, CreationWithProfile) { - Profile* lastProfile = [[NSApp delegate] lastProfile]; + AppController* appController = + base::mac::ObjCCastStrict<AppController>([NSApp delegate]); + Profile* lastProfile = [appController lastProfile]; base::scoped_nsobject<WindowAppleScript> aWindow( [[WindowAppleScript alloc] initWithProfile:lastProfile]); EXPECT_TRUE(aWindow.get());
diff --git a/chrome/browser/ui/cocoa/base_bubble_controller.h b/chrome/browser/ui/cocoa/base_bubble_controller.h index 7de195c..1314263 100644 --- a/chrome/browser/ui/cocoa/base_bubble_controller.h +++ b/chrome/browser/ui/cocoa/base_bubble_controller.h
@@ -88,6 +88,9 @@ parentWindow:(NSWindow*)parentWindow anchoredAt:(NSPoint)anchoredAt; +// Closes the bubble with BUBBLE_CLOSE_CANCELED. +- (IBAction)cancel:(id)sender; + // Creates an autoreleased horizontal separator view with a given frame. The // height of the frame is ignored. - (NSBox*)horizontalSeparatorWithFrame:(NSRect)frame;
diff --git a/chrome/browser/ui/cocoa/bookmarks/bookmark_menu_cocoa_controller.mm b/chrome/browser/ui/cocoa/bookmarks/bookmark_menu_cocoa_controller.mm index 52992120..169beadc 100644 --- a/chrome/browser/ui/cocoa/bookmarks/bookmark_menu_cocoa_controller.mm +++ b/chrome/browser/ui/cocoa/bookmarks/bookmark_menu_cocoa_controller.mm
@@ -4,6 +4,7 @@ #import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_cocoa_controller.h" +#import "base/mac/foundation_util.h" #include "base/strings/sys_string_conversions.h" #include "chrome/app/chrome_command_ids.h" // IDC_BOOKMARK_MENU #import "chrome/browser/app_controller_mac.h" @@ -71,7 +72,8 @@ } - (BOOL)validateMenuItem:(NSMenuItem*)menuItem { - AppController* controller = [NSApp delegate]; + AppController* controller = + base::mac::ObjCCastStrict<AppController>([NSApp delegate]); return ![controller keyWindowIsModal]; }
diff --git a/chrome/browser/ui/cocoa/browser_window_controller_private.h b/chrome/browser/ui/cocoa/browser_window_controller_private.h index b23ed5d..f5a653b 100644 --- a/chrome/browser/ui/cocoa/browser_window_controller_private.h +++ b/chrome/browser/ui/cocoa/browser_window_controller_private.h
@@ -197,8 +197,8 @@ // it when we are entering fullscreen. - (void)adjustUIForEnteringFullscreen; -// Returns YES if the fullscreen is for tab content. -- (BOOL)isFullscreenForTabContent; +// Returns YES if the fullscreen is for tab content or an extension. +- (BOOL)isFullscreenForTabContentOrExtension; #endif
diff --git a/chrome/browser/ui/cocoa/browser_window_controller_private.mm b/chrome/browser/ui/cocoa/browser_window_controller_private.mm index 87aa090a..dabb33c 100644 --- a/chrome/browser/ui/cocoa/browser_window_controller_private.mm +++ b/chrome/browser/ui/cocoa/browser_window_controller_private.mm
@@ -465,7 +465,7 @@ } - (void)configurePresentationModeController { - BOOL fullscreenForTab = [self isFullscreenForTabContent]; + BOOL fullscreenForTab = [self isFullscreenForTabContentOrExtension]; BOOL kioskMode = base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode); BOOL showDropdown = @@ -849,7 +849,7 @@ - (void)adjustUIForEnteringFullscreen { fullscreen_mac::SlidingStyle style; - if ([self isFullscreenForTabContent]) { + if ([self isFullscreenForTabContentOrExtension]) { style = fullscreen_mac::OMNIBOX_TABS_NONE; } else if (enteringPresentationMode_ || ![self shouldShowFullscreenToolbar]) { style = fullscreen_mac::OMNIBOX_TABS_HIDDEN; @@ -1245,10 +1245,11 @@ return nil; } -- (BOOL)isFullscreenForTabContent { - return browser_->exclusive_access_manager() - ->fullscreen_controller() - ->IsWindowFullscreenForTabOrPending(); +- (BOOL)isFullscreenForTabContentOrExtension { + FullscreenController* controller = + browser_->exclusive_access_manager()->fullscreen_controller(); + return controller->IsWindowFullscreenForTabOrPending() || + controller->IsExtensionFullscreenOrPending(); } @end // @implementation BrowserWindowController(Private)
diff --git a/chrome/browser/ui/cocoa/chrome_event_processing_window.mm b/chrome/browser/ui/cocoa/chrome_event_processing_window.mm index 6c9e275d..53ed04c 100644 --- a/chrome/browser/ui/cocoa/chrome_event_processing_window.mm +++ b/chrome/browser/ui/cocoa/chrome_event_processing_window.mm
@@ -5,6 +5,8 @@ #import "chrome/browser/ui/cocoa/chrome_event_processing_window.h" #include "base/logging.h" +#import "base/mac/foundation_util.h" +#import "chrome/browser/app_controller_mac.h" #import "chrome/browser/ui/cocoa/chrome_command_dispatcher_delegate.h" #import "ui/base/cocoa/user_interface_item_command_handler.h" @@ -78,9 +80,12 @@ // command handler, defer to AppController. if ([item action] == @selector(commandDispatch:) || [item action] == @selector(commandDispatchUsingKeyModifiers:)) { - return commandHandler_ - ? [commandHandler_ validateUserInterfaceItem:item window:self] - : [[NSApp delegate] validateUserInterfaceItem:item]; + if (commandHandler_) + return [commandHandler_ validateUserInterfaceItem:item window:self]; + + AppController* appController = + base::mac::ObjCCastStrict<AppController>([NSApp delegate]); + return [appController validateUserInterfaceItem:item]; } return [super validateUserInterfaceItem:item];
diff --git a/chrome/browser/ui/cocoa/extensions/browser_actions_controller.mm b/chrome/browser/ui/cocoa/extensions/browser_actions_controller.mm index 59271e7..a68d687 100644 --- a/chrome/browser/ui/cocoa/extensions/browser_actions_controller.mm +++ b/chrome/browser/ui/cocoa/extensions/browser_actions_controller.mm
@@ -607,7 +607,10 @@ } - (void)removeViewForAction:(ToolbarActionViewController*)action { - BrowserActionButton* button = [self buttonForId:action->GetId()]; + // We're about to remove the button view from the container as well as from + // |buttons_|, so make sure we retain a reference. + base::scoped_nsobject<BrowserActionButton> button = + [[self buttonForId:action->GetId()] retain]; // Note: We remove the button from the view and the buttons list first because // destroying it (or calling -onRemoved) can cause redraws, and we don't want
diff --git a/chrome/browser/ui/cocoa/extensions/extension_action_platform_delegate_cocoa.mm b/chrome/browser/ui/cocoa/extensions/extension_action_platform_delegate_cocoa.mm index 1a62696c..b192ade 100644 --- a/chrome/browser/ui/cocoa/extensions/extension_action_platform_delegate_cocoa.mm +++ b/chrome/browser/ui/cocoa/extensions/extension_action_platform_delegate_cocoa.mm
@@ -151,6 +151,6 @@ break; } default: - NOTREACHED() << L"Unexpected notification"; + NOTREACHED() << "Unexpected notification"; } }
diff --git a/chrome/browser/ui/cocoa/history_menu_cocoa_controller.mm b/chrome/browser/ui/cocoa/history_menu_cocoa_controller.mm index 7a3d6fa..6d672cb 100644 --- a/chrome/browser/ui/cocoa/history_menu_cocoa_controller.mm +++ b/chrome/browser/ui/cocoa/history_menu_cocoa_controller.mm
@@ -4,6 +4,7 @@ #import "chrome/browser/ui/cocoa/history_menu_cocoa_controller.h" +#import "base/mac/foundation_util.h" #include "chrome/app/chrome_command_ids.h" // IDC_HISTORY_MENU #import "chrome/browser/app_controller_mac.h" #include "chrome/browser/profiles/profile.h" @@ -33,7 +34,8 @@ } - (BOOL)validateMenuItem:(NSMenuItem*)menuItem { - AppController* controller = [NSApp delegate]; + AppController* controller = + base::mac::ObjCCastStrict<AppController>([NSApp delegate]); return ![controller keyWindowIsModal]; }
diff --git a/chrome/browser/ui/cocoa/info_bubble_window.mm b/chrome/browser/ui/cocoa/info_bubble_window.mm index 02945546..f42a149 100644 --- a/chrome/browser/ui/cocoa/info_bubble_window.mm +++ b/chrome/browser/ui/cocoa/info_bubble_window.mm
@@ -7,9 +7,11 @@ #include <Carbon/Carbon.h> #include "base/logging.h" -#include "base/mac/scoped_nsobject.h" +#import "base/mac/foundation_util.h" +#import "base/mac/scoped_nsobject.h" #include "base/macros.h" #include "chrome/browser/chrome_notification_types.h" +#import "chrome/browser/ui/cocoa/base_bubble_controller.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" @@ -48,7 +50,7 @@ [owner_ appIsTerminating]; break; default: - NOTREACHED() << L"Unexpected notification"; + NOTREACHED() << "Unexpected notification"; } } @@ -141,7 +143,10 @@ if (([event keyCode] == kVK_Escape) || (([event keyCode] == kVK_ANSI_Period) && (([event modifierFlags] & NSCommandKeyMask) != 0))) { - [[self windowController] cancel:self]; + BaseBubbleController* bubbleController = + base::mac::ObjCCastStrict<BaseBubbleController>( + [self windowController]); + [bubbleController cancel:self]; return YES; } return [super performKeyEquivalent:event];
diff --git a/chrome/browser/ui/cocoa/info_bubble_window_unittest.mm b/chrome/browser/ui/cocoa/info_bubble_window_unittest.mm index 4c0f5fb4..a222b32 100644 --- a/chrome/browser/ui/cocoa/info_bubble_window_unittest.mm +++ b/chrome/browser/ui/cocoa/info_bubble_window_unittest.mm
@@ -6,13 +6,15 @@ #include "base/debug/debugger.h" #include "base/mac/scoped_nsobject.h" #include "base/run_loop.h" +#import "chrome/browser/ui/cocoa/base_bubble_controller.h" #include "chrome/browser/ui/cocoa/cocoa_test_helper.h" #include "chrome/browser/ui/cocoa/info_bubble_window.h" #include "chrome/browser/ui/cocoa/run_loop_testing.h" #include "ui/events/test/cocoa_test_event_utils.h" -@interface InfoBubbleWindowController : NSWindowController -- (IBAction)cancel:(id)sender; +// Mock BaseBubbleController to pick up -cancel:, but don't call the designated +// initializer in order to test just InfoBubbleWindow. +@interface InfoBubbleWindowController : BaseBubbleController @end @implementation InfoBubbleWindowController
diff --git a/chrome/browser/ui/cocoa/login_handler_cocoa.mm b/chrome/browser/ui/cocoa/login_handler_cocoa.mm index 3850b7c6..2ff2a1a 100644 --- a/chrome/browser/ui/cocoa/login_handler_cocoa.mm +++ b/chrome/browser/ui/cocoa/login_handler_cocoa.mm
@@ -134,7 +134,7 @@ // static LoginHandler* LoginHandler::Create(net::AuthChallengeInfo* auth_info, net::URLRequest* request) { - if (chrome::ToolkitViewsDialogsEnabled()) + if (chrome::ToolkitViewsWebUIDialogsEnabled()) return chrome::CreateLoginHandlerViews(auth_info, request); return new LoginHandlerMac(auth_info, request); }
diff --git a/chrome/browser/ui/cocoa/omnibox/omnibox_popup_cell.mm b/chrome/browser/ui/cocoa/omnibox/omnibox_popup_cell.mm index 7e7be465..5b042bb 100644 --- a/chrome/browser/ui/cocoa/omnibox/omnibox_popup_cell.mm +++ b/chrome/browser/ui/cocoa/omnibox/omnibox_popup_cell.mm
@@ -104,18 +104,6 @@ bool is_bold) { NSDictionary* answer_style = nil; switch (style_type) { - case SuggestionAnswer::ANSWER: - answer_style = @{ - NSForegroundColorAttributeName : ContentTextColor(), - NSFontAttributeName : LargeFont() - }; - break; - case SuggestionAnswer::HEADLINE: - answer_style = @{ - NSForegroundColorAttributeName : DimTextColor(), - NSFontAttributeName : LargeFont() - }; - break; case SuggestionAnswer::TOP_ALIGNED: answer_style = @{ NSForegroundColorAttributeName : DimTextColor(), @@ -123,12 +111,6 @@ NSSuperscriptAttributeName : @1 }; break; - case SuggestionAnswer::DESCRIPTION: - answer_style = @{ - NSForegroundColorAttributeName : DimTextColor(), - NSFontAttributeName : FieldFont() - }; - break; case SuggestionAnswer::DESCRIPTION_NEGATIVE: answer_style = @{ NSForegroundColorAttributeName : NegativeTextColor(), @@ -141,42 +123,6 @@ NSFontAttributeName : LargeSuperscriptFont() }; break; - case SuggestionAnswer::MORE_INFO: - answer_style = @{ - NSForegroundColorAttributeName : DimTextColor(), - NSFontAttributeName : SmallFont() - }; - break; - case SuggestionAnswer::SUGGESTION: - answer_style = @{ - NSForegroundColorAttributeName : ContentTextColor(), - NSFontAttributeName : FieldFont() - }; - break; - case SuggestionAnswer::SUGGESTION_POSITIVE: - answer_style = @{ - NSForegroundColorAttributeName : PositiveTextColor(), - NSFontAttributeName : FieldFont() - }; - break; - case SuggestionAnswer::SUGGESTION_NEGATIVE: - answer_style = @{ - NSForegroundColorAttributeName : NegativeTextColor(), - NSFontAttributeName : FieldFont() - }; - break; - case SuggestionAnswer::SUGGESTION_LINK: - answer_style = @{ - NSForegroundColorAttributeName : URLTextColor(), - NSFontAttributeName : FieldFont() - }; - break; - case SuggestionAnswer::STATUS: - answer_style = @{ - NSForegroundColorAttributeName : DimTextColor(), - NSFontAttributeName : LargeSuperscriptFont() - }; - break; case SuggestionAnswer::PERSONALIZED_SUGGESTION: answer_style = @{ NSForegroundColorAttributeName : ContentTextColor(), @@ -207,6 +153,7 @@ NSFontAttributeName : FieldFont() }; break; + case SuggestionAnswer::SUGGESTION: // Fall through. default: answer_style = @{ NSForegroundColorAttributeName : ContentTextColor (),
diff --git a/chrome/browser/ui/cocoa/panels/panel_window_controller_cocoa.mm b/chrome/browser/ui/cocoa/panels/panel_window_controller_cocoa.mm index dc51ed72..4c066a4 100644 --- a/chrome/browser/ui/cocoa/panels/panel_window_controller_cocoa.mm +++ b/chrome/browser/ui/cocoa/panels/panel_window_controller_cocoa.mm
@@ -14,6 +14,7 @@ #include "base/mac/scoped_nsautorelease_pool.h" #include "base/strings/sys_string_conversions.h" #include "chrome/app/chrome_command_ids.h" // IDC_* +#import "chrome/browser/app_controller_mac.h" #include "chrome/browser/chrome_browser_application_mac.h" #include "chrome/browser/profiles/profile.h" #import "chrome/browser/ui/cocoa/browser_window_utils.h" @@ -338,8 +339,10 @@ CommandUpdater* command_updater = windowShim_->panel()->command_updater(); if (command_updater->SupportsCommand(tag)) return command_updater->IsCommandEnabled(tag); - else - return [[NSApp delegate] validateUserInterfaceItem:item]; + + AppController* appController = + base::mac::ObjCCastStrict<AppController>([NSApp delegate]); + return [appController validateUserInterfaceItem:item]; } return NO; } @@ -350,10 +353,13 @@ DCHECK(sender); NSInteger tag = [sender tag]; CommandUpdater* command_updater = windowShim_->panel()->command_updater(); - if (command_updater->SupportsCommand(tag)) + if (command_updater->SupportsCommand(tag)) { windowShim_->panel()->ExecuteCommandIfEnabled(tag); - else - [[NSApp delegate] commandDispatch:sender]; + } else { + AppController* appController = + base::mac::ObjCCastStrict<AppController>([NSApp delegate]); + [appController commandDispatch:sender]; + } } // Handler for the custom Close button.
diff --git a/chrome/browser/ui/cocoa/tabs/tab_window_controller.mm b/chrome/browser/ui/cocoa/tabs/tab_window_controller.mm index 07baee6..0902568 100644 --- a/chrome/browser/ui/cocoa/tabs/tab_window_controller.mm +++ b/chrome/browser/ui/cocoa/tabs/tab_window_controller.mm
@@ -33,23 +33,15 @@ @implementation TabWindowOverlayWindow - (const ui::ThemeProvider*)themeProvider { - if ([self parentWindow]) - return [[[self parentWindow] windowController] themeProvider]; - return NULL; + return [[self parentWindow] themeProvider]; } - (ThemedWindowStyle)themedWindowStyle { - if ([self parentWindow]) - return [[[self parentWindow] windowController] themedWindowStyle]; - return NO; + return [[self parentWindow] themedWindowStyle]; } - (NSPoint)themeImagePositionForAlignment:(ThemeImageAlignment)alignment { - if ([self parentWindow]) { - return [[[self parentWindow] windowController] - themeImagePositionForAlignment:alignment]; - } - return NSZeroPoint; + return [[self parentWindow] themeImagePositionForAlignment:alignment]; } @end
diff --git a/chrome/browser/ui/passwords/password_manager_presenter.cc b/chrome/browser/ui/passwords/password_manager_presenter.cc index f31826a1..3c8a512 100644 --- a/chrome/browser/ui/passwords/password_manager_presenter.cc +++ b/chrome/browser/ui/passwords/password_manager_presenter.cc
@@ -8,6 +8,7 @@ #include "base/bind.h" #include "base/command_line.h" +#include "base/memory/ptr_util.h" #include "base/metrics/user_metrics_action.h" #include "base/strings/string_piece.h" #include "base/strings/string_split.h" @@ -252,12 +253,12 @@ #endif } -std::vector<scoped_ptr<autofill::PasswordForm>> +std::vector<std::unique_ptr<autofill::PasswordForm>> PasswordManagerPresenter::GetAllPasswords() { - std::vector<scoped_ptr<autofill::PasswordForm>> ret_val; + std::vector<std::unique_ptr<autofill::PasswordForm>> ret_val; for (const auto& form : password_list_) { - ret_val.push_back(make_scoped_ptr(new autofill::PasswordForm(*form))); + ret_val.push_back(base::WrapUnique(new autofill::PasswordForm(*form))); } return ret_val;
diff --git a/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model_unittest.cc b/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model_unittest.cc index 67ab3ce..fe126e8 100644 --- a/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model_unittest.cc +++ b/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model_unittest.cc
@@ -495,8 +495,8 @@ } // Per http://crbug.com/603744, MaxSessionsAndRecenty fails intermittently on -// windows and linux. -#if defined(OS_WIN) || defined(OS_LINUX) +// windows, linux and mac. +#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_MACOSX) #define MAYBE_MaxSessionsAndRecency DISABLED_MaxSessionsAndRecency #else #define MAYBE_MaxSessionsAndRecency MaxSessionsAndRecency
diff --git a/chrome/browser/ui/views/extensions/extension_dialog.cc b/chrome/browser/ui/views/extensions/extension_dialog.cc index 36b883b..edd0933 100644 --- a/chrome/browser/ui/views/extensions/extension_dialog.cc +++ b/chrome/browser/ui/views/extensions/extension_dialog.cc
@@ -225,7 +225,7 @@ observer_->ExtensionTerminated(this); break; default: - NOTREACHED() << L"Received unexpected notification"; + NOTREACHED() << "Received unexpected notification"; break; } }
diff --git a/chrome/browser/ui/views/extensions/extension_popup.cc b/chrome/browser/ui/views/extensions/extension_popup.cc index c256d58c..474b270 100644 --- a/chrome/browser/ui/views/extensions/extension_popup.cc +++ b/chrome/browser/ui/views/extensions/extension_popup.cc
@@ -119,7 +119,7 @@ GetWidget()->Close(); break; default: - NOTREACHED() << L"Received unexpected notification"; + NOTREACHED() << "Received unexpected notification"; } }
diff --git a/chrome/browser/ui/views/find_bar_view.cc b/chrome/browser/ui/views/find_bar_view.cc index 3f6031b7..da01048 100644 --- a/chrome/browser/ui/views/find_bar_view.cc +++ b/chrome/browser/ui/views/find_bar_view.cc
@@ -441,7 +441,7 @@ FindBarController::kKeepResultsInFindBox); break; default: - NOTREACHED() << L"Unknown button"; + NOTREACHED() << "Unknown button"; break; } }
diff --git a/chrome/browser/ui/views/omnibox/omnibox_result_view.cc b/chrome/browser/ui/views/omnibox/omnibox_result_view.cc index d2ee13ee..8dc6d54a 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_result_view.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_result_view.cc
@@ -85,134 +85,61 @@ ui::ResourceBundle::FontStyle font; ui::NativeTheme::ColorId colors[OmniboxResultView::NUM_STATES]; gfx::BaselineStyle baseline; -} const kTextStyles[] = { - // 1 ANSWER_TEXT - {ui::ResourceBundle::LargeFont, - {NativeTheme::kColorId_ResultsTableNormalText, - NativeTheme::kColorId_ResultsTableHoveredText, - NativeTheme::kColorId_ResultsTableSelectedText}, - gfx::NORMAL_BASELINE}, - // 2 HEADLINE_TEXT - {ui::ResourceBundle::LargeFont, - {NativeTheme::kColorId_ResultsTableNormalHeadline, - NativeTheme::kColorId_ResultsTableHoveredHeadline, - NativeTheme::kColorId_ResultsTableSelectedHeadline}, - gfx::NORMAL_BASELINE}, - // 3 TOP_ALIGNED_TEXT - {ui::ResourceBundle::LargeFont, - {NativeTheme::kColorId_ResultsTableNormalDimmedText, - NativeTheme::kColorId_ResultsTableHoveredDimmedText, - NativeTheme::kColorId_ResultsTableSelectedDimmedText}, - gfx::SUPERIOR}, - // 4 DESCRIPTION_TEXT - {ui::ResourceBundle::BaseFont, - {NativeTheme::kColorId_ResultsTableNormalDimmedText, - NativeTheme::kColorId_ResultsTableHoveredDimmedText, - NativeTheme::kColorId_ResultsTableSelectedDimmedText}, - gfx::NORMAL_BASELINE}, - // 5 DESCRIPTION_TEXT_NEGATIVE - {ui::ResourceBundle::LargeFont, - {NativeTheme::kColorId_ResultsTableNegativeText, - NativeTheme::kColorId_ResultsTableNegativeHoveredText, - NativeTheme::kColorId_ResultsTableNegativeSelectedText}, - gfx::INFERIOR}, - // 6 DESCRIPTION_TEXT_POSITIVE - {ui::ResourceBundle::LargeFont, - {NativeTheme::kColorId_ResultsTablePositiveText, - NativeTheme::kColorId_ResultsTablePositiveHoveredText, - NativeTheme::kColorId_ResultsTablePositiveSelectedText}, - gfx::INFERIOR}, - // 7 MORE_INFO_TEXT - {ui::ResourceBundle::BaseFont, - {NativeTheme::kColorId_ResultsTableNormalDimmedText, - NativeTheme::kColorId_ResultsTableHoveredDimmedText, - NativeTheme::kColorId_ResultsTableSelectedDimmedText}, - gfx::INFERIOR}, - // 8 SUGGESTION_TEXT - {ui::ResourceBundle::BaseFont, - {NativeTheme::kColorId_ResultsTableNormalText, - NativeTheme::kColorId_ResultsTableHoveredText, - NativeTheme::kColorId_ResultsTableSelectedText}, - gfx::NORMAL_BASELINE}, - // 9 SUGGESTION_TEXT_POSITIVE - {ui::ResourceBundle::BaseFont, - {NativeTheme::kColorId_ResultsTablePositiveText, - NativeTheme::kColorId_ResultsTablePositiveHoveredText, - NativeTheme::kColorId_ResultsTablePositiveSelectedText}, - gfx::NORMAL_BASELINE}, - // 10 SUGGESTION_TEXT_NEGATIVE - {ui::ResourceBundle::BaseFont, - {NativeTheme::kColorId_ResultsTableNegativeText, - NativeTheme::kColorId_ResultsTableNegativeHoveredText, - NativeTheme::kColorId_ResultsTableNegativeSelectedText}, - gfx::NORMAL_BASELINE}, - // 11 SUGGESTION_LINK_COLOR - {ui::ResourceBundle::BaseFont, - {NativeTheme::kColorId_ResultsTableNormalUrl, - NativeTheme::kColorId_ResultsTableHoveredUrl, - NativeTheme::kColorId_ResultsTableSelectedUrl}, - gfx::NORMAL_BASELINE}, - // 12 STATUS_TEXT - {ui::ResourceBundle::LargeFont, - {NativeTheme::kColorId_ResultsTableNormalDimmedText, - NativeTheme::kColorId_ResultsTableHoveredDimmedText, - NativeTheme::kColorId_ResultsTableSelectedDimmedText}, - gfx::INFERIOR}, - // 13 PERSONALIZED_SUGGESTION_TEXT - {ui::ResourceBundle::BaseFont, - {NativeTheme::kColorId_ResultsTableNormalText, - NativeTheme::kColorId_ResultsTableHoveredText, - NativeTheme::kColorId_ResultsTableSelectedText}, - gfx::NORMAL_BASELINE}, - // 14 IMMERSIVE_DESCRIPTION_TEXT (deprecated) - {ui::ResourceBundle::BaseFont, - {NativeTheme::kColorId_ResultsTableNormalText, - NativeTheme::kColorId_ResultsTableHoveredText, - NativeTheme::kColorId_ResultsTableSelectedText}, - gfx::NORMAL_BASELINE}, - // 15 DATE_TEXT (deprecated) - {ui::ResourceBundle::BaseFont, - {NativeTheme::kColorId_ResultsTableNormalText, - NativeTheme::kColorId_ResultsTableHoveredText, - NativeTheme::kColorId_ResultsTableSelectedText}, - gfx::NORMAL_BASELINE}, - // 16 PREVIEW_TEXT (deprecated) - {ui::ResourceBundle::BaseFont, - {NativeTheme::kColorId_ResultsTableNormalText, - NativeTheme::kColorId_ResultsTableHoveredText, - NativeTheme::kColorId_ResultsTableSelectedText}, - gfx::NORMAL_BASELINE}, - // 17 ANSWER_TEXT_MEDIUM - {ui::ResourceBundle::BaseFont, - {NativeTheme::kColorId_ResultsTableNormalText, - NativeTheme::kColorId_ResultsTableHoveredText, - NativeTheme::kColorId_ResultsTableSelectedText}, - gfx::NORMAL_BASELINE}, - // 18 ANSWER_TEXT_LARGE - {ui::ResourceBundle::LargeFont, - {NativeTheme::kColorId_ResultsTableNormalText, - NativeTheme::kColorId_ResultsTableHoveredText, - NativeTheme::kColorId_ResultsTableSelectedText}, - gfx::NORMAL_BASELINE}, - // 19 SUGGESTION_SECONDARY_TEXT_SMALL - {ui::ResourceBundle::BaseFont, - {NativeTheme::kColorId_ResultsTableNormalDimmedText, - NativeTheme::kColorId_ResultsTableHoveredDimmedText, - NativeTheme::kColorId_ResultsTableSelectedDimmedText}, - gfx::NORMAL_BASELINE}, - // 20 SUGGESTION_SECONDARY_TEXT_MEDIUM - {ui::ResourceBundle::BaseFont, - {NativeTheme::kColorId_ResultsTableNormalDimmedText, - NativeTheme::kColorId_ResultsTableHoveredDimmedText, - NativeTheme::kColorId_ResultsTableSelectedDimmedText}, - gfx::NORMAL_BASELINE}, }; -const TextStyle& GetTextStyle(int type) { - if (type < 1 || static_cast<size_t>(type) > arraysize(kTextStyles)) - type = 8; - // Subtract one because the types are one based (not zero based). - return kTextStyles[type - 1]; +TextStyle GetTextStyle(int type) { + switch (type) { + case SuggestionAnswer::TOP_ALIGNED: + return {ui::ResourceBundle::LargeFont, + {NativeTheme::kColorId_ResultsTableNormalDimmedText, + NativeTheme::kColorId_ResultsTableHoveredDimmedText, + NativeTheme::kColorId_ResultsTableSelectedDimmedText}, + gfx::SUPERIOR}; + case SuggestionAnswer::DESCRIPTION_NEGATIVE: + return {ui::ResourceBundle::LargeFont, + {NativeTheme::kColorId_ResultsTableNegativeText, + NativeTheme::kColorId_ResultsTableNegativeHoveredText, + NativeTheme::kColorId_ResultsTableNegativeSelectedText}, + gfx::INFERIOR}; + case SuggestionAnswer::DESCRIPTION_POSITIVE: + return {ui::ResourceBundle::LargeFont, + {NativeTheme::kColorId_ResultsTablePositiveText, + NativeTheme::kColorId_ResultsTablePositiveHoveredText, + NativeTheme::kColorId_ResultsTablePositiveSelectedText}, + gfx::INFERIOR}; + case SuggestionAnswer::PERSONALIZED_SUGGESTION: + return {ui::ResourceBundle::BaseFont, + {NativeTheme::kColorId_ResultsTableNormalText, + NativeTheme::kColorId_ResultsTableHoveredText, + NativeTheme::kColorId_ResultsTableSelectedText}, + gfx::NORMAL_BASELINE}; + case SuggestionAnswer::ANSWER_TEXT_MEDIUM: + return {ui::ResourceBundle::BaseFont, + {NativeTheme::kColorId_ResultsTableNormalText, + NativeTheme::kColorId_ResultsTableHoveredText, + NativeTheme::kColorId_ResultsTableSelectedText}, + gfx::NORMAL_BASELINE}; + case SuggestionAnswer::ANSWER_TEXT_LARGE: + return {ui::ResourceBundle::LargeFont, + {NativeTheme::kColorId_ResultsTableNormalText, + NativeTheme::kColorId_ResultsTableHoveredText, + NativeTheme::kColorId_ResultsTableSelectedText}, + gfx::NORMAL_BASELINE}; + case SuggestionAnswer::SUGGESTION_SECONDARY_TEXT_SMALL: // Fall through. + case SuggestionAnswer::SUGGESTION_SECONDARY_TEXT_MEDIUM: + return {ui::ResourceBundle::BaseFont, + {NativeTheme::kColorId_ResultsTableNormalDimmedText, + NativeTheme::kColorId_ResultsTableHoveredDimmedText, + NativeTheme::kColorId_ResultsTableSelectedDimmedText}, + gfx::NORMAL_BASELINE}; + case SuggestionAnswer::SUGGESTION: // Fall through. + default: + return {ui::ResourceBundle::BaseFont, + {NativeTheme::kColorId_ResultsTableNormalText, + NativeTheme::kColorId_ResultsTableHoveredText, + NativeTheme::kColorId_ResultsTableSelectedText}, + gfx::NORMAL_BASELINE}; + } } } // namespace @@ -795,10 +722,10 @@ } int OmniboxResultView::GetAnswerLineHeight() const { - // GetTextStyle(1) is the largest font used and so defines the boundary that + // ANSWER_TEXT_LARGE is the largest font used and so defines the boundary that // all the other answer styles fit within. return ui::ResourceBundle::GetSharedInstance() - .GetFontList(GetTextStyle(1).font) + .GetFontList(GetTextStyle(SuggestionAnswer::ANSWER_TEXT_LARGE).font) .GetHeight(); }
diff --git a/chrome/browser/ui/views/settings_api_bubble_helper_views.cc b/chrome/browser/ui/views/settings_api_bubble_helper_views.cc index 6bda4f6..589e53f 100644 --- a/chrome/browser/ui/views/settings_api_bubble_helper_views.cc +++ b/chrome/browser/ui/views/settings_api_bubble_helper_views.cc
@@ -38,12 +38,10 @@ return; // TODO(devlin): This should go through the ToolbarActionsBar. - ToolbarActionsBarBubbleViews* bubble = - new ToolbarActionsBarBubbleViews( - anchor_view, - scoped_ptr<ToolbarActionsBarBubbleDelegate>( - new ExtensionMessageBubbleBridge( - std::move(settings_api_bubble)))); + ToolbarActionsBarBubbleViews* bubble = new ToolbarActionsBarBubbleViews( + anchor_view, + std::unique_ptr<ToolbarActionsBarBubbleDelegate>( + new ExtensionMessageBubbleBridge(std::move(settings_api_bubble)))); bubble->set_arrow(arrow); views::BubbleDialogDelegateView::CreateBubble(bubble); bubble->Show();
diff --git a/chrome/browser/ui/views/sync/one_click_signin_dialog_view.cc b/chrome/browser/ui/views/sync/one_click_signin_dialog_view.cc index e47fcd2..c464684 100644 --- a/chrome/browser/ui/views/sync/one_click_signin_dialog_view.cc +++ b/chrome/browser/ui/views/sync/one_click_signin_dialog_view.cc
@@ -41,7 +41,7 @@ // static void OneClickSigninDialogView::ShowDialog( const base::string16& email, - scoped_ptr<OneClickSigninLinksDelegate> delegate, + std::unique_ptr<OneClickSigninLinksDelegate> delegate, gfx::NativeWindow window, const BrowserWindow::StartSyncCallback& start_sync) { if (IsShowing()) @@ -67,7 +67,7 @@ OneClickSigninDialogView::OneClickSigninDialogView( const base::string16& email, - scoped_ptr<OneClickSigninLinksDelegate> delegate, + std::unique_ptr<OneClickSigninLinksDelegate> delegate, const BrowserWindow::StartSyncCallback& start_sync_callback) : delegate_(std::move(delegate)), email_(email),
diff --git a/chrome/browser/ui/views/sync/one_click_signin_dialog_view.h b/chrome/browser/ui/views/sync/one_click_signin_dialog_view.h index bea76830..c5eb67d 100644 --- a/chrome/browser/ui/views/sync/one_click_signin_dialog_view.h +++ b/chrome/browser/ui/views/sync/one_click_signin_dialog_view.h
@@ -5,11 +5,12 @@ #ifndef CHROME_BROWSER_UI_VIEWS_SYNC_ONE_CLICK_SIGNIN_DIALOG_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_SYNC_ONE_CLICK_SIGNIN_DIALOG_VIEW_H_ +#include <memory> + #include "base/callback.h" #include "base/compiler_specific.h" #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/sync/one_click_signin_links_delegate.h" @@ -32,7 +33,7 @@ // Show the one-click signin dialog if not already showing. |start_sync| is // called to start sync. static void ShowDialog(const base::string16& email, - scoped_ptr<OneClickSigninLinksDelegate> delegate, + std::unique_ptr<OneClickSigninLinksDelegate> delegate, gfx::NativeWindow window, const BrowserWindow::StartSyncCallback& start_sync); @@ -48,7 +49,7 @@ // Creates a OneClickSigninDialogView. OneClickSigninDialogView( const base::string16& email, - scoped_ptr<OneClickSigninLinksDelegate> delegate, + std::unique_ptr<OneClickSigninLinksDelegate> delegate, const BrowserWindow::StartSyncCallback& start_sync_callback); ~OneClickSigninDialogView() override; @@ -73,7 +74,7 @@ void LinkClicked(views::Link* source, int event_flags) override; // Delegate to handle clicking on links in the bubble. - scoped_ptr<OneClickSigninLinksDelegate> delegate_; + std::unique_ptr<OneClickSigninLinksDelegate> delegate_; // The user's email address to be used for sync. const base::string16 email_;
diff --git a/chrome/browser/ui/views/sync/one_click_signin_dialog_view_unittest.cc b/chrome/browser/ui/views/sync/one_click_signin_dialog_view_unittest.cc index d1ab41e..693c7b3 100644 --- a/chrome/browser/ui/views/sync/one_click_signin_dialog_view_unittest.cc +++ b/chrome/browser/ui/views/sync/one_click_signin_dialog_view_unittest.cc
@@ -4,12 +4,13 @@ #include "chrome/browser/ui/views/sync/one_click_signin_dialog_view.h" +#include <memory> #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/ui/sync/one_click_signin_links_delegate.h" #include "chrome/browser/ui/views/chrome_constrained_window_views_client.h" #include "components/constrained_window/constrained_window_views.h" @@ -49,7 +50,7 @@ OneClickSigninDialogView* ShowOneClickSigninDialog() { OneClickSigninDialogView::ShowDialog( base::string16(), - make_scoped_ptr(new TestOneClickSigninLinksDelegate(this)), + base::WrapUnique(new TestOneClickSigninLinksDelegate(this)), anchor_widget_->GetNativeWindow(), base::Bind(&OneClickSigninDialogViewTest::OnStartSync, base::Unretained(this)));
diff --git a/chrome/browser/ui/views/toolbar/toolbar_actions_bar_bubble_views_unittest.cc b/chrome/browser/ui/views/toolbar/toolbar_actions_bar_bubble_views_unittest.cc index 46ffe167..d5d1f6c 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_actions_bar_bubble_views_unittest.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_actions_bar_bubble_views_unittest.cc
@@ -4,7 +4,8 @@ #include "chrome/browser/ui/views/toolbar/toolbar_actions_bar_bubble_views.h" -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/ui/toolbar/test_toolbar_actions_bar_bubble_delegate.h"
diff --git a/chrome/browser/ui/views/website_settings/chooser_bubble_ui_view.cc b/chrome/browser/ui/views/website_settings/chooser_bubble_ui_view.cc index 1843c476..2ed20b1 100644 --- a/chrome/browser/ui/views/website_settings/chooser_bubble_ui_view.cc +++ b/chrome/browser/ui/views/website_settings/chooser_bubble_ui_view.cc
@@ -13,6 +13,7 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/strings/string16.h" +#include "base/strings/utf_string_conversions.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/views/exclusive_access_bubble_views.h" @@ -38,6 +39,7 @@ #include "ui/views/controls/table/table_view_observer.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/window/dialog_client_view.h" +#include "url/origin.h" namespace { @@ -189,7 +191,9 @@ } base::string16 ChooserBubbleUiViewDelegate::GetWindowTitle() const { - return l10n_util::GetStringUTF16(IDS_CHOOSER_BUBBLE_PROMPT); + return l10n_util::GetStringFUTF16( + IDS_CHOOSER_BUBBLE_PROMPT, + base::ASCIIToUTF16(controller_->GetOrigin().Serialize())); } base::string16 ChooserBubbleUiViewDelegate::GetDialogButtonLabel(
diff --git a/chrome/browser/ui/website_settings/chooser_bubble_controller.cc b/chrome/browser/ui/website_settings/chooser_bubble_controller.cc index 05113f0..9fc123b 100644 --- a/chrome/browser/ui/website_settings/chooser_bubble_controller.cc +++ b/chrome/browser/ui/website_settings/chooser_bubble_controller.cc
@@ -6,6 +6,7 @@ #include "chrome/browser/net/referrer.h" #include "chrome/browser/ui/browser_finder.h" +#include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" ChooserBubbleController::ChooserBubbleController( @@ -16,6 +17,11 @@ ChooserBubbleController::~ChooserBubbleController() {} +url::Origin ChooserBubbleController::GetOrigin() const { + return const_cast<content::RenderFrameHost*>(owning_frame_) + ->GetLastCommittedOrigin(); +} + void ChooserBubbleController::OpenHelpCenterUrl() const { browser_->OpenURL(content::OpenURLParams( GetHelpCenterUrl(), content::Referrer(), NEW_FOREGROUND_TAB,
diff --git a/chrome/browser/ui/website_settings/chooser_bubble_controller.h b/chrome/browser/ui/website_settings/chooser_bubble_controller.h index 70f7660..9d27c4d 100644 --- a/chrome/browser/ui/website_settings/chooser_bubble_controller.h +++ b/chrome/browser/ui/website_settings/chooser_bubble_controller.h
@@ -14,6 +14,10 @@ class Browser; class GURL; +namespace url { +class Origin; +} + // Subclass ChooserBubbleController to implement a chooser bubble, which has // some introductory text and a list of options that users can pick one of. // Create an instance of your subclass and pass it to @@ -53,6 +57,9 @@ virtual ~Observer() {} }; + // Return the origin URL to be displayed on the bubble title. + url::Origin GetOrigin() const; + // Open help center URL. void OpenHelpCenterUrl() const;
diff --git a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc index faf5740..ea154ef 100644 --- a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc +++ b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc
@@ -97,6 +97,7 @@ #if defined(OS_ANDROID) #include "chrome/browser/ui/webui/net_export_ui.h" #include "chrome/browser/ui/webui/popular_sites_internals_ui.h" +#include "chrome/browser/ui/webui/snippets_internals_ui.h" #else #include "chrome/browser/signin/easy_unlock_service.h" #include "chrome/browser/signin/easy_unlock_service_factory.h" @@ -478,6 +479,8 @@ return &NewWebUI<NetExportUI>; if (url.host() == chrome::kChromeUIPopularSitesInternalsHost) return &NewWebUI<PopularSitesInternalsUI>; + if (url.host() == chrome::kChromeUISnippetsInternalsHost) + return &NewWebUI<SnippetsInternalsUI>; #else if (url.host() == chrome::kChromeUICopresenceHost) return &NewWebUI<CopresenceUI>;
diff --git a/chrome/browser/ui/webui/chromeos/first_run/first_run_ui.cc b/chrome/browser/ui/webui/chromeos/first_run/first_run_ui.cc index 2cfe4cb..03e50bc1 100644 --- a/chrome/browser/ui/webui/chromeos/first_run/first_run_ui.cc +++ b/chrome/browser/ui/webui/chromeos/first_run/first_run_ui.cc
@@ -4,7 +4,7 @@ #include "chrome/browser/ui/webui/chromeos/first_run/first_run_ui.h" -#include "ash/shell.h" +#include "ash/shelf/shelf.h" #include "base/command_line.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" @@ -61,21 +61,9 @@ "transitionsEnabled", base::CommandLine::ForCurrentProcess()->HasSwitch( chromeos::switches::kEnableFirstRunUITransitions)); - std::string shelf_alignment; - ash::Shell* shell = ash::Shell::GetInstance(); - switch (shell->GetShelfAlignment(shell->GetPrimaryRootWindow())) { - case ash::SHELF_ALIGNMENT_BOTTOM: - shelf_alignment = kShelfAlignmentBottom; - break; - case ash::SHELF_ALIGNMENT_LEFT: - shelf_alignment = kShelfAlignmentLeft; - break; - case ash::SHELF_ALIGNMENT_RIGHT: - shelf_alignment = kShelfAlignmentRight; - break; - default: - NOTREACHED() << "Unsupported shelf alignment"; - } + const std::string& shelf_alignment = + ash::Shelf::ForPrimaryDisplay()->SelectValueForShelfAlignment( + kShelfAlignmentBottom, kShelfAlignmentLeft, kShelfAlignmentRight); localized_strings->SetString("shelfAlignment", shelf_alignment); }
diff --git a/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc b/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc index 020cfd4f..ecf0dbad 100644 --- a/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc +++ b/chrome/browser/ui/webui/media_router/media_router_webui_message_handler.cc
@@ -409,6 +409,9 @@ cast_modes, media_router_ui_->GetPresentationRequestSourceName())); initial_data.Set("castModes", cast_modes_list.release()); + Profile* profile = Profile::FromWebUI(web_ui()); + initial_data.SetBoolean("isOffTheRecord", profile->IsOffTheRecord()); + web_ui()->CallJavascriptFunction(kSetInitialData, initial_data); media_router_ui_->UIInitialized(); }
diff --git a/chrome/browser/ui/webui/options/password_manager_handler.cc b/chrome/browser/ui/webui/options/password_manager_handler.cc index f4698d8..404018f3 100644 --- a/chrome/browser/ui/webui/options/password_manager_handler.cc +++ b/chrome/browser/ui/webui/options/password_manager_handler.cc
@@ -93,7 +93,7 @@ } PasswordManagerHandler::PasswordManagerHandler( - scoped_ptr<PasswordManagerPresenter> presenter) + std::unique_ptr<PasswordManagerPresenter> presenter) : password_manager_presenter_(std::move(presenter)) {} PasswordManagerHandler::~PasswordManagerHandler() {} @@ -405,7 +405,7 @@ void PasswordManagerHandler::ExportPasswordFileSelected( const base::FilePath& path) { - std::vector<scoped_ptr<autofill::PasswordForm>> password_list = + std::vector<std::unique_ptr<autofill::PasswordForm>> password_list = password_manager_presenter_->GetAllPasswords(); UMA_HISTOGRAM_COUNTS("PasswordManager.ExportedPasswordsPerUserInCSV", password_list.size());
diff --git a/chrome/browser/ui/webui/options/password_manager_handler.h b/chrome/browser/ui/webui/options/password_manager_handler.h index aa5525c..c2f0651 100644 --- a/chrome/browser/ui/webui/options/password_manager_handler.h +++ b/chrome/browser/ui/webui/options/password_manager_handler.h
@@ -70,7 +70,7 @@ protected: // This constructor is used for testing only. explicit PasswordManagerHandler( - scoped_ptr<PasswordManagerPresenter> presenter); + std::unique_ptr<PasswordManagerPresenter> presenter); private: // Clears and then populates the list of passwords and password exceptions. @@ -127,7 +127,7 @@ // User pref for storing accept languages. std::string languages_; - scoped_ptr<PasswordManagerPresenter> password_manager_presenter_; + std::unique_ptr<PasswordManagerPresenter> password_manager_presenter_; // File picker to import/export file path. scoped_refptr<ui::SelectFileDialog> select_file_dialog_;
diff --git a/chrome/browser/ui/webui/options/password_manager_handler_unittest.cc b/chrome/browser/ui/webui/options/password_manager_handler_unittest.cc index 8ba4583..e3bf459 100644 --- a/chrome/browser/ui/webui/options/password_manager_handler_unittest.cc +++ b/chrome/browser/ui/webui/options/password_manager_handler_unittest.cc
@@ -2,12 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/ui/webui/options/password_manager_handler.h" + +#include "base/memory/ptr_util.h" #include "base/metrics/histogram.h" #include "base/metrics/statistics_recorder.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/password_manager/password_store_factory.h" #include "chrome/browser/ui/passwords/password_manager_presenter.h" -#include "chrome/browser/ui/webui/options/password_manager_handler.h" #include "chrome/test/base/testing_profile.h" #include "components/password_manager/core/browser/mock_password_store.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" @@ -98,8 +100,9 @@ class TestPasswordManagerHandler : public options::PasswordManagerHandler { public: - TestPasswordManagerHandler(scoped_ptr<PasswordManagerPresenter> presenter, - CallbackTestWebUI* web_ui) + TestPasswordManagerHandler( + std::unique_ptr<PasswordManagerPresenter> presenter, + CallbackTestWebUI* web_ui) : PasswordManagerHandler(std::move(presenter)) { set_web_ui(web_ui); } @@ -141,9 +144,9 @@ const std::string&, const base::string16&) override {} void SetPasswordList( - const std::vector<scoped_ptr<autofill::PasswordForm>>&) override {} + const std::vector<std::unique_ptr<autofill::PasswordForm>>&) override {} void SetPasswordExceptionList( - const std::vector<scoped_ptr<autofill::PasswordForm>>&) override {} + const std::vector<std::unique_ptr<autofill::PasswordForm>>&) override {} #if !defined(OS_ANDROID) gfx::NativeWindow GetNativeWindow() const override; @@ -176,7 +179,7 @@ content::WebContentsTester::CreateTestWebContents(&profile_, NULL); web_ui_.set_web_contents(web_contents_); handler_.reset(new TestPasswordManagerHandler( - make_scoped_ptr(presenter_raw_), &web_ui_)); + base::WrapUnique(presenter_raw_), &web_ui_)); handler_->RegisterMessages(); ui::SelectFileDialog::SetFactory(new TestSelectFileDialogFactory); handler_->InitializeHandler(); @@ -197,8 +200,8 @@ PasswordManagerPresenter* presenter_raw_; CallbackTestWebUI web_ui_; content::WebContents* web_contents_; - scoped_ptr<DummyPasswordManagerHandler> dummy_handler_; - scoped_ptr<TestPasswordManagerHandler> handler_; + std::unique_ptr<DummyPasswordManagerHandler> dummy_handler_; + std::unique_ptr<TestPasswordManagerHandler> handler_; private: content::TestBrowserThreadBundle thread_bundle_;
diff --git a/chrome/browser/ui/webui/settings/md_settings_ui.cc b/chrome/browser/ui/webui/settings/md_settings_ui.cc index b947b277..aa71e10d 100644 --- a/chrome/browser/ui/webui/settings/md_settings_ui.cc +++ b/chrome/browser/ui/webui/settings/md_settings_ui.cc
@@ -16,6 +16,7 @@ #include "chrome/browser/ui/webui/settings/languages_handler.h" #include "chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.h" #include "chrome/browser/ui/webui/settings/people_handler.h" +#include "chrome/browser/ui/webui/settings/profile_info_handler.h" #include "chrome/browser/ui/webui/settings/reset_settings_handler.h" #include "chrome/browser/ui/webui/settings/search_engines_handler.h" #include "chrome/browser/ui/webui/settings/settings_clear_browsing_data_handler.h" @@ -64,6 +65,7 @@ AddSettingsPageUIHandler(new FontHandler(web_ui)); AddSettingsPageUIHandler(new LanguagesHandler(web_ui)); AddSettingsPageUIHandler(new PeopleHandler(profile)); + AddSettingsPageUIHandler(new ProfileInfoHandler(profile)); AddSettingsPageUIHandler(new SearchEnginesHandler(profile)); AddSettingsPageUIHandler(new SiteSettingsHandler(profile)); AddSettingsPageUIHandler(new StartupPagesHandler(web_ui));
diff --git a/chrome/browser/ui/webui/settings/people_handler.cc b/chrome/browser/ui/webui/settings/people_handler.cc index 0cc4783..fac1d2d9 100644 --- a/chrome/browser/ui/webui/settings/people_handler.cc +++ b/chrome/browser/ui/webui/settings/people_handler.cc
@@ -16,11 +16,8 @@ #include "base/metrics/histogram.h" #include "base/values.h" #include "build/build_config.h" -#include "chrome/browser/browser_process.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/profiles/profile_attributes_entry.h" -#include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/profiles/profile_window.h" #include "chrome/browser/signin/chrome_signin_helper.h" @@ -53,18 +50,11 @@ #include "google_apis/gaia/gaia_constants.h" #include "grit/components_strings.h" #include "net/base/url_util.h" -#include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" #if defined(OS_CHROMEOS) -#include "chrome/browser/chrome_notification_types.h" -#include "chrome/browser/chromeos/profiles/profile_helper.h" -#include "chrome/browser/ui/webui/options/chromeos/user_image_source.h" -#include "components/signin/core/account_id/account_id.h" #include "components/signin/core/browser/signin_manager_base.h" -#include "components/user_manager/user_manager.h" -#include "content/public/browser/notification_service.h" #else #include "components/signin/core/browser/signin_manager.h" #endif @@ -158,47 +148,6 @@ return true; } -void GetAccountNameAndIcon(const Profile& profile, - std::string* name, - std::string* icon_url) { - DCHECK(name); - DCHECK(icon_url); - -#if defined(OS_CHROMEOS) - *name = profile.GetProfileUserName(); - if (name->empty()) { - const user_manager::User* user = - chromeos::ProfileHelper::Get()->GetUserByProfile(&profile); - if (user && (user->GetType() != user_manager::USER_TYPE_GUEST)) - *name = user->email(); - } - if (!name->empty()) - *name = gaia::SanitizeEmail(gaia::CanonicalizeEmail(*name)); - - // Get image as data URL instead of using chrome://userimage source to avoid - // issues with caching. - const AccountId account_id(AccountId::FromUserEmail(*name)); - scoped_refptr<base::RefCountedMemory> image = - chromeos::options::UserImageSource::GetUserImage(account_id); - *icon_url = webui::GetPngDataUrl(image->front(), image->size()); -#else // !defined(OS_CHROMEOS) - ProfileAttributesEntry* entry; - if (g_browser_process->profile_manager()->GetProfileAttributesStorage(). - GetProfileAttributesWithPath(profile.GetPath(), &entry)) { - *name = base::UTF16ToUTF8(entry->GetName()); - - if (entry->IsUsingGAIAPicture() && entry->GetGAIAPicture()) { - gfx::Image icon = - profiles::GetAvatarIconForWebUI(entry->GetAvatarIcon(), true); - *icon_url = webui::GetBitmapDataUrl(icon.AsBitmap()); - } else { - *icon_url = - profiles::GetDefaultAvatarIconUrl(entry->GetAvatarIconIndex()); - } - } -#endif // defined(OS_CHROMEOS) -} - } // namespace namespace settings { @@ -218,20 +167,9 @@ ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_)); if (sync_service) sync_service_observer_.Add(sync_service); - - g_browser_process->profile_manager()-> - GetProfileAttributesStorage().AddObserver(this); - -#if defined(OS_CHROMEOS) - registrar_.Add(this, chrome::NOTIFICATION_LOGIN_USER_IMAGE_CHANGED, - content::NotificationService::AllSources()); -#endif } PeopleHandler::~PeopleHandler() { - g_browser_process->profile_manager()-> - GetProfileAttributesStorage().RemoveObserver(this); - // Early exit if running unit tests (no actual WebUI is attached). if (!web_ui()) return; @@ -272,9 +210,6 @@ void PeopleHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "getProfileInfo", - base::Bind(&PeopleHandler::HandleGetProfileInfo, base::Unretained(this))); - web_ui()->RegisterMessageCallback( "SyncSetupDidClosePage", base::Bind(&PeopleHandler::OnDidClosePage, base::Unretained(this))); web_ui()->RegisterMessageCallback( @@ -447,16 +382,6 @@ : nullptr; } -void PeopleHandler::HandleGetProfileInfo(const base::ListValue* args) { - std::string name; - std::string icon_url; - GetAccountNameAndIcon(*profile_, &name, &icon_url); - - web_ui()->CallJavascriptFunction("settings.SyncPrivateApi.receiveProfileInfo", - base::StringValue(name), - base::StringValue(icon_url)); -} - void PeopleHandler::HandleConfigure(const base::ListValue* args) { DCHECK(!sync_startup_tracker_); std::string json; @@ -795,31 +720,6 @@ UpdateSyncState(); } -#if defined(OS_CHROMEOS) -void PeopleHandler::Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) { - switch (type) { - case chrome::NOTIFICATION_LOGIN_USER_IMAGE_CHANGED: - HandleGetProfileInfo(nullptr); - break; - default: - NOTREACHED(); - } -} -#endif - -void PeopleHandler::OnProfileNameChanged( - const base::FilePath& /* profile_path */, - const base::string16& /* old_profile_name */) { - HandleGetProfileInfo(nullptr); -} - -void PeopleHandler::OnProfileAvatarChanged( - const base::FilePath& /* profile_path */) { - HandleGetProfileInfo(nullptr); -} - std::unique_ptr<base::DictionaryValue> PeopleHandler::GetSyncStateDictionary() { // The items which are to be written into |sync_status| are also described in // chrome/browser/resources/options/browser_options.js in @typedef
diff --git a/chrome/browser/ui/webui/settings/people_handler.h b/chrome/browser/ui/webui/settings/people_handler.h index 930865f..c265cbfb 100644 --- a/chrome/browser/ui/webui/settings/people_handler.h +++ b/chrome/browser/ui/webui/settings/people_handler.h
@@ -13,7 +13,6 @@ #include "base/strings/utf_string_conversions.h" #include "base/timer/timer.h" #include "build/build_config.h" -#include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/sync/sync_startup_tracker.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "chrome/browser/ui/webui/signin/login_ui_service.h" @@ -21,11 +20,6 @@ #include "components/signin/core/browser/signin_manager_base.h" #include "components/sync_driver/sync_service_observer.h" -#if defined(OS_CHROMEOS) -#include "content/public/browser/notification_observer.h" -#include "content/public/browser/notification_registrar.h" -#endif - class LoginUIService; class ProfileSyncService; class SigninManagerBase; @@ -45,11 +39,7 @@ public SigninManagerBase::Observer, public SyncStartupTracker::Observer, public LoginUIService::LoginUI, - public sync_driver::SyncServiceObserver, -#if defined(OS_CHROMEOS) - public content::NotificationObserver, -#endif - public ProfileAttributesStorage::Observer { + public sync_driver::SyncServiceObserver { public: explicit PeopleHandler(Profile* profile); ~PeopleHandler() override; @@ -75,18 +65,6 @@ // sync_driver::SyncServiceObserver implementation. void OnStateChanged() override; -#if defined(OS_CHROMEOS) - // content::NotificationObserver implementation. - void Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) override; -#endif - - // ProfileAttributesStorage::Observer implementation. - void OnProfileNameChanged(const base::FilePath& profile_path, - const base::string16& old_profile_name) override; - void OnProfileAvatarChanged(const base::FilePath& profile_path) override; - // Initializes the sync setup flow and shows the setup UI. void OpenSyncSetup(bool creating_supervised_user); @@ -214,11 +192,6 @@ // Used to listen for pref changes to allow or disallow signin. PrefChangeRegistrar profile_pref_registrar_; -#if defined(OS_CHROMEOS) - // Used to listen to ChromeOS user image changes. - content::NotificationRegistrar registrar_; -#endif - // Manages observer lifetime. ScopedObserver<ProfileSyncService, PeopleHandler> sync_service_observer_;
diff --git a/chrome/browser/ui/webui/settings/profile_info_handler.cc b/chrome/browser/ui/webui/settings/profile_info_handler.cc new file mode 100644 index 0000000..f092866 --- /dev/null +++ b/chrome/browser/ui/webui/settings/profile_info_handler.cc
@@ -0,0 +1,156 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/settings/profile_info_handler.h" + +#include "base/bind.h" +#include "base/memory/ptr_util.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_attributes_entry.h" +#include "chrome/browser/ui/user_manager.h" +#include "ui/base/webui/web_ui_util.h" + +#if defined(OS_CHROMEOS) +#include "chrome/browser/chrome_notification_types.h" +#include "chrome/browser/chromeos/profiles/profile_helper.h" +#include "chrome/browser/ui/webui/options/chromeos/user_image_source.h" +#include "components/signin/core/account_id/account_id.h" +#include "components/user_manager/user_manager.h" +#include "content/public/browser/notification_service.h" +#else +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/profiles/profile_avatar_icon_util.h" +#include "third_party/skia/include/core/SkBitmap.h" +#endif + +namespace settings { + +// static +const char ProfileInfoHandler::kProfileInfoChangedEventName[] = + "profile-info-changed"; + +ProfileInfoHandler::ProfileInfoHandler(Profile* profile) + : profile_(profile), observers_registered_(false) {} + +void ProfileInfoHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + "getProfileInfo", base::Bind(&ProfileInfoHandler::HandleGetProfileInfo, + base::Unretained(this))); +} + +void ProfileInfoHandler::RenderViewReused() { + if (!observers_registered_) + return; + + g_browser_process->profile_manager() + ->GetProfileAttributesStorage() + .RemoveObserver(this); + +#if defined(OS_CHROMEOS) + registrar_.RemoveAll(); +#endif + + observers_registered_ = false; +} + +#if defined(OS_CHROMEOS) +void ProfileInfoHandler::Observe(int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) { + switch (type) { + case chrome::NOTIFICATION_LOGIN_USER_IMAGE_CHANGED: + PushProfileInfo(); + break; + default: + NOTREACHED(); + } +} +#endif + +void ProfileInfoHandler::OnProfileNameChanged( + const base::FilePath& /* profile_path */, + const base::string16& /* old_profile_name */) { + PushProfileInfo(); +} + +void ProfileInfoHandler::OnProfileAvatarChanged( + const base::FilePath& /* profile_path */) { + PushProfileInfo(); +} + +void ProfileInfoHandler::HandleGetProfileInfo(const base::ListValue* args) { + if (!observers_registered_) { + observers_registered_ = true; + + g_browser_process->profile_manager() + ->GetProfileAttributesStorage() + .AddObserver(this); + +#if defined(OS_CHROMEOS) + registrar_.Add(this, chrome::NOTIFICATION_LOGIN_USER_IMAGE_CHANGED, + content::NotificationService::AllSources()); +#endif + } + + CHECK_EQ(1U, args->GetSize()); + const base::Value* callback_id; + CHECK(args->Get(0, &callback_id)); + + ResolveJavascriptCallback(*callback_id, *GetAccountNameAndIcon()); +} + +void ProfileInfoHandler::PushProfileInfo() { + web_ui()->CallJavascriptFunction( + "cr.webUIListenerCallback", + base::StringValue(kProfileInfoChangedEventName), + *GetAccountNameAndIcon()); +} + +std::unique_ptr<base::DictionaryValue> +ProfileInfoHandler::GetAccountNameAndIcon() const { + std::string name; + std::string icon_url; + +#if defined(OS_CHROMEOS) + name = profile_->GetProfileUserName(); + if (name.empty()) { + const user_manager::User* user = + chromeos::ProfileHelper::Get()->GetUserByProfile(profile_); + if (user && (user->GetType() != user_manager::USER_TYPE_GUEST)) + name = user->email(); + } + if (!name.empty()) + name = gaia::SanitizeEmail(gaia::CanonicalizeEmail(name)); + + // Get image as data URL instead of using chrome://userimage source to avoid + // issues with caching. + const AccountId account_id(AccountId::FromUserEmail(name)); + scoped_refptr<base::RefCountedMemory> image = + chromeos::options::UserImageSource::GetUserImage(account_id); + icon_url = webui::GetPngDataUrl(image->front(), image->size()); +#else // !defined(OS_CHROMEOS) + ProfileAttributesEntry* entry; + if (g_browser_process->profile_manager() + ->GetProfileAttributesStorage() + .GetProfileAttributesWithPath(profile_->GetPath(), &entry)) { + name = base::UTF16ToUTF8(entry->GetName()); + + if (entry->IsUsingGAIAPicture() && entry->GetGAIAPicture()) { + gfx::Image icon = + profiles::GetAvatarIconForWebUI(entry->GetAvatarIcon(), true); + icon_url = webui::GetBitmapDataUrl(icon.AsBitmap()); + } else { + icon_url = profiles::GetDefaultAvatarIconUrl(entry->GetAvatarIconIndex()); + } + } +#endif // defined(OS_CHROMEOS) + + base::DictionaryValue* response = new base::DictionaryValue(); + response->SetString("name", name); + response->SetString("iconUrl", icon_url); + return base::WrapUnique(response); +} + +} // namespace settings
diff --git a/chrome/browser/ui/webui/settings/profile_info_handler.h b/chrome/browser/ui/webui/settings/profile_info_handler.h new file mode 100644 index 0000000..015efcd --- /dev/null +++ b/chrome/browser/ui/webui/settings/profile_info_handler.h
@@ -0,0 +1,77 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_PROFILE_INFO_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_SETTINGS_PROFILE_INFO_HANDLER_H_ + +#include <memory> + +#include "base/macros.h" +#include "build/build_config.h" +#include "chrome/browser/profiles/profile_attributes_storage.h" +#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" + +#if defined(OS_CHROMEOS) +#include "content/public/browser/notification_observer.h" +#include "content/public/browser/notification_registrar.h" +#endif + +class Profile; + +namespace settings { + +class ProfileInfoHandler : public SettingsPageUIHandler, +#if defined(OS_CHROMEOS) + public content::NotificationObserver, +#endif + public ProfileAttributesStorage::Observer { + public: + static const char kProfileInfoChangedEventName[]; + + explicit ProfileInfoHandler(Profile* profile); + ~ProfileInfoHandler() override {} + + // SettingsPageUIHandler implementation. + void RegisterMessages() override; + void RenderViewReused() override; + +#if defined(OS_CHROMEOS) + // content::NotificationObserver implementation. + void Observe(int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) override; +#endif + + // ProfileAttributesStorage::Observer implementation. + void OnProfileNameChanged(const base::FilePath& profile_path, + const base::string16& old_profile_name) override; + void OnProfileAvatarChanged(const base::FilePath& profile_path) override; + + private: + FRIEND_TEST_ALL_PREFIXES(ProfileInfoHandlerTest, GetProfileInfo); + FRIEND_TEST_ALL_PREFIXES(ProfileInfoHandlerTest, PushProfileInfo); + + // Callbacks from the page. + void HandleGetProfileInfo(const base::ListValue* args); + + void PushProfileInfo(); + + std::unique_ptr<base::DictionaryValue> GetAccountNameAndIcon() const; + + // Weak pointer. + Profile* profile_; + +#if defined(OS_CHROMEOS) + // Used to listen to ChromeOS user image changes. + content::NotificationRegistrar registrar_; +#endif + + bool observers_registered_; + + DISALLOW_COPY_AND_ASSIGN(ProfileInfoHandler); +}; + +} // namespace settings + +#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_PROFILE_INFO_HANDLER_H_
diff --git a/chrome/browser/ui/webui/settings/profile_info_handler_unittest.cc b/chrome/browser/ui/webui/settings/profile_info_handler_unittest.cc new file mode 100644 index 0000000..6ae212f --- /dev/null +++ b/chrome/browser/ui/webui/settings/profile_info_handler_unittest.cc
@@ -0,0 +1,137 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/settings/profile_info_handler.h" + +#include <memory> + +#include "chrome/test/base/testing_browser_process.h" +#include "chrome/test/base/testing_profile.h" +#include "chrome/test/base/testing_profile_manager.h" +#include "content/public/browser/web_ui_data_source.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/test_web_ui.h" +#include "testing/gtest/include/gtest/gtest.h" + +#if defined(OS_CHROMEOS) +#include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h" +#include "components/user_manager/fake_user_manager.h" +#endif + +namespace settings { + +namespace { + +class TestProfileInfoHandler : public ProfileInfoHandler { + public: + explicit TestProfileInfoHandler(Profile* profile) + : ProfileInfoHandler(profile) {} + + using ProfileInfoHandler::set_web_ui; +}; + +} // namespace + +class ProfileInfoHandlerTest : public testing::Test { + public: + ProfileInfoHandlerTest() + : profile_manager_(TestingBrowserProcess::GetGlobal()), +#if defined(OS_CHROMEOS) + user_manager_(new user_manager::FakeUserManager), + user_manager_enabler_(user_manager_), +#endif + profile_(nullptr) { + } + + void SetUp() override { + ASSERT_TRUE(profile_manager_.SetUp()); + +#if defined(OS_CHROMEOS) + profile_ = profile_manager_.CreateTestingProfile("fake_id@gmail.com"); +#else + profile_ = profile_manager_.CreateTestingProfile("Profile 1"); +#endif + + handler_.reset(new TestProfileInfoHandler(profile_)); + handler_->set_web_ui(&web_ui_); + } + + void VerifyResponse(const base::Value* call_argument) { + const base::DictionaryValue* response = nullptr; + ASSERT_TRUE(call_argument->GetAsDictionary(&response)); + + std::string name; + std::string icon_url; + ASSERT_TRUE(response->GetString("name", &name)); + ASSERT_TRUE(response->GetString("iconUrl", &icon_url)); + +#if defined(OS_CHROMEOS) + EXPECT_EQ("fake_id@gmail.com", name); + EXPECT_FALSE(icon_url.empty()); +#else + EXPECT_EQ("Profile 1", name); + EXPECT_EQ("chrome://theme/IDR_PROFILE_AVATAR_0", icon_url); +#endif + } + + content::TestWebUI* web_ui() { return &web_ui_; } + Profile* profile() const { return profile_; } + TestProfileInfoHandler* handler() const { return handler_.get(); } + + private: + content::TestBrowserThreadBundle thread_bundle_; + TestingProfileManager profile_manager_; + content::TestWebUI web_ui_; + +#if defined(OS_CHROMEOS) + // |user_manager_| is destroyed by |user_manager_enabler_|. + user_manager::FakeUserManager* user_manager_; + chromeos::ScopedUserManagerEnabler user_manager_enabler_; +#endif + + Profile* profile_; + std::unique_ptr<TestProfileInfoHandler> handler_; +}; + +TEST_F(ProfileInfoHandlerTest, GetProfileInfo) { + base::ListValue list_args; + list_args.Append(new base::StringValue("get-profile-info-callback-id")); + handler()->HandleGetProfileInfo(&list_args); + + EXPECT_EQ(1U, web_ui()->call_data().size()); + + const content::TestWebUI::CallData& data = *web_ui()->call_data().back(); + EXPECT_EQ("cr.webUIResponse", data.function_name()); + + std::string callback_id; + ASSERT_TRUE(data.arg1()->GetAsString(&callback_id)); + EXPECT_EQ("get-profile-info-callback-id", callback_id); + + bool success = false; + ASSERT_TRUE(data.arg2()->GetAsBoolean(&success)); + EXPECT_TRUE(success); + + VerifyResponse(data.arg3()); +} + +TEST_F(ProfileInfoHandlerTest, PushProfileInfo) { + base::ListValue list_args; + list_args.Append(new base::StringValue("get-profile-info-callback-id")); + handler()->HandleGetProfileInfo(&list_args); + + handler()->OnProfileAvatarChanged(base::FilePath()); + + EXPECT_EQ(2U, web_ui()->call_data().size()); + + const content::TestWebUI::CallData& data = *web_ui()->call_data().back(); + EXPECT_EQ("cr.webUIListenerCallback", data.function_name()); + + std::string event_id; + ASSERT_TRUE(data.arg1()->GetAsString(&event_id)); + EXPECT_EQ(ProfileInfoHandler::kProfileInfoChangedEventName, event_id); + + VerifyResponse(data.arg2()); +} + +} // namespace settings
diff --git a/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc b/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc index bb6d8e0..892ff558 100644 --- a/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc +++ b/chrome/browser/ui/webui/settings/settings_manage_profile_handler.cc
@@ -94,8 +94,8 @@ ResolveJavascriptCallback(*callback_id, *GetAvailableIcons()); } -scoped_ptr<base::ListValue> ManageProfileHandler::GetAvailableIcons() { - scoped_ptr<base::ListValue> image_url_list(new base::ListValue()); +std::unique_ptr<base::ListValue> ManageProfileHandler::GetAvailableIcons() { + std::unique_ptr<base::ListValue> image_url_list(new base::ListValue()); // First add the GAIA picture if it is available. ProfileAttributesEntry* entry;
diff --git a/chrome/browser/ui/webui/settings/settings_manage_profile_handler.h b/chrome/browser/ui/webui/settings/settings_manage_profile_handler.h index f51b4e2..ba4e3d5 100644 --- a/chrome/browser/ui/webui/settings/settings_manage_profile_handler.h +++ b/chrome/browser/ui/webui/settings/settings_manage_profile_handler.h
@@ -5,9 +5,9 @@ #ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_SETTINGS_MANAGE_PROFILE_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_SETTINGS_SETTINGS_MANAGE_PROFILE_HANDLER_H_ +#include <memory> #include <string> -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" #include "chrome/browser/profiles/profile_attributes_storage.h" @@ -44,7 +44,7 @@ void HandleGetAvailableIcons(const base::ListValue* args); // Get all the available profile icons to choose from. - scoped_ptr<base::ListValue> GetAvailableIcons(); + std::unique_ptr<base::ListValue> GetAvailableIcons(); // Callback for the "setProfileIconAndName" message. Sets the name and icon // of a given profile.
diff --git a/chrome/browser/ui/webui/snippets_internals_message_handler.cc b/chrome/browser/ui/webui/snippets_internals_message_handler.cc new file mode 100644 index 0000000..363919fb --- /dev/null +++ b/chrome/browser/ui/webui/snippets_internals_message_handler.cc
@@ -0,0 +1,208 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/snippets_internals_message_handler.h" + +#include <memory> +#include <set> +#include <sstream> +#include <vector> + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/command_line.h" +#include "base/feature_list.h" +#include "base/i18n/time_formatting.h" +#include "base/logging.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_piece.h" +#include "base/strings/string_split.h" +#include "base/values.h" +#include "chrome/browser/android/chrome_feature_list.h" +#include "chrome/browser/ntp_snippets/ntp_snippets_service_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "components/ntp_snippets/ntp_snippet.h" +#include "components/ntp_snippets/switches.h" +#include "content/public/browser/web_ui.h" + +namespace { + +std::unique_ptr<base::DictionaryValue> PrepareSnippet( + const ntp_snippets::NTPSnippet& snippet, + int index, + bool discarded) { + std::unique_ptr<base::DictionaryValue> entry(new base::DictionaryValue); + entry->SetString("title", snippet.title()); + entry->SetString("siteTitle", snippet.site_title()); + entry->SetString("snippet", snippet.snippet()); + entry->SetString("published", + TimeFormatShortDateAndTime(snippet.publish_date())); + entry->SetString("expires", + TimeFormatShortDateAndTime(snippet.expiry_date())); + entry->SetString("url", snippet.url().spec()); + entry->SetString("faviconUrl", snippet.favicon_url().spec()); + entry->SetString("salientImageUrl", snippet.salient_image_url().spec()); + + if (discarded) + entry->SetString("id", "discarded-snippet-" + base::IntToString(index)); + else + entry->SetString("id", "snippet-" + base::IntToString(index)); + + return entry; +} + +} // namespace + +SnippetsInternalsMessageHandler::SnippetsInternalsMessageHandler() + : observer_(this), + dom_loaded_(false), + ntp_snippets_service_(nullptr) {} + +SnippetsInternalsMessageHandler::~SnippetsInternalsMessageHandler() {} + +void SnippetsInternalsMessageHandler::NTPSnippetsServiceShutdown() {} + +void SnippetsInternalsMessageHandler::NTPSnippetsServiceLoaded() { + if (!dom_loaded_) return; + + SendSnippets(); + SendDiscardedSnippets(); +} + +void SnippetsInternalsMessageHandler::RegisterMessages() { + // additional initialization (web_ui() does not work from the constructor) + ntp_snippets_service_ = NTPSnippetsServiceFactory::GetInstance()-> + GetForProfile(Profile::FromWebUI(web_ui())); + observer_.Add(ntp_snippets_service_); + + web_ui()->RegisterMessageCallback( + "loaded", + base::Bind(&SnippetsInternalsMessageHandler::HandleLoaded, + base::Unretained(this))); + + web_ui()->RegisterMessageCallback( + "clear", base::Bind(&SnippetsInternalsMessageHandler::HandleClear, + base::Unretained(this))); + + web_ui()->RegisterMessageCallback( + "download", base::Bind(&SnippetsInternalsMessageHandler::HandleDownload, + base::Unretained(this))); + + web_ui()->RegisterMessageCallback( + "clearDiscarded", + base::Bind(&SnippetsInternalsMessageHandler::HandleClearDiscarded, + base::Unretained(this))); +} + +void SnippetsInternalsMessageHandler::HandleLoaded( + const base::ListValue* args) { + DCHECK_EQ(0u, args->GetSize()); + + dom_loaded_ = true; + + SendInitialData(); +} + +void SnippetsInternalsMessageHandler::HandleClear(const base::ListValue* args) { + DCHECK_EQ(0u, args->GetSize()); + + ntp_snippets_service_->ClearSnippets(); +} + +void SnippetsInternalsMessageHandler::HandleClearDiscarded( + const base::ListValue* args) { + DCHECK_EQ(0u, args->GetSize()); + + ntp_snippets_service_->ClearDiscardedSnippets(); + SendDiscardedSnippets(); +} + +void SnippetsInternalsMessageHandler::HandleDownload( + const base::ListValue* args) { + DCHECK_EQ(1u, args->GetSize()); + + std::string hosts_string; + args->GetString(0, &hosts_string); + + std::vector<std::string> hosts_vector = base::SplitString( + hosts_string, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); + std::set<std::string> hosts(hosts_vector.begin(), hosts_vector.end()); + + ntp_snippets_service_->FetchSnippetsFromHosts(hosts); +} + +void SnippetsInternalsMessageHandler::SendInitialData() { + SendHosts(); + + SendBoolean("flag-snippets", base::FeatureList::IsEnabled( + chrome::android::kNTPSnippetsFeature)); + + bool restricted = !base::CommandLine::ForCurrentProcess()->HasSwitch( + ntp_snippets::switches::kDontRestrict); + SendBoolean("switch-restrict-to-hosts", restricted); + const std::string help(restricted ? "(specify at least one host)" : + "(unrestricted if no host is given)"); + SendString("hosts-help", help); + + SendSnippets(); + SendDiscardedSnippets(); +} + +void SnippetsInternalsMessageHandler::SendSnippets() { + std::unique_ptr<base::ListValue> snippets_list(new base::ListValue); + + int index = 0; + for (auto& snippet : *ntp_snippets_service_) + snippets_list->Append(PrepareSnippet(snippet, index++, false)); + + base::DictionaryValue result; + result.Set("list", std::move(snippets_list)); + web_ui()->CallJavascriptFunction("chrome.SnippetsInternals.receiveSnippets", + result); +} + +void SnippetsInternalsMessageHandler::SendDiscardedSnippets() { + std::unique_ptr<base::ListValue> snippets_list(new base::ListValue); + + int index = 0; + for (auto& snippet : ntp_snippets_service_->discarded_snippets()) + snippets_list->Append(PrepareSnippet(*snippet, index++, true)); + + base::DictionaryValue result; + result.Set("list", std::move(snippets_list)); + web_ui()->CallJavascriptFunction( + "chrome.SnippetsInternals.receiveDiscardedSnippets", result); +} + +void SnippetsInternalsMessageHandler::SendHosts() { + std::unique_ptr<base::ListValue> hosts_list(new base::ListValue); + + std::set<std::string> hosts = ntp_snippets_service_->GetSuggestionsHosts(); + + for (const std::string& host : hosts) { + std::unique_ptr<base::DictionaryValue> entry(new base::DictionaryValue); + entry->SetString("url", host); + + hosts_list->Append(std::move(entry)); + } + + base::DictionaryValue result; + result.Set("list", std::move(hosts_list)); + web_ui()->CallJavascriptFunction("chrome.SnippetsInternals.receiveHosts", + result); +} + +void SnippetsInternalsMessageHandler::SendBoolean(const std::string& name, + bool value) { + SendString(name, value ? "True" : "False"); +} + +void SnippetsInternalsMessageHandler::SendString(const std::string& name, + const std::string& value) { + base::StringValue string_name(name); + base::StringValue string_value(value); + + web_ui()->CallJavascriptFunction("chrome.SnippetsInternals.receiveProperty", + string_name, string_value); +}
diff --git a/chrome/browser/ui/webui/snippets_internals_message_handler.h b/chrome/browser/ui/webui/snippets_internals_message_handler.h new file mode 100644 index 0000000..89ef4ee --- /dev/null +++ b/chrome/browser/ui/webui/snippets_internals_message_handler.h
@@ -0,0 +1,59 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_SNIPPETS_INTERNALS_MESSAGE_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_SNIPPETS_INTERNALS_MESSAGE_HANDLER_H_ + +#include <string> + +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "base/scoped_observer.h" +#include "components/ntp_snippets/ntp_snippets_service.h" +#include "content/public/browser/web_ui_message_handler.h" + +namespace base { +class ListValue; +} // namespace base + +// The implementation for the chrome://snippets-internals page. +class SnippetsInternalsMessageHandler + : public content::WebUIMessageHandler, + public ntp_snippets::NTPSnippetsServiceObserver { + public: + SnippetsInternalsMessageHandler(); + ~SnippetsInternalsMessageHandler() override; + + private: + // content::WebUIMessageHandler: + void RegisterMessages() override; + + // ntp_snippets::NTPSnippetsServiceObserver: + // Send everytime the service loads a new set of data. + void NTPSnippetsServiceLoaded() override; + // Send when the service is shutting down. + void NTPSnippetsServiceShutdown() override; + + void HandleLoaded(const base::ListValue* args); + void HandleClear(const base::ListValue* args); + void HandleClearDiscarded(const base::ListValue* args); + void HandleDownload(const base::ListValue* args); + + void SendInitialData(); + void SendSnippets(); + void SendDiscardedSnippets(); + void SendHosts(); + void SendJson(const std::string& json); + void SendBoolean(const std::string& name, bool value); + void SendString(const std::string& name, const std::string& value); + + ScopedObserver<ntp_snippets::NTPSnippetsService, + ntp_snippets::NTPSnippetsServiceObserver> observer_; + bool dom_loaded_; + ntp_snippets::NTPSnippetsService* ntp_snippets_service_; + + DISALLOW_COPY_AND_ASSIGN(SnippetsInternalsMessageHandler); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_SNIPPETS_INTERNALS_MESSAGE_HANDLER_H_
diff --git a/chrome/browser/ui/webui/snippets_internals_ui.cc b/chrome/browser/ui/webui/snippets_internals_ui.cc new file mode 100644 index 0000000..5c697a67 --- /dev/null +++ b/chrome/browser/ui/webui/snippets_internals_ui.cc
@@ -0,0 +1,36 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/snippets_internals_ui.h" + +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/snippets_internals_message_handler.h" +#include "chrome/common/url_constants.h" +#include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" +#include "grit/browser_resources.h" + +namespace { + +content::WebUIDataSource* CreateSnippetsInternalsHTMLSource() { + content::WebUIDataSource* source = + content::WebUIDataSource::Create(chrome::kChromeUISnippetsInternalsHost); + + source->AddResourcePath("snippets_internals.js", IDR_SNIPPETS_INTERNALS_JS); + source->AddResourcePath("snippets_internals.css", IDR_SNIPPETS_INTERNALS_CSS); + source->SetDefaultResource(IDR_SNIPPETS_INTERNALS_HTML); + return source; +} + +} // namespace + +SnippetsInternalsUI::SnippetsInternalsUI(content::WebUI* web_ui) + : WebUIController(web_ui) { + Profile* profile = Profile::FromWebUI(web_ui); + content::WebUIDataSource::Add(profile, CreateSnippetsInternalsHTMLSource()); + + web_ui->AddMessageHandler(new SnippetsInternalsMessageHandler); +} + +SnippetsInternalsUI::~SnippetsInternalsUI() {}
diff --git a/chrome/browser/ui/webui/snippets_internals_ui.h b/chrome/browser/ui/webui/snippets_internals_ui.h new file mode 100644 index 0000000..c6046996d --- /dev/null +++ b/chrome/browser/ui/webui/snippets_internals_ui.h
@@ -0,0 +1,21 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_SNIPPETS_INTERNALS_UI_H_ +#define CHROME_BROWSER_UI_WEBUI_SNIPPETS_INTERNALS_UI_H_ + +#include "base/macros.h" +#include "content/public/browser/web_ui_controller.h" + +// The implementation for the chrome://snippets-internals page. +class SnippetsInternalsUI : public content::WebUIController { + public: + explicit SnippetsInternalsUI(content::WebUI* web_ui); + ~SnippetsInternalsUI() override; + + private: + DISALLOW_COPY_AND_ASSIGN(SnippetsInternalsUI); +}; + +#endif // CHROME_BROWSER_UI_WEBUI_SNIPPETS_INTERNALS_UI_H_
diff --git a/chrome/browser/upgrade_detector_impl.cc b/chrome/browser/upgrade_detector_impl.cc index b7471dcf..cd9668de 100644 --- a/chrome/browser/upgrade_detector_impl.cc +++ b/chrome/browser/upgrade_detector_impl.cc
@@ -6,13 +6,13 @@ #include <stdint.h> +#include <memory> #include <string> #include "base/bind.h" #include "base/build_time.h" #include "base/command_line.h" #include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/path_service.h" #include "base/process/launch.h"
diff --git a/chrome/browser/usb/usb_chooser_context.cc b/chrome/browser/usb/usb_chooser_context.cc index c55fe7d8..5a32788d 100644 --- a/chrome/browser/usb/usb_chooser_context.cc +++ b/chrome/browser/usb/usb_chooser_context.cc
@@ -7,6 +7,7 @@ #include <utility> #include <vector> +#include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" @@ -61,10 +62,10 @@ UsbChooserContext::~UsbChooserContext() {} -std::vector<scoped_ptr<base::DictionaryValue>> +std::vector<std::unique_ptr<base::DictionaryValue>> UsbChooserContext::GetGrantedObjects(const GURL& requesting_origin, const GURL& embedding_origin) { - std::vector<scoped_ptr<base::DictionaryValue>> objects = + std::vector<std::unique_ptr<base::DictionaryValue>> objects = ChooserContextBase::GetGrantedObjects(requesting_origin, embedding_origin); @@ -74,7 +75,8 @@ for (const std::string& guid : it->second) { scoped_refptr<UsbDevice> device = usb_service_->GetDevice(guid); DCHECK(device); - scoped_ptr<base::DictionaryValue> object(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> object( + new base::DictionaryValue()); object->SetString(kDeviceNameKey, device->product_string()); object->SetString(kGuidKey, device->guid()); objects.push_back(std::move(object)); @@ -84,9 +86,9 @@ return objects; } -std::vector<scoped_ptr<ChooserContextBase::Object>> +std::vector<std::unique_ptr<ChooserContextBase::Object>> UsbChooserContext::GetAllGrantedObjects() { - std::vector<scoped_ptr<ChooserContextBase::Object>> objects = + std::vector<std::unique_ptr<ChooserContextBase::Object>> objects = ChooserContextBase::GetAllGrantedObjects(); for (const auto& map_entry : ephemeral_devices_) { @@ -98,7 +100,7 @@ base::DictionaryValue object; object.SetString(kDeviceNameKey, device->product_string()); object.SetString(kGuidKey, device->guid()); - objects.push_back(make_scoped_ptr(new ChooserContextBase::Object( + objects.push_back(base::WrapUnique(new ChooserContextBase::Object( requesting_origin, embedding_origin, &object, "preference", is_off_the_record_))); } @@ -136,7 +138,8 @@ return; if (CanStorePersistentEntry(device)) { - scoped_ptr<base::DictionaryValue> device_dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> device_dict( + new base::DictionaryValue()); device_dict->SetString(kDeviceNameKey, device->product_string()); device_dict->SetInteger(kVendorIdKey, device->vendor_id()); device_dict->SetInteger(kProductIdKey, device->product_id()); @@ -160,9 +163,10 @@ return true; } - std::vector<scoped_ptr<base::DictionaryValue>> device_list = + std::vector<std::unique_ptr<base::DictionaryValue>> device_list = GetGrantedObjects(requesting_origin, embedding_origin); - for (const scoped_ptr<base::DictionaryValue>& device_dict : device_list) { + for (const std::unique_ptr<base::DictionaryValue>& device_dict : + device_list) { int vendor_id; int product_id; base::string16 serial_number;
diff --git a/chrome/browser/usb/usb_chooser_context.h b/chrome/browser/usb/usb_chooser_context.h index 61147f5..39d6605 100644 --- a/chrome/browser/usb/usb_chooser_context.h +++ b/chrome/browser/usb/usb_chooser_context.h
@@ -28,11 +28,11 @@ // These methods from ChooserContextBase are overridden in order to expose // ephemeral devices through the public interface. - std::vector<scoped_ptr<base::DictionaryValue>> GetGrantedObjects( + std::vector<std::unique_ptr<base::DictionaryValue>> GetGrantedObjects( const GURL& requesting_origin, const GURL& embedding_origin) override; - std::vector<scoped_ptr<ChooserContextBase::Object>> GetAllGrantedObjects() - override; + std::vector<std::unique_ptr<ChooserContextBase::Object>> + GetAllGrantedObjects() override; void RevokeObjectPermission(const GURL& requesting_origin, const GURL& embedding_origin, const base::DictionaryValue& object) override;
diff --git a/chrome/browser/usb/usb_chooser_context_unittest.cc b/chrome/browser/usb/usb_chooser_context_unittest.cc index 40b9a32d..1dc9eed 100644 --- a/chrome/browser/usb/usb_chooser_context_unittest.cc +++ b/chrome/browser/usb/usb_chooser_context_unittest.cc
@@ -46,11 +46,11 @@ EXPECT_FALSE(store->HasDevicePermission(origin, origin, device)); store->GrantDevicePermission(origin, origin, device->guid()); EXPECT_TRUE(store->HasDevicePermission(origin, origin, device)); - std::vector<scoped_ptr<base::DictionaryValue>> objects = + std::vector<std::unique_ptr<base::DictionaryValue>> objects = store->GetGrantedObjects(origin, origin); ASSERT_EQ(1u, objects.size()); EXPECT_TRUE(object_dict.Equals(objects[0].get())); - std::vector<scoped_ptr<ChooserContextBase::Object>> all_origin_objects = + std::vector<std::unique_ptr<ChooserContextBase::Object>> all_origin_objects = store->GetAllGrantedObjects(); ASSERT_EQ(1u, all_origin_objects.size()); EXPECT_EQ(origin, all_origin_objects[0]->requesting_origin); @@ -83,11 +83,11 @@ store->GrantDevicePermission(origin, origin, device->guid()); EXPECT_TRUE(store->HasDevicePermission(origin, origin, device)); EXPECT_FALSE(store->HasDevicePermission(origin, origin, other_device)); - std::vector<scoped_ptr<base::DictionaryValue>> objects = + std::vector<std::unique_ptr<base::DictionaryValue>> objects = store->GetGrantedObjects(origin, origin); EXPECT_EQ(1u, objects.size()); EXPECT_TRUE(object_dict.Equals(objects[0].get())); - std::vector<scoped_ptr<ChooserContextBase::Object>> all_origin_objects = + std::vector<std::unique_ptr<ChooserContextBase::Object>> all_origin_objects = store->GetAllGrantedObjects(); EXPECT_EQ(1u, all_origin_objects.size()); EXPECT_EQ(origin, all_origin_objects[0]->requesting_origin); @@ -113,10 +113,10 @@ EXPECT_FALSE(store->HasDevicePermission(origin, origin, device)); store->GrantDevicePermission(origin, origin, device->guid()); EXPECT_TRUE(store->HasDevicePermission(origin, origin, device)); - std::vector<scoped_ptr<base::DictionaryValue>> objects = + std::vector<std::unique_ptr<base::DictionaryValue>> objects = store->GetGrantedObjects(origin, origin); EXPECT_EQ(1u, objects.size()); - std::vector<scoped_ptr<ChooserContextBase::Object>> all_origin_objects = + std::vector<std::unique_ptr<ChooserContextBase::Object>> all_origin_objects = store->GetAllGrantedObjects(); EXPECT_EQ(1u, all_origin_objects.size()); @@ -147,10 +147,10 @@ EXPECT_FALSE(store->HasDevicePermission(origin, origin, device)); store->GrantDevicePermission(origin, origin, device->guid()); EXPECT_TRUE(store->HasDevicePermission(origin, origin, device)); - std::vector<scoped_ptr<base::DictionaryValue>> objects = + std::vector<std::unique_ptr<base::DictionaryValue>> objects = store->GetGrantedObjects(origin, origin); EXPECT_EQ(1u, objects.size()); - std::vector<scoped_ptr<ChooserContextBase::Object>> all_origin_objects = + std::vector<std::unique_ptr<ChooserContextBase::Object>> all_origin_objects = store->GetAllGrantedObjects(); EXPECT_EQ(1u, all_origin_objects.size()); @@ -195,20 +195,20 @@ EXPECT_TRUE(incognito_store->HasDevicePermission(origin, origin, device2)); { - std::vector<scoped_ptr<base::DictionaryValue>> objects = + std::vector<std::unique_ptr<base::DictionaryValue>> objects = store->GetGrantedObjects(origin, origin); EXPECT_EQ(1u, objects.size()); - std::vector<scoped_ptr<ChooserContextBase::Object>> all_origin_objects = - store->GetAllGrantedObjects(); + std::vector<std::unique_ptr<ChooserContextBase::Object>> + all_origin_objects = store->GetAllGrantedObjects(); ASSERT_EQ(1u, all_origin_objects.size()); EXPECT_FALSE(all_origin_objects[0]->incognito); } { - std::vector<scoped_ptr<base::DictionaryValue>> objects = + std::vector<std::unique_ptr<base::DictionaryValue>> objects = incognito_store->GetGrantedObjects(origin, origin); EXPECT_EQ(1u, objects.size()); - std::vector<scoped_ptr<ChooserContextBase::Object>> all_origin_objects = - incognito_store->GetAllGrantedObjects(); + std::vector<std::unique_ptr<ChooserContextBase::Object>> + all_origin_objects = incognito_store->GetAllGrantedObjects(); ASSERT_EQ(1u, all_origin_objects.size()); EXPECT_TRUE(all_origin_objects[0]->incognito); }
diff --git a/chrome/browser/usb/usb_tab_helper.cc b/chrome/browser/usb/usb_tab_helper.cc index 7276b6e..538cb19 100644 --- a/chrome/browser/usb/usb_tab_helper.cc +++ b/chrome/browser/usb/usb_tab_helper.cc
@@ -4,9 +4,9 @@ #include "chrome/browser/usb/usb_tab_helper.h" +#include <memory> #include <utility> -#include "base/memory/scoped_ptr.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/usb/web_usb_permission_provider.h" @@ -24,11 +24,11 @@ DEFINE_WEB_CONTENTS_USER_DATA_KEY(UsbTabHelper); struct FrameUsbServices { - scoped_ptr<WebUSBPermissionProvider> permission_provider; + std::unique_ptr<WebUSBPermissionProvider> permission_provider; #if defined(OS_ANDROID) - scoped_ptr<WebUsbChooserServiceAndroid> chooser_service; + std::unique_ptr<WebUsbChooserServiceAndroid> chooser_service; #else - scoped_ptr<WebUsbChooserService> chooser_service; + std::unique_ptr<WebUsbChooserService> chooser_service; #endif // defined(OS_ANDROID) int device_connection_count_ = 0; }; @@ -98,7 +98,8 @@ FrameUsbServicesMap::const_iterator it = frame_usb_services_.find(render_frame_host); if (it == frame_usb_services_.end()) { - scoped_ptr<FrameUsbServices> frame_usb_services(new FrameUsbServices()); + std::unique_ptr<FrameUsbServices> frame_usb_services( + new FrameUsbServices()); it = (frame_usb_services_.insert( std::make_pair(render_frame_host, std::move(frame_usb_services)))) .first;
diff --git a/chrome/browser/usb/usb_tab_helper.h b/chrome/browser/usb/usb_tab_helper.h index 21ca986..022a05e 100644 --- a/chrome/browser/usb/usb_tab_helper.h +++ b/chrome/browser/usb/usb_tab_helper.h
@@ -22,7 +22,7 @@ struct FrameUsbServices; -typedef std::map<content::RenderFrameHost*, scoped_ptr<FrameUsbServices>> +typedef std::map<content::RenderFrameHost*, std::unique_ptr<FrameUsbServices>> FrameUsbServicesMap; // Per-tab owner of USB services provided to render frames within that tab.
diff --git a/chrome/browser/usb/web_usb_chooser_service.cc b/chrome/browser/usb/web_usb_chooser_service.cc index b035b48..1acb7a7 100644 --- a/chrome/browser/usb/web_usb_chooser_service.cc +++ b/chrome/browser/usb/web_usb_chooser_service.cc
@@ -33,7 +33,7 @@ content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host_); Browser* browser = chrome::FindBrowserWithWebContents(web_contents); - scoped_ptr<UsbChooserBubbleController> bubble_controller( + std::unique_ptr<UsbChooserBubbleController> bubble_controller( new UsbChooserBubbleController(render_frame_host_, std::move(device_filters), render_frame_host_, callback));
diff --git a/chrome/browser/web_applications/update_shortcut_worker_win.h b/chrome/browser/web_applications/update_shortcut_worker_win.h index 1aae4dd..52857b1 100644 --- a/chrome/browser/web_applications/update_shortcut_worker_win.h +++ b/chrome/browser/web_applications/update_shortcut_worker_win.h
@@ -72,7 +72,7 @@ web_app::IconInfoList unprocessed_icons_; // Cached shortcut data from the web_contents_. - scoped_ptr<web_app::ShortcutInfo> shortcut_info_; + std::unique_ptr<web_app::ShortcutInfo> shortcut_info_; // Our copy of profile path. base::FilePath profile_path_;
diff --git a/chrome/browser/web_applications/web_app.cc b/chrome/browser/web_applications/web_app.cc index e6ae026..ee28b485 100644 --- a/chrome/browser/web_applications/web_app.cc +++ b/chrome/browser/web_applications/web_app.cc
@@ -88,7 +88,7 @@ void UpdateAllShortcutsForShortcutInfo( const base::string16& old_app_title, const base::Closure& callback, - scoped_ptr<web_app::ShortcutInfo> shortcut_info, + std::unique_ptr<web_app::ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info) { base::FilePath shortcut_data_dir = GetShortcutDataDir(*shortcut_info); base::Closure task = base::Bind( @@ -102,7 +102,7 @@ } } -void OnImageLoaded(scoped_ptr<web_app::ShortcutInfo> shortcut_info, +void OnImageLoaded(std::unique_ptr<web_app::ShortcutInfo> shortcut_info, extensions::FileHandlersInfo file_handlers_info, web_app::InfoCallback callback, const gfx::ImageFamily& image_family) { @@ -129,7 +129,7 @@ void IgnoreFileHandlersInfo( const web_app::ShortcutInfoCallback& shortcut_info_callback, - scoped_ptr<web_app::ShortcutInfo> shortcut_info, + std::unique_ptr<web_app::ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info) { shortcut_info_callback.Run(std::move(shortcut_info)); } @@ -137,7 +137,7 @@ void ScheduleCreatePlatformShortcut( web_app::ShortcutCreationReason reason, const web_app::ShortcutLocations& locations, - scoped_ptr<web_app::ShortcutInfo> shortcut_info, + std::unique_ptr<web_app::ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info) { base::FilePath shortcut_data_dir = GetShortcutDataDir(*shortcut_info); BrowserThread::PostTask( @@ -184,7 +184,7 @@ } #if defined(TOOLKIT_VIEWS) -scoped_ptr<ShortcutInfo> GetShortcutInfoForTab( +std::unique_ptr<ShortcutInfo> GetShortcutInfoForTab( content::WebContents* web_contents) { const favicon::FaviconDriver* favicon_driver = favicon::ContentFaviconDriver::FromWebContents(web_contents); @@ -192,7 +192,7 @@ extensions::TabHelper::FromWebContents(web_contents); const WebApplicationInfo& app_info = extensions_tab_helper->web_app_info(); - scoped_ptr<ShortcutInfo> info(new ShortcutInfo); + std::unique_ptr<ShortcutInfo> info(new ShortcutInfo); info->url = app_info.app_url.is_empty() ? web_contents->GetURL() : app_info.app_url; info->title = app_info.title.empty() ? @@ -214,10 +214,10 @@ void UpdateShortcutForTabContents(content::WebContents* web_contents) {} #endif -scoped_ptr<ShortcutInfo> ShortcutInfoForExtensionAndProfile( +std::unique_ptr<ShortcutInfo> ShortcutInfoForExtensionAndProfile( const extensions::Extension* app, Profile* profile) { - scoped_ptr<ShortcutInfo> shortcut_info(new ShortcutInfo); + std::unique_ptr<ShortcutInfo> shortcut_info(new ShortcutInfo); shortcut_info->extension_id = app->id(); shortcut_info->is_platform_app = app->is_platform_app(); @@ -241,7 +241,7 @@ void GetInfoForApp(const extensions::Extension* extension, Profile* profile, const InfoCallback& callback) { - scoped_ptr<web_app::ShortcutInfo> shortcut_info( + std::unique_ptr<web_app::ShortcutInfo> shortcut_info( web_app::ShortcutInfoForExtensionAndProfile(extension, profile)); const std::vector<extensions::FileHandlerInfo>* file_handlers = extensions::FileHandlers::GetFileHandlers(extension); @@ -410,7 +410,7 @@ void CreateShortcutsWithInfo( ShortcutCreationReason reason, const ShortcutLocations& locations, - scoped_ptr<ShortcutInfo> shortcut_info, + std::unique_ptr<ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -438,7 +438,7 @@ } void CreateNonAppShortcut(const ShortcutLocations& locations, - scoped_ptr<ShortcutInfo> shortcut_info) { + std::unique_ptr<ShortcutInfo> shortcut_info) { ScheduleCreatePlatformShortcut(SHORTCUT_CREATION_AUTOMATED, locations, std::move(shortcut_info), extensions::FileHandlersInfo()); @@ -460,7 +460,7 @@ void DeleteAllShortcuts(Profile* profile, const extensions::Extension* app) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - scoped_ptr<ShortcutInfo> shortcut_info( + std::unique_ptr<ShortcutInfo> shortcut_info( ShortcutInfoForExtensionAndProfile(app, profile)); base::FilePath shortcut_data_dir = GetShortcutDataDir(*shortcut_info); BrowserThread::PostTask(
diff --git a/chrome/browser/web_applications/web_app.h b/chrome/browser/web_applications/web_app.h index 6a4ccb0..61d099c 100644 --- a/chrome/browser/web_applications/web_app.h +++ b/chrome/browser/web_applications/web_app.h
@@ -5,13 +5,13 @@ #ifndef CHROME_BROWSER_WEB_APPLICATIONS_WEB_APP_H_ #define CHROME_BROWSER_WEB_APPLICATIONS_WEB_APP_H_ +#include <memory> #include <string> #include <vector> #include "base/callback.h" #include "base/files/file_path.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "build/build_config.h" #include "chrome/browser/shell_integration.h" @@ -107,15 +107,17 @@ }; // Called by GetInfoForApp after fetching the ShortcutInfo and FileHandlersInfo. -typedef base::Callback<void(scoped_ptr<ShortcutInfo>, - const extensions::FileHandlersInfo&)> InfoCallback; +typedef base::Callback<void(std::unique_ptr<ShortcutInfo>, + const extensions::FileHandlersInfo&)> + InfoCallback; // Called by GetShortcutInfoForApp after fetching the ShortcutInfo. -typedef base::Callback<void(scoped_ptr<ShortcutInfo>)> ShortcutInfoCallback; +typedef base::Callback<void(std::unique_ptr<ShortcutInfo>)> + ShortcutInfoCallback; #if defined(TOOLKIT_VIEWS) // Extracts shortcut info of the given WebContents. -scoped_ptr<ShortcutInfo> GetShortcutInfoForTab( +std::unique_ptr<ShortcutInfo> GetShortcutInfoForTab( content::WebContents* web_contents); #endif @@ -126,7 +128,7 @@ // updates (recreates) them if they exits. void UpdateShortcutForTabContents(content::WebContents* web_contents); -scoped_ptr<ShortcutInfo> ShortcutInfoForExtensionAndProfile( +std::unique_ptr<ShortcutInfo> ShortcutInfoForExtensionAndProfile( const extensions::Extension* app, Profile* profile); @@ -182,13 +184,13 @@ void CreateShortcutsWithInfo( ShortcutCreationReason reason, const ShortcutLocations& locations, - scoped_ptr<ShortcutInfo> shortcut_info, + std::unique_ptr<ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info); // Currently only called by app_list_service_mac to create a shim for the // app launcher. void CreateNonAppShortcut(const ShortcutLocations& locations, - scoped_ptr<ShortcutInfo> shortcut_info); + std::unique_ptr<ShortcutInfo> shortcut_info); // Creates shortcuts for an app. This loads the app's icon from disk, and calls // CreateShortcutsWithInfo(). If you already have a ShortcutInfo with the app's @@ -251,7 +253,7 @@ // |creation_locations| contains information about where to create them. bool CreatePlatformShortcuts( const base::FilePath& shortcut_data_path, - scoped_ptr<ShortcutInfo> shortcut_info, + std::unique_ptr<ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info, const ShortcutLocations& creation_locations, ShortcutCreationReason creation_reason); @@ -260,7 +262,7 @@ // platform specific implementation of the DeleteAllShortcuts function, and // is executed on the FILE thread. void DeletePlatformShortcuts(const base::FilePath& shortcut_data_path, - scoped_ptr<ShortcutInfo> shortcut_info); + std::unique_ptr<ShortcutInfo> shortcut_info); // Updates all the shortcuts we have added for this extension. This is the // platform specific implementation of the UpdateAllShortcuts function, and @@ -268,7 +270,7 @@ void UpdatePlatformShortcuts( const base::FilePath& shortcut_data_path, const base::string16& old_app_title, - scoped_ptr<ShortcutInfo> shortcut_info, + std::unique_ptr<ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info); // Delete all the shortcuts for an entire profile.
diff --git a/chrome/browser/web_applications/web_app_chromeos.cc b/chrome/browser/web_applications/web_app_chromeos.cc index e86b9eb..4c660f4 100644 --- a/chrome/browser/web_applications/web_app_chromeos.cc +++ b/chrome/browser/web_applications/web_app_chromeos.cc
@@ -15,7 +15,7 @@ bool CreatePlatformShortcuts( const base::FilePath& web_app_path, - scoped_ptr<ShortcutInfo> shortcut_info, + std::unique_ptr<ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info, const ShortcutLocations& creation_locations, ShortcutCreationReason creation_reason) { @@ -23,12 +23,12 @@ } void DeletePlatformShortcuts(const base::FilePath& web_app_path, - scoped_ptr<ShortcutInfo> shortcut_info) {} + std::unique_ptr<ShortcutInfo> shortcut_info) {} void UpdatePlatformShortcuts( const base::FilePath& web_app_path, const base::string16& old_app_title, - scoped_ptr<ShortcutInfo> shortcut_info, + std::unique_ptr<ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info) {} void DeleteAllShortcutsForProfile(const base::FilePath& profile_path) {}
diff --git a/chrome/browser/web_applications/web_app_linux.cc b/chrome/browser/web_applications/web_app_linux.cc index 2a6e813..f1b1b5e 100644 --- a/chrome/browser/web_applications/web_app_linux.cc +++ b/chrome/browser/web_applications/web_app_linux.cc
@@ -23,7 +23,7 @@ bool CreatePlatformShortcuts( const base::FilePath& web_app_path, - scoped_ptr<ShortcutInfo> shortcut_info, + std::unique_ptr<ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info, const ShortcutLocations& creation_locations, ShortcutCreationReason /*creation_reason*/) { @@ -37,7 +37,7 @@ } void DeletePlatformShortcuts(const base::FilePath& web_app_path, - scoped_ptr<ShortcutInfo> shortcut_info) { + std::unique_ptr<ShortcutInfo> shortcut_info) { #if !defined(OS_CHROMEOS) shell_integration_linux::DeleteDesktopShortcuts(shortcut_info->profile_path, shortcut_info->extension_id); @@ -47,11 +47,11 @@ void UpdatePlatformShortcuts( const base::FilePath& web_app_path, const base::string16& /*old_app_title*/, - scoped_ptr<ShortcutInfo> shortcut_info, + std::unique_ptr<ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info) { DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); - scoped_ptr<base::Environment> env(base::Environment::Create()); + std::unique_ptr<base::Environment> env(base::Environment::Create()); // Find out whether shortcuts are already installed. ShortcutLocations creation_locations =
diff --git a/chrome/browser/web_applications/web_app_mac.h b/chrome/browser/web_applications/web_app_mac.h index 3e5a1a97..791ab22 100644 --- a/chrome/browser/web_applications/web_app_mac.h +++ b/chrome/browser/web_applications/web_app_mac.h
@@ -7,13 +7,13 @@ #include <stddef.h> +#include <memory> #include <string> #include <vector> #include "base/files/file_path.h" #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/web_applications/web_app.h" #include "extensions/common/manifest_handlers/file_handler_info.h" @@ -33,7 +33,7 @@ base::FilePath GetAppInstallPath(const ShortcutInfo& shortcut_info); // If necessary, launch the shortcut for an app. -void MaybeLaunchShortcut(scoped_ptr<ShortcutInfo> shortcut_info); +void MaybeLaunchShortcut(std::unique_ptr<ShortcutInfo> shortcut_info); // Rebuild the shortcut and relaunch it. bool MaybeRebuildShortcut(const base::CommandLine& command_line);
diff --git a/chrome/browser/web_applications/web_app_mac.mm b/chrome/browser/web_applications/web_app_mac.mm index 48b5a5d..71f7d2ae 100644 --- a/chrome/browser/web_applications/web_app_mac.mm +++ b/chrome/browser/web_applications/web_app_mac.mm
@@ -255,8 +255,9 @@ user_data_dir.value(), base::CompareCase::SENSITIVE); } -void LaunchShimOnFileThread(scoped_ptr<web_app::ShortcutInfo> shortcut_info, - bool launched_after_rebuild) { +void LaunchShimOnFileThread( + std::unique_ptr<web_app::ShortcutInfo> shortcut_info, + bool launched_after_rebuild) { DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); base::FilePath shim_path = web_app::GetAppInstallPath(*shortcut_info); @@ -306,7 +307,7 @@ } void UpdateAndLaunchShimOnFileThread( - scoped_ptr<web_app::ShortcutInfo> shortcut_info, + std::unique_ptr<web_app::ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info) { base::FilePath shortcut_data_dir = web_app::GetWebAppDataDirectory( shortcut_info->profile_path, shortcut_info->extension_id, GURL()); @@ -316,7 +317,7 @@ } void UpdateAndLaunchShim( - scoped_ptr<web_app::ShortcutInfo> shortcut_info, + std::unique_ptr<web_app::ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info) { content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, @@ -324,7 +325,7 @@ file_handlers_info)); } -void RebuildAppAndLaunch(scoped_ptr<web_app::ShortcutInfo> shortcut_info) { +void RebuildAppAndLaunch(std::unique_ptr<web_app::ShortcutInfo> shortcut_info) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (shortcut_info->extension_id == app_mode::kAppListModeId) { AppListService* app_list_service = AppListService::Get(); @@ -520,11 +521,12 @@ return bundle_paths; } -scoped_ptr<web_app::ShortcutInfo> BuildShortcutInfoFromBundle( +std::unique_ptr<web_app::ShortcutInfo> BuildShortcutInfoFromBundle( const base::FilePath& bundle_path) { NSDictionary* plist = ReadPlist(GetPlistPath(bundle_path)); - scoped_ptr<web_app::ShortcutInfo> shortcut_info(new web_app::ShortcutInfo); + std::unique_ptr<web_app::ShortcutInfo> shortcut_info( + new web_app::ShortcutInfo); shortcut_info->extension_id = base::SysNSStringToUTF8( [plist valueForKey:app_mode::kCrAppModeShortcutIDKey]); shortcut_info->is_platform_app = true; @@ -549,7 +551,7 @@ return shortcut_info; } -scoped_ptr<web_app::ShortcutInfo> RecordAppShimErrorAndBuildShortcutInfo( +std::unique_ptr<web_app::ShortcutInfo> RecordAppShimErrorAndBuildShortcutInfo( const base::FilePath& bundle_path) { NSDictionary* plist = ReadPlist(GetPlistPath(bundle_path)); NSString* version_string = [plist valueForKey:app_mode::kCrBundleVersionKey]; @@ -611,7 +613,7 @@ } void RevealAppShimInFinderForAppOnFileThread( - scoped_ptr<web_app::ShortcutInfo> shortcut_info, + std::unique_ptr<web_app::ShortcutInfo> shortcut_info, const base::FilePath& app_path) { web_app::WebAppShortcutCreator shortcut_creator( app_path, shortcut_info.get(), extensions::FileHandlersInfo()); @@ -1119,7 +1121,7 @@ return shortcut_creator.GetApplicationsShortcutPath(); } -void MaybeLaunchShortcut(scoped_ptr<ShortcutInfo> shortcut_info) { +void MaybeLaunchShortcut(std::unique_ptr<ShortcutInfo> shortcut_info) { if (AppShimsDisabledForTest() && !g_app_shims_allow_update_and_launch_in_tests) { return; @@ -1149,7 +1151,7 @@ Profile* profile, const extensions::Extension* app, const base::Callback<void(bool)>& close_callback, - scoped_ptr<ShortcutInfo> shortcut_info) { + std::unique_ptr<ShortcutInfo> shortcut_info) { base::scoped_nsobject<NSAlert> alert([[NSAlert alloc] init]); NSButton* continue_button = [alert @@ -1217,7 +1219,7 @@ scoped_refptr<Latch> latch = new Latch(callback); // Update all apps. - scoped_ptr<extensions::ExtensionSet> candidates = + std::unique_ptr<extensions::ExtensionSet> candidates = registry->GenerateInstalledExtensionsSet(); for (auto& extension_refptr : *candidates) { const extensions::Extension* extension = extension_refptr.get(); @@ -1230,7 +1232,7 @@ void RevealAppShimInFinderForApp(Profile* profile, const extensions::Extension* app) { - scoped_ptr<web_app::ShortcutInfo> shortcut_info = + std::unique_ptr<web_app::ShortcutInfo> shortcut_info = ShortcutInfoForExtensionAndProfile(app, profile); content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, @@ -1242,7 +1244,7 @@ bool CreatePlatformShortcuts( const base::FilePath& app_data_path, - scoped_ptr<ShortcutInfo> shortcut_info, + std::unique_ptr<ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info, const ShortcutLocations& creation_locations, ShortcutCreationReason creation_reason) { @@ -1256,7 +1258,7 @@ } void DeletePlatformShortcuts(const base::FilePath& app_data_path, - scoped_ptr<ShortcutInfo> shortcut_info) { + std::unique_ptr<ShortcutInfo> shortcut_info) { DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); WebAppShortcutCreator shortcut_creator(app_data_path, shortcut_info.get(), extensions::FileHandlersInfo()); @@ -1266,7 +1268,7 @@ void UpdatePlatformShortcuts( const base::FilePath& app_data_path, const base::string16& old_app_title, - scoped_ptr<ShortcutInfo> shortcut_info, + std::unique_ptr<ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info) { UpdatePlatformShortcutsInternal(app_data_path, old_app_title, *shortcut_info, file_handlers_info); @@ -1279,7 +1281,7 @@ for (std::vector<base::FilePath>::const_iterator it = bundles.begin(); it != bundles.end(); ++it) { - scoped_ptr<web_app::ShortcutInfo> shortcut_info = + std::unique_ptr<web_app::ShortcutInfo> shortcut_info = BuildShortcutInfoFromBundle(*it); WebAppShortcutCreator shortcut_creator(it->DirName(), shortcut_info.get(), extensions::FileHandlersInfo());
diff --git a/chrome/browser/web_applications/web_app_mac_unittest.mm b/chrome/browser/web_applications/web_app_mac_unittest.mm index 7a8815d..0be32b8 100644 --- a/chrome/browser/web_applications/web_app_mac_unittest.mm +++ b/chrome/browser/web_applications/web_app_mac_unittest.mm
@@ -9,13 +9,14 @@ #include <stddef.h> #include <sys/xattr.h> +#include <memory> + #include "base/command_line.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/mac/foundation_util.h" #include "base/mac/scoped_nsobject.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" @@ -63,8 +64,8 @@ DISALLOW_COPY_AND_ASSIGN(WebAppShortcutCreatorMock); }; -scoped_ptr<web_app::ShortcutInfo> GetShortcutInfo() { - scoped_ptr<web_app::ShortcutInfo> info(new web_app::ShortcutInfo); +std::unique_ptr<web_app::ShortcutInfo> GetShortcutInfo() { + std::unique_ptr<web_app::ShortcutInfo> info(new web_app::ShortcutInfo); info->extension_id = "extensionid"; info->extension_path = base::FilePath("/fake/extension/path"); info->title = base::ASCIIToUTF16("Shortcut Title"); @@ -100,7 +101,7 @@ base::FilePath app_data_dir_; base::FilePath destination_dir_; - scoped_ptr<web_app::ShortcutInfo> info_; + std::unique_ptr<web_app::ShortcutInfo> info_; base::FilePath shim_base_name_; base::FilePath internal_shim_path_; base::FilePath shim_path_;
diff --git a/chrome/browser/web_applications/web_app_unittest.cc b/chrome/browser/web_applications/web_app_unittest.cc index 2cf437b..d88ed6b4 100644 --- a/chrome/browser/web_applications/web_app_unittest.cc +++ b/chrome/browser/web_applications/web_app_unittest.cc
@@ -4,8 +4,9 @@ #include "chrome/browser/web_applications/web_app.h" +#include <memory> + #include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/web_applications/web_app.h" @@ -46,7 +47,7 @@ ->InitializeRenderFrameIfNeeded(); RenderViewHostTester::TestOnMessageReceived( rvh(), ChromeViewHostMsg_DidGetWebApplicationInfo(0, web_app_info)); - scoped_ptr<web_app::ShortcutInfo> info = + std::unique_ptr<web_app::ShortcutInfo> info = web_app::GetShortcutInfoForTab(web_contents()); EXPECT_EQ(title, info->title);
diff --git a/chrome/browser/web_applications/web_app_win.cc b/chrome/browser/web_applications/web_app_win.cc index bd267ef..cee81b3 100644 --- a/chrome/browser/web_applications/web_app_win.cc +++ b/chrome/browser/web_applications/web_app_win.cc
@@ -7,13 +7,14 @@ #include <shlobj.h> #include <stddef.h> +#include <memory> + #include "base/command_line.h" #include "base/files/file_enumerator.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/macros.h" #include "base/md5.h" -#include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/strings/string16.h" #include "base/strings/string_piece.h" @@ -337,7 +338,7 @@ void CreateIconAndSetRelaunchDetails( const base::FilePath& web_app_path, const base::FilePath& icon_file, - scoped_ptr<web_app::ShortcutInfo> shortcut_info, + std::unique_ptr<web_app::ShortcutInfo> shortcut_info, HWND hwnd) { DCHECK(content::BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread()); @@ -364,7 +365,7 @@ void OnShortcutInfoLoadedForSetRelaunchDetails( HWND hwnd, - scoped_ptr<web_app::ShortcutInfo> shortcut_info) { + std::unique_ptr<web_app::ShortcutInfo> shortcut_info) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // Set window's icon to the one we're about to create/update in the web app @@ -385,7 +386,7 @@ base::FilePath CreateShortcutInWebAppDir( const base::FilePath& web_app_dir, - scoped_ptr<ShortcutInfo> shortcut_info) { + std::unique_ptr<ShortcutInfo> shortcut_info) { std::vector<base::FilePath> paths; paths.push_back(web_app_dir); std::vector<base::FilePath> out_filenames; @@ -442,7 +443,7 @@ bool CreatePlatformShortcuts( const base::FilePath& web_app_path, - scoped_ptr<ShortcutInfo> shortcut_info, + std::unique_ptr<ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info, const ShortcutLocations& creation_locations, ShortcutCreationReason creation_reason) { @@ -489,7 +490,7 @@ void UpdatePlatformShortcuts( const base::FilePath& web_app_path, const base::string16& old_app_title, - scoped_ptr<ShortcutInfo> shortcut_info, + std::unique_ptr<ShortcutInfo> shortcut_info, const extensions::FileHandlersInfo& file_handlers_info) { DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); @@ -528,7 +529,7 @@ } void DeletePlatformShortcuts(const base::FilePath& web_app_path, - scoped_ptr<ShortcutInfo> shortcut_info) { + std::unique_ptr<ShortcutInfo> shortcut_info) { GetShortcutLocationsAndDeleteShortcuts(web_app_path, shortcut_info->profile_path, shortcut_info->title, NULL, NULL);
diff --git a/chrome/browser/web_applications/web_app_win.h b/chrome/browser/web_applications/web_app_win.h index 08bb704..414d058 100644 --- a/chrome/browser/web_applications/web_app_win.h +++ b/chrome/browser/web_applications/web_app_win.h
@@ -28,7 +28,7 @@ // created shortcut. base::FilePath CreateShortcutInWebAppDir( const base::FilePath& web_app_path, - scoped_ptr<ShortcutInfo> shortcut_info); + std::unique_ptr<ShortcutInfo> shortcut_info); // Update the relaunch details for the given app's window, making the taskbar // group's "Pin to the taskbar" button function correctly.
diff --git a/chrome/chrome_browser.gypi b/chrome/chrome_browser.gypi index 2142bab..563312d 100644 --- a/chrome/chrome_browser.gypi +++ b/chrome/chrome_browser.gypi
@@ -607,6 +607,10 @@ 'browser/storage/storage_info_fetcher.h', 'browser/tab_contents/navigation_metrics_recorder.cc', 'browser/tab_contents/navigation_metrics_recorder.h', + 'browser/tab_contents/origins_seen_service.cc', + 'browser/tab_contents/origins_seen_service.h', + 'browser/tab_contents/origins_seen_service_factory.cc', + 'browser/tab_contents/origins_seen_service_factory.h', 'browser/tab_contents/retargeting_details.h', 'browser/tab_contents/tab_util.cc', 'browser/tab_contents/tab_util.h',
diff --git a/chrome/chrome_browser_chromeos.gypi b/chrome/chrome_browser_chromeos.gypi index e659a43..d2533c2 100644 --- a/chrome/chrome_browser_chromeos.gypi +++ b/chrome/chrome_browser_chromeos.gypi
@@ -765,6 +765,8 @@ 'browser/chromeos/policy/affiliated_invalidation_service_provider_impl.h', 'browser/chromeos/policy/auto_enrollment_client.cc', 'browser/chromeos/policy/auto_enrollment_client.h', + 'browser/chromeos/policy/bluetooth_policy_handler.cc', + 'browser/chromeos/policy/bluetooth_policy_handler.h', 'browser/chromeos/policy/browser_policy_connector_chromeos.cc', 'browser/chromeos/policy/browser_policy_connector_chromeos.h', 'browser/chromeos/policy/cloud_external_data_manager_base.cc',
diff --git a/chrome/chrome_browser_ui.gypi b/chrome/chrome_browser_ui.gypi index 875617171..d53b887 100644 --- a/chrome/chrome_browser_ui.gypi +++ b/chrome/chrome_browser_ui.gypi
@@ -501,6 +501,10 @@ 'browser/ui/webui/popular_sites_internals_message_handler.h', 'browser/ui/webui/popular_sites_internals_ui.cc', 'browser/ui/webui/popular_sites_internals_ui.h', + 'browser/ui/webui/snippets_internals_message_handler.cc', + 'browser/ui/webui/snippets_internals_message_handler.h', + 'browser/ui/webui/snippets_internals_ui.cc', + 'browser/ui/webui/snippets_internals_ui.h', ], # Cross-platform ash sources. 'chrome_browser_ui_ash_sources': [ @@ -2030,6 +2034,8 @@ 'browser/ui/webui/settings/md_settings_ui.h', 'browser/ui/webui/settings/people_handler.cc', 'browser/ui/webui/settings/people_handler.h', + 'browser/ui/webui/settings/profile_info_handler.cc', + 'browser/ui/webui/settings/profile_info_handler.h', 'browser/ui/webui/settings/reset_settings_handler.cc', 'browser/ui/webui/settings/reset_settings_handler.h', 'browser/ui/webui/settings/search_engines_handler.cc',
diff --git a/chrome/chrome_installer.gypi b/chrome/chrome_installer.gypi index dc4cb53..076ed78 100644 --- a/chrome/chrome_installer.gypi +++ b/chrome/chrome_installer.gypi
@@ -107,6 +107,7 @@ 'installer/util/beacons_unittest.cc', 'installer/util/callback_work_item_unittest.cc', 'installer/util/channel_info_unittest.cc', + 'installer/util/conditional_work_item_list_unittest.cc', 'installer/util/copy_tree_work_item_unittest.cc', 'installer/util/create_dir_work_item_unittest.cc', 'installer/util/create_reg_key_work_item_unittest.cc', @@ -147,6 +148,8 @@ 'installer/util/uninstall_metrics_unittest.cc', 'installer/util/wmi_unittest.cc', 'installer/util/work_item_list_unittest.cc', + 'installer/util/work_item_mocks.cc', + 'installer/util/work_item_mocks.h', ], 'msvs_settings': { 'VCManifestTool': {
diff --git a/chrome/chrome_tests_unit.gypi b/chrome/chrome_tests_unit.gypi index 486fd976..3e72ea55 100644 --- a/chrome/chrome_tests_unit.gypi +++ b/chrome/chrome_tests_unit.gypi
@@ -1571,6 +1571,7 @@ 'browser/ui/webui/settings_utils_unittest.cc', 'browser/ui/webui/settings/settings_manage_profile_handler_unittest.cc', 'browser/ui/webui/settings/people_handler_unittest.cc', + 'browser/ui/webui/settings/profile_info_handler_unittest.cc', 'browser/ui/webui/settings/reset_settings_handler_unittest.cc', 'browser/ui/webui/settings/site_settings_handler_unittest.cc', 'browser/ui/webui/signin/login_ui_service_unittest.cc',
diff --git a/chrome/common/safe_browsing/download_protection_util.cc b/chrome/common/safe_browsing/download_protection_util.cc index c90a9f4..381ae51 100644 --- a/chrome/common/safe_browsing/download_protection_util.cc +++ b/chrome/common/safe_browsing/download_protection_util.cc
@@ -270,7 +270,18 @@ EXTENSION_SEARCH_MS, EXTENSION_IMG, EXTENSION_SMI, - + EXTENSION_SPARSEBUNDLE, + EXTENSION_SPARSEIMAGE, + EXTENSION_CDR, + EXTENSION_DMGPART, + EXTENSION_DVDR, + EXTENSION_DART, + EXTENSION_DC42, + EXTENSION_DISKCOPY42, + EXTENSION_IMGPART, + EXTENSION_NDIF, + EXTENSION_UDIF, + EXTENSION_TOAST, // New values go above this one. EXTENSION_MAX }; @@ -309,6 +320,7 @@ {FILE_PATH_LITERAL(".bz2"), EXTENSION_BZ2, true, true}, {FILE_PATH_LITERAL(".bzip2"), EXTENSION_BZIP2, true, true}, {FILE_PATH_LITERAL(".cab"), EXTENSION_CAB, true, true}, + {FILE_PATH_LITERAL(".cdr"), EXTENSION_CDR, true, false}, {FILE_PATH_LITERAL(".cfg"), EXTENSION_CFG, true, false}, {FILE_PATH_LITERAL(".chi"), EXTENSION_CHI, true, false}, {FILE_PATH_LITERAL(".chm"), EXTENSION_CHM, true, false}, @@ -321,11 +333,16 @@ {FILE_PATH_LITERAL(".crt"), EXTENSION_CRT, true, false}, {FILE_PATH_LITERAL(".crx"), EXTENSION_CRX, true, false}, {FILE_PATH_LITERAL(".csh"), EXTENSION_CSH, true, false}, + {FILE_PATH_LITERAL(".dart"), EXTENSION_DART, true, false}, + {FILE_PATH_LITERAL(".dc42"), EXTENSION_DC42, true, false}, {FILE_PATH_LITERAL(".deb"), EXTENSION_DEB, true, false}, {FILE_PATH_LITERAL(".dex"), EXTENSION_DEX, true, false}, + {FILE_PATH_LITERAL(".diskcopy42"), EXTENSION_DISKCOPY42, true, false}, {FILE_PATH_LITERAL(".dll"), EXTENSION_DLL, true, false}, {FILE_PATH_LITERAL(".dmg"), EXTENSION_DMG, true, false}, + {FILE_PATH_LITERAL(".dmgpart"), EXTENSION_DMGPART, true, false}, {FILE_PATH_LITERAL(".drv"), EXTENSION_DRV, true, false}, + {FILE_PATH_LITERAL(".dvdr"), EXTENSION_DVDR, true, false}, {FILE_PATH_LITERAL(".efi"), EXTENSION_EFI, true, false}, {FILE_PATH_LITERAL(".eml"), EXTENSION_EML, true, false}, {FILE_PATH_LITERAL(".exe"), EXTENSION_EXE, true, false}, @@ -342,6 +359,7 @@ {FILE_PATH_LITERAL(".hta"), EXTENSION_HTA, true, false}, {FILE_PATH_LITERAL(".htt"), EXTENSION_HTT, true, false}, {FILE_PATH_LITERAL(".img"), EXTENSION_IMG, true, false}, + {FILE_PATH_LITERAL(".imgpart"), EXTENSION_IMGPART, true, false}, {FILE_PATH_LITERAL(".inf"), EXTENSION_INF, true, false}, {FILE_PATH_LITERAL(".ini"), EXTENSION_INI, true, false}, {FILE_PATH_LITERAL(".ins"), EXTENSION_INS, true, false}, @@ -398,6 +416,7 @@ {FILE_PATH_LITERAL(".msi"), EXTENSION_MSI, true, false}, {FILE_PATH_LITERAL(".msp"), EXTENSION_MSP, true, false}, {FILE_PATH_LITERAL(".mst"), EXTENSION_MST, true, false}, + {FILE_PATH_LITERAL(".ndif"), EXTENSION_NDIF, true, false}, {FILE_PATH_LITERAL(".ntfs"), EXTENSION_NTFS, true, true}, {FILE_PATH_LITERAL(".ocx"), EXTENSION_OCX, true, false}, {FILE_PATH_LITERAL(".ops"), EXTENSION_OPS, true, false}, @@ -478,6 +497,8 @@ {FILE_PATH_LITERAL(".shs"), EXTENSION_SHS, true, false}, {FILE_PATH_LITERAL(".slp"), EXTENSION_SLP, true, true}, {FILE_PATH_LITERAL(".smi"), EXTENSION_SMI, true, false}, + {FILE_PATH_LITERAL(".sparsebundle"), EXTENSION_SPARSEBUNDLE, true, false}, + {FILE_PATH_LITERAL(".sparseimage"), EXTENSION_SPARSEIMAGE, true, false}, {FILE_PATH_LITERAL(".spl"), EXTENSION_SPL, true, false}, {FILE_PATH_LITERAL(".squashfs"), EXTENSION_SQUASHFS, true, true}, {FILE_PATH_LITERAL(".svg"), EXTENSION_SVG, true, false}, @@ -490,12 +511,14 @@ {FILE_PATH_LITERAL(".tbz2"), EXTENSION_TBZ2, true, true}, {FILE_PATH_LITERAL(".tcsh"), EXTENSION_TCSH, true, false}, {FILE_PATH_LITERAL(".tgz"), EXTENSION_TGZ, true, true}, + {FILE_PATH_LITERAL(".toast"), EXTENSION_TOAST, true, false}, {FILE_PATH_LITERAL(".torrent"), EXTENSION_TORRENT, true, false}, {FILE_PATH_LITERAL(".tpz"), EXTENSION_TPZ, true, true}, {FILE_PATH_LITERAL(".txz"), EXTENSION_TXZ, true, true}, {FILE_PATH_LITERAL(".tz"), EXTENSION_TZ, true, true}, {FILE_PATH_LITERAL(".u3p"), EXTENSION_U3P, false, false}, // UMA only. {FILE_PATH_LITERAL(".udf"), EXTENSION_UDF, true, true}, + {FILE_PATH_LITERAL(".udif"), EXTENSION_UDIF, true, false}, {FILE_PATH_LITERAL(".url"), EXTENSION_URL, true, false}, {FILE_PATH_LITERAL(".uu"), EXTENSION_UU, true, true}, {FILE_PATH_LITERAL(".uue"), EXTENSION_UUE, true, true}, @@ -601,7 +624,19 @@ file.MatchesExtension(FILE_PATH_LITERAL(".pkg")) || file.MatchesExtension(FILE_PATH_LITERAL(".smi")) || file.MatchesExtension(FILE_PATH_LITERAL(".osx")) || - file.MatchesExtension(FILE_PATH_LITERAL(".app"))) + file.MatchesExtension(FILE_PATH_LITERAL(".app")) || + file.MatchesExtension(FILE_PATH_LITERAL(".cdr")) || + file.MatchesExtension(FILE_PATH_LITERAL(".dmgpart")) || + file.MatchesExtension(FILE_PATH_LITERAL(".dvdr")) || + file.MatchesExtension(FILE_PATH_LITERAL(".dart")) || + file.MatchesExtension(FILE_PATH_LITERAL(".dc42")) || + file.MatchesExtension(FILE_PATH_LITERAL(".diskcopy42")) || + file.MatchesExtension(FILE_PATH_LITERAL(".imgpart")) || + file.MatchesExtension(FILE_PATH_LITERAL(".ndif")) || + file.MatchesExtension(FILE_PATH_LITERAL(".udif")) || + file.MatchesExtension(FILE_PATH_LITERAL(".toast")) || + file.MatchesExtension(FILE_PATH_LITERAL(".sparsebundle")) || + file.MatchesExtension(FILE_PATH_LITERAL(".sparseimage"))) return ClientDownloadRequest::MAC_EXECUTABLE; else if (IsArchiveFile(file)) return ClientDownloadRequest::ARCHIVE;
diff --git a/chrome/common/url_constants.cc b/chrome/common/url_constants.cc index 545a59cf..4464a92 100644 --- a/chrome/common/url_constants.cc +++ b/chrome/common/url_constants.cc
@@ -268,6 +268,7 @@ const char kChromeUIContextualSearchPromoHost[] = "contextual-search-promo"; const char kChromeUIPhysicalWebHost[] = "physical-web"; const char kChromeUIPopularSitesInternalsHost[] = "popular-sites-internals"; +const char kChromeUISnippetsInternalsHost[] = "snippets-internals"; #endif #if defined(OS_CHROMEOS) @@ -655,6 +656,7 @@ #if defined(OS_ANDROID) kChromeUINetExportHost, kChromeUIPopularSitesInternalsHost, + kChromeUISnippetsInternalsHost, #else // non-mobile kChromeUICopresenceHost, #endif
diff --git a/chrome/common/url_constants.h b/chrome/common/url_constants.h index 3ec91dc..38192c0 100644 --- a/chrome/common/url_constants.h +++ b/chrome/common/url_constants.h
@@ -251,6 +251,7 @@ extern const char kChromeUIContextualSearchPromoHost[]; extern const char kChromeUIPhysicalWebHost[]; extern const char kChromeUIPopularSitesInternalsHost[]; +extern const char kChromeUISnippetsInternalsHost[]; #endif #if defined(OS_CHROMEOS)
diff --git a/chrome/installer/util/BUILD.gn b/chrome/installer/util/BUILD.gn index b78e1ede..63a89d9 100644 --- a/chrome/installer/util/BUILD.gn +++ b/chrome/installer/util/BUILD.gn
@@ -293,6 +293,7 @@ "beacons_unittest.cc", "callback_work_item_unittest.cc", "channel_info_unittest.cc", + "conditional_work_item_list_unittest.cc", "copy_tree_work_item_unittest.cc", "create_dir_work_item_unittest.cc", "create_reg_key_work_item_unittest.cc", @@ -333,6 +334,8 @@ "uninstall_metrics_unittest.cc", "wmi_unittest.cc", "work_item_list_unittest.cc", + "work_item_mocks.cc", + "work_item_mocks.h", ] deps = [
diff --git a/chrome/installer/util/conditional_work_item_list_unittest.cc b/chrome/installer/util/conditional_work_item_list_unittest.cc new file mode 100644 index 0000000..1268f5d --- /dev/null +++ b/chrome/installer/util/conditional_work_item_list_unittest.cc
@@ -0,0 +1,129 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/installer/util/conditional_work_item_list.h" + +#include <memory> + +#include "base/files/file_path.h" +#include "base/files/scoped_temp_dir.h" +#include "base/macros.h" +#include "chrome/installer/util/work_item.h" +#include "chrome/installer/util/work_item_mocks.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using testing::InSequence; +using testing::Return; + +// Execute a ConditionalWorkItemList whose condition is met and then rollback. +TEST(ConditionalWorkItemListTest, ExecutionSuccess) { + std::unique_ptr<StrictMockCondition> condition(new StrictMockCondition); + EXPECT_CALL(*condition, ShouldRun()).WillOnce(Return(true)); + std::unique_ptr<WorkItemList> list( + WorkItem::CreateConditionalWorkItemList(condition.release())); + + // Create the mock work items. + std::unique_ptr<StrictMockWorkItem> item1(new StrictMockWorkItem); + std::unique_ptr<StrictMockWorkItem> item2(new StrictMockWorkItem); + std::unique_ptr<StrictMockWorkItem> item3(new StrictMockWorkItem); + + { + // Expect all three items to be done in order then undone. + InSequence s; + + EXPECT_CALL(*item1, Do()).WillOnce(Return(true)); + EXPECT_CALL(*item2, Do()).WillOnce(Return(true)); + EXPECT_CALL(*item3, Do()).WillOnce(Return(true)); + EXPECT_CALL(*item3, Rollback()); + EXPECT_CALL(*item2, Rollback()); + EXPECT_CALL(*item1, Rollback()); + } + + // Add the items to the list. + list->AddWorkItem(item1.release()); + list->AddWorkItem(item2.release()); + list->AddWorkItem(item3.release()); + + // Do and rollback the list. + EXPECT_TRUE(list->Do()); + list->Rollback(); +} + +// Execute a ConditionalWorkItemList whose condition is met. Fail in the middle. +// Rollback what has been done. +TEST(ConditionalWorkItemListTest, ExecutionFailAndRollback) { + std::unique_ptr<StrictMockCondition> condition(new StrictMockCondition); + EXPECT_CALL(*condition, ShouldRun()).WillOnce(Return(true)); + std::unique_ptr<WorkItemList> list( + WorkItem::CreateConditionalWorkItemList(condition.release())); + + // Create the mock work items. + std::unique_ptr<StrictMockWorkItem> item1(new StrictMockWorkItem); + std::unique_ptr<StrictMockWorkItem> item2(new StrictMockWorkItem); + std::unique_ptr<StrictMockWorkItem> item3(new StrictMockWorkItem); + + { + // Expect the two first work items to be done in order then undone. + InSequence s; + + EXPECT_CALL(*item1, Do()).WillOnce(Return(true)); + EXPECT_CALL(*item2, Do()).WillOnce(Return(false)); + EXPECT_CALL(*item2, Rollback()); + EXPECT_CALL(*item1, Rollback()); + } + + // Add the items to the list. + list->AddWorkItem(item1.release()); + list->AddWorkItem(item2.release()); + list->AddWorkItem(item3.release()); + + // Do and rollback the list. + EXPECT_FALSE(list->Do()); + list->Rollback(); +} + +// Execute a ConditionalWorkItemList whose condition isn't met. +TEST(ConditionalWorkItemListTest, ConditionFailure) { + std::unique_ptr<StrictMockCondition> condition(new StrictMockCondition); + EXPECT_CALL(*condition, ShouldRun()).WillOnce(Return(false)); + std::unique_ptr<WorkItemList> list( + WorkItem::CreateConditionalWorkItemList(condition.release())); + + // Create the mock work items. + std::unique_ptr<StrictMockWorkItem> item1(new StrictMockWorkItem); + std::unique_ptr<StrictMockWorkItem> item2(new StrictMockWorkItem); + std::unique_ptr<StrictMockWorkItem> item3(new StrictMockWorkItem); + + // Don't expect any call to the methods of the work items. + + // Add the items to the list. + list->AddWorkItem(item1.release()); + list->AddWorkItem(item2.release()); + list->AddWorkItem(item3.release()); + + // Do and rollback the list. + EXPECT_TRUE(list->Do()); + list->Rollback(); +} + +TEST(ConditionalWorkItemListTest, ConditionNot) { + std::unique_ptr<StrictMockCondition> condition_true(new StrictMockCondition); + EXPECT_CALL(*condition_true, ShouldRun()).WillOnce(Return(true)); + EXPECT_FALSE(Not(condition_true.release()).ShouldRun()); + + std::unique_ptr<StrictMockCondition> condition_false(new StrictMockCondition); + EXPECT_CALL(*condition_false, ShouldRun()).WillOnce(Return(false)); + EXPECT_TRUE(Not(condition_false.release()).ShouldRun()); +} + +TEST(ConditionalWorkItemListTest, ConditionRunIfFileExists) { + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + + EXPECT_TRUE(ConditionRunIfFileExists(temp_dir.path()).ShouldRun()); + EXPECT_FALSE(ConditionRunIfFileExists( + temp_dir.path().Append(FILE_PATH_LITERAL("DoesNotExist"))) + .ShouldRun()); +}
diff --git a/chrome/installer/util/work_item_list_unittest.cc b/chrome/installer/util/work_item_list_unittest.cc index c0592f9..2d028eb 100644 --- a/chrome/installer/util/work_item_list_unittest.cc +++ b/chrome/installer/util/work_item_list_unittest.cc
@@ -4,284 +4,73 @@ #include "chrome/installer/util/work_item_list.h" -#include <windows.h> - #include <memory> -#include "base/base_paths.h" -#include "base/files/file_util.h" -#include "base/files/scoped_temp_dir.h" -#include "base/strings/string_util.h" -#include "base/test/test_reg_util_win.h" -#include "base/win/registry.h" -#include "chrome/installer/util/conditional_work_item_list.h" +#include "base/macros.h" #include "chrome/installer/util/work_item.h" +#include "chrome/installer/util/work_item_mocks.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -using base::win::RegKey; +using testing::InSequence; +using testing::Return; -namespace { +// Execute a WorkItemList successfully and then rollback. +TEST(WorkItemListTest, ExecutionSuccess) { + std::unique_ptr<WorkItemList> list(WorkItem::CreateWorkItemList()); -const wchar_t kTestRoot[] = L"ListList"; -const wchar_t kDataStr[] = L"data_111"; -const wchar_t kName[] = L"name"; + // Create the mock work items. + std::unique_ptr<StrictMockWorkItem> item1(new StrictMockWorkItem); + std::unique_ptr<StrictMockWorkItem> item2(new StrictMockWorkItem); + std::unique_ptr<StrictMockWorkItem> item3(new StrictMockWorkItem); -class WorkItemListTest : public testing::Test { - protected: - void SetUp() override { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - registry_override_manager_.OverrideRegistry(HKEY_CURRENT_USER); + { + // Expect all three items to be done in order then undone. + InSequence s; + + EXPECT_CALL(*item1, Do()).WillOnce(Return(true)); + EXPECT_CALL(*item2, Do()).WillOnce(Return(true)); + EXPECT_CALL(*item3, Do()).WillOnce(Return(true)); + EXPECT_CALL(*item3, Rollback()); + EXPECT_CALL(*item2, Rollback()); + EXPECT_CALL(*item1, Rollback()); } - void TearDown() override { logging::CloseLogFile(); } + // Add the items to the list. + list->AddWorkItem(item1.release()); + list->AddWorkItem(item2.release()); + list->AddWorkItem(item3.release()); - base::ScopedTempDir temp_dir_; - registry_util::RegistryOverrideManager registry_override_manager_; -}; - -} // namespace - -// Execute a WorkItem list successfully and then rollback. -TEST_F(WorkItemListTest, ExecutionSuccess) { - std::unique_ptr<WorkItemList> work_item_list(WorkItem::CreateWorkItemList()); - std::unique_ptr<WorkItem> work_item; - - base::FilePath top_dir_to_create(temp_dir_.path()); - top_dir_to_create = top_dir_to_create.AppendASCII("a"); - base::FilePath dir_to_create(top_dir_to_create); - dir_to_create = dir_to_create.AppendASCII("b"); - ASSERT_FALSE(base::PathExists(dir_to_create)); - - work_item.reset(reinterpret_cast<WorkItem*>( - WorkItem::CreateCreateDirWorkItem(dir_to_create))); - work_item_list->AddWorkItem(work_item.release()); - - std::wstring key_to_create(kTestRoot); - key_to_create.push_back(base::FilePath::kSeparators[0]); - key_to_create.append(L"ExecutionSuccess"); - - work_item.reset( - reinterpret_cast<WorkItem*>(WorkItem::CreateCreateRegKeyWorkItem( - HKEY_CURRENT_USER, key_to_create, WorkItem::kWow64Default))); - work_item_list->AddWorkItem(work_item.release()); - - std::wstring name(kName); - std::wstring data(kDataStr); - work_item.reset(reinterpret_cast<WorkItem*>( - WorkItem::CreateSetRegValueWorkItem(HKEY_CURRENT_USER, - key_to_create, - WorkItem::kWow64Default, - name, - data, - false))); - work_item_list->AddWorkItem(work_item.release()); - - EXPECT_TRUE(work_item_list->Do()); - - // Verify all WorkItems have been executed. - RegKey key; - EXPECT_EQ(ERROR_SUCCESS, - key.Open(HKEY_CURRENT_USER, key_to_create.c_str(), KEY_READ)); - std::wstring read_out; - EXPECT_EQ(ERROR_SUCCESS, key.ReadValue(name.c_str(), &read_out)); - EXPECT_EQ(0, read_out.compare(kDataStr)); - key.Close(); - EXPECT_TRUE(base::PathExists(dir_to_create)); - - work_item_list->Rollback(); - - // Verify everything is rolled back. - // The value must have been deleted first in roll back otherwise the key - // can not be deleted. - EXPECT_NE(ERROR_SUCCESS, - key.Open(HKEY_CURRENT_USER, key_to_create.c_str(), KEY_READ)); - EXPECT_FALSE(base::PathExists(top_dir_to_create)); + // Do and rollback the list. + EXPECT_TRUE(list->Do()); + list->Rollback(); } -// Execute a WorkItem list. Fail in the middle. Rollback what has been done. -TEST_F(WorkItemListTest, ExecutionFailAndRollback) { - std::unique_ptr<WorkItemList> work_item_list(WorkItem::CreateWorkItemList()); - std::unique_ptr<WorkItem> work_item; +// Execute a WorkItemList. Fail in the middle. Rollback what has been done. +TEST(WorkItemListTest, ExecutionFailAndRollback) { + std::unique_ptr<WorkItemList> list(WorkItem::CreateWorkItemList()); - base::FilePath top_dir_to_create(temp_dir_.path()); - top_dir_to_create = top_dir_to_create.AppendASCII("a"); - base::FilePath dir_to_create(top_dir_to_create); - dir_to_create = dir_to_create.AppendASCII("b"); - ASSERT_FALSE(base::PathExists(dir_to_create)); + // Create the mock work items. + std::unique_ptr<StrictMockWorkItem> item1(new StrictMockWorkItem); + std::unique_ptr<StrictMockWorkItem> item2(new StrictMockWorkItem); + std::unique_ptr<StrictMockWorkItem> item3(new StrictMockWorkItem); - work_item.reset(reinterpret_cast<WorkItem*>( - WorkItem::CreateCreateDirWorkItem(dir_to_create))); - work_item_list->AddWorkItem(work_item.release()); + { + // Expect the two first work items to be done in order then undone. + InSequence s; - std::wstring key_to_create(kTestRoot); - key_to_create.push_back(base::FilePath::kSeparators[0]); - key_to_create.append(L"ExecutionFail"); + EXPECT_CALL(*item1, Do()).WillOnce(Return(true)); + EXPECT_CALL(*item2, Do()).WillOnce(Return(false)); + EXPECT_CALL(*item2, Rollback()); + EXPECT_CALL(*item1, Rollback()); + } - work_item.reset( - reinterpret_cast<WorkItem*>(WorkItem::CreateCreateRegKeyWorkItem( - HKEY_CURRENT_USER, key_to_create, WorkItem::kWow64Default))); - work_item_list->AddWorkItem(work_item.release()); + // Add the items to the list. + list->AddWorkItem(item1.release()); + list->AddWorkItem(item2.release()); + list->AddWorkItem(item3.release()); - std::wstring not_created_key(kTestRoot); - not_created_key.push_back(base::FilePath::kSeparators[0]); - not_created_key.append(L"NotCreated"); - std::wstring name(kName); - std::wstring data(kDataStr); - work_item.reset(reinterpret_cast<WorkItem*>( - WorkItem::CreateSetRegValueWorkItem(HKEY_CURRENT_USER, - not_created_key, - WorkItem::kWow64Default, - name, - data, - false))); - work_item_list->AddWorkItem(work_item.release()); - - // This one will not be executed because we will fail early. - work_item.reset( - reinterpret_cast<WorkItem*>(WorkItem::CreateCreateRegKeyWorkItem( - HKEY_CURRENT_USER, not_created_key, WorkItem::kWow64Default))); - work_item_list->AddWorkItem(work_item.release()); - - EXPECT_FALSE(work_item_list->Do()); - - // Verify the first 2 WorkItems have been executed. - RegKey key; - EXPECT_EQ(ERROR_SUCCESS, - key.Open(HKEY_CURRENT_USER, key_to_create.c_str(), KEY_READ)); - key.Close(); - EXPECT_TRUE(base::PathExists(dir_to_create)); - // The last one should not be there. - EXPECT_NE(ERROR_SUCCESS, - key.Open(HKEY_CURRENT_USER, not_created_key.c_str(), KEY_READ)); - - work_item_list->Rollback(); - - // Verify everything is rolled back. - EXPECT_NE(ERROR_SUCCESS, - key.Open(HKEY_CURRENT_USER, key_to_create.c_str(), KEY_READ)); - EXPECT_FALSE(base::PathExists(top_dir_to_create)); -} - -TEST_F(WorkItemListTest, ConditionalExecutionSuccess) { - std::unique_ptr<WorkItemList> work_item_list(WorkItem::CreateWorkItemList()); - std::unique_ptr<WorkItem> work_item; - - base::FilePath top_dir_to_create(temp_dir_.path()); - top_dir_to_create = top_dir_to_create.AppendASCII("a"); - base::FilePath dir_to_create(top_dir_to_create); - dir_to_create = dir_to_create.AppendASCII("b"); - ASSERT_FALSE(base::PathExists(dir_to_create)); - - work_item.reset(reinterpret_cast<WorkItem*>( - WorkItem::CreateCreateDirWorkItem(dir_to_create))); - work_item_list->AddWorkItem(work_item.release()); - - std::unique_ptr<WorkItemList> conditional_work_item_list( - WorkItem::CreateConditionalWorkItemList( - new ConditionRunIfFileExists(dir_to_create))); - - std::wstring key_to_create(kTestRoot); - key_to_create.push_back(base::FilePath::kSeparators[0]); - key_to_create.append(L"ExecutionSuccess"); - work_item.reset( - reinterpret_cast<WorkItem*>(WorkItem::CreateCreateRegKeyWorkItem( - HKEY_CURRENT_USER, key_to_create, WorkItem::kWow64Default))); - conditional_work_item_list->AddWorkItem(work_item.release()); - - std::wstring name(kName); - std::wstring data(kDataStr); - work_item.reset(reinterpret_cast<WorkItem*>( - WorkItem::CreateSetRegValueWorkItem(HKEY_CURRENT_USER, - key_to_create, - WorkItem::kWow64Default, - name, - data, - false))); - conditional_work_item_list->AddWorkItem(work_item.release()); - - work_item_list->AddWorkItem(conditional_work_item_list.release()); - - EXPECT_TRUE(work_item_list->Do()); - - // Verify all WorkItems have been executed. - RegKey key; - EXPECT_EQ(ERROR_SUCCESS, - key.Open(HKEY_CURRENT_USER, key_to_create.c_str(), KEY_READ)); - std::wstring read_out; - EXPECT_EQ(ERROR_SUCCESS, key.ReadValue(name.c_str(), &read_out)); - EXPECT_EQ(0, read_out.compare(kDataStr)); - key.Close(); - EXPECT_TRUE(base::PathExists(dir_to_create)); - - work_item_list->Rollback(); - - // Verify everything is rolled back. - // The value must have been deleted first in roll back otherwise the key - // can not be deleted. - EXPECT_NE(ERROR_SUCCESS, - key.Open(HKEY_CURRENT_USER, key_to_create.c_str(), KEY_READ)); - EXPECT_FALSE(base::PathExists(top_dir_to_create)); -} - -TEST_F(WorkItemListTest, ConditionalExecutionConditionFailure) { - std::unique_ptr<WorkItemList> work_item_list(WorkItem::CreateWorkItemList()); - std::unique_ptr<WorkItem> work_item; - - base::FilePath top_dir_to_create(temp_dir_.path()); - top_dir_to_create = top_dir_to_create.AppendASCII("a"); - base::FilePath dir_to_create(top_dir_to_create); - dir_to_create = dir_to_create.AppendASCII("b"); - ASSERT_FALSE(base::PathExists(dir_to_create)); - - work_item.reset(reinterpret_cast<WorkItem*>( - WorkItem::CreateCreateDirWorkItem(dir_to_create))); - work_item_list->AddWorkItem(work_item.release()); - - std::unique_ptr<WorkItemList> conditional_work_item_list( - WorkItem::CreateConditionalWorkItemList( - new ConditionRunIfFileExists(dir_to_create.AppendASCII("c")))); - - std::wstring key_to_create(kTestRoot); - key_to_create.push_back(base::FilePath::kSeparators[0]); - key_to_create.append(L"ExecutionSuccess"); - work_item.reset( - reinterpret_cast<WorkItem*>(WorkItem::CreateCreateRegKeyWorkItem( - HKEY_CURRENT_USER, key_to_create, WorkItem::kWow64Default))); - conditional_work_item_list->AddWorkItem(work_item.release()); - - std::wstring name(kName); - std::wstring data(kDataStr); - work_item.reset(reinterpret_cast<WorkItem*>( - WorkItem::CreateSetRegValueWorkItem(HKEY_CURRENT_USER, - key_to_create, - WorkItem::kWow64Default, - name, - data, - false))); - conditional_work_item_list->AddWorkItem(work_item.release()); - - work_item_list->AddWorkItem(conditional_work_item_list.release()); - - EXPECT_TRUE(work_item_list->Do()); - - // Verify that the WorkItems added as part of the conditional list have NOT - // been executed. - RegKey key; - EXPECT_NE(ERROR_SUCCESS, - key.Open(HKEY_CURRENT_USER, key_to_create.c_str(), KEY_READ)); - std::wstring read_out; - EXPECT_NE(ERROR_SUCCESS, key.ReadValue(name.c_str(), &read_out)); - key.Close(); - - // Verify that the other work item was executed. - EXPECT_TRUE(base::PathExists(dir_to_create)); - - work_item_list->Rollback(); - - // Verify everything is rolled back. - // The value must have been deleted first in roll back otherwise the key - // can not be deleted. - EXPECT_NE(ERROR_SUCCESS, - key.Open(HKEY_CURRENT_USER, key_to_create.c_str(), KEY_READ)); - EXPECT_FALSE(base::PathExists(top_dir_to_create)); + // Do and rollback the list. + EXPECT_FALSE(list->Do()); + list->Rollback(); }
diff --git a/chrome/installer/util/work_item_mocks.cc b/chrome/installer/util/work_item_mocks.cc new file mode 100644 index 0000000..44ed442 --- /dev/null +++ b/chrome/installer/util/work_item_mocks.cc
@@ -0,0 +1,11 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/installer/util/work_item_mocks.h" + +MockWorkItem::MockWorkItem() = default; +MockWorkItem::~MockWorkItem() = default; + +MockCondition::MockCondition() = default; +MockCondition::~MockCondition() = default;
diff --git a/chrome/installer/util/work_item_mocks.h b/chrome/installer/util/work_item_mocks.h new file mode 100644 index 0000000..37c9a6a --- /dev/null +++ b/chrome/installer/util/work_item_mocks.h
@@ -0,0 +1,39 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_INSTALLER_UTIL_WORK_ITEM_MOCKS_H_ +#define CHROME_INSTALLER_UTIL_WORK_ITEM_MOCKS_H_ + +#include "base/macros.h" +#include "chrome/installer/util/conditional_work_item_list.h" +#include "chrome/installer/util/work_item.h" +#include "testing/gmock/include/gmock/gmock.h" + +class MockWorkItem : public WorkItem { + public: + MockWorkItem(); + ~MockWorkItem(); + + MOCK_METHOD0(Do, bool()); + MOCK_METHOD0(Rollback, void()); + + private: + DISALLOW_COPY_AND_ASSIGN(MockWorkItem); +}; + +class MockCondition : public WorkItem::Condition { + public: + MockCondition(); + ~MockCondition(); + + MOCK_CONST_METHOD0(ShouldRun, bool()); + + private: + DISALLOW_COPY_AND_ASSIGN(MockCondition); +}; + +using StrictMockWorkItem = testing::StrictMock<MockWorkItem>; +using StrictMockCondition = testing::StrictMock<MockCondition>; + +#endif // CHROME_INSTALLER_UTIL_WORK_ITEM_MOCKS_H_
diff --git a/chrome/renderer/extensions/automation_internal_custom_bindings.cc b/chrome/renderer/extensions/automation_internal_custom_bindings.cc index eaf7731a..bf405aae 100644 --- a/chrome/renderer/extensions/automation_internal_custom_bindings.cc +++ b/chrome/renderer/extensions/automation_internal_custom_bindings.cc
@@ -721,6 +721,29 @@ v8::String::NewFromUtf8(GetIsolate(), "TreeChangeType"), ToEnumObject(GetIsolate(), ui::AX_MUTATION_NONE, ui::AX_MUTATION_LAST)); + v8::Local<v8::Object> name_from_type(v8::Object::New(GetIsolate())); + for (int i = ui::AX_NAME_FROM_NONE; i <= ui::AX_NAME_FROM_LAST; ++i) { + name_from_type->Set( + v8::Integer::New(GetIsolate(), i), + CreateV8String(GetIsolate(), + ui::ToString(static_cast<ui::AXNameFrom>(i)))); + } + + additions->Set(v8::String::NewFromUtf8(GetIsolate(), "NameFromType"), + name_from_type); + + v8::Local<v8::Object> description_from_type(v8::Object::New(GetIsolate())); + for (int i = ui::AX_DESCRIPTION_FROM_NONE; i <= ui::AX_DESCRIPTION_FROM_LAST; + ++i) { + description_from_type->Set( + v8::Integer::New(GetIsolate(), i), + CreateV8String(GetIsolate(), + ui::ToString(static_cast<ui::AXDescriptionFrom>(i)))); + } + + additions->Set(v8::String::NewFromUtf8(GetIsolate(), "DescriptionFromType"), + description_from_type); + args.GetReturnValue().Set(additions); } @@ -1058,6 +1081,7 @@ args->Set(0U, event_params); context()->DispatchEvent("automationInternal.onAccessibilityEvent", args); } + void AutomationInternalCustomBindings::OnNodeDataWillChange( ui::AXTree* tree, const ui::AXNodeData& old_node_data,
diff --git a/chrome/renderer/prerender/prerender_dispatcher.cc b/chrome/renderer/prerender/prerender_dispatcher.cc index 5e616b0..1ef43300 100644 --- a/chrome/renderer/prerender/prerender_dispatcher.cc +++ b/chrome/renderer/prerender/prerender_dispatcher.cc
@@ -127,6 +127,18 @@ return handled; } +void PrerenderDispatcher::OnRenderProcessShutdown() { + // Renderer is shutting down, abandon all in-flight prerenders. + for (auto it : prerenders_) { + const PrerenderExtraData& extra_data = + PrerenderExtraData::FromPrerender(it.second); + content::RenderThread::Get()->Send( + new PrerenderHostMsg_AbandonLinkRelPrerender( + extra_data.prerender_id())); + } + prerenders_.clear(); +} + void PrerenderDispatcher::add(const WebPrerender& prerender) { const PrerenderExtraData& extra_data = PrerenderExtraData::FromPrerender(prerender);
diff --git a/chrome/renderer/prerender/prerender_dispatcher.h b/chrome/renderer/prerender/prerender_dispatcher.h index 4f2f16e1..7a78fc1 100644 --- a/chrome/renderer/prerender/prerender_dispatcher.h +++ b/chrome/renderer/prerender/prerender_dispatcher.h
@@ -44,6 +44,7 @@ // From RenderThreadObserver: bool OnControlMessageReceived(const IPC::Message& message) override; + void OnRenderProcessShutdown() override; // From WebPrerenderingSupport: void add(const blink::WebPrerender& prerender) override;
diff --git a/chrome/renderer/resources/extensions/automation/automation_node.js b/chrome/renderer/resources/extensions/automation/automation_node.js index ade163d..85211225 100644 --- a/chrome/renderer/resources/extensions/automation/automation_node.js +++ b/chrome/renderer/resources/extensions/automation/automation_node.js
@@ -602,8 +602,10 @@ 'backgroundColor', 'color', 'colorValue', + 'descriptionFrom', 'hierarchicalLevel', 'invalidState', + 'nameFrom', 'posInSet', 'scrollX', 'scrollXMax',
diff --git a/chrome/test/android/cast_emulator/src/org/chromium/chrome/browser/media/remote/DummyPlayer.java b/chrome/test/android/cast_emulator/src/org/chromium/chrome/browser/media/remote/DummyPlayer.java index abce2a07..e38eb31 100644 --- a/chrome/test/android/cast_emulator/src/org/chromium/chrome/browser/media/remote/DummyPlayer.java +++ b/chrome/test/android/cast_emulator/src/org/chromium/chrome/browser/media/remote/DummyPlayer.java
@@ -109,7 +109,7 @@ // when seeking is completed) item.setDuration(mMediaPlayer.getDuration()); item.setPosition(mSeekToPos > 0 ? mSeekToPos : mMediaPlayer.getCurrentPosition()); - item.setTimestamp(SystemClock.uptimeMillis()); + item.setTimestamp(SystemClock.elapsedRealtime()); } }
diff --git a/chrome/test/android/cast_emulator/src/org/chromium/chrome/browser/media/remote/MediaItem.java b/chrome/test/android/cast_emulator/src/org/chromium/chrome/browser/media/remote/MediaItem.java index b721e97..fd2ed158 100644 --- a/chrome/test/android/cast_emulator/src/org/chromium/chrome/browser/media/remote/MediaItem.java +++ b/chrome/test/android/cast_emulator/src/org/chromium/chrome/browser/media/remote/MediaItem.java
@@ -33,7 +33,7 @@ mItemId = iid; mUri = uri; mUpdateReceiver = pi; - setTimestamp(SystemClock.uptimeMillis()); + setTimestamp(SystemClock.elapsedRealtime()); } public void setRemoteItemId(String riid) {
diff --git a/chrome/test/data/webui/settings/cr_settings_browsertest.js b/chrome/test/data/webui/settings/cr_settings_browsertest.js index 478a05c..1c82000 100644 --- a/chrome/test/data/webui/settings/cr_settings_browsertest.js +++ b/chrome/test/data/webui/settings/cr_settings_browsertest.js
@@ -124,6 +124,32 @@ GEN('#endif'); /** + * Test fixture for + * chrome/browser/resources/settings/people_page/people_page.html. + * @constructor + * @extends {CrSettingsBrowserTest} +*/ +function CrSettingsPeoplePageTest() {} + +CrSettingsPeoplePageTest.prototype = { + __proto__: CrSettingsBrowserTest.prototype, + + /** @override */ + browsePreload: 'chrome://md-settings/people_page/people_page.html', + + /** @override */ + extraLibraries: PolymerTest.getLibraries(ROOT_PATH).concat([ + 'test_browser_proxy.js', + 'people_page_test.js', + ]), +}; + +TEST_F('CrSettingsPeoplePageTest', 'PeoplePage', function() { + settings_people_page.registerTests(); + mocha.run(); +}); + +/** * @constructor * @extends {CrSettingsBrowserTest} */ @@ -147,7 +173,6 @@ mocha.run(); }); - /** * Test fixture for chrome/browser/resources/settings/reset_page/. * @constructor
diff --git a/chrome/test/data/webui/settings/people_page_test.js b/chrome/test/data/webui/settings/people_page_test.js new file mode 100644 index 0000000..8a4bbe2 --- /dev/null +++ b/chrome/test/data/webui/settings/people_page_test.js
@@ -0,0 +1,87 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +cr.define('settings_people_page', function() { + /** + * @constructor + * @implements {settings.ProfileInfoBrowserProxy} + * @extends {settings.TestBrowserProxy} + */ + var TestProfileInfoBrowserProxy = function() { + settings.TestBrowserProxy.call(this, [ + 'getProfileInfo', + ]); + }; + + TestProfileInfoBrowserProxy.prototype = { + __proto__: settings.TestBrowserProxy.prototype, + + fakeProfileInfo: { + name: 'fakeName', + iconUrl: 'http://fake-icon-url.com/', + }, + + /** @override */ + getProfileInfo: function() { + this.methodCalled('getProfileInfo'); + return Promise.resolve(this.fakeProfileInfo); + }, + }; + + function registerProfileInfoTests() { + suite('ProfileInfoTests', function() { + var peoplePage = null; + var browserProxy = null; + + suiteSetup(function() { + // Force easy unlock off. Those have their own ChromeOS-only tests. + loadTimeData.overrideValues({ + easyUnlockAllowed: false, + }); + }); + + setup(function() { + browserProxy = new TestProfileInfoBrowserProxy(); + settings.ProfileInfoBrowserProxyImpl.instance_ = browserProxy; + + PolymerTest.clearBody(); + peoplePage = document.createElement('settings-people-page'); + peoplePage.currentRoute = { + url: '/', + page: 'basic', + section: '', + }; + document.body.appendChild(peoplePage); + }); + + teardown(function() { peoplePage.remove(); }); + + test('GetProfileInfo', function() { + return browserProxy.whenCalled('getProfileInfo').then(function() { + Polymer.dom.flush(); + assertEquals(browserProxy.fakeProfileInfo.name, + peoplePage.$$('#profile-name').textContent.trim()); + assertEquals(browserProxy.fakeProfileInfo.iconUrl, + peoplePage.$$('#profile-icon').src); + + cr.webUIListenerCallback( + 'profile-info-changed', + {name: 'pushedName', iconUrl: 'http://pushed-url/'}); + + Polymer.dom.flush(); + assertEquals('pushedName', + peoplePage.$$('#profile-name').textContent.trim()); + assertEquals('http://pushed-url/', + peoplePage.$$('#profile-icon').src); + }); + }); + }); + } + + return { + registerTests: function() { + registerProfileInfoTests(); + }, + }; +});
diff --git a/chrome/test/media_router/media_router_e2e_ui_browsertest.cc b/chrome/test/media_router/media_router_e2e_ui_browsertest.cc index aa1c135..6fd22d6 100644 --- a/chrome/test/media_router/media_router_e2e_ui_browsertest.cc +++ b/chrome/test/media_router/media_router_e2e_ui_browsertest.cc
@@ -21,6 +21,8 @@ ExecuteScript(web_contents, script); content::WebContents* dialog_contents = OpenMRDialog(web_contents); ASSERT_TRUE(dialog_contents); + // Wait for 1s to make sure the dialog finishes rendering. + Wait(base::TimeDelta::FromSeconds(1)); WaitUntilSinkDiscoveredOnUI(); ChooseSink(web_contents, receiver()); WaitUntilRouteCreated();
diff --git a/chrome/test/media_router/media_router_perf_tests.isolate b/chrome/test/media_router/media_router_perf_tests.isolate index 41ee089..ddd2c23 100644 --- a/chrome/test/media_router/media_router_perf_tests.isolate +++ b/chrome/test/media_router/media_router_perf_tests.isolate
@@ -15,6 +15,7 @@ '--output-dir=${ISOLATED_OUTDIR}', ], 'files': [ + 'internal/', '<(PRODUCT_DIR)/mr_extension/release/', '../../../third_party/catapult/', '../../../tools/perf/',
diff --git a/chrome/test/media_router/media_router_tests.isolate b/chrome/test/media_router/media_router_tests.isolate index 92ebbfba..e400418 100644 --- a/chrome/test/media_router/media_router_tests.isolate +++ b/chrome/test/media_router/media_router_tests.isolate
@@ -13,7 +13,7 @@ '<(PRODUCT_DIR)/browser_tests<(EXECUTABLE_SUFFIX)', ], 'files': [ - 'internal/media_router_tests.py', + 'internal/', '../../../media/test/data/player.html', '../../../media/test/data/bear-vp9-opus.webm', '<(PRODUCT_DIR)/browser_tests<(EXECUTABLE_SUFFIX)',
diff --git a/chrome/tools/build/win/create_installer_archive.py b/chrome/tools/build/win/create_installer_archive.py index bf1f089..f658ec49 100755 --- a/chrome/tools/build/win/create_installer_archive.py +++ b/chrome/tools/build/win/create_installer_archive.py
@@ -249,11 +249,16 @@ ': \\\n') f.write(' ' + ' \\\n '.join(path_fixup(x) for x in g_archive_inputs)) + # It is important to use abspath to create the path to the directory because + # if you use a relative path without any .. sequences then 7za.exe uses the + # entire relative path as part of the file paths in the archive. If you have + # a .. sequence or an absolute path then only the last directory is stored as + # part of the file paths in the archive, which is what we want. cmd = [lzma_exec, 'a', '-t7z', archive_file, - os.path.join(staging_dir, CHROME_DIR), + os.path.abspath(os.path.join(staging_dir, CHROME_DIR)), '-mx0',] # There doesnt seem to be any way in 7za.exe to override existing file so # we always delete before creating a new one. @@ -602,7 +607,7 @@ def main(options): - """Main method that reads input file, creates archive file and write + """Main method that reads input file, creates archive file and writes resource input file. """ current_version = BuildVersion(options.build_dir)
diff --git a/chromecast/browser/cast_content_browser_client.cc b/chromecast/browser/cast_content_browser_client.cc index 3fe72b1..d2b92478 100644 --- a/chromecast/browser/cast_content_browser_client.cc +++ b/chromecast/browser/cast_content_browser_client.cc
@@ -68,13 +68,13 @@ namespace { #if defined(ENABLE_MOJO_MEDIA_IN_BROWSER_PROCESS) -static std::unique_ptr<shell::ShellClient> CreateCastMojoMediaApplication( +static std::unique_ptr<::shell::ShellClient> CreateCastMojoMediaApplication( CastContentBrowserClient* browser_client) { std::unique_ptr<media::CastMojoMediaClient> mojo_media_client( new media::CastMojoMediaClient( base::Bind(&CastContentBrowserClient::CreateMediaPipelineBackend, base::Unretained(browser_client)))); - return std::unique_ptr<shell::ShellClient>( + return std::unique_ptr<::shell::ShellClient>( new media::CastMojoMediaApplication( std::move(mojo_media_client), browser_client->GetMediaTaskRunner())); }
diff --git a/chromecast/browser/media/cast_mojo_media_application.cc b/chromecast/browser/media/cast_mojo_media_application.cc index 93addceb..0ec21db 100644 --- a/chromecast/browser/media/cast_mojo_media_application.cc +++ b/chromecast/browser/media/cast_mojo_media_application.cc
@@ -39,17 +39,18 @@ CastMojoMediaApplication::~CastMojoMediaApplication() {} -void CastMojoMediaApplication::Initialize(shell::Connector* connector, - const shell::Identity& identity, +void CastMojoMediaApplication::Initialize(::shell::Connector* connector, + const ::shell::Identity& identity, uint32_t /* id */) {} -bool CastMojoMediaApplication::AcceptConnection(shell::Connection* connection) { +bool CastMojoMediaApplication::AcceptConnection( + ::shell::Connection* connection) { connection->AddInterface<::media::interfaces::ServiceFactory>(this); return true; } void CastMojoMediaApplication::Create( - shell::Connection* connection, + ::shell::Connection* connection, mojo::InterfaceRequest<::media::interfaces::ServiceFactory> request) { // Create the app refcount here on the application task runner so that // 1. It is bound to the application task runner, which in turn will
diff --git a/chromecast/browser/media/cast_mojo_media_application.h b/chromecast/browser/media/cast_mojo_media_application.h index e2b7367..fa726a0 100644 --- a/chromecast/browser/media/cast_mojo_media_application.h +++ b/chromecast/browser/media/cast_mojo_media_application.h
@@ -27,8 +27,8 @@ class CastMojoMediaClient; class CastMojoMediaApplication - : public shell::ShellClient, - public shell::InterfaceFactory<::media::interfaces::ServiceFactory> { + : public ::shell::ShellClient, + public ::shell::InterfaceFactory<::media::interfaces::ServiceFactory> { public: CastMojoMediaApplication( std::unique_ptr<CastMojoMediaClient> mojo_media_client, @@ -36,21 +36,21 @@ ~CastMojoMediaApplication() final; private: - // shell::ShellClient implementation. - void Initialize(shell::Connector* connector, - const shell::Identity& identity, + // ::shell::ShellClient implementation. + void Initialize(::shell::Connector* connector, + const ::shell::Identity& identity, uint32_t id) final; - bool AcceptConnection(shell::Connection* connection) final; + bool AcceptConnection(::shell::Connection* connection) final; - // shell::InterfaceFactory<interfaces::ServiceFactory> implementation. - void Create(shell::Connection* connection, + // ::shell::InterfaceFactory<interfaces::ServiceFactory> implementation. + void Create(::shell::Connection* connection, mojo::InterfaceRequest<::media::interfaces::ServiceFactory> request) final; std::unique_ptr<CastMojoMediaClient> mojo_media_client_; scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_; scoped_refptr<::media::MediaLog> media_log_; - shell::MessageLoopRefFactory ref_factory_; + ::shell::MessageLoopRefFactory ref_factory_; }; } // namespace media
diff --git a/components/components_tests.gyp b/components/components_tests.gyp index 244ff1c..dff613f 100644 --- a/components/components_tests.gyp +++ b/components/components_tests.gyp
@@ -639,7 +639,6 @@ 'safe_browsing_db/safe_browsing_api_handler_unittest.cc', ], 'safe_browsing_db_unittest_sources': [ - 'safe_browsing_db/database_manager_unittest.cc', 'safe_browsing_db/prefix_set_unittest.cc', 'safe_browsing_db/testing_util.h', 'safe_browsing_db/util_unittest.cc', @@ -1272,7 +1271,6 @@ 'components.gyp:sessions_content', 'components.gyp:storage_monitor', 'components.gyp:storage_monitor_test_support', - 'components.gyp:test_database_manager', 'components.gyp:ui_zoom', 'components.gyp:url_matcher', 'components.gyp:visitedlink_browser',
diff --git a/components/cronet/android/sample/javatests/src/org/chromium/cronet_sample_apk/CronetSampleTest.java b/components/cronet/android/sample/javatests/src/org/chromium/cronet_sample_apk/CronetSampleTest.java index 032bdac..debacc2 100644 --- a/components/cronet/android/sample/javatests/src/org/chromium/cronet_sample_apk/CronetSampleTest.java +++ b/components/cronet/android/sample/javatests/src/org/chromium/cronet_sample_apk/CronetSampleTest.java
@@ -9,11 +9,11 @@ import android.net.Uri; import android.os.ConditionVariable; import android.test.ActivityInstrumentationTestCase2; -import android.test.FlakyTest; import android.text.Editable; import android.text.TextWatcher; import android.widget.TextView; +import org.chromium.base.test.util.FlakyTest; import org.chromium.net.test.EmbeddedTestServer; /** @@ -45,9 +45,8 @@ /* @SmallTest @Feature({"Cronet"}) - https://crbug.com/592444 */ - @FlakyTest + @FlakyTest(message = "https://crbug.com/592444") public void testLoadUrl() throws Exception { CronetSampleActivity activity = launchCronetSampleWithUrl(mUrl);
diff --git a/components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestContextTest.java b/components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestContextTest.java index 72e88e0..5353b8a 100644 --- a/components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestContextTest.java +++ b/components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestContextTest.java
@@ -11,12 +11,12 @@ import android.os.ConditionVariable; import android.os.Handler; import android.os.Looper; -import android.test.FlakyTest; import android.test.suitebuilder.annotation.SmallTest; import org.chromium.base.PathUtils; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.test.util.Feature; +import org.chromium.base.test.util.FlakyTest; import org.chromium.net.CronetEngine.UrlRequestInfo; import org.chromium.net.TestUrlRequestCallback.ResponseStep; import org.chromium.net.test.EmbeddedTestServer; @@ -342,9 +342,8 @@ @SmallTest @Feature({"Cronet"}) @SuppressWarnings("deprecation") - https://crbug.com/592444 */ - @FlakyTest + @FlakyTest(message = "https://crbug.com/592444") public void testRequestFinishedListenerFailedRequest() throws Exception { String connectionRefusedUrl = "http://127.0.0.1:3"; mTestFramework = startCronetTestFramework(); @@ -557,9 +556,8 @@ /* @SmallTest @Feature({"Cronet"}) - https://crbug.com/592444 */ - @FlakyTest + @FlakyTest(message = "https://crbug.com/592444") public void testShutdownAfterError() throws Exception { mTestFramework = startCronetTestFramework(); TestUrlRequestCallback callback = new ShutdownTestUrlRequestCallback();
diff --git a/components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestTest.java b/components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestTest.java index cc2a0cd..2da038d9 100644 --- a/components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestTest.java +++ b/components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestTest.java
@@ -5,12 +5,12 @@ package org.chromium.net; import android.os.ConditionVariable; -import android.test.FlakyTest; import android.test.MoreAsserts; import android.test.suitebuilder.annotation.SmallTest; import android.util.Log; import org.chromium.base.test.util.Feature; +import org.chromium.base.test.util.FlakyTest; import org.chromium.net.TestUrlRequestCallback.FailureType; import org.chromium.net.TestUrlRequestCallback.ResponseStep; import org.chromium.net.test.FailurePhase; @@ -1519,9 +1519,8 @@ /* @SmallTest @Feature({"Cronet"}) - https://crbug.com/592444 */ - @FlakyTest + @FlakyTest(message = "https://crbug.com/592444") public void testFailures() throws Exception { throwOrCancel(FailureType.CANCEL_SYNC, ResponseStep.ON_RECEIVED_REDIRECT, false, false);
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats_unittest.cc b/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats_unittest.cc index 5a564c3..08e1f257 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats_unittest.cc +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats_unittest.cc
@@ -876,12 +876,7 @@ original2, 2, received2, 2); } -#if defined(OS_ANDROID) -#define MAYBE_ForwardMultipleDays DISABLED_ForwardMultipleDays -#else -#define MAYBE_ForwardMultipleDays ForwardMultipleDays -#endif -TEST_F(DataReductionProxyCompressionStatsTest, MAYBE_ForwardMultipleDays) { +TEST_F(DataReductionProxyCompressionStatsTest, ForwardMultipleDays) { const int64_t kOriginalLength = 200; const int64_t kReceivedLength = 100; RecordContentLengthPrefs(
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_network_delegate_unittest.cc b/components/data_reduction_proxy/core/browser/data_reduction_proxy_network_delegate_unittest.cc index d2a9ce3..c8488ee 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_network_delegate_unittest.cc +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_network_delegate_unittest.cc
@@ -412,12 +412,7 @@ } } -#if defined(OS_ANDROID) -#define MAYBE_NetHistograms DISABLED_NetHistograms -#else -#define MAYBE_NetHistograms NetHistograms -#endif -TEST_F(DataReductionProxyNetworkDelegateTest, MAYBE_NetHistograms) { +TEST_F(DataReductionProxyNetworkDelegateTest, NetHistograms) { const std::string kReceivedValidOCLHistogramName = "Net.HttpContentLengthWithValidOCL"; const std::string kOriginalValidOCLHistogramName = @@ -583,12 +578,7 @@ EXPECT_TRUE(headers.HasHeader(kChromeProxyHeader)); } -#if defined(OS_ANDROID) -#define MAYBE_OnCompletedInternalLoFi DISABLED_OnCompletedInternalLoFi -#else -#define MAYBE_OnCompletedInternalLoFi OnCompletedInternalLoFi -#endif -TEST_F(DataReductionProxyNetworkDelegateTest, MAYBE_OnCompletedInternalLoFi) { +TEST_F(DataReductionProxyNetworkDelegateTest, OnCompletedInternalLoFi) { // Enable Lo-Fi. const struct { bool lofi_response; @@ -615,14 +605,7 @@ } } -#if defined(OS_ANDROID) -#define MAYBE_OnCompletedInternalLoFiPreview \ - DISABLED_OnCompletedInternalLoFiPreview -#else -#define MAYBE_OnCompletedInternalLoFiPreview OnCompletedInternalLoFiPreview -#endif -TEST_F(DataReductionProxyNetworkDelegateTest, - MAYBE_OnCompletedInternalLoFiPreview) { +TEST_F(DataReductionProxyNetworkDelegateTest, OnCompletedInternalLoFiPreview) { // Enable Lo-Fi. const struct { bool is_preview;
diff --git a/components/domain_reliability/beacon.h b/components/domain_reliability/beacon.h index 43b1e4fe..9b1b89e 100644 --- a/components/domain_reliability/beacon.h +++ b/components/domain_reliability/beacon.h
@@ -7,6 +7,7 @@ #include <string> +#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/time/time.h" #include "components/domain_reliability/domain_reliability_export.h"
diff --git a/components/metrics/system_memory_stats_recorder_win.cc b/components/metrics/system_memory_stats_recorder_win.cc index cdd3149..539d80ff 100644 --- a/components/metrics/system_memory_stats_recorder_win.cc +++ b/components/metrics/system_memory_stats_recorder_win.cc
@@ -39,7 +39,7 @@ break; } default: - NOTREACHED() << L"Received unexpected notification"; + NOTREACHED() << "Received unexpected notification"; break; } }
diff --git a/components/mus/manifest.json b/components/mus/manifest.json index 093337f..ca144d18b 100644 --- a/components/mus/manifest.json +++ b/components/mus/manifest.json
@@ -1,7 +1,7 @@ { "manifest_version": 1, "name": "mojo:mus", - "display_name": "Mandoline UI Services", + "display_name": "UI Service", "capabilities": { "required": { "*": { "interfaces": [ "*" ] },
diff --git a/components/mus/mus_app.cc b/components/mus/mus_app.cc index 40cc5423..f3f0a9b 100644 --- a/components/mus/mus_app.cc +++ b/components/mus/mus_app.cc
@@ -127,6 +127,8 @@ platform_display_init_params_.surfaces_state = new SurfacesState; base::PlatformThread::SetName("mus"); + tracing_.Initialize(connector, identity.name()); + TRACE_EVENT0("mus", "MandolineUIServicesApp::Initialize started"); #if defined(USE_X11) XInitThreads(); @@ -149,6 +151,11 @@ // TODO(kylechar): We might not always want a US keyboard layout. ui::KeyboardLayoutEngineManager::GetKeyboardLayoutEngine() ->SetCurrentLayoutByName("us"); + client_native_pixmap_factory_ = ui::ClientNativePixmapFactory::Create(); + ui::ClientNativePixmapFactory::SetInstance( + client_native_pixmap_factory_.get()); + + DCHECK(ui::ClientNativePixmapFactory::GetInstance()); #endif // TODO(rjkroege): Enter sandbox here before we start threads in GpuState @@ -163,8 +170,6 @@ platform_display_init_params_.gpu_state = new GpuState(); window_server_.reset( new ws::WindowServer(this, platform_display_init_params_.surfaces_state)); - - tracing_.Initialize(connector, identity.name()); } bool MandolineUIServicesApp::AcceptConnection(Connection* connection) {
diff --git a/components/mus/mus_app.h b/components/mus/mus_app.h index e90311a4..e07f0bd 100644 --- a/components/mus/mus_app.h +++ b/components/mus/mus_app.h
@@ -26,6 +26,10 @@ #include "services/shell/public/cpp/shell_client.h" #include "services/tracing/public/cpp/tracing_impl.h" +#if defined(USE_OZONE) +#include "ui/ozone/public/client_native_pixmap_factory.h" +#endif + namespace shell { class Connector; } @@ -115,6 +119,10 @@ UserIdToUserState user_id_to_user_state_; +#if defined(USE_OZONE) + scoped_ptr<ui::ClientNativePixmapFactory> client_native_pixmap_factory_; +#endif + DISALLOW_COPY_AND_ASSIGN(MandolineUIServicesApp); };
diff --git a/components/mus/ws/platform_display.cc b/components/mus/ws/platform_display.cc index cc0b748..bfb51c1 100644 --- a/components/mus/ws/platform_display.cc +++ b/components/mus/ws/platform_display.cc
@@ -358,7 +358,11 @@ } void DefaultPlatformDisplay::DispatchEvent(ui::Event* event) { - if (event->IsMouseEvent() && !event->IsMouseWheelEvent()) { + if (event->IsScrollEvent()) { + // TODO(moshayedi): crbug.com/602859. Dispatch scroll events as + // they are once we have proper support for scroll events. + delegate_->OnEvent(ui::MouseWheelEvent(*event->AsScrollEvent())); + } else if (event->IsMouseEvent() && !event->IsMouseWheelEvent()) { delegate_->OnEvent(ui::PointerEvent(*event->AsMouseEvent())); } else if (event->IsTouchEvent()) { delegate_->OnEvent(ui::PointerEvent(*event->AsTouchEvent()));
diff --git a/components/nacl/loader/nacl_ipc_adapter.cc b/components/nacl/loader/nacl_ipc_adapter.cc index 2613168..42e8b5f 100644 --- a/components/nacl/loader/nacl_ipc_adapter.cc +++ b/components/nacl/loader/nacl_ipc_adapter.cc
@@ -233,13 +233,9 @@ const base::SharedMemoryHandle& handle, size_t size) { #if defined(OS_MACOSX) - if (handle.GetType() == base::SharedMemoryHandle::MACH) { - return scoped_ptr<NaClDescWrapper>(new NaClDescWrapper( - NaClDescImcShmMachMake(handle.GetMemoryObject(), size))); - } - CHECK_EQ(base::SharedMemoryHandle::POSIX, handle.GetType()); -#endif - + return scoped_ptr<NaClDescWrapper>(new NaClDescWrapper( + NaClDescImcShmMachMake(handle.GetMemoryObject(), size))); +#else return scoped_ptr<NaClDescWrapper>(new NaClDescWrapper(NaClDescImcShmMake( #if defined(OS_WIN) handle.GetHandle(), @@ -247,6 +243,7 @@ base::SharedMemory::GetFdFromSharedMemoryHandle(handle), #endif size))); +#endif } } // namespace
diff --git a/components/navigation_metrics/navigation_metrics.cc b/components/navigation_metrics/navigation_metrics.cc index e0d61c76..e4c8ed5 100644 --- a/components/navigation_metrics/navigation_metrics.cc +++ b/components/navigation_metrics/navigation_metrics.cc
@@ -47,7 +47,10 @@ namespace navigation_metrics { -void RecordMainFrameNavigation(const GURL& url, bool is_in_page) { +void RecordMainFrameNavigation(const GURL& url, + bool is_in_page, + bool is_off_the_record, + bool have_already_seen_origin) { Scheme scheme = SCHEME_UNKNOWN; for (int i = 1; i < SCHEME_MAX; ++i) { if (url.SchemeIs(kSchemeNames[i])) { @@ -55,10 +58,21 @@ break; } } + + if (!have_already_seen_origin) { + if (is_off_the_record) { + UMA_HISTOGRAM_ENUMERATION("Navigation.SchemePerUniqueOriginOTR", scheme, + SCHEME_MAX); + } else { + UMA_HISTOGRAM_ENUMERATION("Navigation.SchemePerUniqueOrigin", scheme, + SCHEME_MAX); + } + } + UMA_HISTOGRAM_ENUMERATION("Navigation.MainFrameScheme", scheme, SCHEME_MAX); if (!is_in_page) { - UMA_HISTOGRAM_ENUMERATION( - "Navigation.MainFrameSchemeDifferentPage", scheme, SCHEME_MAX); + UMA_HISTOGRAM_ENUMERATION("Navigation.MainFrameSchemeDifferentPage", scheme, + SCHEME_MAX); } }
diff --git a/components/navigation_metrics/navigation_metrics.h b/components/navigation_metrics/navigation_metrics.h index aa6ef008..05176b7 100644 --- a/components/navigation_metrics/navigation_metrics.h +++ b/components/navigation_metrics/navigation_metrics.h
@@ -9,7 +9,10 @@ namespace navigation_metrics { -void RecordMainFrameNavigation(const GURL& url, bool is_in_page); +void RecordMainFrameNavigation(const GURL& url, + bool is_in_page, + bool is_off_the_record, + bool have_already_seen_origin); } // namespace navigation_metrics
diff --git a/components/ntp_snippets/ntp_snippets_service.cc b/components/ntp_snippets/ntp_snippets_service.cc index 38c98f1..79cdcb3 100644 --- a/components/ntp_snippets/ntp_snippets_service.cc +++ b/components/ntp_snippets/ntp_snippets_service.cc
@@ -68,7 +68,7 @@ } // Extracts the hosts from |suggestions| and returns them in a set. -std::set<std::string> GetSuggestionsHosts( +std::set<std::string> GetSuggestionsHostsImpl( const SuggestionsProfile& suggestions) { std::set<std::string> hosts; for (int i = 0; i < suggestions.suggestions_size(); ++i) { @@ -182,12 +182,37 @@ } void NTPSnippetsService::FetchSnippets() { + FetchSnippetsFromHosts(GetSuggestionsHosts()); +} + +void NTPSnippetsService::FetchSnippetsFromHosts( + const std::set<std::string>& hosts) { + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kDontRestrict)) { + snippets_fetcher_->FetchSnippets(std::set<std::string>()); + return; + } + if (!hosts.empty()) + snippets_fetcher_->FetchSnippets(hosts); +} + +void NTPSnippetsService::ClearSnippets() { + snippets_.clear(); + + StoreSnippetsToPrefs(); + + FOR_EACH_OBSERVER(NTPSnippetsServiceObserver, observers_, + NTPSnippetsServiceLoaded()); +} + +std::set<std::string> NTPSnippetsService::GetSuggestionsHosts() const { // |suggestions_service_| can be null in tests. if (!suggestions_service_) - return; + return std::set<std::string>(); - FetchSnippetsImpl(GetSuggestionsHosts( - suggestions_service_->GetSuggestionsDataFromCache())); + // TODO(treib) this should just call GetSnippetHostsFromPrefs + return GetSuggestionsHostsImpl( + suggestions_service_->GetSuggestionsDataFromCache()); } bool NTPSnippetsService::DiscardSnippet(const GURL& url) { @@ -201,9 +226,17 @@ snippets_.erase(it); StoreDiscardedSnippetsToPrefs(); StoreSnippetsToPrefs(); + FOR_EACH_OBSERVER(NTPSnippetsServiceObserver, observers_, + NTPSnippetsServiceLoaded()); return true; } +void NTPSnippetsService::ClearDiscardedSnippets() { + discarded_snippets_.clear(); + StoreDiscardedSnippetsToPrefs(); + FetchSnippets(); +} + void NTPSnippetsService::AddObserver(NTPSnippetsServiceObserver* observer) { observers_.AddObserver(observer); observer->NTPSnippetsServiceLoaded(); @@ -215,7 +248,7 @@ void NTPSnippetsService::OnSuggestionsChanged( const SuggestionsProfile& suggestions) { - std::set<std::string> hosts = GetSuggestionsHosts(suggestions); + std::set<std::string> hosts = GetSuggestionsHostsImpl(suggestions); if (hosts == GetSnippetHostsFromPrefs()) return; @@ -233,7 +266,7 @@ FOR_EACH_OBSERVER(NTPSnippetsServiceObserver, observers_, NTPSnippetsServiceLoaded()); - FetchSnippetsImpl(hosts); + FetchSnippetsFromHosts(hosts); } void NTPSnippetsService::OnSnippetsDownloaded( @@ -256,17 +289,6 @@ LOG(WARNING) << "Received invalid JSON (" << error << "): " << snippets_json; } -void NTPSnippetsService::FetchSnippetsImpl( - const std::set<std::string>& hosts) { - if (base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kDontRestrict)) { - snippets_fetcher_->FetchSnippets(std::set<std::string>()); - return; - } - if (!hosts.empty()) - snippets_fetcher_->FetchSnippets(hosts); -} - bool NTPSnippetsService::LoadFromValue(const base::Value& value) { const base::DictionaryValue* top_dict = nullptr; if (!value.GetAsDictionary(&top_dict))
diff --git a/components/ntp_snippets/ntp_snippets_service.h b/components/ntp_snippets/ntp_snippets_service.h index 0ba1efb..39e8dc8 100644 --- a/components/ntp_snippets/ntp_snippets_service.h +++ b/components/ntp_snippets/ntp_snippets_service.h
@@ -75,11 +75,29 @@ // Fetches snippets from the server and adds them to the current ones. void FetchSnippets(); + // Fetches snippets from the server for specified hosts (overriding + // suggestions from the suggestion service) and adds them to the current ones. + void FetchSnippetsFromHosts(const std::set<std::string>& hosts); + + // Deletes all currently stored snippets. + void ClearSnippets(); // Discards the snippet with the given |url|, if it exists. Returns true iff // a snippet was discarded. bool DiscardSnippet(const GURL& url); + // Returns the lists of snippets previously discarded by the user (that are + // not expired yet). + const NTPSnippetStorage& discarded_snippets() const { + return discarded_snippets_; + } + + // Clears the lists of snippets previously discarded by the user. + void ClearDiscardedSnippets(); + + // Returns the lists of suggestion hosts the snippets are restricted to. + std::set<std::string> GetSuggestionsHosts() const; + // Observer accessors. void AddObserver(NTPSnippetsServiceObserver* observer); void RemoveObserver(NTPSnippetsServiceObserver* observer); @@ -107,8 +125,6 @@ scoped_ptr<base::Value> parsed); void OnJsonError(const std::string& snippets_json, const std::string& error); - void FetchSnippetsImpl(const std::set<std::string>& hosts); - // Expects a top-level dictionary containing a "recos" list, which will be // passed to LoadFromListValue(). bool LoadFromValue(const base::Value& value);
diff --git a/components/ntp_snippets/ntp_snippets_service_unittest.cc b/components/ntp_snippets/ntp_snippets_service_unittest.cc index b4700c5d..b42a450 100644 --- a/components/ntp_snippets/ntp_snippets_service_unittest.cc +++ b/components/ntp_snippets/ntp_snippets_service_unittest.cc
@@ -184,6 +184,16 @@ } } +TEST_F(NTPSnippetsServiceTest, Clear) { + std::string json_str(GetTestJson()); + + LoadFromJSONString(json_str); + EXPECT_EQ(service()->size(), 1u); + + service()->ClearSnippets(); + EXPECT_EQ(service()->size(), 0u); +} + TEST_F(NTPSnippetsServiceTest, LoadInvalidJson) { SetExpectJsonParseSuccess(false); LoadFromJSONString(GetInvalidJson()); @@ -237,6 +247,31 @@ CreateSnippetsService(); LoadFromJSONString(json_str); EXPECT_EQ(0u, service()->size()); + + // The snippet can be added again after clearing discarded snippets. + service()->ClearDiscardedSnippets(); + EXPECT_EQ(0u, service()->size()); + LoadFromJSONString(json_str); + EXPECT_EQ(1u, service()->size()); +} + +TEST_F(NTPSnippetsServiceTest, GetDiscarded) { + std::string json_str( + "{ \"recos\": [ { \"contentInfo\": { \"url\" : \"http://site.com\" }}]}"); + LoadFromJSONString(json_str); + + // For the test, we need the snippet to get discarded. + ASSERT_TRUE(service()->DiscardSnippet(GURL("http://site.com"))); + const NTPSnippetsService::NTPSnippetStorage& snippets = + service()->discarded_snippets(); + EXPECT_EQ(1u, snippets.size()); + for (auto& snippet : snippets) { + EXPECT_EQ(GURL("http://site.com"), snippet->url()); + } + + // There should be no discarded snippet after clearing the list. + service()->ClearDiscardedSnippets(); + EXPECT_EQ(0u, service()->discarded_snippets().size()); } TEST_F(NTPSnippetsServiceTest, CreationTimestampParseFail) {
diff --git a/components/omnibox/browser/suggestion_answer.h b/components/omnibox/browser/suggestion_answer.h index 0a8a25d8..ef4964d 100644 --- a/components/omnibox/browser/suggestion_answer.h +++ b/components/omnibox/browser/suggestion_answer.h
@@ -39,18 +39,18 @@ // These values are named and numbered to match a specification at go/ais_api. // The values are only used for answer results. enum TextType { - ANSWER = 1, - HEADLINE = 2, + // Deprecated: ANSWER = 1, + // Deprecated: HEADLINE = 2, TOP_ALIGNED = 3, - DESCRIPTION = 4, + // Deprecated: DESCRIPTION = 4, DESCRIPTION_NEGATIVE = 5, DESCRIPTION_POSITIVE = 6, - MORE_INFO = 7, + // Deprecated: MORE_INFO = 7, SUGGESTION = 8, - SUGGESTION_POSITIVE = 9, - SUGGESTION_NEGATIVE = 10, - SUGGESTION_LINK = 11, - STATUS = 12, + // Deprecated: SUGGESTION_POSITIVE = 9, + // Deprecated: SUGGESTION_NEGATIVE = 10, + // Deprecated: SUGGESTION_LINK = 11, + // Deprecated: STATUS = 12, PERSONALIZED_SUGGESTION = 13, // Deprecated: IMMERSIVE_DESCRIPTION_TEXT = 14, // Deprecated: DATE_TEXT = 15,
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index 31b61a4e..3b37a9d 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -8351,10 +8351,10 @@ 'name': 'DeviceAllowBluetooth', 'type': 'main', 'schema': { 'type': 'boolean' }, - 'supported_on': ['chrome_os:51-'], + 'supported_on': ['chrome_os:52-'], 'device_only': True, 'features': { - 'dynamic_refresh': True, + 'dynamic_refresh': False, }, 'example_value': True, 'id': 323, @@ -8364,7 +8364,9 @@ If this policy is set to true or left unset, the user will be able to enable or disable Bluetooth as he wishes. - If this policy is set, the user cannot change or override it.''', + If this policy is set, the user cannot change or override it. + + After enabling Bluetooth, the device must be rebooted for the changes to take effect (no need to reboot the device when disabling Bluetooth).''', }, { 'name': 'SuppressUnsupportedOSWarning',
diff --git a/components/proximity_auth/cryptauth/cryptauth_api_call_flow_unittest.cc b/components/proximity_auth/cryptauth/cryptauth_api_call_flow_unittest.cc index 14e23b8b..87de7ce 100644 --- a/components/proximity_auth/cryptauth/cryptauth_api_call_flow_unittest.cc +++ b/components/proximity_auth/cryptauth/cryptauth_api_call_flow_unittest.cc
@@ -5,6 +5,7 @@ #include "components/proximity_auth/cryptauth/cryptauth_api_call_flow.h" #include "base/macros.h" +#include "base/memory/scoped_ptr.h" #include "base/test/test_simple_task_runner.h" #include "net/base/net_errors.h" #include "net/url_request/test_url_fetcher_factory.h"
diff --git a/components/resource_provider/file_utils.cc b/components/resource_provider/file_utils.cc index b8063da..756428e 100644 --- a/components/resource_provider/file_utils.cc +++ b/components/resource_provider/file_utils.cc
@@ -49,13 +49,6 @@ if (end_of_name != std::string::npos) path.erase(path.begin() + end_of_name, path.end()); - // TODO(beng): I'm adding this because there is a collision between the - // executable name in the exe dir and the resource package dir on - // non-Windows systems. Arbitrary exes should probably load their - // resources themselves rather than use resource provider. - if (is_exe) - path += "_res"; - if (!IsPathNameValid(path)) return base::FilePath();
diff --git a/components/safe_browsing_db/BUILD.gn b/components/safe_browsing_db/BUILD.gn index 4f91591..dc5c80a 100644 --- a/components/safe_browsing_db/BUILD.gn +++ b/components/safe_browsing_db/BUILD.gn
@@ -219,7 +219,6 @@ source_set("unit_tests") { testonly = true sources = [ - "database_manager_unittest.cc", "prefix_set_unittest.cc", "util_unittest.cc", "v4_get_hash_protocol_manager_unittest.cc", @@ -227,17 +226,14 @@ "v4_update_protocol_manager_unittest.cc", ] deps = [ - ":database_manager", ":prefix_set", ":proto", - ":test_database_manager", ":util", ":v4_get_hash_protocol_manager", ":v4_local_database_manager", ":v4_protocol_manager_util", ":v4_update_protocol_manager", "//base", - "//content/test:test_support", "//net", "//net:test_support", "//testing/gtest",
diff --git a/components/safe_browsing_db/DEPS b/components/safe_browsing_db/DEPS index 2130e6f..8bf7b58 100644 --- a/components/safe_browsing_db/DEPS +++ b/components/safe_browsing_db/DEPS
@@ -2,7 +2,6 @@ "+components/variations", "+content/public/browser", "+content/public/common", - "+content/public/test", "+crypto", "+net", ]
diff --git a/components/safe_browsing_db/database_manager.cc b/components/safe_browsing_db/database_manager.cc index c8d7aa3..b8998b4 100644 --- a/components/safe_browsing_db/database_manager.cc +++ b/components/safe_browsing_db/database_manager.cc
@@ -25,9 +25,11 @@ net::URLRequestContextGetter* request_context_getter, const V4ProtocolConfig& config) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - - v4_get_hash_protocol_manager_ = V4GetHashProtocolManager::Create( - request_context_getter, config); + if (request_context_getter) { + // Instantiate a V4GetHashProtocolManager. + v4_get_hash_protocol_manager_ = V4GetHashProtocolManager::Create( + request_context_getter, config); + } } // |shutdown| not used. Destroys the v4 protocol managers. This may be called @@ -40,61 +42,11 @@ delete v4_get_hash_protocol_manager_; v4_get_hash_protocol_manager_ = NULL; } - // TODO(kcarattini): Call back clients with pending requests. } -bool SafeBrowsingDatabaseManager::CheckApiBlacklistUrl(const GURL& url, +void SafeBrowsingDatabaseManager::CheckApiBlacklistUrl(const GURL& url, Client* client) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - DCHECK(v4_get_hash_protocol_manager_); - - // Make sure we can check this url. - if (!(url.SchemeIs(url::kHttpScheme) || url.SchemeIs(url::kHttpsScheme))) { - return true; - } - - // Compute a list of hashes for this url. - std::vector<SBFullHash> full_hashes; - UrlToFullHashes(url, false, &full_hashes); - if (full_hashes.empty()) - return true; - - // Copy to prefixes. - std::vector<SBPrefix> prefixes; - for (const SBFullHash& full_hash : full_hashes) { - prefixes.push_back(full_hash.prefix); - } - // Multiple full hashes could share a prefix, remove duplicates. - std::sort(prefixes.begin(), prefixes.end()); - prefixes.erase(std::unique(prefixes.begin(), prefixes.end()), prefixes.end()); - DCHECK(!prefixes.empty()); - - // TODO(kcarattini): Track checks in a map. - std::shared_ptr<SafeBrowsingApiCheck> check( - new SafeBrowsingApiCheck(url, full_hashes, client)); - - // TODO(kcarattini): Implement cache compliance. - v4_get_hash_protocol_manager_->GetFullHashesWithApis(prefixes, - base::Bind(&SafeBrowsingDatabaseManager::HandleGetHashesWithApisResults, - base::Unretained(this), check)); - - return false; -} - -void SafeBrowsingDatabaseManager::HandleGetHashesWithApisResults( - std::shared_ptr<SafeBrowsingApiCheck> check, - const std::vector<SBFullHashResult>& full_hash_results, - const base::TimeDelta& negative_cache_duration) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - // TODO(kcarattini): Implement response handler. -} - -SafeBrowsingDatabaseManager::SafeBrowsingApiCheck::SafeBrowsingApiCheck( - const GURL& url, const std::vector<SBFullHash>& full_hashes, Client* client) - : url_(url), full_hashes_(full_hashes), client_(client) { -} - -SafeBrowsingDatabaseManager::SafeBrowsingApiCheck::~SafeBrowsingApiCheck() { + // TODO(kcarattini): Implement this. } } // namespace safe_browsing
diff --git a/components/safe_browsing_db/database_manager.h b/components/safe_browsing_db/database_manager.h index 083bd0e..12d893d 100644 --- a/components/safe_browsing_db/database_manager.h +++ b/components/safe_browsing_db/database_manager.h
@@ -14,8 +14,6 @@ #include <string> #include <vector> -#include "base/gtest_prod_util.h" -#include "base/macros.h" #include "base/memory/ref_counted.h" #include "components/safe_browsing_db/hit_report.h" #include "components/safe_browsing_db/util.h" @@ -65,6 +63,7 @@ const std::string& threat_hash) {} }; + // Returns true if URL-checking is supported on this build+device. // If false, calls to CheckBrowseUrl may dcheck-fail. virtual bool IsSupported() const = 0; @@ -149,20 +148,15 @@ virtual bool IsCsdWhitelistKillSwitchOn() = 0; // Called on the IO thread to cancel a pending check if the result is no - // longer needed. Also called after the result has been handled. Api checks - // are handled separately. To cancel an API check use CancelApiCheck. + // longer needed. Also called after the result has been handled. virtual void CancelCheck(Client* client) = 0; - // TODO(kcarattini): Add a CancelApiCheck method. - // Called on the IO thread to check if the given url has blacklisted APIs. // "client" is called asynchronously with the result when it is ready. // This method has the same implementation for both the local and remote // database managers since it pings Safe Browsing servers directly without - // accessing the database at all. Returns true if we can synchronously - // determine that the url is safe. Otherwise it returns false, and "client" is - // called asynchronously with the result when it is ready. - virtual bool CheckApiBlacklistUrl(const GURL& url, Client* client); + // accessing the database at all. + virtual void CheckApiBlacklistUrl(const GURL& url, Client* client); // Called to initialize objects that are used on the io_thread, such as the // v4 protocol manager. This may be called multiple times during the life of @@ -181,35 +175,7 @@ friend class base::RefCountedThreadSafe<SafeBrowsingDatabaseManager>; - FRIEND_TEST_ALL_PREFIXES(SafeBrowsingDatabaseManagerTest, - CheckApiBlacklistUrlPrefixes); - - // Bundled client info for an API abuse hash prefix check. - class SafeBrowsingApiCheck { - public: - SafeBrowsingApiCheck(const GURL& url, - const std::vector<SBFullHash>& full_hashes, - Client* client); - ~SafeBrowsingApiCheck(); - - private: - GURL url_; - std::vector<SBFullHash> full_hashes_; - // Not owned. - SafeBrowsingDatabaseManager::Client* client_; - - DISALLOW_COPY_AND_ASSIGN(SafeBrowsingApiCheck); - }; - - // Called on the IO thread wheh the SafeBrowsingProtocolManager has received - // the full hash and api results for prefixes of the |url| argument in - // CheckApiBlacklistUrl. - virtual void HandleGetHashesWithApisResults( - std::shared_ptr<SafeBrowsingApiCheck> check, - const std::vector<SBFullHashResult>& full_hash_results, - const base::TimeDelta& negative_cache_duration); - - // Created and destroyed via StartOnIOThread/StopOnIOThread. + // Created and destroyed via StartonIOThread/StopOnIOThread. V4GetHashProtocolManager* v4_get_hash_protocol_manager_; }; // class SafeBrowsingDatabaseManager
diff --git a/components/safe_browsing_db/database_manager_unittest.cc b/components/safe_browsing_db/database_manager_unittest.cc deleted file mode 100644 index 04490d9..0000000 --- a/components/safe_browsing_db/database_manager_unittest.cc +++ /dev/null
@@ -1,134 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stddef.h> - -#include <string> -#include <vector> - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/run_loop.h" -#include "components/safe_browsing_db/database_manager.h" -#include "components/safe_browsing_db/test_database_manager.h" -#include "components/safe_browsing_db/v4_get_hash_protocol_manager.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -using content::BrowserThread; - -namespace safe_browsing { - -namespace { - -// A TestV4GetHashProtocolManager that returns fixed responses from the -// Safe Browsing server for testing purpose. -class TestV4GetHashProtocolManager : public V4GetHashProtocolManager { - public: - TestV4GetHashProtocolManager( - net::URLRequestContextGetter* request_context_getter, - const V4ProtocolConfig& config) - : V4GetHashProtocolManager(request_context_getter, config) {} - - ~TestV4GetHashProtocolManager() override {} - - void GetFullHashesWithApis(const std::vector<SBPrefix>& prefixes, - FullHashCallback callback) override { - prefixes_ = prefixes; - callback.Run(full_hashes_, base::TimeDelta::FromMinutes(0)); - } - - // Prepare the GetFullHash results for the next request. - void AddGetFullHashResponse(const SBFullHashResult& full_hash_result) { - full_hashes_.push_back(full_hash_result); - } - - // Returns the prefixes that were sent in the last request. - const std::vector<SBPrefix>& GetRequestPrefixes() { return prefixes_; } - - private: - std::vector<SBPrefix> prefixes_; - std::vector<SBFullHashResult> full_hashes_; -}; - -// Factory that creates test protocol manager instances. -class TestV4GetHashProtocolManagerFactory : - public V4GetHashProtocolManagerFactory { - public: - TestV4GetHashProtocolManagerFactory() : pm_(NULL) {} - ~TestV4GetHashProtocolManagerFactory() override {} - - V4GetHashProtocolManager* CreateProtocolManager( - net::URLRequestContextGetter* request_context_getter, - const V4ProtocolConfig& config) override { - pm_ = new TestV4GetHashProtocolManager(request_context_getter, config); - return pm_; - } - - private: - // Owned by the SafeBrowsingDatabaseManager. - TestV4GetHashProtocolManager* pm_; -}; - -class TestClient : public SafeBrowsingDatabaseManager::Client { - public: - TestClient() {} - ~TestClient() override {} - - void OnCheckApiBlacklistUrlResult(const GURL& url, - const ThreatMetadata& metadata) override {} - - private: - DISALLOW_COPY_AND_ASSIGN(TestClient); -}; - -} // namespace - -class SafeBrowsingDatabaseManagerTest : public testing::Test { - protected: - void SetUp() override { - TestV4GetHashProtocolManagerFactory get_hash_pm_factory; - V4GetHashProtocolManager::RegisterFactory(&get_hash_pm_factory); - - db_manager_ = new TestSafeBrowsingDatabaseManager(); - db_manager_->StartOnIOThread(NULL, V4ProtocolConfig()); - } - - void TearDown() override { - base::RunLoop().RunUntilIdle(); - db_manager_->StopOnIOThread(false); - } - - scoped_refptr<SafeBrowsingDatabaseManager> db_manager_; - - private: - content::TestBrowserThreadBundle test_browser_thread_bundle_; -}; - -TEST_F(SafeBrowsingDatabaseManagerTest, CheckApiBlacklistUrlWrongScheme) { - TestClient client; - const GURL url("file://example.txt"); - EXPECT_TRUE(db_manager_->CheckApiBlacklistUrl(url, &client)); -} - -TEST_F(SafeBrowsingDatabaseManagerTest, CheckApiBlacklistUrlPrefixes) { - TestClient client; - const GURL url("https://www.example.com/more"); - // Generated from the sorted output of UrlToFullHashes in util.h. - std::vector<SBPrefix> expected_prefixes = - {1237562338, 2871045197, 3553205461, 3766933875}; - - EXPECT_FALSE(db_manager_->CheckApiBlacklistUrl(url, &client)); - std::vector<SBPrefix> prefixes = static_cast<TestV4GetHashProtocolManager*>( - db_manager_->v4_get_hash_protocol_manager_)->GetRequestPrefixes(); - EXPECT_EQ(expected_prefixes.size(), prefixes.size()); - for (unsigned int i = 0; i < prefixes.size(); ++i) { - EXPECT_EQ(expected_prefixes[i], prefixes[i]); - } -} - -} // namespace safe_browsing
diff --git a/components/safe_browsing_db/test_database_manager.cc b/components/safe_browsing_db/test_database_manager.cc index 1c3a91e..478e064 100644 --- a/components/safe_browsing_db/test_database_manager.cc +++ b/components/safe_browsing_db/test_database_manager.cc
@@ -120,4 +120,17 @@ NOTIMPLEMENTED(); } +void TestSafeBrowsingDatabaseManager::CheckApiBlacklistUrl(const GURL& url, + Client* client) { + NOTIMPLEMENTED(); +} + +void TestSafeBrowsingDatabaseManager::StartOnIOThread( + net::URLRequestContextGetter* request_context_getter, + const V4ProtocolConfig& config) { +} + +void TestSafeBrowsingDatabaseManager::StopOnIOThread(bool shutdown) { +} + } // namespace safe_browsing
diff --git a/components/safe_browsing_db/test_database_manager.h b/components/safe_browsing_db/test_database_manager.h index ae98b9a1..eb7fcfd 100644 --- a/components/safe_browsing_db/test_database_manager.h +++ b/components/safe_browsing_db/test_database_manager.h
@@ -21,8 +21,7 @@ // This is a non-pure-virtual implementation of the SafeBrowsingDatabaseManager // interface. It's used in tests by overriding only the functions that get -// called, and it'll complain if you call one that isn't overriden. The -// non-abstract methods in the base class are not overridden. +// called, and it'll complain if you call one that isn't overriden. class TestSafeBrowsingDatabaseManager : public SafeBrowsingDatabaseManager { public: @@ -48,6 +47,11 @@ bool IsMalwareKillSwitchOn() override; bool IsCsdWhitelistKillSwitchOn() override; void CancelCheck(Client* client) override; + void CheckApiBlacklistUrl(const GURL& url, Client* client) override; + void StartOnIOThread( + net::URLRequestContextGetter* request_context_getter, + const V4ProtocolConfig& config) override; + void StopOnIOThread(bool shutdown) override; protected: ~TestSafeBrowsingDatabaseManager() override {};
diff --git a/components/signin/core/browser/refresh_token_annotation_request.h b/components/signin/core/browser/refresh_token_annotation_request.h index a276697..9d8134cf 100644 --- a/components/signin/core/browser/refresh_token_annotation_request.h +++ b/components/signin/core/browser/refresh_token_annotation_request.h
@@ -8,6 +8,7 @@ #include "base/callback.h" #include "base/gtest_prod_util.h" #include "base/macros.h" +#include "base/memory/scoped_ptr.h" #include "base/threading/non_thread_safe.h" #include "google_apis/gaia/oauth2_api_call_flow.h" #include "google_apis/gaia/oauth2_token_service.h"
diff --git a/components/sync_driver/sync_stopped_reporter.h b/components/sync_driver/sync_stopped_reporter.h index 251ef336..c7e2d1d6 100644 --- a/components/sync_driver/sync_stopped_reporter.h +++ b/components/sync_driver/sync_stopped_reporter.h
@@ -9,6 +9,7 @@ #include "base/callback.h" #include "base/macros.h" +#include "base/memory/scoped_ptr.h" #include "base/timer/timer.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_delegate.h"
diff --git a/components/test_runner/test_runner.cc b/components/test_runner/test_runner.cc index 39855fd..34af6df2 100644 --- a/components/test_runner/test_runner.cc +++ b/components/test_runner/test_runner.cc
@@ -1852,6 +1852,7 @@ void TestRunner::ReplicateLayoutTestRuntimeFlagsChanges( const base::DictionaryValue& changed_values) { + DCHECK(test_is_running_); layout_test_runtime_flags_.tracked_dictionary().ApplyUntrackedChanges( changed_values); }
diff --git a/content/DEPS b/content/DEPS index 0518328..f5efa16c 100644 --- a/content/DEPS +++ b/content/DEPS
@@ -115,7 +115,7 @@ # content -> content/shell dependency is not allowed, except for browser tests. specific_include_rules = { - ".*_browsertest[a-z_]*\.cc": [ + ".*_browsertest[a-z_]*\.(cc|h)": [ "+content/shell/browser", "+content/shell/common", ],
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index c1ee66e..5e4b8de 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -340,7 +340,6 @@ "media/session/media_session_delegate_default.cc", "power_usage_monitor_impl.cc", "power_usage_monitor_impl.h", - "renderer_host/begin_frame_observer_proxy.cc", "tracing/tracing_ui.cc", "tracing/tracing_ui.h",
diff --git a/content/browser/android/content_view_core_impl.cc b/content/browser/android/content_view_core_impl.cc index 82c2b5e..5401267 100644 --- a/content/browser/android/content_view_core_impl.cc +++ b/content/browser/android/content_view_core_impl.cc
@@ -681,21 +681,6 @@ static_cast<jint>(y_dip * dpi_scale())); } -void ContentViewCoreImpl::GetScaledContentBitmap( - float scale, - SkColorType preferred_color_type, - const gfx::Rect& src_subrect, - const ReadbackRequestCallback& result_callback) { - RenderWidgetHostViewAndroid* view = GetRenderWidgetHostViewAndroid(); - if (!view || preferred_color_type == kUnknown_SkColorType) { - result_callback.Run(SkBitmap(), READBACK_FAILED); - return; - } - - view->GetScaledContentBitmap(scale, preferred_color_type, src_subrect, - result_callback); -} - void ContentViewCoreImpl::StartContentIntent(const GURL& content_url, bool is_main_frame) { JNIEnv* env = AttachCurrentThread();
diff --git a/content/browser/android/content_view_core_impl.h b/content/browser/android/content_view_core_impl.h index b022e7e..d768f67 100644 --- a/content/browser/android/content_view_core_impl.h +++ b/content/browser/android/content_view_core_impl.h
@@ -61,11 +61,6 @@ ui::WindowAndroid* GetWindowAndroid() const override; const scoped_refptr<cc::Layer>& GetLayer() const override; bool ShowPastePopup(int x, int y) override; - void GetScaledContentBitmap( - float scale, - SkColorType preferred_color_type, - const gfx::Rect& src_subrect, - const ReadbackRequestCallback& result_callback) override; float GetDpiScale() const override; void PauseOrResumeGeolocation(bool should_pause) override; void RequestTextSurroundingSelection(
diff --git a/content/browser/android/in_process/context_provider_in_process.cc b/content/browser/android/in_process/context_provider_in_process.cc deleted file mode 100644 index bdab089..0000000 --- a/content/browser/android/in_process/context_provider_in_process.cc +++ /dev/null
@@ -1,186 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/android/in_process/context_provider_in_process.h" - -#include <stddef.h> -#include <utility> - -#include "base/bind.h" -#include "base/callback_helpers.h" -#include "base/strings/stringprintf.h" -#include "cc/output/managed_memory_policy.h" -#include "gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.h" -#include "gpu/command_buffer/client/gles2_implementation.h" -#include "gpu/skia_bindings/grcontext_for_gles2_interface.h" -#include "third_party/skia/include/gpu/GrContext.h" - -using gpu_blink::WebGraphicsContext3DInProcessCommandBufferImpl; - -namespace content { - -class ContextProviderInProcess::LostContextCallbackProxy - : public blink::WebGraphicsContext3D::WebGraphicsContextLostCallback { - public: - explicit LostContextCallbackProxy(ContextProviderInProcess* provider) - : provider_(provider) { - provider_->context3d_->setContextLostCallback(this); - } - - ~LostContextCallbackProxy() override { - provider_->context3d_->setContextLostCallback(nullptr); - } - - void onContextLost() override { - provider_->OnLostContext(); - } - - private: - ContextProviderInProcess* provider_; -}; - -// static -scoped_refptr<ContextProviderInProcess> ContextProviderInProcess::Create( - std::unique_ptr<WebGraphicsContext3DInProcessCommandBufferImpl> context3d, - const std::string& debug_name) { - if (!context3d) - return nullptr; - return new ContextProviderInProcess(std::move(context3d), debug_name); -} - -ContextProviderInProcess::ContextProviderInProcess( - std::unique_ptr<WebGraphicsContext3DInProcessCommandBufferImpl> context3d, - const std::string& debug_name) - : context3d_(std::move(context3d)), debug_name_(debug_name) { - DCHECK(main_thread_checker_.CalledOnValidThread()); - DCHECK(context3d_); - context_thread_checker_.DetachFromThread(); -} - -ContextProviderInProcess::~ContextProviderInProcess() { - DCHECK(main_thread_checker_.CalledOnValidThread() || - context_thread_checker_.CalledOnValidThread()); -} - -blink::WebGraphicsContext3D* ContextProviderInProcess::WebContext3D() { - DCHECK(lost_context_callback_proxy_); // Is bound to thread. - DCHECK(context_thread_checker_.CalledOnValidThread()); - - return context3d_.get(); -} - -bool ContextProviderInProcess::BindToCurrentThread() { - DCHECK(context3d_); - - // This is called on the thread the context will be used. - DCHECK(context_thread_checker_.CalledOnValidThread()); - - if (lost_context_callback_proxy_) - return true; - - if (!context3d_->InitializeOnCurrentThread()) - return false; - - InitializeCapabilities(); - - const std::string unique_context_name = - base::StringPrintf("%s-%p", debug_name_.c_str(), context3d_.get()); - ContextGL()->TraceBeginCHROMIUM("gpu_toplevel", unique_context_name.c_str()); - - lost_context_callback_proxy_.reset(new LostContextCallbackProxy(this)); - return true; -} - -void ContextProviderInProcess::DetachFromThread() { - context_thread_checker_.DetachFromThread(); -} - -void ContextProviderInProcess::InitializeCapabilities() { - capabilities_.gpu = context3d_->GetImplementation()->capabilities(); - - size_t mapped_memory_limit = context3d_->GetMappedMemoryLimit(); - capabilities_.max_transfer_buffer_usage_bytes = - mapped_memory_limit == - WebGraphicsContext3DInProcessCommandBufferImpl::kNoLimit - ? std::numeric_limits<size_t>::max() - : mapped_memory_limit; -} - -cc::ContextProvider::Capabilities -ContextProviderInProcess::ContextCapabilities() { - DCHECK(lost_context_callback_proxy_); // Is bound to thread. - DCHECK(context_thread_checker_.CalledOnValidThread()); - return capabilities_; -} - -::gpu::gles2::GLES2Interface* ContextProviderInProcess::ContextGL() { - DCHECK(context3d_); - DCHECK(lost_context_callback_proxy_); // Is bound to thread. - DCHECK(context_thread_checker_.CalledOnValidThread()); - - return context3d_->GetGLInterface(); -} - -::gpu::ContextSupport* ContextProviderInProcess::ContextSupport() { - DCHECK(context3d_); - if (!lost_context_callback_proxy_) - return NULL; // Not bound to anything. - - DCHECK(context_thread_checker_.CalledOnValidThread()); - - return context3d_->GetContextSupport(); -} - -class GrContext* ContextProviderInProcess::GrContext() { - DCHECK(lost_context_callback_proxy_); // Is bound to thread. - DCHECK(context_thread_checker_.CalledOnValidThread()); - - if (gr_context_) - return gr_context_->get(); - - gr_context_.reset(new skia_bindings::GrContextForGLES2Interface( - context3d_->GetGLInterface())); - return gr_context_->get(); -} - -void ContextProviderInProcess::InvalidateGrContext(uint32_t state) { - DCHECK(lost_context_callback_proxy_); // Is bound to thread. - DCHECK(context_thread_checker_.CalledOnValidThread()); - - if (gr_context_) - return gr_context_->ResetContext(state); -} - -void ContextProviderInProcess::SetupLock() { - context3d_->SetLock(&context_lock_); -} - -base::Lock* ContextProviderInProcess::GetLock() { - return &context_lock_; -} - -void ContextProviderInProcess::DeleteCachedResources() { - DCHECK(context_thread_checker_.CalledOnValidThread()); - - if (gr_context_) - gr_context_->FreeGpuResources(); -} - -void ContextProviderInProcess::OnLostContext() { - DCHECK(context_thread_checker_.CalledOnValidThread()); - if (!lost_context_callback_.is_null()) - lost_context_callback_.Run(); - if (gr_context_) - gr_context_->OnLostContext(); -} - -void ContextProviderInProcess::SetLostContextCallback( - const LostContextCallback& lost_context_callback) { - DCHECK(context_thread_checker_.CalledOnValidThread()); - DCHECK(lost_context_callback_.is_null() || - lost_context_callback.is_null()); - lost_context_callback_ = lost_context_callback; -} - -} // namespace content
diff --git a/content/browser/android/in_process/context_provider_in_process.h b/content/browser/android/in_process/context_provider_in_process.h deleted file mode 100644 index 8baf1c4..0000000 --- a/content/browser/android/in_process/context_provider_in_process.h +++ /dev/null
@@ -1,86 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_BROWSER_ANDROID_IN_PROCESS_CONTEXT_PROVIDER_IN_PROCESS_H_ -#define CONTENT_BROWSER_ANDROID_IN_PROCESS_CONTEXT_PROVIDER_IN_PROCESS_H_ - -#include <stdint.h> - -#include <memory> -#include <string> - -#include "base/macros.h" -#include "base/synchronization/lock.h" -#include "base/threading/thread_checker.h" -#include "cc/blink/context_provider_web_context.h" - -namespace blink { class WebGraphicsContext3D; } - -namespace gpu_blink { -class WebGraphicsContext3DInProcessCommandBufferImpl; -} - -namespace skia_bindings { -class GrContextForGLES2Interface; -} - -namespace content { - -class ContextProviderInProcess - : NON_EXPORTED_BASE(public cc_blink::ContextProviderWebContext) { - public: - static scoped_refptr<ContextProviderInProcess> Create( - std::unique_ptr<gpu_blink::WebGraphicsContext3DInProcessCommandBufferImpl> - context3d, - const std::string& debug_name); - - private: - ContextProviderInProcess( - std::unique_ptr<gpu_blink::WebGraphicsContext3DInProcessCommandBufferImpl> - context3d, - const std::string& debug_name); - ~ContextProviderInProcess() override; - - // cc_blink::ContextProviderWebContext: - blink::WebGraphicsContext3D* WebContext3D() override; - - // cc::ContextProvider: - bool BindToCurrentThread() override; - void DetachFromThread() override; - Capabilities ContextCapabilities() override; - ::gpu::gles2::GLES2Interface* ContextGL() override; - ::gpu::ContextSupport* ContextSupport() override; - class GrContext* GrContext() override; - void InvalidateGrContext(uint32_t state) override; - void SetupLock() override; - base::Lock* GetLock() override; - void DeleteCachedResources() override; - void SetLostContextCallback( - const LostContextCallback& lost_context_callback) override; - - void OnLostContext(); - void InitializeCapabilities(); - - base::ThreadChecker main_thread_checker_; - base::ThreadChecker context_thread_checker_; - - std::unique_ptr<gpu_blink::WebGraphicsContext3DInProcessCommandBufferImpl> - context3d_; - std::unique_ptr<skia_bindings::GrContextForGLES2Interface> gr_context_; - - LostContextCallback lost_context_callback_; - - base::Lock context_lock_; - std::string debug_name_; - class LostContextCallbackProxy; - std::unique_ptr<LostContextCallbackProxy> lost_context_callback_proxy_; - - cc::ContextProvider::Capabilities capabilities_; - - DISALLOW_COPY_AND_ASSIGN(ContextProviderInProcess); -}; - -} // namespace content - -#endif // CONTENT_BROWSER_ANDROID_IN_PROCESS_CONTEXT_PROVIDER_IN_PROCESS_H_
diff --git a/content/browser/android/in_process/synchronous_compositor_factory_impl.cc b/content/browser/android/in_process/synchronous_compositor_factory_impl.cc index 720c56d..76331a11 100644 --- a/content/browser/android/in_process/synchronous_compositor_factory_impl.cc +++ b/content/browser/android/in_process/synchronous_compositor_factory_impl.cc
@@ -11,70 +11,21 @@ #include "base/command_line.h" #include "base/macros.h" #include "base/memory/ptr_util.h" -#include "base/observer_list.h" -#include "base/sys_info.h" #include "base/thread_task_runner_handle.h" -#include "content/browser/android/in_process/context_provider_in_process.h" #include "content/browser/android/in_process/synchronous_compositor_impl.h" #include "content/browser/android/in_process/synchronous_compositor_registry_in_proc.h" -#include "content/browser/gpu/browser_gpu_memory_buffer_manager.h" -#include "content/common/gpu/client/context_provider_command_buffer.h" -#include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_switches.h" #include "content/renderer/android/synchronous_compositor_external_begin_frame_source.h" #include "content/renderer/android/synchronous_compositor_output_surface.h" #include "content/renderer/gpu/frame_swap_message_queue.h" #include "content/renderer/render_thread_impl.h" -#include "gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.h" -#include "gpu/command_buffer/client/gl_in_process_context.h" #include "gpu/command_buffer/client/gles2_interface.h" #include "gpu/command_buffer/common/gles2_cmd_utils.h" #include "gpu/ipc/client/gpu_channel_host.h" -#include "ui/gl/android/surface_texture.h" -#include "ui/gl/gl_surface.h" -#include "ui/gl/gl_surface_stub.h" - -using cc_blink::ContextProviderWebContext; -using gpu_blink::WebGraphicsContext3DImpl; -using gpu_blink::WebGraphicsContext3DInProcessCommandBufferImpl; namespace content { -namespace { - -struct ContextHolder { - std::unique_ptr<WebGraphicsContext3DInProcessCommandBufferImpl> - command_buffer; - gpu::GLInProcessContext* gl_in_process_context; -}; - -ContextHolder CreateContextHolder( - const gpu::gles2::ContextCreationAttribHelper& attributes, - scoped_refptr<gpu::InProcessCommandBuffer::Service> service, - const gpu::GLInProcessContextSharedMemoryLimits& mem_limits) { - bool is_offscreen = true; - std::unique_ptr<gpu::GLInProcessContext> context( - gpu::GLInProcessContext::Create( - service, nullptr /* surface */, is_offscreen, - gfx::kNullAcceleratedWidget, gfx::Size(1, 1), - nullptr /* share_context */, attributes, gfx::PreferDiscreteGpu, - mem_limits, BrowserGpuMemoryBufferManager::current(), nullptr)); - - gpu::GLInProcessContext* context_ptr = context.get(); - - ContextHolder holder; - holder.command_buffer = - std::unique_ptr<WebGraphicsContext3DInProcessCommandBufferImpl>( - WebGraphicsContext3DInProcessCommandBufferImpl::WrapContext( - std::move(context), attributes)); - holder.gl_in_process_context = context_ptr; - - return holder; -} - -} // namespace - SynchronousCompositorFactoryImpl::SynchronousCompositorFactoryImpl() { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kSingleProcess)) { @@ -120,161 +71,4 @@ routing_id, SynchronousCompositorRegistryInProc::GetInstance())); } -// SynchronousCompositorStreamTextureFactoryImpl. - -class SynchronousCompositorStreamTextureFactoryImpl::VideoContextProvider - : public StreamTextureFactorySynchronousImpl::ContextProvider { - public: - VideoContextProvider(scoped_refptr<cc::ContextProvider> context_provider, - gpu::GLInProcessContext* gl_in_process_context) - : context_provider_(context_provider), - gl_in_process_context_(gl_in_process_context) { - context_provider_->BindToCurrentThread(); - } - - scoped_refptr<gfx::SurfaceTexture> GetSurfaceTexture( - uint32_t stream_id) override { - return gl_in_process_context_->GetSurfaceTexture(stream_id); - } - - uint32_t CreateStreamTexture(uint32_t texture_id) override { - return gl_in_process_context_->CreateStreamTexture(texture_id); - } - - gpu::gles2::GLES2Interface* ContextGL() override { - return context_provider_->ContextGL(); - } - - void AddObserver(StreamTextureFactoryContextObserver* obs) override { - observer_list_.AddObserver(obs); - } - - void RemoveObserver(StreamTextureFactoryContextObserver* obs) override { - observer_list_.RemoveObserver(obs); - } - - void RestoreContext() { - FOR_EACH_OBSERVER(StreamTextureFactoryContextObserver, observer_list_, - ResetStreamTextureProxy()); - } - - private: - friend class base::RefCountedThreadSafe<VideoContextProvider>; - ~VideoContextProvider() override {} - - scoped_refptr<cc::ContextProvider> context_provider_; - gpu::GLInProcessContext* gl_in_process_context_; - base::ObserverList<StreamTextureFactoryContextObserver> observer_list_; - - DISALLOW_COPY_AND_ASSIGN(VideoContextProvider); -}; - -namespace { -base::LazyInstance<SynchronousCompositorStreamTextureFactoryImpl>::Leaky - g_stream_texture_factory = LAZY_INSTANCE_INITIALIZER; -} // namespace - -// static -SynchronousCompositorStreamTextureFactoryImpl* -SynchronousCompositorStreamTextureFactoryImpl::GetInstance() { - return g_stream_texture_factory.Pointer(); -} - -SynchronousCompositorStreamTextureFactoryImpl:: - SynchronousCompositorStreamTextureFactoryImpl() - : num_hardware_compositors_(0) {} - -scoped_refptr<StreamTextureFactory> -SynchronousCompositorStreamTextureFactoryImpl::CreateStreamTextureFactory() { - return StreamTextureFactorySynchronousImpl::Create( - base::Bind(&SynchronousCompositorStreamTextureFactoryImpl:: - TryCreateStreamTextureFactory, - base::Unretained(this))); -} - -void SynchronousCompositorStreamTextureFactoryImpl:: - CompositorInitializedHardwareDraw() { - base::AutoLock lock(num_hardware_compositor_lock_); - num_hardware_compositors_++; - if (num_hardware_compositors_ == 1 && main_thread_task_runner_.get()) { - main_thread_task_runner_->PostTask( - FROM_HERE, base::Bind(&SynchronousCompositorStreamTextureFactoryImpl:: - RestoreContextOnMainThread, - base::Unretained(this))); - } -} - -void SynchronousCompositorStreamTextureFactoryImpl:: - CompositorReleasedHardwareDraw() { - base::AutoLock lock(num_hardware_compositor_lock_); - DCHECK_GT(num_hardware_compositors_, 0u); - num_hardware_compositors_--; -} - -void SynchronousCompositorStreamTextureFactoryImpl:: - RestoreContextOnMainThread() { - if (CanCreateMainThreadContext() && video_context_provider_.get()) - video_context_provider_->RestoreContext(); -} - -bool SynchronousCompositorStreamTextureFactoryImpl:: - CanCreateMainThreadContext() { - base::AutoLock lock(num_hardware_compositor_lock_); - return num_hardware_compositors_ > 0; -} - -scoped_refptr<StreamTextureFactorySynchronousImpl::ContextProvider> -SynchronousCompositorStreamTextureFactoryImpl::TryCreateStreamTextureFactory() { - { - base::AutoLock lock(num_hardware_compositor_lock_); - main_thread_task_runner_ = base::ThreadTaskRunnerHandle::Get(); - } - - // Always fail creation even if |video_context_provider_| is not NULL. - // This is to avoid synchronous calls that may deadlock. Setting - // |video_context_provider_| to null is also not safe since it makes - // synchronous destruction uncontrolled and possibly deadlock. - if (!CanCreateMainThreadContext()) { - return scoped_refptr< - StreamTextureFactorySynchronousImpl::ContextProvider>(); - } - - if (!video_context_provider_.get()) { - DCHECK(android_view_service_.get()); - - // This is for an offscreen context, so the default framebuffer doesn't need - // any alpha, depth, stencil, antialiasing. - gpu::gles2::ContextCreationAttribHelper attributes; - attributes.alpha_size = -1; - attributes.depth_size = 0; - attributes.stencil_size = 0; - attributes.samples = 0; - attributes.sample_buffers = 0; - attributes.bind_generates_resource = false; - attributes.lose_context_when_out_of_memory = true; - - // This needs to run in on-screen |android_view_service_| context due to - // SurfaceTexture limitations. - ContextHolder holder = - CreateContextHolder(attributes, android_view_service_, - gpu::GLInProcessContextSharedMemoryLimits()); - video_context_provider_ = new VideoContextProvider( - ContextProviderInProcess::Create(std::move(holder.command_buffer), - "Video-Offscreen-main-thread"), - holder.gl_in_process_context); - } - return video_context_provider_; -} - -void SynchronousCompositorStreamTextureFactoryImpl::SetDeferredGpuService( - scoped_refptr<gpu::InProcessCommandBuffer::Service> service) { - DCHECK(!android_view_service_.get()); - android_view_service_ = service; - - if (base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kSingleProcess)) { - RenderThreadImpl::SetStreamTextureFactory(CreateStreamTextureFactory()); - } -} - } // namespace content
diff --git a/content/browser/android/in_process/synchronous_compositor_factory_impl.h b/content/browser/android/in_process/synchronous_compositor_factory_impl.h index 372c617..013175f 100644 --- a/content/browser/android/in_process/synchronous_compositor_factory_impl.h +++ b/content/browser/android/in_process/synchronous_compositor_factory_impl.h
@@ -5,32 +5,14 @@ #ifndef CONTENT_BROWSER_ANDROID_IN_PROCESS_SYNCHRONOUS_COMPOSITOR_FACTORY_IMPL_H_ #define CONTENT_BROWSER_ANDROID_IN_PROCESS_SYNCHRONOUS_COMPOSITOR_FACTORY_IMPL_H_ -#include "base/lazy_instance.h" #include "base/synchronization/lock.h" #include "cc/blink/context_provider_web_context.h" #include "content/browser/android/in_process/synchronous_input_event_filter.h" #include "content/common/gpu/client/command_buffer_metrics.h" #include "content/renderer/android/synchronous_compositor_factory.h" -#include "content/renderer/media/android/stream_texture_factory_synchronous_impl.h" -#include "gpu/command_buffer/service/in_process_command_buffer.h" - -namespace base { -class Thread; -} - -namespace gpu { -class GLInProcessContext; -} - -namespace gpu_blink { -class WebGraphicsContext3DInProcessCommandBufferImpl; -} namespace content { -class InProcessChildThreadParams; -class ContextProviderCommandBuffer; - class SynchronousCompositorFactoryImpl : public SynchronousCompositorFactory { public: SynchronousCompositorFactoryImpl(); @@ -59,40 +41,6 @@ SynchronousInputEventFilter synchronous_input_event_filter_; }; -class SynchronousCompositorStreamTextureFactoryImpl { - public: - static SynchronousCompositorStreamTextureFactoryImpl* GetInstance(); - - scoped_refptr<StreamTextureFactory> CreateStreamTextureFactory(); - void SetDeferredGpuService( - scoped_refptr<gpu::InProcessCommandBuffer::Service> service); - void CompositorInitializedHardwareDraw(); - void CompositorReleasedHardwareDraw(); - - private: - friend struct base::DefaultLazyInstanceTraits< - SynchronousCompositorStreamTextureFactoryImpl>; - - SynchronousCompositorStreamTextureFactoryImpl(); - ~SynchronousCompositorStreamTextureFactoryImpl(); - - bool CanCreateMainThreadContext(); - scoped_refptr<StreamTextureFactorySynchronousImpl::ContextProvider> - TryCreateStreamTextureFactory(); - void RestoreContextOnMainThread(); - - scoped_refptr<gpu::InProcessCommandBuffer::Service> android_view_service_; - - class VideoContextProvider; - scoped_refptr<VideoContextProvider> video_context_provider_; - - // |num_hardware_compositor_lock_| is updated on UI thread only but can be - // read on renderer main thread. - base::Lock num_hardware_compositor_lock_; - unsigned int num_hardware_compositors_; - scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_; -}; - } // namespace content #endif // CONTENT_BROWSER_ANDROID_IN_PROCESS_SYNCHRONOUS_COMPOSITOR_FACTORY_IMPL_H_
diff --git a/content/browser/android/in_process/synchronous_compositor_impl.cc b/content/browser/android/in_process/synchronous_compositor_impl.cc index af54f80..652753ed 100644 --- a/content/browser/android/in_process/synchronous_compositor_impl.cc +++ b/content/browser/android/in_process/synchronous_compositor_impl.cc
@@ -213,17 +213,7 @@ void SynchronousCompositorImpl::SetMemoryPolicy(size_t bytes_limit) { DCHECK(CalledOnValidThread()); DCHECK(output_surface_); - - size_t current_bytes_limit = output_surface_->GetMemoryPolicy(); output_surface_->SetMemoryPolicy(bytes_limit); - - if (bytes_limit && !current_bytes_limit) { - SynchronousCompositorStreamTextureFactoryImpl::GetInstance() - ->CompositorInitializedHardwareDraw(); - } else if (!bytes_limit && current_bytes_limit) { - SynchronousCompositorStreamTextureFactoryImpl::GetInstance() - ->CompositorReleasedHardwareDraw(); - } } void SynchronousCompositorImpl::Invalidate() {
diff --git a/content/browser/android/synchronous_compositor_base.cc b/content/browser/android/synchronous_compositor_base.cc index 62a7a56..967b871e 100644 --- a/content/browser/android/synchronous_compositor_base.cc +++ b/content/browser/android/synchronous_compositor_base.cc
@@ -7,7 +7,6 @@ #include "base/command_line.h" #include "base/memory/ptr_util.h" #include "base/supports_user_data.h" -#include "content/browser/android/in_process/synchronous_compositor_factory_impl.h" #include "content/browser/android/in_process/synchronous_compositor_impl.h" #include "content/browser/android/synchronous_compositor_host.h" #include "content/browser/gpu/gpu_process_host.h"
diff --git a/content/browser/android/synchronous_compositor_base.h b/content/browser/android/synchronous_compositor_base.h index 00aae21..8611696 100644 --- a/content/browser/android/synchronous_compositor_base.h +++ b/content/browser/android/synchronous_compositor_base.h
@@ -25,7 +25,6 @@ namespace content { class RenderWidgetHostViewAndroid; -class SynchronousCompositorStreamTextureFactoryImpl; class WebContents; struct DidOverscrollParams;
diff --git a/content/browser/android/synchronous_compositor_host.cc b/content/browser/android/synchronous_compositor_host.cc index f92b294..e9dc1b8 100644 --- a/content/browser/android/synchronous_compositor_host.cc +++ b/content/browser/android/synchronous_compositor_host.cc
@@ -10,7 +10,6 @@ #include "base/memory/shared_memory.h" #include "base/trace_event/trace_event_argument.h" #include "cc/output/compositor_frame_ack.h" -#include "content/browser/android/in_process/synchronous_compositor_factory_impl.h" #include "content/browser/android/in_process/synchronous_compositor_renderer_statics.h" #include "content/browser/renderer_host/render_widget_host_view_android.h" #include "content/browser/web_contents/web_contents_impl.h" @@ -290,17 +289,8 @@ void SynchronousCompositorHost::SetMemoryPolicy(size_t bytes_limit) { if (bytes_limit_ == bytes_limit) return; - size_t current_bytes_limit = bytes_limit_; bytes_limit_ = bytes_limit; SendAsyncCompositorStateIfNeeded(); - - if (bytes_limit && !current_bytes_limit) { - SynchronousCompositorStreamTextureFactoryImpl::GetInstance() - ->CompositorInitializedHardwareDraw(); - } else if (!bytes_limit && current_bytes_limit) { - SynchronousCompositorStreamTextureFactoryImpl::GetInstance() - ->CompositorReleasedHardwareDraw(); - } } void SynchronousCompositorHost::DidChangeRootLayerScrollOffset(
diff --git a/content/browser/appcache/appcache_internals_ui.h b/content/browser/appcache/appcache_internals_ui.h index f027287f..5fdf4a3 100644 --- a/content/browser/appcache/appcache_internals_ui.h +++ b/content/browser/appcache/appcache_internals_ui.h
@@ -80,7 +80,6 @@ base::WeakPtr<AppCacheInternalsUI> appcache_internals_ui_; base::WeakPtr<AppCacheServiceImpl> appcache_service_; - AppCacheStorage* appcache_storage_; base::FilePath partition_path_; scoped_refptr<AppCacheStorageReference> disabled_appcache_storage_ref_; std::list<ResponseEnquiry> response_enquiries_;
diff --git a/content/browser/bluetooth/bluetooth_dispatcher_host.cc b/content/browser/bluetooth/bluetooth_dispatcher_host.cc index 2725b3d..78d8c12 100644 --- a/content/browser/bluetooth/bluetooth_dispatcher_host.cc +++ b/content/browser/bluetooth/bluetooth_dispatcher_host.cc
@@ -320,13 +320,11 @@ public: RequestDeviceSession(int thread_id, int request_id, - int frame_routing_id, url::Origin origin, const std::vector<BluetoothScanFilter>& filters, const std::vector<BluetoothUUID>& optional_services) : thread_id(thread_id), request_id(request_id), - frame_routing_id(frame_routing_id), origin(origin), filters(filters), optional_services(optional_services) {} @@ -353,7 +351,6 @@ const int thread_id; const int request_id; - const int frame_routing_id; const url::Origin origin; const std::vector<BluetoothScanFilter> filters; const std::vector<BluetoothUUID> optional_services; @@ -1045,9 +1042,9 @@ // Create storage for the information that backs the chooser, and show the // chooser. - RequestDeviceSession* const session = new RequestDeviceSession( - thread_id, request_id, frame_routing_id, requesting_origin, filters, - optional_services_blacklist_filtered); + RequestDeviceSession* const session = + new RequestDeviceSession(thread_id, request_id, requesting_origin, + filters, optional_services_blacklist_filtered); int chooser_id = request_device_sessions_.Add(session); BluetoothChooser::EventHandler chooser_event_handler =
diff --git a/content/browser/cache_storage/cache_storage.cc b/content/browser/cache_storage/cache_storage.cc index fa3251f..eae623c 100644 --- a/content/browser/cache_storage/cache_storage.cc +++ b/content/browser/cache_storage/cache_storage.cc
@@ -470,7 +470,6 @@ scheduler_(new CacheStorageScheduler()), origin_path_(path), cache_task_runner_(cache_task_runner), - memory_only_(memory_only), quota_manager_proxy_(quota_manager_proxy), origin_(origin), weak_factory_(this) {
diff --git a/content/browser/cache_storage/cache_storage.h b/content/browser/cache_storage/cache_storage.h index b8d1e47..2cea28b2 100644 --- a/content/browser/cache_storage/cache_storage.h +++ b/content/browser/cache_storage/cache_storage.h
@@ -229,9 +229,6 @@ // The TaskRunner to run file IO on. scoped_refptr<base::SequencedTaskRunner> cache_task_runner_; - // Whether or not to store data in disk or memory. - bool memory_only_; - // Performs backend specific operations (memory vs disk). std::unique_ptr<CacheLoader> cache_loader_;
diff --git a/content/browser/compositor/browser_compositor_overlay_candidate_validator_mac.h b/content/browser/compositor/browser_compositor_overlay_candidate_validator_mac.h index 4aee133..97bb8da 100644 --- a/content/browser/compositor/browser_compositor_overlay_candidate_validator_mac.h +++ b/content/browser/compositor/browser_compositor_overlay_candidate_validator_mac.h
@@ -16,8 +16,7 @@ class CONTENT_EXPORT BrowserCompositorOverlayCandidateValidatorMac : public BrowserCompositorOverlayCandidateValidator { public: - explicit BrowserCompositorOverlayCandidateValidatorMac( - gfx::AcceleratedWidget widget); + BrowserCompositorOverlayCandidateValidatorMac(); ~BrowserCompositorOverlayCandidateValidatorMac() override; // cc::OverlayCandidateValidator implementation.
diff --git a/content/browser/compositor/browser_compositor_overlay_candidate_validator_mac.mm b/content/browser/compositor/browser_compositor_overlay_candidate_validator_mac.mm index 3e9886b..8898fc4a 100644 --- a/content/browser/compositor/browser_compositor_overlay_candidate_validator_mac.mm +++ b/content/browser/compositor/browser_compositor_overlay_candidate_validator_mac.mm
@@ -14,14 +14,11 @@ namespace content { BrowserCompositorOverlayCandidateValidatorMac:: - BrowserCompositorOverlayCandidateValidatorMac( - gfx::AcceleratedWidget widget) - : widget_(widget), - software_mirror_active_(false), + BrowserCompositorOverlayCandidateValidatorMac() + : software_mirror_active_(false), ca_layers_disabled_( GpuDataManagerImpl::GetInstance()->IsDriverBugWorkaroundActive( - gpu::DISABLE_OVERLAY_CA_LAYERS)) { -} + gpu::DISABLE_OVERLAY_CA_LAYERS)) {} BrowserCompositorOverlayCandidateValidatorMac:: ~BrowserCompositorOverlayCandidateValidatorMac() {
diff --git a/content/browser/compositor/browser_compositor_overlay_candidate_validator_ozone.cc b/content/browser/compositor/browser_compositor_overlay_candidate_validator_ozone.cc index 97f2d92..44b5041 100644 --- a/content/browser/compositor/browser_compositor_overlay_candidate_validator_ozone.cc +++ b/content/browser/compositor/browser_compositor_overlay_candidate_validator_ozone.cc
@@ -29,10 +29,8 @@ BrowserCompositorOverlayCandidateValidatorOzone:: BrowserCompositorOverlayCandidateValidatorOzone( - gfx::AcceleratedWidget widget, std::unique_ptr<ui::OverlayCandidatesOzone> overlay_candidates) - : widget_(widget), - overlay_candidates_(std::move(overlay_candidates)), + : overlay_candidates_(std::move(overlay_candidates)), software_mirror_active_(false) {} BrowserCompositorOverlayCandidateValidatorOzone::
diff --git a/content/browser/compositor/browser_compositor_overlay_candidate_validator_ozone.h b/content/browser/compositor/browser_compositor_overlay_candidate_validator_ozone.h index 8afd295f..4fe26c77 100644 --- a/content/browser/compositor/browser_compositor_overlay_candidate_validator_ozone.h +++ b/content/browser/compositor/browser_compositor_overlay_candidate_validator_ozone.h
@@ -20,8 +20,7 @@ class CONTENT_EXPORT BrowserCompositorOverlayCandidateValidatorOzone : public BrowserCompositorOverlayCandidateValidator { public: - BrowserCompositorOverlayCandidateValidatorOzone( - gfx::AcceleratedWidget widget, + explicit BrowserCompositorOverlayCandidateValidatorOzone( std::unique_ptr<ui::OverlayCandidatesOzone> overlay_candidates); ~BrowserCompositorOverlayCandidateValidatorOzone() override; @@ -34,7 +33,6 @@ void SetSoftwareMirrorMode(bool enabled) override; private: - gfx::AcceleratedWidget widget_; std::unique_ptr<ui::OverlayCandidatesOzone> overlay_candidates_; bool software_mirror_active_;
diff --git a/content/browser/compositor/buffer_queue.cc b/content/browser/compositor/buffer_queue.cc index 798c010e..c1a0340 100644 --- a/content/browser/compositor/buffer_queue.cc +++ b/content/browser/compositor/buffer_queue.cc
@@ -13,7 +13,6 @@ #include "gpu/command_buffer/client/gles2_interface.h" #include "gpu/command_buffer/client/gpu_memory_buffer_manager.h" #include "gpu/command_buffer/common/gpu_memory_buffer_support.h" -#include "gpu/command_buffer/service/image_factory.h" #include "third_party/skia/include/core/SkRect.h" #include "third_party/skia/include/core/SkRegion.h" #include "ui/gfx/gpu_memory_buffer.h"
diff --git a/content/browser/compositor/gl_helper_unittest.cc b/content/browser/compositor/gl_helper_unittest.cc index a423426..627e496 100644 --- a/content/browser/compositor/gl_helper_unittest.cc +++ b/content/browser/compositor/gl_helper_unittest.cc
@@ -34,8 +34,6 @@ #include "content/browser/compositor/gl_helper_scaling.h" #include "gpu/command_buffer/client/gl_in_process_context.h" #include "gpu/command_buffer/client/gles2_implementation.h" -#include "media/base/video_frame.h" -#include "media/base/video_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkTypes.h" @@ -86,68 +84,9 @@ } void TearDown() override { - helper_scaling_.reset(NULL); - helper_.reset(NULL); - context_.reset(NULL); - } - - void StartTracing(const std::string& filter) { - base::trace_event::TraceLog::GetInstance()->SetEnabled( - base::trace_event::TraceConfig(filter, - base::trace_event::RECORD_UNTIL_FULL), - base::trace_event::TraceLog::RECORDING_MODE); - } - - static void TraceDataCB( - const base::Callback<void()>& callback, - std::string* output, - const scoped_refptr<base::RefCountedString>& json_events_str, - bool has_more_events) { - if (output->size() > 1 && !json_events_str->data().empty()) { - output->append(","); - } - output->append(json_events_str->data()); - if (!has_more_events) { - callback.Run(); - } - } - - // End tracing, return tracing data in a simple map - // of event name->counts. - void EndTracing(std::map<std::string, int>* event_counts) { - std::string json_data = "["; - base::trace_event::TraceLog::GetInstance()->SetDisabled(); - base::RunLoop run_loop; - base::trace_event::TraceLog::GetInstance()->Flush( - base::Bind(&GLHelperTest::TraceDataCB, run_loop.QuitClosure(), - base::Unretained(&json_data))); - run_loop.Run(); - json_data.append("]"); - - std::string error_msg; - std::unique_ptr<base::Value> trace_data = - base::JSONReader::ReadAndReturnError(json_data, 0, NULL, &error_msg); - CHECK(trace_data) << "JSON parsing failed (" << error_msg - << ") JSON data:" << std::endl - << json_data; - - base::ListValue* list; - CHECK(trace_data->GetAsList(&list)); - for (size_t i = 0; i < list->GetSize(); i++) { - base::Value* item = NULL; - if (list->Get(i, &item)) { - base::DictionaryValue* dict; - CHECK(item->GetAsDictionary(&dict)); - std::string name; - CHECK(dict->GetString("name", &name)); - std::string trace_type; - CHECK(dict->GetString("ph", &trace_type)); - // Count all except END traces, as they come in BEGIN/END pairs. - if (trace_type != "E" && trace_type != "e") - (*event_counts)[name]++; - VLOG(1) << "trace name: " << name; - } - } + helper_scaling_.reset(nullptr); + helper_.reset(nullptr); + context_.reset(nullptr); } // Bicubic filter kernel function. @@ -773,7 +712,7 @@ if (xsize == scaled_xsize && ysize == scaled_ysize && out_color_type != kAlpha_8_SkColorType) { const std::vector<GLHelperScaling::ScalerStage> dummy_stages; - Compare(input_pixels.get(), &output_pixels, 0, NULL, dummy_stages, + Compare(input_pixels.get(), &output_pixels, 0, nullptr, dummy_stages, message + " comparing against input"); return; } @@ -864,7 +803,7 @@ // If the bitmap shouldn't have changed - compare against input. if (xsize == scaled_xsize && ysize == scaled_ysize) { - Compare(input_pixels.get(), &output_pixels, 0, NULL, stages, + Compare(input_pixels.get(), &output_pixels, 0, nullptr, stages, message + " comparing against input"); return; } @@ -922,105 +861,11 @@ EXPECT_EQ(PrintStages(stages), description); } - // Note: Left/Right means Top/Bottom when used for Y dimension. - enum Margin { - MarginLeft, - MarginMiddle, - MarginRight, - MarginInvalid, - }; - - static Margin NextMargin(Margin m) { - switch (m) { - case MarginLeft: - return MarginMiddle; - case MarginMiddle: - return MarginRight; - case MarginRight: - return MarginInvalid; - default: - return MarginInvalid; - } - } - - int compute_margin(int insize, int outsize, Margin m) { - int available = outsize - insize; - switch (m) { - default: - EXPECT_TRUE(false) << "This should not happen."; - return 0; - case MarginLeft: - return 0; - case MarginMiddle: - return (available / 2) & ~1; - case MarginRight: - return available; - } - } - - // Convert 0.0 - 1.0 to 0 - 255 - int float_to_byte(float v) { - int ret = static_cast<int>(floorf(v * 255.0f + 0.5f)); - if (ret < 0) { - return 0; - } - if (ret > 255) { - return 255; - } - return ret; - } - static void callcallback(const base::Callback<void()>& callback, bool result) { callback.Run(); } - void PrintPlane(unsigned char* plane, int xsize, int stride, int ysize) { - for (int y = 0; y < ysize; y++) { - std::string formatted; - for (int x = 0; x < xsize; x++) { - formatted.append(base::StringPrintf("%3d, ", plane[y * stride + x])); - } - LOG(ERROR) << formatted << " (" << (plane + y * stride) << ")"; - } - } - - // Compare two planes make sure that each component of each pixel - // is no more than |maxdiff| apart. - void ComparePlane(unsigned char* truth, - int truth_stride, - unsigned char* other, - int other_stride, - int maxdiff, - int xsize, - int ysize, - SkBitmap* source, - std::string message) { - for (int x = 0; x < xsize; x++) { - for (int y = 0; y < ysize; y++) { - int a = other[y * other_stride + x]; - int b = truth[y * truth_stride + x]; - EXPECT_NEAR(a, b, maxdiff) << " x=" << x << " y=" << y << " " - << message; - if (std::abs(a - b) > maxdiff) { - LOG(ERROR) << "-------expected--------"; - PrintPlane(truth, xsize, truth_stride, ysize); - LOG(ERROR) << "-------actual--------"; - PrintPlane(other, xsize, other_stride, ysize); - if (source) { - LOG(ERROR) << "-------before yuv conversion: red--------"; - PrintChannel(source, 0); - LOG(ERROR) << "-------before yuv conversion: green------"; - PrintChannel(source, 1); - LOG(ERROR) << "-------before yuv conversion: blue-------"; - PrintChannel(source, 2); - } - return; - } - } - } - } - void DrawGridToBitmap(int w, int h, SkColor background_color, @@ -1243,174 +1088,6 @@ return true; } - // YUV readback test. Create a test pattern, convert to YUV - // with reference implementation and compare to what gl_helper - // returns. - void TestYUVReadback(int xsize, - int ysize, - int output_xsize, - int output_ysize, - int xmargin, - int ymargin, - int test_pattern, - bool flip, - bool use_mrt, - content::GLHelper::ScalerQuality quality) { - GLuint src_texture; - gl_->GenTextures(1, &src_texture); - SkBitmap input_pixels; - input_pixels.allocN32Pixels(xsize, ysize); - - for (int x = 0; x < xsize; ++x) { - for (int y = 0; y < ysize; ++y) { - switch (test_pattern) { - case 0: // Smooth test pattern - SetChannel(&input_pixels, x, y, 0, x * 10); - SetChannel(&input_pixels, x, y, 1, y * 10); - SetChannel(&input_pixels, x, y, 2, (x + y) * 10); - SetChannel(&input_pixels, x, y, 3, 255); - break; - case 1: // Small blocks - SetChannel(&input_pixels, x, y, 0, x & 1 ? 255 : 0); - SetChannel(&input_pixels, x, y, 1, y & 1 ? 255 : 0); - SetChannel(&input_pixels, x, y, 2, (x + y) & 1 ? 255 : 0); - SetChannel(&input_pixels, x, y, 3, 255); - break; - case 2: // Medium blocks - SetChannel(&input_pixels, x, y, 0, 10 + x / 2 * 50); - SetChannel(&input_pixels, x, y, 1, 10 + y / 3 * 50); - SetChannel(&input_pixels, x, y, 2, (x + y) / 5 * 50 + 5); - SetChannel(&input_pixels, x, y, 3, 255); - break; - } - } - } - - gl_->BindTexture(GL_TEXTURE_2D, src_texture); - gl_->TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, xsize, ysize, 0, GL_RGBA, - GL_UNSIGNED_BYTE, input_pixels.getPixels()); - - gpu::Mailbox mailbox; - gl_->GenMailboxCHROMIUM(mailbox.name); - EXPECT_FALSE(mailbox.IsZero()); - gl_->ProduceTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name); - const GLuint64 fence_sync = gl_->InsertFenceSyncCHROMIUM(); - gl_->ShallowFlushCHROMIUM(); - - gpu::SyncToken sync_token; - gl_->GenSyncTokenCHROMIUM(fence_sync, sync_token.GetData()); - - std::string message = base::StringPrintf( - "input size: %dx%d " - "output size: %dx%d " - "margin: %dx%d " - "pattern: %d %s %s", - xsize, ysize, output_xsize, output_ysize, xmargin, ymargin, - test_pattern, flip ? "flip" : "noflip", flip ? "mrt" : "nomrt"); - std::unique_ptr<ReadbackYUVInterface> yuv_reader( - helper_->CreateReadbackPipelineYUV( - quality, gfx::Size(xsize, ysize), gfx::Rect(0, 0, xsize, ysize), - gfx::Size(xsize, ysize), flip, use_mrt)); - - scoped_refptr<media::VideoFrame> output_frame = - media::VideoFrame::CreateFrame( - media::PIXEL_FORMAT_YV12, - // The coded size of the output frame is rounded up to the next - // 16-byte boundary. This tests that the readback is being - // positioned inside the frame's visible region, and not dependent - // on its coded size. - gfx::Size((output_xsize + 15) & ~15, (output_ysize + 15) & ~15), - gfx::Rect(0, 0, output_xsize, output_ysize), - gfx::Size(output_xsize, output_ysize), - base::TimeDelta::FromSeconds(0)); - scoped_refptr<media::VideoFrame> truth_frame = - media::VideoFrame::CreateFrame( - media::PIXEL_FORMAT_YV12, gfx::Size(output_xsize, output_ysize), - gfx::Rect(0, 0, output_xsize, output_ysize), - gfx::Size(output_xsize, output_ysize), - base::TimeDelta::FromSeconds(0)); - - base::RunLoop run_loop; - yuv_reader->ReadbackYUV(mailbox, sync_token, output_frame->visible_rect(), - output_frame->stride(media::VideoFrame::kYPlane), - output_frame->data(media::VideoFrame::kYPlane), - output_frame->stride(media::VideoFrame::kUPlane), - output_frame->data(media::VideoFrame::kUPlane), - output_frame->stride(media::VideoFrame::kVPlane), - output_frame->data(media::VideoFrame::kVPlane), - gfx::Point(xmargin, ymargin), - base::Bind(&callcallback, run_loop.QuitClosure())); - - const gfx::Rect paste_rect(gfx::Point(xmargin, ymargin), - gfx::Size(xsize, ysize)); - media::LetterboxYUV(output_frame.get(), paste_rect); - run_loop.Run(); - - if (flip) { - FlipSKBitmap(&input_pixels); - } - - unsigned char* Y = truth_frame->visible_data(media::VideoFrame::kYPlane); - unsigned char* U = truth_frame->visible_data(media::VideoFrame::kUPlane); - unsigned char* V = truth_frame->visible_data(media::VideoFrame::kVPlane); - int32_t y_stride = truth_frame->stride(media::VideoFrame::kYPlane); - int32_t u_stride = truth_frame->stride(media::VideoFrame::kUPlane); - int32_t v_stride = truth_frame->stride(media::VideoFrame::kVPlane); - memset(Y, 0x00, y_stride * output_ysize); - memset(U, 0x80, u_stride * output_ysize / 2); - memset(V, 0x80, v_stride * output_ysize / 2); - - const float kRGBtoYColorWeights[] = {0.257f, 0.504f, 0.098f, 0.0625f}; - const float kRGBtoUColorWeights[] = {-0.148f, -0.291f, 0.439f, 0.5f}; - const float kRGBtoVColorWeights[] = {0.439f, -0.368f, -0.071f, 0.5f}; - - for (int y = 0; y < ysize; y++) { - for (int x = 0; x < xsize; x++) { - Y[(y + ymargin) * y_stride + x + xmargin] = float_to_byte( - ChannelAsFloat(&input_pixels, x, y, 0) * kRGBtoYColorWeights[0] + - ChannelAsFloat(&input_pixels, x, y, 1) * kRGBtoYColorWeights[1] + - ChannelAsFloat(&input_pixels, x, y, 2) * kRGBtoYColorWeights[2] + - kRGBtoYColorWeights[3]); - } - } - - for (int y = 0; y < ysize / 2; y++) { - for (int x = 0; x < xsize / 2; x++) { - U[(y + ymargin / 2) * u_stride + x + xmargin / 2] = - float_to_byte(Bilinear(&input_pixels, x * 2 + 1.0, y * 2 + 1.0, 0) * - kRGBtoUColorWeights[0] + - Bilinear(&input_pixels, x * 2 + 1.0, y * 2 + 1.0, 1) * - kRGBtoUColorWeights[1] + - Bilinear(&input_pixels, x * 2 + 1.0, y * 2 + 1.0, 2) * - kRGBtoUColorWeights[2] + - kRGBtoUColorWeights[3]); - V[(y + ymargin / 2) * v_stride + x + xmargin / 2] = - float_to_byte(Bilinear(&input_pixels, x * 2 + 1.0, y * 2 + 1.0, 0) * - kRGBtoVColorWeights[0] + - Bilinear(&input_pixels, x * 2 + 1.0, y * 2 + 1.0, 1) * - kRGBtoVColorWeights[1] + - Bilinear(&input_pixels, x * 2 + 1.0, y * 2 + 1.0, 2) * - kRGBtoVColorWeights[2] + - kRGBtoVColorWeights[3]); - } - } - - ComparePlane( - Y, y_stride, output_frame->visible_data(media::VideoFrame::kYPlane), - output_frame->stride(media::VideoFrame::kYPlane), 2, output_xsize, - output_ysize, &input_pixels, message + " Y plane"); - ComparePlane( - U, u_stride, output_frame->visible_data(media::VideoFrame::kUPlane), - output_frame->stride(media::VideoFrame::kUPlane), 2, output_xsize / 2, - output_ysize / 2, &input_pixels, message + " U plane"); - ComparePlane( - V, v_stride, output_frame->visible_data(media::VideoFrame::kVPlane), - output_frame->stride(media::VideoFrame::kVPlane), 2, output_xsize / 2, - output_ysize / 2, &input_pixels, message + " V plane"); - - gl_->DeleteTextures(1, &src_texture); - } - void TestAddOps(int src, int dst, bool scale_x, bool allow3) { std::deque<GLHelperScaling::ScaleOp> ops; GLHelperScaling::ScaleOp::AddOps(src, dst, scale_x, allow3, &ops); @@ -1638,83 +1315,6 @@ EXPECT_EQ(result, true); } -TEST_F(GLHelperPixelTest, YUVReadbackOptTest) { - // This test uses the gpu.service/gpu_decoder tracing events to detect how - // many scaling passes are actually performed by the YUV readback pipeline. - StartTracing(TRACE_DISABLED_BY_DEFAULT( - "gpu.service") "," TRACE_DISABLED_BY_DEFAULT("gpu_decoder")); - - TestYUVReadback(800, 400, 800, 400, 0, 0, 1, false, true, - content::GLHelper::SCALER_QUALITY_FAST); - - std::map<std::string, int> event_counts; - EndTracing(&event_counts); - int draw_buffer_calls = event_counts["kDrawBuffersEXTImmediate"]; - int draw_arrays_calls = event_counts["kDrawArrays"]; - VLOG(1) << "Draw buffer calls: " << draw_buffer_calls; - VLOG(1) << "DrawArrays calls: " << draw_arrays_calls; - - if (draw_buffer_calls) { - // When using MRT, the YUV readback code should only - // execute two draw arrays, and scaling should be integrated - // into those two calls since we are using the FAST scalign - // quality. - EXPECT_EQ(2, draw_arrays_calls); - } else { - // When not using MRT, there are three passes for the YUV, - // and one for the scaling. - EXPECT_EQ(4, draw_arrays_calls); - } -} - -class GLHelperPixelYuvReadback - : public GLHelperPixelTest, - public ::testing::WithParamInterface< - std::tr1::tuple<bool, bool, unsigned int, unsigned int>> {}; - -int kYUVReadBackSizes[] = {2, 4, 14}; - -TEST_P(GLHelperPixelYuvReadback, Test) { - bool flip = std::tr1::get<0>(GetParam()); - bool use_mrt = std::tr1::get<1>(GetParam()); - unsigned int x = std::tr1::get<2>(GetParam()); - unsigned int y = std::tr1::get<3>(GetParam()); - - for (unsigned int ox = x; ox < arraysize(kYUVReadBackSizes); ox++) { - for (unsigned int oy = y; oy < arraysize(kYUVReadBackSizes); oy++) { - // If output is a subsection of the destination frame, (letterbox) - // then try different variations of where the subsection goes. - for (Margin xm = x < ox ? MarginLeft : MarginRight; xm <= MarginRight; - xm = NextMargin(xm)) { - for (Margin ym = y < oy ? MarginLeft : MarginRight; ym <= MarginRight; - ym = NextMargin(ym)) { - for (int pattern = 0; pattern < 3; pattern++) { - TestYUVReadback( - kYUVReadBackSizes[x], kYUVReadBackSizes[y], - kYUVReadBackSizes[ox], kYUVReadBackSizes[oy], - compute_margin(kYUVReadBackSizes[x], kYUVReadBackSizes[ox], xm), - compute_margin(kYUVReadBackSizes[y], kYUVReadBackSizes[oy], ym), - pattern, flip, use_mrt, content::GLHelper::SCALER_QUALITY_GOOD); - if (HasFailure()) { - return; - } - } - } - } - } - } -} - -// First argument is intentionally empty. -INSTANTIATE_TEST_CASE_P( - , - GLHelperPixelYuvReadback, - ::testing::Combine( - ::testing::Bool(), - ::testing::Bool(), - ::testing::Range<unsigned int>(0, arraysize(kYUVReadBackSizes)), - ::testing::Range<unsigned int>(0, arraysize(kYUVReadBackSizes)))); - int kRGBReadBackSizes[] = {3, 6, 16}; class GLHelperPixelReadbackTest
diff --git a/content/browser/compositor/gpu_process_transport_factory.cc b/content/browser/compositor/gpu_process_transport_factory.cc index cdc8798..64a991b 100644 --- a/content/browser/compositor/gpu_process_transport_factory.cc +++ b/content/browser/compositor/gpu_process_transport_factory.cc
@@ -167,12 +167,12 @@ (command_line->HasSwitch(switches::kEnableHardwareOverlays) || command_line->HasSwitch(switches::kOzoneTestSingleOverlaySupport))) { validator.reset(new BrowserCompositorOverlayCandidateValidatorOzone( - widget, std::move(overlay_candidates))); + std::move(overlay_candidates))); } #elif defined(OS_MACOSX) // Overlays are only supported through the remote layer API. if (ui::RemoteLayerAPISupported()) { - validator.reset(new BrowserCompositorOverlayCandidateValidatorMac(widget)); + validator.reset(new BrowserCompositorOverlayCandidateValidatorMac()); } #elif defined(OS_ANDROID) validator.reset(new BrowserCompositorOverlayCandidateValidatorAndroid());
diff --git a/content/browser/compositor/reflector_impl_unittest.cc b/content/browser/compositor/reflector_impl_unittest.cc index 00e57c6..d5a512c61 100644 --- a/content/browser/compositor/reflector_impl_unittest.cc +++ b/content/browser/compositor/reflector_impl_unittest.cc
@@ -62,8 +62,8 @@ #if defined(USE_OZONE) return std::unique_ptr<BrowserCompositorOverlayCandidateValidator>( new BrowserCompositorOverlayCandidateValidatorOzone( - 0, std::unique_ptr<ui::OverlayCandidatesOzone>( - new TestOverlayCandidatesOzone()))); + std::unique_ptr<ui::OverlayCandidatesOzone>( + new TestOverlayCandidatesOzone()))); #else return nullptr; #endif // defined(USE_OZONE)
diff --git a/content/browser/compositor/yuv_readback_unittest.cc b/content/browser/compositor/yuv_readback_unittest.cc new file mode 100644 index 0000000..176b3bf --- /dev/null +++ b/content/browser/compositor/yuv_readback_unittest.cc
@@ -0,0 +1,554 @@ +// 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 "base/json/json_reader.h" +#include "base/memory/ref_counted_memory.h" +#include "base/run_loop.h" +#include "base/strings/stringprintf.h" +#include "base/test/launcher/unit_test_launcher.h" +#include "base/test/test_suite.h" +#include "content/browser/compositor/gl_helper.h" +#include "gpu/command_buffer/client/gl_in_process_context.h" +#include "gpu/command_buffer/client/gles2_implementation.h" +#include "media/base/video_frame.h" +#include "media/base/video_util.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/skia/include/core/SkBitmap.h" +#include "ui/gl/gl_implementation.h" + +namespace content { + +namespace { + +int kYUVReadbackSizes[] = {2, 4, 14}; +} + +class YUVReadbackTest : public testing::Test { + protected: + void SetUp() override { + gpu::gles2::ContextCreationAttribHelper attributes; + attributes.alpha_size = 8; + attributes.depth_size = 24; + attributes.red_size = 8; + attributes.green_size = 8; + attributes.blue_size = 8; + attributes.stencil_size = 8; + attributes.samples = 4; + attributes.sample_buffers = 1; + attributes.bind_generates_resource = false; + + context_.reset(gpu::GLInProcessContext::Create( + nullptr, /* service */ + nullptr, /* surface */ + true, /* offscreen */ + gfx::kNullAcceleratedWidget, /* window */ + gfx::Size(1, 1), /* size */ + nullptr, /* share_context */ + attributes, gfx::PreferDiscreteGpu, + ::gpu::GLInProcessContextSharedMemoryLimits(), + nullptr, /* gpu_memory_buffer_manager */ + nullptr /* image_factory */)); + gl_ = context_->GetImplementation(); + gpu::ContextSupport* support = context_->GetImplementation(); + + helper_.reset(new content::GLHelper(gl_, support)); + } + + void TearDown() override { + helper_.reset(NULL); + context_.reset(NULL); + } + + void StartTracing(const std::string& filter) { + base::trace_event::TraceLog::GetInstance()->SetEnabled( + base::trace_event::TraceConfig(filter, + base::trace_event::RECORD_UNTIL_FULL), + base::trace_event::TraceLog::RECORDING_MODE); + } + + static void TraceDataCB( + const base::Callback<void()>& callback, + std::string* output, + const scoped_refptr<base::RefCountedString>& json_events_str, + bool has_more_events) { + if (output->size() > 1 && !json_events_str->data().empty()) { + output->append(","); + } + output->append(json_events_str->data()); + if (!has_more_events) { + callback.Run(); + } + } + + // End tracing, return tracing data in a simple map + // of event name->counts. + void EndTracing(std::map<std::string, int>* event_counts) { + std::string json_data = "["; + base::trace_event::TraceLog::GetInstance()->SetDisabled(); + base::RunLoop run_loop; + base::trace_event::TraceLog::GetInstance()->Flush( + base::Bind(&YUVReadbackTest::TraceDataCB, run_loop.QuitClosure(), + base::Unretained(&json_data))); + run_loop.Run(); + json_data.append("]"); + + std::string error_msg; + std::unique_ptr<base::Value> trace_data = + base::JSONReader::ReadAndReturnError(json_data, 0, NULL, &error_msg); + CHECK(trace_data) << "JSON parsing failed (" << error_msg + << ") JSON data:" << std::endl + << json_data; + + base::ListValue* list; + CHECK(trace_data->GetAsList(&list)); + for (size_t i = 0; i < list->GetSize(); i++) { + base::Value* item = NULL; + if (list->Get(i, &item)) { + base::DictionaryValue* dict; + CHECK(item->GetAsDictionary(&dict)); + std::string name; + CHECK(dict->GetString("name", &name)); + std::string trace_type; + CHECK(dict->GetString("ph", &trace_type)); + // Count all except END traces, as they come in BEGIN/END pairs. + if (trace_type != "E" && trace_type != "e") + (*event_counts)[name]++; + VLOG(1) << "trace name: " << name; + } + } + } + + // Look up a single channel value. Works for 4-channel and single channel + // bitmaps. Clamp x/y. + int Channel(SkBitmap* pixels, int x, int y, int c) { + if (pixels->bytesPerPixel() == 4) { + uint32_t* data = + pixels->getAddr32(std::max(0, std::min(x, pixels->width() - 1)), + std::max(0, std::min(y, pixels->height() - 1))); + return (*data) >> (c * 8) & 0xff; + } else { + DCHECK_EQ(pixels->bytesPerPixel(), 1); + DCHECK_EQ(c, 0); + return *pixels->getAddr8(std::max(0, std::min(x, pixels->width() - 1)), + std::max(0, std::min(y, pixels->height() - 1))); + } + } + + // Set a single channel value. Works for 4-channel and single channel + // bitmaps. Clamp x/y. + void SetChannel(SkBitmap* pixels, int x, int y, int c, int v) { + DCHECK_GE(x, 0); + DCHECK_GE(y, 0); + DCHECK_LT(x, pixels->width()); + DCHECK_LT(y, pixels->height()); + if (pixels->bytesPerPixel() == 4) { + uint32_t* data = pixels->getAddr32(x, y); + v = std::max(0, std::min(v, 255)); + *data = (*data & ~(0xffu << (c * 8))) | (v << (c * 8)); + } else { + DCHECK_EQ(pixels->bytesPerPixel(), 1); + DCHECK_EQ(c, 0); + uint8_t* data = pixels->getAddr8(x, y); + v = std::max(0, std::min(v, 255)); + *data = v; + } + } + + // Print all the R, G, B or A values from an SkBitmap in a + // human-readable format. + void PrintChannel(SkBitmap* pixels, int c) { + for (int y = 0; y < pixels->height(); y++) { + std::string formatted; + for (int x = 0; x < pixels->width(); x++) { + formatted.append(base::StringPrintf("%3d, ", Channel(pixels, x, y, c))); + } + LOG(ERROR) << formatted; + } + } + + // Get a single R, G, B or A value as a float. + float ChannelAsFloat(SkBitmap* pixels, int x, int y, int c) { + return Channel(pixels, x, y, c) / 255.0; + } + + // Works like a GL_LINEAR lookup on an SkBitmap. + float Bilinear(SkBitmap* pixels, float x, float y, int c) { + x -= 0.5; + y -= 0.5; + int base_x = static_cast<int>(floorf(x)); + int base_y = static_cast<int>(floorf(y)); + x -= base_x; + y -= base_y; + return (ChannelAsFloat(pixels, base_x, base_y, c) * (1 - x) * (1 - y) + + ChannelAsFloat(pixels, base_x + 1, base_y, c) * x * (1 - y) + + ChannelAsFloat(pixels, base_x, base_y + 1, c) * (1 - x) * y + + ChannelAsFloat(pixels, base_x + 1, base_y + 1, c) * x * y); + } + + void FlipSKBitmap(SkBitmap* bitmap) { + int bpp = bitmap->bytesPerPixel(); + DCHECK(bpp == 4 || bpp == 1); + int top_line = 0; + int bottom_line = bitmap->height() - 1; + while (top_line < bottom_line) { + for (int x = 0; x < bitmap->width(); x++) { + bpp == 4 ? std::swap(*bitmap->getAddr32(x, top_line), + *bitmap->getAddr32(x, bottom_line)) + : std::swap(*bitmap->getAddr8(x, top_line), + *bitmap->getAddr8(x, bottom_line)); + } + top_line++; + bottom_line--; + } + } + + // Note: Left/Right means Top/Bottom when used for Y dimension. + enum Margin { + MarginLeft, + MarginMiddle, + MarginRight, + MarginInvalid, + }; + + static Margin NextMargin(Margin m) { + switch (m) { + case MarginLeft: + return MarginMiddle; + case MarginMiddle: + return MarginRight; + case MarginRight: + return MarginInvalid; + default: + return MarginInvalid; + } + } + + int compute_margin(int insize, int outsize, Margin m) { + int available = outsize - insize; + switch (m) { + default: + EXPECT_TRUE(false) << "This should not happen."; + return 0; + case MarginLeft: + return 0; + case MarginMiddle: + return (available / 2) & ~1; + case MarginRight: + return available; + } + } + + // Convert 0.0 - 1.0 to 0 - 255 + int float_to_byte(float v) { + int ret = static_cast<int>(floorf(v * 255.0f + 0.5f)); + if (ret < 0) { + return 0; + } + if (ret > 255) { + return 255; + } + return ret; + } + + static void callcallback(const base::Callback<void()>& callback, + bool result) { + callback.Run(); + } + + void PrintPlane(unsigned char* plane, int xsize, int stride, int ysize) { + for (int y = 0; y < ysize; y++) { + std::string formatted; + for (int x = 0; x < xsize; x++) { + formatted.append(base::StringPrintf("%3d, ", plane[y * stride + x])); + } + LOG(ERROR) << formatted << " (" << (plane + y * stride) << ")"; + } + } + + // Compare two planes make sure that each component of each pixel + // is no more than |maxdiff| apart. + void ComparePlane(unsigned char* truth, + int truth_stride, + unsigned char* other, + int other_stride, + int maxdiff, + int xsize, + int ysize, + SkBitmap* source, + std::string message) { + for (int x = 0; x < xsize; x++) { + for (int y = 0; y < ysize; y++) { + int a = other[y * other_stride + x]; + int b = truth[y * truth_stride + x]; + EXPECT_NEAR(a, b, maxdiff) << " x=" << x << " y=" << y << " " + << message; + if (std::abs(a - b) > maxdiff) { + LOG(ERROR) << "-------expected--------"; + PrintPlane(truth, xsize, truth_stride, ysize); + LOG(ERROR) << "-------actual--------"; + PrintPlane(other, xsize, other_stride, ysize); + if (source) { + LOG(ERROR) << "-------before yuv conversion: red--------"; + PrintChannel(source, 0); + LOG(ERROR) << "-------before yuv conversion: green------"; + PrintChannel(source, 1); + LOG(ERROR) << "-------before yuv conversion: blue-------"; + PrintChannel(source, 2); + } + return; + } + } + } + } + + // YUV readback test. Create a test pattern, convert to YUV + // with reference implementation and compare to what gl_helper + // returns. + void TestYUVReadback(int xsize, + int ysize, + int output_xsize, + int output_ysize, + int xmargin, + int ymargin, + int test_pattern, + bool flip, + bool use_mrt, + content::GLHelper::ScalerQuality quality) { + GLuint src_texture; + gl_->GenTextures(1, &src_texture); + SkBitmap input_pixels; + input_pixels.allocN32Pixels(xsize, ysize); + + for (int x = 0; x < xsize; ++x) { + for (int y = 0; y < ysize; ++y) { + switch (test_pattern) { + case 0: // Smooth test pattern + SetChannel(&input_pixels, x, y, 0, x * 10); + SetChannel(&input_pixels, x, y, 1, y * 10); + SetChannel(&input_pixels, x, y, 2, (x + y) * 10); + SetChannel(&input_pixels, x, y, 3, 255); + break; + case 1: // Small blocks + SetChannel(&input_pixels, x, y, 0, x & 1 ? 255 : 0); + SetChannel(&input_pixels, x, y, 1, y & 1 ? 255 : 0); + SetChannel(&input_pixels, x, y, 2, (x + y) & 1 ? 255 : 0); + SetChannel(&input_pixels, x, y, 3, 255); + break; + case 2: // Medium blocks + SetChannel(&input_pixels, x, y, 0, 10 + x / 2 * 50); + SetChannel(&input_pixels, x, y, 1, 10 + y / 3 * 50); + SetChannel(&input_pixels, x, y, 2, (x + y) / 5 * 50 + 5); + SetChannel(&input_pixels, x, y, 3, 255); + break; + } + } + } + + gl_->BindTexture(GL_TEXTURE_2D, src_texture); + gl_->TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, xsize, ysize, 0, GL_RGBA, + GL_UNSIGNED_BYTE, input_pixels.getPixels()); + + gpu::Mailbox mailbox; + gl_->GenMailboxCHROMIUM(mailbox.name); + EXPECT_FALSE(mailbox.IsZero()); + gl_->ProduceTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name); + const GLuint64 fence_sync = gl_->InsertFenceSyncCHROMIUM(); + gl_->ShallowFlushCHROMIUM(); + + gpu::SyncToken sync_token; + gl_->GenSyncTokenCHROMIUM(fence_sync, sync_token.GetData()); + + std::string message = base::StringPrintf( + "input size: %dx%d " + "output size: %dx%d " + "margin: %dx%d " + "pattern: %d %s %s", + xsize, ysize, output_xsize, output_ysize, xmargin, ymargin, + test_pattern, flip ? "flip" : "noflip", flip ? "mrt" : "nomrt"); + std::unique_ptr<ReadbackYUVInterface> yuv_reader( + helper_->CreateReadbackPipelineYUV( + quality, gfx::Size(xsize, ysize), gfx::Rect(0, 0, xsize, ysize), + gfx::Size(xsize, ysize), flip, use_mrt)); + + scoped_refptr<media::VideoFrame> output_frame = + media::VideoFrame::CreateFrame( + media::PIXEL_FORMAT_YV12, + // The coded size of the output frame is rounded up to the next + // 16-byte boundary. This tests that the readback is being + // positioned inside the frame's visible region, and not dependent + // on its coded size. + gfx::Size((output_xsize + 15) & ~15, (output_ysize + 15) & ~15), + gfx::Rect(0, 0, output_xsize, output_ysize), + gfx::Size(output_xsize, output_ysize), + base::TimeDelta::FromSeconds(0)); + scoped_refptr<media::VideoFrame> truth_frame = + media::VideoFrame::CreateFrame( + media::PIXEL_FORMAT_YV12, gfx::Size(output_xsize, output_ysize), + gfx::Rect(0, 0, output_xsize, output_ysize), + gfx::Size(output_xsize, output_ysize), + base::TimeDelta::FromSeconds(0)); + + base::RunLoop run_loop; + yuv_reader->ReadbackYUV(mailbox, sync_token, output_frame->visible_rect(), + output_frame->stride(media::VideoFrame::kYPlane), + output_frame->data(media::VideoFrame::kYPlane), + output_frame->stride(media::VideoFrame::kUPlane), + output_frame->data(media::VideoFrame::kUPlane), + output_frame->stride(media::VideoFrame::kVPlane), + output_frame->data(media::VideoFrame::kVPlane), + gfx::Point(xmargin, ymargin), + base::Bind(&callcallback, run_loop.QuitClosure())); + + const gfx::Rect paste_rect(gfx::Point(xmargin, ymargin), + gfx::Size(xsize, ysize)); + media::LetterboxYUV(output_frame.get(), paste_rect); + run_loop.Run(); + + if (flip) { + FlipSKBitmap(&input_pixels); + } + + unsigned char* Y = truth_frame->visible_data(media::VideoFrame::kYPlane); + unsigned char* U = truth_frame->visible_data(media::VideoFrame::kUPlane); + unsigned char* V = truth_frame->visible_data(media::VideoFrame::kVPlane); + int32_t y_stride = truth_frame->stride(media::VideoFrame::kYPlane); + int32_t u_stride = truth_frame->stride(media::VideoFrame::kUPlane); + int32_t v_stride = truth_frame->stride(media::VideoFrame::kVPlane); + memset(Y, 0x00, y_stride * output_ysize); + memset(U, 0x80, u_stride * output_ysize / 2); + memset(V, 0x80, v_stride * output_ysize / 2); + + const float kRGBtoYColorWeights[] = {0.257f, 0.504f, 0.098f, 0.0625f}; + const float kRGBtoUColorWeights[] = {-0.148f, -0.291f, 0.439f, 0.5f}; + const float kRGBtoVColorWeights[] = {0.439f, -0.368f, -0.071f, 0.5f}; + + for (int y = 0; y < ysize; y++) { + for (int x = 0; x < xsize; x++) { + Y[(y + ymargin) * y_stride + x + xmargin] = float_to_byte( + ChannelAsFloat(&input_pixels, x, y, 0) * kRGBtoYColorWeights[0] + + ChannelAsFloat(&input_pixels, x, y, 1) * kRGBtoYColorWeights[1] + + ChannelAsFloat(&input_pixels, x, y, 2) * kRGBtoYColorWeights[2] + + kRGBtoYColorWeights[3]); + } + } + + for (int y = 0; y < ysize / 2; y++) { + for (int x = 0; x < xsize / 2; x++) { + U[(y + ymargin / 2) * u_stride + x + xmargin / 2] = + float_to_byte(Bilinear(&input_pixels, x * 2 + 1.0, y * 2 + 1.0, 0) * + kRGBtoUColorWeights[0] + + Bilinear(&input_pixels, x * 2 + 1.0, y * 2 + 1.0, 1) * + kRGBtoUColorWeights[1] + + Bilinear(&input_pixels, x * 2 + 1.0, y * 2 + 1.0, 2) * + kRGBtoUColorWeights[2] + + kRGBtoUColorWeights[3]); + V[(y + ymargin / 2) * v_stride + x + xmargin / 2] = + float_to_byte(Bilinear(&input_pixels, x * 2 + 1.0, y * 2 + 1.0, 0) * + kRGBtoVColorWeights[0] + + Bilinear(&input_pixels, x * 2 + 1.0, y * 2 + 1.0, 1) * + kRGBtoVColorWeights[1] + + Bilinear(&input_pixels, x * 2 + 1.0, y * 2 + 1.0, 2) * + kRGBtoVColorWeights[2] + + kRGBtoVColorWeights[3]); + } + } + + ComparePlane( + Y, y_stride, output_frame->visible_data(media::VideoFrame::kYPlane), + output_frame->stride(media::VideoFrame::kYPlane), 2, output_xsize, + output_ysize, &input_pixels, message + " Y plane"); + ComparePlane( + U, u_stride, output_frame->visible_data(media::VideoFrame::kUPlane), + output_frame->stride(media::VideoFrame::kUPlane), 2, output_xsize / 2, + output_ysize / 2, &input_pixels, message + " U plane"); + ComparePlane( + V, v_stride, output_frame->visible_data(media::VideoFrame::kVPlane), + output_frame->stride(media::VideoFrame::kVPlane), 2, output_xsize / 2, + output_ysize / 2, &input_pixels, message + " V plane"); + + gl_->DeleteTextures(1, &src_texture); + } + + std::unique_ptr<gpu::GLInProcessContext> context_; + gpu::gles2::GLES2Interface* gl_; + std::unique_ptr<content::GLHelper> helper_; + gfx::DisableNullDrawGLBindings enable_pixel_output_; +}; + +TEST_F(YUVReadbackTest, YUVReadbackOptTest) { + // This test uses the gpu.service/gpu_decoder tracing events to detect how + // many scaling passes are actually performed by the YUV readback pipeline. + StartTracing(TRACE_DISABLED_BY_DEFAULT( + "gpu.service") "," TRACE_DISABLED_BY_DEFAULT("gpu_decoder")); + + TestYUVReadback(800, 400, 800, 400, 0, 0, 1, false, true, + content::GLHelper::SCALER_QUALITY_FAST); + + std::map<std::string, int> event_counts; + EndTracing(&event_counts); + int draw_buffer_calls = event_counts["kDrawBuffersEXTImmediate"]; + int draw_arrays_calls = event_counts["kDrawArrays"]; + VLOG(1) << "Draw buffer calls: " << draw_buffer_calls; + VLOG(1) << "DrawArrays calls: " << draw_arrays_calls; + + if (draw_buffer_calls) { + // When using MRT, the YUV readback code should only + // execute two draw arrays, and scaling should be integrated + // into those two calls since we are using the FAST scalign + // quality. + EXPECT_EQ(2, draw_arrays_calls); + } else { + // When not using MRT, there are three passes for the YUV, + // and one for the scaling. + EXPECT_EQ(4, draw_arrays_calls); + } +} + +class YUVReadbackPixelTest + : public YUVReadbackTest, + public ::testing::WithParamInterface< + std::tr1::tuple<bool, bool, unsigned int, unsigned int>> {}; + +TEST_P(YUVReadbackPixelTest, Test) { + bool flip = std::tr1::get<0>(GetParam()); + bool use_mrt = std::tr1::get<1>(GetParam()); + unsigned int x = std::tr1::get<2>(GetParam()); + unsigned int y = std::tr1::get<3>(GetParam()); + + for (unsigned int ox = x; ox < arraysize(kYUVReadbackSizes); ox++) { + for (unsigned int oy = y; oy < arraysize(kYUVReadbackSizes); oy++) { + // If output is a subsection of the destination frame, (letterbox) + // then try different variations of where the subsection goes. + for (Margin xm = x < ox ? MarginLeft : MarginRight; xm <= MarginRight; + xm = NextMargin(xm)) { + for (Margin ym = y < oy ? MarginLeft : MarginRight; ym <= MarginRight; + ym = NextMargin(ym)) { + for (int pattern = 0; pattern < 3; pattern++) { + TestYUVReadback( + kYUVReadbackSizes[x], kYUVReadbackSizes[y], + kYUVReadbackSizes[ox], kYUVReadbackSizes[oy], + compute_margin(kYUVReadbackSizes[x], kYUVReadbackSizes[ox], xm), + compute_margin(kYUVReadbackSizes[y], kYUVReadbackSizes[oy], ym), + pattern, flip, use_mrt, content::GLHelper::SCALER_QUALITY_GOOD); + if (HasFailure()) { + return; + } + } + } + } + } + } +} + +// First argument is intentionally empty. +INSTANTIATE_TEST_CASE_P( + , + YUVReadbackPixelTest, + ::testing::Combine( + ::testing::Bool(), + ::testing::Bool(), + ::testing::Range<unsigned int>(0, arraysize(kYUVReadbackSizes)), + ::testing::Range<unsigned int>(0, arraysize(kYUVReadbackSizes)))); + +} // namespace content
diff --git a/content/browser/download/download_manager_impl.cc b/content/browser/download/download_manager_impl.cc index db6bc81..a390ec1 100644 --- a/content/browser/download/download_manager_impl.cc +++ b/content/browser/download/download_manager_impl.cc
@@ -171,7 +171,6 @@ BrowserContext* browser_context) : item_factory_(new DownloadItemFactoryImpl()), file_factory_(new DownloadFileFactory()), - history_size_(0), shutdown_needed_(true), browser_context_(browser_context), delegate_(NULL),
diff --git a/content/browser/download/download_manager_impl.h b/content/browser/download/download_manager_impl.h index 79b8d4f..8b633fcf 100644 --- a/content/browser/download/download_manager_impl.h +++ b/content/browser/download/download_manager_impl.h
@@ -203,8 +203,6 @@ // DownloadItemImpl already normalizes the string GUID. DownloadGuidMap downloads_by_guid_; - int history_size_; - // True if the download manager has been initialized and requires a shutdown. bool shutdown_needed_;
diff --git a/content/browser/download/download_stats.cc b/content/browser/download/download_stats.cc index 6cd66f2e..9da8ca8 100644 --- a/content/browser/download/download_stats.cc +++ b/content/browser/download/download_stats.cc
@@ -320,6 +320,21 @@ FILE_PATH_LITERAL(".zip"), FILE_PATH_LITERAL(".zipx"), FILE_PATH_LITERAL(".zpaq"), + FILE_PATH_LITERAL(".cdr"), + FILE_PATH_LITERAL(".dart"), + FILE_PATH_LITERAL(".dc42"), + FILE_PATH_LITERAL(".diskcopy42"), + FILE_PATH_LITERAL(".dmg"), + FILE_PATH_LITERAL(".dmgpart"), + FILE_PATH_LITERAL(".dvdr"), + FILE_PATH_LITERAL(".img"), + FILE_PATH_LITERAL(".imgpart"), + FILE_PATH_LITERAL(".ndif"), + FILE_PATH_LITERAL(".smi"), + FILE_PATH_LITERAL(".sparsebundle"), + FILE_PATH_LITERAL(".sparseimage"), + FILE_PATH_LITERAL(".toast"), + FILE_PATH_LITERAL(".udif"), }; // Maps extensions to their matching UMA histogram int value.
diff --git a/content/browser/download/save_package.cc b/content/browser/download/save_package.cc index 1d32c9f..b13a01e 100644 --- a/content/browser/download/save_package.cc +++ b/content/browser/download/save_package.cc
@@ -154,7 +154,6 @@ title_(web_contents->GetTitle()), start_tick_(base::TimeTicks::Now()), finished_(false), - mhtml_finishing_(false), user_canceled_(false), disk_error_occurred_(false), save_type_(save_type), @@ -186,7 +185,6 @@ title_(web_contents->GetTitle()), start_tick_(base::TimeTicks::Now()), finished_(false), - mhtml_finishing_(false), user_canceled_(false), disk_error_occurred_(false), save_type_(SAVE_PAGE_TYPE_UNKNOWN), @@ -215,7 +213,6 @@ saved_main_directory_path_(directory_full_path), start_tick_(base::TimeTicks::Now()), finished_(true), - mhtml_finishing_(false), user_canceled_(false), disk_error_occurred_(false), save_type_(SAVE_PAGE_TYPE_UNKNOWN),
diff --git a/content/browser/download/save_package.h b/content/browser/download/save_package.h index e9a9790..d421981 100644 --- a/content/browser/download/save_package.h +++ b/content/browser/download/save_package.h
@@ -380,9 +380,6 @@ // Indicates whether the actual saving job is finishing or not. bool finished_; - // Indicates whether a call to Finish() has been scheduled. - bool mhtml_finishing_; - // Indicates whether user canceled the saving job. bool user_canceled_;
diff --git a/content/browser/fileapi/sandbox_file_system_backend_unittest.cc b/content/browser/fileapi/sandbox_file_system_backend_unittest.cc index a07a6817..45ddb923 100644 --- a/content/browser/fileapi/sandbox_file_system_backend_unittest.cc +++ b/content/browser/fileapi/sandbox_file_system_backend_unittest.cc
@@ -56,11 +56,9 @@ storage::FileSystemType type; const char* origin_url; const char* expected_path; - const char* virtual_path; } kRootPathFileURITestCases[] = { - {storage::kFileSystemTypeTemporary, "file:///", "000" PS "t", NULL}, - {storage::kFileSystemTypePersistent, "file:///", "000" PS "p", NULL}, -}; + {storage::kFileSystemTypeTemporary, "file:///", "000" PS "t"}, + {storage::kFileSystemTypePersistent, "file:///", "000" PS "p"}}; void DidOpenFileSystem(base::File::Error* error_out, const GURL& origin_url,
diff --git a/content/browser/frame_host/frame_tree.cc b/content/browser/frame_host/frame_tree.cc index 0090c38..1bb52d8 100644 --- a/content/browser/frame_host/frame_tree.cc +++ b/content/browser/frame_host/frame_tree.cc
@@ -96,7 +96,6 @@ root_(new FrameTreeNode(this, navigator, render_frame_delegate, - render_view_delegate, render_widget_delegate, manager_delegate, // The top-level frame must always be in a @@ -187,8 +186,8 @@ FrameTreeNode* added_node = parent->AddChild( base::WrapUnique(new FrameTreeNode( this, parent->navigator(), render_frame_delegate_, - render_view_delegate_, render_widget_delegate_, manager_delegate_, - scope, frame_name, frame_unique_name, frame_owner_properties)), + render_widget_delegate_, manager_delegate_, scope, frame_name, + frame_unique_name, frame_owner_properties)), process_id, new_routing_id); // Set sandbox flags and make them effective immediately, since initial
diff --git a/content/browser/frame_host/frame_tree_node.cc b/content/browser/frame_host/frame_tree_node.cc index 35ad0374..547e872f 100644 --- a/content/browser/frame_host/frame_tree_node.cc +++ b/content/browser/frame_host/frame_tree_node.cc
@@ -75,7 +75,6 @@ FrameTree* frame_tree, Navigator* navigator, RenderFrameHostDelegate* render_frame_delegate, - RenderViewHostDelegate* render_view_delegate, RenderWidgetHostDelegate* render_widget_delegate, RenderFrameHostManager::Delegate* manager_delegate, blink::WebTreeScopeType scope, @@ -86,7 +85,6 @@ navigator_(navigator), render_manager_(this, render_frame_delegate, - render_view_delegate, render_widget_delegate, manager_delegate), frame_tree_node_id_(next_frame_tree_node_id_++),
diff --git a/content/browser/frame_host/frame_tree_node.h b/content/browser/frame_host/frame_tree_node.h index 0972447..d3818580 100644 --- a/content/browser/frame_host/frame_tree_node.h +++ b/content/browser/frame_host/frame_tree_node.h
@@ -56,7 +56,6 @@ FrameTreeNode(FrameTree* frame_tree, Navigator* navigator, RenderFrameHostDelegate* render_frame_delegate, - RenderViewHostDelegate* render_view_delegate, RenderWidgetHostDelegate* render_widget_delegate, RenderFrameHostManager::Delegate* manager_delegate, blink::WebTreeScopeType scope,
diff --git a/content/browser/frame_host/navigator_impl.cc b/content/browser/frame_host/navigator_impl.cc index d7c1ca0..e7d9de64 100644 --- a/content/browser/frame_host/navigator_impl.cc +++ b/content/browser/frame_host/navigator_impl.cc
@@ -651,9 +651,15 @@ DCHECK(!render_frame_host->GetParent() || SiteIsolationPolicy::AreCrossProcessFramesPossible()); - SiteInstance* current_site_instance = render_frame_host->frame_tree_node() - ->current_frame_host() - ->GetSiteInstance(); + // Only the current RenderFrameHost should be sending an OpenURL request. + // Pending RenderFrameHost should know where it is navigating and pending + // deletion RenderFrameHost shouldn't be trying to navigate. + if (render_frame_host != + render_frame_host->frame_tree_node()->current_frame_host()) { + return; + } + + SiteInstance* current_site_instance = render_frame_host->GetSiteInstance(); // TODO(creis): Pass the redirect_chain into this method to support client // redirects. http://crbug.com/311721.
diff --git a/content/browser/frame_host/render_frame_host_manager.cc b/content/browser/frame_host/render_frame_host_manager.cc index 191a94e..398f46a 100644 --- a/content/browser/frame_host/render_frame_host_manager.cc +++ b/content/browser/frame_host/render_frame_host_manager.cc
@@ -54,13 +54,11 @@ RenderFrameHostManager::RenderFrameHostManager( FrameTreeNode* frame_tree_node, RenderFrameHostDelegate* render_frame_delegate, - RenderViewHostDelegate* render_view_delegate, RenderWidgetHostDelegate* render_widget_delegate, Delegate* delegate) : frame_tree_node_(frame_tree_node), delegate_(delegate), render_frame_delegate_(render_frame_delegate), - render_view_delegate_(render_view_delegate), render_widget_delegate_(render_widget_delegate), interstitial_page_(nullptr), weak_factory_(this) { @@ -653,23 +651,24 @@ if (old_render_frame_host->GetSiteInstance()->active_frame_count() <= 1) { // Tell the old RenderFrameHost to swap out, with no proxy to replace it. old_render_frame_host->SwapOut(nullptr, true); - MoveToPendingDeleteHosts(std::move(old_render_frame_host)); - return; + } else { + // Otherwise there are active views and we need a proxy for the old RFH. + // (There should not be one yet.) + RenderFrameProxyHost* proxy = + CreateRenderFrameProxyHost(old_render_frame_host->GetSiteInstance(), + old_render_frame_host->render_view_host()); + + // Tell the old RenderFrameHost to swap out and be replaced by the proxy. + old_render_frame_host->SwapOut(proxy, true); + + // SwapOut creates a RenderFrameProxy, so set the proxy to be initialized. + proxy->set_render_frame_proxy_created(true); } - // Otherwise there are active views and we need a proxy for the old RFH. - // (There should not be one yet.) - RenderFrameProxyHost* proxy = - CreateRenderFrameProxyHost(old_render_frame_host->GetSiteInstance(), - old_render_frame_host->render_view_host()); - - // Tell the old RenderFrameHost to swap out and be replaced by the proxy. - old_render_frame_host->SwapOut(proxy, true); - - // SwapOut creates a RenderFrameProxy, so set the proxy to be initialized. - proxy->set_render_frame_proxy_created(true); - - MoveToPendingDeleteHosts(std::move(old_render_frame_host)); + // |old_render_frame_host| will be deleted when its SwapOut ACK is received, + // or when the timer times out, or when the RFHM itself is deleted (whichever + // comes first). + pending_delete_hosts_.push_back(std::move(old_render_frame_host)); } void RenderFrameHostManager::DiscardUnusedFrame( @@ -701,14 +700,6 @@ render_frame_host.reset(); } -void RenderFrameHostManager::MoveToPendingDeleteHosts( - std::unique_ptr<RenderFrameHostImpl> render_frame_host) { - // |render_frame_host| will be deleted when its SwapOut ACK is received, or - // when the timer times out, or when the RFHM itself is deleted (whichever - // comes first). - pending_delete_hosts_.push_back(std::move(render_frame_host)); -} - bool RenderFrameHostManager::IsViewPendingDeletion( RenderViewHostImpl* render_view_host) { // Only safe to call this on the main frame.
diff --git a/content/browser/frame_host/render_frame_host_manager.h b/content/browser/frame_host/render_frame_host_manager.h index 5468300..90e58e9 100644 --- a/content/browser/frame_host/render_frame_host_manager.h +++ b/content/browser/frame_host/render_frame_host_manager.h
@@ -188,7 +188,6 @@ RenderFrameHostManager( FrameTreeNode* frame_tree_node, RenderFrameHostDelegate* render_frame_delegate, - RenderViewHostDelegate* render_view_delegate, RenderWidgetHostDelegate* render_widget_delegate, Delegate* delegate); ~RenderFrameHostManager(); @@ -705,11 +704,6 @@ void DiscardUnusedFrame( std::unique_ptr<RenderFrameHostImpl> render_frame_host); - // Holds |render_frame_host| until it can be deleted when its swap out ACK - // arrives. - void MoveToPendingDeleteHosts( - std::unique_ptr<RenderFrameHostImpl> render_frame_host); - // Helper method to terminate the pending RenderFrameHost. The frame may be // deleted immediately, or it may be kept around in hopes of later reuse. void CancelPending(); @@ -751,7 +745,6 @@ // Implemented by the owner of this class. These delegates are installed into // all the RenderFrameHosts that we create. RenderFrameHostDelegate* render_frame_delegate_; - RenderViewHostDelegate* render_view_delegate_; RenderWidgetHostDelegate* render_widget_delegate_; // Our RenderFrameHost which is responsible for all communication with a child
diff --git a/content/browser/frame_host/render_widget_host_view_guest_unittest.cc b/content/browser/frame_host/render_widget_host_view_guest_unittest.cc index 4ddc8634..f2fdc76 100644 --- a/content/browser/frame_host/render_widget_host_view_guest_unittest.cc +++ b/content/browser/frame_host/render_widget_host_view_guest_unittest.cc
@@ -138,7 +138,6 @@ cc::SurfaceId last_surface_id_received_; gfx::Size last_frame_size_received_; float last_scale_factor_received_; - float update_scale_factor_received_; }; // TODO(wjmaclean): we should restructure RenderWidgetHostViewChildFrameTest to
diff --git a/content/browser/gpu/gpu_data_manager_impl_private.cc b/content/browser/gpu/gpu_data_manager_impl_private.cc index 131221842..ceb4500 100644 --- a/content/browser/gpu/gpu_data_manager_impl_private.cc +++ b/content/browser/gpu/gpu_data_manager_impl_private.cc
@@ -985,7 +985,6 @@ use_swiftshader_(false), card_blacklisted_(false), update_histograms_(true), - window_count_(0), domain_blocking_enabled_(true), owner_(owner), gpu_process_accessible_(true),
diff --git a/content/browser/gpu/gpu_data_manager_impl_private.h b/content/browser/gpu/gpu_data_manager_impl_private.h index 2f5ee1da..420d6ba 100644 --- a/content/browser/gpu/gpu_data_manager_impl_private.h +++ b/content/browser/gpu/gpu_data_manager_impl_private.h
@@ -255,9 +255,6 @@ // they cause random failures. bool update_histograms_; - // Number of currently open windows, to be used in gpu memory allocation. - int window_count_; - DomainBlockMap blocked_domains_; mutable std::list<base::Time> timestamps_of_gpu_resets_; bool domain_blocking_enabled_;
diff --git a/content/browser/gpu/gpu_ipc_browsertests.cc b/content/browser/gpu/gpu_ipc_browsertests.cc index d218114..651a77a 100644 --- a/content/browser/gpu/gpu_ipc_browsertests.cc +++ b/content/browser/gpu/gpu_ipc_browsertests.cc
@@ -14,7 +14,6 @@ #include "content/public/browser/gpu_data_manager.h" #include "content/public/common/content_switches.h" #include "content/public/test/content_browser_test.h" -#include "gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkPaint.h" #include "third_party/skia/include/core/SkSurface.h"
diff --git a/content/browser/gpu/gpu_process_host.cc b/content/browser/gpu/gpu_process_host.cc index 1cb9675c..909e82d 100644 --- a/content/browser/gpu/gpu_process_host.cc +++ b/content/browser/gpu/gpu_process_host.cc
@@ -43,6 +43,7 @@ #include "content/public/browser/render_widget_host_view_frame_subscriber.h" #include "content/public/common/content_client.h" #include "content/public/common/content_switches.h" +#include "content/public/common/mojo_channel_switches.h" #include "content/public/common/result_codes.h" #include "content/public/common/sandbox_type.h" #include "content/public/common/sandboxed_process_launcher_delegate.h" @@ -537,8 +538,8 @@ if (channel_id.empty()) return false; - if (!SetupMojo()) - return false; + DCHECK(!mojo_application_host_); + mojo_application_host_.reset(new MojoApplicationHost); gpu::GpuPreferences gpu_preferences = GetGpuPreferencesFromCommandLine(); if (in_process_) { @@ -546,7 +547,8 @@ DCHECK(g_gpu_main_thread_factory); in_process_gpu_thread_.reset( g_gpu_main_thread_factory(InProcessChildThreadParams( - channel_id, base::MessageLoop::current()->task_runner()), + channel_id, base::MessageLoop::current()->task_runner(), + std::string(), mojo_application_host_->GetToken()), gpu_preferences)); base::Thread::Options options; #if defined(OS_WIN) @@ -569,12 +571,6 @@ return true; } -bool GpuProcessHost::SetupMojo() { - DCHECK(!mojo_application_host_); - mojo_application_host_.reset(new MojoApplicationHost); - return mojo_application_host_->Init(); -} - void GpuProcessHost::RouteOnUIThread(const IPC::Message& message) { BrowserThread::PostTask( BrowserThread::UI, @@ -898,14 +894,6 @@ void GpuProcessHost::OnProcessLaunched() { UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime", base::TimeTicks::Now() - init_start_time_); - - base::ProcessHandle handle; - if (in_process_) - handle = base::GetCurrentProcessHandle(); - else - handle = process_->GetData().handle; - - mojo_application_host_->Activate(this, handle); } void GpuProcessHost::OnProcessLaunchFailed() { @@ -977,6 +965,8 @@ #endif cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kGpuProcess); cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id); + cmd_line->AppendSwitchASCII(switches::kMojoApplicationChannelToken, + mojo_application_host_->GetToken()); #if defined(OS_WIN) if (GetContentClient()->browser()->ShouldUseWindowsPrefetchArgument())
diff --git a/content/browser/gpu/gpu_process_host.h b/content/browser/gpu/gpu_process_host.h index 63c75df..18b9d2d 100644 --- a/content/browser/gpu/gpu_process_host.h +++ b/content/browser/gpu/gpu_process_host.h
@@ -172,9 +172,6 @@ bool Init(); - // Sets up mojo support in GPU process. Returns false upon failure. - bool SetupMojo(); - // Post an IPC message to the UI shim's message handler on the UI thread. void RouteOnUIThread(const IPC::Message& message);
diff --git a/content/browser/loader/cross_site_resource_handler.cc b/content/browser/loader/cross_site_resource_handler.cc index c645670d..67d364a 100644 --- a/content/browser/loader/cross_site_resource_handler.cc +++ b/content/browser/loader/cross_site_resource_handler.cc
@@ -69,7 +69,7 @@ RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(params.global_request_id.child_id, params.render_frame_id); - if (rfh) { + if (rfh && rfh->is_active()) { if (rfh->GetParent()) { // We should only swap processes for subframes in --site-per-process mode. // CrossSiteResourceHandler is not installed on subframe requests in @@ -80,7 +80,7 @@ params.global_request_id, std::move(cross_site_transferring_request), params.transfer_url_chain, params.referrer, params.page_transition, params.should_replace_current_entry); - } else if (leak_requests_for_testing_ && cross_site_transferring_request) { + } else if (leak_requests_for_testing_) { // Some unit tests expect requests to be leaked in this case, so they can // pass them along manually. cross_site_transferring_request->ReleaseRequest(); @@ -97,7 +97,7 @@ // Without a valid RFH against which to check, we must cancel the request, // to prevent the resource at |url| from being delivered to a potentially // unsuitable renderer process. - if (!rfh) + if (!rfh || !rfh->is_active()) return CrossSiteResourceHandler::NavigationDecision::CANCEL_REQUEST; RenderFrameHostManager* manager = rfh->frame_tree_node()->render_manager();
diff --git a/content/browser/loader/resource_dispatcher_host_unittest.cc b/content/browser/loader/resource_dispatcher_host_unittest.cc index 736bd77..1350fd3 100644 --- a/content/browser/loader/resource_dispatcher_host_unittest.cc +++ b/content/browser/loader/resource_dispatcher_host_unittest.cc
@@ -893,7 +893,6 @@ ResourceDispatcherHostTest() : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), use_test_ssl_certificate_(false), - old_factory_(NULL), send_data_received_acks_(false), auto_advance_(false) { browser_context_.reset(new TestBrowserContext()); @@ -1189,7 +1188,6 @@ std::string response_data_; bool use_test_ssl_certificate_; std::string scheme_; - net::URLRequest::ProtocolFactory* old_factory_; bool send_data_received_acks_; std::set<int> child_ids_; std::unique_ptr<base::RunLoop> wait_for_request_complete_loop_;
diff --git a/content/browser/media/capture/web_contents_video_capture_device_unittest.cc b/content/browser/media/capture/web_contents_video_capture_device_unittest.cc index 81674324..32e4209 100644 --- a/content/browser/media/capture/web_contents_video_capture_device_unittest.cc +++ b/content/browser/media/capture/web_contents_video_capture_device_unittest.cc
@@ -283,8 +283,7 @@ controller)), delegate, main_frame_routing_id, - swapped_out), - controller_(controller) { + swapped_out) { // Override the default view installed by TestRenderViewHost; we need // our special subclass which has mocked-out tab capture support. RenderWidgetHostView* old_view = GetWidget()->GetView(); @@ -293,8 +292,6 @@ } private: - CaptureTestSourceController* controller_; - DISALLOW_IMPLICIT_CONSTRUCTORS(CaptureTestRenderViewHost); };
diff --git a/content/browser/mojo/mojo_application_host.cc b/content/browser/mojo/mojo_application_host.cc index df6a964..f2b110e 100644 --- a/content/browser/mojo/mojo_application_host.cc +++ b/content/browser/mojo/mojo_application_host.cc
@@ -6,12 +6,9 @@ #include <utility> +#include "base/logging.h" #include "build/build_config.h" -#include "content/common/mojo/mojo_messages.h" -#include "content/public/browser/browser_thread.h" -#include "ipc/ipc_sender.h" #include "mojo/edk/embedder/embedder.h" -#include "mojo/edk/embedder/platform_channel_pair.h" namespace content { namespace { @@ -41,70 +38,22 @@ } // namespace -MojoApplicationHost::MojoApplicationHost() : did_activate_(false) { +MojoApplicationHost::MojoApplicationHost() + : token_(mojo::edk::GenerateRandomToken()) { #if defined(OS_ANDROID) service_registry_android_ = ServiceRegistryAndroid::Create(&service_registry_); #endif -} -MojoApplicationHost::~MojoApplicationHost() { -} - -bool MojoApplicationHost::Init() { - DCHECK(!client_handle_.is_valid()) << "Already initialized!"; - - mojo::edk::PlatformChannelPair channel_pair; - - scoped_refptr<base::TaskRunner> io_task_runner; - if (io_task_runner_override_) { - io_task_runner = io_task_runner_override_; - } else { - io_task_runner = - BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO) - ->task_runner(); - } - - // Forward this to the client once we know its process handle. - client_handle_ = channel_pair.PassClientHandle(); - mojo::ScopedMessagePipeHandle pipe = channel_init_.Init( - channel_pair.PassServerHandle().release().handle, io_task_runner); - application_setup_.reset(new ApplicationSetupImpl( - &service_registry_, - mojo::MakeRequest<mojom::ApplicationSetup>(std::move(pipe)))); - return true; -} - -void MojoApplicationHost::Activate(IPC::Sender* sender, - base::ProcessHandle process_handle) { - DCHECK(!did_activate_); - DCHECK(client_handle_.is_valid()); - - base::PlatformFile client_file = client_handle_.release().handle; - did_activate_ = sender->Send(new MojoMsg_Activate( - IPC::GetPlatformFileForTransit(client_file, true))); -} - -std::string MojoApplicationHost::InitWithToken() { - DCHECK(!client_handle_.is_valid()) << "Already initialized!"; - DCHECK(!did_activate_); - - std::string token = mojo::edk::GenerateRandomToken(); mojo::ScopedMessagePipeHandle pipe = - mojo::edk::CreateParentMessagePipe(token); + mojo::edk::CreateParentMessagePipe(token_); DCHECK(pipe.is_valid()); application_setup_.reset(new ApplicationSetupImpl( &service_registry_, mojo::MakeRequest<mojom::ApplicationSetup>(std::move(pipe)))); - - did_activate_ = true; - return token; } -void MojoApplicationHost::OverrideIOTaskRunnerForTest( - scoped_refptr<base::TaskRunner> io_task_runner) { - io_task_runner_override_ = io_task_runner; +MojoApplicationHost::~MojoApplicationHost() { } - } // namespace content
diff --git a/content/browser/mojo/mojo_application_host.h b/content/browser/mojo/mojo_application_host.h index 50fdfdf..b1bc026 100644 --- a/content/browser/mojo/mojo_application_host.h +++ b/content/browser/mojo/mojo_application_host.h
@@ -9,13 +9,9 @@ #include <string> #include "base/macros.h" -#include "base/process/process_handle.h" #include "build/build_config.h" #include "content/common/application_setup.mojom.h" -#include "content/common/mojo/channel_init.h" #include "content/common/mojo/service_registry_impl.h" -#include "mojo/edk/embedder/scoped_platform_handle.h" -#include "mojo/public/cpp/system/message_pipe.h" #if defined(OS_ANDROID) #include "content/public/browser/android/service_registry_android.h" @@ -28,24 +24,18 @@ namespace content { // MojoApplicationHost represents the code needed on the browser side to setup -// a child process as a Mojo application via Chrome IPC. The child process -// should use MojoApplication to handle messages generated by an instance of -// MojoApplicationHost. MojoApplicationHost makes the ServiceRegistry interface -// available so that child-provided services can be invoked. +// a child process as a Mojo application. The child process should use the token +// from GetToken() to initialize its MojoApplication. MojoApplicationHost makes +// the ServiceRegistry interface available so that child-provided services can +// be invoked. class CONTENT_EXPORT MojoApplicationHost { public: MojoApplicationHost(); ~MojoApplicationHost(); - // Two-phase initialization: - // 1- Init makes service_registry() available synchronously. - // 2- Activate establishes the actual connection to the peer process. - bool Init(); - void Activate(IPC::Sender* sender, base::ProcessHandle process_handle); - - // Use a shared token to initialize the application. Returns a token to pass - // to the child process. - std::string InitWithToken(); + // Returns a token to pass to the child process to initialize its + // MojoApplication. + const std::string& GetToken() { return token_; } ServiceRegistry* service_registry() { return &service_registry_; } @@ -55,20 +45,12 @@ } #endif - void OverrideIOTaskRunnerForTest( - scoped_refptr<base::TaskRunner> io_task_runner); - private: - ChannelInit channel_init_; - mojo::edk::ScopedPlatformHandle client_handle_; - - bool did_activate_; + const std::string token_; std::unique_ptr<mojom::ApplicationSetup> application_setup_; ServiceRegistryImpl service_registry_; - scoped_refptr<base::TaskRunner> io_task_runner_override_; - #if defined(OS_ANDROID) std::unique_ptr<ServiceRegistryAndroid> service_registry_android_; #endif
diff --git a/content/browser/presentation/presentation_service_impl_unittest.cc b/content/browser/presentation/presentation_service_impl_unittest.cc index 172e8b5..e1a2b35 100644 --- a/content/browser/presentation/presentation_service_impl_unittest.cc +++ b/content/browser/presentation/presentation_service_impl_unittest.cc
@@ -192,7 +192,7 @@ class PresentationServiceImplTest : public RenderViewHostImplTestHarness { public: - PresentationServiceImplTest() : default_session_started_count_(0) {} + PresentationServiceImplTest() {} void SetUp() override { RenderViewHostImplTestHarness::SetUp(); @@ -366,7 +366,6 @@ client_binding_; base::Closure run_loop_quit_closure_; - int default_session_started_count_; }; TEST_F(PresentationServiceImplTest, ListenForScreenAvailability) {
diff --git a/content/browser/renderer_host/begin_frame_observer_proxy.cc b/content/browser/renderer_host/begin_frame_observer_proxy.cc deleted file mode 100644 index 06baa18b..0000000 --- a/content/browser/renderer_host/begin_frame_observer_proxy.cc +++ /dev/null
@@ -1,78 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/renderer_host/begin_frame_observer_proxy.h" - -namespace content { - -BeginFrameObserverProxy::BeginFrameObserverProxy( - BeginFrameObserverProxyClient* client) - : needs_begin_frames_(false), - client_(client), - compositor_(nullptr) { -} - -BeginFrameObserverProxy::~BeginFrameObserverProxy() { - DCHECK(!compositor_); -} - -void BeginFrameObserverProxy::SetNeedsBeginFrames(bool needs_begin_frames) { - if (needs_begin_frames_ == needs_begin_frames) - return; - - needs_begin_frames_ = needs_begin_frames; - - // In some cases, BeginFrame message is requested before |client_|'s window is - // added in the root window hierarchy. - if (!compositor_) - return; - - if (needs_begin_frames) - StartObservingBeginFrames(); - else - StopObservingBeginFrames(); -} - -void BeginFrameObserverProxy::SetCompositor(ui::Compositor* compositor) { - DCHECK(!compositor_); - DCHECK(compositor); - - compositor_ = compositor; - compositor_->AddObserver(this); - if (needs_begin_frames_) - StartObservingBeginFrames(); -} - -void BeginFrameObserverProxy::ResetCompositor() { - if (!compositor_) - return; - compositor_->RemoveObserver(this); - - if (needs_begin_frames_) - StopObservingBeginFrames(); - compositor_ = nullptr; -} - -void BeginFrameObserverProxy::OnSendBeginFrame(const cc::BeginFrameArgs& args) { - if (last_sent_begin_frame_args_.frame_time != args.frame_time) - client_->SendBeginFrame(args); - last_sent_begin_frame_args_ = args; -} - -void BeginFrameObserverProxy::OnCompositingShuttingDown( - ui::Compositor* compositor) { - ResetCompositor(); -} - -void BeginFrameObserverProxy::StartObservingBeginFrames() { - DCHECK(compositor_); - compositor_->AddBeginFrameObserver(this); -} - -void BeginFrameObserverProxy::StopObservingBeginFrames() { - DCHECK(compositor_); - compositor_->RemoveBeginFrameObserver(this); -} - -} // namespace content
diff --git a/content/browser/renderer_host/begin_frame_observer_proxy.h b/content/browser/renderer_host/begin_frame_observer_proxy.h deleted file mode 100644 index a5fa2e6..0000000 --- a/content/browser/renderer_host/begin_frame_observer_proxy.h +++ /dev/null
@@ -1,73 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_BROWSER_RENDERER_HOST_BEGIN_FRAME_OBSERVER_PROXY_H_ -#define CONTENT_BROWSER_RENDERER_HOST_BEGIN_FRAME_OBSERVER_PROXY_H_ - -#include "base/macros.h" -#include "content/common/content_export.h" -#include "ui/compositor/compositor.h" -#include "ui/compositor/compositor_observer.h" - -namespace cc { -struct BeginFrameArgs; -} - -namespace content { - -// This is the interface from the BeginFrameObserverProxy which manages sending -// BeginFrame messages. -class BeginFrameObserverProxyClient { - public: - virtual void SendBeginFrame(const cc::BeginFrameArgs& args) = 0; -}; - -// This class is used to manage all of the RenderWidgetHostView state and -// functionality that is associated with BeginFrame message handling. -class CONTENT_EXPORT BeginFrameObserverProxy - : public ui::CompositorBeginFrameObserver, - public ui::CompositorObserver { - public: - explicit BeginFrameObserverProxy(BeginFrameObserverProxyClient* client); - ~BeginFrameObserverProxy() override; - - void SetNeedsBeginFrames(bool needs_begin_frames); - - void SetCompositor(ui::Compositor* compositor); - void ResetCompositor(); - - // Overridden from ui::CompositorBeginFrameObserver: - void OnSendBeginFrame(const cc::BeginFrameArgs& args) override; - - // Overridden from ui::CompositorObserver: - // TODO(simonhong): Stop overriding ui::CompositorObserver. We need to make - // sure that this class should be destroyed before ui::Compositor. - void OnCompositingDidCommit(ui::Compositor* compositor) override {} - void OnCompositingStarted(ui::Compositor* compositor, - base::TimeTicks start_time) override {} - void OnCompositingEnded(ui::Compositor* compositor) override {} - void OnCompositingAborted(ui::Compositor* compositor) override {} - void OnCompositingLockStateChanged(ui::Compositor* compositor) override {} - void OnCompositingShuttingDown(ui::Compositor* compositor) override; - - private: - void StartObservingBeginFrames(); - void StopObservingBeginFrames(); - - // True when RenderWidget needs a BeginFrame message. - bool needs_begin_frames_; - - // Used whether to send begin frame to client or not. When |args| from - // Compositor is different from this, send to client. - cc::BeginFrameArgs last_sent_begin_frame_args_; - - BeginFrameObserverProxyClient* client_; - ui::Compositor* compositor_; - - DISALLOW_COPY_AND_ASSIGN(BeginFrameObserverProxy); -}; - -} // namespace content - -#endif // CONTENT_BROWSER_RENDERER_HOST_BEGIN_FRAME_OBSERVER_PROXY_H_
diff --git a/content/browser/renderer_host/begin_frame_observer_proxy_unittest.cc b/content/browser/renderer_host/begin_frame_observer_proxy_unittest.cc deleted file mode 100644 index 56e89760..0000000 --- a/content/browser/renderer_host/begin_frame_observer_proxy_unittest.cc +++ /dev/null
@@ -1,97 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/renderer_host/begin_frame_observer_proxy.h" - -#include <algorithm> -#include <list> -#include <memory> - -#include "base/compiler_specific.h" -#include "base/test/test_simple_task_runner.h" -#include "cc/output/begin_frame_args.h" -#include "cc/test/begin_frame_args_test.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/compositor/compositor.h" -#include "ui/compositor/test/context_factories_for_test.h" - -using testing::Mock; -using testing::_; - -namespace content { -namespace { - -class MockBeginFrameObserverProxyClient : public BeginFrameObserverProxyClient { - public: - MOCK_METHOD1(SendBeginFrame, void(const cc::BeginFrameArgs&)); -}; - -class BeginFrameObserverProxyTest : public testing::Test { - public: - BeginFrameObserverProxyTest() {} - ~BeginFrameObserverProxyTest() override {} - - void SetUp() override { - bool enable_pixel_output = false; - ui::ContextFactory* context_factory = - ui::InitializeContextFactoryForTests(enable_pixel_output); - compositor_task_runner_ = new base::TestSimpleTaskRunner(); - compositor_.reset( - new ui::Compositor(context_factory, compositor_task_runner_)); - compositor_->SetAcceleratedWidget(gfx::kNullAcceleratedWidget); - } - - void TearDown() override { - compositor_.reset(); - ui::TerminateContextFactoryForTests(); - } - - ui::Compositor* compositor() { return compositor_.get(); } - - private: - scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner_; - std::unique_ptr<ui::Compositor> compositor_; -}; - -} // namespace - -TEST_F(BeginFrameObserverProxyTest, BeginFrameScheduling) { - MockBeginFrameObserverProxyClient client; - BeginFrameObserverProxy begin_frame_observer(&client); - begin_frame_observer.SetCompositor(compositor()); - begin_frame_observer.SetNeedsBeginFrames(true); - - // SendBeginFrame is called when new |args| is delivered. - cc::BeginFrameArgs args = - cc::CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE, - base::TimeTicks::FromInternalValue(33)); - EXPECT_CALL(client, SendBeginFrame(args)); - compositor()->SendBeginFramesToChildren(args); - Mock::VerifyAndClearExpectations(&client); - - // SendBeginFrame is called when new |args2| is delivered. - cc::BeginFrameArgs args2 = - cc::CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE, - base::TimeTicks::FromInternalValue(66)); - EXPECT_CALL(client, SendBeginFrame(args2)); - compositor()->SendBeginFramesToChildren(args2); - Mock::VerifyAndClearExpectations(&client); - - // SendBeginFrame is not called when used |args2| is delivered. - EXPECT_CALL(client, SendBeginFrame(_)).Times(0); - compositor()->SendBeginFramesToChildren(args2); - Mock::VerifyAndClearExpectations(&client); - - // SendBeginFrame is not called when compositor is reset. - begin_frame_observer.ResetCompositor(); - cc::BeginFrameArgs args3 = - cc::CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE, - base::TimeTicks::FromInternalValue(99)); - EXPECT_CALL(client, SendBeginFrame(_)).Times(0); - compositor()->SendBeginFramesToChildren(args3); - Mock::VerifyAndClearExpectations(&client); -} - -} // namespace content
diff --git a/content/browser/renderer_host/compositor_impl_android.cc b/content/browser/renderer_host/compositor_impl_android.cc index 6a91f32..499a216 100644 --- a/content/browser/renderer_host/compositor_impl_android.cc +++ b/content/browser/renderer_host/compositor_impl_android.cc
@@ -58,7 +58,6 @@ #include "content/public/browser/android/compositor.h" #include "content/public/browser/android/compositor_client.h" #include "content/public/common/content_switches.h" -#include "gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.h" #include "gpu/command_buffer/client/context_support.h" #include "gpu/command_buffer/client/gles2_interface.h" #include "gpu/ipc/client/command_buffer_proxy_impl.h" @@ -255,8 +254,8 @@ CompositorImpl::CompositorImpl(CompositorClient* client, gfx::NativeWindow root_window) : root_layer_(cc::Layer::Create()), - resource_manager_(root_window), surface_id_allocator_(CreateSurfaceIdAllocator()), + resource_manager_(root_window), has_transparent_background_(false), device_scale_factor_(1), window_(NULL),
diff --git a/content/browser/renderer_host/compositor_impl_android.h b/content/browser/renderer_host/compositor_impl_android.h index 1e284b7..95489d9 100644 --- a/content/browser/renderer_host/compositor_impl_android.h +++ b/content/browser/renderer_host/compositor_impl_android.h
@@ -133,12 +133,12 @@ scoped_refptr<cc::Layer> subroot_layer_; // Destruction order matters here: + std::unique_ptr<cc::SurfaceIdAllocator> surface_id_allocator_; base::ObserverList<VSyncObserver, true> observer_list_; std::unique_ptr<cc::LayerTreeHost> host_; ui::ResourceManagerImpl resource_manager_; std::unique_ptr<cc::OnscreenDisplayClient> display_client_; - std::unique_ptr<cc::SurfaceIdAllocator> surface_id_allocator_; gfx::Size size_; bool has_transparent_background_;
diff --git a/content/browser/renderer_host/delegated_frame_host.cc b/content/browser/renderer_host/delegated_frame_host.cc index cef537d3..60c1000 100644 --- a/content/browser/renderer_host/delegated_frame_host.cc +++ b/content/browser/renderer_host/delegated_frame_host.cc
@@ -73,8 +73,7 @@ background_color_(SK_ColorRED), current_scale_factor_(1.f), can_lock_compositor_(YES_CAN_LOCK), - delegated_frame_evictor_(new DelegatedFrameEvictor(this)), - begin_frame_source_(nullptr) { + delegated_frame_evictor_(new DelegatedFrameEvictor(this)) { ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); factory->AddObserver(this); id_allocator_ = factory->GetContextFactory()->CreateSurfaceIdAllocator(); @@ -552,8 +551,7 @@ void DelegatedFrameHost::SetBeginFrameSource( cc::BeginFrameSource* begin_frame_source) { - // TODO(enne): forward this to DelegatedFrameHostClient to observe and then to - // the renderer as an external begin frame source. + client_->SetBeginFrameSource(begin_frame_source); } void DelegatedFrameHost::EvictDelegatedFrame() {
diff --git a/content/browser/renderer_host/delegated_frame_host.h b/content/browser/renderer_host/delegated_frame_host.h index 66b0ac2..58faa73 100644 --- a/content/browser/renderer_host/delegated_frame_host.h +++ b/content/browser/renderer_host/delegated_frame_host.h
@@ -73,6 +73,7 @@ virtual void DelegatedFrameHostUpdateVSyncParameters( const base::TimeTicks& timebase, const base::TimeDelta& interval) = 0; + virtual void SetBeginFrameSource(cc::BeginFrameSource* source) = 0; }; // The DelegatedFrameHost is used to host all of the RenderWidgetHostView state @@ -317,8 +318,6 @@ std::unique_ptr<content::ReadbackYUVInterface> yuv_readback_pipeline_; std::unique_ptr<DelegatedFrameEvictor> delegated_frame_evictor_; - - cc::BeginFrameSource* begin_frame_source_; }; } // namespace content
diff --git a/content/browser/renderer_host/input/mouse_wheel_event_queue.cc b/content/browser/renderer_host/input/mouse_wheel_event_queue.cc index a777b860..38405d8 100644 --- a/content/browser/renderer_host/input/mouse_wheel_event_queue.cc +++ b/content/browser/renderer_host/input/mouse_wheel_event_queue.cc
@@ -29,7 +29,6 @@ } private: - bool original_can_scroll_; DISALLOW_COPY_AND_ASSIGN(QueuedWebMouseWheelEvent); };
diff --git a/content/browser/renderer_host/input/synthetic_mouse_pointer.h b/content/browser/renderer_host/input/synthetic_mouse_pointer.h index 9f806f3b..a5fbf04 100644 --- a/content/browser/renderer_host/input/synthetic_mouse_pointer.h +++ b/content/browser/renderer_host/input/synthetic_mouse_pointer.h
@@ -34,7 +34,6 @@ const base::TimeTicks& timestamp) override; private: - SyntheticGestureParams::GestureSourceType gesture_source_type_; blink::WebMouseEvent mouse_event_; DISALLOW_COPY_AND_ASSIGN(SyntheticMousePointer); };
diff --git a/content/browser/renderer_host/pepper/pepper_file_io_host.cc b/content/browser/renderer_host/pepper/pepper_file_io_host.cc index bf8bd1a..06621c08 100644 --- a/content/browser/renderer_host/pepper/pepper_file_io_host.cc +++ b/content/browser/renderer_host/pepper/pepper_file_io_host.cc
@@ -110,7 +110,6 @@ PP_Resource resource) : ResourceHost(host->GetPpapiHost(), instance, resource), browser_ppapi_host_(host), - render_process_host_(NULL), file_(BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE) .get()), open_flags_(0),
diff --git a/content/browser/renderer_host/pepper/pepper_file_io_host.h b/content/browser/renderer_host/pepper/pepper_file_io_host.h index 6899c2f..cc214ec2 100644 --- a/content/browser/renderer_host/pepper/pepper_file_io_host.h +++ b/content/browser/renderer_host/pepper/pepper_file_io_host.h
@@ -115,7 +115,6 @@ BrowserPpapiHostImpl* browser_ppapi_host_; - RenderProcessHost* render_process_host_; int render_process_id_; base::ProcessId resolved_render_process_id_;
diff --git a/content/browser/renderer_host/render_message_filter.cc b/content/browser/renderer_host/render_message_filter.cc index 7165bbd..4be8b4b 100644 --- a/content/browser/renderer_host/render_message_filter.cc +++ b/content/browser/renderer_host/render_message_filter.cc
@@ -493,8 +493,7 @@ size_t buffer_size, const base::SharedMemoryHandle& handle, const cc::SharedBitmapId& id) { - bitmap_manager_client_.ChildAllocatedSharedBitmap(buffer_size, handle, - PeerHandle(), id); + bitmap_manager_client_.ChildAllocatedSharedBitmap(buffer_size, handle, id); } void RenderMessageFilter::OnDeletedSharedBitmap(const cc::SharedBitmapId& id) {
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index f37f453..4a8c291 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -128,8 +128,6 @@ #include "content/common/frame_messages.h" #include "content/common/gpu_host_messages.h" #include "content/common/in_process_child_thread_params.h" -#include "content/common/mojo/channel_init.h" -#include "content/common/mojo/mojo_messages.h" #include "content/common/mojo/mojo_shell_connection_impl.h" #include "content/common/render_process_messages.h" #include "content/common/resource_messages.h" @@ -736,9 +734,6 @@ content::BrowserThread::IO)); #endif - // Setup the Mojo channel. - mojo_application_host_->Init(); - // Call the embedder first so that their IPC filters have priority. GetContentClient()->browser()->RenderProcessWillLaunch(this); @@ -758,7 +753,7 @@ channel_id, BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO) ->task_runner(), - in_process_renderer_handle_.release()))); + mojo_channel_token_, mojo_application_host_->GetToken()))); base::Thread::Options options; #if defined(OS_WIN) && !defined(OS_MACOSX) @@ -817,16 +812,9 @@ BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO); if (ShouldUseMojoChannel()) { VLOG(1) << "Mojo Channel is enabled on host"; - mojo::ScopedMessagePipeHandle handle; - - if (run_renderer_in_process()) { - mojo::MessagePipe pipe; - handle = std::move(pipe.handle0); - in_process_renderer_handle_ = std::move(pipe.handle1); - } else { - mojo_channel_token_ = mojo::edk::GenerateRandomToken(); - handle = mojo::edk::CreateParentMessagePipe(mojo_channel_token_); - } + mojo_channel_token_ = mojo::edk::GenerateRandomToken(); + mojo::ScopedMessagePipeHandle handle = + mojo::edk::CreateParentMessagePipe(mojo_channel_token_); // Do NOT expand ifdef or run time condition checks here! Synchronous // IPCs from browser process are banned. It is only narrowly allowed @@ -1390,6 +1378,8 @@ command_line->AppendSwitchASCII(switches::kMojoChannelToken, mojo_channel_token_); } + command_line->AppendSwitchASCII(switches::kMojoApplicationChannelToken, + mojo_application_host_->GetToken()); } void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer( @@ -1399,6 +1389,7 @@ // with any associated values) if present in the browser command line. static const char* const kSwitchNames[] = { switches::kAgcStartupMinVolume, + switches::kAecRefinedAdaptiveFilter, switches::kAllowLoopbackInPeerConnection, switches::kAndroidFontsPath, switches::kAudioBufferSize, @@ -2631,11 +2622,6 @@ Source<RenderProcessHost>(this), NotificationService::NoDetails()); - // Allow Mojo to be setup before the renderer sees any Chrome IPC messages. - // This way, Mojo can be safely used from the renderer in response to any - // Chrome IPC message. - mojo_application_host_->Activate(this, GetHandle()); - while (!queued_messages_.empty()) { Send(queued_messages_.front()); queued_messages_.pop();
diff --git a/content/browser/renderer_host/render_view_host_impl.cc b/content/browser/renderer_host/render_view_host_impl.cc index 64ddcca..13b66f4 100644 --- a/content/browser/renderer_host/render_view_host_impl.cc +++ b/content/browser/renderer_host/render_view_host_impl.cc
@@ -219,7 +219,6 @@ frames_ref_count_(0), delegate_(delegate), instance_(static_cast<SiteInstanceImpl*>(instance)), - waiting_for_drag_context_response_(false), enabled_bindings_(0), page_id_(-1), is_active_(!swapped_out),
diff --git a/content/browser/renderer_host/render_view_host_impl.h b/content/browser/renderer_host/render_view_host_impl.h index 2e73c243..ba69564c 100644 --- a/content/browser/renderer_host/render_view_host_impl.h +++ b/content/browser/renderer_host/render_view_host_impl.h
@@ -359,10 +359,6 @@ // over time. scoped_refptr<SiteInstanceImpl> instance_; - // true if we are currently waiting for a response for drag context - // information. - bool waiting_for_drag_context_response_; - // A bitwise OR of bindings types that have been enabled for this RenderView. // See BindingsPolicy for details. int enabled_bindings_;
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.cc b/content/browser/renderer_host/render_widget_host_view_aura.cc index c4f7a90..1661d36 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura.cc
@@ -366,8 +366,8 @@ in_shutdown_(false), in_bounds_changed_(false), is_fullscreen_(false), - popup_parent_host_view_(NULL), - popup_child_host_view_(NULL), + popup_parent_host_view_(nullptr), + popup_child_host_view_(nullptr), is_loading_(false), text_input_type_(ui::TEXT_INPUT_TYPE_NONE), text_input_mode_(ui::TEXT_INPUT_MODE_DEFAULT), @@ -375,17 +375,16 @@ can_compose_inline_(true), has_composition_text_(false), accept_return_character_(false), - last_swapped_software_frame_scale_factor_(1.f), - paint_canvas_(NULL), + begin_frame_source_(nullptr), + needs_begin_frames_(false), synthetic_move_sent_(false), cursor_visibility_state_in_renderer_(UNKNOWN), #if defined(OS_WIN) - legacy_render_widget_host_HWND_(NULL), + legacy_render_widget_host_HWND_(nullptr), legacy_window_destroyed_(false), #endif has_snapped_to_boundary_(false), is_guest_view_hack_(is_guest_view_hack), - begin_frame_observer_proxy_(this), set_focus_on_mouse_down_or_key_event_(false), device_scale_factor_(0.0f), disable_input_event_router_for_testing_(false), @@ -658,12 +657,29 @@ } void RenderWidgetHostViewAura::OnSetNeedsBeginFrames(bool needs_begin_frames) { - begin_frame_observer_proxy_.SetNeedsBeginFrames(needs_begin_frames); + if (needs_begin_frames_ == needs_begin_frames) + return; + + needs_begin_frames_ = needs_begin_frames; + if (begin_frame_source_) { + if (needs_begin_frames_) + begin_frame_source_->AddObserver(this); + else + begin_frame_source_->RemoveObserver(this); + } } -void RenderWidgetHostViewAura::SendBeginFrame(const cc::BeginFrameArgs& args) { +bool RenderWidgetHostViewAura::OnBeginFrameDerivedImpl( + const cc::BeginFrameArgs& args) { delegated_frame_host_->SetVSyncParameters(args.frame_time, args.interval); host_->Send(new ViewMsg_BeginFrame(host_->GetRoutingID(), args)); + return true; +} + +void RenderWidgetHostViewAura::OnBeginFrameSourcePausedChanged(bool paused) { + // Ignored for now. If the begin frame source is paused, the renderer + // doesn't need to be informed about it and will just not receive more + // begin frames. } void RenderWidgetHostViewAura::SetKeyboardFocus() { @@ -2650,8 +2666,6 @@ #endif delegated_frame_host_->SetCompositor(window_->GetHost()->compositor()); - if (window_->GetHost()->compositor()) - begin_frame_observer_proxy_.SetCompositor(window_->GetHost()->compositor()); } void RenderWidgetHostViewAura::RemovingFromRootWindow() { @@ -2664,7 +2678,6 @@ window_->GetHost()->RemoveObserver(this); delegated_frame_host_->ResetCompositor(); - begin_frame_observer_proxy_.ResetCompositor(); #if defined(OS_WIN) // Update the legacy window's parent temporarily to the desktop window. It @@ -2905,6 +2918,15 @@ host_->UpdateVSyncParameters(timebase, interval); } +void RenderWidgetHostViewAura::SetBeginFrameSource( + cc::BeginFrameSource* source) { + if (begin_frame_source_ && needs_begin_frames_) + begin_frame_source_->RemoveObserver(this); + begin_frame_source_ = source; + if (begin_frame_source_ && needs_begin_frames_) + begin_frame_source_->AddObserver(this); +} + void RenderWidgetHostViewAura::OnDidNavigateMainFrameToNewPage() { ui::GestureRecognizer::Get()->CancelActiveTouches(window_); }
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.h b/content/browser/renderer_host/render_widget_host_view_aura.h index a8e3d3c..65b18e05 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.h +++ b/content/browser/renderer_host/render_widget_host_view_aura.h
@@ -21,10 +21,10 @@ #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "build/build_config.h" +#include "cc/scheduler/begin_frame_source.h" #include "content/browser/accessibility/browser_accessibility_manager.h" #include "content/browser/compositor/image_transport_factory.h" #include "content/browser/compositor/owned_mailbox.h" -#include "content/browser/renderer_host/begin_frame_observer_proxy.h" #include "content/browser/renderer_host/delegated_frame_host.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/common/content_export.h" @@ -92,14 +92,14 @@ class CONTENT_EXPORT RenderWidgetHostViewAura : public RenderWidgetHostViewBase, public DelegatedFrameHostClient, - public BeginFrameObserverProxyClient, public ui::TextInputClient, public gfx::DisplayObserver, public aura::WindowTreeHostObserver, public aura::WindowDelegate, public aura::client::ActivationDelegate, public aura::client::FocusChangeObserver, - public aura::client::CursorClientObserver { + public aura::client::CursorClientObserver, + public cc::BeginFrameObserverBase { public: // When |is_guest_view_hack| is true, this view isn't really the view for // the |widget|, a RenderWidgetHostViewGuest is. @@ -460,9 +460,11 @@ void DelegatedFrameHostUpdateVSyncParameters( const base::TimeTicks& timebase, const base::TimeDelta& interval) override; + void SetBeginFrameSource(cc::BeginFrameSource* source) override; - // BeginFrameObserverProxyClient implementation. - void SendBeginFrame(const cc::BeginFrameArgs& args) override; + // cc::BeginFrameObserverBase implementation. + bool OnBeginFrameDerivedImpl(const cc::BeginFrameArgs& args) override; + void OnBeginFrameSourcePausedChanged(bool paused) override; // Detaches |this| from the input method object. void DetachFromInputMethod(); @@ -592,12 +594,9 @@ // Current tooltip text. base::string16 tooltip_; - // The size and scale of the last software compositing frame that was swapped. - gfx::Size last_swapped_software_frame_size_; - float last_swapped_software_frame_scale_factor_; - - // If non-NULL we're in OnPaint() and this is the supplied canvas. - gfx::Canvas* paint_canvas_; + // The begin frame source being observed. Null if none. + cc::BeginFrameSource* begin_frame_source_; + bool needs_begin_frames_; // Used to record the last position of the mouse. // While the mouse is locked, they store the last known position just as mouse @@ -677,8 +676,6 @@ // compositing surface and showing the disambiguation popup. gfx::Vector2dF disambiguation_scroll_offset_; - BeginFrameObserverProxy begin_frame_observer_proxy_; - // This flag when set ensures that we send over a notification to blink that // the current view has focus. Defaults to false. bool set_focus_on_mouse_down_or_key_event_;
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 c18f1e1a..f41407ec 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
@@ -2130,8 +2130,7 @@ for (size_t i = 0; i < (renderer_count - 1) * handles_per_frame; i++) { bitmap_client.ChildAllocatedSharedBitmap( - 1, base::SharedMemory::NULLHandle(), base::GetCurrentProcessHandle(), - cc::SharedBitmap::GenerateId()); + 1, base::SharedMemory::NULLHandle(), cc::SharedBitmap::GenerateId()); } // Hiding this last bitmap should evict all but two frames.
diff --git a/content/browser/renderer_host/render_widget_host_view_mac.h b/content/browser/renderer_host/render_widget_host_view_mac.h index bde64e7..67acd3d 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.h +++ b/content/browser/renderer_host/render_widget_host_view_mac.h
@@ -22,6 +22,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" +#include "cc/scheduler/begin_frame_source.h" #include "cc/surfaces/surface_id.h" #include "content/browser/renderer_host/browser_compositor_view_mac.h" #include "content/browser/renderer_host/delegated_frame_host.h" @@ -229,7 +230,8 @@ public DelegatedFrameHostClient, public ui::AcceleratedWidgetMacNSView, public IPC::Sender, - public gfx::DisplayObserver { + public gfx::DisplayObserver, + public cc::BeginFrameObserverBase { public: // The view will associate itself with the given widget. The native view must // be hooked up immediately to the view hierarchy, or else when it is @@ -365,6 +367,9 @@ // Forwards the mouse event to the renderer. void ForwardMouseEvent(const blink::WebMouseEvent& event); + // Called when RenderWidget wants to start BeginFrame scheduling or stop. + void OnSetNeedsBeginFrames(bool needs_begin_frames); + void KillSelf(); void SetTextInputActive(bool active); @@ -505,6 +510,11 @@ void DelegatedFrameHostUpdateVSyncParameters( const base::TimeTicks& timebase, const base::TimeDelta& interval) override; + void SetBeginFrameSource(cc::BeginFrameSource* source) override; + + // cc::BeginFrameObserverBase implementation. + bool OnBeginFrameDerivedImpl(const cc::BeginFrameArgs& args) override; + void OnBeginFrameSourcePausedChanged(bool paused) override; // AcceleratedWidgetMacNSView implementation. NSView* AcceleratedWidgetGetNSView() const override; @@ -592,6 +602,10 @@ base::TimeTicks vsync_timebase_; base::TimeDelta vsync_interval_; + // The begin frame source being observed. Null if none. + cc::BeginFrameSource* begin_frame_source_; + bool needs_begin_frames_; + // The current composition character range and its bounds. gfx::Range composition_range_; std::vector<gfx::Rect> composition_bounds_;
diff --git a/content/browser/renderer_host/render_widget_host_view_mac.mm b/content/browser/renderer_host/render_widget_host_view_mac.mm index ddb1a16..1c9ce1e 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.mm +++ b/content/browser/renderer_host/render_widget_host_view_mac.mm
@@ -482,6 +482,44 @@ render_widget_host_->UpdateVSyncParameters(timebase, interval); } +void RenderWidgetHostViewMac::SetBeginFrameSource( + cc::BeginFrameSource* source) { + if (begin_frame_source_ && needs_begin_frames_) + begin_frame_source_->RemoveObserver(this); + begin_frame_source_ = source; + if (begin_frame_source_ && needs_begin_frames_) + begin_frame_source_->AddObserver(this); +} + +//////////////////////////////////////////////////////////////////////////////// +// cc::BeginFrameSourceBase, public: + +void RenderWidgetHostViewMac::OnSetNeedsBeginFrames(bool needs_begin_frames) { + if (needs_begin_frames_ == needs_begin_frames) + return; + + needs_begin_frames_ = needs_begin_frames; + if (begin_frame_source_) { + if (needs_begin_frames_) + begin_frame_source_->AddObserver(this); + else + begin_frame_source_->RemoveObserver(this); + } +} + +bool RenderWidgetHostViewMac::OnBeginFrameDerivedImpl( + const cc::BeginFrameArgs& args) { + delegated_frame_host_->SetVSyncParameters(args.frame_time, args.interval); + render_widget_host_->Send( + new ViewMsg_BeginFrame(render_widget_host_->GetRoutingID(), args)); + return true; +} + +void RenderWidgetHostViewMac::OnBeginFrameSourcePausedChanged( + bool paused) { + // Nothing to do here. +} + //////////////////////////////////////////////////////////////////////////////// // AcceleratedWidgetMacNSView, public: @@ -527,7 +565,9 @@ allow_pause_for_resize_or_repaint_(true), is_guest_view_hack_(is_guest_view_hack), wheel_gestures_enabled_(UseGestureBasedWheelScrolling()), - fullscreen_parent_host_view_(NULL), + fullscreen_parent_host_view_(nullptr), + begin_frame_source_(nullptr), + needs_begin_frames_(false), weak_factory_(this) { // |cocoa_view_| owns us and we will be deleted when |cocoa_view_| // goes away. Since we autorelease it, our caller must put @@ -687,6 +727,8 @@ IPC_BEGIN_MESSAGE_MAP(RenderWidgetHostViewMac, message) IPC_MESSAGE_HANDLER(ViewMsg_GetRenderedTextCompleted, OnGetRenderedTextCompleted) + IPC_MESSAGE_HANDLER(ViewHostMsg_SetNeedsBeginFrames, + OnSetNeedsBeginFrames) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled;
diff --git a/content/browser/service_worker/foreign_fetch_request_handler.cc b/content/browser/service_worker/foreign_fetch_request_handler.cc index ee9aa4b..2034266 100644 --- a/content/browser/service_worker/foreign_fetch_request_handler.cc +++ b/content/browser/service_worker/foreign_fetch_request_handler.cc
@@ -67,6 +67,11 @@ return; } + if (request->initiator().IsSameOriginWith(url::Origin(request->url()))) + return; + if (ServiceWorkerUtils::IsMainResourceType(resource_type)) + return; + // Any more precise checks to see if the request should be intercepted are // asynchronous, so just create our handler in all cases. std::unique_ptr<ForeignFetchRequestHandler> handler(
diff --git a/content/browser/service_worker/service_worker_context_core.cc b/content/browser/service_worker/service_worker_context_core.cc index 56bae6d..25e0f11 100644 --- a/content/browser/service_worker/service_worker_context_core.cc +++ b/content/browser/service_worker/service_worker_context_core.cc
@@ -694,6 +694,11 @@ return; auto it = failure_counts_.find(version_id); + if (it != failure_counts_.end()) { + ServiceWorkerMetrics::RecordStartStatusAfterFailure(it->second.count, + status); + } + if (status == SERVICE_WORKER_OK) { if (it != failure_counts_.end()) failure_counts_.erase(it); @@ -701,11 +706,17 @@ } if (it != failure_counts_.end()) { - DCHECK_GT(it->second, 0); - if (it->second < std::numeric_limits<int>::max()) - ++it->second; + FailureInfo& info = it->second; + DCHECK_GT(info.count, 0); + if (info.count < std::numeric_limits<int>::max()) { + ++info.count; + info.last_failure = status; + } } else { - failure_counts_[version_id] = 1; + FailureInfo info; + info.count = 1; + info.last_failure = status; + failure_counts_[version_id] = info; } } @@ -713,7 +724,7 @@ auto it = failure_counts_.find(version_id); if (it == failure_counts_.end()) return 0; - return it->second; + return it->second.count; } void ServiceWorkerContextCore::OnRunningStateChanged(
diff --git a/content/browser/service_worker/service_worker_context_core.h b/content/browser/service_worker/service_worker_context_core.h index a4b994f..71dcfe8d 100644 --- a/content/browser/service_worker/service_worker_context_core.h +++ b/content/browser/service_worker/service_worker_context_core.h
@@ -292,9 +292,17 @@ } private: + friend class ServiceWorkerContextCoreTest; + FRIEND_TEST_ALL_PREFIXES(ServiceWorkerContextCoreTest, FailureInfo); + typedef std::map<int64_t, ServiceWorkerRegistration*> RegistrationsMap; typedef std::map<int64_t, ServiceWorkerVersion*> VersionMap; + struct FailureInfo { + int count; + ServiceWorkerStatusCode last_failure; + }; + ProviderMap* GetProviderMapForProcess(int process_id) { return providers_->Lookup(process_id); } @@ -342,7 +350,8 @@ std::map<int64_t, ServiceWorkerRegistration*> live_registrations_; std::map<int64_t, ServiceWorkerVersion*> live_versions_; std::map<int64_t, scoped_refptr<ServiceWorkerVersion>> protected_versions_; - std::map<int64_t /* version_id */, int /* count */> failure_counts_; + + std::map<int64_t /* version_id */, FailureInfo> failure_counts_; // PlzNavigate // Map of ServiceWorkerNavigationHandleCores used for navigation requests.
diff --git a/content/browser/service_worker/service_worker_context_core_unittest.cc b/content/browser/service_worker/service_worker_context_core_unittest.cc new file mode 100644 index 0000000..d1a0abb --- /dev/null +++ b/content/browser/service_worker/service_worker_context_core_unittest.cc
@@ -0,0 +1,59 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/service_worker/service_worker_context_core.h" + +#include "content/browser/service_worker/embedded_worker_test_helper.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/test_utils.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace content { + +class ServiceWorkerContextCoreTest : public testing::Test { + protected: + ServiceWorkerContextCoreTest() + : thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP) {} + + void SetUp() override { + helper_.reset(new EmbeddedWorkerTestHelper(base::FilePath())); + } + + void TearDown() override { helper_.reset(); } + + ServiceWorkerContextCore* context() { return helper_->context(); } + + TestBrowserThreadBundle thread_bundle_; + scoped_ptr<EmbeddedWorkerTestHelper> helper_; + + private: + DISALLOW_COPY_AND_ASSIGN(ServiceWorkerContextCoreTest); +}; + +TEST_F(ServiceWorkerContextCoreTest, FailureInfo) { + const int64_t kVersionId = 55; // dummy value + + EXPECT_EQ(0, context()->GetVersionFailureCount(kVersionId)); + context()->UpdateVersionFailureCount(kVersionId, SERVICE_WORKER_OK); + context()->UpdateVersionFailureCount(kVersionId, + SERVICE_WORKER_ERROR_DISALLOWED); + EXPECT_EQ(0, context()->GetVersionFailureCount(kVersionId)); + + context()->UpdateVersionFailureCount(kVersionId, + SERVICE_WORKER_ERROR_NETWORK); + EXPECT_EQ(1, context()->GetVersionFailureCount(kVersionId)); + EXPECT_EQ(SERVICE_WORKER_ERROR_NETWORK, + context()->failure_counts_[kVersionId].last_failure); + + context()->UpdateVersionFailureCount(kVersionId, SERVICE_WORKER_ERROR_ABORT); + EXPECT_EQ(2, context()->GetVersionFailureCount(kVersionId)); + EXPECT_EQ(SERVICE_WORKER_ERROR_ABORT, + context()->failure_counts_[kVersionId].last_failure); + + context()->UpdateVersionFailureCount(kVersionId, SERVICE_WORKER_OK); + EXPECT_EQ(0, context()->GetVersionFailureCount(kVersionId)); + EXPECT_FALSE(ContainsKey(context()->failure_counts_, kVersionId)); +} + +} // namespace content
diff --git a/content/browser/service_worker/service_worker_metrics.cc b/content/browser/service_worker/service_worker_metrics.cc index 3fdb74f..f8cc4daa 100644 --- a/content/browser/service_worker/service_worker_metrics.cc +++ b/content/browser/service_worker/service_worker_metrics.cc
@@ -4,6 +4,9 @@ #include "content/browser/service_worker/service_worker_metrics.h" +#include <limits> +#include <string> + #include "base/metrics/histogram_macros.h" #include "base/metrics/sparse_histogram.h" #include "base/strings/string_util.h" @@ -477,4 +480,29 @@ return StartSituation::EXISTING_PROCESS; } +void ServiceWorkerMetrics::RecordStartStatusAfterFailure( + int failure_count, + ServiceWorkerStatusCode status) { + DCHECK_GT(failure_count, 0); + + if (status == SERVICE_WORKER_OK) { + UMA_HISTOGRAM_COUNTS_1000("ServiceWorker.StartWorker.FailureStreakEnded", + failure_count); + } else if (failure_count < std::numeric_limits<int>::max()) { + UMA_HISTOGRAM_COUNTS_1000("ServiceWorker.StartWorker.FailureStreak", + failure_count + 1); + } + + if (failure_count == 1) { + UMA_HISTOGRAM_ENUMERATION("ServiceWorker.StartWorker.AfterFailureStreak_1", + status, SERVICE_WORKER_ERROR_MAX_VALUE); + } else if (failure_count == 2) { + UMA_HISTOGRAM_ENUMERATION("ServiceWorker.StartWorker.AfterFailureStreak_2", + status, SERVICE_WORKER_ERROR_MAX_VALUE); + } else if (failure_count == 3) { + UMA_HISTOGRAM_ENUMERATION("ServiceWorker.StartWorker.AfterFailureStreak_3", + status, SERVICE_WORKER_ERROR_MAX_VALUE); + } +} + } // namespace content
diff --git a/content/browser/service_worker/service_worker_metrics.h b/content/browser/service_worker/service_worker_metrics.h index e14d1ad..b062223 100644 --- a/content/browser/service_worker/service_worker_metrics.h +++ b/content/browser/service_worker/service_worker_metrics.h
@@ -215,6 +215,11 @@ static StartSituation GetStartSituation(bool is_browser_startup_complete, bool is_new_process); + // Records the result of a start attempt that occurred after the worker had + // failed |failure_count| consecutive times. + static void RecordStartStatusAfterFailure(int failure_count, + ServiceWorkerStatusCode status); + private: DISALLOW_IMPLICIT_CONSTRUCTORS(ServiceWorkerMetrics); };
diff --git a/content/browser/service_worker/service_worker_version.cc b/content/browser/service_worker/service_worker_version.cc index 5cb4d5a82..92f6e10 100644 --- a/content/browser/service_worker/service_worker_version.cc +++ b/content/browser/service_worker/service_worker_version.cc
@@ -1542,7 +1542,7 @@ base::TimeTicks start_time = start_time_; ClearTick(&start_time_); - if (context_) + if (context_ && IsInstalled(prestart_status)) context_->UpdateVersionFailureCount(version_id_, status); ServiceWorkerMetrics::RecordStartWorkerStatus(status, purpose,
diff --git a/content/browser/service_worker/service_worker_version_unittest.cc b/content/browser/service_worker/service_worker_version_unittest.cc index 1f74c047..8ffa18ee 100644 --- a/content/browser/service_worker/service_worker_version_unittest.cc +++ b/content/browser/service_worker/service_worker_version_unittest.cc
@@ -1289,6 +1289,7 @@ helper_->new_render_process_id()); ServiceWorkerContextCore* context = helper_->context(); int64_t id = version_->version_id(); + version_->SetStatus(ServiceWorkerVersion::ACTIVATED); // Start once. It should choose the "existing process". set_start_mode(MessageReceiverDisallowStart::StartMode::SUCCEED);
diff --git a/content/browser/site_per_process_browsertest.cc b/content/browser/site_per_process_browsertest.cc index bd1d088..80c4d16 100644 --- a/content/browser/site_per_process_browsertest.cc +++ b/content/browser/site_per_process_browsertest.cc
@@ -31,7 +31,6 @@ #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/renderer_host/render_widget_host_input_event_router.h" #include "content/browser/renderer_host/render_widget_host_view_aura.h" -#include "content/browser/web_contents/web_contents_impl.h" #include "content/common/frame_messages.h" #include "content/common/input/synthetic_tap_gesture_params.h" #include "content/common/view_messages.h" @@ -47,7 +46,6 @@ #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/test_navigation_observer.h" #include "content/public/test/test_utils.h" -#include "content/shell/browser/shell.h" #include "content/test/content_browser_test_utils_internal.h" #include "content/test/test_frame_navigation_observer.h" #include "ipc/ipc_security_test_util.h" @@ -632,9 +630,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = - static_cast<WebContentsImpl*>(shell()->web_contents())-> - GetFrameTree()->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); @@ -648,8 +644,7 @@ // There should be only one RenderWidgetHost when there are no // cross-process iframes. std::set<RenderWidgetHostView*> views_set = - static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetRenderWidgetHostViewsInTree(); + web_contents()->GetRenderWidgetHostViewsInTree(); EXPECT_EQ(1U, views_set.size()); } @@ -682,8 +677,7 @@ // There should be now two RenderWidgetHosts, one for each process // rendering a frame. std::set<RenderWidgetHostView*> views_set = - static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetRenderWidgetHostViewsInTree(); + web_contents()->GetRenderWidgetHostViewsInTree(); EXPECT_EQ(2U, views_set.size()); } RenderFrameProxyHost* proxy_to_parent = @@ -730,8 +724,7 @@ EXPECT_NE(rph, child->current_frame_host()->GetProcess()); { std::set<RenderWidgetHostView*> views_set = - static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetRenderWidgetHostViewsInTree(); + web_contents()->GetRenderWidgetHostViewsInTree(); EXPECT_EQ(2U, views_set.size()); } EXPECT_EQ(proxy_to_parent, child->render_manager()->GetProxyToParent()); @@ -922,9 +915,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); FrameTreeNode* parent_iframe_node = root->child_at(0); @@ -950,8 +941,7 @@ nested_iframe_node->current_frame_host()->GetRenderWidgetHost()); RenderWidgetHostInputEventRouter* router = - static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetInputEventRouter(); + web_contents()->GetInputEventRouter(); RenderWidgetHostViewBase* root_view = static_cast<RenderWidgetHostViewBase*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); @@ -1003,9 +993,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); FrameTreeNode* child_node = root->child_at(0); @@ -1021,8 +1009,7 @@ child_node->current_frame_host()->GetRenderWidgetHost()); RenderWidgetHostInputEventRouter* router = - static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetInputEventRouter(); + web_contents()->GetInputEventRouter(); RenderWidgetHostViewBase* root_view = static_cast<RenderWidgetHostViewBase*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); @@ -1065,9 +1052,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); FrameTreeNode* child_node = root->child_at(0); @@ -1098,9 +1083,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = - static_cast<WebContentsImpl*>(shell()->web_contents())-> - GetFrameTree()->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); @@ -1157,9 +1140,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = - static_cast<WebContentsImpl*>(shell()->web_contents())-> - GetFrameTree()->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); @@ -1221,9 +1202,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = - static_cast<WebContentsImpl*>(shell()->web_contents())-> - GetFrameTree()->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); @@ -1290,9 +1269,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = - static_cast<WebContentsImpl*>(shell()->web_contents())-> - GetFrameTree()->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); @@ -1398,9 +1375,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = - static_cast<WebContentsImpl*>(shell()->web_contents())-> - GetFrameTree()->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); ASSERT_EQ(2U, root->child_count()); @@ -1449,9 +1424,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = - static_cast<WebContentsImpl*>(shell()->web_contents())-> - GetFrameTree()->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); ASSERT_EQ(2U, root->child_count()); @@ -1536,9 +1509,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Load same-site page into iframe. { @@ -1592,9 +1563,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); FrameTreeNode* child = root->child_at(0); GURL url_a = child->current_url(); @@ -1696,9 +1665,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); EXPECT_EQ( @@ -1761,9 +1728,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ( " Site A ------------ proxies for B\n" @@ -1838,9 +1803,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); SiteInstance* site_instance_a = root->current_frame_host()->GetSiteInstance(); // Open a popup and navigate it cross-process to b.com. @@ -1926,9 +1889,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = - static_cast<WebContentsImpl*>(shell()->web_contents())-> - GetFrameTree()->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(2U, root->child_count()); GURL site_b_url( @@ -2000,9 +1961,7 @@ NavigateToURL(shell(), main_url); // Check the subframe process. - FrameTreeNode* root = - static_cast<WebContentsImpl*>(shell()->web_contents())-> - GetFrameTree()->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" @@ -2063,9 +2022,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); // Make sure the frame starts out at the correct cross-site URL. @@ -2308,9 +2265,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = - static_cast<WebContentsImpl*>(shell()->web_contents())-> - GetFrameTree()->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_TRUE(root->child_at(1) != NULL); EXPECT_EQ(2U, root->child_at(1)->child_count()); @@ -2456,9 +2411,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1u, root->child_count()); EXPECT_EQ( @@ -2524,9 +2477,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1u, root->child_count()); EXPECT_EQ( @@ -2613,9 +2564,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ( " Site A ------------ proxies for B C\n" @@ -2704,9 +2653,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); @@ -2804,9 +2751,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); ASSERT_EQ(2U, root->child_count()); @@ -2928,9 +2873,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); ASSERT_EQ(2U, root->child_count()); @@ -2998,9 +2941,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); ASSERT_EQ(1U, root->child_count()); @@ -3079,9 +3020,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); EXPECT_EQ( @@ -3160,9 +3099,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); @@ -3193,9 +3130,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); // Load cross-site page into iframe. @@ -3252,9 +3187,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); EXPECT_EQ( @@ -3305,9 +3238,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = - static_cast<WebContentsImpl*>(shell()->web_contents())-> - GetFrameTree()->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); @@ -3341,9 +3272,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); // Make sure the first frame is out of process. @@ -3377,9 +3306,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); FrameTreeNode* node2 = root->child_at(0); FrameTreeNode* node3 = root->child_at(1); @@ -3424,9 +3351,7 @@ } // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Load another cross-site page into the iframe and check that the load event // is fired. @@ -3449,9 +3374,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(2U, root->child_count()); @@ -3497,9 +3420,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(2U, root->child_count()); @@ -3608,9 +3529,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(3U, root->child_count()); FrameTreeNode* child0 = root->child_at(0); FrameTreeNode* child1 = root->child_at(1); @@ -3680,9 +3599,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); @@ -3741,9 +3658,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Navigate first child cross-site. GURL frame_url(embedded_test_server()->GetURL("b.com", "/title1.html")); @@ -3845,9 +3760,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Navigate first child cross-site. GURL frame_url(embedded_test_server()->GetURL("b.com", "/title1.html")); @@ -3898,9 +3811,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Open a same-site popup from the main frame. GURL a_com_url(embedded_test_server()->GetURL("a.com", "/title3.html")); @@ -3958,9 +3869,7 @@ "foo.com", "/frame_tree/page_with_two_frames.html"); EXPECT_TRUE(NavigateToURL(shell(), main_url)); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ(2U, root->child_count()); // From the top frame, open a popup and navigate it to a cross-site page with @@ -4033,9 +3942,7 @@ GURL main_url = embedded_test_server()->GetURL("a.com", "/post_message.html"); EXPECT_TRUE(NavigateToURL(shell(), main_url)); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Open a popup with a cross-site page that has a subframe. GURL popup_url(embedded_test_server()->GetURL( @@ -4080,9 +3987,7 @@ "foo.com", "/frame_tree/page_with_two_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ( " Site A ------------ proxies for B\n" " |--Site B ------- proxies for A\n" @@ -4147,9 +4052,7 @@ embedded_test_server()->GetURL("foo.com", "/post_message.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Open a popup with a cross-site page that has two subframes. GURL popup_url(embedded_test_server()->GetURL( @@ -4226,9 +4129,7 @@ GURL a_url(embedded_test_server()->GetURL("a.com", "/title1.html")); NavigateToURL(shell(), a_url); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); RenderFrameHostImpl* rfh = root->current_frame_host(); RenderViewHostImpl* rvh = rfh->render_view_host(); int rvh_routing_id = rvh->GetRoutingID(); @@ -4320,9 +4221,7 @@ embedded_test_server()->GetURL("a.com", "/page_with_input_field.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ( " Site A ------------ proxies for B\n" @@ -4382,9 +4281,7 @@ "a.com", "/cross_site_iframe_factory.html?a(b(c))")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ( " Site A ------------ proxies for B C\n" @@ -4456,9 +4353,7 @@ "a.com", "/cross_site_iframe_factory.html?a(b,c)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_EQ( " Site A ------------ proxies for B C\n" @@ -4595,9 +4490,7 @@ "/frame_tree/page_with_positioned_frame.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); FrameTreeNode* child_node = root->child_at(0); EXPECT_NE(shell()->web_contents()->GetSiteInstance(), @@ -4616,9 +4509,8 @@ root->child_at(0)->current_frame_host()->GetRenderWidgetHost(); RenderWidgetHostViewBase* root_view = static_cast<RenderWidgetHostViewBase*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); - static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetInputEventRouter() - ->RouteMouseEvent(root_view, &mouse_event); + web_contents()->GetInputEventRouter()->RouteMouseEvent(root_view, + &mouse_event); // CursorMessageFilter::Wait() implicitly tests whether we receive a // ViewHostMsg_SetCursor message from the renderer process, because it does @@ -4661,9 +4553,8 @@ "/frame_tree/page_with_positioned_nested_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); - WebContentsImpl* web_contents = - static_cast<WebContentsImpl*>(shell()->web_contents()); - FrameTreeNode* root = web_contents->GetFrameTree()->root(); + WebContentsImpl* contents = web_contents(); + FrameTreeNode* root = contents->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); GURL frame_url( @@ -4681,7 +4572,7 @@ // Simulate touch event to sub-frame. gfx::Point child_center(150, 150); auto rwhv = static_cast<RenderWidgetHostViewAura*>( - web_contents->GetRenderWidgetHostView()); + contents->GetRenderWidgetHostView()); ui::TouchEvent touch_event(ui::ET_TOUCH_PRESSED, child_center, 0, 0, ui::EventTimeForNow(), 30.f, 30.f, 0.f, 0.f); rwhv->OnTouchEvent(&touch_event); @@ -4717,9 +4608,7 @@ "/frame_tree/page_with_positioned_nested_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); - WebContentsImpl* web_contents = - static_cast<WebContentsImpl*>(shell()->web_contents()); - FrameTreeNode* root = web_contents->GetFrameTree()->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); GURL frame_url( @@ -4852,9 +4741,8 @@ "/frame_tree/page_with_positioned_nested_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); - WebContentsImpl* web_contents = - static_cast<WebContentsImpl*>(shell()->web_contents()); - FrameTreeNode* root = web_contents->GetFrameTree()->root(); + WebContentsImpl* contents = web_contents(); + FrameTreeNode* root = contents->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); GURL frame_url( @@ -4873,10 +4761,9 @@ // All touches & gestures are sent to the main frame's view, and should be // routed appropriately from there. auto rwhv_parent = static_cast<RenderWidgetHostViewBase*>( - web_contents->GetRenderWidgetHostView()); + contents->GetRenderWidgetHostView()); - RenderWidgetHostInputEventRouter* router = - web_contents->GetInputEventRouter(); + RenderWidgetHostInputEventRouter* router = contents->GetInputEventRouter(); EXPECT_TRUE(router->gesture_target_queue_.empty()); EXPECT_EQ(nullptr, router->gesture_target_); @@ -5139,16 +5026,14 @@ embedded_test_server()->GetURL("/cross_site_iframe_factory.html?a(a)")); NavigateToURL(shell(), main_url); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); #if !defined(OS_MACOSX) // Unused variable on Mac. RenderWidgetHostViewBase* rwhv_root = static_cast<RenderWidgetHostViewBase*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); #endif - static_cast<WebContentsImpl*>(shell()->web_contents())->SendScreenRects(); + web_contents()->SendScreenRects(); content::TestNavigationObserver navigation_observer(shell()->web_contents()); FrameTreeNode* child_node = root->child_at(0); @@ -5210,16 +5095,14 @@ "/cross_site_iframe_factory.html?a(b(c))")); NavigateToURL(shell(), main_url); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); #if !defined(OS_MACOSX) // Undefined variable on Mac. RenderWidgetHostViewBase* rwhv_root = static_cast<RenderWidgetHostViewBase*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); #endif - static_cast<WebContentsImpl*>(shell()->web_contents())->SendScreenRects(); + web_contents()->SendScreenRects(); // For clarity, we are labeling the frame tree nodes as: // - root_node @@ -5496,10 +5379,7 @@ NavigateToURL(shell(), main_url); // Capture the FrameTreeNode this test will be navigating. - FrameTreeNode* node = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root() - ->child_at(0); + FrameTreeNode* node = web_contents()->GetFrameTree()->root()->child_at(0); EXPECT_TRUE(node); EXPECT_NE(node->current_frame_host()->GetSiteInstance(), node->parent()->current_frame_host()->GetSiteInstance()); @@ -5573,12 +5453,11 @@ "a.com", "/cross_site_iframe_factory.html?a(b,b)")); NavigateToURL(shell(), main_url); - WebContentsImpl* web_contents = - static_cast<WebContentsImpl*>(shell()->web_contents()); - EXPECT_EQ(2U, web_contents->GetFrameTree()->root()->child_count()); + WebContentsImpl* contents = web_contents(); + EXPECT_EQ(2U, contents->GetFrameTree()->root()->child_count()); // Capture the FrameTreeNode this test will be navigating. - FrameTreeNode* node = web_contents->GetFrameTree()->root()->child_at(0); + FrameTreeNode* node = contents->GetFrameTree()->root()->child_at(0); EXPECT_TRUE(node); EXPECT_NE(node->current_frame_host()->GetSiteInstance(), node->parent()->current_frame_host()->GetSiteInstance()); @@ -5598,10 +5477,10 @@ // Have the parent frame remove the child frame from its DOM. This should // result in the child RenderFrame being deleted in the remote process. - EXPECT_TRUE(ExecuteScript(web_contents, + EXPECT_TRUE(ExecuteScript(contents, "document.body.removeChild(" "document.querySelectorAll('iframe')[0])")); - EXPECT_EQ(1U, web_contents->GetFrameTree()->root()->child_count()); + EXPECT_EQ(1U, contents->GetFrameTree()->root()->child_count()); { FrameMsg_NewFrame_Params params; @@ -5622,9 +5501,8 @@ // RenderFrame will be properly created and there will be no crash. // Therefore, navigate the remaining subframe to completely different site, // which will cause the original process to exit cleanly. - NavigateFrameToURL( - web_contents->GetFrameTree()->root()->child_at(0), - embedded_test_server()->GetURL("d.com", "/title3.html")); + NavigateFrameToURL(contents->GetFrameTree()->root()->child_at(0), + embedded_test_server()->GetURL("d.com", "/title3.html")); watcher.Wait(); EXPECT_TRUE(watcher.did_exit_normally()); } @@ -5638,9 +5516,7 @@ GURL cross_site_url = embedded_test_server()->GetURL("oopif.com", "/title1.html"); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); TestNavigationObserver observer(shell()->web_contents()); @@ -5678,9 +5554,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Set sandbox flags for child frame. EXPECT_TRUE(ExecuteScript( @@ -5733,9 +5607,7 @@ NavigateToURL(shell(), main_url); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Set sandbox flags for child frame. EXPECT_TRUE(ExecuteScript( @@ -5785,9 +5657,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Set sandbox flags for child frame. EXPECT_TRUE(ExecuteScript(root->current_frame_host(), @@ -5856,9 +5726,7 @@ EXPECT_TRUE(NavigateToURL(shell(), main_url)); // It is safe to obtain the root frame tree node here, as it doesn't change. - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Set sandbox flags for child frame, specifying that popups opened from it // should not be sandboxed. @@ -5933,9 +5801,7 @@ // When the subframe navigates, the WebContents should still be marked // as having displayed insecure content. GURL navigate_url(https_server.GetURL("/title1.html")); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); NavigateFrameToURL(root->child_at(0), navigate_url); EXPECT_TRUE(shell()->web_contents()->DisplayedInsecureContent()); @@ -5961,9 +5827,7 @@ EXPECT_TRUE(NavigateToURL(shell(), iframe_url_with_strict_blocking)); EXPECT_FALSE(shell()->web_contents()->DisplayedInsecureContent()); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); EXPECT_TRUE(root->current_replication_state() .should_enforce_strict_mixed_content_checking); EXPECT_TRUE(root->child_at(0) @@ -6002,9 +5866,7 @@ GURL iframe_url( https_server.GetURL("/mixed-content/basic-active-in-iframe.html")); EXPECT_TRUE(NavigateToURL(shell(), iframe_url)); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); ASSERT_EQ(1U, root->child_count()); FrameTreeNode* mixed_child = root->child_at(0)->child_at(0); ASSERT_TRUE(mixed_child); @@ -6020,9 +5882,7 @@ "a.com", "/cross_site_iframe_factory.html?a(b)")); NavigateToURL(shell(), main_url); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); RenderWidgetHost* root_render_widget_host = root->current_frame_host()->GetRenderWidgetHost(); @@ -6052,9 +5912,7 @@ "a.com", "/cross_site_iframe_factory.html?a(a)")); NavigateToURL(shell(), main_url); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); // Add a load event handler for the iframe element. EXPECT_TRUE(ExecuteScript(shell()->web_contents(), @@ -6122,9 +5980,7 @@ "a.com", "/cross_site_iframe_factory.html?a(b)")); NavigateToURL(shell(), main_url); - FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) - ->GetFrameTree() - ->root(); + FrameTreeNode* root = web_contents()->GetFrameTree()->root(); FrameTreeNode* child = root->child_at(0); const char* properties[] = {"screenX", "screenY", "outerWidth", @@ -6208,8 +6064,7 @@ "a.com", "/cross_site_iframe_factory.html?a(b)")); EXPECT_TRUE(NavigateToURL(shell(), main_url)); - WebContentsImpl* contents = - static_cast<WebContentsImpl*>(shell()->web_contents()); + WebContentsImpl* contents = web_contents(); FrameTreeNode* root = contents->GetFrameTree()->root(); EXPECT_EQ(1U, root->child_count());
diff --git a/content/browser/site_per_process_browsertest.h b/content/browser/site_per_process_browsertest.h index 16db097..32861ec 100644 --- a/content/browser/site_per_process_browsertest.h +++ b/content/browser/site_per_process_browsertest.h
@@ -7,14 +7,15 @@ #include <string> +#include "content/browser/web_contents/web_contents_impl.h" #include "content/public/test/content_browser_test.h" +#include "content/shell/browser/shell.h" #include "content/test/content_browser_test_utils_internal.h" #include "url/gurl.h" namespace content { class FrameTreeNode; -class Shell; class SitePerProcessBrowserTest : public ContentBrowserTest { public: @@ -26,6 +27,10 @@ void SetUpCommandLine(base::CommandLine* command_line) override; void SetUpOnMainThread() override; + WebContentsImpl* web_contents() const { + return static_cast<WebContentsImpl*>(shell()->web_contents()); + } + private: FrameTreeVisualizer visualizer_; };
diff --git a/content/browser/tracing/tracing_controller_impl.h b/content/browser/tracing/tracing_controller_impl.h index eb7761e..2f344b4b 100644 --- a/content/browser/tracing/tracing_controller_impl.h +++ b/content/browser/tracing/tracing_controller_impl.h
@@ -191,7 +191,6 @@ base::trace_event::MemoryDumpCallback pending_memory_dump_callback_; std::vector<base::trace_event::TracingAgent*> additional_tracing_agents_; - int clock_sync_id_; int pending_clock_sync_ack_count_; base::OneShotTimer clock_sync_timer_;
diff --git a/content/browser/utility_process_host_impl.cc b/content/browser/utility_process_host_impl.cc index d5924961..c025a4a 100644 --- a/content/browser/utility_process_host_impl.cc +++ b/content/browser/utility_process_host_impl.cc
@@ -259,8 +259,6 @@ return false; } - std::string mojo_token = mojo_application_host_->InitWithToken(); - if (RenderProcessHost::run_renderer_in_process()) { DCHECK(g_utility_main_thread_factory); // See comment in RenderProcessHostImpl::Init() for the background on why we @@ -269,7 +267,7 @@ g_utility_main_thread_factory(InProcessChildThreadParams( channel_id, BrowserThread::UnsafeGetMessageLoopForThread( BrowserThread::IO)->task_runner(), - mojo::MessagePipeHandle(), mojo_token))); + std::string(), mojo_application_host_->GetToken()))); in_process_thread_->Start(); } else { const base::CommandLine& browser_command_line = @@ -348,7 +346,7 @@ #endif cmd_line->AppendSwitchASCII(switches::kMojoApplicationChannelToken, - mojo_token); + mojo_application_host_->GetToken()); process_->Launch( new UtilitySandboxedProcessLauncherDelegate(exposed_dir_,
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index a62145ec..b88c94f 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -4218,7 +4218,6 @@ details.reset(new LoadNotificationDetails( entry->GetVirtualURL(), - entry->GetTransitionType(), elapsed, &controller_, controller_.GetCurrentEntryIndex()));
diff --git a/content/browser/web_contents/web_contents_view_aura.cc b/content/browser/web_contents/web_contents_view_aura.cc index c11eefb0..c710eaf6 100644 --- a/content/browser/web_contents/web_contents_view_aura.cc +++ b/content/browser/web_contents/web_contents_view_aura.cc
@@ -47,6 +47,7 @@ #include "net/base/filename_util.h" #include "third_party/WebKit/public/web/WebInputEvent.h" #include "ui/aura/client/aura_constants.h" +#include "ui/aura/client/screen_position_client.h" #include "ui/aura/client/window_tree_client.h" #include "ui/aura/env.h" #include "ui/aura/window.h" @@ -533,14 +534,17 @@ } void WebContentsViewAura::EndDrag(blink::WebDragOperationsMask ops) { - aura::Window* root_window = GetNativeView()->GetRootWindow(); - gfx::Point screen_loc = gfx::Screen::GetScreen()->GetCursorScreenPoint(); - gfx::Point client_loc = screen_loc; - RenderViewHost* rvh = web_contents_->GetRenderViewHost(); - aura::Window* window = rvh->GetWidget()->GetView()->GetNativeView(); - aura::Window::ConvertPointToTarget(root_window, window, &client_loc); if (!web_contents_) return; + + aura::Window* window = GetContentNativeView(); + gfx::Point screen_loc = gfx::Screen::GetScreen()->GetCursorScreenPoint(); + gfx::Point client_loc = screen_loc; + aura::client::ScreenPositionClient* screen_position_client = + aura::client::GetScreenPositionClient(window->GetRootWindow()); + if (screen_position_client) + screen_position_client->ConvertPointFromScreen(window, &client_loc); + web_contents_->DragSourceEndedAt(client_loc.x(), client_loc.y(), screen_loc.x(), screen_loc.y(), ops); }
diff --git a/content/browser/zygote_host/zygote_communication_linux.h b/content/browser/zygote_host/zygote_communication_linux.h index 5bb80962..2766618 100644 --- a/content/browser/zygote_host/zygote_communication_linux.h +++ b/content/browser/zygote_host/zygote_communication_linux.h
@@ -83,7 +83,6 @@ base::Lock child_tracking_lock_; int sandbox_status_; bool have_read_sandbox_status_word_; - bool use_suid_sandbox_for_adj_oom_score_; // Set to true when the zygote is initialized successfully. bool init_; };
diff --git a/content/child/BUILD.gn b/content/child/BUILD.gn index 45cb05b..21f73a5 100644 --- a/content/child/BUILD.gn +++ b/content/child/BUILD.gn
@@ -12,6 +12,7 @@ # (i.e. not content/browser or content/common) and only if they're inside the # content component (i.e. not content/test or content/shell). visibility = [ + ":*", "//content/gpu/*", "//content/ppapi_plugin/*", "//content/public/child:child_sources", @@ -85,3 +86,13 @@ "//build/config/compiler:no_size_t_to_int_warning", ] } + +# See comment at the top of //content/BUILD.gn for how this works. +group("for_content_tests") { + visibility = [ "//content/test/*" ] + if (!is_component_build) { + public_deps = [ + ":child", + ] + } +}
diff --git a/content/child/blink_platform_impl.cc b/content/child/blink_platform_impl.cc index c006142..fb220183a 100644 --- a/content/child/blink_platform_impl.cc +++ b/content/child/blink_platform_impl.cc
@@ -733,6 +733,9 @@ {"viewportAndroid.css", IDR_UASTYLE_VIEWPORT_ANDROID_CSS, ui::SCALE_FACTOR_NONE}, + {"viewportTelevision.css", + IDR_UASTYLE_VIEWPORT_TELEVISION_CSS, + ui::SCALE_FACTOR_NONE}, {"InspectorOverlayPage.html", IDR_INSPECTOR_OVERLAY_PAGE_HTML, ui::SCALE_FACTOR_NONE},
diff --git a/content/child/child_thread_impl.cc b/content/child/child_thread_impl.cc index 173fb08..d3f45dfc 100644 --- a/content/child/child_thread_impl.cc +++ b/content/child/child_thread_impl.cc
@@ -236,7 +236,10 @@ platform_channel.reset(mojo::edk::PlatformHandle( base::GlobalDescriptors::GetInstance()->Get(kMojoIPCChannel))); #endif - CHECK(platform_channel.is_valid()); + // Mojo isn't supported on all child process types. + // TODO(crbug.com/604282): Support Mojo in the remaining processes. + if (!platform_channel.is_valid()) + return; mojo::edk::SetParentPipeHandle(std::move(platform_channel)); } @@ -265,7 +268,7 @@ const InProcessChildThreadParams& params) { options_.browser_process_io_runner = params.io_runner(); options_.channel_name = params.channel_name(); - options_.in_process_message_pipe_handle = params.handle(); + options_.in_process_ipc_token = params.ipc_token(); options_.in_process_application_token = params.application_token(); return *this; } @@ -335,15 +338,18 @@ } void ChildThreadImpl::ConnectChannel(bool use_mojo_channel, - mojo::ScopedMessagePipeHandle handle) { + const std::string& ipc_token) { bool create_pipe_now = true; if (use_mojo_channel) { VLOG(1) << "Mojo is enabled on child"; + mojo::ScopedMessagePipeHandle handle; if (!IsInBrowserProcess()) { DCHECK(!handle.is_valid()); handle = mojo::edk::CreateChildMessagePipe( base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kMojoChannelToken)); + } else { + handle = mojo::edk::CreateChildMessagePipe(ipc_token); } DCHECK(handle.is_valid()); channel_->Init(IPC::ChannelMojo::CreateClientFactory(std::move(handle)), @@ -390,7 +396,7 @@ UMA_HISTOGRAM_TIMES("Mojo.Shell.ChildConnectionTime", timer.Elapsed()); } - mojo_application_.reset(new MojoApplication(GetIOTaskRunner())); + mojo_application_.reset(new MojoApplication()); std::string mojo_application_token; if (!IsInBrowserProcess()) { mojo_application_token = @@ -466,9 +472,7 @@ channel_->AddFilter(startup_filter); } - ConnectChannel( - options.use_mojo_channel, - mojo::MakeScopedHandle(options.in_process_message_pipe_handle)); + ConnectChannel(options.use_mojo_channel, options.in_process_ipc_token); IPC::AttachmentBroker* broker = IPC::AttachmentBroker::GetGlobal(); if (broker && !broker->IsPrivilegedBroker()) broker->RegisterBrokerCommunicationChannel(channel_.get()); @@ -610,9 +614,6 @@ } bool ChildThreadImpl::OnMessageReceived(const IPC::Message& msg) { - if (mojo_application_->OnMessageReceived(msg)) - return true; - // Resource responses are sent to the resource dispatcher. if (resource_dispatcher_->OnMessageReceived(msg)) return true;
diff --git a/content/child/child_thread_impl.h b/content/child/child_thread_impl.h index fe2cc28..1476395 100644 --- a/content/child/child_thread_impl.h +++ b/content/child/child_thread_impl.h
@@ -221,8 +221,7 @@ // We create the channel first without connecting it so we can add filters // prior to any messages being received, then connect it afterwards. - void ConnectChannel(bool use_mojo_channel, - mojo::ScopedMessagePipeHandle handle); + void ConnectChannel(bool use_mojo_channel, const std::string& ipc_token); // IPC message handlers. void OnShutdown(); @@ -305,7 +304,7 @@ bool use_mojo_channel; scoped_refptr<base::SequencedTaskRunner> browser_process_io_runner; std::vector<IPC::MessageFilter*> startup_filters; - mojo::MessagePipeHandle in_process_message_pipe_handle; + std::string in_process_ipc_token; std::string in_process_application_token; private:
diff --git a/content/child/mojo/mojo_application.cc b/content/child/mojo/mojo_application.cc index 833f2997..7aa4597 100644 --- a/content/child/mojo/mojo_application.cc +++ b/content/child/mojo/mojo_application.cc
@@ -6,36 +6,19 @@ #include <utility> -#include "build/build_config.h" -#include "content/child/child_process.h" +#include "base/logging.h" #include "content/common/application_setup.mojom.h" -#include "content/common/mojo/channel_init.h" -#include "content/common/mojo/mojo_messages.h" -#include "ipc/ipc_message.h" #include "mojo/edk/embedder/embedder.h" -#include "mojo/public/cpp/bindings/interface_ptr.h" namespace content { -MojoApplication::MojoApplication( - scoped_refptr<base::SequencedTaskRunner> io_task_runner) - : io_task_runner_(io_task_runner) { - DCHECK(io_task_runner_); +MojoApplication::MojoApplication() { } MojoApplication::~MojoApplication() { } -bool MojoApplication::OnMessageReceived(const IPC::Message& msg) { - bool handled = true; - IPC_BEGIN_MESSAGE_MAP(MojoApplication, msg) - IPC_MESSAGE_HANDLER(MojoMsg_Activate, OnActivate) - IPC_MESSAGE_UNHANDLED(handled = false) - IPC_END_MESSAGE_MAP() - return handled; -} - -void MojoApplication::InitWithToken(std::string token) { +void MojoApplication::InitWithToken(const std::string& token) { mojo::ScopedMessagePipeHandle handle = mojo::edk::CreateChildMessagePipe(token); DCHECK(handle.is_valid()); @@ -52,28 +35,4 @@ service_registry_.BindRemoteServiceProvider(std::move(services)); } -void MojoApplication::OnActivate( - const IPC::PlatformFileForTransit& file) { -#if defined(OS_POSIX) - base::PlatformFile handle = file.fd; -#elif defined(OS_WIN) - base::PlatformFile handle = file.GetHandle(); -#endif - - mojo::ScopedMessagePipeHandle pipe = - channel_init_.Init(handle, io_task_runner_); - DCHECK(pipe.is_valid()); - - mojom::ApplicationSetupPtr application_setup; - application_setup.Bind( - mojo::InterfacePtrInfo<mojom::ApplicationSetup>(std::move(pipe), 0u)); - - shell::mojom::InterfaceProviderPtr services; - shell::mojom::InterfaceProviderPtr exposed_services; - service_registry_.Bind(GetProxy(&exposed_services)); - application_setup->ExchangeInterfaceProviders(GetProxy(&services), - std::move(exposed_services)); - service_registry_.BindRemoteServiceProvider(std::move(services)); -} - } // namespace content
diff --git a/content/child/mojo/mojo_application.h b/content/child/mojo/mojo_application.h index 3481212..68602c4f 100644 --- a/content/child/mojo/mojo_application.h +++ b/content/child/mojo/mojo_application.h
@@ -8,44 +8,26 @@ #include <string> #include "base/macros.h" -#include "content/common/mojo/channel_init.h" #include "content/common/mojo/service_registry_impl.h" -#include "ipc/ipc_platform_file.h" -#include "mojo/public/cpp/system/message_pipe.h" - -namespace base { -class SequencedTaskRunner; -} - -namespace IPC { -class Message; -} namespace content { // MojoApplication represents the code needed to setup a child process as a -// Mojo application via Chrome IPC. Instantiate MojoApplication and call its -// OnMessageReceived method to give it a shot at handling Chrome IPC messages. -// It makes the ServiceRegistry interface available. +// Mojo application. Instantiate MojoApplication and call InitWithToken() with +// a token passed from the process host. It makes the ServiceRegistry interface +// available. class MojoApplication { public: - explicit MojoApplication( - scoped_refptr<base::SequencedTaskRunner> io_task_runner); + MojoApplication(); virtual ~MojoApplication(); - // TODO(amistry): Remove OnMessageReceived() when all bootstrapping has - // migrated to these functions. - void InitWithToken(std::string token); - - bool OnMessageReceived(const IPC::Message& msg); + // Initializes this MojoApplicaiton with a message pipe obtained using + // |token|. + void InitWithToken(const std::string& token); ServiceRegistry* service_registry() { return &service_registry_; } private: - void OnActivate(const IPC::PlatformFileForTransit& file); - - scoped_refptr<base::SequencedTaskRunner> io_task_runner_; - ChannelInit channel_init_; ServiceRegistryImpl service_registry_; DISALLOW_COPY_AND_ASSIGN(MojoApplication);
diff --git a/content/common/content_message_generator.h b/content/common/content_message_generator.h index c26352d0..68f6b11 100644 --- a/content/common/content_message_generator.h +++ b/content/common/content_message_generator.h
@@ -46,7 +46,6 @@ #include "content/common/memory_messages.h" #include "content/common/message_port_messages.h" #include "content/common/mime_registry_messages.h" -#include "content/common/mojo/mojo_messages.h" #include "content/common/page_messages.h" #include "content/common/pepper_messages.h" #include "content/common/platform_notification_messages.h"
diff --git a/content/common/host_shared_bitmap_manager.cc b/content/common/host_shared_bitmap_manager.cc index 2533cf16..3a51de6 100644 --- a/content/common/host_shared_bitmap_manager.cc +++ b/content/common/host_shared_bitmap_manager.cc
@@ -22,11 +22,7 @@ class BitmapData : public base::RefCountedThreadSafe<BitmapData> { public: - BitmapData(base::ProcessHandle process_handle, - size_t buffer_size) - : process_handle(process_handle), - buffer_size(buffer_size) {} - base::ProcessHandle process_handle; + explicit BitmapData(size_t buffer_size) : buffer_size(buffer_size) {} std::unique_ptr<base::SharedMemory> memory; std::unique_ptr<uint8_t[]> pixels; size_t buffer_size; @@ -90,10 +86,8 @@ void HostSharedBitmapManagerClient::ChildAllocatedSharedBitmap( size_t buffer_size, const base::SharedMemoryHandle& handle, - base::ProcessHandle process_handle, const cc::SharedBitmapId& id) { - if (manager_->ChildAllocatedSharedBitmap(buffer_size, handle, process_handle, - id)) { + if (manager_->ChildAllocatedSharedBitmap(buffer_size, handle, id)) { base::AutoLock lock(lock_); owned_bitmaps_.insert(id); } @@ -124,9 +118,7 @@ if (!cc::SharedBitmap::SizeInBytes(size, &bitmap_size)) return std::unique_ptr<cc::SharedBitmap>(); - scoped_refptr<BitmapData> data( - new BitmapData(base::GetCurrentProcessHandle(), - bitmap_size)); + scoped_refptr<BitmapData> data(new BitmapData(bitmap_size)); // Bitmaps allocated in host don't need to be shared to other processes, so // allocate them with new instead. data->pixels = std::unique_ptr<uint8_t[]>(new uint8_t[bitmap_size]); @@ -195,13 +187,11 @@ bool HostSharedBitmapManager::ChildAllocatedSharedBitmap( size_t buffer_size, const base::SharedMemoryHandle& handle, - base::ProcessHandle process_handle, const cc::SharedBitmapId& id) { base::AutoLock lock(lock_); if (handle_map_.find(id) != handle_map_.end()) return false; - scoped_refptr<BitmapData> data( - new BitmapData(process_handle, buffer_size)); + scoped_refptr<BitmapData> data(new BitmapData(buffer_size)); handle_map_[id] = data; data->memory = base::WrapUnique(new base::SharedMemory(handle, false)); @@ -227,8 +217,7 @@ return; } - scoped_refptr<BitmapData> data( - new BitmapData(process_handle, buffer_size)); + scoped_refptr<BitmapData> data(new BitmapData(buffer_size)); data->memory = std::move(shared_memory); handle_map_[id] = data;
diff --git a/content/common/host_shared_bitmap_manager.h b/content/common/host_shared_bitmap_manager.h index c96e1c6..d2abcd4 100644 --- a/content/common/host_shared_bitmap_manager.h +++ b/content/common/host_shared_bitmap_manager.h
@@ -47,7 +47,6 @@ base::SharedMemoryHandle* shared_memory_handle); void ChildAllocatedSharedBitmap(size_t buffer_size, const base::SharedMemoryHandle& handle, - base::ProcessHandle process_handle, const cc::SharedBitmapId& id); void ChildDeletedSharedBitmap(const cc::SharedBitmapId& id); @@ -95,7 +94,6 @@ base::SharedMemoryHandle* shared_memory_handle); bool ChildAllocatedSharedBitmap(size_t buffer_size, const base::SharedMemoryHandle& handle, - base::ProcessHandle process_handle, const cc::SharedBitmapId& id); void ChildDeletedSharedBitmap(const cc::SharedBitmapId& id);
diff --git a/content/common/host_shared_bitmap_manager_unittest.cc b/content/common/host_shared_bitmap_manager_unittest.cc index 16cb139..e1f5feeb 100644 --- a/content/common/host_shared_bitmap_manager_unittest.cc +++ b/content/common/host_shared_bitmap_manager_unittest.cc
@@ -29,8 +29,7 @@ HostSharedBitmapManagerClient client(manager_.get()); base::SharedMemoryHandle handle; bitmap->ShareToProcess(base::GetCurrentProcessHandle(), &handle); - client.ChildAllocatedSharedBitmap(size_in_bytes, handle, - base::GetCurrentProcessHandle(), id); + client.ChildAllocatedSharedBitmap(size_in_bytes, handle, id); std::unique_ptr<cc::SharedBitmap> large_bitmap; large_bitmap = manager_->GetSharedBitmapFromId(gfx::Size(1024, 1024), id); @@ -115,8 +114,7 @@ std::unique_ptr<HostSharedBitmapManagerClient> client( new HostSharedBitmapManagerClient(manager_.get())); bitmap->ShareToProcess(base::GetCurrentProcessHandle(), &handle); - client->ChildAllocatedSharedBitmap(size_in_bytes, handle, - base::GetCurrentProcessHandle(), id); + client->ChildAllocatedSharedBitmap(size_in_bytes, handle, id); std::unique_ptr<cc::SharedBitmap> shared_bitmap; shared_bitmap = manager_->GetSharedBitmapFromId(bitmap_size, id); @@ -147,15 +145,13 @@ base::SharedMemoryHandle handle; bitmap->ShareToProcess(base::GetCurrentProcessHandle(), &handle); - client.ChildAllocatedSharedBitmap(size_in_bytes, handle, - base::GetCurrentProcessHandle(), id); + client.ChildAllocatedSharedBitmap(size_in_bytes, handle, id); std::unique_ptr<base::SharedMemory> bitmap2(new base::SharedMemory()); bitmap2->CreateAndMapAnonymous(size_in_bytes); memset(bitmap2->memory(), 0x00, size_in_bytes); - client.ChildAllocatedSharedBitmap(size_in_bytes, bitmap2->handle(), - base::GetCurrentProcessHandle(), id); + client.ChildAllocatedSharedBitmap(size_in_bytes, bitmap2->handle(), id); std::unique_ptr<cc::SharedBitmap> shared_bitmap; shared_bitmap = manager_->GetSharedBitmapFromId(bitmap_size, id);
diff --git a/content/common/in_process_child_thread_params.cc b/content/common/in_process_child_thread_params.cc index 25162b7..47e0fd9 100644 --- a/content/common/in_process_child_thread_params.cc +++ b/content/common/in_process_child_thread_params.cc
@@ -9,9 +9,9 @@ InProcessChildThreadParams::InProcessChildThreadParams( const std::string& channel_name, scoped_refptr<base::SequencedTaskRunner> io_runner, - mojo::MessagePipeHandle handle, + const std::string& ipc_token, const std::string& application_token) - : channel_name_(channel_name), io_runner_(io_runner), handle_(handle), + : channel_name_(channel_name), io_runner_(io_runner), ipc_token_(ipc_token), application_token_(application_token) {} InProcessChildThreadParams::InProcessChildThreadParams(
diff --git a/content/common/in_process_child_thread_params.h b/content/common/in_process_child_thread_params.h index f96060b..ebbf8f6 100644 --- a/content/common/in_process_child_thread_params.h +++ b/content/common/in_process_child_thread_params.h
@@ -10,7 +10,6 @@ #include "base/memory/ref_counted.h" #include "base/sequenced_task_runner.h" #include "content/common/content_export.h" -#include "mojo/public/cpp/system/message_pipe.h" namespace content { @@ -22,7 +21,7 @@ InProcessChildThreadParams( const std::string& channel_name, scoped_refptr<base::SequencedTaskRunner> io_runner, - mojo::MessagePipeHandle handle = mojo::MessagePipeHandle(), + const std::string& ipc_token = std::string(), const std::string& application_token = std::string()); InProcessChildThreadParams(const InProcessChildThreadParams& other); ~InProcessChildThreadParams(); @@ -31,7 +30,7 @@ scoped_refptr<base::SequencedTaskRunner> io_runner() const { return io_runner_; } - mojo::MessagePipeHandle handle() const { return handle_; } + const std::string& ipc_token() const { return ipc_token_; } const std::string& application_token() const { return application_token_; } @@ -39,7 +38,7 @@ private: std::string channel_name_; scoped_refptr<base::SequencedTaskRunner> io_runner_; - mojo::MessagePipeHandle handle_; + std::string ipc_token_; std::string application_token_; };
diff --git a/content/common/mojo/channel_init.cc b/content/common/mojo/channel_init.cc deleted file mode 100644 index c8172ab2..0000000 --- a/content/common/mojo/channel_init.cc +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/common/mojo/channel_init.h" - -#include <utility> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/command_line.h" -#include "base/lazy_instance.h" -#include "base/memory/ref_counted.h" -#include "base/message_loop/message_loop.h" -#include "base/task_runner.h" -#include "base/thread_task_runner_handle.h" -#include "mojo/edk/embedder/embedder.h" - -namespace content { - -ChannelInit::ChannelInit() {} - -ChannelInit::~ChannelInit() {} - -mojo::ScopedMessagePipeHandle ChannelInit::Init( - base::PlatformFile file, - scoped_refptr<base::TaskRunner> io_thread_task_runner) { - return mojo::edk::CreateMessagePipe( - mojo::edk::ScopedPlatformHandle(mojo::edk::PlatformHandle(file))); -} - -} // namespace content
diff --git a/content/common/mojo/channel_init.h b/content/common/mojo/channel_init.h deleted file mode 100644 index 6b9daae..0000000 --- a/content/common/mojo/channel_init.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_COMMON_MOJO_CHANNEL_INIT_H_ -#define CONTENT_COMMON_MOJO_CHANNEL_INIT_H_ - -#include "base/files/file.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "content/common/content_export.h" -#include "mojo/public/cpp/system/message_pipe.h" - -namespace base { -class TaskRunner; -} - -namespace content { - -// ChannelInit handles creation and destruction of the Mojo channel. It is not -// thread-safe, but may be used on any single thread with a MessageLoop. -// -// TODO(rockot): Get rid of this class ASAP (i.e. once the patch which includes -// this TODO has stuck for a bit) since it's no longer necessary. -class CONTENT_EXPORT ChannelInit { - public: - ChannelInit(); - ~ChannelInit(); - - // Initializes the channel. This takes ownership of |file|. - mojo::ScopedMessagePipeHandle Init( - base::PlatformFile file, - scoped_refptr<base::TaskRunner> io_thread_task_runner); - - private: - DISALLOW_COPY_AND_ASSIGN(ChannelInit); -}; - -} // namespace content - -#endif // CONTENT_COMMON_MOJO_CHANNEL_INIT_H_
diff --git a/content/common/mojo/mojo_messages.h b/content/common/mojo/mojo_messages.h deleted file mode 100644 index 1232902..0000000 --- a/content/common/mojo/mojo_messages.h +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright (c) 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. - -// IPC messages for mojo. -// Multiply-included message file, hence no include guard. - -#include "content/common/content_export.h" -#include "content/public/common/common_param_traits.h" -#include "ipc/ipc_message_macros.h" -#include "ipc/ipc_message_utils.h" -#include "ipc/ipc_param_traits.h" -#include "ipc/ipc_platform_file.h" -#include "ipc/param_traits_macros.h" - -#undef IPC_MESSAGE_EXPORT -#define IPC_MESSAGE_EXPORT CONTENT_EXPORT -#define IPC_MESSAGE_START MojoMsgStart - -// Mojo IPC is bootstrapped over Chrome IPC via this message. -IPC_MESSAGE_CONTROL1(MojoMsg_Activate, - IPC::PlatformFileForTransit /* handle */)
diff --git a/content/content_browser.gypi b/content/content_browser.gypi index c630a6a..90b1b684 100644 --- a/content/content_browser.gypi +++ b/content/content_browser.gypi
@@ -1195,8 +1195,6 @@ 'browser/quota_dispatcher_host.cc', 'browser/quota_dispatcher_host.h', 'browser/renderer_data_memoizing_store.h', - 'browser/renderer_host/begin_frame_observer_proxy.cc', - 'browser/renderer_host/begin_frame_observer_proxy.h', 'browser/renderer_host/clipboard_message_filter.cc', 'browser/renderer_host/clipboard_message_filter.h', 'browser/renderer_host/clipboard_message_filter_mac.mm', @@ -1727,8 +1725,6 @@ 'browser/web_contents/web_contents_view_android.h', ], 'android_in_process_browser_sources': [ - 'browser/android/in_process/context_provider_in_process.cc', - 'browser/android/in_process/context_provider_in_process.h', 'browser/android/in_process/synchronous_compositor_factory_impl.cc', 'browser/android/in_process/synchronous_compositor_factory_impl.h', 'browser/android/in_process/synchronous_compositor_impl.cc', @@ -2104,7 +2100,6 @@ 'browser/media/session/media_session_delegate_default.cc', 'browser/power_usage_monitor_impl.cc', 'browser/power_usage_monitor_impl.h', - 'browser/renderer_host/begin_frame_observer_proxy.cc', 'browser/renderer_host/native_web_keyboard_event.cc', ] }],
diff --git a/content/content_common.gypi b/content/content_common.gypi index 78bd2fe..36d59656 100644 --- a/content/content_common.gypi +++ b/content/content_common.gypi
@@ -459,11 +459,8 @@ 'common/memory_messages.h', 'common/message_port_messages.h', 'common/mime_registry_messages.h', - 'common/mojo/channel_init.cc', - 'common/mojo/channel_init.h', 'common/mojo/embedded_application_runner.cc', 'common/mojo/embedded_application_runner.h', - 'common/mojo/mojo_messages.h', 'common/mojo/mojo_shell_connection_impl.cc', 'common/mojo/mojo_shell_connection_impl.h', 'common/mojo/service_registry_impl.cc',
diff --git a/content/content_renderer.gypi b/content/content_renderer.gypi index fadb26e..d2efa37 100644 --- a/content/content_renderer.gypi +++ b/content/content_renderer.gypi
@@ -291,8 +291,6 @@ 'renderer/media/android/stream_texture_factory.h', 'renderer/media/android/stream_texture_factory_impl.cc', 'renderer/media/android/stream_texture_factory_impl.h', - 'renderer/media/android/stream_texture_factory_synchronous_impl.cc', - 'renderer/media/android/stream_texture_factory_synchronous_impl.h', 'renderer/media/android/webmediaplayer_android.cc', 'renderer/media/android/webmediaplayer_android.h', 'renderer/media/android/webmediasession_android.cc',
diff --git a/content/content_shell.gypi b/content/content_shell.gypi index f093081..cb15a5f 100644 --- a/content/content_shell.gypi +++ b/content/content_shell.gypi
@@ -101,12 +101,12 @@ 'shell/browser/layout_test/blink_test_controller.h', 'shell/browser/layout_test/layout_test_android.cc', 'shell/browser/layout_test/layout_test_android.h', - 'shell/browser/layout_test/layout_test_bluetooth_fake_adapter_setter_impl.cc', - 'shell/browser/layout_test/layout_test_bluetooth_fake_adapter_setter_impl.h', 'shell/browser/layout_test/layout_test_bluetooth_adapter_provider.cc', 'shell/browser/layout_test/layout_test_bluetooth_adapter_provider.h', 'shell/browser/layout_test/layout_test_bluetooth_chooser_factory.cc', 'shell/browser/layout_test/layout_test_bluetooth_chooser_factory.h', + 'shell/browser/layout_test/layout_test_bluetooth_fake_adapter_setter_impl.cc', + 'shell/browser/layout_test/layout_test_bluetooth_fake_adapter_setter_impl.h', 'shell/browser/layout_test/layout_test_browser_context.cc', 'shell/browser/layout_test/layout_test_browser_context.h', 'shell/browser/layout_test/layout_test_browser_main.cc', @@ -133,8 +133,8 @@ 'shell/browser/layout_test/layout_test_resource_dispatcher_host_delegate.h', 'shell/browser/layout_test/layout_test_url_request_context_getter.cc', 'shell/browser/layout_test/layout_test_url_request_context_getter.h', - 'shell/browser/layout_test/notify_done_forwarder.cc', - 'shell/browser/layout_test/notify_done_forwarder.h', + 'shell/browser/layout_test/secondary_test_window_observer.cc', + 'shell/browser/layout_test/secondary_test_window_observer.h', 'shell/browser/layout_test/test_info_extractor.cc', 'shell/browser/layout_test/test_info_extractor.h', 'shell/browser/shell.cc',
diff --git a/content/content_tests.gypi b/content/content_tests.gypi index e69ad48..8d8c03e 100644 --- a/content/content_tests.gypi +++ b/content/content_tests.gypi
@@ -544,7 +544,6 @@ 'browser/quota/quota_temporary_storage_evictor_unittest.cc', 'browser/quota/storage_monitor_unittest.cc', 'browser/quota/usage_tracker_unittest.cc', - 'browser/renderer_host/begin_frame_observer_proxy_unittest.cc', 'browser/renderer_host/clipboard_message_filter_unittest.cc', 'browser/renderer_host/dwrite_font_proxy_message_filter_win_unittest.cc', 'browser/renderer_host/input/gesture_event_queue_unittest.cc', @@ -599,6 +598,7 @@ 'browser/service_worker/service_worker_cache_writer_unittest.cc', 'browser/service_worker/service_worker_context_request_handler_unittest.cc', 'browser/service_worker/service_worker_context_unittest.cc', + 'browser/service_worker/service_worker_context_core_unittest.cc', 'browser/service_worker/service_worker_controllee_request_handler_unittest.cc', 'browser/service_worker/service_worker_database_unittest.cc', 'browser/service_worker/service_worker_dispatcher_host_unittest.cc', @@ -1166,7 +1166,6 @@ 'browser/geolocation/network_location_provider_unittest.cc', 'browser/geolocation/wifi_data_provider_common_unittest.cc', 'browser/power_usage_monitor_impl_unittest.cc', - 'browser/renderer_host/begin_frame_observer_proxy_unittest.cc', 'browser/webui/url_data_manager_backend_unittest.cc', 'renderer/media/audio_track_recorder_unittest.cc', 'renderer/media/media_recorder_handler_unittest.cc', @@ -1537,6 +1536,7 @@ ], 'sources': [ 'browser/compositor/gl_helper_unittest.cc', + 'browser/compositor/yuv_readback_unittest.cc', 'common/gpu/client/gpu_context_tests.h', 'common/gpu/client/gpu_in_process_context_tests.cc', 'test/run_all_gl_tests.cc',
diff --git a/content/gpu/BUILD.gn b/content/gpu/BUILD.gn index 35fc15e..2536b86 100644 --- a/content/gpu/BUILD.gn +++ b/content/gpu/BUILD.gn
@@ -46,6 +46,7 @@ "//base/third_party/dynamic_annotations", "//components/tracing", "//content:export", + "//content/child", "//content/common", "//content/public/child:child_sources", "//content/public/common:common_sources",
diff --git a/content/public/android/java/res/OWNERS b/content/public/android/java/res/OWNERS index 7b0bde5..8780d0c1 100644 --- a/content/public/android/java/res/OWNERS +++ b/content/public/android/java/res/OWNERS
@@ -1,7 +1,5 @@ set noparent tedchoc@chromium.org -aurimas@chromium.org -newt@chromium.org dtrainor@chromium.org yusufo@chromium.org dfalcantara@chromium.org
diff --git a/content/public/android/java/src/org/chromium/content/browser/input/OWNERS b/content/public/android/java/src/org/chromium/content/browser/input/OWNERS index 28400a3..41b4ecb 100644 --- a/content/public/android/java/src/org/chromium/content/browser/input/OWNERS +++ b/content/public/android/java/src/org/chromium/content/browser/input/OWNERS
@@ -1,3 +1,2 @@ aelias@chromium.org -aurimas@chromium.org changwan@chromium.org
diff --git a/content/public/android/javatests/src/org/chromium/content/browser/ContentViewCoreSelectionTest.java b/content/public/android/javatests/src/org/chromium/content/browser/ContentViewCoreSelectionTest.java index b62c845..a0b5e0b 100644 --- a/content/public/android/javatests/src/org/chromium/content/browser/ContentViewCoreSelectionTest.java +++ b/content/public/android/javatests/src/org/chromium/content/browser/ContentViewCoreSelectionTest.java
@@ -8,12 +8,12 @@ import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; -import android.test.FlakyTest; import android.test.suitebuilder.annotation.SmallTest; import android.text.TextUtils; import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.Feature; +import org.chromium.base.test.util.FlakyTest; import org.chromium.base.test.util.UrlUtils; import org.chromium.content.browser.input.ChromiumBaseInputConnection; import org.chromium.content.browser.input.ImeTestUtils; @@ -131,9 +131,8 @@ /* @SmallTest @Feature({"TextInput"}) - https://crbug.com/592428 */ - @FlakyTest + @FlakyTest(message = "https://crbug.com/592428") public void testPastePopupNotShownOnLongPressingNonEmptyInput() throws Throwable { copyStringToClipboard("SampleTextToCopy"); DOMUtils.longPressNode(this, mContentViewCore, "empty_input_text"); @@ -146,9 +145,8 @@ /* @SmallTest @Feature({"TextInput"}) - https://crbug.com/592428 */ - @FlakyTest + @FlakyTest(message = "https://crbug.com/592428") public void testPastePopupClearedOnTappingEmptyInput() throws Throwable { copyStringToClipboard("SampleTextToCopy"); DOMUtils.longPressNode(this, mContentViewCore, "empty_input_text"); @@ -160,9 +158,8 @@ /* @SmallTest @Feature({"TextInput"}) - https://crbug.com/592428 */ - @FlakyTest + @FlakyTest(message = "https://crbug.com/592428") public void testPastePopupClearedOnTappingNonEmptyInput() throws Throwable { copyStringToClipboard("SampleTextToCopy"); DOMUtils.longPressNode(this, mContentViewCore, "empty_input_text"); @@ -174,9 +171,8 @@ /* @SmallTest @Feature({"TextInput"}) - https://crbug.com/592428 */ - @FlakyTest + @FlakyTest(message = "https://crbug.com/592428") public void testPastePopupClearedOnTappingOutsideInput() throws Throwable { copyStringToClipboard("SampleTextToCopy"); DOMUtils.longPressNode(this, mContentViewCore, "empty_input_text"); @@ -188,9 +184,8 @@ /* @SmallTest @Feature({"TextInput"}) - https://crbug.com/592428 */ - @FlakyTest + @FlakyTest(message = "https://crbug.com/592428") public void testPastePopupClearedOnLongPressingOutsideInput() throws Throwable { copyStringToClipboard("SampleTextToCopy"); DOMUtils.longPressNode(this, mContentViewCore, "empty_input_text"); @@ -202,9 +197,8 @@ /* @SmallTest @Feature({"TextInput"}) - https://crbug.com/592428 */ - @FlakyTest + @FlakyTest(message = "https://crbug.com/592428") public void testPastePopupNotShownOnLongPressingDisabledInput() throws Throwable { copyStringToClipboard("SampleTextToCopy"); DOMUtils.longPressNode(this, mContentViewCore, "empty_input_text"); @@ -218,9 +212,8 @@ /* @SmallTest @Feature({"TextInput"}) - https://crbug.com/592428 */ - @FlakyTest + @FlakyTest(message = "https://crbug.com/592428") public void testPastePopupDismissedOnDestroy() throws Throwable { copyStringToClipboard("SampleTextToCopy"); DOMUtils.longPressNode(this, mContentViewCore, "empty_input_text"); @@ -520,9 +513,8 @@ /* @SmallTest @Feature({"TextInput"}) - https://crbug.com/592428 */ - @FlakyTest + @FlakyTest(message = "https://crbug.com/592428") public void testSelectActionBarPasswordPaste() throws Exception { copyStringToClipboard("SamplePassword2");
diff --git a/content/public/android/javatests/src/org/chromium/content/browser/input/OWNERS b/content/public/android/javatests/src/org/chromium/content/browser/input/OWNERS index 28400a3..41b4ecb 100644 --- a/content/public/android/javatests/src/org/chromium/content/browser/input/OWNERS +++ b/content/public/android/javatests/src/org/chromium/content/browser/input/OWNERS
@@ -1,3 +1,2 @@ aelias@chromium.org -aurimas@chromium.org changwan@chromium.org
diff --git a/content/public/browser/android/content_view_core.h b/content/public/browser/android/content_view_core.h index d0b8f0c..800a188 100644 --- a/content/public/browser/android/content_view_core.h +++ b/content/public/browser/android/content_view_core.h
@@ -48,14 +48,6 @@ virtual const scoped_refptr<cc::Layer>& GetLayer() const = 0; virtual bool ShowPastePopup(int x, int y) = 0; - // Request a scaled content readback. The result is passed through the - // callback. The boolean parameter indicates whether the readback was a - // success or not. The content is passed through the SkBitmap parameter. - virtual void GetScaledContentBitmap( - float scale, - SkColorType color_type, - const gfx::Rect& src_rect, - const ReadbackRequestCallback& result_callback) = 0; virtual float GetDpiScale() const = 0; virtual void PauseOrResumeGeolocation(bool should_pause) = 0;
diff --git a/content/public/browser/load_notification_details.h b/content/public/browser/load_notification_details.h index 22af84cab..b02e0f0 100644 --- a/content/public/browser/load_notification_details.h +++ b/content/public/browser/load_notification_details.h
@@ -17,14 +17,12 @@ // log page load metrics. struct LoadNotificationDetails { LoadNotificationDetails(const GURL& url, - ui::PageTransition origin, base::TimeDelta load_time, NavigationController* controller, int session_index) : url(url), load_time(load_time), session_index(session_index), - origin(origin), controller(controller) {} // The URL loaded. @@ -36,9 +34,6 @@ // The index of the load within the tab session. int session_index; - // The type of action that caused the load. - ui::PageTransition origin; - // The NavigationController for the load. NavigationController* controller; };
diff --git a/content/public/child/BUILD.gn b/content/public/child/BUILD.gn index 68c99869..a9240179 100644 --- a/content/public/child/BUILD.gn +++ b/content/public/child/BUILD.gn
@@ -33,11 +33,8 @@ configs += [ "//content:content_implementation" ] - public_deps = [ - "//content/child", - ] - deps = [ + "//content/child", # Must not be public_deps! "//content/public/common:common_sources", "//gin", ]
diff --git a/content/public/common/common_param_traits_macros.h b/content/public/common/common_param_traits_macros.h index ae29c73..647624ab 100644 --- a/content/public/common/common_param_traits_macros.h +++ b/content/public/common/common_param_traits_macros.h
@@ -61,6 +61,9 @@ IPC_ENUM_TRAITS_MIN_MAX_VALUE(content::ImageAnimationPolicy, content::IMAGE_ANIMATION_POLICY_ALLOWED, content::IMAGE_ANIMATION_POLICY_NO_ANIMATION) +IPC_ENUM_TRAITS_MIN_MAX_VALUE(content::ViewportStyle, + content::ViewportStyle::DEFAULT, + content::ViewportStyle::LAST) IPC_STRUCT_TRAITS_BEGIN(blink::WebPoint) IPC_STRUCT_TRAITS_MEMBER(x) @@ -193,6 +196,7 @@ IPC_STRUCT_TRAITS_MEMBER(supports_multiple_windows) IPC_STRUCT_TRAITS_MEMBER(viewport_enabled) IPC_STRUCT_TRAITS_MEMBER(viewport_meta_enabled) + IPC_STRUCT_TRAITS_MEMBER(viewport_style) IPC_STRUCT_TRAITS_MEMBER(main_frame_resizes_are_orientation_changes) IPC_STRUCT_TRAITS_MEMBER(initialize_at_minimum_page_scale) IPC_STRUCT_TRAITS_MEMBER(smart_insert_delete_enabled)
diff --git a/content/public/common/content_switches.cc b/content/public/common/content_switches.cc index 8c441d8..eae2357b 100644 --- a/content/public/common/content_switches.cc +++ b/content/public/common/content_switches.cc
@@ -11,6 +11,14 @@ // have an effect. 0 disables MSAA. const char kAcceleratedCanvas2dMSAASampleCount[] = "canvas-msaa-sample-count"; +// Enables a new tuning of the WebRTC Acoustic Echo Canceler (AEC). The new +// tuning aims at resolving two issues with the AEC: +// https://bugs.chromium.org/p/webrtc/issues/detail?id=5777 +// https://bugs.chromium.org/p/webrtc/issues/detail?id=5778 +// TODO(hlundin): Remove this switch when experimentation is over; +// crbug.com/603821. +const char kAecRefinedAdaptiveFilter[] = "aec-refined-adaptive-filter"; + // Override the default minimum starting volume of the Automatic Gain Control // algorithm in WebRTC used with audio tracks from getUserMedia. // The valid range is 12-255. Values outside that range will be clamped
diff --git a/content/public/common/content_switches.h b/content/public/common/content_switches.h index bdd898e..525366f 100644 --- a/content/public/common/content_switches.h +++ b/content/public/common/content_switches.h
@@ -15,6 +15,7 @@ // All switches in alphabetical order. The switches should be documented // alongside the definition of their values in the .cc file. CONTENT_EXPORT extern const char kAcceleratedCanvas2dMSAASampleCount[]; +CONTENT_EXPORT extern const char kAecRefinedAdaptiveFilter[]; CONTENT_EXPORT extern const char kAgcStartupMinVolume[]; CONTENT_EXPORT extern const char kAllowFileAccessFromFiles[]; CONTENT_EXPORT extern const char kAllowLoopbackInPeerConnection[];
diff --git a/content/public/common/web_preferences.cc b/content/public/common/web_preferences.cc index c1cdd19..a0bc6f1 100644 --- a/content/public/common/web_preferences.cc +++ b/content/public/common/web_preferences.cc
@@ -48,6 +48,11 @@ STATIC_ASSERT_ENUM(ui::HOVER_TYPE_ON_DEMAND, blink::HoverTypeOnDemand); STATIC_ASSERT_ENUM(ui::HOVER_TYPE_HOVER, blink::HoverTypeHover); +STATIC_ASSERT_ENUM(ViewportStyle::DEFAULT, blink::WebViewportStyle::Default); +STATIC_ASSERT_ENUM(ViewportStyle::MOBILE, blink::WebViewportStyle::Mobile); +STATIC_ASSERT_ENUM(ViewportStyle::TELEVISION, + blink::WebViewportStyle::Television); + WebPreferences::WebPreferences() : default_font_size(16), default_fixed_font_size(13), @@ -142,8 +147,10 @@ viewport_enabled(false), #if defined(OS_ANDROID) viewport_meta_enabled(true), + viewport_style(ViewportStyle::MOBILE), #else viewport_meta_enabled(false), + viewport_style(ViewportStyle::DEFAULT), #endif main_frame_resizes_are_orientation_changes(false), initialize_at_minimum_page_scale(true),
diff --git a/content/public/common/web_preferences.h b/content/public/common/web_preferences.h index 7b72351..2a75e30 100644 --- a/content/public/common/web_preferences.h +++ b/content/public/common/web_preferences.h
@@ -52,6 +52,8 @@ IMAGE_ANIMATION_POLICY_NO_ANIMATION }; +enum class ViewportStyle { DEFAULT, MOBILE, TELEVISION, LAST = TELEVISION }; + // The ISO 15924 script code for undetermined script aka Common. It's the // default used on WebKit's side to get/set a font setting when no script is // specified. @@ -166,6 +168,7 @@ bool supports_multiple_windows; bool viewport_enabled; bool viewport_meta_enabled; + ViewportStyle viewport_style; bool main_frame_resizes_are_orientation_changes; bool initialize_at_minimum_page_scale; bool smart_insert_delete_enabled;
diff --git a/content/renderer/BUILD.gn b/content/renderer/BUILD.gn index 9a00f8e..318ed29 100644 --- a/content/renderer/BUILD.gn +++ b/content/renderer/BUILD.gn
@@ -37,6 +37,7 @@ "//components/scheduler:scheduler", "//components/url_formatter", "//content:resources", + "//content/child", "//content/common", "//content/gpu:gpu_sources", "//content/public/child:child_sources",
diff --git a/content/renderer/android/synchronous_compositor_factory.h b/content/renderer/android/synchronous_compositor_factory.h index d9bc10d2..47ea588 100644 --- a/content/renderer/android/synchronous_compositor_factory.h +++ b/content/renderer/android/synchronous_compositor_factory.h
@@ -21,19 +21,10 @@ class OutputSurface; } -namespace cc_blink { -class ContextProviderWebContext; -} - -namespace gpu_blink { -class WebGraphicsContext3DInProcessCommandBufferImpl; -} - namespace content { class InputHandlerManagerClient; class SynchronousInputHandlerProxyClient; -class StreamTextureFactory; class FrameSwapMessageQueue; // Decouples creation from usage of the parts needed for the synchonous
diff --git a/content/renderer/browser_plugin/browser_plugin.cc b/content/renderer/browser_plugin/browser_plugin.cc index e9c4bffa..40b9008 100644 --- a/content/renderer/browser_plugin/browser_plugin.cc +++ b/content/renderer/browser_plugin/browser_plugin.cc
@@ -68,7 +68,6 @@ : attached_(false), render_frame_routing_id_(render_frame->GetRoutingID()), container_(nullptr), - sad_guest_(nullptr), guest_crashed_(false), plugin_focused_(false), visible_(true),
diff --git a/content/renderer/browser_plugin/browser_plugin.h b/content/renderer/browser_plugin/browser_plugin.h index 52156ba..6cd8bebe 100644 --- a/content/renderer/browser_plugin/browser_plugin.h +++ b/content/renderer/browser_plugin/browser_plugin.h
@@ -174,8 +174,6 @@ blink::WebPluginContainer* container_; // The plugin's rect in css pixels. gfx::Rect view_rect_; - // Bitmap for crashed plugin. Lazily initialized, non-owning pointer. - SkBitmap* sad_guest_; bool guest_crashed_; bool plugin_focused_; // Tracks the visibility of the browser plugin regardless of the whole @@ -195,9 +193,6 @@ // URL for the embedder frame. int browser_plugin_instance_id_; - // Indicates whether the guest content is opaque. - bool contents_opaque_; - std::vector<EditCommand> edit_commands_; // We call lifetime managing methods on |delegate_|, but we do not directly
diff --git a/content/renderer/child_frame_compositing_helper.h b/content/renderer/child_frame_compositing_helper.h index 47c20251..e51ab82 100644 --- a/content/renderer/child_frame_compositing_helper.h +++ b/content/renderer/child_frame_compositing_helper.h
@@ -112,7 +112,6 @@ void UpdateWebLayer(blink::WebLayer* layer); int host_routing_id_; - bool opaque_; gfx::Size buffer_size_;
diff --git a/content/renderer/media/android/stream_texture_factory.h b/content/renderer/media/android/stream_texture_factory.h index d9c7323..4806c6a 100644 --- a/content/renderer/media/android/stream_texture_factory.h +++ b/content/renderer/media/android/stream_texture_factory.h
@@ -21,6 +21,7 @@ } // namespace gles2 } // namespace gpu +// TODO(boliu): Remove interfaces. namespace content { // The proxy class for the gpu thread to notify the compositor thread @@ -47,12 +48,6 @@ typedef std::unique_ptr<StreamTextureProxy, StreamTextureProxy::Deleter> ScopedStreamTextureProxy; -class StreamTextureFactoryContextObserver { - public: - virtual ~StreamTextureFactoryContextObserver() {} - virtual void ResetStreamTextureProxy() = 0; -}; - // Factory class for managing stream textures. class StreamTextureFactory : public base::RefCounted<StreamTextureFactory> { public: @@ -80,9 +75,6 @@ virtual gpu::gles2::GLES2Interface* ContextGL() = 0; - virtual void AddObserver(StreamTextureFactoryContextObserver* obs) = 0; - virtual void RemoveObserver(StreamTextureFactoryContextObserver* obs) = 0; - protected: friend class base::RefCounted<StreamTextureFactory>; virtual ~StreamTextureFactory() {}
diff --git a/content/renderer/media/android/stream_texture_factory_impl.cc b/content/renderer/media/android/stream_texture_factory_impl.cc index e79faa7..2b38b7a 100644 --- a/content/renderer/media/android/stream_texture_factory_impl.cc +++ b/content/renderer/media/android/stream_texture_factory_impl.cc
@@ -158,12 +158,4 @@ return context_provider_->ContextGL(); } -void StreamTextureFactoryImpl::AddObserver( - StreamTextureFactoryContextObserver* obs) { -} - -void StreamTextureFactoryImpl::RemoveObserver( - StreamTextureFactoryContextObserver* obs) { -} - } // namespace content
diff --git a/content/renderer/media/android/stream_texture_factory_impl.h b/content/renderer/media/android/stream_texture_factory_impl.h index e07122d..0f93d7c 100644 --- a/content/renderer/media/android/stream_texture_factory_impl.h +++ b/content/renderer/media/android/stream_texture_factory_impl.h
@@ -39,8 +39,6 @@ gpu::Mailbox* texture_mailbox) override; void SetStreamTextureSize(int32_t texture_id, const gfx::Size& size) override; gpu::gles2::GLES2Interface* ContextGL() override; - void AddObserver(StreamTextureFactoryContextObserver* obs) override; - void RemoveObserver(StreamTextureFactoryContextObserver* obs) override; private: friend class base::RefCounted<StreamTextureFactoryImpl>;
diff --git a/content/renderer/media/android/stream_texture_factory_synchronous_impl.cc b/content/renderer/media/android/stream_texture_factory_synchronous_impl.cc deleted file mode 100644 index 513432a..0000000 --- a/content/renderer/media/android/stream_texture_factory_synchronous_impl.cc +++ /dev/null
@@ -1,210 +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 "content/renderer/media/android/stream_texture_factory_synchronous_impl.h" - -#include <algorithm> - -#include "base/bind.h" -#include "base/callback.h" -#include "base/location.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "base/process/process_handle.h" -#include "base/single_thread_task_runner.h" -#include "base/synchronization/lock.h" -#include "cc/output/context_provider.h" -#include "content/renderer/render_thread_impl.h" -#include "gpu/command_buffer/client/gles2_interface.h" -#include "gpu/ipc/common/android/surface_texture_peer.h" -#include "ui/gl/android/surface_texture.h" - -using gpu::gles2::GLES2Interface; - -namespace content { - -namespace { - -class StreamTextureProxyImpl - : public StreamTextureProxy, - public base::SupportsWeakPtr<StreamTextureProxyImpl> { - public: - explicit StreamTextureProxyImpl( - StreamTextureFactorySynchronousImpl::ContextProvider* provider); - ~StreamTextureProxyImpl() override; - - // StreamTextureProxy implementation: - void BindToLoop(int32_t stream_id, - cc::VideoFrameProvider::Client* client, - scoped_refptr<base::SingleThreadTaskRunner> loop) override; - void Release() override; - - private: - void BindOnThread(int32_t stream_id); - void OnFrameAvailable(); - - // Protects access to |client_| and |loop_|. - base::Lock lock_; - cc::VideoFrameProvider::Client* client_; - scoped_refptr<base::SingleThreadTaskRunner> loop_; - - // Accessed on the |loop_| thread only. - base::Closure callback_; - scoped_refptr<StreamTextureFactorySynchronousImpl::ContextProvider> - context_provider_; - scoped_refptr<gfx::SurfaceTexture> surface_texture_; - - DISALLOW_IMPLICIT_CONSTRUCTORS(StreamTextureProxyImpl); -}; - -StreamTextureProxyImpl::StreamTextureProxyImpl( - StreamTextureFactorySynchronousImpl::ContextProvider* provider) - : client_(NULL), context_provider_(provider) { -} - -StreamTextureProxyImpl::~StreamTextureProxyImpl() {} - -void StreamTextureProxyImpl::Release() { - { - // Cannot call into |client_| anymore (from any thread) after returning - // from here. - base::AutoLock lock(lock_); - client_ = NULL; - } - // Release is analogous to the destructor, so there should be no more external - // calls to this object in Release. Therefore there is no need to acquire the - // lock to access |loop_|. - if (!loop_.get() || loop_->BelongsToCurrentThread() || - !loop_->DeleteSoon(FROM_HERE, this)) { - delete this; - } -} - -void StreamTextureProxyImpl::BindToLoop( - int32_t stream_id, - cc::VideoFrameProvider::Client* client, - scoped_refptr<base::SingleThreadTaskRunner> loop) { - DCHECK(loop.get()); - - { - base::AutoLock lock(lock_); - DCHECK(!loop_.get() || (loop.get() == loop_.get())); - loop_ = loop; - client_ = client; - } - - if (loop->BelongsToCurrentThread()) { - BindOnThread(stream_id); - return; - } - // Unretained is safe here only because the object is deleted on |loop_| - // thread. - loop->PostTask(FROM_HERE, - base::Bind(&StreamTextureProxyImpl::BindOnThread, - base::Unretained(this), - stream_id)); -} - -void StreamTextureProxyImpl::BindOnThread(int32_t stream_id) { - surface_texture_ = context_provider_->GetSurfaceTexture(stream_id); - if (!surface_texture_.get()) { - LOG(ERROR) << "Failed to get SurfaceTexture for stream."; - return; - } - - callback_ = - base::Bind(&StreamTextureProxyImpl::OnFrameAvailable, AsWeakPtr()); - surface_texture_->SetFrameAvailableCallback(callback_); -} - -void StreamTextureProxyImpl::OnFrameAvailable() { - base::AutoLock lock(lock_); - if (client_) - client_->DidReceiveFrame(); -} - -} // namespace - -// static -scoped_refptr<StreamTextureFactorySynchronousImpl> -StreamTextureFactorySynchronousImpl::Create( - const CreateContextProviderCallback& try_create_callback) { - return new StreamTextureFactorySynchronousImpl(try_create_callback); -} - -StreamTextureFactorySynchronousImpl::StreamTextureFactorySynchronousImpl( - const CreateContextProviderCallback& try_create_callback) - : create_context_provider_callback_(try_create_callback) {} - -StreamTextureFactorySynchronousImpl::~StreamTextureFactorySynchronousImpl() {} - -StreamTextureProxy* StreamTextureFactorySynchronousImpl::CreateProxy() { - bool had_proxy = !!context_provider_.get(); - if (!had_proxy) - context_provider_ = create_context_provider_callback_.Run(); - - if (!context_provider_.get()) - return NULL; - - if (!observers_.empty() && !had_proxy) { - for (auto& observer : observers_) - context_provider_->AddObserver(observer); - } - return new StreamTextureProxyImpl(context_provider_.get()); -} - -void StreamTextureFactorySynchronousImpl::EstablishPeer(int32_t stream_id, - int player_id, - int frame_id) { - DCHECK(context_provider_.get()); - scoped_refptr<gfx::SurfaceTexture> surface_texture = - context_provider_->GetSurfaceTexture(stream_id); - if (surface_texture.get()) { - gpu::SurfaceTexturePeer::GetInstance()->EstablishSurfaceTexturePeer( - base::GetCurrentProcessHandle(), surface_texture, frame_id, player_id); - } -} - -unsigned StreamTextureFactorySynchronousImpl::CreateStreamTexture( - unsigned texture_target, - unsigned* texture_id, - gpu::Mailbox* texture_mailbox) { - DCHECK(context_provider_.get()); - unsigned stream_id = 0; - GLES2Interface* gl = context_provider_->ContextGL(); - gl->GenTextures(1, texture_id); - gl->ShallowFlushCHROMIUM(); - stream_id = context_provider_->CreateStreamTexture(*texture_id); - gl->GenMailboxCHROMIUM(texture_mailbox->name); - gl->ProduceTextureDirectCHROMIUM( - *texture_id, texture_target, texture_mailbox->name); - return stream_id; -} - -void StreamTextureFactorySynchronousImpl::SetStreamTextureSize( - int32_t stream_id, - const gfx::Size& size) {} - -gpu::gles2::GLES2Interface* StreamTextureFactorySynchronousImpl::ContextGL() { - DCHECK(context_provider_.get()); - return context_provider_->ContextGL(); -} - -void StreamTextureFactorySynchronousImpl::AddObserver( - StreamTextureFactoryContextObserver* obs) { - DCHECK(observers_.find(obs) == observers_.end()); - observers_.insert(obs); - if (context_provider_.get()) - context_provider_->AddObserver(obs); -} - -void StreamTextureFactorySynchronousImpl::RemoveObserver( - StreamTextureFactoryContextObserver* obs) { - DCHECK(observers_.find(obs) != observers_.end()); - observers_.erase(obs); - if (context_provider_.get()) - context_provider_->RemoveObserver(obs); -} - -} // namespace content
diff --git a/content/renderer/media/android/stream_texture_factory_synchronous_impl.h b/content/renderer/media/android/stream_texture_factory_synchronous_impl.h deleted file mode 100644 index a8b759a..0000000 --- a/content/renderer/media/android/stream_texture_factory_synchronous_impl.h +++ /dev/null
@@ -1,81 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_RENDERER_MEDIA_ANDROID_STREAM_TEXTURE_FACTORY_SYNCHRONOUS_IMPL_H_ -#define CONTENT_RENDERER_MEDIA_ANDROID_STREAM_TEXTURE_FACTORY_SYNCHRONOUS_IMPL_H_ - -#include <stdint.h> - -#include <set> - -#include "base/callback.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/observer_list.h" -#include "content/renderer/media/android/stream_texture_factory.h" - -namespace gfx { -class SurfaceTexture; -} - -namespace gpu { -namespace gles2 { -class GLES2Interface; -} // namespace gles2 -} // namespace gpu - -namespace content { - -// Factory for when using synchronous compositor in Android WebView. -class StreamTextureFactorySynchronousImpl : public StreamTextureFactory { - public: - class ContextProvider : public base::RefCountedThreadSafe<ContextProvider> { - public: - virtual scoped_refptr<gfx::SurfaceTexture> GetSurfaceTexture( - uint32_t stream_id) = 0; - - virtual uint32_t CreateStreamTexture(uint32_t texture_id) = 0; - - virtual gpu::gles2::GLES2Interface* ContextGL() = 0; - - virtual void AddObserver(StreamTextureFactoryContextObserver* obs) = 0; - virtual void RemoveObserver(StreamTextureFactoryContextObserver* obs) = 0; - - protected: - friend class base::RefCountedThreadSafe<ContextProvider>; - virtual ~ContextProvider() {} - }; - - typedef base::Callback<scoped_refptr<ContextProvider>(void)> - CreateContextProviderCallback; - - static scoped_refptr<StreamTextureFactorySynchronousImpl> Create( - const CreateContextProviderCallback& try_create_callback); - - StreamTextureProxy* CreateProxy() override; - void EstablishPeer(int32_t stream_id, int player_id, int frame_id) override; - unsigned CreateStreamTexture(unsigned texture_target, - unsigned* texture_id, - gpu::Mailbox* texture_mailbox) override; - void SetStreamTextureSize(int32_t stream_id, const gfx::Size& size) override; - gpu::gles2::GLES2Interface* ContextGL() override; - void AddObserver(StreamTextureFactoryContextObserver* obs) override; - void RemoveObserver(StreamTextureFactoryContextObserver* obs) override; - - private: - friend class base::RefCounted<StreamTextureFactorySynchronousImpl>; - StreamTextureFactorySynchronousImpl( - const CreateContextProviderCallback& try_create_callback); - ~StreamTextureFactorySynchronousImpl() override; - - CreateContextProviderCallback create_context_provider_callback_; - scoped_refptr<ContextProvider> context_provider_; - std::set<StreamTextureFactoryContextObserver*> observers_; - - DISALLOW_IMPLICIT_CONSTRUCTORS(StreamTextureFactorySynchronousImpl); -}; - -} // namespace content - -#endif // CONTENT_RENDERER_MEDIA_ANDROID_STREAM_TEXTURE_FACTORY_SYNCHRONOUS_IMPL_H_
diff --git a/content/renderer/media/android/webmediaplayer_android.cc b/content/renderer/media/android/webmediaplayer_android.cc index d4a05a9..f673573 100644 --- a/content/renderer/media/android/webmediaplayer_android.cc +++ b/content/renderer/media/android/webmediaplayer_android.cc
@@ -226,7 +226,6 @@ DCHECK(player_manager_); DCHECK(main_thread_checker_.CalledOnValidThread()); - stream_texture_factory_->AddObserver(this); if (delegate_) delegate_id_ = delegate_->AddObserver(this); @@ -284,8 +283,6 @@ delegate_->RemoveObserver(delegate_id_); } - stream_texture_factory_->RemoveObserver(this); - if (media_source_delegate_) { // Part of |media_source_delegate_| needs to be stopped on the media thread. // Wait until |media_source_delegate_| is fully stopped before tearing @@ -1308,21 +1305,6 @@ void WebMediaPlayerAndroid::PutCurrentFrame() { } -void WebMediaPlayerAndroid::ResetStreamTextureProxy() { - DCHECK(main_thread_checker_.CalledOnValidThread()); - // When suppress_deleting_texture_ is true, OnDidExitFullscreen has already - // re-connected surface texture for embedded playback. There is no need to - // delete them and create again. In fact, Android gives MediaPlayer erorr - // code: what == 1, extra == -19 when Android WebView tries to create, delete - // then create the surface textures for a video in quick succession. - if (!suppress_deleting_texture_) - RemoveSurfaceTextureAndProxy(); - - TryCreateStreamTextureProxyIfNeeded(); - if (needs_establish_peer_ && is_playing_) - EstablishSurfaceTexturePeer(); -} - void WebMediaPlayerAndroid::RemoveSurfaceTextureAndProxy() { DCHECK(main_thread_checker_.CalledOnValidThread());
diff --git a/content/renderer/media/android/webmediaplayer_android.h b/content/renderer/media/android/webmediaplayer_android.h index 73d8e2c..75dd1be 100644 --- a/content/renderer/media/android/webmediaplayer_android.h +++ b/content/renderer/media/android/webmediaplayer_android.h
@@ -79,7 +79,6 @@ class WebMediaPlayerAndroid : public blink::WebMediaPlayer, public cc::VideoFrameProvider, - public StreamTextureFactoryContextObserver, public media::RendererMediaPlayerInterface, public NON_EXPORTED_BASE(media::WebMediaPlayerDelegate::Observer) { public: @@ -215,9 +214,6 @@ void OnMediaPlayerPause() override; void OnRemoteRouteAvailabilityChanged(bool routes_available) override; - // StreamTextureFactoryContextObserver implementation. - void ResetStreamTextureProxy() override; - // Called when the player is released. void OnPlayerReleased() override;
diff --git a/content/renderer/media/media_stream_audio_processor.cc b/content/renderer/media/media_stream_audio_processor.cc index 869e416..23039de6 100644 --- a/content/renderer/media/media_stream_audio_processor.cc +++ b/content/renderer/media/media_stream_audio_processor.cc
@@ -111,6 +111,13 @@ base::StringToInt(min_volume_str, startup_min_volume); } +// Checks if the AEC's refined adaptive filter tuning was enabled on the command +// line. +bool UseAecRefinedAdaptiveFilter() { + return base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kAecRefinedAdaptiveFilter); +} + } // namespace // Wraps AudioBus to provide access to the array of channel pointers, since this @@ -516,6 +523,10 @@ config.Set<webrtc::ExperimentalNs>( new webrtc::ExperimentalNs(goog_experimental_ns)); config.Set<webrtc::DelayAgnostic>(new webrtc::DelayAgnostic(true)); + if (UseAecRefinedAdaptiveFilter()) { + config.Set<webrtc::RefinedAdaptiveFilter>( + new webrtc::RefinedAdaptiveFilter(true)); + } if (goog_beamforming) { const auto& geometry = GetArrayGeometryPreferringConstraints(audio_constraints, input_params);
diff --git a/content/renderer/media/media_stream_dispatcher_unittest.cc b/content/renderer/media/media_stream_dispatcher_unittest.cc index fa9e80b..295de9cb 100644 --- a/content/renderer/media/media_stream_dispatcher_unittest.cc +++ b/content/renderer/media/media_stream_dispatcher_unittest.cc
@@ -116,9 +116,7 @@ MediaStreamDispatcherTest() : dispatcher_(new MediaStreamDispatcherUnderTest()), handler_(new MockMediaStreamDispatcherEventHandler), - security_origin_("http://test.com"), - request_id_(10) { - } + security_origin_("http://test.com") {} // Generates a request for a MediaStream and returns the request id that is // used in IPC. Use this returned id in CompleteGenerateStream to identify @@ -178,7 +176,6 @@ std::unique_ptr<MediaStreamDispatcherUnderTest> dispatcher_; std::unique_ptr<MockMediaStreamDispatcherEventHandler> handler_; GURL security_origin_; - int request_id_; }; } // namespace
diff --git a/content/renderer/media/video_capture_message_filter_unittest.cc b/content/renderer/media/video_capture_message_filter_unittest.cc index fd189a64e..6a33940 100644 --- a/content/renderer/media/video_capture_message_filter_unittest.cc +++ b/content/renderer/media/video_capture_message_filter_unittest.cc
@@ -107,6 +107,10 @@ OnBufferCreated( ::testing::Property(&base::SharedMemoryHandle::GetHandle, h), 100, 1)); +#elif defined(OS_MACOSX) && !defined(OS_IOS) + const base::SharedMemoryHandle handle = + base::SharedMemoryHandle(10, 100, base::GetCurrentProcId()); + EXPECT_CALL(delegate, OnBufferCreated(handle, 100, 1)); #else const base::SharedMemoryHandle handle = base::SharedMemoryHandle(10, true); EXPECT_CALL(delegate, OnBufferCreated(handle, 100, 1));
diff --git a/content/renderer/media/webaudio_capturer_source.h b/content/renderer/media/webaudio_capturer_source.h index 3063aeec..b9b69276 100644 --- a/content/renderer/media/webaudio_capturer_source.h +++ b/content/renderer/media/webaudio_capturer_source.h
@@ -88,7 +88,6 @@ // Synchronizes HandleCapture() with AudioCapturerSource calls. base::Lock lock_; - bool started_; // This object registers with a blink::WebMediaStreamSource. We keep track of // that in order to be able to deregister before stopping the audio track.
diff --git a/content/renderer/media/webrtc/peer_connection_dependency_factory.cc b/content/renderer/media/webrtc/peer_connection_dependency_factory.cc index 0885aef..03bc115 100644 --- a/content/renderer/media/webrtc/peer_connection_dependency_factory.cc +++ b/content/renderer/media/webrtc/peer_connection_dependency_factory.cc
@@ -504,18 +504,6 @@ } // static -void PeerConnectionDependencyFactory::SetDefaultCertificate( - webrtc::PeerConnectionInterface::RTCConfiguration* config) { - if (config->certificates.empty()) { - rtc::scoped_ptr<rtc::SSLIdentity> identity(rtc::SSLIdentity::Generate( - webrtc::kIdentityName, rtc::KeyParams::ECDSA(rtc::EC_NIST_P256))); - rtc::scoped_refptr<rtc::RTCCertificate> certificate = - rtc::RTCCertificate::Create(std::move(identity)); - config->certificates.push_back(certificate); - } -} - -// static rtc::scoped_refptr<rtc::RTCCertificate> PeerConnectionDependencyFactory::GenerateDefaultCertificate() { rtc::scoped_ptr<rtc::SSLIdentity> identity(rtc::SSLIdentity::Generate(
diff --git a/content/renderer/media/webrtc/peer_connection_dependency_factory.h b/content/renderer/media/webrtc/peer_connection_dependency_factory.h index 276f3d1..02088fb9 100644 --- a/content/renderer/media/webrtc/peer_connection_dependency_factory.h +++ b/content/renderer/media/webrtc/peer_connection_dependency_factory.h
@@ -71,10 +71,7 @@ blink::WebRTCPeerConnectionHandler* CreateRTCPeerConnectionHandler( blink::WebRTCPeerConnectionHandlerClient* client); - // Add an ECDSA certificate to |config| in case it contains no certificate. - static void SetDefaultCertificate( - webrtc::PeerConnectionInterface::RTCConfiguration* config); - + // Generate an ECDSA certificate. static rtc::scoped_refptr<rtc::RTCCertificate> GenerateDefaultCertificate(); // Asks the PeerConnection factory to create a Local MediaStream object.
diff --git a/content/renderer/media/webrtc_audio_device_impl.cc b/content/renderer/media/webrtc_audio_device_impl.cc index 17a0585..206672d 100644 --- a/content/renderer/media/webrtc_audio_device_impl.cc +++ b/content/renderer/media/webrtc_audio_device_impl.cc
@@ -26,8 +26,7 @@ output_delay_ms_(0), initialized_(false), playing_(false), - recording_(false), - microphone_volume_(0) { + recording_(false) { DVLOG(1) << "WebRtcAudioDeviceImpl::WebRtcAudioDeviceImpl()"; // This object can be constructed on either the signaling thread or the main // thread, so we need to detach these thread checkers here and have them
diff --git a/content/renderer/media/webrtc_audio_device_impl.h b/content/renderer/media/webrtc_audio_device_impl.h index 490eaf4a..52cb2a0 100644 --- a/content/renderer/media/webrtc_audio_device_impl.h +++ b/content/renderer/media/webrtc_audio_device_impl.h
@@ -380,9 +380,6 @@ // RegisterAudioCallback(). webrtc::AudioTransport* audio_transport_callback_; - // Cached value of the current audio delay on the input/capture side. - int input_delay_ms_; - // Cached value of the current audio delay on the output/renderer side. int output_delay_ms_; @@ -398,10 +395,6 @@ bool playing_; bool recording_; - // Stores latest microphone volume received in a CaptureData() callback. - // Range is [0, 255]. - uint32_t microphone_volume_; - // Buffer used for temporary storage during render callback. // It is only accessed by the audio render thread. std::vector<int16_t> render_buffer_;
diff --git a/content/renderer/pepper/pepper_graphics_2d_host.h b/content/renderer/pepper/pepper_graphics_2d_host.h index 03b97e7e..8d957c229 100644 --- a/content/renderer/pepper/pepper_graphics_2d_host.h +++ b/content/renderer/pepper/pepper_graphics_2d_host.h
@@ -202,7 +202,6 @@ bool is_running_in_process_; bool texture_mailbox_modified_; - bool is_using_texture_layer_; // This is a bitmap that was recently released by the compositor and may be // used to transfer bytes to the compositor again.
diff --git a/content/renderer/pepper/pepper_plugin_instance_impl.cc b/content/renderer/pepper/pepper_plugin_instance_impl.cc index 6894654d..27907db 100644 --- a/content/renderer/pepper/pepper_plugin_instance_impl.cc +++ b/content/renderer/pepper/pepper_plugin_instance_impl.cc
@@ -507,7 +507,6 @@ gamepad_impl_(new GamepadImpl()), uma_private_impl_(NULL), plugin_print_interface_(NULL), - plugin_graphics_3d_interface_(NULL), always_on_top_(false), fullscreen_container_(NULL), flash_fullscreen_(false),
diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc index a668699c..263167cf 100644 --- a/content/renderer/render_thread_impl.cc +++ b/content/renderer/render_thread_impl.cc
@@ -1534,24 +1534,11 @@ #if defined(OS_ANDROID) -namespace { -base::LazyInstance<scoped_refptr<StreamTextureFactory>> - g_stream_texture_factory_override; -} - -// static -void RenderThreadImpl::SetStreamTextureFactory( - scoped_refptr<StreamTextureFactory> factory) { - g_stream_texture_factory_override.Get() = factory; -} - scoped_refptr<StreamTextureFactory> RenderThreadImpl::GetStreamTexureFactory() { DCHECK(IsMainThread()); - if (g_stream_texture_factory_override.Get()) { - stream_texture_factory_ = g_stream_texture_factory_override.Get(); - } else if (!stream_texture_factory_.get() || - stream_texture_factory_->ContextGL() - ->GetGraphicsResetStatusKHR() != GL_NO_ERROR) { + if (!stream_texture_factory_.get() || + stream_texture_factory_->ContextGL()->GetGraphicsResetStatusKHR() != + GL_NO_ERROR) { if (!SharedMainThreadContextProvider().get()) { stream_texture_factory_ = NULL; return NULL; @@ -1570,8 +1557,7 @@ } bool RenderThreadImpl::EnableStreamTextureCopy() { - return !g_stream_texture_factory_override.Get() && - sync_compositor_message_filter_.get(); + return sync_compositor_message_filter_.get(); } #endif @@ -2044,7 +2030,8 @@ bool shared_worker_context_provider_lost = false; if (shared_worker_context_provider_) { // Note: If context is lost, delete reference after releasing the lock. - base::AutoLock lock(*shared_worker_context_provider_->GetLock()); + cc::ContextProvider::ScopedContextLock lock( + shared_worker_context_provider_.get()); if (shared_worker_context_provider_->ContextGL() ->GetGraphicsResetStatusKHR() != GL_NO_ERROR) { shared_worker_context_provider_lost = true;
diff --git a/content/renderer/render_thread_impl.h b/content/renderer/render_thread_impl.h index ae69e3b4..2e3304a 100644 --- a/content/renderer/render_thread_impl.h +++ b/content/renderer/render_thread_impl.h
@@ -298,9 +298,6 @@ return sync_compositor_message_filter_.get(); } - static void SetStreamTextureFactory( - scoped_refptr<StreamTextureFactory> factory); - scoped_refptr<StreamTextureFactory> GetStreamTexureFactory(); bool EnableStreamTextureCopy(); #endif @@ -672,7 +669,6 @@ bool is_lcd_text_enabled_; bool is_distance_field_text_enabled_; bool is_zero_copy_enabled_; - bool is_one_copy_enabled_; bool is_gpu_memory_buffer_compositor_resources_enabled_; bool is_partial_raster_enabled_; bool is_elastic_overscroll_enabled_;
diff --git a/content/renderer/render_thread_impl_browsertest.cc b/content/renderer/render_thread_impl_browsertest.cc index 534a324..52367e46 100644 --- a/content/renderer/render_thread_impl_browsertest.cc +++ b/content/renderer/render_thread_impl_browsertest.cc
@@ -183,7 +183,8 @@ thread_ = new RenderThreadImplForTest( InProcessChildThreadParams(test_helper_->GetChannelId(), test_helper_->GetIOTaskRunner(), - test_helper_->GetMessagePipeHandle()), + test_helper_->GetMojoIpcToken(), + test_helper_->GetMojoApplicationToken()), std::move(renderer_scheduler), test_task_counter); cmd->InitFromArgv(old_argv);
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index cb4fa74..2369944 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -1088,14 +1088,16 @@ prefs.resue_global_for_unowned_main_frame); settings->setPreferHiddenVolumeControls(true); settings->setShrinksViewportContentToFit(true); - settings->setUseMobileViewportStyle(true); settings->setAutoplayExperimentMode( blink::WebString::fromUTF8(prefs.autoplay_experiment_mode)); #endif settings->setViewportEnabled(prefs.viewport_enabled); - settings->setLoadWithOverviewMode(prefs.initialize_at_minimum_page_scale); settings->setViewportMetaEnabled(prefs.viewport_meta_enabled); + settings->setViewportStyle( + static_cast<blink::WebViewportStyle>(prefs.viewport_style)); + + settings->setLoadWithOverviewMode(prefs.initialize_at_minimum_page_scale); settings->setMainFrameResizesAreOrientationChanges( prefs.main_frame_resizes_are_orientation_changes);
diff --git a/content/renderer/renderer_blink_platform_impl.cc b/content/renderer/renderer_blink_platform_impl.cc index 83701b1f..61541ea2 100644 --- a/content/renderer/renderer_blink_platform_impl.cc +++ b/content/renderer/renderer_blink_platform_impl.cc
@@ -104,11 +104,6 @@ #include "ui/gfx/color_profile.h" #include "url/gurl.h" -#if defined(OS_ANDROID) -#include "content/renderer/android/synchronous_compositor_factory.h" -#include "gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.h" -#endif - #if defined(OS_MACOSX) #include "content/common/mac/font_descriptor.h" #include "content/common/mac/font_loader.h"
diff --git a/content/renderer/scheduler/resource_dispatch_throttler_unittest.cc b/content/renderer/scheduler/resource_dispatch_throttler_unittest.cc index 35d87a2..0a6c159 100644 --- a/content/renderer/scheduler/resource_dispatch_throttler_unittest.cc +++ b/content/renderer/scheduler/resource_dispatch_throttler_unittest.cc
@@ -191,7 +191,6 @@ std::unique_ptr<ResourceDispatchThrottlerForTest> throttler_; RendererSchedulerForTest scheduler_; int last_request_id_; - bool flush_scheduled_; DISALLOW_COPY_AND_ASSIGN(ResourceDispatchThrottlerTest); };
diff --git a/content/shell/BUILD.gn b/content/shell/BUILD.gn index 31ffc7f..b141202 100644 --- a/content/shell/BUILD.gn +++ b/content/shell/BUILD.gn
@@ -86,8 +86,8 @@ "browser/layout_test/layout_test_resource_dispatcher_host_delegate.h", "browser/layout_test/layout_test_url_request_context_getter.cc", "browser/layout_test/layout_test_url_request_context_getter.h", - "browser/layout_test/notify_done_forwarder.cc", - "browser/layout_test/notify_done_forwarder.h", + "browser/layout_test/secondary_test_window_observer.cc", + "browser/layout_test/secondary_test_window_observer.h", "browser/layout_test/test_info_extractor.cc", "browser/layout_test/test_info_extractor.h", "browser/shell.cc",
diff --git a/content/shell/browser/layout_test/blink_test_controller.cc b/content/shell/browser/layout_test/blink_test_controller.cc index bc7011e..91f7c13 100644 --- a/content/shell/browser/layout_test/blink_test_controller.cc +++ b/content/shell/browser/layout_test/blink_test_controller.cc
@@ -17,6 +17,7 @@ #include "base/logging.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" +#include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/thread_task_runner_handle.h" @@ -44,6 +45,7 @@ #include "content/shell/browser/shell_browser_context.h" #include "content/shell/browser/shell_content_browser_client.h" #include "content/shell/browser/shell_devtools_frontend.h" +#include "content/shell/common/layout_test/layout_test_messages.h" #include "content/shell/common/layout_test/layout_test_switches.h" #include "content/shell/common/shell_messages.h" #include "content/shell/renderer/layout_test/blink_test_helpers.h" @@ -269,6 +271,8 @@ printer_->reset(); frame_to_layout_dump_map_.clear(); render_process_host_observer_.RemoveAll(); + all_observed_render_process_hosts_.clear(); + main_window_render_process_hosts_.clear(); accumulated_layout_test_runtime_flags_changes_.Clear(); ShellBrowserContext* browser_context = ShellContentBrowserClient::Get()->browser_context(); @@ -376,7 +380,7 @@ gfx::Size()); } -void BlinkTestController::TestFinishedInSecondaryRenderer() { +void BlinkTestController::OnTestFinishedInSecondaryRenderer() { RenderViewHost* render_view_host = main_window_->web_contents()->GetRenderViewHost(); render_view_host->Send( @@ -443,8 +447,6 @@ bool handled = true; IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(BlinkTestController, message, render_frame_host) - IPC_MESSAGE_HANDLER(ShellViewHostMsg_LayoutTestRuntimeFlagsChanged, - OnLayoutTestRuntimeFlagsChanged) IPC_MESSAGE_HANDLER(ShellViewHostMsg_LayoutDumpResponse, OnLayoutDumpResponse) IPC_MESSAGE_UNHANDLED(handled = false) @@ -492,6 +494,8 @@ void BlinkTestController::RenderProcessHostDestroyed( RenderProcessHost* render_process_host) { render_process_host_observer_.Remove(render_process_host); + all_observed_render_process_hosts_.erase(render_process_host); + main_window_render_process_hosts_.erase(render_process_host); } void BlinkTestController::RenderProcessExited( @@ -574,40 +578,55 @@ void BlinkTestController::HandleNewRenderFrameHost(RenderFrameHost* frame) { RenderProcessHost* process = frame->GetProcess(); + bool main_window = + WebContents::FromRenderFrameHost(frame) == main_window_->web_contents(); // Track pid of the renderer handling the main frame. - if (frame->GetParent() == nullptr) { + if (main_window && frame->GetParent() == nullptr) { base::ProcessHandle process_handle = process->GetHandle(); if (process_handle != base::kNullProcessHandle) current_pid_ = base::GetProcId(process_handle); } - // Does RenderFrameHost map to a RenderFrame in a previously unknown process? - if (render_process_host_observer_.IsObserving(process)) - return; // No need to do anything more for an already known process. - render_process_host_observer_.Add(process); + // Is this the 1st time this renderer contains parts of the main test window? + if (main_window && !ContainsKey(main_window_render_process_hosts_, process)) { + main_window_render_process_hosts_.insert(process); - // Make sure the new renderer process has a test configuration shared with - // other renderers. - ShellTestConfiguration params; - params.current_working_directory = current_working_directory_; - params.temp_path = temp_path_; - params.test_url = test_url_; - params.enable_pixel_dumping = enable_pixel_dumping_; - params.allow_external_pages = - base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kAllowExternalPages); - params.expected_pixel_hash = expected_pixel_hash_; - params.initial_size = initial_size_; + // Make sure the new renderer process has a test configuration shared with + // other renderers. + ShellTestConfiguration params; + params.current_working_directory = current_working_directory_; + params.temp_path = temp_path_; + params.test_url = test_url_; + params.enable_pixel_dumping = enable_pixel_dumping_; + params.allow_external_pages = + base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kAllowExternalPages); + params.expected_pixel_hash = expected_pixel_hash_; + params.initial_size = initial_size_; - if (did_send_initial_test_configuration_) { - frame->Send(new ShellViewMsg_ReplicateTestConfiguration( - frame->GetRoutingID(), params, + if (did_send_initial_test_configuration_) { + frame->Send(new ShellViewMsg_ReplicateTestConfiguration( + frame->GetRoutingID(), params)); + } else { + did_send_initial_test_configuration_ = true; + frame->Send( + new ShellViewMsg_SetTestConfiguration(frame->GetRoutingID(), params)); + } + } + + // Is this a previously unknown renderer process? + if (!render_process_host_observer_.IsObserving(process)) { + render_process_host_observer_.Add(process); + all_observed_render_process_hosts_.insert(process); + + if (!main_window) { + frame->Send( + new ShellViewMsg_SetupSecondaryRenderer(frame->GetRoutingID())); + } + + process->Send(new LayoutTestMsg_ReplicateLayoutTestRuntimeFlagsChanges( accumulated_layout_test_runtime_flags_changes_)); - } else { - did_send_initial_test_configuration_ = true; - frame->Send( - new ShellViewMsg_SetTestConfiguration(frame->GetRoutingID(), params)); } } @@ -679,29 +698,22 @@ } void BlinkTestController::OnLayoutTestRuntimeFlagsChanged( - RenderFrameHost* sender, + int sender_process_host_id, const base::DictionaryValue& changed_layout_test_runtime_flags) { - // Stash the changes for future renderers. + // Stash the accumulated changes for future, not-yet-created renderers. accumulated_layout_test_runtime_flags_changes_.MergeDictionary( &changed_layout_test_runtime_flags); - // Only need to send the propagation message once per renderer process. - std::set<int> already_covered_process_ids; + // Propagate the changes to all the tracked renderer processes. + for (RenderProcessHost* process : all_observed_render_process_hosts_) { + // Do not propagate the changes back to the process that originated them. + // (propagating them back could also clobber subsequent changes in the + // originator). + if (process->GetID() == sender_process_host_id) + continue; - // No need to propagate the changes back to the process that originated them. - // (propagating them back could also clobber subsequent changes in the - // originator). - already_covered_process_ids.insert(sender->GetProcess()->GetID()); - - // Propagate the changes to all the renderer processes associated with the - // main window. - for (RenderFrameHost* frame : main_window_->web_contents()->GetAllFrames()) { - bool inserted_new_item = - already_covered_process_ids.insert(frame->GetProcess()->GetID()).second; - if (inserted_new_item) { - frame->Send(new ShellViewMsg_ReplicateLayoutTestRuntimeFlagsChanges( - frame->GetRoutingID(), changed_layout_test_runtime_flags)); - } + process->Send(new LayoutTestMsg_ReplicateLayoutTestRuntimeFlagsChanges( + changed_layout_test_runtime_flags)); } }
diff --git a/content/shell/browser/layout_test/blink_test_controller.h b/content/shell/browser/layout_test/blink_test_controller.h index 602438c..50732b7 100644 --- a/content/shell/browser/layout_test/blink_test_controller.h +++ b/content/shell/browser/layout_test/blink_test_controller.h
@@ -8,6 +8,7 @@ #include <map> #include <memory> #include <ostream> +#include <set> #include <string> #include "base/cancelable_callback.h" @@ -133,11 +134,21 @@ // True if the controller was reset successfully. bool ResetAfterLayoutTest(); + // IPC messages forwarded from elsewhere. + void OnLayoutTestRuntimeFlagsChanged( + int sender_process_host_id, + const base::DictionaryValue& changed_layout_test_runtime_flags); + void OnTestFinishedInSecondaryRenderer(); + + // Makes sure that the potentially new renderer associated with |frame| is 1) + // initialized for the test, 2) kept-up-to-date wrt test flags and 3) + // monitored for crashes. + void HandleNewRenderFrameHost(RenderFrameHost* frame); + void SetTempPath(const base::FilePath& temp_path); void RendererUnresponsive(); void OverrideWebkitPrefs(WebPreferences* prefs); void OpenURL(const GURL& url); - void TestFinishedInSecondaryRenderer(); bool IsMainWindow(WebContents* web_contents) const; std::unique_ptr<BluetoothChooser> RunBluetoothChooser( RenderFrameHost* frame, @@ -184,17 +195,12 @@ static BlinkTestController* instance_; void DiscardMainWindow(); - void HandleNewRenderFrameHost( - RenderFrameHost* frame_representing_target_process); // Message handlers. void OnAudioDump(const std::vector<unsigned char>& audio_dump); void OnImageDump(const std::string& actual_pixel_hash, const SkBitmap& image); void OnTextDump(const std::string& dump); void OnInitiateLayoutDump(); - void OnLayoutTestRuntimeFlagsChanged( - RenderFrameHost* sender, - const base::DictionaryValue& changed_layout_test_runtime_flags); void OnLayoutDumpResponse(RenderFrameHost* sender, const std::string& dump); void OnPrintMessage(const std::string& message); void OnOverridePreferences(const WebPreferences& prefs); @@ -266,6 +272,8 @@ // Renderer processes are observed to detect crashes. ScopedObserver<RenderProcessHost, RenderProcessHostObserver> render_process_host_observer_; + std::set<RenderProcessHost*> all_observed_render_process_hosts_; + std::set<RenderProcessHost*> main_window_render_process_hosts_; // Changes reported by OnLayoutTestRuntimeFlagsChanged that have accumulated // since PrepareForLayoutTest (i.e. changes that need to be send to a fresh
diff --git a/content/shell/browser/layout_test/layout_test_devtools_frontend.cc b/content/shell/browser/layout_test/layout_test_devtools_frontend.cc index fb17fca2..9b0064ef 100644 --- a/content/shell/browser/layout_test/layout_test_devtools_frontend.cc +++ b/content/shell/browser/layout_test/layout_test_devtools_frontend.cc
@@ -133,4 +133,15 @@ BlinkTestController::Get()->DevToolsProcessCrashed(); } +void LayoutTestDevToolsFrontend::RenderFrameCreated( + RenderFrameHost* render_frame_host) { + BlinkTestController::Get()->HandleNewRenderFrameHost(render_frame_host); +} + +void LayoutTestDevToolsFrontend::RenderFrameHostChanged( + RenderFrameHost* old_host, + RenderFrameHost* new_host) { + BlinkTestController::Get()->HandleNewRenderFrameHost(new_host); +} + } // namespace content
diff --git a/content/shell/browser/layout_test/layout_test_devtools_frontend.h b/content/shell/browser/layout_test/layout_test_devtools_frontend.h index 839a9a56..8ab36d5 100644 --- a/content/shell/browser/layout_test/layout_test_devtools_frontend.h +++ b/content/shell/browser/layout_test/layout_test_devtools_frontend.h
@@ -41,6 +41,9 @@ // WebContentsObserver implementation. void RenderProcessGone(base::TerminationStatus status) override; + void RenderFrameCreated(RenderFrameHost* render_frame_host) override; + void RenderFrameHostChanged(RenderFrameHost* old_host, + RenderFrameHost* new_host) override; bool ready_for_test_; std::vector<std::pair<int, std::string>> pending_evaluations_;
diff --git a/content/shell/browser/layout_test/layout_test_message_filter.cc b/content/shell/browser/layout_test/layout_test_message_filter.cc index 165c39d..082fc238 100644 --- a/content/shell/browser/layout_test/layout_test_message_filter.cc +++ b/content/shell/browser/layout_test/layout_test_message_filter.cc
@@ -11,6 +11,7 @@ #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/permission_type.h" #include "content/public/test/layouttest_support.h" +#include "content/shell/browser/layout_test/blink_test_controller.h" #include "content/shell/browser/layout_test/layout_test_browser_context.h" #include "content/shell/browser/layout_test/layout_test_content_browser_client.h" #include "content/shell/browser/layout_test/layout_test_notification_manager.h" @@ -46,13 +47,18 @@ void LayoutTestMessageFilter::OverrideThreadForMessage( const IPC::Message& message, BrowserThread::ID* thread) { - if (message.type() == LayoutTestHostMsg_ClearAllDatabases::ID) - *thread = BrowserThread::FILE; - if (message.type() == LayoutTestHostMsg_SimulateWebNotificationClick::ID || - message.type() == LayoutTestHostMsg_SimulateWebNotificationClose::ID || - message.type() == LayoutTestHostMsg_SetPermission::ID || - message.type() == LayoutTestHostMsg_ResetPermissions::ID) - *thread = BrowserThread::UI; + switch (message.type()) { + case LayoutTestHostMsg_ClearAllDatabases::ID: + *thread = BrowserThread::FILE; + break; + case LayoutTestHostMsg_SimulateWebNotificationClick::ID: + case LayoutTestHostMsg_SimulateWebNotificationClose::ID: + case LayoutTestHostMsg_SetPermission::ID: + case LayoutTestHostMsg_ResetPermissions::ID: + case LayoutTestHostMsg_LayoutTestRuntimeFlagsChanged::ID: + *thread = BrowserThread::UI; + break; + } } bool LayoutTestMessageFilter::OnMessageReceived(const IPC::Message& message) { @@ -72,6 +78,8 @@ IPC_MESSAGE_HANDLER(LayoutTestHostMsg_DeleteAllCookies, OnDeleteAllCookies) IPC_MESSAGE_HANDLER(LayoutTestHostMsg_SetPermission, OnSetPermission) IPC_MESSAGE_HANDLER(LayoutTestHostMsg_ResetPermissions, OnResetPermissions) + IPC_MESSAGE_HANDLER(LayoutTestHostMsg_LayoutTestRuntimeFlagsChanged, + OnLayoutTestRuntimeFlagsChanged) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() @@ -179,4 +187,10 @@ ->ResetPermissions(); } +void LayoutTestMessageFilter::OnLayoutTestRuntimeFlagsChanged( + const base::DictionaryValue& changed_layout_test_runtime_flags) { + BlinkTestController::Get()->OnLayoutTestRuntimeFlagsChanged( + render_process_id_, changed_layout_test_runtime_flags); +} + } // namespace content
diff --git a/content/shell/browser/layout_test/layout_test_message_filter.h b/content/shell/browser/layout_test/layout_test_message_filter.h index 1b77a9f..2123acfe 100644 --- a/content/shell/browser/layout_test/layout_test_message_filter.h +++ b/content/shell/browser/layout_test/layout_test_message_filter.h
@@ -15,6 +15,10 @@ class GURL; +namespace base { +class DictionaryValue; +} + namespace net { class URLRequestContextGetter; } @@ -66,6 +70,8 @@ const GURL& origin, const GURL& embedding_origin); void OnResetPermissions(); + void OnLayoutTestRuntimeFlagsChanged( + const base::DictionaryValue& changed_layout_test_runtime_flags); int render_process_id_;
diff --git a/content/shell/browser/layout_test/notify_done_forwarder.cc b/content/shell/browser/layout_test/notify_done_forwarder.cc deleted file mode 100644 index b9213938..0000000 --- a/content/shell/browser/layout_test/notify_done_forwarder.cc +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/shell/browser/layout_test/notify_done_forwarder.h" - -#include "content/shell/browser/layout_test/blink_test_controller.h" -#include "content/shell/common/shell_messages.h" - -namespace content { - -DEFINE_WEB_CONTENTS_USER_DATA_KEY(NotifyDoneForwarder); - -NotifyDoneForwarder::NotifyDoneForwarder(WebContents* web_contents) - : WebContentsObserver(web_contents) {} - -NotifyDoneForwarder::~NotifyDoneForwarder() {} - -bool NotifyDoneForwarder::OnMessageReceived(const IPC::Message& message) { - bool handled = true; - IPC_BEGIN_MESSAGE_MAP(NotifyDoneForwarder, message) - IPC_MESSAGE_HANDLER(ShellViewHostMsg_TestFinishedInSecondaryRenderer, - OnTestFinishedInSecondaryRenderer) - IPC_MESSAGE_UNHANDLED(handled = false) - IPC_END_MESSAGE_MAP() - return handled; -} - -void NotifyDoneForwarder::OnTestFinishedInSecondaryRenderer() { - BlinkTestController::Get()->TestFinishedInSecondaryRenderer(); -} - -} // namespace content
diff --git a/content/shell/browser/layout_test/notify_done_forwarder.h b/content/shell/browser/layout_test/notify_done_forwarder.h deleted file mode 100644 index c512c247..0000000 --- a/content/shell/browser/layout_test/notify_done_forwarder.h +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_SHELL_BROWSER_LAYOUT_TEST_NOTIFY_DONE_FORWARDER_H_ -#define CONTENT_SHELL_BROWSER_LAYOUT_TEST_NOTIFY_DONE_FORWARDER_H_ - -#include "base/macros.h" -#include "content/public/browser/web_contents_observer.h" -#include "content/public/browser/web_contents_user_data.h" - -namespace content { - -class NotifyDoneForwarder : public WebContentsObserver, - public WebContentsUserData<NotifyDoneForwarder> { - public: - ~NotifyDoneForwarder() override; - - // WebContentsObserver implementation. - bool OnMessageReceived(const IPC::Message& message) override; - - private: - friend class WebContentsUserData<NotifyDoneForwarder>; - - explicit NotifyDoneForwarder(WebContents* web_contents); - - void OnTestFinishedInSecondaryRenderer(); - - DISALLOW_COPY_AND_ASSIGN(NotifyDoneForwarder); -}; - -} // namespace content - -#endif // CONTENT_SHELL_BROWSER_LAYOUT_TEST_NOTIFY_DONE_FORWARDER_H_
diff --git a/content/shell/browser/layout_test/secondary_test_window_observer.cc b/content/shell/browser/layout_test/secondary_test_window_observer.cc new file mode 100644 index 0000000..933ce0e --- /dev/null +++ b/content/shell/browser/layout_test/secondary_test_window_observer.cc
@@ -0,0 +1,50 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/shell/browser/layout_test/secondary_test_window_observer.h" + +#include "content/shell/browser/layout_test/blink_test_controller.h" +#include "content/shell/common/shell_messages.h" + +namespace content { + +DEFINE_WEB_CONTENTS_USER_DATA_KEY(SecondaryTestWindowObserver); + +SecondaryTestWindowObserver::SecondaryTestWindowObserver( + WebContents* web_contents) + : WebContentsObserver(web_contents) {} + +SecondaryTestWindowObserver::~SecondaryTestWindowObserver() {} + +bool SecondaryTestWindowObserver::OnMessageReceived( + const IPC::Message& message) { + bool handled = true; + IPC_BEGIN_MESSAGE_MAP(SecondaryTestWindowObserver, message) + IPC_MESSAGE_HANDLER(ShellViewHostMsg_TestFinishedInSecondaryRenderer, + OnTestFinishedInSecondaryRenderer) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + return handled; +} + +void SecondaryTestWindowObserver::OnTestFinishedInSecondaryRenderer() { + BlinkTestController::Get()->OnTestFinishedInSecondaryRenderer(); +} + +void SecondaryTestWindowObserver::RenderFrameCreated( + RenderFrameHost* render_frame_host) { + DCHECK(!BlinkTestController::Get()->IsMainWindow( + WebContents::FromRenderFrameHost(render_frame_host))); + BlinkTestController::Get()->HandleNewRenderFrameHost(render_frame_host); +} + +void SecondaryTestWindowObserver::RenderFrameHostChanged( + RenderFrameHost* old_host, + RenderFrameHost* new_host) { + DCHECK(!BlinkTestController::Get()->IsMainWindow( + WebContents::FromRenderFrameHost(new_host))); + BlinkTestController::Get()->HandleNewRenderFrameHost(new_host); +} + +} // namespace content
diff --git a/content/shell/browser/layout_test/secondary_test_window_observer.h b/content/shell/browser/layout_test/secondary_test_window_observer.h new file mode 100644 index 0000000..b41a95b --- /dev/null +++ b/content/shell/browser/layout_test/secondary_test_window_observer.h
@@ -0,0 +1,38 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_SHELL_BROWSER_LAYOUT_TEST_SECONDARY_TEST_WINDOW_OBSERVER_H_ +#define CONTENT_SHELL_BROWSER_LAYOUT_TEST_SECONDARY_TEST_WINDOW_OBSERVER_H_ + +#include "base/macros.h" +#include "content/public/browser/web_contents_observer.h" +#include "content/public/browser/web_contents_user_data.h" + +namespace content { + +class SecondaryTestWindowObserver + : public WebContentsObserver, + public WebContentsUserData<SecondaryTestWindowObserver> { + public: + ~SecondaryTestWindowObserver() override; + + // WebContentsObserver implementation. + bool OnMessageReceived(const IPC::Message& message) override; + void RenderFrameCreated(RenderFrameHost* render_frame_host) override; + void RenderFrameHostChanged(RenderFrameHost* old_host, + RenderFrameHost* new_host) override; + + private: + friend class WebContentsUserData<SecondaryTestWindowObserver>; + + explicit SecondaryTestWindowObserver(WebContents* web_contents); + + void OnTestFinishedInSecondaryRenderer(); + + DISALLOW_COPY_AND_ASSIGN(SecondaryTestWindowObserver); +}; + +} // namespace content + +#endif // CONTENT_SHELL_BROWSER_LAYOUT_TEST_SECONDARY_TEST_WINDOW_OBSERVER_H_
diff --git a/content/shell/browser/shell.cc b/content/shell/browser/shell.cc index a9053ae..4781834e3 100644 --- a/content/shell/browser/shell.cc +++ b/content/shell/browser/shell.cc
@@ -32,7 +32,7 @@ #include "content/shell/browser/layout_test/layout_test_bluetooth_chooser_factory.h" #include "content/shell/browser/layout_test/layout_test_devtools_frontend.h" #include "content/shell/browser/layout_test/layout_test_javascript_dialog_manager.h" -#include "content/shell/browser/layout_test/notify_done_forwarder.h" +#include "content/shell/browser/layout_test/secondary_test_window_observer.h" #include "content/shell/browser/shell_browser_main_parts.h" #include "content/shell/browser/shell_content_browser_client.h" #include "content/shell/browser/shell_devtools_frontend.h" @@ -252,7 +252,7 @@ bool* was_blocked) { CreateShell(new_contents, AdjustWindowSize(initial_rect.size())); if (switches::IsRunLayoutTestSwitchPresent()) - NotifyDoneForwarder::CreateForWebContents(new_contents); + SecondaryTestWindowObserver::CreateForWebContents(new_contents); } void Shell::GoBackOrForward(int offset) {
diff --git a/content/shell/common/layout_test/layout_test_content_client.cc b/content/shell/common/layout_test/layout_test_content_client.cc index da2e962..404eebf8a 100644 --- a/content/shell/common/layout_test/layout_test_content_client.cc +++ b/content/shell/common/layout_test/layout_test_content_client.cc
@@ -13,7 +13,6 @@ switch (message->type()) { // Used in layout tests; handled in BlinkTestController. case ShellViewHostMsg_PrintMessage::ID: - case ShellViewHostMsg_LayoutTestRuntimeFlagsChanged::ID: return true; default:
diff --git a/content/shell/common/layout_test/layout_test_messages.h b/content/shell/common/layout_test/layout_test_messages.h index 1f420f1..a0fa170 100644 --- a/content/shell/common/layout_test/layout_test_messages.h +++ b/content/shell/common/layout_test/layout_test_messages.h
@@ -42,3 +42,16 @@ GURL /* origin */, GURL /* embedding_origin */) IPC_MESSAGE_ROUTED0(LayoutTestHostMsg_ResetPermissions) + +// Notifies the browser that one of renderers has changed layout test runtime +// flags (i.e. has set dump_as_text). +IPC_MESSAGE_CONTROL1( + LayoutTestHostMsg_LayoutTestRuntimeFlagsChanged, + base::DictionaryValue /* changed_layout_test_runtime_flags */) + +// Used send flag changes to renderers - either when +// 1) broadcasting change happening in one renderer to all other renderers, or +// 2) sending accumulated changes to a single new renderer. +IPC_MESSAGE_CONTROL1( + LayoutTestMsg_ReplicateLayoutTestRuntimeFlagsChanges, + base::DictionaryValue /* changed_layout_test_runtime_flags */)
diff --git a/content/shell/common/shell_messages.h b/content/shell/common/shell_messages.h index f9146b9..248ca20 100644 --- a/content/shell/common/shell_messages.h +++ b/content/shell/common/shell_messages.h
@@ -36,20 +36,19 @@ IPC_MESSAGE_CONTROL1(ShellViewMsg_SetWebKitSourceDir, base::FilePath /* webkit source dir */) -// Sets the test config for a layout test that is being started. +// Sets the test config for a layout test that is being started. This message +// is sent only to a renderer that hosts parts of the main test window. IPC_MESSAGE_ROUTED1(ShellViewMsg_SetTestConfiguration, content::ShellTestConfiguration) -// Replicates test config (for an already started test) to a new renderer. -IPC_MESSAGE_ROUTED2( - ShellViewMsg_ReplicateTestConfiguration, - content::ShellTestConfiguration, - base::DictionaryValue /* accumulated_layout_test_runtime_flags_changes */) +// Replicates test config (for an already started test) to a new renderer +// that hosts parts of the main test window. +IPC_MESSAGE_ROUTED1(ShellViewMsg_ReplicateTestConfiguration, + content::ShellTestConfiguration) -// Used to broadcast changes happening in one renderer to all other renderers. -IPC_MESSAGE_ROUTED1( - ShellViewMsg_ReplicateLayoutTestRuntimeFlagsChanges, - base::DictionaryValue /* changed_layout_test_runtime_flags */) +// Sets up a secondary renderer (renderer that doesn't [yet] host parts of the +// main test window) for a layout test. +IPC_MESSAGE_ROUTED0(ShellViewMsg_SetupSecondaryRenderer) // Tells the main window that a secondary renderer in a different process thinks // the test is finished. @@ -75,12 +74,6 @@ IPC_MESSAGE_ROUTED1(ShellViewMsg_LayoutDumpCompleted, std::string /* completed/stitched layout dump */) -// Notifies the browser that one of renderers has changed layout test runtime -// flags (i.e. has set dump_as_text). -IPC_MESSAGE_ROUTED1( - ShellViewHostMsg_LayoutTestRuntimeFlagsChanged, - base::DictionaryValue /* changed_layout_test_runtime_flags */) - // Send a text dump of the WebContents to the render host. IPC_MESSAGE_ROUTED1(ShellViewHostMsg_TextDump, std::string /* dump */)
diff --git a/content/shell/renderer/layout_test/blink_test_runner.cc b/content/shell/renderer/layout_test/blink_test_runner.cc index 8ebd862..2d49a1e9f 100644 --- a/content/shell/renderer/layout_test/blink_test_runner.cc +++ b/content/shell/renderer/layout_test/blink_test_runner.cc
@@ -529,20 +529,8 @@ if (!is_main_window_) return; - // Message needs to be send via a local frame to eventually reach - // WebContentsObserver via OnMessage(..., RenderFrameHost*) overload - this - // lets BlinkTestController figure out the originator of the message. - RenderFrame* local_frame = nullptr; - for (WebFrame* frame = render_view()->GetWebView()->mainFrame(); frame; - frame = frame->traverseNext(false)) { - if (frame->isWebLocalFrame()) { - local_frame = RenderFrame::FromWebFrame(frame); - break; - } - } - DCHECK(local_frame); - Send(new ShellViewHostMsg_LayoutTestRuntimeFlagsChanged( - local_frame->GetRoutingID(), changed_values)); + RenderThread::Get()->Send( + new LayoutTestHostMsg_LayoutTestRuntimeFlagsChanged(changed_values)); } void BlinkTestRunner::TestFinished() { @@ -744,15 +732,6 @@ void BlinkTestRunner::Navigate(const GURL& url) { focus_on_next_commit_ = true; - if (!is_main_window_ && - LayoutTestRenderThreadObserver::GetInstance()->main_test_runner() == - this) { - test_runner::WebTestInterfaces* interfaces = - LayoutTestRenderThreadObserver::GetInstance()->test_interfaces(); - interfaces->SetTestIsRunning(true); - interfaces->ConfigureForTestWithURL(GURL(), false); - ForceResizeRenderView(render_view(), WebSize(800, 600)); - } } void BlinkTestRunner::DidCommitProvisionalLoad(WebLocalFrame* frame, @@ -904,6 +883,16 @@ return *bluetooth_fake_adapter_setter_; } +void BlinkTestRunner::OnSetupSecondaryRenderer() { + DCHECK(!is_main_window_); + + test_runner::WebTestInterfaces* interfaces = + LayoutTestRenderThreadObserver::GetInstance()->test_interfaces(); + interfaces->SetTestIsRunning(true); + interfaces->ConfigureForTestWithURL(GURL(), false); + ForceResizeRenderView(render_view(), WebSize(800, 600)); +} + void BlinkTestRunner::OnReplicateTestConfiguration( const ShellTestConfiguration& params) { test_config_ = params;
diff --git a/content/shell/renderer/layout_test/blink_test_runner.h b/content/shell/renderer/layout_test/blink_test_runner.h index bf554db..dd622ad5e 100644 --- a/content/shell/renderer/layout_test/blink_test_runner.h +++ b/content/shell/renderer/layout_test/blink_test_runner.h
@@ -170,6 +170,7 @@ // Message handlers forwarded by LayoutTestRenderFrameObserver. void OnSetTestConfiguration(const ShellTestConfiguration& params); void OnReplicateTestConfiguration(const ShellTestConfiguration& params); + void OnSetupSecondaryRenderer(); private: // Message handlers.
diff --git a/content/shell/renderer/layout_test/layout_test_content_renderer_client.cc b/content/shell/renderer/layout_test/layout_test_content_renderer_client.cc index 67cc21d2..2f7fca7 100644 --- a/content/shell/renderer/layout_test/layout_test_content_renderer_client.cc +++ b/content/shell/renderer/layout_test/layout_test_content_renderer_client.cc
@@ -111,8 +111,15 @@ test_runner::WebTestDelegate* delegate = LayoutTestRenderThreadObserver::GetInstance()->test_delegate(); - if (delegate == static_cast<test_runner::WebTestDelegate*>(test_runner)) - LayoutTestRenderThreadObserver::GetInstance()->SetMainWindow(render_view); + if (delegate == static_cast<test_runner::WebTestDelegate*>(test_runner)) { + // TODO(lukasza): Should this instead by done by BlinkTestRunner, + // when it gets notified by the browser that it is the main window? + + // Let test_runner layer know what is the main test window. + LayoutTestRenderThreadObserver::GetInstance() + ->test_interfaces() + ->SetWebView(render_view->GetWebView(), proxy); + } } WebMediaStreamCenter*
diff --git a/content/shell/renderer/layout_test/layout_test_render_frame_observer.cc b/content/shell/renderer/layout_test/layout_test_render_frame_observer.cc index 14bc812..e86a226 100644 --- a/content/shell/renderer/layout_test/layout_test_render_frame_observer.cc +++ b/content/shell/renderer/layout_test/layout_test_render_frame_observer.cc
@@ -32,12 +32,12 @@ bool handled = true; IPC_BEGIN_MESSAGE_MAP(LayoutTestRenderFrameObserver, message) IPC_MESSAGE_HANDLER(ShellViewMsg_LayoutDumpRequest, OnLayoutDumpRequest) - IPC_MESSAGE_HANDLER(ShellViewMsg_ReplicateLayoutTestRuntimeFlagsChanges, - OnReplicateLayoutTestRuntimeFlagsChanges) IPC_MESSAGE_HANDLER(ShellViewMsg_ReplicateTestConfiguration, OnReplicateTestConfiguration) IPC_MESSAGE_HANDLER(ShellViewMsg_SetTestConfiguration, OnSetTestConfiguration) + IPC_MESSAGE_HANDLER(ShellViewMsg_SetupSecondaryRenderer, + OnSetupSecondaryRenderer) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() @@ -53,32 +53,21 @@ Send(new ShellViewHostMsg_LayoutDumpResponse(routing_id(), dump)); } -void LayoutTestRenderFrameObserver::OnReplicateLayoutTestRuntimeFlagsChanges( - const base::DictionaryValue& changed_layout_test_runtime_flags) { - LayoutTestRenderThreadObserver::GetInstance() - ->test_interfaces() - ->TestRunner() - ->ReplicateLayoutTestRuntimeFlagsChanges( - changed_layout_test_runtime_flags); -} - void LayoutTestRenderFrameObserver::OnReplicateTestConfiguration( - const ShellTestConfiguration& test_config, - const base::DictionaryValue& - accumulated_layout_test_runtime_flags_changes) { - LayoutTestRenderThreadObserver::GetInstance() - ->main_test_runner() + const ShellTestConfiguration& test_config) { + BlinkTestRunner::Get(render_frame()->GetRenderView()) ->OnReplicateTestConfiguration(test_config); - - OnReplicateLayoutTestRuntimeFlagsChanges( - accumulated_layout_test_runtime_flags_changes); } void LayoutTestRenderFrameObserver::OnSetTestConfiguration( const ShellTestConfiguration& test_config) { - LayoutTestRenderThreadObserver::GetInstance() - ->main_test_runner() + BlinkTestRunner::Get(render_frame()->GetRenderView()) ->OnSetTestConfiguration(test_config); } +void LayoutTestRenderFrameObserver::OnSetupSecondaryRenderer() { + BlinkTestRunner::Get(render_frame()->GetRenderView()) + ->OnSetupSecondaryRenderer(); +} + } // namespace content
diff --git a/content/shell/renderer/layout_test/layout_test_render_frame_observer.h b/content/shell/renderer/layout_test/layout_test_render_frame_observer.h index 0517faf..3f5da4ae 100644 --- a/content/shell/renderer/layout_test/layout_test_render_frame_observer.h +++ b/content/shell/renderer/layout_test/layout_test_render_frame_observer.h
@@ -30,13 +30,9 @@ private: void OnLayoutDumpRequest(); - void OnReplicateLayoutTestRuntimeFlagsChanges( - const base::DictionaryValue& changed_layout_test_runtime_flags); void OnSetTestConfiguration(const ShellTestConfiguration& test_config); - void OnReplicateTestConfiguration( - const ShellTestConfiguration& test_config, - const base::DictionaryValue& - accumulated_layout_test_runtime_flags_changes); + void OnReplicateTestConfiguration(const ShellTestConfiguration& test_config); + void OnSetupSecondaryRenderer(); DISALLOW_COPY_AND_ASSIGN(LayoutTestRenderFrameObserver); };
diff --git a/content/shell/renderer/layout_test/layout_test_render_thread_observer.cc b/content/shell/renderer/layout_test/layout_test_render_thread_observer.cc index 5974f33..de9c6631 100644 --- a/content/shell/renderer/layout_test/layout_test_render_thread_observer.cc +++ b/content/shell/renderer/layout_test/layout_test_render_thread_observer.cc
@@ -5,20 +5,19 @@ #include "content/shell/renderer/layout_test/layout_test_render_thread_observer.h" #include "base/command_line.h" -#include "components/test_runner/event_sender.h" #include "components/test_runner/test_interfaces.h" #include "components/test_runner/web_test_interfaces.h" +#include "components/test_runner/web_test_runner.h" #include "content/common/input/input_event_utils.h" #include "content/public/common/content_client.h" #include "content/public/renderer/render_thread.h" -#include "content/public/renderer/render_view.h" #include "content/public/test/layouttest_support.h" +#include "content/shell/common/layout_test/layout_test_messages.h" #include "content/shell/common/layout_test/layout_test_switches.h" #include "content/shell/common/shell_messages.h" #include "content/shell/renderer/layout_test/blink_test_runner.h" #include "third_party/WebKit/public/web/WebKit.h" #include "third_party/WebKit/public/web/WebRuntimeFeatures.h" -#include "third_party/WebKit/public/web/WebView.h" #include "v8/include/v8.h" using blink::WebFrame; @@ -37,8 +36,7 @@ } LayoutTestRenderThreadObserver::LayoutTestRenderThreadObserver() - : main_test_runner_(NULL), - test_delegate_(NULL) { + : test_delegate_(nullptr) { CHECK(!g_instance); g_instance = this; RenderThread::Get()->AddObserver(this); @@ -77,12 +75,6 @@ test_delegate_ = delegate; } -void LayoutTestRenderThreadObserver::SetMainWindow(RenderView* view) { - BlinkTestRunner* test_runner = BlinkTestRunner::Get(view); - test_interfaces_->SetWebView(view->GetWebView(), test_runner->proxy()); - main_test_runner_ = test_runner; -} - void LayoutTestRenderThreadObserver::OnRenderProcessShutdown() { test_interfaces_.reset(); } @@ -92,6 +84,8 @@ bool handled = true; IPC_BEGIN_MESSAGE_MAP(LayoutTestRenderThreadObserver, message) IPC_MESSAGE_HANDLER(ShellViewMsg_SetWebKitSourceDir, OnSetWebKitSourceDir) + IPC_MESSAGE_HANDLER(LayoutTestMsg_ReplicateLayoutTestRuntimeFlagsChanges, + OnReplicateLayoutTestRuntimeFlagsChanges) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() @@ -103,4 +97,10 @@ webkit_source_dir_ = webkit_source_dir; } +void LayoutTestRenderThreadObserver::OnReplicateLayoutTestRuntimeFlagsChanges( + const base::DictionaryValue& changed_layout_test_runtime_flags) { + test_interfaces()->TestRunner()->ReplicateLayoutTestRuntimeFlagsChanges( + changed_layout_test_runtime_flags); +} + } // namespace content
diff --git a/content/shell/renderer/layout_test/layout_test_render_thread_observer.h b/content/shell/renderer/layout_test/layout_test_render_thread_observer.h index 945a420..305eb625 100644 --- a/content/shell/renderer/layout_test/layout_test_render_thread_observer.h +++ b/content/shell/renderer/layout_test/layout_test_render_thread_observer.h
@@ -13,6 +13,10 @@ #include "content/public/renderer/render_thread_observer.h" #include "ipc/ipc_platform_file.h" +namespace base { +class DictionaryValue; +} + namespace blink { class WebFrame; } @@ -24,9 +28,6 @@ namespace content { -class RenderView; -class BlinkTestRunner; - class LayoutTestRenderThreadObserver : public RenderThreadObserver { public: static LayoutTestRenderThreadObserver* GetInstance(); @@ -35,7 +36,6 @@ ~LayoutTestRenderThreadObserver() override; void SetTestDelegate(test_runner::WebTestDelegate* delegate); - void SetMainWindow(RenderView* view); // RenderThreadObserver implementation. void OnRenderProcessShutdown() override; @@ -47,14 +47,14 @@ test_runner::WebTestInterfaces* test_interfaces() const { return test_interfaces_.get(); } - BlinkTestRunner* main_test_runner() const { return main_test_runner_; } const base::FilePath& webkit_source_dir() const { return webkit_source_dir_; } private: // Message handlers. void OnSetWebKitSourceDir(const base::FilePath& webkit_source_dir); + void OnReplicateLayoutTestRuntimeFlagsChanges( + const base::DictionaryValue& changed_layout_test_runtime_flags); - BlinkTestRunner* main_test_runner_; test_runner::WebTestDelegate* test_delegate_; std::unique_ptr<test_runner::WebTestInterfaces> test_interfaces_;
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 989c6c3a..7cdd4d83 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -54,6 +54,7 @@ "//components/scheduler:test_support", "//content/app:both_for_content_tests", "//content/browser/speech/proto", + "//content/child:for_content_tests", "//content/gpu", "//content/public/browser", "//content/public/child", @@ -651,6 +652,7 @@ "//content/browser/notifications:notification_proto", "//content/browser/service_worker:service_worker_proto", "//content/browser/speech/proto", + "//content/child:for_content_tests", "//content/common:mojo_bindings", "//content/gpu", "//content/public/browser", @@ -804,7 +806,6 @@ "../browser/geolocation/network_location_provider_unittest.cc", "../browser/geolocation/wifi_data_provider_common_unittest.cc", "../browser/power_usage_monitor_impl_unittest.cc", - "../browser/renderer_host/begin_frame_observer_proxy_unittest.cc", "../browser/webui/url_data_manager_backend_unittest.cc", ] deps -= [ "//device/battery" ] @@ -915,6 +916,7 @@ sources = [ "../browser/compositor/gl_helper_unittest.cc", + "../browser/compositor/yuv_readback_unittest.cc", "../common/gpu/client/gpu_context_tests.h", "../common/gpu/client/gpu_in_process_context_tests.cc", "run_all_gl_tests.cc",
diff --git a/content/test/gpu/gpu_tests/__init__.py b/content/test/gpu/gpu_tests/__init__.py index 4ce924f..fe6cb71f 100644 --- a/content/test/gpu/gpu_tests/__init__.py +++ b/content/test/gpu/gpu_tests/__init__.py
@@ -1,27 +1,5 @@ # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -"""A library for Chrome GPU test code.""" -import os -import sys -def Init(): - chromium_src_dir = os.path.abspath(os.path.join( - os.path.dirname(__file__), '..', '..', '..', '..')) - - perf_path = os.path.join(chromium_src_dir, 'tools', 'perf') - absolute_perf_path = os.path.abspath(perf_path) - - sys.path.append(absolute_perf_path) - from chrome_telemetry_build import chromium_config - - telemetry_path = chromium_config.GetTelemetryDir() - if telemetry_path not in sys.path: - sys.path.append(telemetry_path) - - catapult_base_path = os.path.join( - chromium_src_dir, 'third_party', 'catapult', 'catapult_base') - if catapult_base_path not in sys.path: - sys.path.append(catapult_base_path) - -Init() +# Empty file so Python treats this directory as a package.
diff --git a/content/test/gpu/gpu_tests/path_util.py b/content/test/gpu/gpu_tests/path_util.py index 1a43269..e178d76 100644 --- a/content/test/gpu/gpu_tests/path_util.py +++ b/content/test/gpu/gpu_tests/path_util.py
@@ -19,3 +19,22 @@ path = os.path.abspath(os.path.join(*path_parts)) if os.path.isdir(path) and path not in sys.path: sys.path.append(path) + + +def SetupTelemetryPaths(): + chromium_src_dir = GetChromiumSrcDir() + + perf_path = os.path.join(chromium_src_dir, 'tools', 'perf') + absolute_perf_path = os.path.abspath(perf_path) + + sys.path.append(absolute_perf_path) + from chrome_telemetry_build import chromium_config + + telemetry_path = chromium_config.GetTelemetryDir() + if telemetry_path not in sys.path: + sys.path.append(telemetry_path) + + catapult_base_path = os.path.join( + chromium_src_dir, 'third_party', 'catapult', 'catapult_base') + if catapult_base_path not in sys.path: + sys.path.append(catapult_base_path)
diff --git a/content/test/gpu/run_gpu_test.py b/content/test/gpu/run_gpu_test.py index 9927f98..aab3f8d5 100755 --- a/content/test/gpu/run_gpu_test.py +++ b/content/test/gpu/run_gpu_test.py
@@ -9,8 +9,8 @@ import sys from gpu_tests import path_util -path_util.AddDirToPathIfNeeded(path_util.GetChromiumSrcDir(), 'tools', - 'telemetry') + +path_util.SetupTelemetryPaths() from telemetry import benchmark_runner
diff --git a/content/test/gpu/run_unittests.py b/content/test/gpu/run_unittests.py index b874ce7..30452b8 100755 --- a/content/test/gpu/run_unittests.py +++ b/content/test/gpu/run_unittests.py
@@ -11,10 +11,10 @@ import sys from gpu_tests import path_util -import gpu_project_config -path_util.AddDirToPathIfNeeded(path_util.GetChromiumSrcDir(), 'tools', - 'telemetry') +path_util.SetupTelemetryPaths() + +import gpu_project_config from telemetry.testing import unittest_runner
diff --git a/content/test/render_thread_impl_browser_test_ipc_helper.cc b/content/test/render_thread_impl_browser_test_ipc_helper.cc index 241ec1c..11f0851 100644 --- a/content/test/render_thread_impl_browser_test_ipc_helper.cc +++ b/content/test/render_thread_impl_browser_test_ipc_helper.cc
@@ -4,8 +4,8 @@ #include "content/test/render_thread_impl_browser_test_ipc_helper.h" -#include "content/common/mojo/channel_init.h" #include "content/public/common/mojo_channel_switches.h" +#include "mojo/edk/embedder/embedder.h" #include "testing/gtest/include/gtest/gtest.h" namespace content { @@ -48,18 +48,15 @@ ipc_support_.reset(new IPC::ScopedIPCSupport(ipc_thread_->task_runner())); mojo_application_host_.reset(new MojoApplicationHost()); - mojo_application_host_->OverrideIOTaskRunnerForTest( - ipc_thread_->task_runner()); + mojo_application_token_ = mojo_application_host_->GetToken(); + + mojo_ipc_token_ = mojo::edk::GenerateRandomToken(); mojo::MessagePipe pipe; channel_ = IPC::ChannelProxy::Create( - IPC::ChannelMojo::CreateServerFactory(std::move(pipe.handle0)), + IPC::ChannelMojo::CreateServerFactory( + mojo::edk::CreateParentMessagePipe(mojo_ipc_token_)), dummy_listener_.get(), ipc_thread_->task_runner()); - message_pipe_handle_ = std::move(pipe.handle1); - - mojo_application_host_->Init(); - mojo_application_host_->Activate(channel_.get(), - base::GetCurrentProcessHandle()); } scoped_refptr<base::SingleThreadTaskRunner>
diff --git a/content/test/render_thread_impl_browser_test_ipc_helper.h b/content/test/render_thread_impl_browser_test_ipc_helper.h index 8420d6a..f98824b 100644 --- a/content/test/render_thread_impl_browser_test_ipc_helper.h +++ b/content/test/render_thread_impl_browser_test_ipc_helper.h
@@ -7,7 +7,6 @@ #include "content/app/mojo/mojo_init.h" #include "content/browser/mojo/mojo_application_host.h" -#include "content/common/mojo/mojo_messages.h" #include "ipc/ipc_channel_proxy.h" #include "ipc/mojo/ipc_channel_mojo.h" #include "ipc/mojo/scoped_ipc_support.h" @@ -34,8 +33,12 @@ scoped_refptr<base::SingleThreadTaskRunner> GetIOTaskRunner() const; - mojo::MessagePipeHandle GetMessagePipeHandle() { - return message_pipe_handle_.release(); + const std::string& GetMojoIpcToken() const { + return mojo_ipc_token_; + } + + const std::string& GetMojoApplicationToken() const { + return mojo_application_token_; } private: @@ -50,7 +53,8 @@ std::unique_ptr<DummyListener> dummy_listener_; std::unique_ptr<IPC::ScopedIPCSupport> ipc_support_; std::unique_ptr<MojoApplicationHost> mojo_application_host_; - mojo::ScopedMessagePipeHandle message_pipe_handle_; + std::string mojo_ipc_token_; + std::string mojo_application_token_; std::string channel_id_; };
diff --git a/content/test/web_contents_observer_sanity_checker.cc b/content/test/web_contents_observer_sanity_checker.cc index 5290e191..47415357 100644 --- a/content/test/web_contents_observer_sanity_checker.cc +++ b/content/test/web_contents_observer_sanity_checker.cc
@@ -328,6 +328,7 @@ web_contents_destroyed_ = true; CHECK(ongoing_navigations_.empty()); CHECK(active_media_players_.empty()); + CHECK(live_routes_.empty()); } void WebContentsObserverSanityChecker::DidStartLoading() {
diff --git a/docs/chromeos_build_instructions.md b/docs/chromeos_build_instructions.md index 2638b2a..8eac95e 100644 --- a/docs/chromeos_build_instructions.md +++ b/docs/chromeos_build_instructions.md
@@ -12,25 +12,42 @@ instructions](https://chromium.googlesource.com/chromium/src/+/master/docs/linux_build_instructions.md) as usual to get a Chromium checkout. -## Running Chromium on your local machine +## Building and running Chromium with Chromium OS UI on your local machine If you plan to test the Chromium build on your dev machine and not a -Chromium OS device run: +Chromium OS device, run the following in your chromium checkout: -```shell -export GYP_DEFINES="chromeos=1" -gclient runhooks + $ gn gen out/Default --args='target_os="chromeos"' + $ ninja -C out/Default + +NOTE: You may wish to replace 'Default' with something like 'Cros' if +you switch back and forth between Linux and Chromium OS builds, or 'Debug' +if you want to differentiate between Debug and Release builds (see below) +or DebugCros or whatever you like. + +Now, when you build, you will build with Chromium OS features turned on. + +See [GN Build Configuration](https://www.chromium.org/developers/gn-build-configuration) +for more information about configuring your build. + +Some additional options you may wish to set: +``` + is_component_build = true + use_goma = true + is_debug = false # Release build + dcheck_always_on = true # Enable DCHECK (with is_debug = false) + is_official_build = true + is_chrome_branded = true ``` -Now, once you build, you will build with Chromium OS features turned on. - -### Notes +## Notes When you build Chromium OS Chromium, you'll be using the TOOLKIT\_VIEWS front-end just like Windows, so the files you'll probably want are in src/ui/views and src/chrome/browser/ui/views. -If chromeos=1 is specified, then toolkit\_views=0 must not be specified. +When target_os = "chromeos", then toolkit\_views need not (and should not) +be specified. The Chromium OS build requires a functioning GL so if you plan on testing it through Chromium Remote Desktop you might face drawing @@ -41,9 +58,6 @@ osmesa yourself. * ... or just don't use Remote Desktop. :) -Note the underscore in the GYP_DEFINES variable name, as people -sometimes mistakenly write it GYPDEFINES. - To more closely match the UI used on devices, you can install fonts used by Chrome OS, such as Roboto, on your Linux distro. @@ -62,43 +76,7 @@ Signing in as a specific user is useful for debugging features like sync that require a logged in user. -### Compile Testing Chromium with the Chromium OS SDK (quick version) +## Compile Testing Chromium with the Chromium OS SDK (quick version) -Note: These instructions are intended for Chromium developers trying to -diagnose compile issues on Chromium OS, which can block changes in the -CQ. See the [full -documentation](http://www.chromium.org/chromium-os/how-tos-and-troubleshooting/building-chromium-browser) -for more information about building & testing chromium for Chromium OS. - -To do a build of Chromium that can run on Chromium OS itself, the Chromium OS -SDK must be used. The SDK provides all of chromium's dependencies as they are -distributed with Chromium OS (as opposed to other distributions such as Ubuntu). - -To enter the SDK build environment, run the following command (replace the value -of the `--board` flag with the name of the configuration you want to test). - -```shell -cros chrome-sdk --board=amd64-generic --use-external-config -``` - -Once in the SDK build environment, build using the normal linux workflow (except -for a different build directory): - -```shell -gclient runhooks -ninja -C out_amd64-generic/Release chromium_builder_tests -``` - -The current configurations verified by the CQ are: - - Board Flag | Build Directory | CPU architecture - --- | --- | --- - amd64-generic | out_amd64-generic | 64-bit Intel - x86-generic | out_x86-generic | 32-bit Intel - daisy | out_daisy | 32-bit ARM - -## Running Chromium on a Chromium OS device - -Look at the [Chromium OS -documentation](http://www.chromium.org/chromium-os/how-tos-and-troubleshooting/building-chromium-browser) -for the official flow for doing this. +See [Building Chromium for a Chromium OS device](https://www.chromium.org/chromium-os/how-tos-and-troubleshooting/building-chromium-browser) +for information about building & testing chromium for Chromium OS.
diff --git a/extensions/common/user_script.h b/extensions/common/user_script.h index 40ad3303..d6b3377 100644 --- a/extensions/common/user_script.h +++ b/extensions/common/user_script.h
@@ -220,8 +220,6 @@ bool is_incognito_enabled() const { return incognito_enabled_; } void set_incognito_enabled(bool enabled) { incognito_enabled_ = enabled; } - bool is_standalone() const { return extension_id().empty(); } - // Returns true if the script should be applied to the specified URL, false // otherwise. bool MatchesURL(const GURL& url) const;
diff --git a/extensions/renderer/user_script_injector.cc b/extensions/renderer/user_script_injector.cc index 9885b4e..b1218d50e 100644 --- a/extensions/renderer/user_script_injector.cc +++ b/extensions/renderer/user_script_injector.cc
@@ -195,19 +195,15 @@ std::vector<blink::WebScriptSource> sources; const UserScript::FileList& js_scripts = script_->js_scripts(); - bool is_standalone_or_emulate_greasemonkey = - script_->is_standalone() || script_->emulate_greasemonkey(); for (UserScript::FileList::const_iterator iter = js_scripts.begin(); iter != js_scripts.end(); ++iter) { std::string content = iter->GetContent().as_string(); - // We add this dumb function wrapper for standalone user script to - // emulate what Greasemonkey does. - // TODO(aa): I think that maybe "is_standalone" scripts don't exist - // anymore. Investigate. - if (is_standalone_or_emulate_greasemonkey) { + // We add this dumb function wrapper for user scripts to emulate what + // Greasemonkey does. + if (script_->emulate_greasemonkey()) { content.insert(0, kUserScriptHead); content += kUserScriptTail; } @@ -215,9 +211,9 @@ blink::WebString::fromUTF8(content), iter->url())); } - // Emulate Greasemonkey API for scripts that were converted to extensions - // and "standalone" user scripts. - if (is_standalone_or_emulate_greasemonkey) + // Emulate Greasemonkey API for scripts that were converted to extension + // user scripts. + if (script_->emulate_greasemonkey()) sources.insert(sources.begin(), g_greasemonkey_api.Get().GetSource()); return sources;
diff --git a/google_apis/BUILD.gn b/google_apis/BUILD.gn index 197ccfb..4cf9fe4 100644 --- a/google_apis/BUILD.gn +++ b/google_apis/BUILD.gn
@@ -216,17 +216,6 @@ } } -bundle_data("google_apis_unittests_bundle_data") { - testonly = true - sources = [ - "test", - ] - outputs = [ - "{{bundle_resources_dir}}/" + - "{{source_root_relative_dir}}/{{source_file_part}}", - ] -} - test("google_apis_unittests") { sources = [ "gaia/gaia_auth_fetcher_unittest.cc", @@ -250,7 +239,6 @@ deps = [ ":google_apis", - ":google_apis_unittests_bundle_data", ":test_support", "//base", "//base/test:run_all_unittests",
diff --git a/gpu/BUILD.gn b/gpu/BUILD.gn index 1b96799..da3bb21 100644 --- a/gpu/BUILD.gn +++ b/gpu/BUILD.gn
@@ -57,8 +57,6 @@ # TODO(hendrikw): Move egl out of gles2_conform_support. "gles2_conform_support/egl/config.cc", "gles2_conform_support/egl/config.h", - "gles2_conform_support/egl/context.cc", - "gles2_conform_support/egl/context.h", "gles2_conform_support/egl/display.cc", "gles2_conform_support/egl/display.h", "gles2_conform_support/egl/egl.cc", @@ -66,8 +64,6 @@ "gles2_conform_support/egl/surface.h", "gles2_conform_support/egl/test_support.cc", "gles2_conform_support/egl/test_support.h", - "gles2_conform_support/egl/thread_state.cc", - "gles2_conform_support/egl/thread_state.h", ] deps = [ @@ -75,7 +71,6 @@ "//base", "//gpu/command_buffer/client:gles2_c_lib", "//gpu/command_buffer/client:gles2_implementation", - "//gpu/command_buffer/common:gles2_utils", "//ui/gl:gl", ]
diff --git a/gpu/blink/BUILD.gn b/gpu/blink/BUILD.gn index 8bb98b1..1c446c9 100644 --- a/gpu/blink/BUILD.gn +++ b/gpu/blink/BUILD.gn
@@ -10,8 +10,6 @@ "gpu_blink_export.h", "webgraphicscontext3d_impl.cc", "webgraphicscontext3d_impl.h", - "webgraphicscontext3d_in_process_command_buffer_impl.cc", - "webgraphicscontext3d_in_process_command_buffer_impl.h", ] # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.
diff --git a/gpu/blink/gpu_blink.gyp b/gpu/blink/gpu_blink.gyp index 06a7c122..a1d3cb5 100644 --- a/gpu/blink/gpu_blink.gyp +++ b/gpu/blink/gpu_blink.gyp
@@ -35,8 +35,6 @@ 'gpu_blink_export.h', 'webgraphicscontext3d_impl.cc', 'webgraphicscontext3d_impl.h', - 'webgraphicscontext3d_in_process_command_buffer_impl.cc', - 'webgraphicscontext3d_in_process_command_buffer_impl.h', ], 'defines': [ 'GPU_BLINK_IMPLEMENTATION',
diff --git a/gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.cc b/gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.cc deleted file mode 100644 index 29de128..0000000 --- a/gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.cc +++ /dev/null
@@ -1,130 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.h" - -#include <GLES2/gl2.h> -#include <utility> -#ifndef GL_GLEXT_PROTOTYPES -#define GL_GLEXT_PROTOTYPES 1 -#endif -#include <GLES2/gl2ext.h> -#include <GLES2/gl2extchromium.h> -#include <stddef.h> - -#include <string> - -#include "base/atomicops.h" -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/callback.h" -#include "base/logging.h" -#include "gpu/command_buffer/client/gles2_implementation.h" -#include "gpu/command_buffer/common/gles2_cmd_utils.h" -#include "gpu/skia_bindings/gl_bindings_skia_cmd_buffer.h" -#include "ui/gfx/geometry/size.h" -#include "ui/gl/gl_implementation.h" - -using gpu::gles2::GLES2Implementation; -using gpu::GLInProcessContext; - -namespace gpu_blink { - -// static -scoped_ptr<WebGraphicsContext3DInProcessCommandBufferImpl> -WebGraphicsContext3DInProcessCommandBufferImpl::CreateOffscreenContext( - const gpu::gles2::ContextCreationAttribHelper& attributes) { - bool is_offscreen = true; - return make_scoped_ptr(new WebGraphicsContext3DInProcessCommandBufferImpl( - scoped_ptr<::gpu::GLInProcessContext>(), attributes, is_offscreen, - gfx::kNullAcceleratedWidget)); -} - -scoped_ptr<WebGraphicsContext3DInProcessCommandBufferImpl> -WebGraphicsContext3DInProcessCommandBufferImpl::WrapContext( - scoped_ptr<::gpu::GLInProcessContext> context, - const gpu::gles2::ContextCreationAttribHelper& attributes) { - bool is_offscreen = true; // Not used. - gfx::AcceleratedWidget window = gfx::kNullAcceleratedWidget; // Not used. - return make_scoped_ptr(new WebGraphicsContext3DInProcessCommandBufferImpl( - std::move(context), attributes, is_offscreen, window)); -} - -WebGraphicsContext3DInProcessCommandBufferImpl:: - WebGraphicsContext3DInProcessCommandBufferImpl( - scoped_ptr<::gpu::GLInProcessContext> context, - const gpu::gles2::ContextCreationAttribHelper& attributes, - bool is_offscreen, - gfx::AcceleratedWidget window) - : attributes_(attributes), - is_offscreen_(is_offscreen), - window_(window), - context_(std::move(context)) {} - -WebGraphicsContext3DInProcessCommandBufferImpl:: - ~WebGraphicsContext3DInProcessCommandBufferImpl() { - if (real_gl_) - real_gl_->SetLostContextCallback(base::Closure()); -} - -size_t WebGraphicsContext3DInProcessCommandBufferImpl::GetMappedMemoryLimit() { - return context_->GetMappedMemoryLimit(); -} - -bool WebGraphicsContext3DInProcessCommandBufferImpl::MaybeInitializeGL() { - if (initialized_) - return true; - - if (initialize_failed_) - return false; - - if (!context_) { - // TODO(kbr): More work will be needed in this implementation to - // properly support GPU switching. Like in the out-of-process - // command buffer implementation, all previously created contexts - // will need to be lost either when the first context requesting the - // discrete GPU is created, or the last one is destroyed. - gfx::GpuPreference gpu_preference = gfx::PreferDiscreteGpu; - context_.reset(GLInProcessContext::Create( - NULL, /* service */ - NULL, /* surface */ - is_offscreen_, window_, gfx::Size(1, 1), NULL, /* share_context */ - attributes_, gpu_preference, - ::gpu::GLInProcessContextSharedMemoryLimits(), nullptr, nullptr)); - } - - if (!context_) { - initialize_failed_ = true; - return false; - } - - real_gl_ = context_->GetImplementation(); - SetGLInterface(real_gl_); - - real_gl_->TraceBeginCHROMIUM("WebGraphicsContext3D", - "InProcessContext"); - - initialized_ = true; - return true; -} - -bool -WebGraphicsContext3DInProcessCommandBufferImpl::InitializeOnCurrentThread() { - if (!MaybeInitializeGL()) - return false; - return context_ && - context_->GetImplementation()->GetGraphicsResetStatusKHR() == - GL_NO_ERROR; -} - -void WebGraphicsContext3DInProcessCommandBufferImpl::SetLock(base::Lock* lock) { - context_->SetLock(lock); -} - -::gpu::ContextSupport* -WebGraphicsContext3DInProcessCommandBufferImpl::GetContextSupport() { - return real_gl_; -} - -} // namespace gpu_blink
diff --git a/gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.h b/gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.h deleted file mode 100644 index 2dd275d..0000000 --- a/gpu/blink/webgraphicscontext3d_in_process_command_buffer_impl.h +++ /dev/null
@@ -1,91 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef GPU_BLINK_WEBGRAPHICSCONTEXT3D_IN_PROCESS_COMMAND_BUFFER_IMPL_H_ -#define GPU_BLINK_WEBGRAPHICSCONTEXT3D_IN_PROCESS_COMMAND_BUFFER_IMPL_H_ - -#include <stddef.h> - -#include <vector> - -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "gpu/blink/gpu_blink_export.h" -#include "gpu/blink/webgraphicscontext3d_impl.h" -#include "gpu/command_buffer/client/gl_in_process_context.h" -#include "third_party/WebKit/public/platform/WebGraphicsContext3D.h" -#include "third_party/WebKit/public/platform/WebString.h" -#include "ui/gfx/native_widget_types.h" - -namespace gpu { -class ContextSupport; -class GLInProcessContext; - -namespace gles2 { -class GLES2Interface; -class GLES2Implementation; -struct ContextCreationAttribHelper; -} -} - -namespace gpu_blink { - -class GPU_BLINK_EXPORT WebGraphicsContext3DInProcessCommandBufferImpl - : public WebGraphicsContext3DImpl { - public: - enum MappedMemoryReclaimLimit { - kNoLimit = 0, - }; - - static scoped_ptr<WebGraphicsContext3DInProcessCommandBufferImpl> - CreateOffscreenContext( - const gpu::gles2::ContextCreationAttribHelper& attributes); - - static scoped_ptr<WebGraphicsContext3DInProcessCommandBufferImpl> WrapContext( - scoped_ptr<::gpu::GLInProcessContext> context, - const gpu::gles2::ContextCreationAttribHelper& attributes); - - ~WebGraphicsContext3DInProcessCommandBufferImpl() override; - - size_t GetMappedMemoryLimit(); - - bool InitializeOnCurrentThread(); - void SetLock(base::Lock* lock); - - ::gpu::ContextSupport* GetContextSupport(); - - ::gpu::gles2::GLES2Implementation* GetImplementation() { - return real_gl_; - } - - private: - WebGraphicsContext3DInProcessCommandBufferImpl( - scoped_ptr<::gpu::GLInProcessContext> context, - const gpu::gles2::ContextCreationAttribHelper& attributes, - bool is_offscreen, - gfx::AcceleratedWidget window); - - void OnContextLost(); - - bool MaybeInitializeGL(); - - // Used to try to find bugs in code that calls gl directly through the gl api - // instead of going through WebGraphicsContext3D. - void ClearContext(); - - ::gpu::gles2::ContextCreationAttribHelper attributes_; - - bool is_offscreen_; - // Only used when not offscreen. - gfx::AcceleratedWidget window_; - - // The context we use for OpenGL rendering. - scoped_ptr< ::gpu::GLInProcessContext> context_; - // The GLES2Implementation we use for OpenGL rendering. - ::gpu::gles2::GLES2Implementation* real_gl_; -}; - -} // namespace gpu_blink - -#endif // GPU_BLINK_WEBGRAPHICSCONTEXT3D_IN_PROCESS_COMMAND_BUFFER_IMPL_H_
diff --git a/gpu/command_buffer/client/gl_in_process_context.cc b/gpu/command_buffer/client/gl_in_process_context.cc index ece3715..6f2fb0d 100644 --- a/gpu/command_buffer/client/gl_in_process_context.cc +++ b/gpu/command_buffer/client/gl_in_process_context.cc
@@ -71,12 +71,6 @@ size_t GetMappedMemoryLimit() override; void SetLock(base::Lock* lock) override; -#if defined(OS_ANDROID) - scoped_refptr<gfx::SurfaceTexture> GetSurfaceTexture( - uint32_t stream_id) override; - uint32_t CreateStreamTexture(uint32_t texture_id) override; -#endif - private: void Destroy(); void OnSignalSyncPoint(const base::Closure& callback); @@ -207,17 +201,6 @@ command_buffer_.reset(); } -#if defined(OS_ANDROID) -scoped_refptr<gfx::SurfaceTexture> GLInProcessContextImpl::GetSurfaceTexture( - uint32_t stream_id) { - return command_buffer_->GetSurfaceTexture(stream_id); -} - -uint32_t GLInProcessContextImpl::CreateStreamTexture(uint32_t texture_id) { - return command_buffer_->CreateStreamTexture(texture_id); -} -#endif - } // anonymous namespace GLInProcessContextSharedMemoryLimits::GLInProcessContextSharedMemoryLimits()
diff --git a/gpu/command_buffer/client/gl_in_process_context.h b/gpu/command_buffer/client/gl_in_process_context.h index 8a78f8e..eab98b2 100644 --- a/gpu/command_buffer/client/gl_in_process_context.h +++ b/gpu/command_buffer/client/gl_in_process_context.h
@@ -75,12 +75,6 @@ virtual size_t GetMappedMemoryLimit() = 0; virtual void SetLock(base::Lock* lock) = 0; - -#if defined(OS_ANDROID) - virtual scoped_refptr<gfx::SurfaceTexture> GetSurfaceTexture( - uint32_t stream_id) = 0; - virtual uint32_t CreateStreamTexture(uint32_t texture_id) = 0; -#endif }; } // namespace gpu
diff --git a/gpu/command_buffer/common/capabilities.cc b/gpu/command_buffer/common/capabilities.cc index 23d1abb..11dbcc8 100644 --- a/gpu/command_buffer/common/capabilities.cc +++ b/gpu/command_buffer/common/capabilities.cc
@@ -84,6 +84,7 @@ surfaceless(false), flips_vertically(false), msaa_is_slow(false), + chromium_image_rgb_emulation(false), major_version(2), minor_version(0) {}
diff --git a/gpu/command_buffer/service/BUILD.gn b/gpu/command_buffer/service/BUILD.gn index 3b83386..eacc480 100644 --- a/gpu/command_buffer/service/BUILD.gn +++ b/gpu/command_buffer/service/BUILD.gn
@@ -109,8 +109,6 @@ "shader_translator.h", "shader_translator_cache.cc", "shader_translator_cache.h", - "stream_texture_manager_in_process_android.cc", - "stream_texture_manager_in_process_android.h", "sync_point_manager.cc", "sync_point_manager.h", "texture_definition.cc",
diff --git a/gpu/command_buffer/service/feature_info.cc b/gpu/command_buffer/service/feature_info.cc index 1014e6d..acf8c7b9 100644 --- a/gpu/command_buffer/service/feature_info.cc +++ b/gpu/command_buffer/service/feature_info.cc
@@ -996,12 +996,8 @@ #if defined(OS_MACOSX) if (gfx::GetGLImplementation() != gfx::kGLImplementationOSMesaGL) { AddExtensionString("GL_CHROMIUM_iosurface"); - // TODO(dcastagna): Make this format work with GL Core Profile. - // crbug.com/587158 - if (!gl_version_info_->is_desktop_core_profile) { - AddExtensionString("GL_CHROMIUM_ycbcr_420v_image"); - feature_flags_.chromium_image_ycbcr_420v = true; - } + AddExtensionString("GL_CHROMIUM_ycbcr_420v_image"); + feature_flags_.chromium_image_ycbcr_420v = true; } #endif
diff --git a/gpu/command_buffer/service/gl_context_virtual.cc b/gpu/command_buffer/service/gl_context_virtual.cc index 998d553..11138fe 100644 --- a/gpu/command_buffer/service/gl_context_virtual.cc +++ b/gpu/command_buffer/service/gl_context_virtual.cc
@@ -106,6 +106,10 @@ shared_context_->SetUnbindFboOnMakeCurrent(); } +gl::YUVToRGBConverter* GLContextVirtual::GetYUVToRGBConverter() { + return shared_context_->GetYUVToRGBConverter(); +} + GLContextVirtual::~GLContextVirtual() { Destroy(); }
diff --git a/gpu/command_buffer/service/gl_context_virtual.h b/gpu/command_buffer/service/gl_context_virtual.h index ece0fc7..bedf253 100644 --- a/gpu/command_buffer/service/gl_context_virtual.h +++ b/gpu/command_buffer/service/gl_context_virtual.h
@@ -46,6 +46,7 @@ void SetSafeToForceGpuSwitch() override; bool WasAllocatedUsingRobustnessExtension() override; void SetUnbindFboOnMakeCurrent() override; + gl::YUVToRGBConverter* GetYUVToRGBConverter() override; protected: ~GLContextVirtual() override;
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder.cc b/gpu/command_buffer/service/gles2_cmd_decoder.cc index 4009773..27114203 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder.cc
@@ -594,7 +594,6 @@ const std::vector<int32_t>& attribs) override; void Destroy(bool have_context) override; void SetSurface(const scoped_refptr<gfx::GLSurface>& surface) override; - void ReleaseSurface() override; void ProduceFrontBuffer(const Mailbox& mailbox) override; bool ResizeOffscreenFrameBuffer(const gfx::Size& size) override; void UpdateParentTextureInfo(); @@ -3712,7 +3711,6 @@ // } // anonymous namespace bool GLES2DecoderImpl::MakeCurrent() { - DCHECK(surface_); if (!context_.get()) return false; @@ -4270,22 +4268,11 @@ void GLES2DecoderImpl::SetSurface( const scoped_refptr<gfx::GLSurface>& surface) { DCHECK(context_->IsCurrent(NULL)); - DCHECK(surface); + DCHECK(surface_.get()); surface_ = surface; RestoreCurrentFramebufferBindings(); } -void GLES2DecoderImpl::ReleaseSurface() { - if (!context_.get()) - return; - if (WasContextLost()) { - DLOG(ERROR) << " GLES2DecoderImpl: Trying to release lost context."; - return; - } - context_->ReleaseCurrent(surface_.get()); - surface_ = nullptr; -} - void GLES2DecoderImpl::ProduceFrontBuffer(const Mailbox& mailbox) { if (!offscreen_saved_color_texture_.get()) { LOG(ERROR) << "Called ProduceFrontBuffer on a non-offscreen context";
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder.h b/gpu/command_buffer/service/gles2_cmd_decoder.h index 43e3492..297b9cf 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder.h +++ b/gpu/command_buffer/service/gles2_cmd_decoder.h
@@ -159,10 +159,6 @@ // Set the surface associated with the default FBO. virtual void SetSurface(const scoped_refptr<gfx::GLSurface>& surface) = 0; - // Releases the surface associated with the GL context. - // The decoder should not be used until a new surface is set. - virtual void ReleaseSurface() = 0; - virtual void ProduceFrontBuffer(const Mailbox& mailbox) = 0; // Resize an offscreen frame buffer.
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_mock.h b/gpu/command_buffer/service/gles2_cmd_decoder_mock.h index 636dc14e..396f531a 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_mock.h +++ b/gpu/command_buffer/service/gles2_cmd_decoder_mock.h
@@ -52,7 +52,6 @@ const std::vector<int32_t>& attribs)); MOCK_METHOD1(Destroy, void(bool have_context)); MOCK_METHOD1(SetSurface, void(const scoped_refptr<gfx::GLSurface>& surface)); - MOCK_METHOD0(ReleaseSurface, void()); MOCK_METHOD1(ProduceFrontBuffer, void(const Mailbox& mailbox)); MOCK_METHOD1(ResizeOffscreenFrameBuffer, bool(const gfx::Size& size)); MOCK_METHOD0(MakeCurrent, bool());
diff --git a/gpu/command_buffer/service/in_process_command_buffer.cc b/gpu/command_buffer/service/in_process_command_buffer.cc index 5936b97c..c1d4620 100644 --- a/gpu/command_buffer/service/in_process_command_buffer.cc +++ b/gpu/command_buffer/service/in_process_command_buffer.cc
@@ -47,11 +47,6 @@ #include "ui/gl/gl_image_shared_memory.h" #include "ui/gl/gl_share_group.h" -#if defined(OS_ANDROID) -#include "gpu/command_buffer/service/stream_texture_manager_in_process_android.h" -#include "ui/gl/android/surface_texture.h" -#endif - #if defined(OS_WIN) #include <windows.h> #include "base/process/process_handle.h" @@ -342,10 +337,6 @@ ? params.context_group->gl_share_group_ : service_->share_group(); -#if defined(OS_ANDROID) - stream_texture_manager_.reset(new StreamTextureManagerInProcess); -#endif - bool bind_generates_resource = false; decoder_.reset(gles2::GLES2Decoder::Create( params.context_group @@ -484,9 +475,6 @@ sync_point_order_data_ = nullptr; } gl_share_group_ = nullptr; -#if defined(OS_ANDROID) - stream_texture_manager_.reset(); -#endif return true; } @@ -993,16 +981,6 @@ return sync_token->namespace_id() == GetNamespaceID(); } -uint32_t InProcessCommandBuffer::CreateStreamTextureOnGpuThread( - uint32_t client_texture_id) { -#if defined(OS_ANDROID) - return stream_texture_manager_->CreateStreamTexture( - client_texture_id, decoder_->GetContextGroup()->texture_manager()); -#else - return 0; -#endif -} - gpu::error::Error InProcessCommandBuffer::GetLastError() { CheckSequencedThread(); return last_state_.error; @@ -1049,26 +1027,6 @@ return wrapped_callback; } -#if defined(OS_ANDROID) -scoped_refptr<gfx::SurfaceTexture> InProcessCommandBuffer::GetSurfaceTexture( - uint32_t stream_id) { - DCHECK(stream_texture_manager_); - return stream_texture_manager_->GetSurfaceTexture(stream_id); -} - -uint32_t InProcessCommandBuffer::CreateStreamTexture(uint32_t texture_id) { - base::WaitableEvent completion(true, false); - uint32_t stream_id = 0; - base::Callback<uint32_t(void)> task = - base::Bind(&InProcessCommandBuffer::CreateStreamTextureOnGpuThread, - base::Unretained(this), texture_id); - QueueTask( - base::Bind(&RunTaskWithResult<uint32_t>, task, &stream_id, &completion)); - completion.Wait(); - return stream_id; -} -#endif - GpuInProcessThread::GpuInProcessThread(SyncPointManager* sync_point_manager) : base::Thread("GpuThread"), sync_point_manager_(sync_point_manager) { Start();
diff --git a/gpu/command_buffer/service/in_process_command_buffer.h b/gpu/command_buffer/service/in_process_command_buffer.h index c406fbc..e8ccb33 100644 --- a/gpu/command_buffer/service/in_process_command_buffer.h +++ b/gpu/command_buffer/service/in_process_command_buffer.h
@@ -43,15 +43,6 @@ class Size; } -#if defined(OS_ANDROID) -namespace gfx { -class SurfaceTexture; -} -namespace gpu { -class StreamTextureManagerInProcess; -} -#endif - namespace gpu { class SyncPointClient; class SyncPointOrderData; @@ -178,11 +169,6 @@ scoped_ptr<gpu::gles2::ProgramCache> program_cache_; }; -#if defined(OS_ANDROID) - scoped_refptr<gfx::SurfaceTexture> GetSurfaceTexture(uint32_t stream_id); - uint32_t CreateStreamTexture(uint32_t texture_id); -#endif - private: struct InitializeOnGpuThreadParams { bool is_offscreen; @@ -217,7 +203,6 @@ bool DestroyOnGpuThread(); void FlushOnGpuThread(int32_t put_offset, uint32_t order_num); void ScheduleDelayedWorkOnGpuThread(); - uint32_t CreateStreamTextureOnGpuThread(uint32_t client_texture_id); bool MakeCurrent(); base::Closure WrapCallback(const base::Closure& callback); State GetStateFast(); @@ -288,10 +273,6 @@ scoped_refptr<gfx::GLShareGroup> gl_share_group_; base::WaitableEvent fence_sync_wait_event_; -#if defined(OS_ANDROID) - scoped_ptr<StreamTextureManagerInProcess> stream_texture_manager_; -#endif - // Only used with explicit scheduling and the gpu thread is the same as // the client thread. scoped_ptr<base::SequenceChecker> sequence_checker_;
diff --git a/gpu/command_buffer/service/stream_texture_manager_in_process_android.cc b/gpu/command_buffer/service/stream_texture_manager_in_process_android.cc deleted file mode 100644 index 35a7a84..0000000 --- a/gpu/command_buffer/service/stream_texture_manager_in_process_android.cc +++ /dev/null
@@ -1,214 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "gpu/command_buffer/service/stream_texture_manager_in_process_android.h" - -#include <stdint.h> - -#include "base/bind.h" -#include "base/callback.h" -#include "base/macros.h" -#include "gpu/command_buffer/service/texture_manager.h" -#include "ui/gfx/geometry/size.h" -#include "ui/gl/android/surface_texture.h" -#include "ui/gl/gl_bindings.h" -#include "ui/gl/gl_image.h" - -namespace gpu { - -namespace { - -// Simply wraps a SurfaceTexture reference as a GLImage. -class GLImageImpl : public gl::GLImage { - public: - GLImageImpl(uint32_t texture_id, - gles2::TextureManager* texture_manager, - const scoped_refptr<gfx::SurfaceTexture>& surface_texture, - const base::Closure& release_callback); - - // implement gl::GLImage - void Destroy(bool have_context) override; - gfx::Size GetSize() override; - unsigned GetInternalFormat() override; - bool BindTexImage(unsigned target) override; - void ReleaseTexImage(unsigned target) override; - bool CopyTexImage(unsigned target) override; - bool CopyTexSubImage(unsigned target, - const gfx::Point& offset, - const gfx::Rect& rect) override; - bool ScheduleOverlayPlane(gfx::AcceleratedWidget widget, - int z_order, - gfx::OverlayTransform transform, - const gfx::Rect& bounds_rect, - const gfx::RectF& crop_rect) override; - void OnMemoryDump(base::trace_event::ProcessMemoryDump* pmd, - uint64_t process_tracing_id, - const std::string& dump_name) override; - - private: - ~GLImageImpl() override; - - uint32_t texture_id_; - gles2::TextureManager* texture_manager_; - scoped_refptr<gfx::SurfaceTexture> surface_texture_; - base::Closure release_callback_; - - DISALLOW_COPY_AND_ASSIGN(GLImageImpl); -}; - -GLImageImpl::GLImageImpl( - uint32_t texture_id, - gles2::TextureManager* texture_manager, - const scoped_refptr<gfx::SurfaceTexture>& surface_texture, - const base::Closure& release_callback) - : texture_id_(texture_id), - texture_manager_(texture_manager), - surface_texture_(surface_texture), - release_callback_(release_callback) {} - -GLImageImpl::~GLImageImpl() { - release_callback_.Run(); -} - -void GLImageImpl::Destroy(bool have_context) { - NOTREACHED(); -} - -gfx::Size GLImageImpl::GetSize() { - return gfx::Size(); -} - -unsigned GLImageImpl::GetInternalFormat() { - return GL_RGBA; -} - -bool GLImageImpl::BindTexImage(unsigned target) { - NOTREACHED(); - return false; -} - -void GLImageImpl::ReleaseTexImage(unsigned target) { - NOTREACHED(); -} - -bool GLImageImpl::CopyTexImage(unsigned target) { - if (target != GL_TEXTURE_EXTERNAL_OES) - return false; - - GLint texture_id; - glGetIntegerv(GL_TEXTURE_BINDING_EXTERNAL_OES, &texture_id); - DCHECK(texture_id); - - // The following code only works if we're being asked to copy into - // |texture_id_|. Copying into a different texture is not supported. - if (static_cast<unsigned>(texture_id) != texture_id_) - return false; - - surface_texture_->UpdateTexImage(); - - gles2::Texture* texture = - texture_manager_->GetTextureForServiceId(texture_id_); - if (texture) { - // By setting image state to UNBOUND instead of COPIED we ensure that - // CopyTexImage() is called each time the surface texture is used for - // drawing. - texture->SetLevelImage(GL_TEXTURE_EXTERNAL_OES, 0, this, - gles2::Texture::UNBOUND); - } - return true; -} - -bool GLImageImpl::CopyTexSubImage(unsigned target, - const gfx::Point& offset, - const gfx::Rect& rect) { - return false; -} - -bool GLImageImpl::ScheduleOverlayPlane(gfx::AcceleratedWidget widget, - int z_order, - gfx::OverlayTransform transform, - const gfx::Rect& bounds_rect, - const gfx::RectF& crop_rect) { - NOTREACHED(); - return false; -} - -void GLImageImpl::OnMemoryDump(base::trace_event::ProcessMemoryDump* pmd, - uint64_t process_tracing_id, - const std::string& dump_name) { - // TODO(ericrk): Implement GLImage OnMemoryDump. crbug.com/514914 -} - -} // anonymous namespace - -StreamTextureManagerInProcess::StreamTextureManagerInProcess() - : next_id_(1), weak_factory_(this) {} - -StreamTextureManagerInProcess::~StreamTextureManagerInProcess() { - if (!textures_.empty()) { - LOG(WARNING) << "Undestroyed surface textures while tearing down " - "StreamTextureManager."; - } -} - -GLuint StreamTextureManagerInProcess::CreateStreamTexture( - uint32_t client_texture_id, - gles2::TextureManager* texture_manager) { - CalledOnValidThread(); - - gles2::TextureRef* texture = texture_manager->GetTexture(client_texture_id); - - if (!texture || (texture->texture()->target() && - texture->texture()->target() != GL_TEXTURE_EXTERNAL_OES)) { - return 0; - } - - scoped_refptr<gfx::SurfaceTexture> surface_texture( - gfx::SurfaceTexture::Create(texture->service_id())); - - uint32_t stream_id = next_id_++; - base::Closure release_callback = - base::Bind(&StreamTextureManagerInProcess::OnReleaseStreamTexture, - weak_factory_.GetWeakPtr(), stream_id); - scoped_refptr<gl::GLImage> gl_image( - new GLImageImpl(texture->service_id(), texture_manager, surface_texture, - release_callback)); - - gfx::Size size = gl_image->GetSize(); - texture_manager->SetTarget(texture, GL_TEXTURE_EXTERNAL_OES); - texture_manager->SetLevelInfo(texture, GL_TEXTURE_EXTERNAL_OES, 0, GL_RGBA, - size.width(), size.height(), 1, 0, GL_RGBA, - GL_UNSIGNED_BYTE, gfx::Rect(size)); - texture_manager->SetLevelImage(texture, GL_TEXTURE_EXTERNAL_OES, 0, - gl_image.get(), gles2::Texture::UNBOUND); - - { - base::AutoLock lock(map_lock_); - textures_[stream_id] = surface_texture; - } - - if (next_id_ == 0) - next_id_++; - - return stream_id; -} - -void StreamTextureManagerInProcess::OnReleaseStreamTexture(uint32_t stream_id) { - CalledOnValidThread(); - base::AutoLock lock(map_lock_); - textures_.erase(stream_id); -} - -// This can get called from any thread. -scoped_refptr<gfx::SurfaceTexture> -StreamTextureManagerInProcess::GetSurfaceTexture(uint32_t stream_id) { - base::AutoLock lock(map_lock_); - TextureMap::const_iterator it = textures_.find(stream_id); - if (it != textures_.end()) - return it->second; - - return NULL; -} - -} // namespace gpu
diff --git a/gpu/command_buffer/service/stream_texture_manager_in_process_android.h b/gpu/command_buffer/service/stream_texture_manager_in_process_android.h deleted file mode 100644 index 1f503bf..0000000 --- a/gpu/command_buffer/service/stream_texture_manager_in_process_android.h +++ /dev/null
@@ -1,53 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef GPU_STREAM_TEXTURE_MANAGER_IN_PROCESS_ANDROID_H_ -#define GPU_STREAM_TEXTURE_MANAGER_IN_PROCESS_ANDROID_H_ - -#include <stdint.h> - -#include <map> - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/synchronization/lock.h" -#include "base/threading/non_thread_safe.h" - -namespace gfx { -class SurfaceTexture; -} - -namespace gpu { - -namespace gles2 { -class TextureManager; -} - -class StreamTextureManagerInProcess : public base::NonThreadSafe { - public: - StreamTextureManagerInProcess(); - ~StreamTextureManagerInProcess(); - - uint32_t CreateStreamTexture(uint32_t client_texture_id, - gles2::TextureManager* texture_manager); - - // This method can be called from any thread. - scoped_refptr<gfx::SurfaceTexture> GetSurfaceTexture(uint32_t stream_id); - - private: - void OnReleaseStreamTexture(uint32_t stream_id); - - typedef std::map<uint32_t, scoped_refptr<gfx::SurfaceTexture>> TextureMap; - TextureMap textures_; - base::Lock map_lock_; - uint32_t next_id_; - - base::WeakPtrFactory<StreamTextureManagerInProcess> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(StreamTextureManagerInProcess); -}; - -} // gpu - -#endif // GPU_STREAM_TEXTURE_MANAGER_IN_PROCESS_ANDROID_H_
diff --git a/gpu/command_buffer/tests/command_buffer_gles2_tests_main.cc b/gpu/command_buffer/tests/command_buffer_gles2_tests_main.cc index 6fda0631..f945390 100644 --- a/gpu/command_buffer/tests/command_buffer_gles2_tests_main.cc +++ b/gpu/command_buffer/tests/command_buffer_gles2_tests_main.cc
@@ -9,8 +9,8 @@ #endif #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_suite.h" +#include "gpu/gles2_conform_support/egl/test_support.h" #include "testing/gmock/include/gmock/gmock.h" -#include "gpu/gles2_conform_support/egl/test_support.h" // NOLINT // This file implements the main entry point for tests for command_buffer_gles2, // the mode of command buffer where the code is compiled as a standalone dynamic
diff --git a/gpu/command_buffer/tests/egl_test.cc b/gpu/command_buffer/tests/egl_test.cc index e6bf4a9..bf7e30e5 100644 --- a/gpu/command_buffer/tests/egl_test.cc +++ b/gpu/command_buffer/tests/egl_test.cc
@@ -6,610 +6,31 @@ #include "testing/gtest/include/gtest/gtest.h" #include <EGL/egl.h> -#include <GLES2/gl2.h> - -#include "base/bind.h" -#include "base/synchronization/waitable_event.h" -#include "base/threading/thread.h" -#include "gpu/gles2_conform_support/egl/test_support.h" // This file tests EGL basic interface for command_buffer_gles2, the mode of // command buffer where the code is compiled as a standalone dynamic library and // exposed through EGL API. namespace gpu { -class EGLTest : public testing::Test { - public: - void TearDown() override; -}; +using testing::Test; -void EGLTest::TearDown() { - EXPECT_TRUE(eglReleaseThread()); -} - -TEST_F(EGLTest, OnlyReleaseThread) {} - -TEST_F(EGLTest, GetDisplay) { - EGLDisplay display1 = eglGetDisplay(EGL_DEFAULT_DISPLAY); - EXPECT_NE(display1, EGL_NO_DISPLAY); - - EGLDisplay display2 = eglGetDisplay(EGL_DEFAULT_DISPLAY); - EXPECT_EQ(display1, display2); - - EGLNativeDisplayType invalid_display_type = - reinterpret_cast<EGLNativeDisplayType>(0x1); - EXPECT_NE(invalid_display_type, EGL_DEFAULT_DISPLAY); - EXPECT_EQ(EGL_NO_DISPLAY, eglGetDisplay(invalid_display_type)); - EXPECT_EQ(EGL_SUCCESS, eglGetError()); - - // eglTerminate can be called with uninitialized display. - EXPECT_TRUE(eglTerminate(display1)); -} - -TEST_F(EGLTest, GetError) { - // GetError returns success. - EXPECT_EQ(EGL_SUCCESS, eglGetError()); - - // "calling eglGetError twice without any other intervening EGL calls will - // always return EGL_SUCCESS on the second call" +TEST_F(Test, BasicEGLInitialization) { EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); - EXPECT_NE(display, EGL_NO_DISPLAY); - EXPECT_EQ(EGL_SUCCESS, eglGetError()); - EXPECT_EQ(nullptr, eglQueryString(display, EGL_EXTENSIONS)); - EXPECT_EQ(EGL_NOT_INITIALIZED, eglGetError()); - EXPECT_EQ(EGL_SUCCESS, eglGetError()); - - EXPECT_TRUE(eglTerminate(display)); - EXPECT_EQ(EGL_SUCCESS, eglGetError()); -} - -TEST_F(EGLTest, Initialize) { - EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); - EXPECT_NE(display, EGL_NO_DISPLAY); + ASSERT_NE(display, EGL_NO_DISPLAY); // Test for no crash even though passing nullptrs for major, minor. - EXPECT_TRUE(eglInitialize(display, nullptr, nullptr)); + EGLBoolean success = eglInitialize(display, nullptr, nullptr); + ASSERT_TRUE(success); EGLint major = 0; EGLint minor = 0; - EXPECT_TRUE(eglInitialize(display, &major, &minor)); - EXPECT_EQ(major, 1); - EXPECT_EQ(minor, 4); + success = eglInitialize(display, &major, &minor); + ASSERT_TRUE(success); + ASSERT_EQ(major, 1); + ASSERT_EQ(minor, 4); - EGLDisplay invalid_display = reinterpret_cast<EGLDisplay>(0x1); - EXPECT_FALSE(eglInitialize(invalid_display, nullptr, nullptr)); - EXPECT_EQ(EGL_BAD_DISPLAY, eglGetError()); -} - -TEST_F(EGLTest, Terminate) { - EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); - EXPECT_NE(display, EGL_NO_DISPLAY); - - // eglTerminate can be called multiple times without initialization. - EXPECT_TRUE(eglTerminate(display)); - EXPECT_EQ(EGL_SUCCESS, eglGetError()); - EXPECT_TRUE(eglTerminate(display)); - EXPECT_EQ(EGL_SUCCESS, eglGetError()); - - EXPECT_TRUE(eglInitialize(display, nullptr, nullptr)); - - // eglTerminate can be called multiple times. - EXPECT_TRUE(eglTerminate(display)); - EXPECT_EQ(EGL_SUCCESS, eglGetError()); - EXPECT_TRUE(eglTerminate(display)); - EXPECT_EQ(EGL_SUCCESS, eglGetError()); - - // After Terminate, an egl call returns not initialized. - EXPECT_EQ(nullptr, eglQueryString(display, EGL_EXTENSIONS)); - EXPECT_EQ(EGL_NOT_INITIALIZED, eglGetError()); - - // Re-initialization of same display. - EXPECT_TRUE(eglInitialize(display, nullptr, nullptr)); - EXPECT_NE(nullptr, eglQueryString(display, EGL_EXTENSIONS)); - EXPECT_TRUE(eglTerminate(display)); - - EGLDisplay invalid_display = reinterpret_cast<EGLDisplay>(0x1); - EXPECT_FALSE(eglTerminate(invalid_display)); - EXPECT_EQ(EGL_BAD_DISPLAY, eglGetError()); -} - -TEST_F(EGLTest, QueryString) { - EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); - EXPECT_NE(display, EGL_NO_DISPLAY); - EXPECT_EQ(nullptr, eglQueryString(display, EGL_EXTENSIONS)); - EXPECT_EQ(EGL_NOT_INITIALIZED, eglGetError()); - EXPECT_STREQ("", eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS)); - - EXPECT_EQ(nullptr, eglQueryString(display, EGL_VERSION)); - EXPECT_EQ(EGL_NOT_INITIALIZED, eglGetError()); - EXPECT_STREQ("1.4", eglQueryString(EGL_NO_DISPLAY, EGL_VERSION)); - - EXPECT_EQ(nullptr, eglQueryString(display, EGL_CLIENT_APIS)); - EXPECT_EQ(EGL_NOT_INITIALIZED, eglGetError()); - EXPECT_EQ(nullptr, eglQueryString(EGL_NO_DISPLAY, EGL_CLIENT_APIS)); - EXPECT_EQ(EGL_BAD_DISPLAY, eglGetError()); - EXPECT_EQ(nullptr, eglQueryString(display, EGL_VENDOR)); - EXPECT_EQ(EGL_NOT_INITIALIZED, eglGetError()); - EXPECT_EQ(nullptr, eglQueryString(EGL_NO_DISPLAY, EGL_VENDOR)); - EXPECT_EQ(EGL_BAD_DISPLAY, eglGetError()); - - EXPECT_TRUE(eglInitialize(display, nullptr, nullptr)); - EXPECT_EQ(EGL_SUCCESS, eglGetError()); - - EXPECT_STREQ("", eglQueryString(display, EGL_EXTENSIONS)); - EXPECT_EQ(EGL_SUCCESS, eglGetError()); - EXPECT_STREQ("1.4", eglQueryString(display, EGL_VERSION)); - EXPECT_EQ(EGL_SUCCESS, eglGetError()); - EXPECT_STREQ("OpenGL_ES", eglQueryString(display, EGL_CLIENT_APIS)); - EXPECT_EQ(EGL_SUCCESS, eglGetError()); - EXPECT_STREQ("Google Inc.", eglQueryString(display, EGL_VENDOR)); - EXPECT_EQ(EGL_SUCCESS, eglGetError()); -} - -TEST_F(EGLTest, GetConfigsUninitialized) { - EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); - EXPECT_NE(display, EGL_NO_DISPLAY); - - EGLint num_config = 0; - const int kConfigsSize = 5; - EGLConfig configs[kConfigsSize] = { - 0, - }; - - EXPECT_FALSE(eglGetConfigs(display, configs, kConfigsSize, &num_config)); - EXPECT_EQ(EGL_NOT_INITIALIZED, eglGetError()); - - EXPECT_FALSE(eglGetConfigs(display, configs, kConfigsSize, nullptr)); - EXPECT_EQ(EGL_NOT_INITIALIZED, eglGetError()); -} - -TEST_F(EGLTest, ChooseConfigUninitialized) { - EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); - EXPECT_NE(display, EGL_NO_DISPLAY); - - EGLint num_config = 0; - EGLint attrib_list[] = {EGL_NONE}; - const int kConfigsSize = 5; - EGLConfig configs[kConfigsSize] = { - 0, - }; - - EXPECT_FALSE(eglChooseConfig(display, attrib_list, configs, kConfigsSize, - &num_config)); - EXPECT_EQ(EGL_NOT_INITIALIZED, eglGetError()); - - EXPECT_FALSE( - eglChooseConfig(display, attrib_list, configs, kConfigsSize, nullptr)); - EXPECT_EQ(EGL_NOT_INITIALIZED, eglGetError()); -} - -class EGLConfigTest : public EGLTest { - public: - void SetUp() override; - - protected: - void CheckConfigsExist(EGLint num_config); - - enum { kConfigsSize = 5 }; - EGLDisplay display_; - EGLConfig configs_[kConfigsSize]; -}; - -void EGLConfigTest::SetUp() { - display_ = eglGetDisplay(EGL_DEFAULT_DISPLAY); - ASSERT_NE(display_, EGL_NO_DISPLAY); - EXPECT_TRUE(eglInitialize(display_, nullptr, nullptr)); - memset(configs_, 0, sizeof(configs_)); -} - -void EGLConfigTest::CheckConfigsExist(EGLint num_config) { - EGLint i; - if (num_config > kConfigsSize) - num_config = static_cast<EGLint>(kConfigsSize); - for (i = 0; i < num_config; ++i) - EXPECT_NE(nullptr, configs_[i]); - for (; i < kConfigsSize; ++i) - EXPECT_EQ(nullptr, configs_[i]); -} - -TEST_F(EGLConfigTest, GetConfigsBadNumConfigs) { - EXPECT_FALSE(eglGetConfigs(display_, configs_, kConfigsSize, nullptr)); - EXPECT_EQ(EGL_BAD_PARAMETER, eglGetError()); -} - -TEST_F(EGLConfigTest, GetConfigsNullConfigs) { - EGLint num_config = 0; - EXPECT_TRUE(eglGetConfigs(display_, nullptr, 55, &num_config)); - EXPECT_GT(num_config, 0); -} - -TEST_F(EGLConfigTest, GetConfigsZeroConfigsSize) { - EGLint num_config = 0; - EXPECT_TRUE(eglGetConfigs(display_, configs_, 0, &num_config)); - EXPECT_GT(num_config, 0); - EXPECT_EQ(nullptr, configs_[0]); -} - -TEST_F(EGLConfigTest, GetConfigs) { - EGLint num_config = 0; - EXPECT_TRUE(eglGetConfigs(display_, configs_, kConfigsSize, &num_config)); - EXPECT_GT(num_config, 0); - CheckConfigsExist(num_config); -} - -TEST_F(EGLConfigTest, ChooseConfigBadNumConfigs) { - EGLint attrib_list[] = {EGL_NONE}; - EXPECT_FALSE( - eglChooseConfig(display_, attrib_list, configs_, kConfigsSize, nullptr)); - EXPECT_EQ(EGL_BAD_PARAMETER, eglGetError()); -} - -TEST_F(EGLConfigTest, ChooseConfigNullConfigs) { - EGLint num_config = 0; - EGLint attrib_list[] = {EGL_NONE}; - EXPECT_TRUE(eglChooseConfig(display_, attrib_list, nullptr, 55, &num_config)); - EXPECT_GT(num_config, 0); -} - -TEST_F(EGLConfigTest, ChooseConfigZeroConfigsSize) { - EGLint num_config = 0; - EGLint attrib_list[] = {EGL_NONE}; - EXPECT_TRUE(eglChooseConfig(display_, attrib_list, configs_, 0, &num_config)); - EXPECT_GT(num_config, 0); - EXPECT_EQ(nullptr, configs_[0]); -} - -TEST_F(EGLConfigTest, ChooseConfig) { - EGLint num_config = 0; - EGLint attrib_list[] = {EGL_NONE}; - EXPECT_TRUE(eglChooseConfig(display_, attrib_list, configs_, kConfigsSize, - &num_config)); - EXPECT_GT(num_config, 0); - CheckConfigsExist(num_config); -} - -TEST_F(EGLConfigTest, ChooseConfigInvalidAttrib) { - const EGLint kNotModified = 55; - EGLint num_config = kNotModified; - EGLint invalid_attrib_list[] = {0xABCD}; - EXPECT_FALSE(eglChooseConfig(display_, invalid_attrib_list, configs_, - kConfigsSize, &num_config)); - EXPECT_EQ(EGL_BAD_ATTRIBUTE, eglGetError()); - EXPECT_EQ(kNotModified, num_config); -} - -TEST_F(EGLConfigTest, ChooseConfigWindow) { - EGLint num_config = 0; - EGLint attrib_list[] = {EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE}; - EXPECT_TRUE(eglChooseConfig(display_, attrib_list, configs_, kConfigsSize, - &num_config)); - EXPECT_GT(num_config, 0); - for (int i = 0; i < num_config; ++i) { - EGLint value = EGL_NONE; - eglGetConfigAttrib(display_, configs_[i], EGL_SURFACE_TYPE, &value); - EXPECT_NE(0, value & EGL_WINDOW_BIT); - } -} - -TEST_F(EGLConfigTest, ChooseConfigPBuffer) { - EGLint num_config = 0; - EGLint attrib_list[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_NONE}; - EXPECT_TRUE(eglChooseConfig(display_, attrib_list, configs_, kConfigsSize, - &num_config)); - EXPECT_GT(num_config, 0); - for (int i = 0; i < num_config; ++i) { - EGLint value = EGL_NONE; - eglGetConfigAttrib(display_, configs_[0], EGL_SURFACE_TYPE, &value); - EXPECT_NE(0, value & EGL_PBUFFER_BIT); - } -} - -TEST_F(EGLConfigTest, ChooseConfigWindowPBufferNotPossible) { - EGLint num_config = 0; - EGLint attrib_list[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT | EGL_WINDOW_BIT, - EGL_NONE}; - EXPECT_TRUE(eglChooseConfig(display_, attrib_list, configs_, kConfigsSize, - &num_config)); - EXPECT_EQ(0, num_config); -} - -TEST_F(EGLConfigTest, ChooseConfigBugExample) { - static const EGLint kConfigAttribs[] = { - EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, - EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 8, EGL_STENCIL_SIZE, 8, - EGL_SAMPLE_BUFFERS, 1, EGL_SAMPLES, 4, EGL_NONE}; - EGLint num_config = 0; - EXPECT_TRUE(eglChooseConfig(display_, kConfigAttribs, configs_, kConfigsSize, - &num_config)); - - // The EGL attribs are not really implemented at the moment. - EGLint value = EGL_NONE; - EXPECT_TRUE(eglGetConfigAttrib(display_, configs_[0], EGL_RED_SIZE, &value)); - EXPECT_EQ(0, value); -} - -TEST_F(EGLTest, MakeCurrent) { - EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); - EXPECT_NE(display, EGL_NO_DISPLAY); - // "This is the only case where an uninitialized display may be passed to - // eglMakeCurrent." - EXPECT_TRUE( - eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)); - EGLDisplay invalid_display = reinterpret_cast<EGLDisplay>(0x1); - EXPECT_FALSE(eglMakeCurrent(invalid_display, EGL_NO_SURFACE, EGL_NO_SURFACE, - EGL_NO_CONTEXT)); - EXPECT_EQ(EGL_BAD_DISPLAY, eglGetError()); - - EXPECT_TRUE(eglInitialize(display, nullptr, nullptr)); - EXPECT_TRUE( - eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)); - EXPECT_FALSE(eglMakeCurrent(invalid_display, EGL_NO_SURFACE, EGL_NO_SURFACE, - EGL_NO_CONTEXT)); -} - -class EGLSurfaceTest : public EGLTest { - public: - void SetUp() override; - void CreateSurfaceAndContext(EGLSurface* surface, EGLContext* context); - - protected: - EGLDisplay display_; -}; - -void EGLSurfaceTest::SetUp() { - EGLTest::SetUp(); - display_ = eglGetDisplay(EGL_DEFAULT_DISPLAY); - EXPECT_TRUE(eglInitialize(display_, nullptr, nullptr)); -} - -void EGLSurfaceTest::CreateSurfaceAndContext(EGLSurface* surface, - EGLContext* context) { - static const EGLint config_attribs[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, - EGL_NONE}; - EGLint num_config; - EGLConfig config; - EXPECT_TRUE( - eglChooseConfig(display_, config_attribs, &config, 1, &num_config)); - ASSERT_GT(num_config, 0); - static const EGLint surface_attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, - EGL_NONE}; - *surface = eglCreatePbufferSurface(display_, config, surface_attribs); - static const EGLint context_attribs[] = {EGL_CONTEXT_CLIENT_VERSION, 2, - EGL_NONE}; - *context = eglCreateContext(display_, config, nullptr, context_attribs); -} - -class EGLMultipleSurfacesContextsTest : public EGLSurfaceTest { - public: - void SetUp() override; - void TearDown() override; - - protected: - EGLSurface surface1_; - EGLSurface surface2_; - EGLContext context1_; - EGLContext context2_; -}; - -void EGLMultipleSurfacesContextsTest::SetUp() { - EGLSurfaceTest::SetUp(); - CreateSurfaceAndContext(&surface1_, &context1_); - CreateSurfaceAndContext(&surface2_, &context2_); - EXPECT_NE(EGL_NO_SURFACE, surface1_); - EXPECT_NE(EGL_NO_SURFACE, surface2_); - EXPECT_NE(surface1_, surface2_); - EXPECT_NE(EGL_NO_CONTEXT, context1_); - EXPECT_NE(EGL_NO_CONTEXT, context2_); - EXPECT_NE(context1_, context2_); -} - -void EGLMultipleSurfacesContextsTest::TearDown() { - EXPECT_TRUE(eglDestroyContext(display_, context1_)); - EXPECT_TRUE(eglDestroySurface(display_, surface1_)); - EXPECT_TRUE(eglDestroyContext(display_, context2_)); - EXPECT_TRUE(eglDestroySurface(display_, surface2_)); - EGLTest::TearDown(); -} - -TEST_F(EGLMultipleSurfacesContextsTest, NoMakeCurrent) {} - -TEST_F(EGLMultipleSurfacesContextsTest, MakeCurrentSurfaces) { - EXPECT_TRUE(eglMakeCurrent(display_, surface1_, surface1_, context1_)); - EXPECT_TRUE(eglMakeCurrent(display_, surface2_, surface2_, context2_)); - EXPECT_TRUE(eglMakeCurrent(display_, surface1_, surface1_, context2_)); - EXPECT_TRUE(eglMakeCurrent(display_, surface2_, surface2_, context1_)); -} - -TEST_F(EGLMultipleSurfacesContextsTest, MakeCurrentSameSurface1) { - EXPECT_TRUE(eglMakeCurrent(display_, surface1_, surface1_, context1_)); - EXPECT_TRUE(eglMakeCurrent(display_, surface1_, surface1_, context2_)); -} - -TEST_F(EGLMultipleSurfacesContextsTest, MakeCurrentSameSurface2) { - EXPECT_TRUE(eglMakeCurrent(display_, surface1_, surface1_, context1_)); - EXPECT_TRUE(eglMakeCurrent(display_, surface2_, surface2_, context1_)); - EXPECT_TRUE(eglMakeCurrent(display_, surface2_, surface2_, context2_)); -} - -TEST_F(EGLMultipleSurfacesContextsTest, MakeCurrentSurfacesAndReleases) { - EXPECT_TRUE(eglMakeCurrent(display_, surface1_, surface1_, context1_)); - EXPECT_TRUE( - eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)); - EXPECT_TRUE(eglMakeCurrent(display_, surface2_, surface2_, context2_)); - EXPECT_TRUE( - eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)); - EXPECT_TRUE(eglMakeCurrent(display_, surface1_, surface1_, context2_)); - EXPECT_TRUE( - eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)); - EXPECT_TRUE(eglMakeCurrent(display_, surface2_, surface2_, context1_)); - EXPECT_TRUE( - eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)); -} - -TEST_F(EGLMultipleSurfacesContextsTest, MakeCurrentSurfaceFails) { - EXPECT_FALSE(eglMakeCurrent(display_, surface1_, surface1_, EGL_NO_CONTEXT)); - EXPECT_EQ(EGL_BAD_CONTEXT, eglGetError()); - EXPECT_FALSE(eglMakeCurrent(display_, surface1_, EGL_NO_SURFACE, context1_)); - EXPECT_EQ(EGL_BAD_SURFACE, eglGetError()); - EXPECT_FALSE(eglMakeCurrent(display_, EGL_NO_SURFACE, surface1_, context1_)); - EXPECT_EQ(EGL_BAD_SURFACE, eglGetError()); - - EGLDisplay invalid_display = reinterpret_cast<EGLDisplay>(0x1); - EGLSurface invalid_surface = reinterpret_cast<EGLSurface>(0x1); - EGLSurface invalid_context = reinterpret_cast<EGLContext>(0x1); - EXPECT_FALSE( - eglMakeCurrent(invalid_display, surface1_, surface1_, context1_)); - EXPECT_EQ(EGL_BAD_DISPLAY, eglGetError()); - EXPECT_FALSE(eglMakeCurrent(display_, surface1_, surface1_, invalid_context)); - EXPECT_EQ(EGL_BAD_CONTEXT, eglGetError()); - EXPECT_FALSE(eglMakeCurrent(display_, surface1_, invalid_surface, context1_)); - EXPECT_EQ(EGL_BAD_SURFACE, eglGetError()); - EXPECT_FALSE(eglMakeCurrent(display_, invalid_surface, surface1_, context1_)); - EXPECT_EQ(EGL_BAD_SURFACE, eglGetError()); - - // Command buffer limitation: - // Different read and draw surfaces fail. - EXPECT_FALSE(eglMakeCurrent(display_, surface1_, surface2_, context1_)); - EXPECT_EQ(EGL_BAD_MATCH, eglGetError()); -} - -TEST_F(EGLMultipleSurfacesContextsTest, CallGLOnMultipleContextNoCrash) { - EXPECT_TRUE(eglMakeCurrent(display_, surface1_, surface1_, context1_)); - - typedef void(GL_APIENTRY * glEnableProc)(GLenum); - glEnableProc glEnable = - reinterpret_cast<glEnableProc>(eglGetProcAddress("glEnable")); - EXPECT_NE(nullptr, glEnable); - - glEnable(GL_BLEND); - - EXPECT_TRUE(eglMakeCurrent(display_, surface2_, surface2_, context2_)); - glEnable(GL_BLEND); -} - -class EGLThreadTest : public EGLSurfaceTest { - public: - EGLThreadTest(); - void SetUp() override; - void TearDown() override; - void OtherThreadTearDown(base::WaitableEvent*); - void OtherThreadMakeCurrent(EGLSurface surface, - EGLContext context, - EGLBoolean* result, - base::WaitableEvent*); - void OtherThreadGetError(EGLint* result, base::WaitableEvent*); - - protected: - base::Thread other_thread_; -}; - -EGLThreadTest::EGLThreadTest() - : EGLSurfaceTest(), other_thread_("EGLThreadTest thread") {} -void EGLThreadTest::SetUp() { - EGLSurfaceTest::SetUp(); - other_thread_.Start(); -} - -void EGLThreadTest::TearDown() { - base::WaitableEvent completion(true, false); - other_thread_.task_runner()->PostTask( - FROM_HERE, base::Bind(&EGLThreadTest::OtherThreadTearDown, - base::Unretained(this), &completion)); - completion.Wait(); - other_thread_.Stop(); - EGLSurfaceTest::TearDown(); -} - -void EGLThreadTest::OtherThreadTearDown(base::WaitableEvent* completion) { - EXPECT_TRUE(eglReleaseThread()); - completion->Signal(); -} - -void EGLThreadTest::OtherThreadMakeCurrent(EGLSurface surface, - EGLContext context, - EGLBoolean* result, - base::WaitableEvent* completion) { - *result = eglMakeCurrent(display_, surface, surface, context); - completion->Signal(); -} - -void EGLThreadTest::OtherThreadGetError(EGLint* result, - base::WaitableEvent* completion) { - *result = eglGetError(); - completion->Signal(); -} - -TEST_F(EGLThreadTest, OnlyReleaseThreadInOther) {} - -TEST_F(EGLThreadTest, Basic) { - EGLSurface surface; - EGLContext context; - CreateSurfaceAndContext(&surface, &context); - EXPECT_NE(EGL_NO_SURFACE, surface); - EXPECT_NE(EGL_NO_CONTEXT, context); - - EXPECT_TRUE(eglMakeCurrent(display_, surface, surface, context)); - - base::WaitableEvent completion(false, false); - - EGLBoolean result = EGL_FALSE; - other_thread_.task_runner()->PostTask( - FROM_HERE, - base::Bind(&EGLThreadTest::OtherThreadMakeCurrent, base::Unretained(this), - surface, context, &result, &completion)); - completion.Wait(); - EXPECT_FALSE(result); - EXPECT_EQ(EGL_SUCCESS, eglGetError()); - - EGLint error = EGL_NONE; - other_thread_.task_runner()->PostTask( - FROM_HERE, base::Bind(&EGLThreadTest::OtherThreadGetError, - base::Unretained(this), &error, &completion)); - completion.Wait(); - EXPECT_EQ(EGL_BAD_ACCESS, error); - EXPECT_EQ(EGL_SUCCESS, eglGetError()); - - other_thread_.task_runner()->PostTask( - FROM_HERE, base::Bind(&EGLThreadTest::OtherThreadGetError, - base::Unretained(this), &error, &completion)); - completion.Wait(); - EXPECT_EQ(EGL_SUCCESS, error); - - EXPECT_TRUE( - eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)); - - other_thread_.task_runner()->PostTask( - FROM_HERE, - base::Bind(&EGLThreadTest::OtherThreadMakeCurrent, base::Unretained(this), - surface, context, &result, &completion)); - completion.Wait(); - EXPECT_TRUE(result); - - EXPECT_FALSE(eglMakeCurrent(display_, surface, surface, context)); - EXPECT_EQ(EGL_BAD_ACCESS, eglGetError()); - - EXPECT_TRUE(eglDestroySurface(display_, surface)); - EXPECT_TRUE(eglDestroyContext(display_, context)); -} - -TEST_F(EGLTest, WindowlessNativeWindows) { - EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); - EXPECT_TRUE(eglInitialize(display, nullptr, nullptr)); - - static const EGLint config_attribs[] = {EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_NONE}; - EGLint num_config; - EGLConfig config; - EXPECT_TRUE( - eglChooseConfig(display, config_attribs, &config, 1, &num_config)); - ASSERT_GT(num_config, 0); - static const EGLint surface_attribs[] = {EGL_NONE}; - CommandBufferGLESSetNextCreateWindowSurfaceCreatesPBuffer(display, 100, 100); - EGLNativeWindowType win = 0; - EGLSurface surface = - eglCreateWindowSurface(display, config, win, surface_attribs); - EXPECT_NE(EGL_NO_SURFACE, surface); - EXPECT_TRUE(eglDestroySurface(display, surface)); + success = eglTerminate(display); + ASSERT_TRUE(success); } } // namespace gpu
diff --git a/gpu/command_buffer_service.gypi b/gpu/command_buffer_service.gypi index bb3112d8..4e71ca8 100644 --- a/gpu/command_buffer_service.gypi +++ b/gpu/command_buffer_service.gypi
@@ -113,8 +113,6 @@ 'command_buffer/service/shader_translator.h', 'command_buffer/service/shader_translator_cache.cc', 'command_buffer/service/shader_translator_cache.h', - 'command_buffer/service/stream_texture_manager_in_process_android.cc', - 'command_buffer/service/stream_texture_manager_in_process_android.h', 'command_buffer/service/sync_point_manager.cc', 'command_buffer/service/sync_point_manager.h', 'command_buffer/service/texture_definition.cc',
diff --git a/gpu/config/BUILD.gn b/gpu/config/BUILD.gn index d0434ea0..57db87b 100644 --- a/gpu/config/BUILD.gn +++ b/gpu/config/BUILD.gn
@@ -3,11 +3,13 @@ # found in the LICENSE file. import("//build/config/chrome_build.gni") +import("//build/config/chromecast_build.gni") import("//build/config/ui.gni") declare_args() { # Use the PCI lib to collect GPU information on Linux. - use_libpci = is_linux && !is_chromecast && (use_x11 || use_ozone) + use_libpci = is_linux && (!is_chromecast || is_cast_desktop_build) && + (use_x11 || use_ozone) } group("config") {
diff --git a/gpu/gles2_conform_support/egl/BUILD.gn b/gpu/gles2_conform_support/egl/BUILD.gn index f11dd0ad..556f053 100644 --- a/gpu/gles2_conform_support/egl/BUILD.gn +++ b/gpu/gles2_conform_support/egl/BUILD.gn
@@ -8,17 +8,11 @@ sources = [ "config.cc", "config.h", - "context.cc", - "context.h", "display.cc", "display.h", "egl.cc", "surface.cc", "surface.h", - "test_support.cc", - "test_support.h", - "thread_state.cc", - "thread_state.h", ] configs += [ "//build/config/compiler:no_size_t_to_int_warning" ] @@ -34,7 +28,6 @@ "//gpu:command_buffer_gles2", "//gpu/command_buffer/client:gles2_c_lib_nocheck", "//gpu/command_buffer/client:gles2_implementation_no_check", - "//gpu/command_buffer/common:gles2_utils", "//gpu/command_buffer/service", "//ui/base", "//ui/gfx",
diff --git a/gpu/gles2_conform_support/egl/config.cc b/gpu/gles2_conform_support/egl/config.cc index 53bd440d..d6ce3072 100644 --- a/gpu/gles2_conform_support/egl/config.cc +++ b/gpu/gles2_conform_support/egl/config.cc
@@ -3,11 +3,10 @@ // found in the LICENSE file. #include "gpu/gles2_conform_support/egl/config.h" -#include "base/logging.h" namespace egl { -Config::Config(EGLint surface_type) +Config::Config() : buffer_size_(0), red_size_(0), green_size_(0), @@ -35,37 +34,16 @@ sample_buffers_(0), samples_(0), stencil_size_(0), - surface_type_(surface_type), + surface_type_(EGL_WINDOW_BIT), transparent_type_(EGL_NONE), transparent_red_value_(EGL_DONT_CARE), transparent_green_value_(EGL_DONT_CARE), transparent_blue_value_(EGL_DONT_CARE) { - DCHECK(surface_type == EGL_WINDOW_BIT || surface_type == EGL_PBUFFER_BIT); } Config::~Config() { } -bool Config::Matches(const EGLint* attrib_list) const { - DCHECK(ValidateAttributeList(attrib_list)); - if (attrib_list) { - for (int i = 0; attrib_list[i] != EGL_NONE; i += 2) { - switch (attrib_list[i]) { - case EGL_SURFACE_TYPE: { - EGLint requested_surface_type = attrib_list[i + 1]; - if (requested_surface_type != EGL_DONT_CARE && - (requested_surface_type & surface_type_) != - requested_surface_type) - return false; - } - default: - break; - } - } - } - return true; -} - bool Config::GetAttrib(EGLint attribute, EGLint* value) const { // TODO(alokp): Find out how to get correct values. switch (attribute) { @@ -171,52 +149,4 @@ return true; } -bool Config::ValidateAttributeList(const EGLint* attrib_list) { - if (attrib_list) { - for (int i = 0; attrib_list[i] != EGL_NONE; i += 2) { - switch (attrib_list[i]) { - case EGL_ALPHA_MASK_SIZE: - case EGL_ALPHA_SIZE: - case EGL_BIND_TO_TEXTURE_RGB: - case EGL_BIND_TO_TEXTURE_RGBA: - case EGL_BLUE_SIZE: - case EGL_BUFFER_SIZE: - case EGL_COLOR_BUFFER_TYPE: - case EGL_CONFIG_CAVEAT: - case EGL_CONFIG_ID: - case EGL_CONFORMANT: - case EGL_DEPTH_SIZE: - case EGL_GREEN_SIZE: - case EGL_LEVEL: - case EGL_LUMINANCE_SIZE: - case EGL_MATCH_NATIVE_PIXMAP: - case EGL_NATIVE_RENDERABLE: - case EGL_MAX_SWAP_INTERVAL: - case EGL_MIN_SWAP_INTERVAL: - case EGL_RED_SIZE: - case EGL_SAMPLE_BUFFERS: - case EGL_SAMPLES: - case EGL_STENCIL_SIZE: - case EGL_RENDERABLE_TYPE: - case EGL_SURFACE_TYPE: - case EGL_MULTISAMPLE_RESOLVE_BOX_BIT: - case EGL_PBUFFER_BIT: - case EGL_PIXMAP_BIT: - case EGL_SWAP_BEHAVIOR_PRESERVED_BIT: - case EGL_VG_ALPHA_FORMAT_PRE_BIT: - case EGL_VG_COLORSPACE_LINEAR_BIT: - case EGL_WINDOW_BIT: - case EGL_TRANSPARENT_TYPE: - case EGL_TRANSPARENT_RED_VALUE: - case EGL_TRANSPARENT_GREEN_VALUE: - case EGL_TRANSPARENT_BLUE_VALUE: - break; - default: - return false; - } - } - } - return true; -} - } // namespace egl
diff --git a/gpu/gles2_conform_support/egl/config.h b/gpu/gles2_conform_support/egl/config.h index 1ce8156..53bb568 100644 --- a/gpu/gles2_conform_support/egl/config.h +++ b/gpu/gles2_conform_support/egl/config.h
@@ -13,11 +13,10 @@ class Config { public: - explicit Config(EGLint surface_type); + Config(); ~Config(); - bool Matches(const EGLint* attrib_list) const; + bool GetAttrib(EGLint attribute, EGLint* value) const; - static bool ValidateAttributeList(const EGLint* attrib_list); private: // Total color component bits in the color buffer.
diff --git a/gpu/gles2_conform_support/egl/context.cc b/gpu/gles2_conform_support/egl/context.cc deleted file mode 100644 index 2f89b8e..0000000 --- a/gpu/gles2_conform_support/egl/context.cc +++ /dev/null
@@ -1,398 +0,0 @@ -// Copyright (c) 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "gpu/gles2_conform_support/egl/context.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "gpu/command_buffer/client/gles2_implementation.h" -#include "gpu/command_buffer/client/gles2_lib.h" -#include "gpu/command_buffer/client/transfer_buffer.h" -#include "gpu/command_buffer/common/value_state.h" -#include "gpu/command_buffer/service/context_group.h" -#include "gpu/command_buffer/service/mailbox_manager.h" -#include "gpu/command_buffer/service/memory_tracking.h" -#include "gpu/command_buffer/service/transfer_buffer_manager.h" -#include "gpu/command_buffer/service/valuebuffer_manager.h" -#include "gpu/gles2_conform_support/egl/config.h" -#include "gpu/gles2_conform_support/egl/display.h" -#include "gpu/gles2_conform_support/egl/surface.h" -#include "gpu/gles2_conform_support/egl/thread_state.h" - -// The slight complexification in this file comes from following properties: -// 1) Command buffer connection (context) can not be established without a -// GLSurface. EGL Context can be created independent of a surface. This is why -// the connection is created only during first MakeCurrent. -// 2) Command buffer MakeCurrent calls need the real gl context and surface be -// current. -// 3) Client can change real EGL context behind the scenes and then still expect -// command buffer MakeCurrent re-set the command buffer context. This is why all -// MakeCurrent calls must actually reset the real context, even though command -// buffer current context does not change. -// 4) EGL context can be destroyed without surface, but command buffer would -// need the surface to run various cleanups. If context is destroyed -// surfaceless, the context is marked lost before destruction. This is avoided -// if possible, since command buffer at the time of writing prints out debug -// text in this case. - -namespace { -const int32_t kCommandBufferSize = 1024 * 1024; -const int32_t kTransferBufferSize = 512 * 1024; -const bool kBindGeneratesResources = true; -const bool kLoseContextWhenOutOfMemory = false; -const bool kSupportClientSideArrays = true; -} - -namespace egl { -Context::Context(Display* display, const Config* config) - : display_(display), - config_(config), - is_current_in_some_thread_(false), - is_destroyed_(false) {} - -Context::~Context() { - // We might not have a surface, so we must lose the context. Cleanup will - // execute GL commands otherwise. TODO: if shared contexts are ever - // implemented, this will leak the GL resources. For pbuffer contexts, one - // could track the last current surface or create a surface for destroying - // purposes only. Other option would be to make the service usable without - // surface. - if (HasService()) { - if (!WasServiceContextLost()) - MarkServiceContextLost(); - DestroyService(); - } -} - -void Context::MarkDestroyed() { - is_destroyed_ = true; -} - -void Context::FlushAndSwapBuffers(gfx::GLSurface* current_surface) { - DCHECK(HasService() && is_current_in_some_thread_); - if (!Flush(current_surface)) - return; - current_surface->SwapBuffers(); -} - -bool Context::MakeCurrent(Context* current_context, - gfx::GLSurface* current_surface, - Context* new_context, - gfx::GLSurface* new_surface) { - if (!new_context && !current_context) { - return true; - } - - bool cleanup_old_current_context = false; - if (current_context) { - if (current_context->Flush(current_surface)) - cleanup_old_current_context = new_context != current_context; - } - - if (new_context) { - if (!new_context->IsCompatibleSurface(new_surface)) - return false; - - if (new_context->HasService()) { - if (new_context->WasServiceContextLost()) - return false; - if (new_context != current_context) { - // If Flush did not set the current context, set it now. Otherwise - // calling into the decoder is not ok. - if (!new_context->gl_context_->MakeCurrent(new_surface)) { - new_context->MarkServiceContextLost(); - return false; - } - } - if (new_context != current_context || new_surface != current_surface) - new_context->decoder_->SetSurface(new_surface); - if (!new_context->decoder_->MakeCurrent()) { - new_context->MarkServiceContextLost(); - return false; - } - } else { - if (!new_context->CreateService(new_surface)) { - return false; - } - } - } - - // The current_surface will be released when MakeCurrent succeeds. - // Cleanup in this case only. - if (cleanup_old_current_context) { - if (current_context->is_destroyed_ && current_surface != new_surface) { - current_context->gl_context_->MakeCurrent(current_surface); - // If we are releasing the context and we have one ref, it means that the - // ref will be lost and the object will be destroyed. Destroy the service - // explicitly here, so that cleanup can happen and client GL - // implementation does not print errors. - current_context->DestroyService(); - } else { - current_context->decoder_->ReleaseSurface(); - } - } - - return true; -} - -bool Context::ValidateAttributeList(const EGLint* attrib_list) { - if (attrib_list) { - for (int i = 0; attrib_list[i] != EGL_NONE; attrib_list += 2) { - switch (attrib_list[i]) { - case EGL_CONTEXT_CLIENT_VERSION: - break; - default: - return false; - } - } - } - return true; -} - -void Context::SetGpuControlClient(gpu::GpuControlClient*) { - // The client is not currently called, so don't store it. -} - -gpu::Capabilities Context::GetCapabilities() { - return decoder_->GetCapabilities(); -} - -int32_t Context::CreateImage(ClientBuffer buffer, - size_t width, - size_t height, - unsigned internalformat) { - NOTIMPLEMENTED(); - return -1; -} - -void Context::DestroyImage(int32_t id) { - NOTIMPLEMENTED(); -} - -int32_t Context::CreateGpuMemoryBufferImage(size_t width, - size_t height, - unsigned internalformat, - unsigned usage) { - NOTIMPLEMENTED(); - return -1; -} - -void Context::SignalQuery(uint32_t query, const base::Closure& callback) { - NOTIMPLEMENTED(); -} - -void Context::SetLock(base::Lock*) { - NOTIMPLEMENTED(); -} - -bool Context::IsGpuChannelLost() { - NOTIMPLEMENTED(); - return false; -} - -void Context::EnsureWorkVisible() { - // This is only relevant for out-of-process command buffers. -} - -gpu::CommandBufferNamespace Context::GetNamespaceID() const { - return gpu::CommandBufferNamespace::IN_PROCESS; -} - -gpu::CommandBufferId Context::GetCommandBufferID() const { - return gpu::CommandBufferId(); -} - -int32_t Context::GetExtraCommandBufferData() const { - return 0; -} - -uint64_t Context::GenerateFenceSyncRelease() { - return display_->GenerateFenceSyncRelease(); -} - -bool Context::IsFenceSyncRelease(uint64_t release) { - return display_->IsFenceSyncRelease(release); -} - -bool Context::IsFenceSyncFlushed(uint64_t release) { - return display_->IsFenceSyncFlushed(release); -} - -bool Context::IsFenceSyncFlushReceived(uint64_t release) { - return display_->IsFenceSyncFlushReceived(release); -} - -void Context::SignalSyncToken(const gpu::SyncToken& sync_token, - const base::Closure& callback) { - NOTIMPLEMENTED(); -} - -bool Context::CanWaitUnverifiedSyncToken(const gpu::SyncToken* sync_token) { - return false; -} - -void Context::ApplyCurrentContext(gfx::GLSurface* current_surface) { - DCHECK(HasService()); - // The current_surface will be the same as - // the surface of the decoder. We can not DCHECK as there is - // no accessor. - if (!WasServiceContextLost()) { - if (!gl_context_->MakeCurrent(current_surface)) - MarkServiceContextLost(); - } - gles2::SetGLContext(client_gl_context_.get()); -} - -void Context::ApplyContextReleased() { - gles2::SetGLContext(nullptr); -} - -bool Context::CreateService(gfx::GLSurface* gl_surface) { - scoped_refptr<gpu::TransferBufferManager> transfer_buffer_manager( - new gpu::TransferBufferManager(nullptr)); - transfer_buffer_manager->Initialize(); - - scoped_ptr<gpu::CommandBufferService> command_buffer( - new gpu::CommandBufferService(transfer_buffer_manager.get())); - if (!command_buffer->Initialize()) - return false; - - scoped_refptr<gpu::gles2::ContextGroup> group(new gpu::gles2::ContextGroup( - gpu_preferences_, nullptr, nullptr, - new gpu::gles2::ShaderTranslatorCache(gpu_preferences_), - new gpu::gles2::FramebufferCompletenessCache, nullptr, nullptr, nullptr, - true)); - - scoped_ptr<gpu::gles2::GLES2Decoder> decoder( - gpu::gles2::GLES2Decoder::Create(group.get())); - if (!decoder.get()) - return false; - - scoped_ptr<gpu::CommandExecutor> command_executor(new gpu::CommandExecutor( - command_buffer.get(), decoder.get(), decoder.get())); - - decoder->set_engine(command_executor.get()); - - scoped_refptr<gfx::GLContext> gl_context(gfx::GLContext::CreateGLContext( - nullptr, gl_surface, gfx::PreferDiscreteGpu)); - if (!gl_context) - return false; - - gl_context->MakeCurrent(gl_surface); - - gpu::gles2::ContextCreationAttribHelper helper; - config_->GetAttrib(EGL_ALPHA_SIZE, &helper.alpha_size); - config_->GetAttrib(EGL_BLUE_SIZE, &helper.blue_size); - config_->GetAttrib(EGL_GREEN_SIZE, &helper.green_size); - config_->GetAttrib(EGL_RED_SIZE, &helper.red_size); - config_->GetAttrib(EGL_DEPTH_SIZE, &helper.depth_size); - config_->GetAttrib(EGL_STENCIL_SIZE, &helper.stencil_size); - config_->GetAttrib(EGL_SAMPLES, &helper.samples); - config_->GetAttrib(EGL_SAMPLE_BUFFERS, &helper.sample_buffers); - - helper.buffer_preserved = false; - helper.bind_generates_resource = kBindGeneratesResources; - helper.fail_if_major_perf_caveat = false; - helper.lose_context_when_out_of_memory = kLoseContextWhenOutOfMemory; - helper.context_type = gpu::gles2::CONTEXT_TYPE_OPENGLES2; - std::vector<int32_t> attribs; - helper.Serialize(&attribs); - - if (!decoder->Initialize(gl_surface, gl_context.get(), - gl_surface->IsOffscreen(), gl_surface->GetSize(), - gpu::gles2::DisallowedFeatures(), attribs)) { - return false; - } - - command_buffer->SetPutOffsetChangeCallback( - base::Bind(&gpu::CommandExecutor::PutChanged, - base::Unretained(command_executor.get()))); - command_buffer->SetGetBufferChangeCallback( - base::Bind(&gpu::CommandExecutor::SetGetBuffer, - base::Unretained(command_executor.get()))); - - scoped_ptr<gpu::gles2::GLES2CmdHelper> gles2_cmd_helper( - new gpu::gles2::GLES2CmdHelper(command_buffer.get())); - if (!gles2_cmd_helper->Initialize(kCommandBufferSize)) { - decoder->Destroy(true); - return false; - } - - scoped_ptr<gpu::TransferBuffer> transfer_buffer( - new gpu::TransferBuffer(gles2_cmd_helper.get())); - - gles2_cmd_helper_.reset(gles2_cmd_helper.release()); - transfer_buffer_.reset(transfer_buffer.release()); - command_buffer_.reset(command_buffer.release()); - command_executor_.reset(command_executor.release()); - decoder_.reset(decoder.release()); - gl_context_ = gl_context.get(); - - scoped_ptr<gpu::gles2::GLES2Implementation> context( - new gpu::gles2::GLES2Implementation( - gles2_cmd_helper_.get(), nullptr, transfer_buffer_.get(), - kBindGeneratesResources, kLoseContextWhenOutOfMemory, - kSupportClientSideArrays, this)); - - if (!context->Initialize(kTransferBufferSize, kTransferBufferSize / 2, - kTransferBufferSize * 2, - gpu::gles2::GLES2Implementation::kNoLimit)) { - DestroyService(); - return false; - } - - context->EnableFeatureCHROMIUM("pepper3d_allow_buffers_on_multiple_targets"); - context->EnableFeatureCHROMIUM("pepper3d_support_fixed_attribs"); - client_gl_context_.reset(context.release()); - return true; -} - -void Context::DestroyService() { - DCHECK(HasService()); - bool have_context = !WasServiceContextLost(); - // The client gl interface might still be set to current global - // interface. This will be cleaned up in ApplyContextReleased - // with AutoCurrentContextRestore. - client_gl_context_.reset(); - gl_context_ = nullptr; - - transfer_buffer_.reset(); - command_executor_.reset(); - if (decoder_) - decoder_->Destroy(have_context); - gles2_cmd_helper_.reset(); - command_buffer_.reset(); -} - -bool Context::HasService() const { - return decoder_ != nullptr; -} - -void Context::MarkServiceContextLost() { - decoder_->MarkContextLost(gpu::error::kMakeCurrentFailed); -} - -bool Context::WasServiceContextLost() const { - return decoder_->WasContextLost(); -} - -bool Context::IsCompatibleSurface(gfx::GLSurface* gl_surface) { - EGLint value = EGL_NONE; - config_->GetAttrib(EGL_SURFACE_TYPE, &value); - bool config_is_offscreen = (value & EGL_PBUFFER_BIT) != 0; - return gl_surface->IsOffscreen() == config_is_offscreen; -} - -bool Context::Flush(gfx::GLSurface* gl_surface) { - if (WasServiceContextLost()) - return false; - if (!gl_context_->MakeCurrent(gl_surface)) { - MarkServiceContextLost(); - return false; - } - client_gl_context_->Flush(); - return true; -} - -} // namespace egl
diff --git a/gpu/gles2_conform_support/egl/context.h b/gpu/gles2_conform_support/egl/context.h deleted file mode 100644 index e07aaac5..0000000 --- a/gpu/gles2_conform_support/egl/context.h +++ /dev/null
@@ -1,120 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef GPU_GLES2_CONFORM_TEST_CONTEXT_H_ -#define GPU_GLES2_CONFORM_TEST_CONTEXT_H_ - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "gpu/command_buffer/client/gles2_cmd_helper.h" -#include "gpu/command_buffer/client/gpu_control.h" -#include "gpu/command_buffer/service/command_buffer_service.h" -#include "gpu/command_buffer/service/command_executor.h" -#include "gpu/command_buffer/service/gles2_cmd_decoder.h" -#include "gpu/command_buffer/service/gpu_preferences.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gl/gl_context.h" -#include "ui/gl/gl_context.h" -#include "ui/gl/gl_surface.h" -#include "ui/gl/gl_surface.h" -#include <EGL/egl.h> - -namespace gpu { -class TransferBuffer; -class TransferBufferManagerInterface; - -namespace gles2 { -class GLES2CmdHelper; -class GLES2Interface; -} // namespace gles2 -} // namespace gpu - -namespace egl { -class Display; -class Surface; -class Config; - -class Context : public base::RefCountedThreadSafe<Context>, - private gpu::GpuControl { - public: - Context(Display* display, const Config* config); - bool is_current_in_some_thread() const { return is_current_in_some_thread_; } - void set_is_current_in_some_thread(bool flag) { - is_current_in_some_thread_ = flag; - } - void MarkDestroyed(); - void FlushAndSwapBuffers(gfx::GLSurface* current_surface); - - static bool MakeCurrent(Context* current_context, - gfx::GLSurface* current_surface, - Context* new_context, - gfx::GLSurface* new_surface); - - static bool ValidateAttributeList(const EGLint* attrib_list); - - // GpuControl implementation. - void SetGpuControlClient(gpu::GpuControlClient*) override; - gpu::Capabilities GetCapabilities() override; - int32_t CreateImage(ClientBuffer buffer, - size_t width, - size_t height, - unsigned internalformat) override; - void DestroyImage(int32_t id) override; - int32_t CreateGpuMemoryBufferImage(size_t width, - size_t height, - unsigned internalformat, - unsigned usage) override; - void SignalQuery(uint32_t query, const base::Closure& callback) override; - void SetLock(base::Lock*) override; - bool IsGpuChannelLost() override; - void EnsureWorkVisible() override; - gpu::CommandBufferNamespace GetNamespaceID() const override; - gpu::CommandBufferId GetCommandBufferID() const override; - int32_t GetExtraCommandBufferData() const override; - uint64_t GenerateFenceSyncRelease() override; - bool IsFenceSyncRelease(uint64_t release) override; - bool IsFenceSyncFlushed(uint64_t release) override; - bool IsFenceSyncFlushReceived(uint64_t release) override; - void SignalSyncToken(const gpu::SyncToken& sync_token, - const base::Closure& callback) override; - bool CanWaitUnverifiedSyncToken(const gpu::SyncToken* sync_token) override; - - // Called by ThreadState to set the needed global variables when this context - // is current. - void ApplyCurrentContext(gfx::GLSurface* current_surface); - static void ApplyContextReleased(); - - private: - friend class base::RefCountedThreadSafe<Context>; - ~Context() override; - bool CreateService(gfx::GLSurface* gl_surface); - void DestroyService(); - // Returns true if the object has GL service, either a working one or one - // that has lost its GL context. - bool HasService() const; - void MarkServiceContextLost(); - bool WasServiceContextLost() const; - bool IsCompatibleSurface(gfx::GLSurface* gl_surface); - bool Flush(gfx::GLSurface* gl_surface); - - Display* display_; - const Config* config_; - bool is_current_in_some_thread_; - bool is_destroyed_; - gpu::GpuPreferences gpu_preferences_; - scoped_ptr<gpu::CommandBufferService> command_buffer_; - scoped_ptr<gpu::gles2::GLES2CmdHelper> gles2_cmd_helper_; - scoped_ptr<gpu::gles2::GLES2Decoder> decoder_; - scoped_ptr<gpu::CommandExecutor> command_executor_; - scoped_ptr<gpu::TransferBuffer> transfer_buffer_; - - scoped_refptr<gfx::GLContext> gl_context_; - - scoped_ptr<gpu::gles2::GLES2Interface> client_gl_context_; - DISALLOW_COPY_AND_ASSIGN(Context); -}; - -} // namespace egl - -#endif // GPU_GLES2_CONFORM_TEST_CONTEXT_H_
diff --git a/gpu/gles2_conform_support/egl/display.cc b/gpu/gles2_conform_support/egl/display.cc index 2053f7d..a19718b 100644 --- a/gpu/gles2_conform_support/egl/display.cc +++ b/gpu/gles2_conform_support/egl/display.cc
@@ -4,114 +4,133 @@ #include "gpu/gles2_conform_support/egl/display.h" +#include <stddef.h> +#include <stdint.h> + +#include <vector> +#include "base/at_exit.h" +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/lazy_instance.h" +#include "gpu/command_buffer/client/gles2_implementation.h" +#include "gpu/command_buffer/client/gles2_lib.h" +#include "gpu/command_buffer/client/transfer_buffer.h" +#include "gpu/command_buffer/common/value_state.h" +#include "gpu/command_buffer/service/context_group.h" +#include "gpu/command_buffer/service/mailbox_manager.h" +#include "gpu/command_buffer/service/memory_tracking.h" +#include "gpu/command_buffer/service/transfer_buffer_manager.h" +#include "gpu/command_buffer/service/valuebuffer_manager.h" #include "gpu/gles2_conform_support/egl/config.h" -#include "gpu/gles2_conform_support/egl/context.h" #include "gpu/gles2_conform_support/egl/surface.h" -#include "gpu/gles2_conform_support/egl/thread_state.h" +#include "gpu/gles2_conform_support/egl/test_support.h" + +namespace { +const int32_t kCommandBufferSize = 1024 * 1024; +const int32_t kTransferBufferSize = 512 * 1024; +} namespace egl { +#if defined(COMMAND_BUFFER_GLES_LIB_SUPPORT_ONLY) +// egl::Display is used for comformance tests and command_buffer_gles. We only +// need the exit manager for the command_buffer_gles library. +// TODO(hendrikw): Find a cleaner solution for this. +namespace { +base::LazyInstance<base::Lock>::Leaky g_exit_manager_lock; +int g_exit_manager_use_count; +base::AtExitManager* g_exit_manager; +void RefAtExitManager() { + base::AutoLock lock(g_exit_manager_lock.Get()); +#if defined(COMPONENT_BUILD) + if (g_command_buffer_gles_has_atexit_manager) { + return; + } +#endif + if (g_exit_manager_use_count == 0) { + g_exit_manager = new base::AtExitManager; + } + ++g_exit_manager_use_count; +} +void ReleaseAtExitManager() { + base::AutoLock lock(g_exit_manager_lock.Get()); +#if defined(COMPONENT_BUILD) + if (g_command_buffer_gles_has_atexit_manager) { + return; + } +#endif + --g_exit_manager_use_count; + if (g_exit_manager_use_count == 0) { + delete g_exit_manager; + g_exit_manager = nullptr; + } +} +} +#endif -Display::Display() - : is_initialized_(false), - next_create_window_surface_creates_pbuffer_(false), - window_surface_pbuffer_width_(0), - window_surface_pbuffer_height_(0) {} +Display::Display(EGLNativeDisplayType display_id) + : display_id_(display_id), + is_initialized_(false), + create_offscreen_(false), + create_offscreen_width_(0), + create_offscreen_height_(0), + next_fence_sync_release_(1) { +#if defined(COMMAND_BUFFER_GLES_LIB_SUPPORT_ONLY) + RefAtExitManager(); +#endif +} Display::~Display() { - surfaces_.clear(); - contexts_.clear(); -} -void Display::SetNextCreateWindowSurfaceCreatesPBuffer(EGLint width, - EGLint height) { - next_create_window_surface_creates_pbuffer_ = true; - window_surface_pbuffer_width_ = width; - window_surface_pbuffer_height_ = height; + gles2::Terminate(); +#if defined(COMMAND_BUFFER_GLES_LIB_SUPPORT_ONLY) + ReleaseAtExitManager(); +#endif } -EGLBoolean Display::Initialize(ThreadState* ts, EGLint* major, EGLint* minor) { - base::AutoLock auto_lock(lock_); +bool Display::Initialize() { + gles2::Initialize(); is_initialized_ = true; - - if (major) - *major = 1; - if (minor) - *minor = 4; - return ts->ReturnSuccess(EGL_TRUE); + return true; } -EGLBoolean Display::Terminate(ThreadState* ts) { - base::AutoLock auto_lock(lock_); - is_initialized_ = false; - surfaces_.clear(); - for (const auto& context : contexts_) - context->MarkDestroyed(); - contexts_.clear(); - return ts->ReturnSuccess(EGL_TRUE); +bool Display::IsValidConfig(EGLConfig config) { + return (config != NULL) && (config == config_.get()); } -const char* Display::QueryString(ThreadState* ts, EGLint name) { - base::AutoLock auto_lock(lock_); - if (!is_initialized_) - return ts->ReturnError<const char*>(EGL_NOT_INITIALIZED, nullptr); - switch (name) { - case EGL_CLIENT_APIS: - return ts->ReturnSuccess("OpenGL_ES"); - case EGL_EXTENSIONS: - return ts->ReturnSuccess(""); - case EGL_VENDOR: - return ts->ReturnSuccess("Google Inc."); - case EGL_VERSION: - return ts->ReturnSuccess("1.4"); - default: - return ts->ReturnError<const char*>(EGL_BAD_PARAMETER, nullptr); - } -} - -EGLBoolean Display::ChooseConfig(ThreadState* ts, - const EGLint* attrib_list, - EGLConfig* configs, - EGLint config_size, - EGLint* num_config) { - base::AutoLock auto_lock(lock_); - if (!is_initialized_) - return ts->ReturnError(EGL_NOT_INITIALIZED, EGL_FALSE); - if (num_config == nullptr) - return ts->ReturnError(EGL_BAD_PARAMETER, EGL_FALSE); - if (!Config::ValidateAttributeList(attrib_list)) - return ts->ReturnError(EGL_BAD_ATTRIBUTE, EGL_FALSE); - InitializeConfigsIfNeeded(); - if (!configs) - config_size = 0; - *num_config = 0; - for (size_t i = 0; i < arraysize(configs_); ++i) { - if (configs_[i]->Matches(attrib_list)) { - if (*num_config < config_size) { - configs[*num_config] = configs_[i].get(); - } - ++*num_config; +bool Display::ChooseConfigs(EGLConfig* configs, + EGLint config_size, + EGLint* num_config) { + // TODO(alokp): Find out a way to find all configs. CommandBuffer currently + // does not support finding or choosing configs. + *num_config = 1; + if (configs != NULL) { + if (config_ == NULL) { + config_.reset(new Config); } + configs[0] = config_.get(); } - return ts->ReturnSuccess(EGL_TRUE); + return true; } -EGLBoolean Display::GetConfigs(ThreadState* ts, - EGLConfig* configs, - EGLint config_size, - EGLint* num_config) { - base::AutoLock auto_lock(lock_); - if (!is_initialized_) - return ts->ReturnError(EGL_NOT_INITIALIZED, EGL_FALSE); - if (num_config == nullptr) - return ts->ReturnError(EGL_BAD_PARAMETER, EGL_FALSE); - InitializeConfigsIfNeeded(); - if (!configs) - config_size = 0; - *num_config = arraysize(configs_); - size_t count = - std::min(arraysize(configs_), static_cast<size_t>(config_size)); - for (size_t i = 0; i < count; ++i) - configs[i] = configs_[i].get(); - return ts->ReturnSuccess(EGL_TRUE); +bool Display::GetConfigs(EGLConfig* configs, + EGLint config_size, + EGLint* num_config) { + // TODO(alokp): Find out a way to find all configs. CommandBuffer currently + // does not support finding or choosing configs. + *num_config = 1; + if (configs != NULL) { + if (config_ == NULL) { + config_.reset(new Config); + } + configs[0] = config_.get(); + } + return true; +} + +bool Display::GetConfigAttrib(EGLConfig config, + EGLint attribute, + EGLint* value) { + const egl::Config* cfg = static_cast<egl::Config*>(config); + return cfg->GetAttrib(attribute, value); } bool Display::IsValidNativeWindow(EGLNativeWindowType win) { @@ -123,229 +142,248 @@ #endif // OS_WIN } -EGLBoolean Display::GetConfigAttrib(ThreadState* ts, - EGLConfig cfg, - EGLint attribute, - EGLint* value) { - base::AutoLock auto_lock(lock_); - if (!is_initialized_) - return ts->ReturnError(EGL_NOT_INITIALIZED, EGL_FALSE); - const egl::Config* config = GetConfig(cfg); - if (!config) - return ts->ReturnError(EGL_BAD_CONFIG, EGL_FALSE); - if (!config->GetAttrib(attribute, value)) - return ts->ReturnError(EGL_BAD_ATTRIBUTE, EGL_FALSE); - return ts->ReturnSuccess(EGL_TRUE); +bool Display::IsValidSurface(EGLSurface surface) { + return (surface != NULL) && (surface == surface_.get()); } -EGLSurface Display::CreatePbufferSurface(ThreadState* ts, - EGLConfig cfg, - const EGLint* attrib_list) { - base::AutoLock auto_lock(lock_); - if (!is_initialized_) - return ts->ReturnError(EGL_NOT_INITIALIZED, EGL_NO_SURFACE); - const egl::Config* config = GetConfig(cfg); - if (!config) - return ts->ReturnError(EGL_BAD_CONFIG, EGL_NO_SURFACE); - EGLint value = EGL_NONE; - config->GetAttrib(EGL_SURFACE_TYPE, &value); - if ((value & EGL_PBUFFER_BIT) == 0) - return ts->ReturnError(EGL_BAD_MATCH, EGL_NO_SURFACE); - if (!egl::Surface::ValidatePbufferAttributeList(attrib_list)) - return ts->ReturnError(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE); - - int width = 1; - int height = 1; - if (attrib_list) { - for (const int32_t* attr = attrib_list; attr[0] != EGL_NONE; attr += 2) { - switch (attr[0]) { - case EGL_WIDTH: - width = attr[1]; - break; - case EGL_HEIGHT: - height = attr[1]; - break; - } - } - } - return DoCreatePbufferSurface(ts, width, height); -} - -EGLSurface Display::DoCreatePbufferSurface(ThreadState* ts, - EGLint width, - EGLint height) { - lock_.AssertAcquired(); - scoped_refptr<gfx::GLSurface> gl_surface; - gl_surface = - gfx::GLSurface::CreateOffscreenGLSurface(gfx::Size(width, height)); - if (!gl_surface) - return ts->ReturnError(EGL_BAD_ALLOC, nullptr); - surfaces_.emplace_back(new Surface(gl_surface.get())); - return ts->ReturnSuccess<EGLSurface>(surfaces_.back().get()); -} - -EGLSurface Display::CreateWindowSurface(ThreadState* ts, - EGLConfig cfg, +EGLSurface Display::CreateWindowSurface(EGLConfig config, EGLNativeWindowType win, const EGLint* attrib_list) { - base::AutoLock auto_lock(lock_); - if (!is_initialized_) - return ts->ReturnError(EGL_NOT_INITIALIZED, EGL_NO_SURFACE); - const egl::Config* config = GetConfig(cfg); - if (!config) - return ts->ReturnError(EGL_BAD_CONFIG, EGL_NO_SURFACE); - EGLint value = EGL_NONE; - config->GetAttrib(EGL_SURFACE_TYPE, &value); - if ((value & EGL_WINDOW_BIT) == 0) - return ts->ReturnError(EGL_BAD_CONFIG, EGL_NO_SURFACE); - if (!next_create_window_surface_creates_pbuffer_ && !IsValidNativeWindow(win)) - return ts->ReturnError(EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE); - if (!Surface::ValidateWindowAttributeList(attrib_list)) - return ts->ReturnError(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE); - if (next_create_window_surface_creates_pbuffer_) { - next_create_window_surface_creates_pbuffer_ = false; - window_surface_pbuffer_width_ = 0; - window_surface_pbuffer_height_ = 0; - return DoCreatePbufferSurface(ts, window_surface_pbuffer_width_, - window_surface_pbuffer_height_); + if (surface_ != NULL) { + // We do not support more than one window surface. + return EGL_NO_SURFACE; } - scoped_refptr<gfx::GLSurface> gl_surface; - gl_surface = gfx::GLSurface::CreateViewGLSurface(win); - if (!gl_surface) - return ts->ReturnError(EGL_BAD_ALLOC, EGL_NO_SURFACE); - surfaces_.emplace_back(new Surface(gl_surface.get())); - return ts->ReturnSuccess(surfaces_.back().get()); -} -EGLBoolean Display::DestroySurface(ThreadState* ts, EGLSurface sfe) { - base::AutoLock auto_lock(lock_); - if (!is_initialized_) - return ts->ReturnError(EGL_NOT_INITIALIZED, EGL_FALSE); - auto it = std::find(surfaces_.begin(), surfaces_.end(), sfe); - if (it == surfaces_.end()) - return ts->ReturnError(EGL_BAD_SURFACE, EGL_FALSE); - surfaces_.erase(it); - return ts->ReturnSuccess(EGL_TRUE); -} - -EGLBoolean Display::ReleaseCurrent(ThreadState* ts) { - base::AutoLock auto_lock(lock_); - if (!is_initialized_) - return ts->ReturnSuccess(EGL_TRUE); - ThreadState::AutoCurrentContextRestore accr(ts); - if (ts->current_context()) { - Context::MakeCurrent(ts->current_context(), - ts->current_surface()->gl_surface(), nullptr, nullptr); - accr.SetCurrent(nullptr, nullptr); + { + gpu::TransferBufferManager* manager = + new gpu::TransferBufferManager(nullptr); + transfer_buffer_manager_ = manager; + manager->Initialize(); } - return ts->ReturnSuccess(EGL_TRUE); + scoped_ptr<gpu::CommandBufferService> command_buffer( + new gpu::CommandBufferService(transfer_buffer_manager_.get())); + if (!command_buffer->Initialize()) + return NULL; + + scoped_refptr<gpu::gles2::ContextGroup> group(new gpu::gles2::ContextGroup( + gpu_preferences_, NULL, NULL, + new gpu::gles2::ShaderTranslatorCache(gpu_preferences_), + new gpu::gles2::FramebufferCompletenessCache, NULL, NULL, NULL, true)); + + decoder_.reset(gpu::gles2::GLES2Decoder::Create(group.get())); + if (!decoder_.get()) + return EGL_NO_SURFACE; + + executor_.reset( + new gpu::CommandExecutor(command_buffer.get(), decoder_.get(), NULL)); + + decoder_->set_engine(executor_.get()); + gfx::Size size(create_offscreen_width_, create_offscreen_height_); + if (create_offscreen_) { + gl_surface_ = gfx::GLSurface::CreateOffscreenGLSurface(size); + create_offscreen_ = false; + create_offscreen_width_ = 0; + create_offscreen_height_ = 0; + } else { + gl_surface_ = gfx::GLSurface::CreateViewGLSurface(win); + } + if (!gl_surface_.get()) + return EGL_NO_SURFACE; + + gl_context_ = gfx::GLContext::CreateGLContext(NULL, + gl_surface_.get(), + gfx::PreferDiscreteGpu); + if (!gl_context_.get()) + return EGL_NO_SURFACE; + + gl_context_->MakeCurrent(gl_surface_.get()); + + EGLint depth_size = 0; + EGLint alpha_size = 0; + EGLint stencil_size = 0; + GetConfigAttrib(config, EGL_DEPTH_SIZE, &depth_size); + GetConfigAttrib(config, EGL_ALPHA_SIZE, &alpha_size); + GetConfigAttrib(config, EGL_STENCIL_SIZE, &stencil_size); + std::vector<int32_t> attribs; + attribs.push_back(EGL_DEPTH_SIZE); + attribs.push_back(depth_size); + attribs.push_back(EGL_ALPHA_SIZE); + attribs.push_back(alpha_size); + attribs.push_back(EGL_STENCIL_SIZE); + attribs.push_back(stencil_size); + // TODO(gman): Insert attrib_list. Although ES 1.1 says it must be null + attribs.push_back(EGL_NONE); + + if (!decoder_->Initialize(gl_surface_.get(), + gl_context_.get(), + gl_surface_->IsOffscreen(), + size, + gpu::gles2::DisallowedFeatures(), + attribs)) { + return EGL_NO_SURFACE; + } + + command_buffer->SetPutOffsetChangeCallback(base::Bind( + &gpu::CommandExecutor::PutChanged, base::Unretained(executor_.get()))); + command_buffer->SetGetBufferChangeCallback(base::Bind( + &gpu::CommandExecutor::SetGetBuffer, base::Unretained(executor_.get()))); + + scoped_ptr<gpu::gles2::GLES2CmdHelper> cmd_helper( + new gpu::gles2::GLES2CmdHelper(command_buffer.get())); + if (!cmd_helper->Initialize(kCommandBufferSize)) + return NULL; + + scoped_ptr<gpu::TransferBuffer> transfer_buffer(new gpu::TransferBuffer( + cmd_helper.get())); + + command_buffer_.reset(command_buffer.release()); + transfer_buffer_.reset(transfer_buffer.release()); + gles2_cmd_helper_.reset(cmd_helper.release()); + surface_.reset(new Surface(win)); + + return surface_.get(); } -EGLBoolean Display::MakeCurrent(ThreadState* ts, - EGLSurface draw, - EGLSurface read, - EGLSurface ctx) { - base::AutoLock auto_lock(lock_); - if (!is_initialized_) - return ts->ReturnError(EGL_NOT_INITIALIZED, EGL_FALSE); - ThreadState::AutoCurrentContextRestore accr(ts); - // Client might have called use because it changed some other gl binding - // global state. For example, the client might have called eglMakeCurrent on - // the same EGL as what command buffer uses. The client probably knows that - // this invalidates the internal state of command buffer, too. So reset the - // current context with accr in any case, regardless whether context or - // surface pointer changes. - Surface* new_surface = GetSurface(draw); - if (!new_surface) - return ts->ReturnError(EGL_BAD_SURFACE, EGL_FALSE); - new_surface = GetSurface(read); - if (!new_surface) - return ts->ReturnError(EGL_BAD_SURFACE, EGL_FALSE); - egl::Context* new_context = GetContext(ctx); - if (!new_context) - return ts->ReturnError(EGL_BAD_CONTEXT, EGL_FALSE); - if (draw != read) - return ts->ReturnError(EGL_BAD_MATCH, EGL_FALSE); - - Surface* current_surface = ts->current_surface(); - Context* current_context = ts->current_context(); - - if (current_context != new_context && - new_context->is_current_in_some_thread()) - return ts->ReturnError(EGL_BAD_ACCESS, EGL_FALSE); - - if (current_surface != new_surface && - new_surface->is_current_in_some_thread()) - return ts->ReturnError(EGL_BAD_ACCESS, EGL_FALSE); - - if (!Context::MakeCurrent( - current_context, - current_context ? current_surface->gl_surface() : nullptr, - new_context, new_context ? new_surface->gl_surface() : nullptr)) - return ts->ReturnError(EGL_BAD_MATCH, EGL_FALSE); - - accr.SetCurrent(new_surface, new_context); - return ts->ReturnSuccess(EGL_TRUE); +void Display::DestroySurface(EGLSurface surface) { + DCHECK(IsValidSurface(surface)); + executor_.reset(); + if (decoder_.get()) { + decoder_->Destroy(true); + } + decoder_.reset(); + gl_surface_ = NULL; + gl_context_ = NULL; + surface_.reset(); } -EGLBoolean Display::SwapBuffers(ThreadState* ts, EGLSurface sfe) { - base::AutoLock auto_lock(lock_); - if (!is_initialized_) - return ts->ReturnError(EGL_NOT_INITIALIZED, EGL_FALSE); - egl::Surface* surface = GetSurface(sfe); - if (!surface) - return ts->ReturnError(EGL_BAD_SURFACE, EGL_FALSE); - if (ts->current_surface() != surface) - return ts->ReturnError(EGL_BAD_SURFACE, EGL_FALSE); - ts->current_context()->FlushAndSwapBuffers(surface->gl_surface()); - return ts->ReturnSuccess(EGL_TRUE); +void Display::SwapBuffers(EGLSurface surface) { + DCHECK(IsValidSurface(surface)); + context_->SwapBuffers(); } -EGLContext Display::CreateContext(ThreadState* ts, - EGLConfig cfg, +bool Display::IsValidContext(EGLContext ctx) { + return (ctx != NULL) && (ctx == context_.get()); +} + +EGLContext Display::CreateContext(EGLConfig config, EGLContext share_ctx, const EGLint* attrib_list) { - base::AutoLock auto_lock(lock_); - if (!is_initialized_) - return ts->ReturnError(EGL_NOT_INITIALIZED, EGL_NO_CONTEXT); - if (share_ctx != EGL_NO_CONTEXT) { - egl::Context* share_context = GetContext(share_ctx); - if (!share_context) - return ts->ReturnError(EGL_BAD_CONTEXT, EGL_NO_CONTEXT); - // TODO(alokp): Add support for shared contexts. - return ts->ReturnError(EGL_BAD_MATCH, EGL_NO_CONTEXT); + DCHECK(IsValidConfig(config)); + // TODO(alokp): Add support for shared contexts. + if (share_ctx != NULL) + return EGL_NO_CONTEXT; + + DCHECK(command_buffer_ != NULL); + DCHECK(transfer_buffer_.get()); + + bool bind_generates_resources = true; + bool lose_context_when_out_of_memory = false; + bool support_client_side_arrays = true; + + context_.reset( + new gpu::gles2::GLES2Implementation(gles2_cmd_helper_.get(), + NULL, + transfer_buffer_.get(), + bind_generates_resources, + lose_context_when_out_of_memory, + support_client_side_arrays, + this)); + + if (!context_->Initialize( + kTransferBufferSize, + kTransferBufferSize / 2, + kTransferBufferSize * 2, + gpu::gles2::GLES2Implementation::kNoLimit)) { + return EGL_NO_CONTEXT; } - if (!egl::Context::ValidateAttributeList(attrib_list)) - return ts->ReturnError(EGL_BAD_ATTRIBUTE, EGL_NO_CONTEXT); - const egl::Config* config = GetConfig(cfg); - if (!config) - return ts->ReturnError(EGL_BAD_CONFIG, EGL_NO_CONTEXT); - scoped_refptr<Context> context(new Context(this, config)); - if (!context) - return ts->ReturnError(EGL_BAD_ALLOC, EGL_NO_CONTEXT); - contexts_.emplace_back(context.get()); - return ts->ReturnSuccess<EGLContext>(context.get()); + + context_->EnableFeatureCHROMIUM("pepper3d_allow_buffers_on_multiple_targets"); + context_->EnableFeatureCHROMIUM("pepper3d_support_fixed_attribs"); + + return context_.get(); } -EGLBoolean Display::DestroyContext(ThreadState* ts, EGLContext ctx) { - base::AutoLock auto_lock(lock_); - if (!is_initialized_) - return ts->ReturnError(EGL_NOT_INITIALIZED, EGL_FALSE); - auto it = std::find(contexts_.begin(), contexts_.end(), ctx); - if (it == contexts_.end()) - return ts->ReturnError(EGL_BAD_CONTEXT, EGL_FALSE); - (*it)->MarkDestroyed(); - contexts_.erase(it); - return ts->ReturnSuccess(EGL_TRUE); +void Display::DestroyContext(EGLContext ctx) { + DCHECK(IsValidContext(ctx)); + context_.reset(); + transfer_buffer_.reset(); +} + +bool Display::MakeCurrent(EGLSurface draw, EGLSurface read, EGLContext ctx) { + if (ctx == EGL_NO_CONTEXT) { + gles2::SetGLContext(NULL); + } else { + DCHECK(IsValidSurface(draw)); + DCHECK(IsValidSurface(read)); + DCHECK(IsValidContext(ctx)); + gles2::SetGLContext(context_.get()); + gl_context_->MakeCurrent(gl_surface_.get()); + } + return true; +} + +void Display::SetGpuControlClient(gpu::GpuControlClient*) { + // The client is not currently called, so don't store it. +} + +gpu::Capabilities Display::GetCapabilities() { + return decoder_->GetCapabilities(); +} + +int32_t Display::CreateImage(ClientBuffer buffer, + size_t width, + size_t height, + unsigned internalformat) { + NOTIMPLEMENTED(); + return -1; +} + +void Display::DestroyImage(int32_t id) { + NOTIMPLEMENTED(); +} + +int32_t Display::CreateGpuMemoryBufferImage(size_t width, + size_t height, + unsigned internalformat, + unsigned usage) { + NOTIMPLEMENTED(); + return -1; +} + +void Display::SignalQuery(uint32_t query, const base::Closure& callback) { + NOTIMPLEMENTED(); +} + +void Display::SetLock(base::Lock*) { + NOTIMPLEMENTED(); +} + +bool Display::IsGpuChannelLost() { + NOTIMPLEMENTED(); + return false; +} + +void Display::EnsureWorkVisible() { + // This is only relevant for out-of-process command buffers. +} + +gpu::CommandBufferNamespace Display::GetNamespaceID() const { + return gpu::CommandBufferNamespace::IN_PROCESS; +} + +gpu::CommandBufferId Display::GetCommandBufferID() const { + return gpu::CommandBufferId(); +} + +int32_t Display::GetExtraCommandBufferData() const { + return 0; } uint64_t Display::GenerateFenceSyncRelease() { - base::AutoLock auto_lock(lock_); return next_fence_sync_release_++; } bool Display::IsFenceSyncRelease(uint64_t release) { - base::AutoLock auto_lock(lock_); return release > 0 && release < next_fence_sync_release_; } @@ -357,41 +395,13 @@ return IsFenceSyncRelease(release); } -void Display::InitializeConfigsIfNeeded() { - lock_.AssertAcquired(); - if (!configs_[0]) { - // The interface offers separate configs for window and pbuffer. - // This way we can record the client intention at context creation time. - // The GL implementation (gfx::GLContext and gfx::GLSurface) needs this - // distinction when creating a context. - configs_[0].reset(new Config(EGL_WINDOW_BIT)); - configs_[1].reset(new Config(EGL_PBUFFER_BIT)); - } +void Display::SignalSyncToken(const gpu::SyncToken& sync_token, + const base::Closure& callback) { + NOTIMPLEMENTED(); } -const Config* Display::GetConfig(EGLConfig cfg) { - lock_.AssertAcquired(); - for (const auto& config : configs_) { - if (config.get() == cfg) - return config.get(); - } - return nullptr; -} - -Surface* Display::GetSurface(EGLSurface surface) { - lock_.AssertAcquired(); - auto it = std::find(surfaces_.begin(), surfaces_.end(), surface); - if (it == surfaces_.end()) - return nullptr; - return it->get(); -} - -Context* Display::GetContext(EGLContext context) { - lock_.AssertAcquired(); - auto it = std::find(contexts_.begin(), contexts_.end(), context); - if (it == contexts_.end()) - return nullptr; - return it->get(); +bool Display::CanWaitUnverifiedSyncToken(const gpu::SyncToken* sync_token) { + return false; } } // namespace egl
diff --git a/gpu/gles2_conform_support/egl/display.h b/gpu/gles2_conform_support/egl/display.h index 8ed12a4..52252323 100644 --- a/gpu/gles2_conform_support/egl/display.h +++ b/gpu/gles2_conform_support/egl/display.h
@@ -9,98 +9,125 @@ #include <stddef.h> #include <stdint.h> -#include <vector> - #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" -#include "base/synchronization/lock.h" +#include "gpu/command_buffer/client/gles2_cmd_helper.h" +#include "gpu/command_buffer/client/gpu_control.h" +#include "gpu/command_buffer/service/command_buffer_service.h" +#include "gpu/command_buffer/service/command_executor.h" +#include "gpu/command_buffer/service/gles2_cmd_decoder.h" +#include "gpu/command_buffer/service/gpu_preferences.h" +#include "ui/gfx/native_widget_types.h" +#include "ui/gl/gl_context.h" +#include "ui/gl/gl_surface.h" + +namespace gpu { +class CommandBufferService; +class GpuControl; +class CommandExecutor; +class TransferBuffer; +class TransferBufferManagerInterface; + +namespace gles2 { +class GLES2CmdHelper; +class GLES2Implementation; +} // namespace gles2 +} // namespace gpu namespace egl { class Config; -class Context; class Surface; -class ThreadState; -class Display { +class Display : private gpu::GpuControl { public: - explicit Display(); - ~Display(); + explicit Display(EGLNativeDisplayType display_id); + ~Display() override; + + void SetCreateOffscreen(int width, int height) { + create_offscreen_ = true; + create_offscreen_width_ = width; + create_offscreen_height_ = height; + } bool is_initialized() const { return is_initialized_; } - - void ReleaseCurrentForReleaseThread(ThreadState*); - - // A function for windowless GTF tests. - void SetNextCreateWindowSurfaceCreatesPBuffer(EGLint width, EGLint height); - - EGLBoolean Initialize(ThreadState* ts, EGLint* major, EGLint* minor); - EGLBoolean Terminate(ThreadState* ts); - const char* QueryString(ThreadState* ts, EGLint name); + bool Initialize(); // Config routines. - EGLBoolean GetConfigAttrib(ThreadState* ts, - EGLConfig cfg, - EGLint attribute, - EGLint* value); - EGLBoolean ChooseConfig(ThreadState* ts, - const EGLint* attrib_list, - EGLConfig* configs, - EGLint config_size, - EGLint* num_config); - EGLBoolean GetConfigs(ThreadState*, - EGLConfig*, - EGLint config_size, - EGLint* num_config); + bool IsValidConfig(EGLConfig config); + bool ChooseConfigs( + EGLConfig* configs, EGLint config_size, EGLint* num_config); + bool GetConfigs(EGLConfig* configs, EGLint config_size, EGLint* num_config); + bool GetConfigAttrib(EGLConfig config, EGLint attribute, EGLint* value); // Surface routines. - static bool IsValidNativeWindow(EGLNativeWindowType); - EGLSurface CreatePbufferSurface(ThreadState*, - EGLConfig, - const EGLint* attrib_list); - EGLSurface CreateWindowSurface(ThreadState*, - EGLConfig, + bool IsValidNativeWindow(EGLNativeWindowType win); + bool IsValidSurface(EGLSurface surface); + EGLSurface CreateWindowSurface(EGLConfig config, EGLNativeWindowType win, const EGLint* attrib_list); - EGLBoolean DestroySurface(ThreadState*, EGLSurface); - EGLBoolean SwapBuffers(ThreadState*, EGLSurface); + void DestroySurface(EGLSurface surface); + void SwapBuffers(EGLSurface surface); // Context routines. - EGLContext CreateContext(ThreadState*, - EGLConfig, - EGLSurface share_ctx, + bool IsValidContext(EGLContext ctx); + EGLContext CreateContext(EGLConfig config, + EGLContext share_ctx, const EGLint* attrib_list); - EGLBoolean DestroyContext(ThreadState*, EGLContext); + void DestroyContext(EGLContext ctx); + bool MakeCurrent(EGLSurface draw, EGLSurface read, EGLContext ctx); - EGLBoolean ReleaseCurrent(ThreadState*); - EGLBoolean MakeCurrent(ThreadState*, EGLSurface, EGLSurface, EGLContext); - - uint64_t GenerateFenceSyncRelease(); - bool IsFenceSyncRelease(uint64_t release); - bool IsFenceSyncFlushed(uint64_t release); - bool IsFenceSyncFlushReceived(uint64_t release); + // GpuControl implementation. + void SetGpuControlClient(gpu::GpuControlClient*) override; + gpu::Capabilities GetCapabilities() override; + int32_t CreateImage(ClientBuffer buffer, + size_t width, + size_t height, + unsigned internalformat) override; + void DestroyImage(int32_t id) override; + int32_t CreateGpuMemoryBufferImage(size_t width, + size_t height, + unsigned internalformat, + unsigned usage) override; + void SignalQuery(uint32_t query, const base::Closure& callback) override; + void SetLock(base::Lock*) override; + bool IsGpuChannelLost() override; + void EnsureWorkVisible() override; + gpu::CommandBufferNamespace GetNamespaceID() const override; + gpu::CommandBufferId GetCommandBufferID() const override; + int32_t GetExtraCommandBufferData() const override; + uint64_t GenerateFenceSyncRelease() override; + bool IsFenceSyncRelease(uint64_t release) override; + bool IsFenceSyncFlushed(uint64_t release) override; + bool IsFenceSyncFlushReceived(uint64_t release) override; + void SignalSyncToken(const gpu::SyncToken& sync_token, + const base::Closure& callback) override; + bool CanWaitUnverifiedSyncToken(const gpu::SyncToken* sync_token) override; private: - void InitializeConfigsIfNeeded(); - const Config* GetConfig(EGLConfig); - Surface* GetSurface(EGLSurface); - Context* GetContext(EGLContext); - EGLSurface DoCreatePbufferSurface(ThreadState* ts, - EGLint width, - EGLint height); + EGLNativeDisplayType display_id_; - base::Lock lock_; + gpu::GpuPreferences gpu_preferences_; bool is_initialized_; - uint64_t next_fence_sync_release_; - std::vector<scoped_refptr<Surface>> surfaces_; - std::vector<scoped_refptr<Context>> contexts_; - scoped_ptr<Config> configs_[2]; - // GTF windowless support. - bool next_create_window_surface_creates_pbuffer_; - EGLint window_surface_pbuffer_width_; - EGLint window_surface_pbuffer_height_; + bool create_offscreen_; + int create_offscreen_width_; + int create_offscreen_height_; + uint64_t next_fence_sync_release_; + + scoped_refptr<gpu::TransferBufferManagerInterface> transfer_buffer_manager_; + scoped_ptr<gpu::CommandBufferService> command_buffer_; + scoped_ptr<gpu::CommandExecutor> executor_; + scoped_ptr<gpu::gles2::GLES2Decoder> decoder_; + scoped_refptr<gfx::GLContext> gl_context_; + scoped_refptr<gfx::GLSurface> gl_surface_; + scoped_ptr<gpu::gles2::GLES2CmdHelper> gles2_cmd_helper_; + scoped_ptr<gpu::TransferBuffer> transfer_buffer_; + + // TODO(alokp): Support more than one config, surface, and context. + scoped_ptr<Config> config_; + scoped_ptr<Surface> surface_; + scoped_ptr<gpu::gles2::GLES2Implementation> context_; DISALLOW_COPY_AND_ASSIGN(Display); };
diff --git a/gpu/gles2_conform_support/egl/egl.cc b/gpu/gles2_conform_support/egl/egl.cc index b14479bc3..5a81954b 100644 --- a/gpu/gles2_conform_support/egl/egl.cc +++ b/gpu/gles2_conform_support/egl/egl.cc
@@ -5,58 +5,184 @@ #include <EGL/egl.h> #include <stdint.h> +#include "base/command_line.h" +#include "base/environment.h" +#include "base/strings/string_split.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" #include "gpu/command_buffer/client/gles2_lib.h" -#include "gpu/gles2_conform_support/egl/config.h" -#include "gpu/gles2_conform_support/egl/context.h" +#include "gpu/command_buffer/service/gpu_switches.h" +#include "gpu/config/gpu_info_collector.h" +#include "gpu/config/gpu_util.h" #include "gpu/gles2_conform_support/egl/display.h" -#include "gpu/gles2_conform_support/egl/surface.h" -#include "gpu/gles2_conform_support/egl/thread_state.h" +#include "ui/gl/gl_context.h" +#include "ui/gl/gl_surface.h" + +#if REGAL_STATIC_EGL +extern "C" { + +typedef EGLContext RegalSystemContext; +#define REGAL_DECL +REGAL_DECL void RegalMakeCurrent( RegalSystemContext ctx ); + +} // extern "C" +#endif + +namespace { +void SetCurrentError(EGLint error_code) { +} + +template<typename T> +T EglError(EGLint error_code, T return_value) { + SetCurrentError(error_code); + return return_value; +} + +template<typename T> +T EglSuccess(T return_value) { + SetCurrentError(EGL_SUCCESS); + return return_value; +} + +EGLint ValidateDisplay(EGLDisplay dpy) { + if (dpy == EGL_NO_DISPLAY) + return EGL_BAD_DISPLAY; + + egl::Display* display = static_cast<egl::Display*>(dpy); + if (!display->is_initialized()) + return EGL_NOT_INITIALIZED; + + return EGL_SUCCESS; +} + +EGLint ValidateDisplayConfig(EGLDisplay dpy, EGLConfig config) { + EGLint error_code = ValidateDisplay(dpy); + if (error_code != EGL_SUCCESS) + return error_code; + + egl::Display* display = static_cast<egl::Display*>(dpy); + if (!display->IsValidConfig(config)) + return EGL_BAD_CONFIG; + + return EGL_SUCCESS; +} + +EGLint ValidateDisplaySurface(EGLDisplay dpy, EGLSurface surface) { + EGLint error_code = ValidateDisplay(dpy); + if (error_code != EGL_SUCCESS) + return error_code; + + egl::Display* display = static_cast<egl::Display*>(dpy); + if (!display->IsValidSurface(surface)) + return EGL_BAD_SURFACE; + + return EGL_SUCCESS; +} + +EGLint ValidateDisplayContext(EGLDisplay dpy, EGLContext context) { + EGLint error_code = ValidateDisplay(dpy); + if (error_code != EGL_SUCCESS) + return error_code; + + egl::Display* display = static_cast<egl::Display*>(dpy); + if (!display->IsValidContext(context)) + return EGL_BAD_CONTEXT; + + return EGL_SUCCESS; +} +} // namespace extern "C" { EGLAPI EGLint EGLAPIENTRY eglGetError() { - return egl::ThreadState::Get()->ConsumeErrorCode(); + // TODO(alokp): Fix me. + return EGL_SUCCESS; } EGLAPI EGLDisplay EGLAPIENTRY eglGetDisplay(EGLNativeDisplayType display_id) { - if (display_id != EGL_DEFAULT_DISPLAY) - return EGL_NO_DISPLAY; - return egl::ThreadState::Get()->GetDefaultDisplay(); + return new egl::Display(display_id); } EGLAPI EGLBoolean EGLAPIENTRY eglInitialize(EGLDisplay dpy, EGLint* major, EGLint* minor) { - egl::ThreadState* ts = egl::ThreadState::Get(); - egl::Display* display = ts->GetDisplay(dpy); - if (!display) - return ts->ReturnError(EGL_BAD_DISPLAY, EGL_FALSE); - return display->Initialize(ts, major, minor); + if (dpy == EGL_NO_DISPLAY) + return EglError(EGL_BAD_DISPLAY, EGL_FALSE); + + egl::Display* display = static_cast<egl::Display*>(dpy); + if (!display->Initialize()) + return EglError(EGL_NOT_INITIALIZED, EGL_FALSE); + + // eglInitialize can be called multiple times, prevent InitializeOneOff from + // being called multiple times. + if (gfx::GetGLImplementation() == gfx::kGLImplementationNone) { + base::CommandLine::StringVector argv; + scoped_ptr<base::Environment> env(base::Environment::Create()); + std::string env_string; + env->GetVar("CHROME_COMMAND_BUFFER_GLES2_ARGS", &env_string); +#if defined(OS_WIN) + argv = base::SplitString(base::UTF8ToUTF16(env_string), + base::kWhitespaceUTF16, base::TRIM_WHITESPACE, + base::SPLIT_WANT_NONEMPTY); + argv.insert(argv.begin(), base::UTF8ToUTF16("dummy")); +#else + argv = base::SplitString(env_string, + base::kWhitespaceASCII, base::TRIM_WHITESPACE, + base::SPLIT_WANT_NONEMPTY); + argv.insert(argv.begin(), "dummy"); +#endif + base::CommandLine::Init(0, nullptr); + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + // Need to call both Init and InitFromArgv, since Windows does not use + // argc, argv in CommandLine::Init(argc, argv). + command_line->InitFromArgv(argv); + if (!command_line->HasSwitch(switches::kDisableGpuDriverBugWorkarounds)) { + gpu::GPUInfo gpu_info; + gpu::CollectBasicGraphicsInfo(&gpu_info); + gpu::ApplyGpuDriverBugWorkarounds(gpu_info, command_line); + } + + gfx::GLSurface::InitializeOneOff(); + } + if (major) + *major = 1; + if (minor) + *minor = 4; + return EglSuccess(EGL_TRUE); } EGLAPI EGLBoolean EGLAPIENTRY eglTerminate(EGLDisplay dpy) { - egl::ThreadState* ts = egl::ThreadState::Get(); - egl::Display* display = ts->GetDisplay(dpy); - if (!display) - return ts->ReturnError(EGL_BAD_DISPLAY, EGL_FALSE); - return display->Terminate(ts); + EGLint error_code = ValidateDisplay(dpy); + if (error_code != EGL_SUCCESS) + return EglError(error_code, EGL_FALSE); + + egl::Display* display = static_cast<egl::Display*>(dpy); + delete display; + + // TODO: EGL specifies that the objects are marked for deletion and they will + // remain alive as long as "contexts or surfaces associated with display is + // current to any thread". + // Currently we delete the display here, and may also call exit handlers. + + return EglSuccess(EGL_TRUE); } EGLAPI const char* EGLAPIENTRY eglQueryString(EGLDisplay dpy, EGLint name) { - egl::ThreadState* ts = egl::ThreadState::Get(); - if (dpy == EGL_NO_DISPLAY) { - switch (name) { - case EGL_EXTENSIONS: - return ts->ReturnSuccess(""); - case EGL_VERSION: - return ts->ReturnSuccess("1.4"); - default: - break; - } + EGLint error_code = ValidateDisplay(dpy); + if (error_code != EGL_SUCCESS) + return EglError(error_code, static_cast<const char*>(NULL)); + + switch (name) { + case EGL_CLIENT_APIS: + return EglSuccess("OpenGL_ES"); + case EGL_EXTENSIONS: + return EglSuccess(""); + case EGL_VENDOR: + return EglSuccess("Google Inc."); + case EGL_VERSION: + return EglSuccess("1.4"); + default: + return EglError(EGL_BAD_PARAMETER, static_cast<const char*>(NULL)); } - egl::Display* display = ts->GetDisplay(dpy); - if (!display) - return ts->ReturnError<const char*>(EGL_BAD_DISPLAY, nullptr); - return display->QueryString(ts, name); } EGLAPI EGLBoolean EGLAPIENTRY eglChooseConfig(EGLDisplay dpy, @@ -64,57 +190,103 @@ EGLConfig* configs, EGLint config_size, EGLint* num_config) { - egl::ThreadState* ts = egl::ThreadState::Get(); - egl::Display* display = ts->GetDisplay(dpy); - if (!display) - return ts->ReturnError(EGL_BAD_DISPLAY, EGL_FALSE); - return display->ChooseConfig(ts, attrib_list, configs, config_size, - num_config); + EGLint error_code = ValidateDisplay(dpy); + if (error_code != EGL_SUCCESS) + return EglError(error_code, EGL_FALSE); + + if (num_config == NULL) + return EglError(EGL_BAD_PARAMETER, EGL_FALSE); + + egl::Display* display = static_cast<egl::Display*>(dpy); + if (!display->ChooseConfigs(configs, config_size, num_config)) + return EglError(EGL_BAD_ATTRIBUTE, EGL_FALSE); + + return EglSuccess(EGL_TRUE); } EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigs(EGLDisplay dpy, EGLConfig* configs, EGLint config_size, EGLint* num_config) { - egl::ThreadState* ts = egl::ThreadState::Get(); - egl::Display* display = ts->GetDisplay(dpy); - if (!display) - return ts->ReturnError(EGL_BAD_DISPLAY, EGL_FALSE); - return display->GetConfigs(ts, configs, config_size, num_config); + EGLint error_code = ValidateDisplay(dpy); + if (error_code != EGL_SUCCESS) + return EglError(error_code, EGL_FALSE); + + if (num_config == NULL) + return EglError(EGL_BAD_PARAMETER, EGL_FALSE); + + egl::Display* display = static_cast<egl::Display*>(dpy); + if (!display->GetConfigs(configs, config_size, num_config)) + return EglError(EGL_BAD_ATTRIBUTE, EGL_FALSE); + + return EglSuccess(EGL_TRUE); } EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigAttrib(EGLDisplay dpy, - EGLConfig cfg, + EGLConfig config, EGLint attribute, EGLint* value) { - egl::ThreadState* ts = egl::ThreadState::Get(); - egl::Display* display = ts->GetDisplay(dpy); - if (!display) - return ts->ReturnError(EGL_BAD_DISPLAY, EGL_FALSE); - return display->GetConfigAttrib(ts, cfg, attribute, value); + EGLint error_code = ValidateDisplayConfig(dpy, config); + if (error_code != EGL_SUCCESS) + return EglError(error_code, EGL_FALSE); + + egl::Display* display = static_cast<egl::Display*>(dpy); + if (!display->GetConfigAttrib(config, attribute, value)) + return EglError(EGL_BAD_ATTRIBUTE, EGL_FALSE); + + return EglSuccess(EGL_TRUE); } EGLAPI EGLSurface EGLAPIENTRY eglCreateWindowSurface(EGLDisplay dpy, - EGLConfig cfg, + EGLConfig config, EGLNativeWindowType win, const EGLint* attrib_list) { - egl::ThreadState* ts = egl::ThreadState::Get(); - egl::Display* display = ts->GetDisplay(dpy); - if (!display) - return ts->ReturnError(EGL_BAD_DISPLAY, EGL_NO_SURFACE); - return display->CreateWindowSurface(ts, cfg, win, attrib_list); + EGLint error_code = ValidateDisplayConfig(dpy, config); + if (error_code != EGL_SUCCESS) + return EglError(error_code, EGL_NO_SURFACE); + + egl::Display* display = static_cast<egl::Display*>(dpy); + if (!display->IsValidNativeWindow(win)) + return EglError(EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE); + + EGLSurface surface = display->CreateWindowSurface(config, win, attrib_list); + if (surface == EGL_NO_SURFACE) + return EglError(EGL_BAD_ALLOC, EGL_NO_SURFACE); + + return EglSuccess(surface); } EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferSurface(EGLDisplay dpy, - EGLConfig cfg, + EGLConfig config, const EGLint* attrib_list) { - egl::ThreadState* ts = egl::ThreadState::Get(); - egl::Display* display = ts->GetDisplay(dpy); - if (!display) - return ts->ReturnError(EGL_BAD_DISPLAY, EGL_NO_SURFACE); - return display->CreatePbufferSurface(ts, cfg, attrib_list); + EGLint error_code = ValidateDisplayConfig(dpy, config); + if (error_code != EGL_SUCCESS) + return EglError(error_code, EGL_NO_SURFACE); + + egl::Display* display = static_cast<egl::Display*>(dpy); + int width = 1; + int height = 1; + if (attrib_list) { + for (const int32_t* attr = attrib_list; attr[0] != EGL_NONE; attr += 2) { + switch (attr[0]) { + case EGL_WIDTH: + width = attr[1]; + break; + case EGL_HEIGHT: + height = attr[1]; + break; + } + } + } + display->SetCreateOffscreen(width, height); + + EGLSurface surface = display->CreateWindowSurface(config, 0, attrib_list); + if (surface == EGL_NO_SURFACE) + return EglError(EGL_BAD_ALLOC, EGL_NO_SURFACE); + + return EglSuccess(surface); } EGLAPI EGLSurface EGLAPIENTRY @@ -126,12 +298,14 @@ } EGLAPI EGLBoolean EGLAPIENTRY eglDestroySurface(EGLDisplay dpy, - EGLSurface sfe) { - egl::ThreadState* ts = egl::ThreadState::Get(); - egl::Display* display = ts->GetDisplay(dpy); - if (!display) - return ts->ReturnError(EGL_BAD_DISPLAY, EGL_FALSE); - return display->DestroySurface(ts, sfe); + EGLSurface surface) { + EGLint error_code = ValidateDisplaySurface(dpy, surface); + if (error_code != EGL_SUCCESS) + return EglError(error_code, EGL_FALSE); + + egl::Display* display = static_cast<egl::Display*>(dpy); + display->DestroySurface(surface); + return EglSuccess(EGL_TRUE); } EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurface(EGLDisplay dpy, @@ -154,8 +328,7 @@ } EGLAPI EGLBoolean EGLAPIENTRY eglReleaseThread(void) { - egl::ThreadState::ReleaseThread(); - return EGL_TRUE; + return EGL_FALSE; } EGLAPI EGLSurface EGLAPIENTRY @@ -191,42 +364,64 @@ } EGLAPI EGLContext EGLAPIENTRY eglCreateContext(EGLDisplay dpy, - EGLConfig cfg, - EGLContext share_ctx, + EGLConfig config, + EGLContext share_context, const EGLint* attrib_list) { - egl::ThreadState* ts = egl::ThreadState::Get(); - egl::Display* display = ts->GetDisplay(dpy); - if (!display) - return ts->ReturnError(EGL_BAD_DISPLAY, EGL_NO_CONTEXT); - return display->CreateContext(ts, cfg, share_ctx, attrib_list); + EGLint error_code = ValidateDisplayConfig(dpy, config); + if (error_code != EGL_SUCCESS) + return EglError(error_code, EGL_NO_CONTEXT); + + if (share_context != EGL_NO_CONTEXT) { + error_code = ValidateDisplayContext(dpy, share_context); + if (error_code != EGL_SUCCESS) + return EglError(error_code, EGL_NO_CONTEXT); + } + + egl::Display* display = static_cast<egl::Display*>(dpy); + EGLContext context = display->CreateContext( + config, share_context, attrib_list); + if (context == EGL_NO_CONTEXT) + return EglError(EGL_BAD_ALLOC, EGL_NO_CONTEXT); + + return EglSuccess(context); } EGLAPI EGLBoolean EGLAPIENTRY eglDestroyContext(EGLDisplay dpy, EGLContext ctx) { - egl::ThreadState* ts = egl::ThreadState::Get(); - egl::Display* display = ts->GetDisplay(dpy); - if (!display) - return ts->ReturnError(EGL_BAD_DISPLAY, EGL_FALSE); - return display->DestroyContext(ts, ctx); + EGLint error_code = ValidateDisplayContext(dpy, ctx); + if (error_code != EGL_SUCCESS) + return EglError(error_code, EGL_FALSE); + + egl::Display* display = static_cast<egl::Display*>(dpy); + display->DestroyContext(ctx); + return EGL_TRUE; } EGLAPI EGLBoolean EGLAPIENTRY eglMakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) { - egl::ThreadState* ts = egl::ThreadState::Get(); - if (draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE && - ctx == EGL_NO_CONTEXT) { - egl::Display* display = - dpy == EGL_NO_DISPLAY ? ts->GetDefaultDisplay() : ts->GetDisplay(dpy); - if (!display) - return ts->ReturnError(EGL_BAD_DISPLAY, EGL_FALSE); - return display->ReleaseCurrent(ts); + if (ctx != EGL_NO_CONTEXT) { + EGLint error_code = ValidateDisplaySurface(dpy, draw); + if (error_code != EGL_SUCCESS) + return EglError(error_code, EGL_FALSE); + error_code = ValidateDisplaySurface(dpy, read); + if (error_code != EGL_SUCCESS) + return EglError(error_code, EGL_FALSE); + error_code = ValidateDisplayContext(dpy, ctx); + if (error_code != EGL_SUCCESS) + return EglError(error_code, EGL_FALSE); } - egl::Display* display = ts->GetDisplay(dpy); - if (!display) - return ts->ReturnError(EGL_BAD_DISPLAY, EGL_FALSE); - return display->MakeCurrent(ts, draw, read, ctx); + + egl::Display* display = static_cast<egl::Display*>(dpy); + if (!display->MakeCurrent(draw, read, ctx)) + return EglError(EGL_CONTEXT_LOST, EGL_FALSE); + +#if REGAL_STATIC_EGL + RegalMakeCurrent(ctx); +#endif + + return EGL_TRUE; } EGLAPI EGLContext EGLAPIENTRY eglGetCurrentContext() { @@ -256,12 +451,15 @@ return EGL_FALSE; } -EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffers(EGLDisplay dpy, EGLSurface sfe) { - egl::ThreadState* ts = egl::ThreadState::Get(); - egl::Display* display = ts->GetDisplay(dpy); - if (!display) - return ts->ReturnError(EGL_BAD_DISPLAY, EGL_FALSE); - return display->SwapBuffers(ts, sfe); +EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffers(EGLDisplay dpy, + EGLSurface surface) { + EGLint error_code = ValidateDisplaySurface(dpy, surface); + if (error_code != EGL_SUCCESS) + return EglError(error_code, EGL_FALSE); + + egl::Display* display = static_cast<egl::Display*>(dpy); + display->SwapBuffers(surface); + return EglSuccess(EGL_TRUE); } EGLAPI EGLBoolean EGLAPIENTRY eglCopyBuffers(EGLDisplay dpy,
diff --git a/gpu/gles2_conform_support/egl/surface.cc b/gpu/gles2_conform_support/egl/surface.cc index 9899cb3..423fe275 100644 --- a/gpu/gles2_conform_support/egl/surface.cc +++ b/gpu/gles2_conform_support/egl/surface.cc
@@ -3,40 +3,13 @@ // found in the LICENSE file. #include "gpu/gles2_conform_support/egl/surface.h" -#include "ui/gl/gl_surface.h" namespace egl { -Surface::Surface(gfx::GLSurface* gl_surface) - : is_current_in_some_thread_(false), gl_surface_(gl_surface) {} +Surface::Surface(EGLNativeWindowType win) : window_(win) { +} Surface::~Surface() { } -gfx::GLSurface* Surface::gl_surface() const { - return gl_surface_.get(); -} - -bool Surface::ValidatePbufferAttributeList(const EGLint* attrib_list) { - if (attrib_list) { - for (int i = 0; attrib_list[i] != EGL_NONE; i += 2) { - switch (attrib_list[i]) { - case EGL_WIDTH: - case EGL_HEIGHT: - break; - default: - return false; - } - } - } - return true; -} - -bool Surface::ValidateWindowAttributeList(const EGLint* attrib_list) { - if (attrib_list) { - if (attrib_list[0] != EGL_NONE) - return false; - } - return true; -} } // namespace egl
diff --git a/gpu/gles2_conform_support/egl/surface.h b/gpu/gles2_conform_support/egl/surface.h index 84ba0aa..3db553e 100644 --- a/gpu/gles2_conform_support/egl/surface.h +++ b/gpu/gles2_conform_support/egl/surface.h
@@ -8,28 +8,19 @@ #include <EGL/egl.h> #include "base/macros.h" -#include "base/memory/ref_counted.h" -namespace gfx { -class GLSurface; -} + namespace egl { -class Surface : public base::RefCountedThreadSafe<Surface> { +class Surface { public: - explicit Surface(gfx::GLSurface* gl_surface); - void set_is_current_in_some_thread(bool flag) { - is_current_in_some_thread_ = flag; - } - bool is_current_in_some_thread() const { return is_current_in_some_thread_; } - gfx::GLSurface* gl_surface() const; - static bool ValidatePbufferAttributeList(const EGLint* attrib_list); - static bool ValidateWindowAttributeList(const EGLint* attrib_list); + explicit Surface(EGLNativeWindowType win); + ~Surface(); + + EGLNativeWindowType window() { return window_; } private: - friend class base::RefCountedThreadSafe<Surface>; - ~Surface(); - bool is_current_in_some_thread_; - scoped_refptr<gfx::GLSurface> gl_surface_; + EGLNativeWindowType window_; + DISALLOW_COPY_AND_ASSIGN(Surface); };
diff --git a/gpu/gles2_conform_support/egl/test_support.cc b/gpu/gles2_conform_support/egl/test_support.cc index 84fb3ef..938abcfd4 100644 --- a/gpu/gles2_conform_support/egl/test_support.cc +++ b/gpu/gles2_conform_support/egl/test_support.cc
@@ -3,22 +3,7 @@ // found in the LICENSE file. #include "test_support.h" -#include "gpu/gles2_conform_support/egl/display.h" -#include "gpu/gles2_conform_support/egl/thread_state.h" #if defined(COMPONENT_BUILD) && defined(COMMAND_BUFFER_GLES_LIB_SUPPORT_ONLY) bool g_command_buffer_gles_has_atexit_manager; #endif - -extern "C" { -EGLAPI void EGLAPIENTRY -CommandBufferGLESSetNextCreateWindowSurfaceCreatesPBuffer(EGLDisplay dpy, - EGLint width, - EGLint height) { - egl::ThreadState* ts = egl::ThreadState::Get(); - egl::Display* display = ts->GetDisplay(dpy); - if (!display) - return; - display->SetNextCreateWindowSurfaceCreatesPBuffer(width, height); -} -}
diff --git a/gpu/gles2_conform_support/egl/test_support.h b/gpu/gles2_conform_support/egl/test_support.h index f5cca7f..b1a70885 100644 --- a/gpu/gles2_conform_support/egl/test_support.h +++ b/gpu/gles2_conform_support/egl/test_support.h
@@ -5,8 +5,6 @@ #ifndef GPU_GLES2_CONFORM_SUPPORT_EGL_TEST_SUPPORT_H_ #define GPU_GLES2_CONFORM_SUPPORT_EGL_TEST_SUPPORT_H_ -#include <EGL/egl.h> - #if defined(COMPONENT_BUILD) && defined(COMMAND_BUFFER_GLES_LIB_SUPPORT_ONLY) // A variable used for communicating whether the app has initialized the global // variables. @@ -18,15 +16,4 @@ EGLAPI extern EGLAPIENTRY bool g_command_buffer_gles_has_atexit_manager; #endif -extern "C" { -// A function to support GTF windowless tests. gles2_conform_test_windowless and -// khronos_glcts_test_windowless create "windowless" native windows and render -// to those. The test runners do not at the moment implement creating said -// windowless native windows. This call sets the system so that it will create a -// pbuffer when eglCreateWindow is called. -EGLAPI EGLAPIENTRY void -CommandBufferGLESSetNextCreateWindowSurfaceCreatesPBuffer(EGLDisplay eglDisplay, - EGLint width, - EGLint height); -} #endif
diff --git a/gpu/gles2_conform_support/egl/thread_state.cc b/gpu/gles2_conform_support/egl/thread_state.cc deleted file mode 100644 index 5f2e691..0000000 --- a/gpu/gles2_conform_support/egl/thread_state.cc +++ /dev/null
@@ -1,199 +0,0 @@ -// Copyright (c) 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "gpu/gles2_conform_support/egl/thread_state.h" - -#include "base/at_exit.h" -#include "base/command_line.h" -#include "base/environment.h" -#include "base/lazy_instance.h" -#include "base/strings/string_split.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "gpu/command_buffer/client/gles2_lib.h" -#include "gpu/command_buffer/common/thread_local.h" -#include "gpu/command_buffer/service/gpu_switches.h" -#include "gpu/config/gpu_info_collector.h" -#include "gpu/config/gpu_util.h" -#include "gpu/gles2_conform_support/egl/context.h" -#include "gpu/gles2_conform_support/egl/display.h" -#include "gpu/gles2_conform_support/egl/surface.h" -#include "gpu/gles2_conform_support/egl/test_support.h" -#include "ui/gl/gl_context.h" -#include "ui/gl/gl_surface.h" - -// Thread local key for ThreadState instance. Accessed when holding g_egl_lock -// only, since the initialization can not be Guaranteed otherwise. Not in -// anonymous namespace due to Mac OS X 10.6 linker. See gles2_lib.cc. -static gpu::ThreadLocalKey g_egl_thread_state_key; - -namespace { -base::LazyInstance<base::Lock>::Leaky g_egl_lock; -int g_egl_active_thread_count; - -egl::Display* g_egl_default_display; - -#if defined(COMMAND_BUFFER_GLES_LIB_SUPPORT_ONLY) -// egl::Display is used for comformance tests and command_buffer_gles. We only -// need the exit manager for the command_buffer_gles library. -base::AtExitManager* g_exit_manager; -#endif -} // namespace - -namespace egl { - -egl::ThreadState* ThreadState::Get() { - base::AutoLock lock(g_egl_lock.Get()); - if (g_egl_active_thread_count == 0) { -#if defined(COMMAND_BUFFER_GLES_LIB_SUPPORT_ONLY) -#if defined(COMPONENT_BUILD) - if (!g_command_buffer_gles_has_atexit_manager) - g_exit_manager = new base::AtExitManager; -#else - g_exit_manager = new base::AtExitManager; -#endif -#endif - gles2::Initialize(); - - if (gfx::GetGLImplementation() == gfx::kGLImplementationNone) { - base::CommandLine::StringVector argv; - scoped_ptr<base::Environment> env(base::Environment::Create()); - std::string env_string; - env->GetVar("CHROME_COMMAND_BUFFER_GLES2_ARGS", &env_string); -#if defined(OS_WIN) - argv = base::SplitString(base::UTF8ToUTF16(env_string), - base::kWhitespaceUTF16, base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY); - argv.insert(argv.begin(), base::UTF8ToUTF16("dummy")); -#else - argv = - base::SplitString(env_string, base::kWhitespaceASCII, - base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); - argv.insert(argv.begin(), "dummy"); -#endif - base::CommandLine::Init(0, nullptr); - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - // Need to call both Init and InitFromArgv, since Windows does not use - // argc, argv in CommandLine::Init(argc, argv). - command_line->InitFromArgv(argv); - if (!command_line->HasSwitch(switches::kDisableGpuDriverBugWorkarounds)) { - gpu::GPUInfo gpu_info; - gpu::CollectBasicGraphicsInfo(&gpu_info); - gpu::ApplyGpuDriverBugWorkarounds(gpu_info, command_line); - } - - gfx::GLSurface::InitializeOneOff(); - } - - g_egl_default_display = new egl::Display(); - g_egl_thread_state_key = gpu::ThreadLocalAlloc(); - } - egl::ThreadState* thread_state = static_cast<egl::ThreadState*>( - gpu::ThreadLocalGetValue(g_egl_thread_state_key)); - if (!thread_state) { - thread_state = new egl::ThreadState; - gpu::ThreadLocalSetValue(g_egl_thread_state_key, thread_state); - ++g_egl_active_thread_count; - } - return thread_state; -} - -void ThreadState::ReleaseThread() { - base::AutoLock lock(g_egl_lock.Get()); - if (g_egl_active_thread_count == 0) - return; - - egl::ThreadState* thread_state = static_cast<egl::ThreadState*>( - gpu::ThreadLocalGetValue(g_egl_thread_state_key)); - if (!thread_state) - return; - - --g_egl_active_thread_count; - if (g_egl_active_thread_count > 0) { - g_egl_default_display->ReleaseCurrent(thread_state); - delete thread_state; - } else { - gpu::ThreadLocalFree(g_egl_thread_state_key); - - // First delete the display object, so that it drops the possible refs to - // current context. - delete g_egl_default_display; - g_egl_default_display = nullptr; - - // We can use Surface and Context without lock, since there's no threads - // left anymore. Destroy the current context explicitly, in an attempt to - // reduce the number of error messages abandoned context would produce. - if (thread_state->current_context()) { - Context::MakeCurrent(thread_state->current_context(), - thread_state->current_surface()->gl_surface(), - nullptr, nullptr); - } - delete thread_state; - - gles2::Terminate(); -#if defined(COMMAND_BUFFER_GLES_LIB_SUPPORT_ONLY) -#if defined(COMPONENT_BUILD) - if (g_command_buffer_gles_has_atexit_manager) - delete g_exit_manager; -#else - delete g_exit_manager; -#endif - g_exit_manager = nullptr; -#endif - } -} - -ThreadState::ThreadState() : error_code_(EGL_SUCCESS) {} - -ThreadState::~ThreadState() {} - -EGLint ThreadState::ConsumeErrorCode() { - EGLint current_error_code = error_code_; - error_code_ = EGL_SUCCESS; - return current_error_code; -} - -Display* ThreadState::GetDisplay(EGLDisplay dpy) { - if (dpy == g_egl_default_display) - return g_egl_default_display; - return nullptr; -} - -Display* ThreadState::GetDefaultDisplay() { - return g_egl_default_display; -} - -void ThreadState::SetCurrent(Surface* surface, Context* context) { - DCHECK((surface == nullptr) == (context == nullptr)); - if (current_context_) { - current_context_->set_is_current_in_some_thread(false); - current_surface_->set_is_current_in_some_thread(false); - } - current_surface_ = surface; - current_context_ = context; - if (current_context_) { - current_context_->set_is_current_in_some_thread(true); - current_surface_->set_is_current_in_some_thread(true); - } -} - -ThreadState::AutoCurrentContextRestore::AutoCurrentContextRestore( - ThreadState* thread_state) - : thread_state_(thread_state) {} - -ThreadState::AutoCurrentContextRestore::~AutoCurrentContextRestore() { - if (Context* current_context = thread_state_->current_context()) { - current_context->ApplyCurrentContext( - thread_state_->current_surface()->gl_surface()); - } else { - Context::ApplyContextReleased(); - } -} - -void ThreadState::AutoCurrentContextRestore::SetCurrent(Surface* surface, - Context* context) { - thread_state_->SetCurrent(surface, context); -} - -} // namespace egl
diff --git a/gpu/gles2_conform_support/egl/thread_state.h b/gpu/gles2_conform_support/egl/thread_state.h deleted file mode 100644 index 963ac5c6..0000000 --- a/gpu/gles2_conform_support/egl/thread_state.h +++ /dev/null
@@ -1,70 +0,0 @@ -// Copyright (c) 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef GPU_GLES2_CONFORM_SUPPORT_EGL_STATE_H_ -#define GPU_GLES2_CONFORM_SUPPORT_EGL_STATE_H_ - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include <EGL/egl.h> - -namespace egl { - -class Context; -class Display; -class Surface; - -// Thread-local API state of EGL. -class ThreadState { - public: - // Factory getter for the class. Should only be called by the API layer, and - // then passed through Display in order to avoid lock issues. - static ThreadState* Get(); - static void ReleaseThread(); - - Surface* current_surface() const { return current_surface_.get(); } - Context* current_context() const { return current_context_.get(); } - - template <typename T> - T ReturnError(EGLint error, T return_value) { - error_code_ = error; - return return_value; - } - template <typename T> - T ReturnSuccess(T return_value) { - error_code_ = EGL_SUCCESS; - return return_value; - } - EGLint ConsumeErrorCode(); - - Display* GetDefaultDisplay(); - Display* GetDisplay(EGLDisplay); - - // RAII class for ensuring that ThreadState current context - // is reflected in the gfx:: and gles:: global variables. - class AutoCurrentContextRestore { - public: - AutoCurrentContextRestore(ThreadState*); - ~AutoCurrentContextRestore(); - void SetCurrent(Surface*, Context*); - - private: - ThreadState* thread_state_; - DISALLOW_COPY_AND_ASSIGN(AutoCurrentContextRestore); - }; - - private: - ThreadState(); - ~ThreadState(); - void SetCurrent(Surface*, Context*); - - EGLint error_code_; - scoped_refptr<Surface> current_surface_; - scoped_refptr<Context> current_context_; - DISALLOW_COPY_AND_ASSIGN(ThreadState); -}; - -} // namespace egl - -#endif
diff --git a/gpu/gles2_conform_support/gles2_conform_support.gyp b/gpu/gles2_conform_support/gles2_conform_support.gyp index 0316ddb..d4f18708 100644 --- a/gpu/gles2_conform_support/gles2_conform_support.gyp +++ b/gpu/gles2_conform_support/gles2_conform_support.gyp
@@ -27,7 +27,6 @@ 'type': 'static_library', 'dependencies': [ '../../base/base.gyp:base', - '../../gpu/command_buffer/command_buffer.gyp:gles2_utils', '../../gpu/gpu.gyp:command_buffer_service', '../../gpu/gpu.gyp:gles2_implementation_no_check', '../../gpu/gpu.gyp:gpu', @@ -39,17 +38,11 @@ 'sources': [ 'egl/config.cc', 'egl/config.h', - 'egl/context.cc', - 'egl/context.h', 'egl/display.cc', 'egl/display.h', 'egl/egl.cc', 'egl/surface.cc', 'egl/surface.h', - 'egl/test_support.cc', - 'egl/test_support.h', - 'egl/thread_state.cc', - 'egl/thread_state.h', ], 'defines': [ 'EGLAPI=',
diff --git a/gpu/gles2_conform_support/native/egl_native_windowless.cc b/gpu/gles2_conform_support/native/egl_native_windowless.cc index 94d6daca..725d0a0 100644 --- a/gpu/gles2_conform_support/native/egl_native_windowless.cc +++ b/gpu/gles2_conform_support/native/egl_native_windowless.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "gpu/gles2_conform_support/egl/test_support.h" +#include "gpu/gles2_conform_support/egl/display.h" extern "C" { #if defined(GLES2_CONFORM_SUPPORT_ONLY) @@ -24,8 +24,8 @@ EGLDisplay eglDisplay, EGLConfig eglConfig, const char* title, int width, int height, EGLNativeWindowType *pNativeWindow) { - CommandBufferGLESSetNextCreateWindowSurfaceCreatesPBuffer(eglDisplay, width, - height); + egl::Display* display = static_cast<egl::Display*>(eglDisplay); + display->SetCreateOffscreen(width, height); return GTFtrue; }
diff --git a/gpu/gpu.gyp b/gpu/gpu.gyp index fe2aa61b..8dcbb291 100644 --- a/gpu/gpu.gyp +++ b/gpu/gpu.gyp
@@ -518,7 +518,6 @@ '../gpu/gpu.gyp:command_buffer_service', '../ui/gfx/gfx.gyp:gfx_geometry', '../ui/gl/gl.gyp:gl', - 'command_buffer/command_buffer.gyp:gles2_utils', 'gles2_c_lib', 'gles2_implementation', ], @@ -527,8 +526,6 @@ # TODO(hendrikw): Move egl out of gles2_conform_support. 'gles2_conform_support/egl/config.cc', 'gles2_conform_support/egl/config.h', - 'gles2_conform_support/egl/context.cc', - 'gles2_conform_support/egl/context.h', 'gles2_conform_support/egl/display.cc', 'gles2_conform_support/egl/display.h', 'gles2_conform_support/egl/egl.cc', @@ -536,8 +533,6 @@ 'gles2_conform_support/egl/surface.h', 'gles2_conform_support/egl/test_support.cc', 'gles2_conform_support/egl/test_support.h', - 'gles2_conform_support/egl/thread_state.cc', - 'gles2_conform_support/egl/thread_state.h', ], 'defines': [ 'COMMAND_BUFFER_GLES_LIB_SUPPORT_ONLY',
diff --git a/ios/web/BUILD.gn b/ios/web/BUILD.gn index 0046225..7676026f 100644 --- a/ios/web/BUILD.gn +++ b/ios/web/BUILD.gn
@@ -144,6 +144,8 @@ "public/web_state/ui/crw_web_view_content_view.h", "public/web_state/url_verification_constants.h", "public/web_state/web_state.h", + "public/web_state/web_state_delegate.h", + "public/web_state/web_state_delegate_bridge.h", "public/web_state/web_state_observer.h", "public/web_state/web_state_observer_bridge.h", "public/web_state/web_state_policy_decider.h", @@ -213,6 +215,8 @@ "web_state/web_controller_observer_bridge.h", "web_state/web_controller_observer_bridge.mm", "web_state/web_state.mm", + "web_state/web_state_delegate.mm", + "web_state/web_state_delegate_bridge.mm", "web_state/web_state_facade_delegate.h", "web_state/web_state_impl.h", "web_state/web_state_impl.mm", @@ -408,6 +412,9 @@ "web_state/ui/web_view_js_utils_unittest.mm", "web_state/ui/wk_back_forward_list_item_holder_unittest.mm", "web_state/ui/wk_web_view_configuration_provider_unittest.mm", + "web_state/web_state_delegate_bridge_unittest.mm", + "web_state/web_state_delegate_stub.h", + "web_state/web_state_delegate_stub.mm", "web_state/web_state_impl_unittest.mm", "web_state/web_view_internal_creation_util_unittest.mm", "web_state/wk_web_view_security_util_unittest.mm",
diff --git a/ios/web/ios_web.gyp b/ios/web/ios_web.gyp index db2715e..6e03650 100644 --- a/ios/web/ios_web.gyp +++ b/ios/web/ios_web.gyp
@@ -180,6 +180,8 @@ 'public/web_state/ui/crw_web_view_content_view.h', 'public/web_state/url_verification_constants.h', 'public/web_state/web_state.h', + 'public/web_state/web_state_delegate.h', + 'public/web_state/web_state_delegate_bridge.h', 'public/web_state/web_state_observer.h', 'public/web_state/web_state_observer_bridge.h', 'public/web_state/web_state_policy_decider.h', @@ -249,6 +251,8 @@ 'web_state/web_controller_observer_bridge.h', 'web_state/web_controller_observer_bridge.mm', 'web_state/web_state.mm', + 'web_state/web_state_delegate.mm', + 'web_state/web_state_delegate_bridge.mm', 'web_state/web_state_facade_delegate.h', 'web_state/web_state_impl.h', 'web_state/web_state_impl.mm',
diff --git a/ios/web/ios_web_shell_tests.gyp b/ios/web/ios_web_shell_tests.gyp index 79c93e8b..806c056c 100644 --- a/ios/web/ios_web_shell_tests.gyp +++ b/ios/web/ios_web_shell_tests.gyp
@@ -14,6 +14,7 @@ { 'variables': { 'test_host': 'ios_web_shell.app/ios_web_shell', + 'test_host_name': 'ios_web_shell', }, 'target_name': 'ios_web_shell_test', 'type': 'loadable_module', @@ -27,7 +28,7 @@ ], 'xcode_settings': { 'WRAPPER_EXTENSION': 'xctest', - 'TEST_HOST': '<(test_host)', + 'TEST_HOST': '$(CONFIGURATION_BUILD_DIR)/<(test_host)', 'BUNDLE_LOADER': '$(TEST_HOST)', 'conditions':[ ['"<(GENERATOR)"!="xcode" or "<(GENERATOR_FLAVOR)"=="ninja"', { @@ -46,6 +47,16 @@ 'XCTest.framework', ], }, + 'postbuilds': [ + { + 'postbuild_name': 'Copy xctest to TEST_HOST', + 'action': [ + 'ditto', + '${BUILT_PRODUCTS_DIR}/ios_web_shell_test.xctest', + '${BUILT_PRODUCTS_DIR}/<(test_host_name).app/PlugIns/ios_web_shell_test.xctest', + ], + }, + ], }, ], }, { # GENERATOR == ninja or GENERATOR_FLAVOR == ninja
diff --git a/ios/web/ios_web_unittests.gyp b/ios/web/ios_web_unittests.gyp index 11989a50..3a91ebd 100644 --- a/ios/web/ios_web_unittests.gyp +++ b/ios/web/ios_web_unittests.gyp
@@ -68,6 +68,9 @@ 'web_state/ui/wk_back_forward_list_item_holder_unittest.mm', 'web_state/ui/wk_web_view_configuration_provider_unittest.mm', 'web_state/web_state_impl_unittest.mm', + 'web_state/web_state_delegate_bridge_unittest.mm', + "web_state/web_state_delegate_stub.h", + "web_state/web_state_delegate_stub.mm", 'web_state/web_view_internal_creation_util_unittest.mm', 'web_state/wk_web_view_security_util_unittest.mm', 'webui/crw_web_ui_manager_unittest.mm',
diff --git a/ios/web/net/crw_ssl_status_updater.mm b/ios/web/net/crw_ssl_status_updater.mm index 6cc48a6..6f9e7eb 100644 --- a/ios/web/net/crw_ssl_status_updater.mm +++ b/ios/web/net/crw_ssl_status_updater.mm
@@ -153,7 +153,8 @@ web::CertStore::GetInstance()->StoreCert(cert.get(), self.certGroupID); std::string GURLHost = base::SysNSStringToUTF8(host); web::SSLStatus& SSLStatus = item->GetSSL(); - if (SSLStatus.cert_id == certID && item->GetURL().host() == GURLHost) { + if (item->GetURL().SchemeIsCryptographic() && SSLStatus.cert_id == certID && + item->GetURL().host() == GURLHost) { web::SSLStatus previousSSLStatus = item->GetSSL(); SSLStatus.cert_status = certStatus; SSLStatus.security_style = style;
diff --git a/ios/web/net/crw_ssl_status_updater_unittest.mm b/ios/web/net/crw_ssl_status_updater_unittest.mm index 4cb05ff..8b8ea0f 100644 --- a/ios/web/net/crw_ssl_status_updater_unittest.mm +++ b/ios/web/net/crw_ssl_status_updater_unittest.mm
@@ -299,10 +299,7 @@ nav_manager_->SetSessionController(SessionControllerWithEntry(kHttpsUrl)); web::NavigationItem* item = nav_manager_->GetLastCommittedItem(); - // Make sure that item change callback was called twice for changing cert_id - // and then security_style. - [[delegate_ expect] SSLStatusUpdater:ssl_status_updater_ - didChangeSSLStatusForNavigationItem:item]; + // Make sure that item change callback was called. [[delegate_ expect] SSLStatusUpdater:ssl_status_updater_ didChangeSSLStatusForNavigationItem:item]; @@ -319,12 +316,8 @@ EXPECT_EQ(web::SECURITY_STYLE_UNKNOWN, item->GetSSL().security_style); EXPECT_FALSE(item->GetSSL().cert_status); - // Downgrade to http which again triggers SSL Status update. + // Downgrade to http. item->SetURL(GURL(kHttpUrl)); - [ssl_status_updater_ updateSSLStatusForNavigationItem:item - withCertHost:kHostName - certChain:@[] - hasOnlySecureContent:YES]; // Reply with calculated cert verification status. [data_source_ @@ -332,7 +325,42 @@ securityStyle:web::SECURITY_STYLE_AUTHENTICATED]; // Make sure that security style and content status did change. - EXPECT_EQ(web::SECURITY_STYLE_UNAUTHENTICATED, item->GetSSL().security_style); + EXPECT_EQ(web::SECURITY_STYLE_UNKNOWN, item->GetSSL().security_style); + EXPECT_EQ(web::SSLStatus::NORMAL_CONTENT, item->GetSSL().content_status); +} + +// Tests that SSL status is not changed if navigation item's cert is changed. +TEST_F(CRWSSLStatusUpdaterTest, CertChanged) { + nav_manager_->SetSessionController(SessionControllerWithEntry(kHttpsUrl)); + web::NavigationItem* item = nav_manager_->GetLastCommittedItem(); + + // Make sure that item change callback was called. + [[delegate_ expect] SSLStatusUpdater:ssl_status_updater_ + didChangeSSLStatusForNavigationItem:item]; + + [ssl_status_updater_ updateSSLStatusForNavigationItem:item + withCertHost:kHostName + certChain:cert_chain_ + hasOnlySecureContent:YES]; + + // Make sure that cert verification was requested. + EXPECT_TRUE([data_source_ certVerificationRequested]); + + // Make sure that security style and cert status are reset during + // verification. + EXPECT_EQ(web::SECURITY_STYLE_UNKNOWN, item->GetSSL().security_style); + EXPECT_FALSE(item->GetSSL().cert_status); + + // Change the cert. + item->GetSSL().cert_id = -1; + + // Reply with calculated cert verification status. + [data_source_ + finishVerificationWithCertStatus:0 + securityStyle:web::SECURITY_STYLE_AUTHENTICATED]; + + // Make sure that security style and content status did change. + EXPECT_EQ(web::SECURITY_STYLE_UNKNOWN, item->GetSSL().security_style); EXPECT_EQ(web::SSLStatus::NORMAL_CONTENT, item->GetSSL().content_status); }
diff --git a/ios/web/public/test/test_web_state.h b/ios/web/public/test/test_web_state.h index 4506a1d..2d7e41d 100644 --- a/ios/web/public/test/test_web_state.h +++ b/ios/web/public/test/test_web_state.h
@@ -24,6 +24,8 @@ // WebState implementation. UIView* GetView() override; + WebStateDelegate* GetDelegate() override; + void SetDelegate(WebStateDelegate* delegate) override; BrowserState* GetBrowserState() const override; void OpenURL(const OpenURLParams& params) override {} NavigationManager* GetNavigationManager() override;
diff --git a/ios/web/public/test/test_web_state.mm b/ios/web/public/test/test_web_state.mm index ebd739e0..a659af8 100644 --- a/ios/web/public/test/test_web_state.mm +++ b/ios/web/public/test/test_web_state.mm
@@ -17,6 +17,12 @@ return nullptr; } +WebStateDelegate* TestWebState::GetDelegate() { + return nil; +} + +void TestWebState::SetDelegate(WebStateDelegate* delegate) {} + BrowserState* TestWebState::GetBrowserState() const { return nullptr; }
diff --git a/ios/web/public/web_state/web_state.h b/ios/web/public/web_state/web_state.h index 667c8af..292e778 100644 --- a/ios/web/public/web_state/web_state.h +++ b/ios/web/public/web_state/web_state.h
@@ -39,6 +39,7 @@ class BrowserState; class NavigationManager; class WebInterstitial; +class WebStateDelegate; class WebStateObserver; class WebStatePolicyDecider; class WebStateWeakPtrFactory; @@ -84,6 +85,10 @@ ~WebState() override {} + // Gets/Sets the delegate. + virtual WebStateDelegate* GetDelegate() = 0; + virtual void SetDelegate(WebStateDelegate* delegate) = 0; + // The view containing the contents of the current web page. If the view has // been purged due to low memory, this will recreate it. It is up to the // caller to size the view.
diff --git a/ios/web/public/web_state/web_state_delegate.h b/ios/web/public/web_state/web_state_delegate.h new file mode 100644 index 0000000..f611da3 --- /dev/null +++ b/ios/web/public/web_state/web_state_delegate.h
@@ -0,0 +1,50 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_WEB_PUBLIC_WEB_STATE_WEB_STATE_DELEGATE_H_ +#define IOS_WEB_PUBLIC_WEB_STATE_WEB_STATE_DELEGATE_H_ + +#include <set> + +#include "base/callback.h" + +namespace net { +class SSLInfo; +} + +namespace web { + +struct SSLStatus; +class WebState; + +// Objects implement this interface to get notified about changes in the +// WebState and to provide necessary functionality. +class WebStateDelegate { + public: + WebStateDelegate(); + + // Notifies the delegate that the page has made some progress loading. + // |progress| is a value between 0.0 (nothing loaded) to 1.0 (page fully + // loaded). + virtual void LoadProgressChanged(WebState* source, double progress); + + protected: + virtual ~WebStateDelegate(); + + private: + friend class WebStateImpl; + + // Called when |this| becomes the WebStateDelegate for |source|. + void Attach(WebState* source); + + // Called when |this| is no longer the WebStateDelegate for |source|. + void Detach(WebState* source); + + // The WebStates for which |this| is currently a delegate. + std::set<WebState*> attached_states_; +}; + +} // namespace web + +#endif // IOS_WEB_PUBLIC_WEB_STATE_WEB_STATE_DELEGATE_H_
diff --git a/ios/web/public/web_state/web_state_delegate_bridge.h b/ios/web/public/web_state/web_state_delegate_bridge.h new file mode 100644 index 0000000..8026bf7 --- /dev/null +++ b/ios/web/public/web_state/web_state_delegate_bridge.h
@@ -0,0 +1,42 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_WEB_PUBLIC_WEB_STATE_WEB_STATE_DELEGATE_BRIDGE_H_ +#define IOS_WEB_PUBLIC_WEB_STATE_WEB_STATE_DELEGATE_BRIDGE_H_ + +#import <Foundation/Foundation.h> + +#import "base/ios/weak_nsobject.h" +#include "ios/web/public/web_state/web_state_delegate.h" + +// Objective-C interface for web::WebStateDelegate. +@protocol CRWWebStateDelegate<NSObject> +@optional + +// Called when the page has made some progress loading. |progress| is a value +// between 0.0 (nothing loaded) to 1.0 (page fully loaded). +- (void)webState:(web::WebState*)webState didChangeProgress:(double)progress; + +@end + +namespace web { + +// Adapter to use an id<CRWWebStateDelegate> as a web::WebStateDelegate. +class WebStateDelegateBridge : public web::WebStateDelegate { + public: + explicit WebStateDelegateBridge(id<CRWWebStateDelegate> delegate); + ~WebStateDelegateBridge() override; + + // web::WebStateDelegate methods. + void LoadProgressChanged(WebState* source, double progress) override; + + private: + // CRWWebStateDelegate which receives forwarded calls. + base::WeakNSProtocol<id<CRWWebStateDelegate>> delegate_; + DISALLOW_COPY_AND_ASSIGN(WebStateDelegateBridge); +}; + +} // web + +#endif // IOS_WEB_PUBLIC_WEB_STATE_WEB_STATE_DELEGATE_BRIDGE_H_
diff --git a/ios/web/shell/view_controller.mm b/ios/web/shell/view_controller.mm index e91df14..bca82a93 100644 --- a/ios/web/shell/view_controller.mm +++ b/ios/web/shell/view_controller.mm
@@ -17,6 +17,7 @@ #import "ios/net/empty_nsurlcache.h" #include "ios/web/public/referrer.h" #include "ios/web/public/web_state/web_state.h" +#import "ios/web/public/web_state/web_state_delegate_bridge.h" #import "ios/web/public/web_state/web_state_observer_bridge.h" #include "ios/web/shell/shell_browser_state.h" #include "ios/web/web_state/ui/crw_web_controller.h" @@ -29,10 +30,11 @@ using web::NavigationManager; -@interface ViewController ()<CRWWebStateObserver> { +@interface ViewController ()<CRWWebStateDelegate, CRWWebStateObserver> { web::BrowserState* _browserState; std::unique_ptr<web::WebStateImpl> _webState; std::unique_ptr<web::WebStateObserverBridge> _webStateObserver; + std::unique_ptr<web::WebStateDelegateBridge> _webStateDelegate; base::mac::ObjCPropertyReleaser _propertyReleaser_ViewController; } @@ -115,6 +117,8 @@ _webStateObserver.reset( new web::WebStateObserverBridge(_webState.get(), self)); + _webStateDelegate.reset(new web::WebStateDelegateBridge(self)); + _webState->SetDelegate(_webStateDelegate.get()); UIView* view = _webState->GetView(); [view setFrame:[_containerView bounds]];
diff --git a/ios/web/web_state/ui/crw_web_controller+protected.h b/ios/web/web_state/ui/crw_web_controller+protected.h index 261e42f..9ac7546 100644 --- a/ios/web/web_state/ui/crw_web_controller+protected.h +++ b/ios/web/web_state/ui/crw_web_controller+protected.h
@@ -12,7 +12,6 @@ #include <memory> #include "base/containers/mru_cache.h" -#import "base/mac/objc_property_releaser.h" #include "base/mac/scoped_nsobject.h" #include "ios/web/net/cert_host_pair.h" #import "ios/web/net/crw_cert_verification_controller.h" @@ -82,28 +81,6 @@ #pragma mark - -// A container object for any navigation information that is only available -// during pre-commit delegate callbacks, and thus must be held until the -// navigation commits and the informatino can be used. -@interface CRWWebControllerPendingNavigationInfo : NSObject { - base::mac::ObjCPropertyReleaser - _propertyReleaser_CRWWebControllerPendingNavigationInfo; -} -// The referrer for the page. -@property(nonatomic, copy) NSString* referrer; -// The MIME type for the page. -@property(nonatomic, copy) NSString* MIMEType; -// The navigation type for the load. -@property(nonatomic, assign) WKNavigationType navigationType; -// Whether the pending navigation has been directly cancelled before the -// navigation is committed. -// Cancelled navigations should be simply discarded without handling any -// specific error. -@property(nonatomic, assign) BOOL cancelled; -@end - -#pragma mark - - // Category for methods used or implemented by implementation subclasses of // CRWWebController. @interface CRWWebController ( @@ -115,25 +92,6 @@ // Downloader for PassKit files. Lazy initialized. @property(nonatomic, readonly) CRWPassKitDownloader* passKitDownloader; -// The actual URL of the document object (i.e., the last committed URL). -// TODO(crbug.com/549616): Remove this in favor of just updating the -// navigation manager and treating that as authoritative. For now, this allows -// sharing the flow that's currently in the superclass. -@property(nonatomic, readonly) GURL documentURL; - -// YES if the user has interacted with the content area since the last URL -// change. -@property(nonatomic, readonly) BOOL interactionRegisteredSinceLastURLChange; - -- (CRWWebControllerPendingNavigationInfo*)pendingNavigationInfo; - -// Sets _documentURL to newURL, and updates any relevant state information. -- (void)setDocumentURL:(const GURL&)newURL; - -// Returns the current URL of the web view, and sets |trustLevel| accordingly -// based on the confidence in the verification. -- (GURL)webURLWithTrustLevel:(web::URLVerificationTrustLevel*)trustLevel; - // Returns the type of document object loaded in the web view. - (web::WebViewDocumentType)webViewDocumentType; @@ -142,15 +100,6 @@ // Called before loading current URL in WebView. - (void)willLoadCurrentURLInWebView; -// Loads request for the URL of the current navigation item. Subclasses may -// choose to build a new NSURLRequest and call |loadRequest| on the underlying -// web view, or use native web view navigation where possible (for example, -// going back and forward through the history stack). -- (void)loadRequestForCurrentNavigationItem; - -// Cancels any load in progress in the web view. -- (void)abortWebLoad; - // Called when web view process has been terminated. - (void)webViewWebProcessDidCrash; @@ -237,10 +186,6 @@ // Last URL change registered for load request. @property(nonatomic, readonly) GURL lastRegisteredRequestURL; -// Pending information for an in-progress page navigation. -@property(nonatomic, readonly) - CRWWebControllerPendingNavigationInfo* pendingNavigationInfo; - // Returns YES if the object is being deallocated. @property(nonatomic, readonly) BOOL isBeingDestroyed; @@ -251,10 +196,6 @@ // Returns whether the user is interacting with the page. @property(nonatomic, readonly) BOOL userIsInteracting; -// YES if a user interaction has been registered at any time since the page has -// loaded. -@property(nonatomic, readwrite) BOOL userInteractionRegistered; - // YES if the web process backing _wkWebView is believed to currently be dead. @property(nonatomic, assign) BOOL webProcessIsDead; @@ -285,9 +226,6 @@ // content view. - (void)webViewDidChange; -// Aborts any load for both the web view and web controller. -- (void)abortLoad; - // Returns the URL that the navigation system believes should be currently // active. // TODO(stuartmorgan):Remove this in favor of more specific getters.
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index a3dd7ee4..66173f2 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -197,6 +197,44 @@ } } // namespace +#pragma mark - + +// A container object for any navigation information that is only available +// during pre-commit delegate callbacks, and thus must be held until the +// navigation commits and the informatino can be used. +@interface CRWWebControllerPendingNavigationInfo : NSObject { + base::mac::ObjCPropertyReleaser + _propertyReleaser_CRWWebControllerPendingNavigationInfo; +} +// The referrer for the page. +@property(nonatomic, copy) NSString* referrer; +// The MIME type for the page. +@property(nonatomic, copy) NSString* MIMEType; +// The navigation type for the load. +@property(nonatomic, assign) WKNavigationType navigationType; +// Whether the pending navigation has been directly cancelled before the +// navigation is committed. +// Cancelled navigations should be simply discarded without handling any +// specific error. +@property(nonatomic, assign) BOOL cancelled; +@end + +@implementation CRWWebControllerPendingNavigationInfo +@synthesize referrer = _referrer; +@synthesize MIMEType = _MIMEType; +@synthesize navigationType = _navigationType; +@synthesize cancelled = _cancelled; + +- (instancetype)init { + if ((self = [super init])) { + _propertyReleaser_CRWWebControllerPendingNavigationInfo.Init( + self, [CRWWebControllerPendingNavigationInfo class]); + _navigationType = WKNavigationTypeOther; + } + return self; +} +@end + @interface CRWWebController ()<CRWNativeContentDelegate, CRWSSLStatusUpdaterDataSource, CRWSSLStatusUpdaterDelegate, @@ -231,6 +269,13 @@ // YES if a user interaction has been registered at any time once the page has // loaded. BOOL _userInteractionRegistered; + // YES if the user has interacted with the content area since the last URL + // change. + BOOL _interactionRegisteredSinceLastURLChange; + // The actual URL of the document object (i.e., the last committed URL). + // TODO(crbug.com/549616): Remove this in favor of just updating the + // navigation manager and treating that as authoritative. + GURL _documentURL; // Last URL change reported to webWill/DidStartLoadingURL. Used to detect page // location changes (client redirects) in practice. GURL _lastRegisteredRequestURL; @@ -429,6 +474,9 @@ // controller's BrowserState. - (web::WKWebViewConfigurationProvider&)webViewConfigurationProvider; +// Returns the current URL of the web view, and sets |trustLevel| accordingly +// based on the confidence in the verification. +- (GURL)webURLWithTrustLevel:(web::URLVerificationTrustLevel*)trustLevel; // Returns |YES| if |url| should be loaded in a native view. - (BOOL)shouldLoadURLInNativeView:(const GURL&)url; // Loads the HTML into the page at the given URL. @@ -442,6 +490,10 @@ // Internal implementation of reload. Reloads without notifying the delegate. // Most callers should use -reload instead. - (void)reloadInternal; +// Aborts any load for both the web view and web controller. +- (void)abortLoad; +// Cancels any load in progress in the web view. +- (void)abortWebLoad; // If YES, the page should be closed if it successfully redirects to a native // application, for example if a new tab redirects to the App Store. - (BOOL)shouldClosePageOnNativeApplicationLoad; @@ -535,11 +587,16 @@ // Assigns the given URL and state object to the current CRWSessionEntry. - (void)replaceStateWithPageURL:(const GURL&)pageUrl stateObject:(NSString*)stateObject; +// Sets _documentURL to newURL, and updates any relevant state information. +- (void)setDocumentURL:(const GURL&)newURL; // Returns YES if the current navigation item corresponds to a web page // loaded by a POST request. - (BOOL)isCurrentNavigationItemPOST; // Returns whether the given navigation is triggered by a user link click. - (BOOL)isLinkNavigation:(WKNavigationType)navigationType; +// Returns YES if the given WKBackForwardListItem is valid to use for +// navigation. +- (BOOL)isBackForwardListItemValid:(WKBackForwardListItem*)item; // Finds all the scrollviews in the view hierarchy and makes sure they do not // interfere with scroll to top when tapping the statusbar. @@ -624,6 +681,11 @@ // Returns YES if there is currently a requested but uncommitted load for // |targetURL|. - (BOOL)isLoadRequestPendingForURL:(const GURL&)targetURL; +// Loads request for the URL of the current navigation item. Subclasses may +// choose to build a new NSURLRequest and call |loadRequest| on the underlying +// web view, or use native web view navigation where possible (for example, +// going back and forward through the history stack). +- (void)loadRequestForCurrentNavigationItem; // Handlers for JavaScript messages. |message| contains a JavaScript command and // data relevant to the message, and |context| contains contextual information @@ -684,6 +746,12 @@ - (BOOL)handleWindowHistoryGoMessage:(base::DictionaryValue*)message context:(NSDictionary*)context; +// Called when a load ends in an error. +// TODO(stuartmorgan): Figure out if there's actually enough shared logic that +// this makes sense. At the very least remove inMainFrame since that only makes +// sense for UIWebView. +- (void)handleLoadError:(NSError*)error inMainFrame:(BOOL)inMainFrame; + // Handles cancelled load in WKWebView (error with NSURLErrorCancelled code). - (void)handleCancelledError:(NSError*)error; @@ -1317,6 +1385,13 @@ [self didUpdateHistoryStateWithPageURL:pageUrl]; } +- (void)setDocumentURL:(const GURL&)newURL { + if (newURL != _documentURL) { + _documentURL = newURL; + _interactionRegisteredSinceLastURLChange = NO; + } +} + - (BOOL)isCurrentNavigationItemPOST { // |_pendingNavigationInfo| will be nil if the decidePolicy* delegate methods // were not called. @@ -1339,6 +1414,15 @@ } } +- (BOOL)isBackForwardListItemValid:(WKBackForwardListItem*)item { + // The current back-forward list item MUST be in the WKWebView's back-forward + // list to be valid. + WKBackForwardList* list = [self.webView backForwardList]; + return list.currentItem == item || + [list.forwardList indexOfObject:item] != NSNotFound || + [list.backList indexOfObject:item] != NSNotFound; +} + - (void)injectEarlyInjectionScripts { DCHECK(self.webView); if (![_earlyScriptManager hasBeenInjected]) { @@ -1502,8 +1586,8 @@ // Get the navigation type from the last main frame load request, and try to // map that to a PageTransition. WKNavigationType navigationType = - self.pendingNavigationInfo ? [self.pendingNavigationInfo navigationType] - : WKNavigationTypeOther; + _pendingNavigationInfo ? [_pendingNavigationInfo navigationType] + : WKNavigationTypeOther; ui::PageTransition transition = ui::PAGE_TRANSITION_CLIENT_REDIRECT; switch (navigationType) { case WKNavigationTypeLinkActivated: @@ -1524,7 +1608,7 @@ // or may not be the result of user actions. For now, guess based on // whether there's been an interaction since the last URL change. // TODO(crbug.com/549301): See if this heuristic can be improved. - transition = self.interactionRegisteredSinceLastURLChange + transition = _interactionRegisteredSinceLastURLChange ? ui::PAGE_TRANSITION_LINK : ui::PAGE_TRANSITION_CLIENT_REDIRECT; break; @@ -1639,11 +1723,6 @@ [self loadRequestForCurrentNavigationItem]; } -- (void)loadRequestForCurrentNavigationItem { - // Handled differently by UIWebView and WKWebView subclasses. - NOTIMPLEMENTED(); -} - - (void)updatePendingNavigationInfoFromNavigationAction: (WKNavigationAction*)action { if (action.targetFrame.mainFrame) { @@ -1727,8 +1806,8 @@ [self currentBackForwardListItemHolder]; WKNavigationType navigationType = - self.pendingNavigationInfo ? [self.pendingNavigationInfo navigationType] - : WKNavigationTypeOther; + _pendingNavigationInfo ? [_pendingNavigationInfo navigationType] + : WKNavigationTypeOther; holder->set_back_forward_list_item( [self.webView backForwardList].currentItem); holder->set_navigation_type(navigationType); @@ -1737,8 +1816,8 @@ // as part of this pending load. It will be nil when doing a fast // back/forward navigation, for instance, because the callback that would // populate it is not called in that flow. - if ([self.pendingNavigationInfo MIMEType]) - holder->set_mime_type([self.pendingNavigationInfo MIMEType]); + if ([_pendingNavigationInfo MIMEType]) + holder->set_mime_type([_pendingNavigationInfo MIMEType]); } - (void)loadNativeViewWithSuccess:(BOOL)loadSuccess { @@ -1899,6 +1978,12 @@ _expectedReconstructionURL = GURL(); } +- (GURL)webURLWithTrustLevel:(web::URLVerificationTrustLevel*)trustLevel { + DCHECK(trustLevel); + *trustLevel = web::URLVerificationTrustLevel::kAbsolute; + return _documentURL; +} + - (BOOL)shouldLoadURLInNativeView:(const GURL&)url { // App-specific URLs that don't require WebUI are loaded in native views. return web::GetWebClient()->IsAppSpecificURL(url) && @@ -2004,6 +2089,17 @@ [self reloadInternal]; } +- (void)abortLoad { + [self abortWebLoad]; + _certVerificationErrors->Clear(); + [self loadCancelled]; +} + +- (void)abortWebLoad { + [_webView stopLoading]; + [_pendingNavigationInfo setCancelled:YES]; +} + - (void)loadCancelled { [_passKitDownloader cancelPendingDownload]; @@ -2036,12 +2132,6 @@ } } -- (void)abortLoad { - [self abortWebLoad]; - _certVerificationErrors->Clear(); - [self loadCancelled]; -} - - (void)prepareForGoBack { // Make sure any transitions that may have occurred have been seen and acted // on by the CRWWebController, so the history stack and state of the @@ -3107,6 +3197,8 @@ - (void)setUserInteractionRegistered:(BOOL)flag { _userInteractionRegistered = flag; + if (flag) + _interactionRegisteredSinceLastURLChange = YES; } - (BOOL)userInteractionRegistered { @@ -3247,6 +3339,9 @@ } - (void)handleLoadError:(NSError*)error inMainFrame:(BOOL)inMainFrame { + NSString* MIMEType = [_pendingNavigationInfo MIMEType]; + if ([_passKitDownloader isMIMETypePassKitType:MIMEType]) + return; if ([error code] == NSURLErrorUnsupportedURL) return; // In cases where a Plug-in handles the load do not take any further action. @@ -4320,7 +4415,7 @@ certGroupID:self.certGroupID]); [_SSLStatusUpdater setDelegate:self]; } - NSString* host = base::SysUTF8ToNSString(self.documentURL.host()); + NSString* host = base::SysUTF8ToNSString(_documentURL.host()); NSArray* certChain = [self.webView certificateChain]; BOOL hasOnlySecureContent = [self.webView hasOnlySecureContent]; [_SSLStatusUpdater updateSSLStatusForNavigationItem:currentNavItem @@ -4675,7 +4770,7 @@ if (allowLoad) { allowLoad = self.webStateImpl->ShouldAllowRequest(request); if (!allowLoad && navigationAction.targetFrame.mainFrame) { - [self.pendingNavigationInfo setCancelled:YES]; + [_pendingNavigationInfo setCancelled:YES]; } } @@ -4710,11 +4805,11 @@ allowNavigation = self.webStateImpl->ShouldAllowResponse(navigationResponse.response); if (!allowNavigation && navigationResponse.isForMainFrame) { - [self.pendingNavigationInfo setCancelled:YES]; + [_pendingNavigationInfo setCancelled:YES]; } } if ([self.passKitDownloader - isMIMETypePassKitType:[self.pendingNavigationInfo MIMEType]]) { + isMIMETypePassKitType:[_pendingNavigationInfo MIMEType]]) { GURL URL = net::GURLWithNSURL(navigationResponse.response.URL); [self.passKitDownloader downloadPassKitFileWithURL:URL]; } @@ -4797,7 +4892,7 @@ // Handle load cancellation for directly cancelled navigations without // handling their potential errors. Otherwise, handle the error. - if ([self.pendingNavigationInfo cancelled]) { + if ([_pendingNavigationInfo cancelled]) { [self loadCancelled]; } else { error = WKWebViewErrorWithSource(error, PROVISIONAL_LOAD); @@ -4826,8 +4921,8 @@ // This is the point where the document's URL has actually changed, and // pending navigation information should be applied to state information. [self setDocumentURL:net::GURLWithNSURL([self.webView URL])]; - DCHECK(self.documentURL == self.lastRegisteredRequestURL); - self.webStateImpl->OnNavigationCommitted(self.documentURL); + DCHECK(_documentURL == self.lastRegisteredRequestURL); + self.webStateImpl->OnNavigationCommitted(_documentURL); [self commitPendingNavigationInfo]; if ([self currentBackForwardListItemHolder]->navigation_type() == WKNavigationTypeBackForward) { @@ -4845,7 +4940,7 @@ [self updateSSLStatusForCurrentNavigationItem]; // Report cases where SSL cert is missing for a secure connection. - if (self.documentURL.SchemeIsCryptographic()) { + if (_documentURL.SchemeIsCryptographic()) { scoped_refptr<net::X509Certificate> cert = web::CreateCertFromChain([self.webView certificateChain]); UMA_HISTOGRAM_BOOLEAN("WebController.WKWebViewHasCertForSecureConnection", @@ -4956,10 +5051,14 @@ } - (void)webViewEstimatedProgressDidChange { - if ([self.delegate + if ([self isBeingDestroyed]) + return; + + self.webStateImpl->SendChangeLoadProgress([_webView estimatedProgress]); + if ([_delegate respondsToSelector:@selector(webController:didUpdateProgress:)]) { - [self.delegate webController:self - didUpdateProgress:[self.webView estimatedProgress]]; + [_delegate webController:self + didUpdateProgress:[_webView estimatedProgress]]; } } @@ -5037,7 +5136,7 @@ // window.location.href will match the previous URL at this stage, not the web // view's current URL. if (![self.webView isLoading]) { - if (self.documentURL == URL) + if (_documentURL == URL) return; [self URLDidChangeWithoutDocumentChange:URL]; } else if ([self isKVOChangePotentialSameDocumentNavigationToURL:URL]) { @@ -5058,7 +5157,7 @@ // Re-check origin in case navigaton has occured since // start of JavaScript evaluation. BOOL newURLOriginMatchesDocumentURLOrigin = - self.documentURL.GetOrigin() == URL.GetOrigin(); + _documentURL.GetOrigin() == URL.GetOrigin(); // Check that the web view URL still matches the new URL. // TODO(crbug.com/563568): webViewURLMatchesNewURL check // may drop same document URL changes if pending URL @@ -5068,7 +5167,7 @@ net::GURLWithNSURL([self.webView URL]) == URL; // Check that the new URL is different from the current // document URL. If not, URL change should not be reported. - BOOL URLDidChangeFromDocumentURL = URL != self.documentURL; + BOOL URLDidChangeFromDocumentURL = URL != _documentURL; if (windowLocationMatchesNewURL && newURLOriginMatchesDocumentURLOrigin && webViewURLMatchesNewURL && URLDidChangeFromDocumentURL) { @@ -5081,8 +5180,8 @@ - (BOOL)isKVOChangePotentialSameDocumentNavigationToURL:(const GURL&)newURL { DCHECK([self.webView isLoading]); // If the origin changes, it can't be same-document. - if (self.documentURL.GetOrigin().is_empty() || - self.documentURL.GetOrigin() != newURL.GetOrigin()) { + if (_documentURL.GetOrigin().is_empty() || + _documentURL.GetOrigin() != newURL.GetOrigin()) { return NO; } if (self.loadPhase == web::LOAD_REQUESTED) { @@ -5090,7 +5189,7 @@ // navigation, but it can also happen during a fast-back navigation across // a hash change, so that case is potentially a same-document navigation. return web::GURLByRemovingRefFromGURL(newURL) == - web::GURLByRemovingRefFromGURL(self.documentURL); + web::GURLByRemovingRefFromGURL(_documentURL); } // If it passes all the checks above, it might be (but there's no guarantee // that it is). @@ -5099,8 +5198,8 @@ - (void)URLDidChangeWithoutDocumentChange:(const GURL&)newURL { DCHECK(newURL == net::GURLWithNSURL([self.webView URL])); - DCHECK_EQ(self.documentURL.host(), newURL.host()); - DCHECK(self.documentURL != newURL); + DCHECK_EQ(_documentURL.host(), newURL.host()); + DCHECK(_documentURL != newURL); // If called during window.history.pushState or window.history.replaceState // JavaScript evaluation, only update the document URL. This callback does not @@ -5126,7 +5225,7 @@ [self setDocumentURL:newURL]; if (!self.changingHistoryState) { - [self didStartLoadingURL:self.documentURL updateHistory:YES]; + [self didStartLoadingURL:_documentURL updateHistory:YES]; [self updateSSLStatusForCurrentNavigationItem]; [self didFinishNavigation]; } @@ -5141,6 +5240,89 @@ return pendingItem && pendingItem->GetURL() == targetURL; } +- (void)loadRequestForCurrentNavigationItem { + DCHECK(self.webView && !self.nativeController); + DCHECK([self currentSessionEntry]); + // If a load is kicked off on a WKWebView with a frame whose size is {0, 0} or + // that has a negative dimension for a size, rendering issues occur that + // manifest in erroneous scrolling and tap handling (crbug.com/574996, + // crbug.com/577793). + DCHECK_GT(CGRectGetWidth(self.webView.frame), 0.0); + DCHECK_GT(CGRectGetHeight(self.webView.frame), 0.0); + + web::WKBackForwardListItemHolder* holder = + [self currentBackForwardListItemHolder]; + BOOL isFormResubmission = + (holder->navigation_type() == WKNavigationTypeFormResubmitted || + holder->navigation_type() == WKNavigationTypeFormSubmitted); + web::NavigationItemImpl* currentItem = + [self currentSessionEntry].navigationItemImpl; + NSData* POSTData = currentItem->GetPostData(); + NSMutableURLRequest* request = [self requestForCurrentNavigationItem]; + + // If the request has POST data and is not a form resubmission, configure and + // run the POST request. + if (POSTData.length && !isFormResubmission) { + [request setHTTPMethod:@"POST"]; + [request setHTTPBody:POSTData]; + [request setAllHTTPHeaderFields:[self currentHTTPHeaders]]; + [self registerLoadRequest:[self currentNavigationURL] + referrer:[self currentSessionEntryReferrer] + transition:[self currentTransition]]; + [self loadPOSTRequest:request]; + return; + } + + ProceduralBlock defaultNavigationBlock = ^{ + [self registerLoadRequest:[self currentNavigationURL] + referrer:[self currentSessionEntryReferrer] + transition:[self currentTransition]]; + [self loadRequest:request]; + }; + + // If there is no corresponding WKBackForwardListItem, or the item is not in + // the current WKWebView's back-forward list, navigating using WKWebView API + // is not possible. In this case, fall back to the default navigation + // mechanism. + if (!holder->back_forward_list_item() || + ![self isBackForwardListItemValid:holder->back_forward_list_item()]) { + defaultNavigationBlock(); + return; + } + + ProceduralBlock webViewNavigationBlock = ^{ + // If the current navigation URL is the same as the URL of the visible + // page, that means the user requested a reload. |goToBackForwardListItem| + // will be a no-op when it is passed the current back forward list item, + // so |reload| must be explicitly called. + [self registerLoadRequest:[self currentNavigationURL] + referrer:[self currentSessionEntryReferrer] + transition:[self currentTransition]]; + if ([self currentNavigationURL] == net::GURLWithNSURL([self.webView URL])) { + [self.webView reload]; + } else { + [self.webView goToBackForwardListItem:holder->back_forward_list_item()]; + } + }; + + // If the request is not a form submission or resubmission, or the user + // doesn't need to confirm the load, then continue right away. + + if (!isFormResubmission || + currentItem->ShouldSkipResubmitDataConfirmation()) { + webViewNavigationBlock(); + return; + } + + // If the request is form submission or resubmission, then prompt the + // user before proceeding. + DCHECK(isFormResubmission); + [self.delegate webController:self + onFormResubmissionForRequest:nil + continueBlock:webViewNavigationBlock + cancelBlock:defaultNavigationBlock]; +} + #pragma mark - #pragma mark Testing-Only Methods @@ -5223,10 +5405,6 @@ return _lastRegisteredRequestURL; } -- (CRWWebControllerPendingNavigationInfo*)pendingNavigationInfo { - return _pendingNavigationInfo; -} - - (void)simulateLoadRequestWithURL:(const GURL&)URL { _lastRegisteredRequestURL = URL; _loadPhase = web::LOAD_REQUESTED;
diff --git a/ios/web/web_state/ui/crw_wk_web_view_web_controller.mm b/ios/web/web_state/ui/crw_wk_web_view_web_controller.mm index ad2bf71..c02be66 100644 --- a/ios/web/web_state/ui/crw_wk_web_view_web_controller.mm +++ b/ios/web/web_state/ui/crw_wk_web_view_web_controller.mm
@@ -42,69 +42,10 @@ #include "net/ssl/ssl_info.h" #include "url/url_constants.h" -@implementation CRWWebControllerPendingNavigationInfo -@synthesize referrer = _referrer; -@synthesize MIMEType = _MIMEType; -@synthesize navigationType = _navigationType; -@synthesize cancelled = _cancelled; - -- (instancetype)init { - if ((self = [super init])) { - _propertyReleaser_CRWWebControllerPendingNavigationInfo.Init( - self, [CRWWebControllerPendingNavigationInfo class]); - _navigationType = WKNavigationTypeOther; - } - return self; -} -@end - -#pragma mark - - -@interface CRWWKWebViewWebController () { - // The actual URL of the document object (i.e., the last committed URL). - // TODO(crbug.com/549616): Remove this in favor of just updating the - // navigation manager and treating that as authoritative. For now, this allows - // sharing the flow that's currently in the superclass. - GURL _documentURL; - - // YES if the user has interacted with the content area since the last URL - // change. - BOOL _interactionRegisteredSinceLastURLChange; -} - -// Returns YES if the given WKBackForwardListItem is valid to use for -// navigation. -- (BOOL)isBackForwardListItemValid:(WKBackForwardListItem*)item; - -@end - @implementation CRWWKWebViewWebController -#pragma mark - Protected property implementations - -- (GURL)documentURL { - return _documentURL; -} - -- (BOOL)interactionRegisteredSinceLastURLChange { - return _interactionRegisteredSinceLastURLChange; -} - -// Overridden to track interactions since URL change. -- (void)setUserInteractionRegistered:(BOOL)flag { - [super setUserInteractionRegistered:flag]; - if (flag) - _interactionRegisteredSinceLastURLChange = YES; -} - #pragma mark Protected method implementations -- (GURL)webURLWithTrustLevel:(web::URLVerificationTrustLevel*)trustLevel { - DCHECK(trustLevel); - *trustLevel = web::URLVerificationTrustLevel::kAbsolute; - return _documentURL; -} - // The core.js cannot pass messages back to obj-c if it is injected // to |WEB_VIEW_DOCUMENT| because it does not support iframe creation used // by core.js to communicate back. That functionality is only supported @@ -125,89 +66,6 @@ // code working for debug builds. } -- (void)loadRequestForCurrentNavigationItem { - DCHECK(self.webView && !self.nativeController); - DCHECK([self currentSessionEntry]); - // If a load is kicked off on a WKWebView with a frame whose size is {0, 0} or - // that has a negative dimension for a size, rendering issues occur that - // manifest in erroneous scrolling and tap handling (crbug.com/574996, - // crbug.com/577793). - DCHECK_GT(CGRectGetWidth(self.webView.frame), 0.0); - DCHECK_GT(CGRectGetHeight(self.webView.frame), 0.0); - - web::WKBackForwardListItemHolder* holder = - [self currentBackForwardListItemHolder]; - BOOL isFormResubmission = - (holder->navigation_type() == WKNavigationTypeFormResubmitted || - holder->navigation_type() == WKNavigationTypeFormSubmitted); - web::NavigationItemImpl* currentItem = - [self currentSessionEntry].navigationItemImpl; - NSData* POSTData = currentItem->GetPostData(); - NSMutableURLRequest* request = [self requestForCurrentNavigationItem]; - - // If the request has POST data and is not a form resubmission, configure and - // run the POST request. - if (POSTData.length && !isFormResubmission) { - [request setHTTPMethod:@"POST"]; - [request setHTTPBody:POSTData]; - [request setAllHTTPHeaderFields:[self currentHTTPHeaders]]; - [self registerLoadRequest:[self currentNavigationURL] - referrer:[self currentSessionEntryReferrer] - transition:[self currentTransition]]; - [self loadPOSTRequest:request]; - return; - } - - ProceduralBlock defaultNavigationBlock = ^{ - [self registerLoadRequest:[self currentNavigationURL] - referrer:[self currentSessionEntryReferrer] - transition:[self currentTransition]]; - [self loadRequest:request]; - }; - - // If there is no corresponding WKBackForwardListItem, or the item is not in - // the current WKWebView's back-forward list, navigating using WKWebView API - // is not possible. In this case, fall back to the default navigation - // mechanism. - if (!holder->back_forward_list_item() || - ![self isBackForwardListItemValid:holder->back_forward_list_item()]) { - defaultNavigationBlock(); - return; - } - - ProceduralBlock webViewNavigationBlock = ^{ - // If the current navigation URL is the same as the URL of the visible - // page, that means the user requested a reload. |goToBackForwardListItem| - // will be a no-op when it is passed the current back forward list item, - // so |reload| must be explicitly called. - [self registerLoadRequest:[self currentNavigationURL] - referrer:[self currentSessionEntryReferrer] - transition:[self currentTransition]]; - if ([self currentNavigationURL] == net::GURLWithNSURL([self.webView URL])) { - [self.webView reload]; - } else { - [self.webView goToBackForwardListItem:holder->back_forward_list_item()]; - } - }; - - // If the request is not a form submission or resubmission, or the user - // doesn't need to confirm the load, then continue right away. - - if (!isFormResubmission || - currentItem->ShouldSkipResubmitDataConfirmation()) { - webViewNavigationBlock(); - return; - } - - // If the request is form submission or resubmission, then prompt the - // user before proceeding. - DCHECK(isFormResubmission); - [self.delegate webController:self - onFormResubmissionForRequest:nil - continueBlock:webViewNavigationBlock - cancelBlock:defaultNavigationBlock]; -} - // Overrides the hashchange workaround in the super class that manually // triggers Javascript hashchange events. If navigating with native API, // i.e. using a back forward list item, hashchange events will be triggered @@ -223,11 +81,6 @@ return [super URLForHistoryNavigationFromItem:fromItem toItem:toItem]; } -- (void)abortWebLoad { - [self.webView stopLoading]; - [self.pendingNavigationInfo setCancelled:YES]; -} - - (void)applyWebViewScrollZoomScaleFromZoomState: (const web::PageZoomState&)zoomState { // After rendering a web page, WKWebView keeps the |minimumZoomScale| and @@ -244,32 +97,8 @@ self.webScrollView.zoomScale = zoomScale; } -// Override |handleLoadError| to check for PassKit case. -- (void)handleLoadError:(NSError*)error inMainFrame:(BOOL)inMainFrame { - NSString* MIMEType = [self.pendingNavigationInfo MIMEType]; - if ([self.passKitDownloader isMIMETypePassKitType:MIMEType]) - return; - [super handleLoadError:error inMainFrame:inMainFrame]; -} - #pragma mark Private methods -- (void)setDocumentURL:(const GURL&)newURL { - if (newURL != _documentURL) { - _documentURL = newURL; - _interactionRegisteredSinceLastURLChange = NO; - } -} - -- (BOOL)isBackForwardListItemValid:(WKBackForwardListItem*)item { - // The current back-forward list item MUST be in the WKWebView's back-forward - // list to be valid. - WKBackForwardList* list = [self.webView backForwardList]; - return list.currentItem == item || - [list.forwardList indexOfObject:item] != NSNotFound || - [list.backList indexOfObject:item] != NSNotFound; -} - - (void)webViewWebProcessDidCrash { [self setWebProcessIsDead:YES];
diff --git a/ios/web/web_state/web_state_delegate.mm b/ios/web/web_state/web_state_delegate.mm new file mode 100644 index 0000000..516f155 --- /dev/null +++ b/ios/web/web_state/web_state_delegate.mm
@@ -0,0 +1,33 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/web/public/web_state/web_state_delegate.h" + +#import "ios/web/public/web_state/web_state.h" + +namespace web { + +WebStateDelegate::WebStateDelegate() {} + +WebStateDelegate::~WebStateDelegate() { + while (!attached_states_.empty()) { + WebState* web_state = *attached_states_.begin(); + web_state->SetDelegate(nullptr); + } + DCHECK(attached_states_.empty()); +} + +void WebStateDelegate::LoadProgressChanged(WebState*, double) {} + +void WebStateDelegate::Attach(WebState* source) { + DCHECK(attached_states_.find(source) == attached_states_.end()); + attached_states_.insert(source); +} + +void WebStateDelegate::Detach(WebState* source) { + DCHECK(attached_states_.find(source) != attached_states_.end()); + attached_states_.erase(source); +} + +} // web
diff --git a/ios/web/web_state/web_state_delegate_bridge.mm b/ios/web/web_state/web_state_delegate_bridge.mm new file mode 100644 index 0000000..2ce0f6a --- /dev/null +++ b/ios/web/web_state/web_state_delegate_bridge.mm
@@ -0,0 +1,22 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/web/public/web_state/web_state_delegate_bridge.h" + +#include "base/logging.h" + +namespace web { + +WebStateDelegateBridge::WebStateDelegateBridge(id<CRWWebStateDelegate> delegate) + : delegate_(delegate) {} + +WebStateDelegateBridge::~WebStateDelegateBridge() {} + +void WebStateDelegateBridge::LoadProgressChanged(WebState* source, + double progress) { + if ([delegate_ respondsToSelector:@selector(webState:didChangeProgress:)]) + [delegate_ webState:source didChangeProgress:progress]; +} + +} // web \ No newline at end of file
diff --git a/ios/web/web_state/web_state_delegate_bridge_unittest.mm b/ios/web/web_state/web_state_delegate_bridge_unittest.mm new file mode 100644 index 0000000..a650633a --- /dev/null +++ b/ios/web/web_state/web_state_delegate_bridge_unittest.mm
@@ -0,0 +1,46 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/web/public/web_state/web_state_delegate_bridge.h" + +#include <memory> + +#import "base/mac/scoped_nsobject.h" +#import "ios/web/web_state/web_state_delegate_stub.h" +#include "testing/platform_test.h" +#import "third_party/ocmock/gtest_support.h" + +namespace web { + +// Test fixture to test WebStateDelegateBridge class. +class WebStateDelegateBridgeTest : public PlatformTest { + protected: + void SetUp() override { + PlatformTest::SetUp(); + + id originalMockDelegate = + [OCMockObject niceMockForProtocol:@protocol(CRWWebStateDelegate)]; + delegate_.reset([[CRWWebStateDelegateStub alloc] + initWithRepresentedObject:originalMockDelegate]); + + bridge_.reset(new WebStateDelegateBridge(delegate_.get())); + } + + void TearDown() override { + EXPECT_OCMOCK_VERIFY(delegate_); + PlatformTest::TearDown(); + } + + base::scoped_nsprotocol<id> delegate_; + std::unique_ptr<WebStateDelegateBridge> bridge_; +}; + +// Tests |LoadProgressChanged| forwarding. +TEST_F(WebStateDelegateBridgeTest, LoadProgressChanged) { + ASSERT_EQ(0.0, [delegate_ changedProgress]); + bridge_->LoadProgressChanged(nullptr, 1.0); + EXPECT_EQ(1.0, [delegate_ changedProgress]); +} + +} // namespace web
diff --git a/ios/web/web_state/web_state_delegate_stub.h b/ios/web/web_state/web_state_delegate_stub.h new file mode 100644 index 0000000..afd86ac --- /dev/null +++ b/ios/web/web_state/web_state_delegate_stub.h
@@ -0,0 +1,20 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_WEB_WEB_STATE_WEB_STATE_DELEGATE_STUB_H_ +#define IOS_WEB_WEB_STATE_WEB_STATE_DELEGATE_STUB_H_ + +#import "ios/testing/ocmock_complex_type_helper.h" +#import "ios/web/public/web_state/web_state_delegate_bridge.h" + +// Stub implementation for CRWWebStateDelegate protocol. +@interface CRWWebStateDelegateStub + : OCMockComplexTypeHelper<CRWWebStateDelegate> +// web::WebState received in delegate method calls.. +@property(nonatomic, readonly) web::WebState* webState; +// Progress received in |webState:didChangeProgress| call. +@property(nonatomic, readonly) double changedProgress; +@end + +#endif // IOS_WEB_WEB_STATE_WEB_STATE_DELEGATE_STUB_H_
diff --git a/ios/web/web_state/web_state_delegate_stub.mm b/ios/web/web_state/web_state_delegate_stub.mm new file mode 100644 index 0000000..78a438c --- /dev/null +++ b/ios/web/web_state/web_state_delegate_stub.mm
@@ -0,0 +1,19 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/web/web_state/web_state_delegate_stub.h" + +#import "ios/web/public/web_state/web_state.h" + +@implementation CRWWebStateDelegateStub + +@synthesize webState = _webState; +@synthesize changedProgress = _changedProgress; + +- (void)webState:(web::WebState*)webState didChangeProgress:(double)progress { + _webState = webState; + _changedProgress = progress; +} + +@end
diff --git a/ios/web/web_state/web_state_impl.h b/ios/web/web_state/web_state_impl.h index 261d87f..7b8e186 100644 --- a/ios/web/web_state/web_state_impl.h +++ b/ios/web/web_state/web_state_impl.h
@@ -41,6 +41,7 @@ struct LoadCommittedDetails; class NavigationManager; class WebInterstitialImpl; +class WebStateDelegate; class WebStateFacadeDelegate; class WebStatePolicyDecider; class WebUIIOS; @@ -215,6 +216,8 @@ NSString* GetRequestGroupID(); // WebState: + WebStateDelegate* GetDelegate() override; + void SetDelegate(WebStateDelegate* delegate) override; UIView* GetView() override; BrowserState* GetBrowserState() const override; void OpenURL(const WebState::OpenURLParams& params) override; @@ -250,6 +253,9 @@ // Called to dismiss the currently-displayed transient content view. void ClearTransientContentView(); + // Notifies the delegate that the load progress was updated. + void SendChangeLoadProgress(double progress); + // NavigationManagerDelegate: void NavigateToPendingEntry() override; void LoadURLWithParams(const NavigationManager::WebLoadParams&) override; @@ -278,6 +284,9 @@ // Returns true if |web_controller_| has been set. bool Configured() const; + // Delegate, not owned by this object. + WebStateDelegate* delegate_; + // Stores whether the web state is currently loading a page. bool is_loading_;
diff --git a/ios/web/web_state/web_state_impl.mm b/ios/web/web_state/web_state_impl.mm index f8d9071..281be04 100644 --- a/ios/web/web_state/web_state_impl.mm +++ b/ios/web/web_state/web_state_impl.mm
@@ -19,6 +19,7 @@ #include "ios/web/public/web_client.h" #include "ios/web/public/web_state/credential.h" #include "ios/web/public/web_state/ui/crw_content_view.h" +#include "ios/web/public/web_state/web_state_delegate.h" #include "ios/web/public/web_state/web_state_observer.h" #include "ios/web/public/web_state/web_state_policy_decider.h" #include "ios/web/web_state/global_web_state_event_tracker.h" @@ -33,7 +34,8 @@ namespace web { WebStateImpl::WebStateImpl(BrowserState* browser_state) - : is_loading_(false), + : delegate_(nullptr), + is_loading_(false), is_being_destroyed_(false), facade_delegate_(nullptr), web_controller_(nil), @@ -65,6 +67,22 @@ DCHECK(script_command_callbacks_.empty()); if (request_tracker_.get()) CloseRequestTracker(); + SetDelegate(nullptr); +} + +WebStateDelegate* WebStateImpl::GetDelegate() { + return delegate_; +} + +void WebStateImpl::SetDelegate(WebStateDelegate* delegate) { + if (delegate == delegate_) + return; + if (delegate_) + delegate_->Detach(this); + delegate_ = delegate; + if (delegate_) { + delegate_->Attach(this); + } } void WebStateImpl::AddObserver(WebStateObserver* observer) { @@ -379,6 +397,12 @@ [web_controller_ clearTransientContentView]; } +void WebStateImpl::SendChangeLoadProgress(double progress) { + if (delegate_) { + delegate_->LoadProgressChanged(this, progress); + } +} + WebUIIOS* WebStateImpl::CreateWebUIIOS(const GURL& url) { WebUIIOSControllerFactory* factory = WebUIIOSControllerFactoryRegistry::GetInstance();
diff --git a/ios/web/web_state/web_state_impl_unittest.mm b/ios/web/web_state/web_state_impl_unittest.mm index 2502cb91..a47a626 100644 --- a/ios/web/web_state/web_state_impl_unittest.mm +++ b/ios/web/web_state/web_state_impl_unittest.mm
@@ -14,6 +14,7 @@ #include "ios/web/public/load_committed_details.h" #include "ios/web/public/test/test_browser_state.h" #include "ios/web/public/web_state/global_web_state_observer.h" +#include "ios/web/public/web_state/web_state_delegate.h" #include "ios/web/public/web_state/web_state_observer.h" #include "ios/web/public/web_state/web_state_policy_decider.h" #import "ios/web/test/web_test.h" @@ -106,6 +107,27 @@ bool web_state_destroyed_called_; }; +// Test delegate to check that the WebStateDelegate methods are called as +// expected. +class TestWebStateDelegate : public WebStateDelegate { + public: + TestWebStateDelegate() : load_progress_changed_called_(false) {} + + // Methods returning true if the corresponding WebStateObserver method has + // been called. + bool load_progress_changed_called() const { + return load_progress_changed_called_; + } + + private: + // WebStateObserver implementation: + void LoadProgressChanged(WebState* source, double progress) override { + load_progress_changed_called_ = true; + } + + bool load_progress_changed_called_; +}; + // Test observer to check that the WebStateObserver methods are called as // expected. class TestWebStateObserver : public WebStateObserver { @@ -344,6 +366,17 @@ EXPECT_EQ(nullptr, observer->web_state()); } +// Tests that WebStateDelegate methods appropriately called. +TEST_F(WebStateTest, DelegateTest) { + TestWebStateDelegate delegate; + web_state_->SetDelegate(&delegate); + + // Test that LoadProgressChanged() is called. + EXPECT_FALSE(delegate.load_progress_changed_called()); + web_state_->SendChangeLoadProgress(0.0); + EXPECT_TRUE(delegate.load_progress_changed_called()); +} + // Verifies that GlobalWebStateObservers are called when expected. TEST_F(WebStateTest, GlobalObserverTest) { std::unique_ptr<TestGlobalWebStateObserver> observer(
diff --git a/ipc/ipc_message_start.h b/ipc/ipc_message_start.h index ea1f7b998..0d589ff 100644 --- a/ipc/ipc_message_start.h +++ b/ipc/ipc_message_start.h
@@ -91,7 +91,6 @@ ScreenOrientationMsgStart, MediaStreamTrackMetricsHostMsgStart, ChromeExtensionMsgStart, - MojoMsgStart, TranslateMsgStart, CldDataProviderMsgStart, PushMessagingMsgStart,
diff --git a/ipc/ipc_message_utils.cc b/ipc/ipc_message_utils.cc index 9edc3bb..59057ee 100644 --- a/ipc/ipc_message_utils.cc +++ b/ipc/ipc_message_utils.cc
@@ -690,90 +690,40 @@ #if defined(OS_MACOSX) && !defined(OS_IOS) void ParamTraits<base::SharedMemoryHandle>::Write(base::Pickle* m, const param_type& p) { - m->WriteInt(p.GetType()); + MachPortMac mach_port_mac(p.GetMemoryObject()); + ParamTraits<MachPortMac>::Write(m, mach_port_mac); + size_t size = 0; + bool result = p.GetSize(&size); + DCHECK(result); + ParamTraits<uint32_t>::Write(m, static_cast<uint32_t>(size)); - switch (p.GetType()) { - case base::SharedMemoryHandle::POSIX: - ParamTraits<base::FileDescriptor>::Write(m, p.GetFileDescriptor()); - break; - case base::SharedMemoryHandle::MACH: - MachPortMac mach_port_mac(p.GetMemoryObject()); - ParamTraits<MachPortMac>::Write(m, mach_port_mac); - size_t size = 0; - bool result = p.GetSize(&size); - DCHECK(result); - ParamTraits<uint32_t>::Write(m, static_cast<uint32_t>(size)); - - // If the caller intended to pass ownership to the IPC stack, release a - // reference. - if (p.OwnershipPassesToIPC()) - p.Close(); - - break; - } + // If the caller intended to pass ownership to the IPC stack, release a + // reference. + if (p.OwnershipPassesToIPC()) + p.Close(); } bool ParamTraits<base::SharedMemoryHandle>::Read(const base::Pickle* m, base::PickleIterator* iter, param_type* r) { - base::SharedMemoryHandle::TypeWireFormat type; - if (!iter->ReadInt(&type)) + MachPortMac mach_port_mac; + if (!ParamTraits<MachPortMac>::Read(m, iter, &mach_port_mac)) return false; - base::SharedMemoryHandle::Type shm_type = base::SharedMemoryHandle::POSIX; - switch (type) { - case base::SharedMemoryHandle::POSIX: - case base::SharedMemoryHandle::MACH: { - shm_type = static_cast<base::SharedMemoryHandle::Type>(type); - break; - } - default: { - return false; - } - } + uint32_t size; + if (!ParamTraits<uint32_t>::Read(m, iter, &size)) + return false; - switch (shm_type) { - case base::SharedMemoryHandle::POSIX: { - base::FileDescriptor file_descriptor; - - bool success = - ParamTraits<base::FileDescriptor>::Read(m, iter, &file_descriptor); - if (!success) - return false; - - *r = base::SharedMemoryHandle(file_descriptor.fd, - file_descriptor.auto_close); - return true; - } - case base::SharedMemoryHandle::MACH: { - MachPortMac mach_port_mac; - if (!ParamTraits<MachPortMac>::Read(m, iter, &mach_port_mac)) - return false; - - uint32_t size; - if (!ParamTraits<uint32_t>::Read(m, iter, &size)) - return false; - - *r = base::SharedMemoryHandle(mach_port_mac.get_mach_port(), - static_cast<size_t>(size), - base::GetCurrentProcId()); - return true; - } - } + *r = base::SharedMemoryHandle(mach_port_mac.get_mach_port(), + static_cast<size_t>(size), + base::GetCurrentProcId()); + return true; } void ParamTraits<base::SharedMemoryHandle>::Log(const param_type& p, std::string* l) { - switch (p.GetType()) { - case base::SharedMemoryHandle::POSIX: - l->append("POSIX Fd: "); - ParamTraits<base::FileDescriptor>::Log(p.GetFileDescriptor(), l); - break; - case base::SharedMemoryHandle::MACH: - l->append("Mach port: "); - LogParam(p.GetMemoryObject(), l); - break; - } + l->append("Mach port: "); + LogParam(p.GetMemoryObject(), l); } #elif defined(OS_WIN)
diff --git a/jingle/glue/proxy_resolving_client_socket.h b/jingle/glue/proxy_resolving_client_socket.h index 14f5175..554c201 100644 --- a/jingle/glue/proxy_resolving_client_socket.h +++ b/jingle/glue/proxy_resolving_client_socket.h
@@ -13,6 +13,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "net/base/completion_callback.h" #include "net/base/host_port_pair.h"
diff --git a/mash/catalog_viewer/BUILD.gn b/mash/catalog_viewer/BUILD.gn index cfe5428..96547a68 100644 --- a/mash/catalog_viewer/BUILD.gn +++ b/mash/catalog_viewer/BUILD.gn
@@ -15,6 +15,7 @@ deps = [ "//base", + "//mash/public/interfaces", "//mojo/public/cpp/bindings", "//services/catalog/public/interfaces", "//services/shell/public/cpp",
diff --git a/mash/catalog_viewer/catalog_viewer.cc b/mash/catalog_viewer/catalog_viewer.cc index 66027f1..ec008780 100644 --- a/mash/catalog_viewer/catalog_viewer.cc +++ b/mash/catalog_viewer/catalog_viewer.cc
@@ -35,8 +35,10 @@ class CatalogViewerContents : public views::WidgetDelegateView, public ui::TableModel { public: - CatalogViewerContents(catalog::mojom::CatalogPtr catalog) - : catalog_(std::move(catalog)), + CatalogViewerContents(CatalogViewer* catalog_viewer, + catalog::mojom::CatalogPtr catalog) + : catalog_viewer_(catalog_viewer), + catalog_(std::move(catalog)), table_view_(nullptr), table_view_parent_(nullptr), observer_(nullptr), @@ -57,7 +59,7 @@ } ~CatalogViewerContents() override { table_view_->SetModel(nullptr); - base::MessageLoop::current()->QuitWhenIdle(); + catalog_viewer_->RemoveWindow(GetWidget()); } private: @@ -115,11 +117,10 @@ observer_ = observer; } - void OnGotCatalogEntries( - mojo::Map<mojo::String, catalog::mojom::CatalogEntryPtr> entries) { + void OnGotCatalogEntries(mojo::Array<catalog::mojom::EntryPtr> entries) { entries_.clear(); for (auto& entry : entries) - entries_.push_back(Entry(entry.second->display_name, entry.first)); + entries_.push_back(Entry(entry->display_name, entry->name)); observer_->OnModelChanged(); } @@ -147,6 +148,7 @@ return columns; } + CatalogViewer* catalog_viewer_; catalog::mojom::CatalogPtr catalog_; views::TableView* table_view_; @@ -165,21 +167,49 @@ CatalogViewer::CatalogViewer() {} CatalogViewer::~CatalogViewer() {} +void CatalogViewer::RemoveWindow(views::Widget* window) { + auto it = std::find(windows_.begin(), windows_.end(), window); + DCHECK(it != windows_.end()); + windows_.erase(it); + if (windows_.empty()) + base::MessageLoop::current()->QuitWhenIdle(); +} + void CatalogViewer::Initialize(shell::Connector* connector, const shell::Identity& identity, uint32_t id) { + connector_ = connector; tracing_.Initialize(connector, identity.name()); aura_init_.reset(new views::AuraInit(connector, "views_mus_resources.pak")); views::WindowManagerConnection::Create(connector); +} +bool CatalogViewer::AcceptConnection(shell::Connection* connection) { + connection->AddInterface<mojom::Launchable>(this); + return true; +} + +void CatalogViewer::Launch(uint32_t what, mojom::LaunchMode how) { + bool reuse = how == mojom::LaunchMode::REUSE || + how == mojom::LaunchMode::DEFAULT; + if (reuse && !windows_.empty()) { + windows_.back()->Activate(); + return; + } catalog::mojom::CatalogPtr catalog; - connector->ConnectToInterface("mojo:catalog", &catalog); + connector_->ConnectToInterface("mojo:catalog", &catalog); views::Widget* window = views::Widget::CreateWindowWithContextAndBounds( - new CatalogViewerContents(std::move(catalog)), nullptr, + new CatalogViewerContents(this, std::move(catalog)), nullptr, gfx::Rect(25, 25, 500, 600)); window->Show(); + windows_.push_back(window); +} + +void CatalogViewer::Create(shell::Connection* connection, + mojom::LaunchableRequest request) { + bindings_.AddBinding(this, std::move(request)); } } // namespace catalog_viewer
diff --git a/mash/catalog_viewer/catalog_viewer.h b/mash/catalog_viewer/catalog_viewer.h index 36c4a2ff..892847c 100644 --- a/mash/catalog_viewer/catalog_viewer.h +++ b/mash/catalog_viewer/catalog_viewer.h
@@ -10,26 +10,46 @@ #include "base/callback.h" #include "base/macros.h" +#include "mash/public/interfaces/launchable.mojom.h" +#include "mojo/public/cpp/bindings/binding_set.h" #include "services/shell/public/cpp/shell_client.h" #include "services/tracing/public/cpp/tracing_impl.h" namespace views { class AuraInit; +class Widget; } namespace mash { namespace catalog_viewer { -class CatalogViewer : public shell::ShellClient { +class CatalogViewer : public shell::ShellClient, + public mojom::Launchable, + public shell::InterfaceFactory<mojom::Launchable> { public: CatalogViewer(); ~CatalogViewer() override; + void RemoveWindow(views::Widget* window); + private: // shell::ShellClient: void Initialize(shell::Connector* connector, const shell::Identity& identity, uint32_t id) override; + bool AcceptConnection(shell::Connection* connection) override; + + // mojom::Launchable: + void Launch(uint32_t what, mojom::LaunchMode how) override; + + // shell::InterfaceFactory<mojom::Launchable>: + void Create(shell::Connection* connection, + mojom::LaunchableRequest request) override; + + + shell::Connector* connector_ = nullptr; + mojo::BindingSet<mojom::Launchable> bindings_; + std::vector<views::Widget*> windows_; mojo::TracingImpl tracing_; std::unique_ptr<views::AuraInit> aura_init_;
diff --git a/mash/catalog_viewer/manifest.json b/mash/catalog_viewer/manifest.json index fb81a6e8..c8913020 100644 --- a/mash/catalog_viewer/manifest.json +++ b/mash/catalog_viewer/manifest.json
@@ -1,5 +1,9 @@ { + "manifest_version": 1, "name": "mojo:catalog_viewer", "display_name": "Catalog Viewer", - "capabilities": { "*": [ "*" ] } + "capabilities": { + "provided": { "launchable": ["mash::mojom::Launchable"] }, + "required": { "*": { "interfaces": [ "*" ] } } + } }
diff --git a/mash/example/views_examples/BUILD.gn b/mash/example/views_examples/BUILD.gn index 1913237f..0c7a5dfd 100644 --- a/mash/example/views_examples/BUILD.gn +++ b/mash/example/views_examples/BUILD.gn
@@ -20,6 +20,7 @@ deps = [ "//base", "//components/mus/public/interfaces", + "//mash/public/interfaces", "//mojo/converters/geometry", "//mojo/public/cpp/bindings", "//services/shell/public/cpp",
diff --git a/mash/example/views_examples/manifest.json b/mash/example/views_examples/manifest.json index fa7fa99d4..950431f 100644 --- a/mash/example/views_examples/manifest.json +++ b/mash/example/views_examples/manifest.json
@@ -1,5 +1,9 @@ { + "manifest_version": 1, "name": "mojo:views_examples", "display_name": "Views Examples", - "capabilities": { "*": ["*"] } + "capabilities": { + "provided": { "launchable": ["mash::mojom::Launchable"] }, + "required": { "*": { "interfaces": [ "*" ] } } + } }
diff --git a/mash/example/views_examples/views_examples_application_delegate.cc b/mash/example/views_examples/views_examples_application_delegate.cc index ef2e8c7..fc7ec53 100644 --- a/mash/example/views_examples/views_examples_application_delegate.cc +++ b/mash/example/views_examples/views_examples_application_delegate.cc
@@ -22,14 +22,23 @@ uint32_t id) { tracing_.Initialize(connector, identity.name()); aura_init_.reset(new views::AuraInit(connector, "views_mus_resources.pak")); - views::WindowManagerConnection::Create(connector); - - views::examples::ShowExamplesWindow(views::examples::DO_NOTHING_ON_CLOSE, - nullptr, nullptr); } bool ViewsExamplesApplicationDelegate::AcceptConnection( shell::Connection* connection) { - return false; + connection->AddInterface<mash::mojom::Launchable>(this); + return true; +} + +void ViewsExamplesApplicationDelegate::Launch(uint32_t what, + mash::mojom::LaunchMode how) { + views::examples::ShowExamplesWindow(views::examples::QUIT_ON_CLOSE, + nullptr, nullptr); +} + +void ViewsExamplesApplicationDelegate::Create( + shell::Connection* connection, + mash::mojom::LaunchableRequest request) { + bindings_.AddBinding(this, std::move(request)); }
diff --git a/mash/example/views_examples/views_examples_application_delegate.h b/mash/example/views_examples/views_examples_application_delegate.h index 005dde7..a05cb33 100644 --- a/mash/example/views_examples/views_examples_application_delegate.h +++ b/mash/example/views_examples/views_examples_application_delegate.h
@@ -8,6 +8,8 @@ #include <memory> #include "base/macros.h" +#include "mash/public/interfaces/launchable.mojom.h" +#include "mojo/public/cpp/bindings/binding_set.h" #include "services/shell/public/cpp/shell_client.h" #include "services/tracing/public/cpp/tracing_impl.h" @@ -15,7 +17,10 @@ class AuraInit; } -class ViewsExamplesApplicationDelegate : public shell::ShellClient { +class ViewsExamplesApplicationDelegate + : public shell::ShellClient, + public mash::mojom::Launchable, + public shell::InterfaceFactory<mash::mojom::Launchable> { public: ViewsExamplesApplicationDelegate(); ~ViewsExamplesApplicationDelegate() override; @@ -27,8 +32,16 @@ uint32_t id) override; bool AcceptConnection(shell::Connection* connection) override; - mojo::TracingImpl tracing_; + // mash::mojom::Launchable: + void Launch(uint32_t what, mash::mojom::LaunchMode how) override; + // shell::InterfaceFactory<mash::mojom::Launchable>: + void Create(shell::Connection* connection, + mash::mojom::LaunchableRequest request) override; + + mojo::BindingSet<mash::mojom::Launchable> bindings_; + + mojo::TracingImpl tracing_; std::unique_ptr<views::AuraInit> aura_init_; DISALLOW_COPY_AND_ASSIGN(ViewsExamplesApplicationDelegate);
diff --git a/mash/example/window_type_launcher/BUILD.gn b/mash/example/window_type_launcher/BUILD.gn index 99d037e..7b81e9d 100644 --- a/mash/example/window_type_launcher/BUILD.gn +++ b/mash/example/window_type_launcher/BUILD.gn
@@ -24,6 +24,7 @@ "//base:base_static", "//build/config/sanitizers:deps", "//components/mus/public/interfaces", + "//mash/public/interfaces", "//mash/session/public/interfaces", "//mojo/common:common_base", "//mojo/converters/geometry", @@ -54,7 +55,7 @@ "$root_out_dir/views_mus_resources.pak", ] outputs = [ - "$root_out_dir/window_type_launcher_exe_res/resources/views_mus_resources.pak", + "$root_out_dir/Mojo Applications/window_type_launcher_exe/resources/views_mus_resources.pak", ] deps = [ "//ui/views/mus:resources",
diff --git a/mash/example/window_type_launcher/window_type_launcher.cc b/mash/example/window_type_launcher/window_type_launcher.cc index e18b8a7..76efffcb 100644 --- a/mash/example/window_type_launcher/window_type_launcher.cc +++ b/mash/example/window_type_launcher/window_type_launcher.cc
@@ -165,8 +165,10 @@ public views::MenuDelegate, public views::ContextMenuController { public: - explicit WindowTypeLauncherView(shell::Connector* connector) - : connector_(connector), + explicit WindowTypeLauncherView(WindowTypeLauncher* window_type_launcher, + shell::Connector* connector) + : window_type_launcher_(window_type_launcher), + connector_(connector), create_button_( new views::LabelButton(this, base::ASCIIToUTF16("Create Window"))), panel_button_( @@ -250,7 +252,9 @@ AddViewToLayout(layout, show_web_notification_); set_context_menu_controller(this); } - ~WindowTypeLauncherView() override {} + ~WindowTypeLauncherView() override { + window_type_launcher_->RemoveWindow(GetWidget()); + } private: typedef std::pair<aura::Window*, gfx::Rect> WindowAndBoundsPair; @@ -354,6 +358,7 @@ } } + WindowTypeLauncher* window_type_launcher_; shell::Connector* connector_; views::LabelButton* create_button_; views::LabelButton* panel_button_; @@ -380,21 +385,44 @@ WindowTypeLauncher::WindowTypeLauncher() {} WindowTypeLauncher::~WindowTypeLauncher() {} +void WindowTypeLauncher::RemoveWindow(views::Widget* window) { + auto it = std::find(windows_.begin(), windows_.end(), window); + DCHECK(it != windows_.end()); + windows_.erase(it); + if (windows_.empty()) + base::MessageLoop::current()->QuitWhenIdle(); +} + void WindowTypeLauncher::Initialize(shell::Connector* connector, const shell::Identity& identity, uint32_t id) { + connector_ = connector; aura_init_.reset(new views::AuraInit(connector, "views_mus_resources.pak")); views::WindowManagerConnection::Create(connector); - - views::Widget* widget = new views::Widget; - views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW); - params.delegate = new WindowTypeLauncherView(connector); - widget->Init(params); - widget->Show(); } -bool WindowTypeLauncher::ShellConnectionLost() { - base::MessageLoop::current()->QuitWhenIdle(); - return false; +bool WindowTypeLauncher::AcceptConnection(shell::Connection* connection) { + connection->AddInterface<mash::mojom::Launchable>(this); + return true; +} + +void WindowTypeLauncher::Launch(uint32_t what, mash::mojom::LaunchMode how) { + bool reuse = how == mash::mojom::LaunchMode::REUSE || + how == mash::mojom::LaunchMode::DEFAULT; + if (reuse && !windows_.empty()) { + windows_.back()->Activate(); + return; + } + views::Widget* window = new views::Widget; + views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW); + params.delegate = new WindowTypeLauncherView(this, connector_); + window->Init(params); + window->Show(); + windows_.push_back(window); +} + +void WindowTypeLauncher::Create(shell::Connection* connection, + mash::mojom::LaunchableRequest request) { + bindings_.AddBinding(this, std::move(request)); }
diff --git a/mash/example/window_type_launcher/window_type_launcher.h b/mash/example/window_type_launcher/window_type_launcher.h index 67d32ab..9b3851c 100644 --- a/mash/example/window_type_launcher/window_type_launcher.h +++ b/mash/example/window_type_launcher/window_type_launcher.h
@@ -8,23 +8,42 @@ #include <memory> #include "base/macros.h" +#include "mash/public/interfaces/launchable.mojom.h" +#include "mojo/public/cpp/bindings/binding_set.h" #include "services/shell/public/cpp/shell_client.h" namespace views { class AuraInit; +class Widget; } -class WindowTypeLauncher : public shell::ShellClient { +class WindowTypeLauncher + : public shell::ShellClient, + public mash::mojom::Launchable, + public shell::InterfaceFactory<mash::mojom::Launchable> { public: WindowTypeLauncher(); ~WindowTypeLauncher() override; + void RemoveWindow(views::Widget* window); + private: // shell::ShellClient: void Initialize(shell::Connector* connector, const shell::Identity& identity, uint32_t id) override; - bool ShellConnectionLost() override; + bool AcceptConnection(shell::Connection* connection) override; + + // mash::mojom::Launchable: + void Launch(uint32_t what, mash::mojom::LaunchMode how) override; + + // shell::InterfaceFactory<mash::mojom::Launchable>: + void Create(shell::Connection* connection, + mash::mojom::LaunchableRequest request) override; + + shell::Connector* connector_ = nullptr; + mojo::BindingSet<mash::mojom::Launchable> bindings_; + std::vector<views::Widget*> windows_; std::unique_ptr<views::AuraInit> aura_init_;
diff --git a/mash/public/interfaces/BUILD.gn b/mash/public/interfaces/BUILD.gn new file mode 100644 index 0000000..17753e7 --- /dev/null +++ b/mash/public/interfaces/BUILD.gn
@@ -0,0 +1,11 @@ +# Copyright 2016 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//mojo/public/tools/bindings/mojom.gni") + +mojom("interfaces") { + sources = [ + "launchable.mojom", + ] +}
diff --git a/mash/public/interfaces/launchable.mojom b/mash/public/interfaces/launchable.mojom new file mode 100644 index 0000000..21fe41f --- /dev/null +++ b/mash/public/interfaces/launchable.mojom
@@ -0,0 +1,22 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module mash.mojom; + +const uint32 kWindow = 1; +const uint32 kDocument = 2; + +enum LaunchMode { + DEFAULT, + REUSE, + MAKE_NEW +}; + +interface Launchable { + // Launches something. The implementor decides what constitutes a "thing." If + // an instance of the thing is already present, the implementor may decide to + // re-select that thing instead of making another, depending on the value of + // |how|. In many windowing cases, the thing is a window. + Launch(uint32 what, LaunchMode how); +};
diff --git a/mash/quick_launch/BUILD.gn b/mash/quick_launch/BUILD.gn index 93487af4..988ab82 100644 --- a/mash/quick_launch/BUILD.gn +++ b/mash/quick_launch/BUILD.gn
@@ -16,6 +16,7 @@ deps = [ "//base", + "//mash/public/interfaces", "//mojo/public/cpp/bindings", "//services/catalog/public/interfaces", "//services/shell/public/cpp",
diff --git a/mash/quick_launch/manifest.json b/mash/quick_launch/manifest.json index 363322b..7159c415 100644 --- a/mash/quick_launch/manifest.json +++ b/mash/quick_launch/manifest.json
@@ -1,5 +1,9 @@ { + "manifest_version": 1, "name": "mojo:quick_launch", - "display_name": "Quick Launch", - "capabilities": { "*": ["*"] } + "display_name": "Quick Launch Bar", + "capabilities": { + "provided": { "launchable": ["mash::mojom::Launchable"] }, + "required": { "*": { "interfaces": [ "*" ] } } + } }
diff --git a/mash/quick_launch/quick_launch_application.cc b/mash/quick_launch/quick_launch_application.cc index f4ada35..5c3d164 100644 --- a/mash/quick_launch/quick_launch_application.cc +++ b/mash/quick_launch/quick_launch_application.cc
@@ -9,7 +9,9 @@ #include "base/strings/string16.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "mash/public/interfaces/launchable.mojom.h" #include "mojo/public/c/system/main.h" +#include "services/catalog/public/interfaces/resolver.mojom.h" #include "services/shell/public/cpp/application_runner.h" #include "services/shell/public/cpp/connector.h" #include "services/shell/public/cpp/shell_client.h" @@ -32,17 +34,22 @@ class QuickLaunchUI : public views::WidgetDelegateView, public views::TextfieldController { public: - QuickLaunchUI(shell::Connector* connector, catalog::mojom::CatalogPtr catalog) - : connector_(connector), + QuickLaunchUI(QuickLaunchApplication* quick_launch, + shell::Connector* connector, + catalog::mojom::ResolverPtr resolver) + : quick_launch_(quick_launch), + connector_(connector), prompt_(new views::Textfield), - catalog_(std::move(catalog)) { + resolver_(std::move(resolver)) { set_background(views::Background::CreateStandardPanelBackground()); prompt_->set_controller(this); AddChildView(prompt_); UpdateEntries(); } - ~QuickLaunchUI() override {} + ~QuickLaunchUI() override { + quick_launch_->RemoveWindow(GetWidget()); + } private: // Overridden from views::WidgetDelegate: @@ -70,8 +77,7 @@ suggestion_rejected_ = false; switch (key_event.key_code()) { case ui::VKEY_RETURN: { - std::string url = Canonicalize(prompt_->text()); - connections_.push_back(connector_->Connect(url)); + Launch(Canonicalize(prompt_->text()), key_event.IsControlDown()); prompt_->SetText(base::string16()); UpdateEntries(); } break; @@ -117,21 +123,31 @@ } void UpdateEntries() { - catalog_->GetEntries(nullptr, - base::Bind(&QuickLaunchUI::OnGotCatalogEntries, - base::Unretained(this))); + resolver_->ResolveClass("launchable", + base::Bind(&QuickLaunchUI::OnGotCatalogEntries, + base::Unretained(this))); } - void OnGotCatalogEntries( - mojo::Map<mojo::String, catalog::mojom::CatalogEntryPtr> entries) { + void OnGotCatalogEntries(mojo::Array<catalog::mojom::EntryPtr> entries) { for (const auto& entry : entries) - app_names_.insert(base::UTF8ToUTF16(entry.first.get())); + app_names_.insert(base::UTF8ToUTF16(entry->name.get())); } + void Launch(const std::string& name, bool new_window) { + scoped_ptr<shell::Connection> connection = connector_->Connect(name); + mojom::LaunchablePtr launchable; + connection->GetInterface(&launchable); + connections_.push_back(std::move(connection)); + launchable->Launch(mojom::kWindow, + new_window ? mojom::LaunchMode::MAKE_NEW + : mojom::LaunchMode::REUSE); + } + + QuickLaunchApplication* quick_launch_; shell::Connector* connector_; views::Textfield* prompt_; std::vector<std::unique_ptr<shell::Connection>> connections_; - catalog::mojom::CatalogPtr catalog_; + catalog::mojom::ResolverPtr resolver_; std::set<base::string16> app_names_; bool suggestion_rejected_ = false; @@ -141,26 +157,52 @@ QuickLaunchApplication::QuickLaunchApplication() {} QuickLaunchApplication::~QuickLaunchApplication() {} +void QuickLaunchApplication::RemoveWindow(views::Widget* window) { + auto it = std::find(windows_.begin(), windows_.end(), window); + DCHECK(it != windows_.end()); + windows_.erase(it); + if (windows_.empty()) + base::MessageLoop::current()->QuitWhenIdle(); +} + void QuickLaunchApplication::Initialize(shell::Connector* connector, const shell::Identity& identity, uint32_t id) { + connector_ = connector; tracing_.Initialize(connector, identity.name()); aura_init_.reset(new views::AuraInit(connector, "views_mus_resources.pak")); views::WindowManagerConnection::Create(connector); - catalog::mojom::CatalogPtr catalog; - connector->ConnectToInterface("mojo:catalog", &catalog); - - views::Widget* window = views::Widget::CreateWindowWithContextAndBounds( - new QuickLaunchUI(connector, std::move(catalog)), nullptr, - gfx::Rect(10, 640, 0, 0)); - window->Show(); + Launch(mojom::kWindow, mojom::LaunchMode::MAKE_NEW); } bool QuickLaunchApplication::AcceptConnection(shell::Connection* connection) { + connection->AddInterface<mojom::Launchable>(this); return true; } +void QuickLaunchApplication::Launch(uint32_t what, mojom::LaunchMode how) { + bool reuse = how == mojom::LaunchMode::REUSE || + how == mojom::LaunchMode::DEFAULT; + if (reuse && !windows_.empty()) { + windows_.back()->Activate(); + return; + } + catalog::mojom::ResolverPtr resolver; + connector_->ConnectToInterface("mojo:catalog", &resolver); + + views::Widget* window = views::Widget::CreateWindowWithContextAndBounds( + new QuickLaunchUI(this, connector_, std::move(resolver)), nullptr, + gfx::Rect(10, 640, 0, 0)); + window->Show(); + windows_.push_back(window); +} + +void QuickLaunchApplication::Create(shell::Connection* connection, + mojom::LaunchableRequest request) { + bindings_.AddBinding(this, std::move(request)); +} + } // namespace quick_launch } // namespace mash
diff --git a/mash/quick_launch/quick_launch_application.h b/mash/quick_launch/quick_launch_application.h index b11ec71e..347c2963 100644 --- a/mash/quick_launch/quick_launch_application.h +++ b/mash/quick_launch/quick_launch_application.h
@@ -8,22 +8,29 @@ #include <memory> #include "base/macros.h" -#include "services/catalog/public/interfaces/catalog.mojom.h" +#include "mash/public/interfaces/launchable.mojom.h" +#include "mojo/public/cpp/bindings/binding_set.h" #include "services/shell/public/cpp/shell_client.h" #include "services/tracing/public/cpp/tracing_impl.h" namespace views { class AuraInit; +class Widget; } namespace mash { namespace quick_launch { -class QuickLaunchApplication : public shell::ShellClient { +class QuickLaunchApplication + : public shell::ShellClient, + public mojom::Launchable, + public shell::InterfaceFactory<mojom::Launchable> { public: QuickLaunchApplication(); ~QuickLaunchApplication() override; + void RemoveWindow(views::Widget* window); + private: // shell::ShellClient: void Initialize(shell::Connector* connector, @@ -31,6 +38,17 @@ uint32_t id) override; bool AcceptConnection(shell::Connection* connection) override; + // mojom::Launchable: + void Launch(uint32_t what, mojom::LaunchMode how) override; + + // shell::InterfaceFactory<mojom::Launchable>: + void Create(shell::Connection* connection, + mojom::LaunchableRequest request) override; + + shell::Connector* connector_ = nullptr; + mojo::BindingSet<mojom::Launchable> bindings_; + std::vector<views::Widget*> windows_; + mojo::TracingImpl tracing_; std::unique_ptr<views::AuraInit> aura_init_;
diff --git a/mash/task_viewer/BUILD.gn b/mash/task_viewer/BUILD.gn index 1a1b7b7..f7515da3 100644 --- a/mash/task_viewer/BUILD.gn +++ b/mash/task_viewer/BUILD.gn
@@ -15,6 +15,7 @@ deps = [ "//base", + "//mash/public/interfaces", "//mojo/public/cpp/bindings", "//services/catalog/public/interfaces", "//services/shell/public/cpp",
diff --git a/mash/task_viewer/manifest.json b/mash/task_viewer/manifest.json index a9cea18..2f1487a 100644 --- a/mash/task_viewer/manifest.json +++ b/mash/task_viewer/manifest.json
@@ -1,5 +1,9 @@ { + "manifest_version": 1, "name": "mojo:task_viewer", "display_name": "Task Viewer", - "capabilities": { "*": [ "*" ] } + "capabilities": { + "provided": { "launchable": ["mash::mojom::Launchable"] }, + "required": { "*": { "interfaces": [ "*" ] } } + } }
diff --git a/mash/task_viewer/task_viewer.cc b/mash/task_viewer/task_viewer.cc index b1a2285..ead7f6f4 100644 --- a/mash/task_viewer/task_viewer.cc +++ b/mash/task_viewer/task_viewer.cc
@@ -41,9 +41,11 @@ public views::ButtonListener, public shell::mojom::InstanceListener { public: - TaskViewerContents(shell::mojom::InstanceListenerRequest request, + TaskViewerContents(TaskViewer* task_viewer, + shell::mojom::InstanceListenerRequest request, catalog::mojom::CatalogPtr catalog) - : binding_(this, std::move(request)), + : task_viewer_(task_viewer), + binding_(this, std::move(request)), catalog_(std::move(catalog)), table_view_(nullptr), table_view_parent_(nullptr), @@ -67,7 +69,7 @@ } ~TaskViewerContents() override { table_view_->SetModel(nullptr); - base::MessageLoop::current()->QuitWhenIdle(); + task_viewer_->RemoveWindow(GetWidget()); } private: @@ -207,14 +209,15 @@ instances_.push_back(base::WrapUnique(new InstanceInfo(id, url, pid))); } - void OnGotCatalogEntries( - mojo::Map<mojo::String, catalog::mojom::CatalogEntryPtr> entries) { + void OnGotCatalogEntries(mojo::Array<catalog::mojom::EntryPtr> entries) { for (auto it = instances_.begin(); it != instances_.end(); ++it) { - auto entry_it = entries.find((*it)->url); - if (entry_it != entries.end()) { - (*it)->name = entry_it->second->display_name; - observer_->OnItemsChanged( - static_cast<int>(it - instances_.begin()), 1); + for (auto& entry : entries) { + if (entry->name == (*it)->url) { + (*it)->name = entry->display_name; + observer_->OnItemsChanged( + static_cast<int>(it - instances_.begin()), 1); + break; + } } } } @@ -251,6 +254,7 @@ return columns; } + TaskViewer* task_viewer_; mojo::Binding<shell::mojom::InstanceListener> binding_; catalog::mojom::CatalogPtr catalog_; @@ -271,29 +275,58 @@ TaskViewer::TaskViewer() {} TaskViewer::~TaskViewer() {} +void TaskViewer::RemoveWindow(views::Widget* widget) { + auto it = std::find(windows_.begin(), windows_.end(), widget); + DCHECK(it != windows_.end()); + windows_.erase(it); + if (windows_.empty()) + base::MessageLoop::current()->QuitWhenIdle(); +} + void TaskViewer::Initialize(shell::Connector* connector, const shell::Identity& identity, uint32_t id) { + connector_ = connector; tracing_.Initialize(connector, identity.name()); aura_init_.reset(new views::AuraInit(connector, "views_mus_resources.pak")); views::WindowManagerConnection::Create(connector); +} + +bool TaskViewer::AcceptConnection(shell::Connection* connection) { + connection->AddInterface<mojom::Launchable>(this); + return true; +} + +void TaskViewer::Launch(uint32_t what, mojom::LaunchMode how) { + bool reuse = how == mojom::LaunchMode::REUSE || + how == mojom::LaunchMode::DEFAULT; + if (reuse && !windows_.empty()) { + windows_.back()->Activate(); + return; + } shell::mojom::ShellPtr shell; - connector->ConnectToInterface("mojo:shell", &shell); + connector_->ConnectToInterface("mojo:shell", &shell); shell::mojom::InstanceListenerPtr listener; shell::mojom::InstanceListenerRequest request = GetProxy(&listener); shell->AddInstanceListener(std::move(listener)); catalog::mojom::CatalogPtr catalog; - connector->ConnectToInterface("mojo:catalog", &catalog); + connector_->ConnectToInterface("mojo:catalog", &catalog); TaskViewerContents* task_viewer = new TaskViewerContents( - std::move(request), std::move(catalog)); + this, std::move(request), std::move(catalog)); views::Widget* window = views::Widget::CreateWindowWithContextAndBounds( task_viewer, nullptr, gfx::Rect(10, 10, 500, 500)); window->Show(); + windows_.push_back(window); +} + +void TaskViewer::Create(shell::Connection* connection, + mojom::LaunchableRequest request) { + bindings_.AddBinding(this, std::move(request)); } } // namespace task_viewer
diff --git a/mash/task_viewer/task_viewer.h b/mash/task_viewer/task_viewer.h index 4772f1b..372c293 100644 --- a/mash/task_viewer/task_viewer.h +++ b/mash/task_viewer/task_viewer.h
@@ -10,26 +10,45 @@ #include "base/callback.h" #include "base/macros.h" +#include "mash/public/interfaces/launchable.mojom.h" +#include "mojo/public/cpp/bindings/binding_set.h" #include "services/shell/public/cpp/shell_client.h" #include "services/tracing/public/cpp/tracing_impl.h" namespace views { class AuraInit; +class Widget; } namespace mash { namespace task_viewer { -class TaskViewer : public shell::ShellClient { +class TaskViewer : public shell::ShellClient, + public mojom::Launchable, + public shell::InterfaceFactory<mojom::Launchable> { public: TaskViewer(); ~TaskViewer() override; + void RemoveWindow(views::Widget* widget); + private: // shell::ShellClient: void Initialize(shell::Connector* connector, const shell::Identity& identity, uint32_t id) override; + bool AcceptConnection(shell::Connection* connection) override; + + // mojom::Launchable: + void Launch(uint32_t what, mojom::LaunchMode how) override; + + // shell::InterfaceFactory<mojom::Launchable>: + void Create(shell::Connection* connection, + mojom::LaunchableRequest request) override; + + shell::Connector* connector_ = nullptr; + mojo::BindingSet<mojom::Launchable> bindings_; + std::vector<views::Widget*> windows_; mojo::TracingImpl tracing_; std::unique_ptr<views::AuraInit> aura_init_;
diff --git a/mash/wm/manifest.json b/mash/wm/manifest.json index 367d263..46267f0 100644 --- a/mash/wm/manifest.json +++ b/mash/wm/manifest.json
@@ -1,5 +1,5 @@ { "name": "mojo:desktop_wm", - "display_name": "Desktop Window Manager", + "display_name": "Window Manager", "capabilities": { "*": ["*"] } }
diff --git a/media/base/android/media_codec_util.cc b/media/base/android/media_codec_util.cc index 0365aa36..6e00c57 100644 --- a/media/base/android/media_codec_util.cc +++ b/media/base/android/media_codec_util.cc
@@ -178,7 +178,8 @@ // static bool MediaCodecUtil::IsVp8DecoderAvailable() { - return IsMediaCodecAvailable() && IsDecoderSupportedByDevice("vp8"); + return IsMediaCodecAvailable() && + IsDecoderSupportedByDevice(CodecTypeToAndroidMimeType("vp8")); } // static @@ -190,7 +191,8 @@ // static bool MediaCodecUtil::IsVp9DecoderAvailable() { - return IsMediaCodecAvailable() && IsDecoderSupportedByDevice("vp9"); + return IsMediaCodecAvailable() && + IsDecoderSupportedByDevice(CodecTypeToAndroidMimeType("vp9")); } // static
diff --git a/media/base/demuxer.h b/media/base/demuxer.h index e2c68eb..027264b 100644 --- a/media/base/demuxer.h +++ b/media/base/demuxer.h
@@ -67,7 +67,7 @@ EncryptedMediaInitDataCB; // Notifies demuxer clients that media track configuration has been updated - // (e.g. the initial stream metadata has been parsed successfully, or a new + // (e.g. the inital stream metadata has been parsed successfully, or a new // init segment has been parsed successfully in MSE case). typedef base::Callback<void(scoped_ptr<MediaTracks>)> MediaTracksUpdatedCB; @@ -134,18 +134,6 @@ // Returns the memory usage in bytes for the demuxer. virtual int64_t GetMemoryUsage() const = 0; - // Notifies the demuxer that blink track ids have been assigned to |tracks|. - // The |track_ids| collection must contain blink track ids in the same - // sequence as media tracks in |tracks|. The collection sizes must be the - // same. - virtual void OnTrackIdsAssigned(const MediaTracks& tracks, - const std::vector<unsigned>& track_ids) = 0; - - // Finds a DemuxerStream corresponding to the given blink |track_id|. Note - // that the input track id is blink track id and not bytestream track id. - virtual const DemuxerStream* GetDemuxerStreamByTrackId( - unsigned track_id) const = 0; - private: DISALLOW_COPY_AND_ASSIGN(Demuxer); };
diff --git a/media/base/key_systems_unittest.cc b/media/base/key_systems_unittest.cc index 44b8819..619a5c9 100644 --- a/media/base/key_systems_unittest.cc +++ b/media/base/key_systems_unittest.cc
@@ -401,8 +401,10 @@ #if defined(ENABLE_PEPPER_CDMS) std::string type; - EXPECT_DEBUG_DEATH(type = GetPepperType(kUnrecognized), - "x-org.example.unrecognized is not a known system"); +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) + EXPECT_DEATH(type = GetPepperType(kUnrecognized), + "x-org.example.unrecognized is not a known system"); +#endif EXPECT_TRUE(type.empty()); #endif } @@ -418,8 +420,10 @@ EXPECT_TRUE(CanUseAesDecryptor(kUsesAes)); #if defined(ENABLE_PEPPER_CDMS) std::string type; - EXPECT_DEBUG_DEATH(type = GetPepperType(kUsesAes), - "x-org.example.clear is not Pepper-based"); +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) + EXPECT_DEATH(type = GetPepperType(kUsesAes), + "x-org.example.clear is not Pepper-based"); +#endif EXPECT_TRUE(type.empty()); #endif }
diff --git a/media/base/media_tracks.cc b/media/base/media_tracks.cc index 070e8c7..832e5a8 100644 --- a/media/base/media_tracks.cc +++ b/media/base/media_tracks.cc
@@ -14,66 +14,30 @@ MediaTracks::~MediaTracks() {} -const MediaTrack* MediaTracks::AddAudioTrack(const AudioDecoderConfig& config, - const std::string& id, - const std::string& kind, - const std::string& label, - const std::string& language) { +void MediaTracks::AddAudioTrack(const AudioDecoderConfig& config, + const std::string& id, + const std::string& kind, + const std::string& label, + const std::string& language) { DCHECK(config.IsValidConfig()); CHECK(audio_configs_.find(id) == audio_configs_.end()); scoped_ptr<MediaTrack> track = make_scoped_ptr( new MediaTrack(MediaTrack::Audio, id, kind, label, language)); tracks_.push_back(std::move(track)); audio_configs_[id] = config; - return tracks_.back().get(); } -const MediaTrack* MediaTracks::AddVideoTrack(const VideoDecoderConfig& config, - const std::string& id, - const std::string& kind, - const std::string& label, - const std::string& language) { +void MediaTracks::AddVideoTrack(const VideoDecoderConfig& config, + const std::string& id, + const std::string& kind, + const std::string& label, + const std::string& language) { DCHECK(config.IsValidConfig()); CHECK(video_configs_.find(id) == video_configs_.end()); scoped_ptr<MediaTrack> track = make_scoped_ptr( new MediaTrack(MediaTrack::Video, id, kind, label, language)); tracks_.push_back(std::move(track)); video_configs_[id] = config; - return tracks_.back().get(); -} - -void MediaTracks::SetDemuxerStreamForMediaTrack(const MediaTrack* track, - const DemuxerStream* stream) { - DCHECK(track_to_demux_stream_map_.find(track) == - track_to_demux_stream_map_.end()); - - bool track_found = false; - for (const auto& t : tracks_) { - if (t.get() == track) { - track_found = true; - break; - } - } - CHECK(track_found); - - track_to_demux_stream_map_[track] = stream; -} - -MediaTracks::TrackIdToDemuxStreamMap MediaTracks::OnTrackIdsAssigned( - const std::vector<unsigned>& track_ids) const { - TrackIdToDemuxStreamMap result; - CHECK_EQ(tracks().size(), track_ids.size()); - CHECK_EQ(track_to_demux_stream_map_.size(), tracks().size()); - for (size_t i = 0; i < track_ids.size(); ++i) { - const MediaTrack* track = tracks()[i].get(); - DCHECK(track); - const auto& it = track_to_demux_stream_map_.find(track); - CHECK(it != track_to_demux_stream_map_.end()); - DVLOG(3) << "OnTrackIdsAssigned track_id=" << track_ids[i] - << " DemuxerStream=" << it->second; - result[track_ids[i]] = it->second; - } - return result; } const AudioDecoderConfig& MediaTracks::getAudioConfig(
diff --git a/media/base/media_tracks.h b/media/base/media_tracks.h index b45f81d..4e0fbb0f 100644 --- a/media/base/media_tracks.h +++ b/media/base/media_tracks.h
@@ -17,47 +17,30 @@ namespace media { class AudioDecoderConfig; -class DemuxerStream; class VideoDecoderConfig; class MEDIA_EXPORT MediaTracks { public: typedef std::vector<scoped_ptr<MediaTrack>> MediaTracksCollection; - typedef std::map<unsigned, const DemuxerStream*> TrackIdToDemuxStreamMap; MediaTracks(); ~MediaTracks(); // Callers need to ensure that track id is unique. - const MediaTrack* AddAudioTrack(const AudioDecoderConfig& config, - const std::string& id, - const std::string& kind, - const std::string& label, - const std::string& language); + void AddAudioTrack(const AudioDecoderConfig& config, + const std::string& id, + const std::string& kind, + const std::string& label, + const std::string& language); // Callers need to ensure that track id is unique. - const MediaTrack* AddVideoTrack(const VideoDecoderConfig& config, - const std::string& id, - const std::string& kind, - const std::string& label, - const std::string& language); + void AddVideoTrack(const VideoDecoderConfig& config, + const std::string& id, + const std::string& kind, + const std::string& label, + const std::string& language); const MediaTracksCollection& tracks() const { return tracks_; } - // TODO(servolk,wolenetz): Consider refactoring media track creation in MSE to - // simplify track id to DemuxerStream mapping. crbug.com/604088 - - // Notifies MediaTracks that a given media |track| object is backed by the - // given DemuxerStream |stream| object. - void SetDemuxerStreamForMediaTrack(const MediaTrack* track, - const DemuxerStream* stream); - // Notifies MediaTracks that external (blink) track ids have been assigned to - // the media |tracks_|. The size and ordering of |track_ids| must match the - // size and ordering of tracks in the |tracks_| collection, and - // |track_to_demux_stream_map_| must have an entry for each track in |tracks_| - // (set by SetDemuxerStreamForMediaTrack()). - TrackIdToDemuxStreamMap OnTrackIdsAssigned( - const std::vector<unsigned>& track_ids) const; - const AudioDecoderConfig& getAudioConfig(const std::string& id) const; const VideoDecoderConfig& getVideoConfig(const std::string& id) const; @@ -71,10 +54,6 @@ std::map<std::string, AudioDecoderConfig> audio_configs_; std::map<std::string, VideoDecoderConfig> video_configs_; - typedef std::map<const MediaTrack*, const DemuxerStream*> - TrackToDemuxStreamMap; - TrackToDemuxStreamMap track_to_demux_stream_map_; - DISALLOW_COPY_AND_ASSIGN(MediaTracks); };
diff --git a/media/base/mock_filters.h b/media/base/mock_filters.h index d1c150a1..f60c9cd 100644 --- a/media/base/mock_filters.h +++ b/media/base/mock_filters.h
@@ -18,7 +18,6 @@ #include "media/base/decoder_buffer.h" #include "media/base/decryptor.h" #include "media/base/demuxer.h" -#include "media/base/media_tracks.h" #include "media/base/pipeline.h" #include "media/base/pipeline_status.h" #include "media/base/renderer.h" @@ -116,10 +115,6 @@ MOCK_CONST_METHOD0(GetTimelineOffset, base::Time()); MOCK_CONST_METHOD0(GetMemoryUsage, int64_t()); - MOCK_METHOD2(OnTrackIdsAssigned, - void(const MediaTracks&, const std::vector<unsigned>&)); - MOCK_CONST_METHOD1(GetDemuxerStreamByTrackId, const DemuxerStream*(unsigned)); - private: DISALLOW_COPY_AND_ASSIGN(MockDemuxer); };
diff --git a/media/base/pipeline.h b/media/base/pipeline.h index 07e197b..db326c2 100644 --- a/media/base/pipeline.h +++ b/media/base/pipeline.h
@@ -19,7 +19,6 @@ namespace media { class Demuxer; -class DemuxerStream; class Renderer; class VideoFrame; @@ -156,15 +155,6 @@ virtual void SetCdm(CdmContext* cdm_context, const CdmAttachedCB& cdm_attached_cb) = 0; - - // Notifies pipeline that the set of enabled audio streams/tracks has changed. - virtual void OnEnabledAudioStreamsChanged( - const std::vector<const DemuxerStream*>& enabledAudioStreams) {} - - // Notifies pipeline that the selected video stream has changed. The input - // parameter |selectedVideoStream| can be null, which means video is disabled. - virtual void OnSelectedVideoStreamChanged( - const DemuxerStream* selectedVideoStream) {} }; } // namespace media
diff --git a/media/base/pipeline_impl.cc b/media/base/pipeline_impl.cc index 7971a2a..5f4705b5 100644 --- a/media/base/pipeline_impl.cc +++ b/media/base/pipeline_impl.cc
@@ -204,36 +204,6 @@ cdm_attached_cb)); } -void PipelineImpl::OnEnabledAudioStreamsChanged( - const std::vector<const DemuxerStream*>& enabledAudioStreams) { - if (!task_runner_->BelongsToCurrentThread()) { - task_runner_->PostTask( - FROM_HERE, base::Bind(&PipelineImpl::OnEnabledAudioStreamsChanged, - weak_factory_.GetWeakPtr(), enabledAudioStreams)); - return; - } - base::AutoLock auto_lock(lock_); - DCHECK(task_runner_->BelongsToCurrentThread()); - if (renderer_) { - renderer_->OnEnabledAudioStreamsChanged(enabledAudioStreams); - } -} - -void PipelineImpl::OnSelectedVideoStreamChanged( - const DemuxerStream* selectedVideoStream) { - if (!task_runner_->BelongsToCurrentThread()) { - task_runner_->PostTask( - FROM_HERE, base::Bind(&PipelineImpl::OnSelectedVideoStreamChanged, - weak_factory_.GetWeakPtr(), selectedVideoStream)); - return; - } - base::AutoLock auto_lock(lock_); - DCHECK(task_runner_->BelongsToCurrentThread()); - if (renderer_) { - renderer_->OnSelectedVideoStreamChanged(selectedVideoStream); - } -} - void PipelineImpl::SetErrorForTesting(PipelineStatus status) { OnError(status); }
diff --git a/media/base/pipeline_impl.h b/media/base/pipeline_impl.h index a26b224..7a6da3a7 100644 --- a/media/base/pipeline_impl.h +++ b/media/base/pipeline_impl.h
@@ -111,10 +111,6 @@ PipelineStatistics GetStatistics() const override; void SetCdm(CdmContext* cdm_context, const CdmAttachedCB& cdm_attached_cb) override; - void OnEnabledAudioStreamsChanged( - const std::vector<const DemuxerStream*>& enabledAudioStreams) override; - void OnSelectedVideoStreamChanged( - const DemuxerStream* selectedVideoStream) override; private: friend class MediaLog;
diff --git a/media/base/renderer.h b/media/base/renderer.h index bedbb34..89e349a9 100644 --- a/media/base/renderer.h +++ b/media/base/renderer.h
@@ -5,8 +5,6 @@ #ifndef MEDIA_BASE_RENDERER_H_ #define MEDIA_BASE_RENDERER_H_ -#include <vector> - #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" @@ -18,7 +16,6 @@ namespace media { -class DemuxerStream; class DemuxerStreamProvider; class VideoFrame; @@ -80,22 +77,6 @@ // Returns whether |this| renders video. virtual bool HasVideo() = 0; - // TODO(servolk,wolenetz): Enable media track handling in mojo, then make sure - // OnEnabledAudioStreamsChanged and OnSelectedVideoStreamChanged are - // implemented by all media renderers and make them pure virtual here. - // crbug.com/604083 - - // Notifies renderer that the set of enabled audio streams/tracks has changed. - // The input parameter |enabledAudioStreams| might be empty, which means that - // all audio tracks should be disabled/muted. - virtual void OnEnabledAudioStreamsChanged( - const std::vector<const DemuxerStream*>& enabledAudioStreams) {} - - // Notifies renderer that the selected video stream has changed. The input - // parameter |selectedVideoStream| can be null, which means video is disabled. - virtual void OnSelectedVideoStreamChanged( - const DemuxerStream* selectedVideoStream) {} - private: DISALLOW_COPY_AND_ASSIGN(Renderer); };
diff --git a/media/blink/webmediaplayer_impl.cc b/media/blink/webmediaplayer_impl.cc index f26a75b1..d1f5f2e 100644 --- a/media/blink/webmediaplayer_impl.cc +++ b/media/blink/webmediaplayer_impl.cc
@@ -7,7 +7,6 @@ #include <algorithm> #include <cmath> #include <limits> -#include <sstream> #include <string> #include <utility> @@ -564,45 +563,6 @@ return pipeline_metadata_.has_audio; } -void WebMediaPlayerImpl::enabledAudioTracksChanged( - const blink::WebVector<blink::WebMediaPlayer::TrackId>& enabledTrackIds) { - DCHECK(main_task_runner_->BelongsToCurrentThread()); - CHECK(demuxer_.get()); - - std::vector<const DemuxerStream*> enabledAudioStreams; - std::stringstream trackIdsStr; - for (const auto& trackId : enabledTrackIds) { - const DemuxerStream* s = demuxer_->GetDemuxerStreamByTrackId(trackId); - CHECK(s); - enabledAudioStreams.push_back(s); - trackIdsStr << trackId << " "; - } - MEDIA_LOG(INFO, media_log_) - << "WebMediaPlayerImpl::enabledAudioTracksChanged enabledTrackIds=" - << trackIdsStr.str(); - pipeline_.OnEnabledAudioStreamsChanged(enabledAudioStreams); -} - -void WebMediaPlayerImpl::selectedVideoTrackChanged( - blink::WebMediaPlayer::TrackId* selectedTrackId) { - DCHECK(main_task_runner_->BelongsToCurrentThread()); - CHECK(demuxer_.get()); - - const DemuxerStream* selectedVideoStream = nullptr; - if (selectedTrackId) { - selectedVideoStream = demuxer_->GetDemuxerStreamByTrackId(*selectedTrackId); - CHECK(selectedVideoStream); - MEDIA_LOG(INFO, media_log_) - << "WebMediaPlayerImpl::selectedVideoTrackChanged selectedTrackId=" - << *selectedTrackId << " selectedVideoStream=" << selectedVideoStream; - } else { - MEDIA_LOG(INFO, media_log_) << "WebMediaPlayerImpl::" - "selectedVideoTrackChanged " - "selectedTrackId=none"; - } - pipeline_.OnSelectedVideoStreamChanged(selectedVideoStream); -} - blink::WebSize WebMediaPlayerImpl::naturalSize() const { DCHECK(main_task_runner_->BelongsToCurrentThread()); @@ -866,7 +826,6 @@ DCHECK(!chunk_demuxer_); // Report the media track information to blink. - std::vector<blink::WebMediaPlayer::TrackId> blinkTrackIds; for (const auto& track : tracks->tracks()) { if (track->type() == MediaTrack::Audio) { auto track_id = client_->addAudioTrack( @@ -875,7 +834,7 @@ blink::WebString::fromUTF8(track->label()), blink::WebString::fromUTF8(track->language()), /*enabled*/ true); - blinkTrackIds.push_back(track_id); + (void)track_id; } else if (track->type() == MediaTrack::Video) { auto track_id = client_->addVideoTrack( blink::WebString::fromUTF8(track->id()), @@ -883,14 +842,12 @@ blink::WebString::fromUTF8(track->label()), blink::WebString::fromUTF8(track->language()), /*selected*/ true); - blinkTrackIds.push_back(track_id); + (void)track_id; } else { // Text tracks are not supported through this code path yet. NOTREACHED(); } } - - demuxer_->OnTrackIdsAssigned(*tracks.get(), blinkTrackIds); } void WebMediaPlayerImpl::OnWaitingForDecryptionKey() {
diff --git a/media/blink/webmediaplayer_impl.h b/media/blink/webmediaplayer_impl.h index abca43c62..59b021f 100644 --- a/media/blink/webmediaplayer_impl.h +++ b/media/blink/webmediaplayer_impl.h
@@ -127,13 +127,6 @@ bool hasVideo() const override; bool hasAudio() const override; - void enabledAudioTracksChanged( - const blink::WebVector<blink::WebMediaPlayer::TrackId>& enabledTrackIds) - override; - // |selectedTrackId| is null if no track is selected. - void selectedVideoTrackChanged( - blink::WebMediaPlayer::TrackId* selectedTrackId) override; - // Dimensions of the video. blink::WebSize naturalSize() const override;
diff --git a/media/blink/websourcebuffer_impl.cc b/media/blink/websourcebuffer_impl.cc index fffc4b1..9386f52 100644 --- a/media/blink/websourcebuffer_impl.cc +++ b/media/blink/websourcebuffer_impl.cc
@@ -189,8 +189,6 @@ std::vector<blink::WebMediaPlayer::TrackId> blinkTrackIds = client_->initializationSegmentReceived(trackInfoVector); - - demuxer_->OnTrackIdsAssigned(*tracks.get(), blinkTrackIds); } } // namespace media
diff --git a/media/cast/test/utility/net_utility.cc b/media/cast/test/utility/net_utility.cc index 3fcc747..d3204c0 100644 --- a/media/cast/test/utility/net_utility.cc +++ b/media/cast/test/utility/net_utility.cc
@@ -4,6 +4,7 @@ #include "media/cast/test/utility/net_utility.h" +#include "base/memory/scoped_ptr.h" #include "net/base/ip_address.h" #include "net/base/net_errors.h" #include "net/udp/udp_server_socket.h"
diff --git a/media/filters/chunk_demuxer.cc b/media/filters/chunk_demuxer.cc index fc5c073..554c9cfd7 100644 --- a/media/filters/chunk_demuxer.cc +++ b/media/filters/chunk_demuxer.cc
@@ -17,7 +17,6 @@ #include "base/stl_util.h" #include "media/base/audio_decoder_config.h" #include "media/base/bind_to_current_loop.h" -#include "media/base/media_tracks.h" #include "media/base/stream_parser_buffer.h" #include "media/base/timestamp_constants.h" #include "media/base/video_decoder_config.h" @@ -1004,30 +1003,31 @@ } ChunkDemuxerStream* ChunkDemuxer::CreateDemuxerStream( - const MediaTrack& media_track) { - // Demuxer streams can only be created when ChunkDemuxer::AppendData is in - // progress. - lock_.AssertAcquired(); - switch (media_track.type()) { - case MediaTrack::Audio: + DemuxerStream::Type type) { + switch (type) { + case DemuxerStream::AUDIO: if (audio_) return NULL; audio_.reset( new ChunkDemuxerStream(DemuxerStream::AUDIO, splice_frames_enabled_)); return audio_.get(); break; - case MediaTrack::Video: + case DemuxerStream::VIDEO: if (video_) return NULL; video_.reset( new ChunkDemuxerStream(DemuxerStream::VIDEO, splice_frames_enabled_)); return video_.get(); break; - case MediaTrack::Text: { + case DemuxerStream::TEXT: { return new ChunkDemuxerStream(DemuxerStream::TEXT, splice_frames_enabled_); break; } + case DemuxerStream::UNKNOWN: + case DemuxerStream::NUM_TYPES: + NOTREACHED(); + return NULL; } NOTREACHED(); return NULL; @@ -1040,31 +1040,6 @@ host_->AddTextStream(text_stream, config); } -void ChunkDemuxer::OnTrackIdsAssigned(const MediaTracks& tracks, - const std::vector<unsigned>& track_ids) { - // New tracks and therefore track id assignements can happen only during - // ChunkDemuxer::AppendData processing, which should be holding the lock. - lock_.AssertAcquired(); - - const auto& new_track_id_map = tracks.OnTrackIdsAssigned(track_ids); - - // ChunkDemuxer might have multiple media track sets (since it can have - // multiple SourceBuffers), so we need to merge the map for the current set of - // tracks with the global |track_id_to_demux_stream_| map shared across all - // SourceBuffers. - for (const auto& it : new_track_id_map) { - track_id_to_demux_stream_[it.first] = it.second; - } -} - -const DemuxerStream* ChunkDemuxer::GetDemuxerStreamByTrackId( - unsigned track_id) const { - base::AutoLock auto_lock(lock_); - const auto& it = track_id_to_demux_stream_.find(track_id); - CHECK(it != track_id_to_demux_stream_.end()); - return it->second; -} - bool ChunkDemuxer::IsValidId(const std::string& source_id) const { lock_.AssertAcquired(); return source_state_map_.count(source_id) > 0u;
diff --git a/media/filters/chunk_demuxer.h b/media/filters/chunk_demuxer.h index bd08a8e2..969afb22 100644 --- a/media/filters/chunk_demuxer.h +++ b/media/filters/chunk_demuxer.h
@@ -19,7 +19,6 @@ #include "media/base/byte_queue.h" #include "media/base/demuxer.h" #include "media/base/demuxer_stream.h" -#include "media/base/media_tracks.h" #include "media/base/ranges.h" #include "media/base/stream_parser.h" #include "media/filters/media_source_state.h" @@ -209,15 +208,6 @@ void SetTracksWatcher(const std::string& id, const MediaTracksUpdatedCB& tracks_updated_cb); - // Notifies the demuxer that track ids has been assigned to a media tracks. - void OnTrackIdsAssigned(const MediaTracks& tracks, - const std::vector<unsigned>& track_ids) override; - - // Finds a DemuxerStream corresponding to the given blink |track_id|. Note - // that the input track id is blink track id and not bytestream track id. - const DemuxerStream* GetDemuxerStreamByTrackId( - unsigned track_id) const override; - // Removed an ID & associated resources that were previously added with // AddId(). void RemoveId(const std::string& id); @@ -328,10 +318,10 @@ // MediaSourceState callbacks. void OnSourceInitDone(const StreamParser::InitParameters& params); - // Creates a DemuxerStream for the specified |media_track|. + // Creates a DemuxerStream for the specified |type|. // Returns a new ChunkDemuxerStream instance if a stream of this type // has not been created before. Returns NULL otherwise. - ChunkDemuxerStream* CreateDemuxerStream(const MediaTrack& media_track); + ChunkDemuxerStream* CreateDemuxerStream(DemuxerStream::Type type); void OnNewTextTrack(ChunkDemuxerStream* text_stream, const TextTrackConfig& config); @@ -395,8 +385,6 @@ // Incremented in AddId(), decremented in OnSourceInitDone(). int pending_source_init_done_count_; - MediaTracks::TrackIdToDemuxStreamMap track_id_to_demux_stream_; - base::TimeDelta duration_; // The duration passed to the last SetDuration(). If
diff --git a/media/filters/chunk_demuxer_unittest.cc b/media/filters/chunk_demuxer_unittest.cc index bb783783..a6828da 100644 --- a/media/filters/chunk_demuxer_unittest.cc +++ b/media/filters/chunk_demuxer_unittest.cc
@@ -82,8 +82,6 @@ const int kVideoTrackEntryHeaderSize = kVideoTrackSizeOffset + kVideoTrackSizeWidth; -// Track numbers AKA bytestream track ids. Bytestream track ids might change -// within a single playback session if there is only one track of a given type. const int kVideoTrackNum = 1; const int kAudioTrackNum = 2; const int kTextTrackNum = 3; @@ -91,14 +89,6 @@ const int kAlternateAudioTrackNum = 5; const int kAlternateTextTrackNum = 6; -// These value represent externally assigned track ids (for example track ids -// assigned by blink). Not to be confused with bytestream track ids above. The -// main difference is that these track ids must stay the same for the duration -// of the playback session, whereas track numbers / bytestream track ids might -// change in subsequent init segments. -const int kVideoTrackId = 10; -const int kAudioTrackId = 11; - const int kAudioBlockDuration = 23; const int kVideoBlockDuration = 33; const int kTextBlockDuration = 100; @@ -1410,18 +1400,6 @@ DCHECK(tracks.get()); DCHECK_GT(tracks->tracks().size(), 0u); - std::vector<unsigned> track_ids; - for (const auto& track : tracks->tracks()) { - if (track->type() == MediaTrack::Audio) { - track_ids.push_back(kAudioTrackId); - } else if (track->type() == MediaTrack::Video) { - track_ids.push_back(kVideoTrackId); - } else { - NOTREACHED(); - } - } - demuxer_->OnTrackIdsAssigned(*tracks.get(), track_ids); - InitSegmentReceivedMock(tracks); } @@ -1621,8 +1599,6 @@ DemuxerStream* video_stream = demuxer_->GetStream(DemuxerStream::VIDEO); ASSERT_TRUE(audio_stream); ASSERT_TRUE(video_stream); - ASSERT_EQ(audio_stream, demuxer_->GetDemuxerStreamByTrackId(kAudioTrackId)); - ASSERT_EQ(video_stream, demuxer_->GetDemuxerStreamByTrackId(kVideoTrackId)); AppendMuxedCluster(MuxedStreamInfo(kAudioTrackNum, "0K 23K", 23), MuxedStreamInfo(kVideoTrackNum, "0K 30", 30)); @@ -1636,8 +1612,6 @@ CheckExpectedRanges("{ [0,92) }"); CheckExpectedBuffers(audio_stream, "0K 23K 46K 69K"); CheckExpectedBuffers(video_stream, "0K 30 60K"); - ASSERT_EQ(audio_stream, demuxer_->GetDemuxerStreamByTrackId(kAudioTrackId)); - ASSERT_EQ(video_stream, demuxer_->GetDemuxerStreamByTrackId(kVideoTrackId)); ShutdownDemuxer(); }
diff --git a/media/filters/ffmpeg_demuxer.cc b/media/filters/ffmpeg_demuxer.cc index c3d8525e..c7e00ce5 100644 --- a/media/filters/ffmpeg_demuxer.cc +++ b/media/filters/ffmpeg_demuxer.cc
@@ -1221,25 +1221,22 @@ // Note when we find our audio/video stream (we only want one of each) and // record src= playback UMA stats for the stream's decoder config. - const MediaTrack* media_track = nullptr; if (codec_type == AVMEDIA_TYPE_AUDIO) { CHECK(!audio_stream); audio_stream = stream; audio_config = streams_[i]->audio_decoder_config(); RecordAudioCodecStats(audio_config); - media_track = media_tracks->AddAudioTrack(audio_config, track_id, "main", - track_label, track_language); - media_tracks->SetDemuxerStreamForMediaTrack(media_track, streams_[i]); + media_tracks->AddAudioTrack(audio_config, track_id, "main", track_label, + track_language); } else if (codec_type == AVMEDIA_TYPE_VIDEO) { CHECK(!video_stream); video_stream = stream; video_config = streams_[i]->video_decoder_config(); RecordVideoCodecStats(video_config, stream->codec->color_range); - media_track = media_tracks->AddVideoTrack(video_config, track_id, "main", - track_label, track_language); - media_tracks->SetDemuxerStreamForMediaTrack(media_track, streams_[i]); + media_tracks->AddVideoTrack(video_config, track_id, "main", track_label, + track_language); } max_duration = std::max(max_duration, streams_[i]->duration()); @@ -1598,16 +1595,4 @@ } } -void FFmpegDemuxer::OnTrackIdsAssigned(const MediaTracks& tracks, - const std::vector<unsigned>& track_ids) { - track_id_to_demux_stream_ = tracks.OnTrackIdsAssigned(track_ids); -} - -const DemuxerStream* FFmpegDemuxer::GetDemuxerStreamByTrackId( - unsigned track_id) const { - const auto& it = track_id_to_demux_stream_.find(track_id); - CHECK(it != track_id_to_demux_stream_.end()); - return it->second; -} - } // namespace media
diff --git a/media/filters/ffmpeg_demuxer.h b/media/filters/ffmpeg_demuxer.h index 73aded71..b89196d 100644 --- a/media/filters/ffmpeg_demuxer.h +++ b/media/filters/ffmpeg_demuxer.h
@@ -25,7 +25,6 @@ #include <stddef.h> #include <stdint.h> -#include <map> #include <string> #include <utility> #include <vector> @@ -39,7 +38,6 @@ #include "media/base/decoder_buffer.h" #include "media/base/decoder_buffer_queue.h" #include "media/base/demuxer.h" -#include "media/base/media_tracks.h" #include "media/base/pipeline_status.h" #include "media/base/text_track_config.h" #include "media/base/video_decoder_config.h" @@ -225,15 +223,6 @@ // timeline. base::TimeDelta start_time() const { return start_time_; } - // Notifies the demuxer that track ids has been assigned to a media tracks. - void OnTrackIdsAssigned(const MediaTracks& tracks, - const std::vector<unsigned>& track_ids) override; - - // Finds a DemuxerStream corresponding to the given blink |track_id|. Note - // that the input track id is blink track id and not bytestream track id. - const DemuxerStream* GetDemuxerStreamByTrackId( - unsigned track_id) const override; - private: // To allow tests access to privates. friend class FFmpegDemuxerTest; @@ -345,8 +334,6 @@ const MediaTracksUpdatedCB media_tracks_updated_cb_; - MediaTracks::TrackIdToDemuxStreamMap track_id_to_demux_stream_; - // NOTE: Weak pointers must be invalidated before all other member variables. base::WeakPtrFactory<FFmpegDemuxer> weak_factory_;
diff --git a/media/filters/media_source_state.cc b/media/filters/media_source_state.cc index d59011d6..98028b4 100644 --- a/media/filters/media_source_state.cc +++ b/media/filters/media_source_state.cc
@@ -480,22 +480,9 @@ const StreamParser::TextTrackConfigMap& text_configs) { DCHECK_GE(state_, PENDING_PARSER_CONFIG); DCHECK(tracks.get()); - - const MediaTrack* audio_track = nullptr; - const MediaTrack* video_track = nullptr; - AudioDecoderConfig audio_config; - VideoDecoderConfig video_config; - for (const auto& track : tracks->tracks()) { - if (!audio_track && track->type() == MediaTrack::Audio && - tracks->getAudioConfig(track->id()).IsValidConfig()) { - audio_config = tracks->getAudioConfig(track->id()); - audio_track = track.get(); - } else if (!video_track && track->type() == MediaTrack::Video && - tracks->getVideoConfig(track->id()).IsValidConfig()) { - video_config = tracks->getVideoConfig(track->id()); - video_track = track.get(); - } - } + media_tracks_ = std::move(tracks); + const AudioDecoderConfig& audio_config = media_tracks_->getFirstAudioConfig(); + const VideoDecoderConfig& video_config = media_tracks_->getFirstVideoConfig(); DVLOG(1) << "OnNewConfigs(" << allow_audio << ", " << allow_video << ", " << audio_config.IsValidConfig() << ", " @@ -543,8 +530,7 @@ } if (!audio_) { - DCHECK(audio_track); - audio_ = create_demuxer_stream_cb_.Run(*audio_track); + audio_ = create_demuxer_stream_cb_.Run(DemuxerStream::AUDIO); if (!audio_) { DVLOG(1) << "Failed to create an audio stream."; @@ -572,8 +558,7 @@ } if (!video_) { - DCHECK(video_track); - video_ = create_demuxer_stream_cb_.Run(*video_track); + video_ = create_demuxer_stream_cb_.Run(DemuxerStream::VIDEO); if (!video_) { DVLOG(1) << "Failed to create a video stream."; @@ -593,11 +578,8 @@ if (text_stream_map_.empty()) { for (TextConfigItr itr = text_configs.begin(); itr != text_configs.end(); ++itr) { - // TODO(servolk): Look into unifying text tracks code path with audio and - // video track code paths. - MediaTrack dummy_text_track(MediaTrack::Text, "", "", "", ""); ChunkDemuxerStream* const text_stream = - create_demuxer_stream_cb_.Run(dummy_text_track); + create_demuxer_stream_cb_.Run(DemuxerStream::TEXT); if (!frame_processor_->AddTrack(itr->first, text_stream)) { success &= false; MEDIA_LOG(ERROR, media_log_) << "Failed to add text track ID " @@ -669,21 +651,12 @@ frame_processor_->SetAllTrackBuffersNeedRandomAccessPoint(); - if (audio_track) { - DCHECK(audio_); - tracks->SetDemuxerStreamForMediaTrack(audio_track, audio_); - } - if (video_track) { - DCHECK(video_); - tracks->SetDemuxerStreamForMediaTrack(video_track, video_); - } - DVLOG(1) << "OnNewConfigs() : " << (success ? "success" : "failed"); if (success) { if (state_ == PENDING_PARSER_CONFIG) state_ = PENDING_PARSER_INIT; DCHECK(!init_segment_received_cb_.is_null()); - init_segment_received_cb_.Run(std::move(tracks)); + init_segment_received_cb_.Run(std::move(media_tracks_)); } return success;
diff --git a/media/filters/media_source_state.h b/media/filters/media_source_state.h index 616cd44..89974a6b 100644 --- a/media/filters/media_source_state.h +++ b/media/filters/media_source_state.h
@@ -20,13 +20,12 @@ class ChunkDemuxerStream; class FrameProcessor; -class MediaTrack; // Contains state belonging to a source id. class MEDIA_EXPORT MediaSourceState { public: // Callback signature used to create ChunkDemuxerStreams. - typedef base::Callback<ChunkDemuxerStream*(const MediaTrack&)> + typedef base::Callback<ChunkDemuxerStream*(DemuxerStream::Type)> CreateDemuxerStreamCB; typedef base::Callback<void(ChunkDemuxerStream*, const TextTrackConfig&)> @@ -191,6 +190,8 @@ // The object used to parse appended data. scoped_ptr<StreamParser> stream_parser_; + scoped_ptr<MediaTracks> media_tracks_; + ChunkDemuxerStream* audio_; // Not owned by |this|. ChunkDemuxerStream* video_; // Not owned by |this|.
diff --git a/media/renderers/renderer_impl.cc b/media/renderers/renderer_impl.cc index 26ea9384..38f49d4 100644 --- a/media/renderers/renderer_impl.cc +++ b/media/renderers/renderer_impl.cc
@@ -205,16 +205,8 @@ DVLOG(1) << __FUNCTION__; DCHECK(task_runner_->BelongsToCurrentThread()); - audio_volume_ = volume; - if (!audio_renderer_) - return; - - if (audio_stream_currently_disabled_) { - DVLOG(1) << "SetVolume ignored since audio stream is currently disabled."; - return; - } - - audio_renderer_->SetVolume(volume); + if (audio_renderer_) + audio_renderer_->SetVolume(volume); } base::TimeDelta RendererImpl::GetMediaTime() { @@ -233,52 +225,6 @@ return video_renderer_ != NULL; } -void RendererImpl::OnEnabledAudioStreamsChanged( - const std::vector<const DemuxerStream*>& enabledAudioStreams) { - DCHECK(task_runner_->BelongsToCurrentThread()); - DemuxerStream* audio_stream = - demuxer_stream_provider_->GetStream(DemuxerStream::AUDIO); - - bool audio_stream_enabled = false; - for (const DemuxerStream* demuxer_stream : enabledAudioStreams) { - DCHECK_EQ(demuxer_stream->type(), DemuxerStream::AUDIO); - DCHECK_EQ(demuxer_stream, audio_stream); - audio_stream_enabled = true; - } - - // TODO(servolk,wolenetz): Need to find a way to completely disable audio - // (i.e. stop audio decoder and switch video to wall clock) when audio stream - // is disabled, but for now just set volume to 0. crbug.com/599709 - if (audio_renderer_) { - if (audio_stream_enabled && audio_stream_currently_disabled_) { - DVLOG(3) << __FUNCTION__ << " enabled audio. SetVolume=" << audio_volume_; - audio_stream_currently_disabled_ = false; - audio_renderer_->SetVolume(audio_volume_); - } else if (!audio_stream_enabled) { - DVLOG(3) << __FUNCTION__ << " disabled audio. SetVolume=0"; - DCHECK(!audio_stream_currently_disabled_); - audio_stream_currently_disabled_ = true; - audio_renderer_->SetVolume(0); - } - } -} - -void RendererImpl::OnSelectedVideoStreamChanged( - const DemuxerStream* selectedVideoStream) { - DCHECK(task_runner_->BelongsToCurrentThread()); - DemuxerStream* video_stream = - demuxer_stream_provider_->GetStream(DemuxerStream::VIDEO); - if (selectedVideoStream) { - DVLOG(3) << __FUNCTION__ << " selectedVideoStream=" << selectedVideoStream; - DCHECK_EQ(selectedVideoStream->type(), DemuxerStream::VIDEO); - CHECK_EQ(selectedVideoStream, video_stream); - } else { - DVLOG(3) << __FUNCTION__ << " selectedVideoStream=none"; - // TODO(servolk,wolenetz): Need to find a way to stop video decoding and - // rendering when the video stream is deselected. crbug.com/599709 - } -} - void RendererImpl::DisableUnderflowForTesting() { DVLOG(1) << __FUNCTION__; DCHECK(task_runner_->BelongsToCurrentThread());
diff --git a/media/renderers/renderer_impl.h b/media/renderers/renderer_impl.h index 6345ecf..fc17f6c 100644 --- a/media/renderers/renderer_impl.h +++ b/media/renderers/renderer_impl.h
@@ -63,10 +63,6 @@ base::TimeDelta GetMediaTime() final; bool HasAudio() final; bool HasVideo() final; - void OnEnabledAudioStreamsChanged( - const std::vector<const DemuxerStream*>& enabledAudioStreams) final; - void OnSelectedVideoStreamChanged( - const DemuxerStream* selectedVideoStream) final; // Helper functions for testing purposes. Must be called before Initialize(). void DisableUnderflowForTesting(); @@ -155,9 +151,6 @@ scoped_ptr<AudioRenderer> audio_renderer_; scoped_ptr<VideoRenderer> video_renderer_; - bool audio_stream_currently_disabled_ = false; - float audio_volume_ = 1.0f; - // Renderer-provided time source used to control playback. TimeSource* time_source_; scoped_ptr<WallClockTimeSource> wall_clock_time_source_;
diff --git a/media/test/pipeline_integration_test.cc b/media/test/pipeline_integration_test.cc index 1748fc38..5411600 100644 --- a/media/test/pipeline_integration_test.cc +++ b/media/test/pipeline_integration_test.cc
@@ -617,7 +617,7 @@ CHECK_EQ(chunk_demuxer_->AddId(kSourceId, type, codecs), ChunkDemuxer::kOk); chunk_demuxer_->SetTracksWatcher( - kSourceId, base::Bind(&MockMediaSource::InitSegmentReceived, + kSourceId, base::Bind(&MockMediaSource::InitSegmentReceivedWrapper, base::Unretained(this))); AppendData(initial_append_size_); @@ -634,21 +634,12 @@ return last_timestamp_offset_; } - void InitSegmentReceived(scoped_ptr<MediaTracks> tracks) { - CHECK(tracks.get()); - EXPECT_GT(tracks->tracks().size(), 0u); - CHECK(chunk_demuxer_); - // Generate track ids. - std::vector<unsigned> track_ids; - for (size_t track_id = 1; track_id <= tracks->tracks().size(); ++track_id) { - track_ids.push_back(track_id); - } - - chunk_demuxer_->OnTrackIdsAssigned(*tracks.get(), track_ids); - InitSegmentReceivedMock(tracks); + // A workaround for gtest mocks not allowing moving scoped_ptrs. + void InitSegmentReceivedWrapper(scoped_ptr<MediaTracks> tracks) { + InitSegmentReceived(tracks); } - MOCK_METHOD1(InitSegmentReceivedMock, void(scoped_ptr<MediaTracks>&)); + MOCK_METHOD1(InitSegmentReceived, void(scoped_ptr<MediaTracks>&)); private: scoped_refptr<DecoderBuffer> file_data_; @@ -702,7 +693,7 @@ hashing_enabled_ = test_type & kHashed; clockless_playback_ = test_type & kClockless; - EXPECT_CALL(*source, InitSegmentReceivedMock(_)).Times(AtLeast(1)); + EXPECT_CALL(*source, InitSegmentReceived(_)).Times(AtLeast(1)); EXPECT_CALL(*this, OnMetadata(_)) .Times(AtMost(1)) .WillRepeatedly(SaveArg<0>(&metadata_)); @@ -736,7 +727,7 @@ void StartPipelineWithEncryptedMedia(MockMediaSource* source, FakeEncryptedMedia* encrypted_media) { - EXPECT_CALL(*source, InitSegmentReceivedMock(_)).Times(AtLeast(1)); + EXPECT_CALL(*source, InitSegmentReceived(_)).Times(AtLeast(1)); EXPECT_CALL(*this, OnMetadata(_)) .Times(AtMost(1)) .WillRepeatedly(SaveArg<0>(&metadata_)); @@ -2144,63 +2135,4 @@ demuxer_->GetStartTime()); } -TEST_F(PipelineIntegrationTest, AudioTrackMuteUnmute) { - ASSERT_EQ(PIPELINE_OK, Start("bear-320x240.webm")); - - // Start playback and play a little, to ensure demuxer streams are created. - Play(); - ASSERT_TRUE( - WaitUntilCurrentTimeIsAfter(base::TimeDelta::FromMilliseconds(200))); - Pause(); - - const DemuxerStream* demux_stream = demuxer_->GetDemuxerStreamByTrackId(2); - EXPECT_NE(demux_stream, nullptr); - EXPECT_EQ(demux_stream->type(), DemuxerStream::AUDIO); - - // TODO(servolk): Find a way to verify that audio is really muted/unmuted. - // This should mute the audio stream. - std::vector<const DemuxerStream*> enabledAudioStreams; - pipeline_->OnEnabledAudioStreamsChanged(enabledAudioStreams); - - Play(); - ASSERT_TRUE( - WaitUntilCurrentTimeIsAfter(base::TimeDelta::FromMilliseconds(500))); - Pause(); - - // This should unmute the audio stream. - enabledAudioStreams.push_back(demux_stream); - pipeline_->OnEnabledAudioStreamsChanged(enabledAudioStreams); - - Play(); - ASSERT_TRUE(WaitUntilOnEnded()); -} - -TEST_F(PipelineIntegrationTest, VideoTrackSelectDeselect) { - ASSERT_EQ(PIPELINE_OK, Start("bear-320x240.webm")); - - // Start playback and play a little, to ensure demuxer streams are created. - Play(); - ASSERT_TRUE( - WaitUntilCurrentTimeIsAfter(base::TimeDelta::FromMilliseconds(200))); - Pause(); - - const DemuxerStream* demux_stream = demuxer_->GetDemuxerStreamByTrackId(1); - EXPECT_NE(demux_stream, nullptr); - EXPECT_EQ(demux_stream->type(), DemuxerStream::VIDEO); - - // Deselect video stream. - pipeline_->OnSelectedVideoStreamChanged(nullptr); - - Play(); - ASSERT_TRUE( - WaitUntilCurrentTimeIsAfter(base::TimeDelta::FromMilliseconds(500))); - Pause(); - - // Select video stream. - pipeline_->OnSelectedVideoStreamChanged(demux_stream); - - Play(); - ASSERT_TRUE(WaitUntilOnEnded()); -} - } // namespace media
diff --git a/media/test/pipeline_integration_test_base.cc b/media/test/pipeline_integration_test_base.cc index 9c20aeb..17647ba 100644 --- a/media/test/pipeline_integration_test_base.cc +++ b/media/test/pipeline_integration_test_base.cc
@@ -83,15 +83,6 @@ void PipelineIntegrationTestBase::DemuxerMediaTracksUpdatedCB( scoped_ptr<MediaTracks> tracks) { CHECK(tracks); - CHECK(demuxer_); - - // Generate track ids. - std::vector<unsigned> track_ids; - for (size_t track_id = 1; track_id <= tracks->tracks().size(); ++track_id) { - track_ids.push_back(track_id); - } - - demuxer_->OnTrackIdsAssigned(*tracks.get(), track_ids); } void PipelineIntegrationTestBase::OnEnded() { @@ -282,14 +273,16 @@ scoped_ptr<DataSource> data_source) { data_source_ = std::move(data_source); + Demuxer::MediaTracksUpdatedCB tracks_updated_cb = + base::Bind(&PipelineIntegrationTestBase::DemuxerMediaTracksUpdatedCB, + base::Unretained(this)); + #if !defined(MEDIA_DISABLE_FFMPEG) demuxer_ = scoped_ptr<Demuxer>(new FFmpegDemuxer( message_loop_.task_runner(), data_source_.get(), base::Bind(&PipelineIntegrationTestBase::DemuxerEncryptedMediaInitDataCB, base::Unretained(this)), - base::Bind(&PipelineIntegrationTestBase::DemuxerMediaTracksUpdatedCB, - base::Unretained(this)), - new MediaLog())); + tracks_updated_cb, new MediaLog())); #endif }
diff --git a/mojo/edk/embedder/embedder_unittest.cc b/mojo/edk/embedder/embedder_unittest.cc index b21d898e..5d38b6e 100644 --- a/mojo/edk/embedder/embedder_unittest.cc +++ b/mojo/edk/embedder/embedder_unittest.cc
@@ -303,9 +303,6 @@ // from it. base::SharedMemoryCreateOptions options; options.size = 123; -#if defined(OS_MACOSX) && !defined(OS_IOS) - options.type = base::SharedMemoryHandle::POSIX; -#endif base::SharedMemory shared_memory; ASSERT_TRUE(shared_memory.Create(options)); base::SharedMemoryHandle shm_handle = base::SharedMemory::DuplicateHandle( @@ -385,7 +382,6 @@ // buffer from it. base::SharedMemoryCreateOptions options; options.size = 123; - options.type = base::SharedMemoryHandle::MACH; base::SharedMemory shared_memory; ASSERT_TRUE(shared_memory.Create(options)); base::SharedMemoryHandle shm_handle = base::SharedMemory::DuplicateHandle( @@ -460,7 +456,6 @@ } else { base::SharedMemoryCreateOptions options; options.size = kShmSize; - options.type = base::SharedMemoryHandle::MACH; base::SharedMemory shared_memory; ASSERT_TRUE(shared_memory.Create(options)); base::SharedMemoryHandle shm_handle =
diff --git a/mojo/edk/embedder/platform_shared_buffer.cc b/mojo/edk/embedder/platform_shared_buffer.cc index 63e5676..a3537392 100644 --- a/mojo/edk/embedder/platform_shared_buffer.cc +++ b/mojo/edk/embedder/platform_shared_buffer.cc
@@ -27,14 +27,7 @@ #elif defined(OS_WIN) return ScopedPlatformHandle(PlatformHandle(memory_handle.GetHandle())); #else - if (memory_handle.GetType() == base::SharedMemoryHandle::MACH) { - return ScopedPlatformHandle(PlatformHandle( - memory_handle.GetMemoryObject())); - } else { - DCHECK(memory_handle.GetType() == base::SharedMemoryHandle::POSIX); - return ScopedPlatformHandle(PlatformHandle( - memory_handle.GetFileDescriptor().fd)); - } + return ScopedPlatformHandle(PlatformHandle(memory_handle.GetMemoryObject())); #endif } @@ -227,9 +220,6 @@ options.size = num_bytes_; // By default, we can share as read-only. options.share_read_only = true; -#if defined(OS_MACOSX) && !defined(OS_IOS) - options.type = base::SharedMemoryHandle::MACH; -#endif shared_memory_.reset(new base::SharedMemory); return shared_memory_->Create(options); @@ -244,12 +234,8 @@ base::GetCurrentProcId()); #elif defined(OS_MACOSX) && !defined(OS_IOS) base::SharedMemoryHandle handle; - if (platform_handle.get().type == PlatformHandle::Type::MACH) { - handle = base::SharedMemoryHandle( - platform_handle.release().port, num_bytes_, base::GetCurrentProcId()); - } else { - handle = base::SharedMemoryHandle(platform_handle.release().handle, false); - } + handle = base::SharedMemoryHandle(platform_handle.release().port, num_bytes_, + base::GetCurrentProcId()); #else base::SharedMemoryHandle handle(platform_handle.release().handle, false); #endif
diff --git a/mojo/edk/embedder/platform_shared_buffer_unittest.cc b/mojo/edk/embedder/platform_shared_buffer_unittest.cc index 098ff26a..315f7ea 100644 --- a/mojo/edk/embedder/platform_shared_buffer_unittest.cc +++ b/mojo/edk/embedder/platform_shared_buffer_unittest.cc
@@ -194,9 +194,6 @@ const size_t kBufferSize = 1234; base::SharedMemoryCreateOptions options; options.size = kBufferSize; -#if defined(OS_MACOSX) && !defined(OS_IOS) - options.type = base::SharedMemoryHandle::POSIX; -#endif base::SharedMemory shared_memory; ASSERT_TRUE(shared_memory.Create(options)); ASSERT_TRUE(shared_memory.Map(kBufferSize));
diff --git a/mojo/edk/system/BUILD.gn b/mojo/edk/system/BUILD.gn index 5d83bb6c..7ec5ac98 100644 --- a/mojo/edk/system/BUILD.gn +++ b/mojo/edk/system/BUILD.gn
@@ -23,6 +23,7 @@ sources = [ "async_waiter.cc", "async_waiter.h", + "atomic_flag.h", "awakable.h", "awakable_list.cc", "awakable_list.h",
diff --git a/mojo/edk/system/atomic_flag.h b/mojo/edk/system/atomic_flag.h new file mode 100644 index 0000000..6bdcfaad --- /dev/null +++ b/mojo/edk/system/atomic_flag.h
@@ -0,0 +1,57 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef MOJO_EDK_SYSTEM_ATOMIC_FLAG_H_ +#define MOJO_EDK_SYSTEM_ATOMIC_FLAG_H_ + +#include "base/atomicops.h" +#include "base/macros.h" + +namespace mojo { +namespace edk { + +// AtomicFlag is a boolean flag that can be set and tested atomically. It is +// intended to be used to fast-path checks where the common case would normally +// release the governing mutex immediately after checking. +// +// Example usage: +// void DoFoo(Bar* bar) { +// AutoLock l(lock_); +// queue_.push_back(bar); +// flag_.Set(true); +// } +// +// void Baz() { +// if (!flag_) // Assume this is the common case. +// return; +// +// AutoLock l(lock_); +// ... drain queue_ ... +// flag_.Set(false); +// } +class AtomicFlag { + public: + AtomicFlag() : flag_(0) {} + ~AtomicFlag() {} + + void Set(bool value) { + base::subtle::Release_Store(&flag_, value ? 1 : 0); + } + + bool Get() const { + return base::subtle::Acquire_Load(&flag_) ? true : false; + } + + operator const bool() const { return Get(); } + + private: + base::subtle::Atomic32 flag_; + + DISALLOW_COPY_AND_ASSIGN(AtomicFlag); +}; + +} // namespace edk +} // namespace mojo + +#endif // MOJO_EDK_SYSTEM_ATOMIC_FLAG_H_
diff --git a/mojo/edk/system/message_pipe_dispatcher.cc b/mojo/edk/system/message_pipe_dispatcher.cc index 187176d..b90f3b79 100644 --- a/mojo/edk/system/message_pipe_dispatcher.cc +++ b/mojo/edk/system/message_pipe_dispatcher.cc
@@ -107,7 +107,7 @@ { base::AutoLock lock(signal_lock_); port0 = port_; - port_closed_ = true; + port_closed_.Set(true); awakables_.CancelAll(); } @@ -115,7 +115,7 @@ { base::AutoLock lock(other->signal_lock_); port1 = other->port_; - other->port_closed_ = true; + other->port_closed_.Set(true); other->awakables_.CancelAll(); } @@ -163,11 +163,9 @@ uint32_t num_dispatchers, MojoWriteMessageFlags flags) { - { - base::AutoLock lock(signal_lock_); - if (port_closed_ || in_transit_) - return MOJO_RESULT_INVALID_ARGUMENT; - } + + if (port_closed_ || in_transit_) + return MOJO_RESULT_INVALID_ARGUMENT; // A structure for retaining information about every Dispatcher we're about // to send. This information is collected by calling StartSerialize() on @@ -316,12 +314,9 @@ MojoHandle* handles, uint32_t* num_handles, MojoReadMessageFlags flags) { - { - base::AutoLock lock(signal_lock_); - // We can't read from a port that's closed or in transit! - if (port_closed_ || in_transit_) - return MOJO_RESULT_INVALID_ARGUMENT; - } + // We can't read from a port that's closed or in transit! + if (port_closed_ || in_transit_) + return MOJO_RESULT_INVALID_ARGUMENT; bool no_space = false; bool may_discard = flags & MOJO_READ_MESSAGE_FLAG_MAY_DISCARD; @@ -549,7 +544,7 @@ base::AutoLock lock(signal_lock_); if (in_transit_ || port_closed_) return false; - in_transit_ = true; + in_transit_.Set(true); return in_transit_; } @@ -557,14 +552,14 @@ node_controller_->SetPortObserver(port_, nullptr); base::AutoLock lock(signal_lock_); - in_transit_ = false; port_transferred_ = true; + in_transit_.Set(false); CloseNoLock(); } void MessagePipeDispatcher::CancelTransit() { base::AutoLock lock(signal_lock_); - in_transit_ = false; + in_transit_.Set(false); // Something may have happened while we were waiting for potential transit. awakables_.AwakeForStateChange(GetHandleSignalsStateNoLock()); @@ -601,7 +596,7 @@ if (port_closed_ || in_transit_) return MOJO_RESULT_INVALID_ARGUMENT; - port_closed_ = true; + port_closed_.Set(true); awakables_.CancelAll(); if (!port_transferred_) {
diff --git a/mojo/edk/system/message_pipe_dispatcher.h b/mojo/edk/system/message_pipe_dispatcher.h index b457ab99..fd3f665b 100644 --- a/mojo/edk/system/message_pipe_dispatcher.h +++ b/mojo/edk/system/message_pipe_dispatcher.h
@@ -11,6 +11,7 @@ #include "base/macros.h" #include "base/memory/scoped_ptr.h" +#include "mojo/edk/system/atomic_flag.h" #include "mojo/edk/system/awakable_list.h" #include "mojo/edk/system/dispatcher.h" #include "mojo/edk/system/ports/port_ref.h" @@ -107,10 +108,10 @@ // This is not the same is |port_transferred_|. It's only held true between // BeginTransit() and Complete/CancelTransit(). - bool in_transit_ = false; + AtomicFlag in_transit_; bool port_transferred_ = false; - bool port_closed_ = false; + AtomicFlag port_closed_; AwakableList awakables_; DISALLOW_COPY_AND_ASSIGN(MessagePipeDispatcher);
diff --git a/mojo/edk/system/node_controller.cc b/mojo/edk/system/node_controller.cc index 54e7e3c..431547a4 100644 --- a/mojo/edk/system/node_controller.cc +++ b/mojo/edk/system/node_controller.cc
@@ -256,6 +256,7 @@ { base::AutoLock lock(shutdown_lock_); shutdown_callback_ = callback; + shutdown_callback_flag_.Set(true); } AttemptShutdownIfRequested(); @@ -480,7 +481,7 @@ } void NodeController::AcceptIncomingMessages() { - for (;;) { + while (incoming_messages_flag_) { // TODO: We may need to be more careful to avoid starving the rest of the // thread here. Revisit this if it turns out to be a problem. One // alternative would be to schedule a task to continue pumping messages @@ -495,6 +496,7 @@ // the size is 0. So avoid creating it until it is necessary. std::queue<ports::ScopedMessage> messages; std::swap(messages, incoming_messages_); + incoming_messages_flag_.Set(false); messages_lock_.Release(); while (!messages.empty()) { @@ -558,6 +560,7 @@ // AcceptMessage, we flush the queue after calling any of those methods. base::AutoLock lock(messages_lock_); incoming_messages_.emplace(std::move(message)); + incoming_messages_flag_.Set(true); } else { SendPeerMessage(node, std::move(message)); } @@ -975,6 +978,9 @@ } void NodeController::AttemptShutdownIfRequested() { + if (!shutdown_callback_flag_) + return; + base::Closure callback; { base::AutoLock lock(shutdown_lock_); @@ -986,6 +992,7 @@ callback = shutdown_callback_; shutdown_callback_.Reset(); + shutdown_callback_flag_.Set(false); } DCHECK(!callback.is_null());
diff --git a/mojo/edk/system/node_controller.h b/mojo/edk/system/node_controller.h index c177f8f4..930c080 100644 --- a/mojo/edk/system/node_controller.h +++ b/mojo/edk/system/node_controller.h
@@ -19,6 +19,7 @@ #include "mojo/edk/embedder/platform_handle_vector.h" #include "mojo/edk/embedder/platform_shared_buffer.h" #include "mojo/edk/embedder/scoped_platform_handle.h" +#include "mojo/edk/system/atomic_flag.h" #include "mojo/edk/system/node_channel.h" #include "mojo/edk/system/ports/hash_functions.h" #include "mojo/edk/system/ports/name.h" @@ -247,6 +248,8 @@ // Guards |incoming_messages_|. base::Lock messages_lock_; std::queue<ports::ScopedMessage> incoming_messages_; + // Flag to fast-path checking |incoming_messages_|. + AtomicFlag incoming_messages_flag_; // Guards |shutdown_callback_|. base::Lock shutdown_lock_; @@ -255,6 +258,8 @@ // begin polling the Node to see if clean shutdown is possible any time the // Node's state is modified by the controller. base::Closure shutdown_callback_; + // Flag to fast-path checking |shutdown_callback_|. + AtomicFlag shutdown_callback_flag_; // All other fields below must only be accessed on the I/O thread, i.e., the // thread on which core_->io_task_runner() runs tasks.
diff --git a/mojo/mojo_edk.gyp b/mojo/mojo_edk.gyp index db57fc5..8cf0f93d 100644 --- a/mojo/mojo_edk.gyp +++ b/mojo/mojo_edk.gyp
@@ -58,6 +58,7 @@ 'edk/system/awakable_list.h', 'edk/system/async_waiter.cc', 'edk/system/async_waiter.h', + 'edk/system/atomic_flag.h', 'edk/system/broker.h', 'edk/system/broker_host.h', 'edk/system/broker_host_posix.cc',
diff --git a/net/BUILD.gn b/net/BUILD.gn index 48cbb81d..0e282398 100644 --- a/net/BUILD.gn +++ b/net/BUILD.gn
@@ -1915,6 +1915,7 @@ "//base", "//net", ] + dict = "data/http/http.dict" } fuzzer_test("net_ftp_ctrl_response_fuzzer") { @@ -1983,6 +1984,7 @@ "//base", "//net", ] + dict = "data/http/http.dict" } fuzzer_test("net_quic_crypto_framer_parse_message_fuzzer") {
diff --git a/net/android/http_auth_negotiate_android.h b/net/android/http_auth_negotiate_android.h index af8163c..98ad8e5 100644 --- a/net/android/http_auth_negotiate_android.h +++ b/net/android/http_auth_negotiate_android.h
@@ -6,13 +6,14 @@ #define NET_ANDROID_HTTP_AUTH_NEGOTIATE_ANDROID_H_ #include <jni.h> + +#include <memory> #include <string> #include "base/android/jni_android.h" #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "net/base/completion_callback.h" #include "net/http/http_auth.h"
diff --git a/net/android/keystore_openssl.cc b/net/android/keystore_openssl.cc index f60842c..7437e1a 100644 --- a/net/android/keystore_openssl.cc +++ b/net/android/keystore_openssl.cc
@@ -13,11 +13,12 @@ #include <openssl/rsa.h> #include <stdint.h> +#include <memory> + #include "base/android/build_info.h" #include "base/android/scoped_java_ref.h" #include "base/lazy_instance.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "crypto/openssl_util.h" #include "net/android/keystore.h" #include "net/android/legacy_openssl.h" @@ -330,7 +331,7 @@ return nullptr; } - scoped_ptr<KeyExData> ex_data(new KeyExData); + std::unique_ptr<KeyExData> ex_data(new KeyExData); ex_data->private_key.Reset(nullptr, private_key); if (ex_data->private_key.is_null()) { LOG(ERROR) << "Could not create global JNI reference"; @@ -500,7 +501,7 @@ return nullptr; } - scoped_ptr<KeyExData> ex_data(new KeyExData); + std::unique_ptr<KeyExData> ex_data(new KeyExData); ex_data->private_key.Reset(nullptr, private_key); if (ex_data->private_key.is_null()) { LOG(ERROR) << "Can't create global JNI reference";
diff --git a/net/android/network_change_notifier_android.cc b/net/android/network_change_notifier_android.cc index 74d47936..e7350e06 100644 --- a/net/android/network_change_notifier_android.cc +++ b/net/android/network_change_notifier_android.cc
@@ -142,7 +142,7 @@ const DnsConfig* dns_config_for_testing_; const base::Time creation_time_; - scoped_ptr<internal::DnsConfigServicePosix> dns_config_service_; + std::unique_ptr<internal::DnsConfigServicePosix> dns_config_service_; // Used to detect tunnel state changes. internal::AddressTrackerLinux address_tracker_;
diff --git a/net/android/network_change_notifier_android.h b/net/android/network_change_notifier_android.h index e6c0477..a931f743 100644 --- a/net/android/network_change_notifier_android.h +++ b/net/android/network_change_notifier_android.h
@@ -5,10 +5,11 @@ #ifndef NET_ANDROID_NETWORK_CHANGE_NOTIFIER_ANDROID_H_ #define NET_ANDROID_NETWORK_CHANGE_NOTIFIER_ANDROID_H_ +#include <memory> + #include "base/android/jni_android.h" #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/android/network_change_notifier_delegate_android.h" #include "net/base/network_change_notifier.h" @@ -92,7 +93,7 @@ static NetworkChangeCalculatorParams NetworkChangeCalculatorParamsAndroid(); NetworkChangeNotifierDelegateAndroid* const delegate_; - scoped_ptr<DnsConfigServiceThread> dns_config_service_thread_; + std::unique_ptr<DnsConfigServiceThread> dns_config_service_thread_; bool force_network_handles_supported_for_testing_; DISALLOW_COPY_AND_ASSIGN(NetworkChangeNotifierAndroid);
diff --git a/net/android/network_change_notifier_android_unittest.cc b/net/android/network_change_notifier_android_unittest.cc index e07a89e..6d714706 100644 --- a/net/android/network_change_notifier_android_unittest.cc +++ b/net/android/network_change_notifier_android_unittest.cc
@@ -274,7 +274,7 @@ delegate_.GetCurrentConnectionType()); // Instantiate another delegate to validate that it uses the actual // connection type at construction. - scoped_ptr<NetworkChangeNotifierDelegateAndroid> other_delegate( + std::unique_ptr<NetworkChangeNotifierDelegateAndroid> other_delegate( new NetworkChangeNotifierDelegateAndroid()); EXPECT_EQ(NetworkChangeNotifier::CONNECTION_NONE, other_delegate->GetCurrentConnectionType()); @@ -314,7 +314,7 @@ NetworkChangeNotifierObserver other_connection_type_observer_; NetworkChangeNotifier::DisableForTest disable_for_test_; DnsConfig dns_config_; - scoped_ptr<NetworkChangeNotifierAndroid> notifier_; + std::unique_ptr<NetworkChangeNotifierAndroid> notifier_; }; class NetworkChangeNotifierDelegateAndroidTest
diff --git a/net/android/traffic_stats_unittest.cc b/net/android/traffic_stats_unittest.cc index 29abbe7..71e9eb09 100644 --- a/net/android/traffic_stats_unittest.cc +++ b/net/android/traffic_stats_unittest.cc
@@ -32,7 +32,7 @@ TestDelegate test_delegate; TestURLRequestContext context(false); - scoped_ptr<URLRequest> request( + std::unique_ptr<URLRequest> request( context.CreateRequest(embedded_test_server.GetURL("/echo.html"), DEFAULT_PRIORITY, &test_delegate)); request->Start(); @@ -65,7 +65,7 @@ TestDelegate test_delegate; TestURLRequestContext context(false); - scoped_ptr<URLRequest> request( + std::unique_ptr<URLRequest> request( context.CreateRequest(embedded_test_server.GetURL("/echo.html"), DEFAULT_PRIORITY, &test_delegate)); request->Start();
diff --git a/net/base/ip_address.cc b/net/base/ip_address.cc index e14dbb9..a0cf673 100644 --- a/net/base/ip_address.cc +++ b/net/base/ip_address.cc
@@ -13,6 +13,10 @@ namespace { +// The prefix for IPv6 mapped IPv4 addresses. +// https://tools.ietf.org/html/rfc4291#section-2.5.5.2 +const uint8_t kIPv4MappedPrefix[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF}; + bool IPAddressPrefixCheck(const std::vector<uint8_t>& ip_address, const unsigned char* ip_prefix, size_t prefix_length_in_bits) { @@ -152,7 +156,7 @@ } bool IPAddress::IsIPv4MappedIPv6() const { - return net::IsIPv4Mapped(ip_address_); + return IsIPv6() && IPAddressStartsWith(*this, kIPv4MappedPrefix); } std::string IPAddress::ToString() const { @@ -222,11 +226,23 @@ } IPAddress ConvertIPv4ToIPv4MappedIPv6(const IPAddress& address) { - return IPAddress(ConvertIPv4NumberToIPv6Number(address.bytes())); + DCHECK(address.IsIPv4()); + // IPv4-mapped addresses are formed by: + // <80 bits of zeros> + <16 bits of ones> + <32-bit IPv4 address>. + std::vector<uint8_t> bytes; + bytes.reserve(16); + bytes.insert(bytes.end(), std::begin(kIPv4MappedPrefix), + std::end(kIPv4MappedPrefix)); + bytes.insert(bytes.end(), address.bytes().begin(), address.bytes().end()); + return IPAddress(bytes); } IPAddress ConvertIPv4MappedIPv6ToIPv4(const IPAddress& address) { - return IPAddress(ConvertIPv4MappedToIPv4(address.bytes())); + DCHECK(address.IsIPv4MappedIPv6()); + + return IPAddress(std::vector<uint8_t>( + address.bytes().begin() + arraysize(kIPv4MappedPrefix), + address.bytes().end())); } bool IPAddressMatchesPrefix(const IPAddress& ip_address,
diff --git a/net/base/ip_address_number.cc b/net/base/ip_address_number.cc index ddd9582d..8564888 100644 --- a/net/base/ip_address_number.cc +++ b/net/base/ip_address_number.cc
@@ -84,41 +84,6 @@ return family == url::CanonHostInfo::IPV4; } -namespace { - -const unsigned char kIPv4MappedPrefix[] = - { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF }; -} - -IPAddressNumber ConvertIPv4NumberToIPv6Number( - const IPAddressNumber& ipv4_number) { - DCHECK(ipv4_number.size() == 4); - - // IPv4-mapped addresses are formed by: - // <80 bits of zeros> + <16 bits of ones> + <32-bit IPv4 address>. - IPAddressNumber ipv6_number; - ipv6_number.reserve(16); - ipv6_number.insert(ipv6_number.end(), - kIPv4MappedPrefix, - kIPv4MappedPrefix + arraysize(kIPv4MappedPrefix)); - ipv6_number.insert(ipv6_number.end(), ipv4_number.begin(), ipv4_number.end()); - return ipv6_number; -} - -bool IsIPv4Mapped(const IPAddressNumber& address) { - if (address.size() != kIPv6AddressSize) - return false; - return std::equal(address.begin(), - address.begin() + arraysize(kIPv4MappedPrefix), - kIPv4MappedPrefix); -} - -IPAddressNumber ConvertIPv4MappedToIPv4(const IPAddressNumber& address) { - DCHECK(IsIPv4Mapped(address)); - return IPAddressNumber(address.begin() + arraysize(kIPv4MappedPrefix), - address.end()); -} - unsigned CommonPrefixLength(const IPAddressNumber& a1, const IPAddressNumber& a2) { DCHECK_EQ(a1.size(), a2.size());
diff --git a/net/base/ip_address_number.h b/net/base/ip_address_number.h index 5661648e..a0894b6 100644 --- a/net/base/ip_address_number.h +++ b/net/base/ip_address_number.h
@@ -58,19 +58,6 @@ NET_EXPORT bool ParseIPLiteralToNumber(const base::StringPiece& ip_literal, IPAddressNumber* ip_number); -// Converts an IPv4 address to an IPv4-mapped IPv6 address. -// For example 192.168.0.1 would be converted to ::ffff:192.168.0.1. -NET_EXPORT_PRIVATE IPAddressNumber ConvertIPv4NumberToIPv6Number( - const IPAddressNumber& ipv4_number); - -// Returns true iff |address| is an IPv4-mapped IPv6 address. -NET_EXPORT_PRIVATE bool IsIPv4Mapped(const IPAddressNumber& address); - -// Converts an IPv4-mapped IPv6 address to IPv4 address. Should only be called -// on IPv4-mapped IPv6 addresses. -NET_EXPORT_PRIVATE IPAddressNumber ConvertIPv4MappedToIPv4( - const IPAddressNumber& address); - // Returns number of matching initial bits between the addresses |a1| and |a2|. unsigned CommonPrefixLength(const IPAddressNumber& a1, const IPAddressNumber& a2);
diff --git a/net/base/ip_address_number_unittest.cc b/net/base/ip_address_number_unittest.cc index d06f944..cc68a25 100644 --- a/net/base/ip_address_number_unittest.cc +++ b/net/base/ip_address_number_unittest.cc
@@ -82,43 +82,6 @@ EXPECT_EQ("1:abcd::3:4:ff", IPAddressToString(number)); } -// Test mapping an IPv4 address to an IPv6 address. -TEST(IpAddressNumberTest, ConvertIPv4NumberToIPv6Number) { - IPAddressNumber ipv4_number; - EXPECT_TRUE(ParseIPLiteralToNumber("192.168.0.1", &ipv4_number)); - - IPAddressNumber ipv6_number = - ConvertIPv4NumberToIPv6Number(ipv4_number); - - // ::ffff:192.168.0.1 - EXPECT_EQ("0,0,0,0,0,0,0,0,0,0,255,255,192,168,0,1", - DumpIPNumber(ipv6_number)); - EXPECT_EQ("::ffff:c0a8:1", IPAddressToString(ipv6_number)); -} - -TEST(IpAddressNumberTest, IsIPv4Mapped) { - IPAddressNumber ipv4_number; - EXPECT_TRUE(ParseIPLiteralToNumber("192.168.0.1", &ipv4_number)); - EXPECT_FALSE(IsIPv4Mapped(ipv4_number)); - - IPAddressNumber ipv6_number; - EXPECT_TRUE(ParseIPLiteralToNumber("::1", &ipv6_number)); - EXPECT_FALSE(IsIPv4Mapped(ipv6_number)); - - IPAddressNumber ipv4mapped_number; - EXPECT_TRUE(ParseIPLiteralToNumber("::ffff:0101:1", &ipv4mapped_number)); - EXPECT_TRUE(IsIPv4Mapped(ipv4mapped_number)); -} - -TEST(IpAddressNumberTest, ConvertIPv4MappedToIPv4) { - IPAddressNumber ipv4mapped_number; - EXPECT_TRUE(ParseIPLiteralToNumber("::ffff:0101:1", &ipv4mapped_number)); - IPAddressNumber expected; - EXPECT_TRUE(ParseIPLiteralToNumber("1.1.0.1", &expected)); - IPAddressNumber result = ConvertIPv4MappedToIPv4(ipv4mapped_number); - EXPECT_EQ(expected, result); -} - } // anonymous namespace } // namespace net
diff --git a/net/base/ip_address_unittest.cc b/net/base/ip_address_unittest.cc index 2ad8900f..35fdd741 100644 --- a/net/base/ip_address_unittest.cc +++ b/net/base/ip_address_unittest.cc
@@ -124,6 +124,15 @@ EXPECT_FALSE(empty_address.IsZero()); } +TEST(IpAddressNumberTest, IsIPv4Mapped) { + IPAddress ipv4_address(192, 168, 0, 1); + EXPECT_FALSE(ipv4_address.IsIPv4MappedIPv6()); + IPAddress ipv6_address(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1); + EXPECT_FALSE(ipv6_address.IsIPv4MappedIPv6()); + IPAddress mapped_address(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 1, 1, 0, 1); + EXPECT_TRUE(mapped_address.IsIPv4MappedIPv6()); +} + TEST(IPAddressTest, AllZeros) { EXPECT_TRUE(IPAddress::AllZeros(0).empty()); @@ -184,18 +193,13 @@ EXPECT_EQ("1:abcd::3:4:ff", address.ToString()); } -TEST(IPAddressTest, IsIPv4MappedIPv6) { - IPAddress ipv4_address; - EXPECT_TRUE(ipv4_address.AssignFromIPLiteral("192.168.0.1")); +TEST(IpAddressNumberTest, IsIPv4MappedIPv6) { + IPAddress ipv4_address(192, 168, 0, 1); EXPECT_FALSE(ipv4_address.IsIPv4MappedIPv6()); - - IPAddress ipv6_address; - EXPECT_TRUE(ipv6_address.AssignFromIPLiteral("::1")); + IPAddress ipv6_address = IPAddress::IPv6Localhost(); EXPECT_FALSE(ipv6_address.IsIPv4MappedIPv6()); - - IPAddress ipv4mapped_address; - EXPECT_TRUE(ipv4mapped_address.AssignFromIPLiteral("::ffff:0101:1")); - EXPECT_TRUE(ipv4mapped_address.IsIPv4MappedIPv6()); + IPAddress mapped_address(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 1, 1, 0, 1); + EXPECT_TRUE(mapped_address.IsIPv4MappedIPv6()); } TEST(IPAddressTest, IsEqual) { @@ -259,22 +263,23 @@ EXPECT_EQ(expected_ipv6_address, IPAddressToPackedString(ipv6_address)); } +// Test mapping an IPv4 address to an IPv6 address. TEST(IPAddressTest, ConvertIPv4ToIPv4MappedIPv6) { - IPAddress ipv4_address; - EXPECT_TRUE(ipv4_address.AssignFromIPLiteral("192.168.0.1")); - + IPAddress ipv4_address(192, 168, 0, 1); IPAddress ipv6_address = ConvertIPv4ToIPv4MappedIPv6(ipv4_address); // ::ffff:192.168.0.1 + EXPECT_EQ("0,0,0,0,0,0,0,0,0,0,255,255,192,168,0,1", + DumpIPAddress(ipv6_address)); EXPECT_EQ("::ffff:c0a8:1", ipv6_address.ToString()); } +// Test reversal of a IPv6 address mapping. TEST(IPAddressTest, ConvertIPv4MappedIPv6ToIPv4) { IPAddress ipv4mapped_address; EXPECT_TRUE(ipv4mapped_address.AssignFromIPLiteral("::ffff:c0a8:1")); - IPAddress expected; - EXPECT_TRUE(expected.AssignFromIPLiteral("192.168.0.1")); + IPAddress expected(192, 168, 0, 1); IPAddress result = ConvertIPv4MappedIPv6ToIPv4(ipv4mapped_address); EXPECT_EQ(expected, result);
diff --git a/net/cert/internal/verify_name_match.cc b/net/cert/internal/verify_name_match.cc index 723c2575..3cfa4a1 100644 --- a/net/cert/internal/verify_name_match.cc +++ b/net/cert/internal/verify_name_match.cc
@@ -4,8 +4,13 @@ #include "net/cert/internal/verify_name_match.h" +#include <algorithm> +#include <vector> + #include "base/strings/string_util.h" #include "base/tuple.h" +#include "crypto/auto_cbb.h" +#include "crypto/scoped_openssl_types.h" #include "net/cert/internal/parse_name.h" #include "net/der/input.h" #include "net/der/parser.h" @@ -248,7 +253,7 @@ // RDNs, for each RDN in DN1 there is a matching RDN in DN2, and the matching // RDNs appear in the same order in both DNs. - // First just check if the inputs have the same number of RDNs: + // As an optimization, first just compare the number of RDNs: der::Parser a_rdn_sequence_counter(a); der::Parser b_rdn_sequence_counter(b); while (a_rdn_sequence_counter.HasMore() && b_rdn_sequence_counter.HasMore()) { @@ -265,7 +270,7 @@ if (match_type == EXACT_MATCH && a_rdn_sequence_counter.HasMore()) return false; - // Same number of RDNs, now check if they match. + // Verify that RDNs in |a| and |b| match. der::Parser a_rdn_sequence(a); der::Parser b_rdn_sequence(b); while (a_rdn_sequence.HasMore() && b_rdn_sequence.HasMore()) { @@ -283,6 +288,113 @@ } // namespace +bool NormalizeName(const der::Input& name_rdn_sequence, + std::string* normalized_rdn_sequence) { + // RFC 5280 section 4.1.2.4 + // RDNSequence ::= SEQUENCE OF RelativeDistinguishedName + der::Parser rdn_sequence_parser(name_rdn_sequence); + + crypto::AutoCBB cbb; + if (!CBB_init(cbb.get(), 0)) + return false; + + while (rdn_sequence_parser.HasMore()) { + // RelativeDistinguishedName ::= SET SIZE (1..MAX) OF AttributeTypeAndValue + der::Parser rdn_parser; + if (!rdn_sequence_parser.ReadConstructed(der::kSet, &rdn_parser)) + return false; + RelativeDistinguishedName type_and_values; + if (!ReadRdn(&rdn_parser, &type_and_values)) + return false; + + // The AttributeTypeAndValue objects in the SET OF need to be sorted on + // their DER encodings. Encode each individually and save the encoded values + // in |encoded_attribute_type_and_values| so that it can be sorted before + // being added to |rdn_cbb|. |scoped_encoded_attribute_type_and_values| + // owns the |OPENSSL_malloc|ed memory referred to by + // |encoded_attribute_type_and_values|. + CBB rdn_cbb; + if (!CBB_add_asn1(cbb.get(), &rdn_cbb, CBS_ASN1_SET)) + return false; + std::vector<crypto::ScopedOpenSSLBytes> + scoped_encoded_attribute_type_and_values; + std::vector<der::Input> encoded_attribute_type_and_values; + + for (const auto& type_and_value : type_and_values) { + // A top-level CBB for encoding each individual AttributeTypeAndValue. + crypto::AutoCBB type_and_value_encoder_cbb; + if (!CBB_init(type_and_value_encoder_cbb.get(), 0)) + return false; + + // AttributeTypeAndValue ::= SEQUENCE { + // type AttributeType, + // value AttributeValue } + CBB attribute_type_and_value_cbb, type_cbb, value_cbb; + if (!CBB_add_asn1(type_and_value_encoder_cbb.get(), + &attribute_type_and_value_cbb, CBS_ASN1_SEQUENCE)) { + return false; + } + + // AttributeType ::= OBJECT IDENTIFIER + if (!CBB_add_asn1(&attribute_type_and_value_cbb, &type_cbb, + CBS_ASN1_OBJECT) || + !CBB_add_bytes(&type_cbb, type_and_value.type.UnsafeData(), + type_and_value.type.Length())) { + return false; + } + + // AttributeValue ::= ANY -- DEFINED BY AttributeType + if (IsNormalizableDirectoryString(type_and_value.value_tag)) { + std::string normalized_value; + if (!NormalizeValue(type_and_value, &normalized_value)) + return false; + if (!CBB_add_asn1(&attribute_type_and_value_cbb, &value_cbb, + CBS_ASN1_UTF8STRING) || + !CBB_add_bytes(&value_cbb, reinterpret_cast<const uint8_t*>( + normalized_value.data()), + normalized_value.size())) + return false; + } else { + if (!CBB_add_asn1(&attribute_type_and_value_cbb, &value_cbb, + type_and_value.value_tag) || + !CBB_add_bytes(&value_cbb, type_and_value.value.UnsafeData(), + type_and_value.value.Length())) + return false; + } + + uint8_t* bytes; + size_t len; + if (!CBB_finish(type_and_value_encoder_cbb.get(), &bytes, &len)) + return false; + scoped_encoded_attribute_type_and_values.push_back( + crypto::ScopedOpenSSLBytes(bytes)); + encoded_attribute_type_and_values.push_back(der::Input(bytes, len)); + } + + std::sort(encoded_attribute_type_and_values.begin(), + encoded_attribute_type_and_values.end()); + for (const auto& encoded_attribute_type_and_value : + encoded_attribute_type_and_values) { + if (!CBB_add_bytes(&rdn_cbb, + encoded_attribute_type_and_value.UnsafeData(), + encoded_attribute_type_and_value.Length())) { + return false; + } + } + + if (!CBB_flush(cbb.get())) + return false; + } + + uint8_t* der; + size_t der_len; + if (!CBB_finish(cbb.get(), &der, &der_len)) + return false; + normalized_rdn_sequence->assign(der, der + der_len); + OPENSSL_free(der); + return true; +} + bool VerifyNameMatch(const der::Input& a_rdn_sequence, const der::Input& b_rdn_sequence) { return VerifyNameMatchInternal(a_rdn_sequence, b_rdn_sequence, EXACT_MATCH);
diff --git a/net/cert/internal/verify_name_match.h b/net/cert/internal/verify_name_match.h index 5cca36a..02236bb 100644 --- a/net/cert/internal/verify_name_match.h +++ b/net/cert/internal/verify_name_match.h
@@ -5,6 +5,8 @@ #ifndef NET_CERT_INTERNAL_VERIFY_NAME_MATCH_H_ #define NET_CERT_INTERNAL_VERIFY_NAME_MATCH_H_ +#include <string> + #include "base/compiler_specific.h" #include "base/strings/string_piece.h" #include "net/base/net_export.h" @@ -15,6 +17,14 @@ class Input; } // namespace der +// Normalizes DER-encoded X.501 Name |name_rdn_sequence| (which should not +// include the Sequence tag). If successful, returns true and stores the +// normalized DER-encoded Name into |normalized_rdn_sequence| (not including an +// outer Sequence tag). Returns false if there was an error parsing or +// normalizing the input. +NET_EXPORT bool NormalizeName(const der::Input& name_rdn_sequence, + std::string* normalized_rdn_sequence); + // Compares DER-encoded X.501 Name values according to RFC 5280 rules. // |a_rdn_sequence| and |b_rdn_sequence| should be the DER-encoded RDNSequence // values (not including the Sequence tag).
diff --git a/net/cert/internal/verify_name_match_unittest.cc b/net/cert/internal/verify_name_match_unittest.cc index 2bdf82e..6eaf7014 100644 --- a/net/cert/internal/verify_name_match_unittest.cc +++ b/net/cert/internal/verify_name_match_unittest.cc
@@ -352,6 +352,8 @@ // Verification should fail due to the invalid character. EXPECT_FALSE(VerifyNameMatch(SequenceValueFromString(&der), SequenceValueFromString(&der))); + std::string normalized_der; + EXPECT_FALSE(NormalizeName(SequenceValueFromString(&der), &normalized_der)); } } @@ -368,6 +370,9 @@ bool expected_result = (c <= 127); EXPECT_EQ(expected_result, VerifyNameMatch(SequenceValueFromString(&der), SequenceValueFromString(&der))); + std::string normalized_der; + EXPECT_EQ(expected_result, + NormalizeName(SequenceValueFromString(&der), &normalized_der)); } } @@ -379,6 +384,9 @@ // sequence. EXPECT_FALSE(VerifyNameMatch(SequenceValueFromString(&invalid), SequenceValueFromString(&invalid))); + std::string normalized_der; + EXPECT_FALSE( + NormalizeName(SequenceValueFromString(&invalid), &normalized_der)); } TEST(VerifyNameMatchInvalidDataTest, FailOnAttributeTypeAndValueShort) { @@ -389,6 +397,9 @@ // one element. EXPECT_FALSE(VerifyNameMatch(SequenceValueFromString(&invalid), SequenceValueFromString(&invalid))); + std::string normalized_der; + EXPECT_FALSE( + NormalizeName(SequenceValueFromString(&invalid), &normalized_der)); } TEST(VerifyNameMatchInvalidDataTest, FailOnAttributeTypeAndValueEmpty) { @@ -398,6 +409,9 @@ // Verification should fail due to empty AttributeTypeAndValue sequence. EXPECT_FALSE(VerifyNameMatch(SequenceValueFromString(&invalid), SequenceValueFromString(&invalid))); + std::string normalized_der; + EXPECT_FALSE( + NormalizeName(SequenceValueFromString(&invalid), &normalized_der)); } TEST(VerifyNameMatchInvalidDataTest, FailOnBadAttributeType) { @@ -407,6 +421,9 @@ // Verification should fail due to Attribute Type not being an OID. EXPECT_FALSE(VerifyNameMatch(SequenceValueFromString(&invalid), SequenceValueFromString(&invalid))); + std::string normalized_der; + EXPECT_FALSE( + NormalizeName(SequenceValueFromString(&invalid), &normalized_der)); } TEST(VerifyNameMatchInvalidDataTest, FailOnAttributeTypeAndValueNotSequence) { @@ -417,6 +434,9 @@ // of a Sequence. EXPECT_FALSE(VerifyNameMatch(SequenceValueFromString(&invalid), SequenceValueFromString(&invalid))); + std::string normalized_der; + EXPECT_FALSE( + NormalizeName(SequenceValueFromString(&invalid), &normalized_der)); } TEST(VerifyNameMatchInvalidDataTest, FailOnRdnNotSet) { @@ -425,6 +445,9 @@ // Verification should fail due to RDN being a Sequence instead of a Set. EXPECT_FALSE(VerifyNameMatch(SequenceValueFromString(&invalid), SequenceValueFromString(&invalid))); + std::string normalized_der; + EXPECT_FALSE( + NormalizeName(SequenceValueFromString(&invalid), &normalized_der)); } TEST(VerifyNameMatchInvalidDataTest, FailOnEmptyRdn) { @@ -433,6 +456,9 @@ // Verification should fail due to RDN having zero AttributeTypeAndValues. EXPECT_FALSE(VerifyNameMatch(SequenceValueFromString(&invalid), SequenceValueFromString(&invalid))); + std::string normalized_der; + EXPECT_FALSE( + NormalizeName(SequenceValueFromString(&invalid), &normalized_der)); } // Matching should fail if a BMPString contains surrogates. @@ -449,6 +475,9 @@ // Verification should fail due to the invalid codepoints. EXPECT_FALSE(VerifyNameMatch(SequenceValueFromString(&invalid), SequenceValueFromString(&invalid))); + std::string normalized_der; + EXPECT_FALSE( + NormalizeName(SequenceValueFromString(&invalid), &normalized_der)); } TEST(VerifyNameMatchTest, EmptyNameMatching) { @@ -457,6 +486,11 @@ // Empty names are equal. EXPECT_TRUE(VerifyNameMatch(SequenceValueFromString(&empty), SequenceValueFromString(&empty))); + // An empty name normalized is unchanged. + std::string normalized_empty_der; + EXPECT_TRUE( + NormalizeName(SequenceValueFromString(&empty), &normalized_empty_der)); + EXPECT_EQ(SequenceValueFromString(&empty), der::Input(&normalized_empty_der)); // An empty name is not equal to non-empty name. std::string non_empty; @@ -527,4 +561,26 @@ SequenceValueFromString(&non_empty))); } +// Verify that the normalized output matches the pre-generated expected value +// for a single larger input that exercises all of the string types, unicode +// (basic and supplemental planes), whitespace collapsing, case folding, as +// well as SET sorting. +TEST(NameNormalizationTest, TestEverything) { + std::string expected_normalized_der; + ASSERT_TRUE( + LoadTestData("unicode", "mixed", "normalized", &expected_normalized_der)); + + std::string raw_der; + ASSERT_TRUE(LoadTestData("unicode", "mixed", "unnormalized", &raw_der)); + std::string normalized_der; + ASSERT_TRUE( + NormalizeName(SequenceValueFromString(&raw_der), &normalized_der)); + EXPECT_EQ(SequenceValueFromString(&expected_normalized_der), + der::Input(&normalized_der)); + // Re-normalizing an already normalized Name should not change it. + std::string renormalized_der; + ASSERT_TRUE(NormalizeName(der::Input(&normalized_der), &renormalized_der)); + EXPECT_EQ(normalized_der, renormalized_der); +} + } // namespace net
diff --git a/net/cert_net/cert_net_fetcher_impl.cc b/net/cert_net/cert_net_fetcher_impl.cc index e80aa1b..e46a0f3 100644 --- a/net/cert_net/cert_net_fetcher_impl.cc +++ b/net/cert_net/cert_net_fetcher_impl.cc
@@ -11,6 +11,7 @@ #include "base/containers/linked_list.h" #include "base/logging.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/numerics/safe_math.h" #include "base/stl_util.h" #include "base/timer/timer.h" @@ -146,7 +147,8 @@ // the pending requests for it. class CertNetFetcherImpl::Job : public URLRequest::Delegate { public: - Job(scoped_ptr<RequestParams> request_params, CertNetFetcherImpl* parent); + Job(std::unique_ptr<RequestParams> request_params, + CertNetFetcherImpl* parent); ~Job() override; // Cancels the job and all requests attached to it. No callbacks will be @@ -158,7 +160,7 @@ // Create a request and attaches it to the job. When the job completes it will // notify the request of completion through OnJobCompleted. Note that the Job // does NOT own the request. - scoped_ptr<Request> CreateRequest(const FetchCallback& callback); + std::unique_ptr<Request> CreateRequest(const FetchCallback& callback); // Removes |request| from the job. void DetachRequest(RequestImpl* request); @@ -206,13 +208,13 @@ RequestList requests_; // The input parameters for starting a URLRequest. - scoped_ptr<RequestParams> request_params_; + std::unique_ptr<RequestParams> request_params_; // The URLRequest response information. std::vector<uint8_t> response_body_; Error result_net_error_; - scoped_ptr<URLRequest> url_request_; + std::unique_ptr<URLRequest> url_request_; scoped_refptr<IOBuffer> read_buffer_; // Used to timeout the job when the URLRequest takes too long. This timer is @@ -230,7 +232,7 @@ job_->DetachRequest(this); } -CertNetFetcherImpl::Job::Job(scoped_ptr<RequestParams> request_params, +CertNetFetcherImpl::Job::Job(std::unique_ptr<RequestParams> request_params, CertNetFetcherImpl* parent) : request_params_(std::move(request_params)), result_net_error_(ERR_IO_PENDING), @@ -257,15 +259,15 @@ Stop(); } -scoped_ptr<CertNetFetcher::Request> CertNetFetcherImpl::Job::CreateRequest( +std::unique_ptr<CertNetFetcher::Request> CertNetFetcherImpl::Job::CreateRequest( const FetchCallback& callback) { - scoped_ptr<RequestImpl> request(new RequestImpl(this, callback)); + std::unique_ptr<RequestImpl> request(new RequestImpl(this, callback)); requests_.Append(request.get()); return std::move(request); } void CertNetFetcherImpl::Job::DetachRequest(RequestImpl* request) { - scoped_ptr<Job> delete_this; + std::unique_ptr<Job> delete_this; request->RemoveFromList(); @@ -411,7 +413,7 @@ // * The parent CertNetFetcherImpl may be deleted // * Requests in this job may be cancelled - scoped_ptr<Job> delete_this = parent_->RemoveJob(this); + std::unique_ptr<Job> delete_this = parent_->RemoveJob(this); parent_->SetCurrentlyCompletingJob(this); while (!requests_.empty()) { @@ -437,12 +439,12 @@ currently_completing_job_->Cancel(); } -scoped_ptr<CertNetFetcher::Request> CertNetFetcherImpl::FetchCaIssuers( +std::unique_ptr<CertNetFetcher::Request> CertNetFetcherImpl::FetchCaIssuers( const GURL& url, int timeout_milliseconds, int max_response_bytes, const FetchCallback& callback) { - scoped_ptr<RequestParams> request_params(new RequestParams); + std::unique_ptr<RequestParams> request_params(new RequestParams); request_params->url = url; request_params->http_method = HTTP_METHOD_GET; @@ -453,12 +455,12 @@ return Fetch(std::move(request_params), callback); } -scoped_ptr<CertNetFetcher::Request> CertNetFetcherImpl::FetchCrl( +std::unique_ptr<CertNetFetcher::Request> CertNetFetcherImpl::FetchCrl( const GURL& url, int timeout_milliseconds, int max_response_bytes, const FetchCallback& callback) { - scoped_ptr<RequestParams> request_params(new RequestParams); + std::unique_ptr<RequestParams> request_params(new RequestParams); request_params->url = url; request_params->http_method = HTTP_METHOD_GET; @@ -469,12 +471,12 @@ return Fetch(std::move(request_params), callback); } -scoped_ptr<CertNetFetcher::Request> CertNetFetcherImpl::FetchOcsp( +std::unique_ptr<CertNetFetcher::Request> CertNetFetcherImpl::FetchOcsp( const GURL& url, int timeout_milliseconds, int max_response_bytes, const FetchCallback& callback) { - scoped_ptr<RequestParams> request_params(new RequestParams); + std::unique_ptr<RequestParams> request_params(new RequestParams); request_params->url = url; request_params->http_method = HTTP_METHOD_GET; @@ -490,8 +492,8 @@ return job1->request_params() < job2->request_params(); } -scoped_ptr<CertNetFetcher::Request> CertNetFetcherImpl::Fetch( - scoped_ptr<RequestParams> request_params, +std::unique_ptr<CertNetFetcher::Request> CertNetFetcherImpl::Fetch( + std::unique_ptr<RequestParams> request_params, const FetchCallback& callback) { DCHECK(thread_checker_.CalledOnValidThread()); @@ -528,11 +530,12 @@ return nullptr; } -scoped_ptr<CertNetFetcherImpl::Job> CertNetFetcherImpl::RemoveJob(Job* job) { +std::unique_ptr<CertNetFetcherImpl::Job> CertNetFetcherImpl::RemoveJob( + Job* job) { DCHECK(thread_checker_.CalledOnValidThread()); bool erased_job = jobs_.erase(job) == 1; CHECK(erased_job); - return make_scoped_ptr(job); + return base::WrapUnique(job); } void CertNetFetcherImpl::SetCurrentlyCompletingJob(Job* job) {
diff --git a/net/cert_net/cert_net_fetcher_impl.h b/net/cert_net/cert_net_fetcher_impl.h index c3a1fb6..08d1b55 100644 --- a/net/cert_net/cert_net_fetcher_impl.h +++ b/net/cert_net/cert_net_fetcher_impl.h
@@ -5,11 +5,11 @@ #ifndef NET_CERT_NET_CERT_NET_FETCHER_H_ #define NET_CERT_NET_CERT_NET_FETCHER_H_ +#include <memory> #include <set> #include "base/callback.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/threading/thread_checker.h" #include "net/base/net_errors.h" #include "net/base/net_export.h" @@ -33,19 +33,19 @@ // Deletion implicitly cancels any outstanding requests. ~CertNetFetcherImpl() override; - WARN_UNUSED_RESULT scoped_ptr<Request> FetchCaIssuers( + WARN_UNUSED_RESULT std::unique_ptr<Request> FetchCaIssuers( const GURL& url, int timeout_milliseconds, int max_response_bytes, const FetchCallback& callback) override; - WARN_UNUSED_RESULT scoped_ptr<Request> FetchCrl( + WARN_UNUSED_RESULT std::unique_ptr<Request> FetchCrl( const GURL& url, int timeout_milliseconds, int max_response_bytes, const FetchCallback& callback) override; - WARN_UNUSED_RESULT scoped_ptr<Request> FetchOcsp( + WARN_UNUSED_RESULT std::unique_ptr<Request> FetchOcsp( const GURL& url, int timeout_milliseconds, int max_response_bytes, @@ -70,8 +70,8 @@ // Completion of the request will never occur synchronously. In other words it // is guaranteed that |callback| will only be invoked once the Fetch*() method // has returned. - WARN_UNUSED_RESULT scoped_ptr<Request> Fetch( - scoped_ptr<RequestParams> request_params, + WARN_UNUSED_RESULT std::unique_ptr<Request> Fetch( + std::unique_ptr<RequestParams> request_params, const FetchCallback& callback); // Finds a job with a matching RequestPararms or returns nullptr if there was @@ -80,7 +80,7 @@ // Removes |job| from the in progress jobs and transfers ownership to the // caller. - scoped_ptr<Job> RemoveJob(Job* job); + std::unique_ptr<Job> RemoveJob(Job* job); // Indicates which Job is currently executing inside of OnJobCompleted(). void SetCurrentlyCompletingJob(Job* job);
diff --git a/net/cert_net/cert_net_fetcher_impl_unittest.cc b/net/cert_net/cert_net_fetcher_impl_unittest.cc index 311e93a..42fe60d 100644 --- a/net/cert_net/cert_net_fetcher_impl_unittest.cc +++ b/net/cert_net/cert_net_fetcher_impl_unittest.cc
@@ -8,6 +8,7 @@ #include <utility> #include "base/compiler_specific.h" +#include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "net/cert/mock_cert_verifier.h" #include "net/dns/mock_host_resolver.h" @@ -34,14 +35,15 @@ public: RequestContext() : storage_(this) { ProxyConfig no_proxy; - storage_.set_host_resolver(scoped_ptr<HostResolver>(new MockHostResolver)); - storage_.set_cert_verifier(make_scoped_ptr(new MockCertVerifier)); + storage_.set_host_resolver( + std::unique_ptr<HostResolver>(new MockHostResolver)); + storage_.set_cert_verifier(base::WrapUnique(new MockCertVerifier)); storage_.set_transport_security_state( - make_scoped_ptr(new TransportSecurityState)); + base::WrapUnique(new TransportSecurityState)); storage_.set_proxy_service(ProxyService::CreateFixed(no_proxy)); storage_.set_ssl_config_service(new SSLConfigServiceDefaults); storage_.set_http_server_properties( - scoped_ptr<HttpServerProperties>(new HttpServerPropertiesImpl())); + std::unique_ptr<HttpServerProperties>(new HttpServerPropertiesImpl())); HttpNetworkSession::Params params; params.host_resolver = host_resolver(); @@ -51,11 +53,11 @@ params.ssl_config_service = ssl_config_service(); params.http_server_properties = http_server_properties(); storage_.set_http_network_session( - make_scoped_ptr(new HttpNetworkSession(params))); - storage_.set_http_transaction_factory(make_scoped_ptr(new HttpCache( + base::WrapUnique(new HttpNetworkSession(params))); + storage_.set_http_transaction_factory(base::WrapUnique(new HttpCache( storage_.http_network_session(), HttpCache::DefaultBackend::InMemory(0), false /* set_up_quic_server_info */))); - storage_.set_job_factory(make_scoped_ptr(new URLRequestJobFactoryImpl())); + storage_.set_job_factory(base::WrapUnique(new URLRequestJobFactoryImpl())); } ~RequestContext() override { AssertNoURLRequests(); } @@ -95,7 +97,7 @@ const CertNetFetcher::FetchCallback& callback() const { return callback_; } - scoped_ptr<FetchResult> WaitForResult() { + std::unique_ptr<FetchResult> WaitForResult() { DCHECK(quit_closure_.is_null()); while (!HasResult()) { base::RunLoop run_loop; @@ -127,7 +129,7 @@ } CertNetFetcher::FetchCallback callback_; - scoped_ptr<FetchResult> result_; + std::unique_ptr<FetchResult> result_; base::Closure quit_closure_; base::Closure extra_closure_; }; @@ -148,7 +150,7 @@ }; // Helper to start an AIA fetch using default parameters. -WARN_UNUSED_RESULT scoped_ptr<CertNetFetcher::Request> StartRequest( +WARN_UNUSED_RESULT std::unique_ptr<CertNetFetcher::Request> StartRequest( CertNetFetcher* fetcher, const GURL& url, const TestFetchCallback& callback) { @@ -168,23 +170,23 @@ // Request a URL with Content-Type "application/pkix-cert" GURL url1 = test_server_.GetURL("/cert.crt"); - scoped_ptr<CertNetFetcher::Request> request1 = + std::unique_ptr<CertNetFetcher::Request> request1 = StartRequest(&fetcher, url1, callback1); // Request a URL with Content-Type "application/pkix-crl" GURL url2 = test_server_.GetURL("/root.crl"); - scoped_ptr<CertNetFetcher::Request> request2 = + std::unique_ptr<CertNetFetcher::Request> request2 = StartRequest(&fetcher, url2, callback2); // Request a URL with Content-Type "application/pkcs7-mime" GURL url3 = test_server_.GetURL("/certs.p7c"); - scoped_ptr<CertNetFetcher::Request> request3 = + std::unique_ptr<CertNetFetcher::Request> request3 = StartRequest(&fetcher, url3, callback3); // Wait for all of the requests to complete. - scoped_ptr<FetchResult> result1 = callback1.WaitForResult(); - scoped_ptr<FetchResult> result2 = callback2.WaitForResult(); - scoped_ptr<FetchResult> result3 = callback3.WaitForResult(); + std::unique_ptr<FetchResult> result1 = callback1.WaitForResult(); + std::unique_ptr<FetchResult> result2 = callback2.WaitForResult(); + std::unique_ptr<FetchResult> result3 = callback3.WaitForResult(); // Verify the fetch results. result1->VerifySuccess("-cert.crt-\n"); @@ -205,9 +207,9 @@ TestFetchCallback callback; GURL url = test_server_.GetURL("/foo.txt"); - scoped_ptr<CertNetFetcher::Request> request = + std::unique_ptr<CertNetFetcher::Request> request = StartRequest(&fetcher, url, callback); - scoped_ptr<FetchResult> result = callback.WaitForResult(); + std::unique_ptr<FetchResult> result = callback.WaitForResult(); result->VerifySuccess("-foo.txt-\n"); } @@ -222,9 +224,9 @@ { TestFetchCallback callback; GURL url = test_server_.GetURL("/404.html"); - scoped_ptr<CertNetFetcher::Request> request = + std::unique_ptr<CertNetFetcher::Request> request = StartRequest(&fetcher, url, callback); - scoped_ptr<FetchResult> result = callback.WaitForResult(); + std::unique_ptr<FetchResult> result = callback.WaitForResult(); result->VerifyFailure(ERR_FAILED); } @@ -232,9 +234,9 @@ { TestFetchCallback callback; GURL url = test_server_.GetURL("/500.html"); - scoped_ptr<CertNetFetcher::Request> request = + std::unique_ptr<CertNetFetcher::Request> request = StartRequest(&fetcher, url, callback); - scoped_ptr<FetchResult> result = callback.WaitForResult(); + std::unique_ptr<FetchResult> result = callback.WaitForResult(); result->VerifyFailure(ERR_FAILED); } } @@ -247,9 +249,9 @@ TestFetchCallback callback; GURL url = test_server_.GetURL("/downloadable.js"); - scoped_ptr<CertNetFetcher::Request> request = + std::unique_ptr<CertNetFetcher::Request> request = StartRequest(&fetcher, url, callback); - scoped_ptr<FetchResult> result = callback.WaitForResult(); + std::unique_ptr<FetchResult> result = callback.WaitForResult(); result->VerifySuccess("-downloadable.js-\n"); } @@ -265,9 +267,9 @@ { TestFetchCallback callback; - scoped_ptr<CertNetFetcher::Request> request = + std::unique_ptr<CertNetFetcher::Request> request = StartRequest(&fetcher, url, callback); - scoped_ptr<FetchResult> result = callback.WaitForResult(); + std::unique_ptr<FetchResult> result = callback.WaitForResult(); result->VerifySuccess("-cacheable_1hr.crt-\n"); } @@ -279,9 +281,9 @@ // Fetch again -- will fail unless served from cache. { TestFetchCallback callback; - scoped_ptr<CertNetFetcher::Request> request = + std::unique_ptr<CertNetFetcher::Request> request = StartRequest(&fetcher, url, callback); - scoped_ptr<FetchResult> result = callback.WaitForResult(); + std::unique_ptr<FetchResult> result = callback.WaitForResult(); result->VerifySuccess("-cacheable_1hr.crt-\n"); } @@ -299,10 +301,10 @@ // bytes will cause it to fail. GURL url(test_server_.GetURL("/certs.p7c")); TestFetchCallback callback; - scoped_ptr<CertNetFetcher::Request> request = fetcher.FetchCaIssuers( + std::unique_ptr<CertNetFetcher::Request> request = fetcher.FetchCaIssuers( url, CertNetFetcher::DEFAULT, 11, callback.callback()); - scoped_ptr<FetchResult> result = callback.WaitForResult(); + std::unique_ptr<FetchResult> result = callback.WaitForResult(); result->VerifyFailure(ERR_FILE_TOO_BIG); } @@ -315,9 +317,9 @@ GURL url(test_server_.GetURL("/slow/certs.p7c?5")); TestFetchCallback callback; - scoped_ptr<CertNetFetcher::Request> request = fetcher.FetchCaIssuers( + std::unique_ptr<CertNetFetcher::Request> request = fetcher.FetchCaIssuers( url, 10, CertNetFetcher::DEFAULT, callback.callback()); - scoped_ptr<FetchResult> result = callback.WaitForResult(); + std::unique_ptr<FetchResult> result = callback.WaitForResult(); result->VerifyFailure(ERR_TIMED_OUT); } @@ -330,9 +332,9 @@ GURL url(test_server_.GetURL("/gzipped_crl")); TestFetchCallback callback; - scoped_ptr<CertNetFetcher::Request> request = + std::unique_ptr<CertNetFetcher::Request> request = StartRequest(&fetcher, url, callback); - scoped_ptr<FetchResult> result = callback.WaitForResult(); + std::unique_ptr<FetchResult> result = callback.WaitForResult(); result->VerifySuccess("-gzipped_crl-\n"); } @@ -344,12 +346,12 @@ GURL url("https://foopy/foo.crt"); TestFetchCallback callback; - scoped_ptr<CertNetFetcher::Request> request = + std::unique_ptr<CertNetFetcher::Request> request = StartRequest(&fetcher, url, callback); // Should NOT complete synchronously despite being a test that could be done // immediately. EXPECT_FALSE(callback.HasResult()); - scoped_ptr<FetchResult> result = callback.WaitForResult(); + std::unique_ptr<FetchResult> result = callback.WaitForResult(); result->VerifyFailure(ERR_DISALLOWED_URL_SCHEME); // No request was created because the URL scheme was unsupported. @@ -365,9 +367,9 @@ GURL url(test_server_.GetURL("/redirect_https")); TestFetchCallback callback; - scoped_ptr<CertNetFetcher::Request> request = + std::unique_ptr<CertNetFetcher::Request> request = StartRequest(&fetcher, url, callback); - scoped_ptr<FetchResult> result = callback.WaitForResult(); + std::unique_ptr<FetchResult> result = callback.WaitForResult(); result->VerifyFailure(ERR_DISALLOWED_URL_SCHEME); EXPECT_EQ(1, network_delegate_.created_requests()); @@ -382,7 +384,7 @@ GURL url("https://foopy/foo.crt"); TestFetchCallback callback; - scoped_ptr<CertNetFetcher::Request> request = + std::unique_ptr<CertNetFetcher::Request> request = StartRequest(&fetcher, url, callback); // Cancel the request. @@ -409,16 +411,16 @@ TestFetchCallback callback3; GURL url1 = test_server_.GetURL("/cert.crt"); - scoped_ptr<CertNetFetcher::Request> request1 = + std::unique_ptr<CertNetFetcher::Request> request1 = StartRequest(&fetcher, url1, callback1); GURL url2 = test_server_.GetURL("/root.crl"); - scoped_ptr<CertNetFetcher::Request> request2 = + std::unique_ptr<CertNetFetcher::Request> request2 = StartRequest(&fetcher, url2, callback2); GURL url3 = test_server_.GetURL("/certs.p7c"); - scoped_ptr<CertNetFetcher::Request> request3 = + std::unique_ptr<CertNetFetcher::Request> request3 = StartRequest(&fetcher, url3, callback3); EXPECT_EQ(3, network_delegate_.created_requests()); @@ -430,8 +432,8 @@ request2.reset(); // Wait for the non-cancelled requests to complete. - scoped_ptr<FetchResult> result1 = callback1.WaitForResult(); - scoped_ptr<FetchResult> result3 = callback3.WaitForResult(); + std::unique_ptr<FetchResult> result1 = callback1.WaitForResult(); + std::unique_ptr<FetchResult> result3 = callback3.WaitForResult(); // Verify the fetch results. result1->VerifySuccess("-cert.crt-\n"); @@ -462,15 +464,15 @@ GURL url1 = test_server_.GetURL("/cert.crt"); - scoped_ptr<CertNetFetcher::Request> request1 = + std::unique_ptr<CertNetFetcher::Request> request1 = StartRequest(&fetcher, url1, callback1); GURL url2 = test_server_.GetURL("/certs.p7c"); - scoped_ptr<CertNetFetcher::Request> request2 = + std::unique_ptr<CertNetFetcher::Request> request2 = StartRequest(&fetcher, url2, callback2); GURL url3("ftp://www.not.supported.com/foo"); - scoped_ptr<CertNetFetcher::Request> request3 = + std::unique_ptr<CertNetFetcher::Request> request3 = StartRequest(&fetcher, url3, callback3); EXPECT_FALSE(callback1.HasResult()); @@ -479,14 +481,14 @@ // Wait for the ftp request to complete (it should complete right away since // it doesn't even try to connect to the server). - scoped_ptr<FetchResult> result3 = callback3.WaitForResult(); + std::unique_ptr<FetchResult> result3 = callback3.WaitForResult(); result3->VerifyFailure(ERR_DISALLOWED_URL_SCHEME); // Cancel the second outstanding request. request2.reset(); // Wait for the first request to complete. - scoped_ptr<FetchResult> result2 = callback1.WaitForResult(); + std::unique_ptr<FetchResult> result2 = callback1.WaitForResult(); // Verify the fetch results. result2->VerifySuccess("-cert.crt-\n"); @@ -496,11 +498,12 @@ TEST_F(CertNetFetcherImplTest, DeleteCancels) { ASSERT_TRUE(test_server_.Start()); - scoped_ptr<CertNetFetcherImpl> fetcher(new CertNetFetcherImpl(&context_)); + std::unique_ptr<CertNetFetcherImpl> fetcher( + new CertNetFetcherImpl(&context_)); GURL url(test_server_.GetURL("/slow/certs.p7c?20")); TestFetchCallback callback; - scoped_ptr<CertNetFetcher::Request> request = + std::unique_ptr<CertNetFetcher::Request> request = StartRequest(fetcher.get(), url, callback); // Destroy the fetcher before the outstanding request. @@ -519,27 +522,27 @@ // Issue 3 requests for url1, and 3 requests for url2 TestFetchCallback callback1; - scoped_ptr<CertNetFetcher::Request> request1 = + std::unique_ptr<CertNetFetcher::Request> request1 = StartRequest(&fetcher, url1, callback1); TestFetchCallback callback2; - scoped_ptr<CertNetFetcher::Request> request2 = + std::unique_ptr<CertNetFetcher::Request> request2 = StartRequest(&fetcher, url2, callback2); TestFetchCallback callback3; - scoped_ptr<CertNetFetcher::Request> request3 = + std::unique_ptr<CertNetFetcher::Request> request3 = StartRequest(&fetcher, url1, callback3); TestFetchCallback callback4; - scoped_ptr<CertNetFetcher::Request> request4 = + std::unique_ptr<CertNetFetcher::Request> request4 = StartRequest(&fetcher, url2, callback4); TestFetchCallback callback5; - scoped_ptr<CertNetFetcher::Request> request5 = + std::unique_ptr<CertNetFetcher::Request> request5 = StartRequest(&fetcher, url2, callback5); TestFetchCallback callback6; - scoped_ptr<CertNetFetcher::Request> request6 = + std::unique_ptr<CertNetFetcher::Request> request6 = StartRequest(&fetcher, url1, callback6); // Cancel all but one of the requests for url1. @@ -547,10 +550,10 @@ request3.reset(); // Wait for the remaining requests to finish. - scoped_ptr<FetchResult> result2 = callback2.WaitForResult(); - scoped_ptr<FetchResult> result4 = callback4.WaitForResult(); - scoped_ptr<FetchResult> result5 = callback5.WaitForResult(); - scoped_ptr<FetchResult> result6 = callback6.WaitForResult(); + std::unique_ptr<FetchResult> result2 = callback2.WaitForResult(); + std::unique_ptr<FetchResult> result4 = callback4.WaitForResult(); + std::unique_ptr<FetchResult> result5 = callback5.WaitForResult(); + std::unique_ptr<FetchResult> result6 = callback6.WaitForResult(); // Verify that none of the cancelled requests for url1 completed (since they // were cancelled). @@ -579,19 +582,19 @@ GURL url = test_server_.GetURL("/cert.crt"); - scoped_ptr<CertNetFetcher::Request> request1 = + std::unique_ptr<CertNetFetcher::Request> request1 = StartRequest(&fetcher, url, callback1); request1.reset(); - scoped_ptr<CertNetFetcher::Request> request2 = + std::unique_ptr<CertNetFetcher::Request> request2 = StartRequest(&fetcher, url, callback2); - scoped_ptr<CertNetFetcher::Request> request3 = + std::unique_ptr<CertNetFetcher::Request> request3 = StartRequest(&fetcher, url, callback3); request3.reset(); // All but |request2| were canceled. - scoped_ptr<FetchResult> result = callback2.WaitForResult(); + std::unique_ptr<FetchResult> result = callback2.WaitForResult(); result->VerifySuccess("-cert.crt-\n"); @@ -608,7 +611,7 @@ CertNetFetcherImpl fetcher(&context_); TestFetchCallback callback[3]; - scoped_ptr<CertNetFetcher::Request> request[3]; + std::unique_ptr<CertNetFetcher::Request> request[3]; GURL url = test_server_.GetURL("/cert.crt"); @@ -640,7 +643,7 @@ GURL url = test_server_.GetURL("/cert.crt"); TestFetchCallback callback[4]; - scoped_ptr<CertNetFetcher::Request> reqs[4]; + std::unique_ptr<CertNetFetcher::Request> reqs[4]; callback[1].set_extra_closure(base::Bind(DeleteCertNetFetcher, fetcher)); for (size_t i = 0; i < arraysize(callback); ++i) @@ -659,7 +662,7 @@ void FetchRequest(CertNetFetcher* fetcher, const GURL& url, TestFetchCallback* callback, - scoped_ptr<CertNetFetcher::Request>* request) { + std::unique_ptr<CertNetFetcher::Request>* request) { *request = StartRequest(fetcher, url, *callback); } @@ -672,7 +675,7 @@ GURL url = test_server_.GetURL("/cert.crt"); TestFetchCallback callback[5]; - scoped_ptr<CertNetFetcher::Request> req[5]; + std::unique_ptr<CertNetFetcher::Request> req[5]; callback[1].set_extra_closure( base::Bind(FetchRequest, &fetcher, url, &callback[4], &req[4])); @@ -682,7 +685,7 @@ EXPECT_EQ(1, network_delegate_.created_requests()); for (size_t i = 0; i < arraysize(callback); ++i) { - scoped_ptr<FetchResult> result = callback[i].WaitForResult(); + std::unique_ptr<FetchResult> result = callback[i].WaitForResult(); result->VerifySuccess("-cert.crt-\n"); } @@ -691,7 +694,7 @@ EXPECT_EQ(2, network_delegate_.created_requests()); } -void CancelRequest(scoped_ptr<CertNetFetcher::Request>* request) { +void CancelRequest(std::unique_ptr<CertNetFetcher::Request>* request) { request->reset(); } @@ -704,7 +707,7 @@ GURL url = test_server_.GetURL("/cert.crt"); TestFetchCallback callback[4]; - scoped_ptr<CertNetFetcher::Request> request[4]; + std::unique_ptr<CertNetFetcher::Request> request[4]; for (size_t i = 0; i < arraysize(callback); ++i) request[i] = StartRequest(&fetcher, url, callback[i]); @@ -718,7 +721,7 @@ if (i == 2) continue; - scoped_ptr<FetchResult> result = callback[i].WaitForResult(); + std::unique_ptr<FetchResult> result = callback[i].WaitForResult(); result->VerifySuccess("-cert.crt-\n"); } @@ -736,11 +739,11 @@ GURL url = test_server_.GetURL("/cert.crt"); TestFetchCallback callback1; - scoped_ptr<CertNetFetcher::Request> request1 = + std::unique_ptr<CertNetFetcher::Request> request1 = StartRequest(&fetcher, url, callback1); TestFetchCallback callback2; - scoped_ptr<CertNetFetcher::Request> request2 = + std::unique_ptr<CertNetFetcher::Request> request2 = StartRequest(&fetcher, url, callback1); // Cancel request2 when the callback for request1 runs. @@ -748,7 +751,7 @@ EXPECT_EQ(1, network_delegate_.created_requests()); - scoped_ptr<FetchResult> result = callback1.WaitForResult(); + std::unique_ptr<FetchResult> result = callback1.WaitForResult(); result->VerifySuccess("-cert.crt-\n"); // request2 was cancelled.
diff --git a/net/cert_net/nss_ocsp.cc b/net/cert_net/nss_ocsp.cc index 40b79da..50edb930 100644 --- a/net/cert_net/nss_ocsp.cc +++ b/net/cert_net/nss_ocsp.cc
@@ -11,7 +11,9 @@ #include <ocsp.h> #include <pthread.h> #include <secerr.h> + #include <algorithm> +#include <memory> #include <string> #include <utility> @@ -21,7 +23,6 @@ #include "base/location.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/histogram_macros.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" @@ -407,7 +408,7 @@ extra_request_headers_.SetHeader( HttpRequestHeaders::kContentType, upload_content_type_); - scoped_ptr<UploadElementReader> reader(new UploadBytesElementReader( + std::unique_ptr<UploadElementReader> reader(new UploadBytesElementReader( upload_content_.data(), upload_content_.size())); request_->set_upload( ElementsUploadDataStream::CreateWithReader(std::move(reader), 0)); @@ -422,7 +423,7 @@ GURL url_; // The URL we eventually wound up at std::string http_request_method_; base::TimeDelta timeout_; // The timeout for OCSP - scoped_ptr<URLRequest> request_; // The actual request this wraps + std::unique_ptr<URLRequest> request_; // The actual request this wraps scoped_refptr<IOBuffer> buffer_; // Read buffer HttpRequestHeaders extra_request_headers_;
diff --git a/net/cert_net/nss_ocsp_unittest.cc b/net/cert_net/nss_ocsp_unittest.cc index e4367cc..21ccb09 100644 --- a/net/cert_net/nss_ocsp_unittest.cc +++ b/net/cert_net/nss_ocsp_unittest.cc
@@ -88,7 +88,7 @@ // Ownership of |handler| is transferred to the URLRequestFilter, but // hold onto the original pointer in order to access |request_count()|. - scoped_ptr<AiaResponseHandler> handler( + std::unique_ptr<AiaResponseHandler> handler( new AiaResponseHandler(kAiaHeaders, file_contents)); handler_ = handler.get(); @@ -121,7 +121,7 @@ TestURLRequestContext context_; AiaResponseHandler* handler_; scoped_refptr<CertVerifyProc> verify_proc_; - scoped_ptr<CertVerifier> verifier_; + std::unique_ptr<CertVerifier> verifier_; }; // Tests that when using NSS to verify certificates, and IO is enabled, @@ -140,7 +140,7 @@ CertVerifyResult verify_result; TestCompletionCallback test_callback; - scoped_ptr<CertVerifier::Request> request; + std::unique_ptr<CertVerifier::Request> request; int flags = CertVerifier::VERIFY_CERT_IO_ENABLED; int error = verifier()->Verify(
diff --git a/net/cookies/canonical_cookie.cc b/net/cookies/canonical_cookie.cc index bce2b54..1572cc1 100644 --- a/net/cookies/canonical_cookie.cc +++ b/net/cookies/canonical_cookie.cc
@@ -46,6 +46,7 @@ #include "base/format_macros.h" #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" @@ -192,7 +193,7 @@ } // static -scoped_ptr<CanonicalCookie> CanonicalCookie::Create( +std::unique_ptr<CanonicalCookie> CanonicalCookie::Create( const GURL& url, const std::string& cookie_line, const base::Time& creation_time, @@ -245,7 +246,7 @@ return nullptr; } - return make_scoped_ptr(new CanonicalCookie( + return base::WrapUnique(new CanonicalCookie( url, parsed_cookie.Name(), parsed_cookie.Value(), cookie_domain, cookie_path, creation_time, cookie_expires, creation_time, parsed_cookie.IsSecure(), parsed_cookie.IsHttpOnly(), @@ -253,7 +254,7 @@ } // static -scoped_ptr<CanonicalCookie> CanonicalCookie::Create( +std::unique_ptr<CanonicalCookie> CanonicalCookie::Create( const GURL& url, const std::string& name, const std::string& value, @@ -304,7 +305,7 @@ cookie_path = std::string(canon_path.data() + canon_path_component.begin, canon_path_component.len); - return make_scoped_ptr(new CanonicalCookie( + return base::WrapUnique(new CanonicalCookie( url, parsed_name, parsed_value, cookie_domain, cookie_path, creation, expiration, creation, secure, http_only, same_site, priority)); }
diff --git a/net/cookies/canonical_cookie.h b/net/cookies/canonical_cookie.h index f95501c7..254e1173 100644 --- a/net/cookies/canonical_cookie.h +++ b/net/cookies/canonical_cookie.h
@@ -5,11 +5,11 @@ #ifndef NET_COOKIES_CANONICAL_COOKIE_H_ #define NET_COOKIES_CANONICAL_COOKIE_H_ +#include <memory> #include <string> #include <vector> #include "base/gtest_prod_util.h" -#include "base/memory/scoped_ptr.h" #include "base/time/time.h" #include "net/base/net_export.h" #include "net/cookies/cookie_constants.h" @@ -50,26 +50,27 @@ // Creates a new |CanonicalCookie| from the |cookie_line| and the // |creation_time|. Canonicalizes and validates inputs. May return NULL if // an attribute value is invalid. - static scoped_ptr<CanonicalCookie> Create(const GURL& url, - const std::string& cookie_line, - const base::Time& creation_time, - const CookieOptions& options); + static std::unique_ptr<CanonicalCookie> Create( + const GURL& url, + const std::string& cookie_line, + const base::Time& creation_time, + const CookieOptions& options); // Creates a canonical cookie from unparsed attribute values. // Canonicalizes and validates inputs. May return NULL if an attribute // value is invalid. - static scoped_ptr<CanonicalCookie> Create(const GURL& url, - const std::string& name, - const std::string& value, - const std::string& domain, - const std::string& path, - const base::Time& creation, - const base::Time& expiration, - bool secure, - bool http_only, - CookieSameSite same_site, - bool enforce_strict_secure, - CookiePriority priority); + static std::unique_ptr<CanonicalCookie> Create(const GURL& url, + const std::string& name, + const std::string& value, + const std::string& domain, + const std::string& path, + const base::Time& creation, + const base::Time& expiration, + bool secure, + bool http_only, + CookieSameSite same_site, + bool enforce_strict_secure, + CookiePriority priority); const GURL& Source() const { return source_; } const std::string& Name() const { return name_; }
diff --git a/net/cookies/canonical_cookie_unittest.cc b/net/cookies/canonical_cookie_unittest.cc index 80b772e..9bdfc16 100644 --- a/net/cookies/canonical_cookie_unittest.cc +++ b/net/cookies/canonical_cookie_unittest.cc
@@ -4,7 +4,8 @@ #include "net/cookies/canonical_cookie.h" -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "base/test/histogram_tester.h" #include "net/cookies/cookie_constants.h" #include "net/cookies/cookie_options.h" @@ -49,7 +50,7 @@ base::Time creation_time = base::Time::Now(); CookieOptions options; - scoped_ptr<CanonicalCookie> cookie( + std::unique_ptr<CanonicalCookie> cookie( CanonicalCookie::Create(url, "A=2", creation_time, options)); EXPECT_EQ(url.GetOrigin(), cookie->Source()); EXPECT_EQ("A", cookie->Name()); @@ -126,7 +127,7 @@ TEST(CanonicalCookieTest, CreateInvalidSameSite) { GURL url("http://www.example.com/test/foo.html"); base::Time now = base::Time::Now(); - scoped_ptr<CanonicalCookie> cookie; + std::unique_ptr<CanonicalCookie> cookie; CookieOptions options; // Invalid 'SameSite' attribute values. @@ -147,7 +148,7 @@ std::string cookie_line = "ACSTM=20130308043820420042; path=/; domain=ipdl.inpit.go.jp; Expires="; - scoped_ptr<CanonicalCookie> cookie( + std::unique_ptr<CanonicalCookie> cookie( CanonicalCookie::Create(url, cookie_line, creation_time, options)); EXPECT_TRUE(cookie.get()); EXPECT_FALSE(cookie->IsPersistent()); @@ -185,14 +186,14 @@ CookieSameSite same_site(CookieSameSite::NO_RESTRICTION); // Test that a cookie is equivalent to itself. - scoped_ptr<CanonicalCookie> cookie(new CanonicalCookie( + std::unique_ptr<CanonicalCookie> cookie(new CanonicalCookie( url, cookie_name, cookie_value, cookie_domain, cookie_path, creation_time, expiration_time, last_access_time, secure, httponly, same_site, COOKIE_PRIORITY_MEDIUM)); EXPECT_TRUE(cookie->IsEquivalent(*cookie)); // Test that two identical cookies are equivalent. - scoped_ptr<CanonicalCookie> other_cookie(new CanonicalCookie( + std::unique_ptr<CanonicalCookie> other_cookie(new CanonicalCookie( url, cookie_name, cookie_value, cookie_domain, cookie_path, creation_time, expiration_time, last_access_time, secure, httponly, same_site, COOKIE_PRIORITY_MEDIUM)); @@ -275,14 +276,14 @@ CookieSameSite same_site(CookieSameSite::NO_RESTRICTION); // Test that a cookie is equivalent to itself. - scoped_ptr<CanonicalCookie> cookie(new CanonicalCookie( + std::unique_ptr<CanonicalCookie> cookie(new CanonicalCookie( url, cookie_name, cookie_value, cookie_domain, cookie_path, creation_time, expiration_time, last_access_time, secure, httponly, same_site, COOKIE_PRIORITY_MEDIUM)); EXPECT_TRUE(cookie->IsEquivalentForSecureCookieMatching(*cookie)); // Test that two identical cookies are equivalent. - scoped_ptr<CanonicalCookie> other_cookie(new CanonicalCookie( + std::unique_ptr<CanonicalCookie> other_cookie(new CanonicalCookie( url, cookie_name, cookie_value, cookie_domain, cookie_path, creation_time, expiration_time, last_access_time, secure, httponly, same_site, COOKIE_PRIORITY_MEDIUM)); @@ -364,7 +365,7 @@ base::Time creation_time = base::Time::Now(); CookieOptions options; - scoped_ptr<CanonicalCookie> cookie( + std::unique_ptr<CanonicalCookie> cookie( CanonicalCookie::Create(url, "A=2", creation_time, options)); EXPECT_TRUE(cookie->IsHostCookie()); EXPECT_TRUE(cookie->IsDomainMatch("www.example.com")); @@ -395,7 +396,7 @@ base::Time creation_time = base::Time::Now(); CookieOptions options; - scoped_ptr<CanonicalCookie> cookie(CanonicalCookie::Create( + std::unique_ptr<CanonicalCookie> cookie(CanonicalCookie::Create( GURL("http://www.example.com"), "A=2", creation_time, options)); EXPECT_TRUE(cookie->IsOnPath("/")); EXPECT_TRUE(cookie->IsOnPath("/test")); @@ -417,7 +418,7 @@ base::Time creation_time = base::Time::Now(); CookieOptions options; - scoped_ptr<CanonicalCookie> cookie( + std::unique_ptr<CanonicalCookie> cookie( CanonicalCookie::Create(url, "A=2", creation_time, options)); EXPECT_TRUE(cookie->IncludeForRequestURL(url, options)); EXPECT_TRUE(cookie->IncludeForRequestURL( @@ -460,7 +461,7 @@ GURL url("https://example.test"); base::Time creation_time = base::Time::Now(); CookieOptions options; - scoped_ptr<CanonicalCookie> cookie; + std::unique_ptr<CanonicalCookie> cookie; // `SameSite=Strict` cookies are included for a URL only if the options' // SameSiteCookieMode is INCLUDE_STRICT_AND_LAX. @@ -497,11 +498,11 @@ GURL url("http://www.example.com"); base::Time creation_time = base::Time::Now(); CookieOptions options; - scoped_ptr<CanonicalCookie> cookie( + std::unique_ptr<CanonicalCookie> cookie( CanonicalCookie::Create(url, "a=b", creation_time, options)); - scoped_ptr<CanonicalCookie> cookie_different_path( + std::unique_ptr<CanonicalCookie> cookie_different_path( CanonicalCookie::Create(url, "a=b; path=/foo", creation_time, options)); - scoped_ptr<CanonicalCookie> cookie_different_value( + std::unique_ptr<CanonicalCookie> cookie_different_value( CanonicalCookie::Create(url, "a=c", creation_time, options)); // Cookie is equivalent to itself. @@ -524,11 +525,11 @@ GURL url("http://www.example.com"); base::Time creation_time = base::Time::Now(); CookieOptions options; - scoped_ptr<CanonicalCookie> cookie( + std::unique_ptr<CanonicalCookie> cookie( CanonicalCookie::Create(url, "a=b", creation_time, options)); - scoped_ptr<CanonicalCookie> cookie_different_path( + std::unique_ptr<CanonicalCookie> cookie_different_path( CanonicalCookie::Create(url, "a=b; path=/foo", creation_time, options)); - scoped_ptr<CanonicalCookie> cookie_different_value( + std::unique_ptr<CanonicalCookie> cookie_different_value( CanonicalCookie::Create(url, "a=c", creation_time, options)); // Cookie is equivalent to itself. @@ -638,13 +639,13 @@ CookieOptions options; options.set_enforce_strict_secure(); - scoped_ptr<CanonicalCookie> http_cookie_no_secure( + std::unique_ptr<CanonicalCookie> http_cookie_no_secure( CanonicalCookie::Create(http_url, "a=b", creation_time, options)); - scoped_ptr<CanonicalCookie> http_cookie_secure( + std::unique_ptr<CanonicalCookie> http_cookie_secure( CanonicalCookie::Create(http_url, "a=b; Secure", creation_time, options)); - scoped_ptr<CanonicalCookie> https_cookie_no_secure( + std::unique_ptr<CanonicalCookie> https_cookie_no_secure( CanonicalCookie::Create(https_url, "a=b", creation_time, options)); - scoped_ptr<CanonicalCookie> https_cookie_secure(CanonicalCookie::Create( + std::unique_ptr<CanonicalCookie> https_cookie_secure(CanonicalCookie::Create( https_url, "a=b; Secure", creation_time, options)); EXPECT_TRUE(http_cookie_no_secure.get()); @@ -652,19 +653,19 @@ EXPECT_TRUE(https_cookie_no_secure.get()); EXPECT_TRUE(https_cookie_secure.get()); - scoped_ptr<CanonicalCookie> http_cookie_no_secure_extended( + std::unique_ptr<CanonicalCookie> http_cookie_no_secure_extended( CanonicalCookie::Create( http_url, "a", "b", "", "", creation_time, creation_time, false, false, CookieSameSite::STRICT_MODE, true, COOKIE_PRIORITY_DEFAULT)); - scoped_ptr<CanonicalCookie> http_cookie_secure_extended( + std::unique_ptr<CanonicalCookie> http_cookie_secure_extended( CanonicalCookie::Create( http_url, "a", "b", "", "", creation_time, creation_time, true, false, CookieSameSite::STRICT_MODE, true, COOKIE_PRIORITY_DEFAULT)); - scoped_ptr<CanonicalCookie> https_cookie_no_secure_extended( + std::unique_ptr<CanonicalCookie> https_cookie_no_secure_extended( CanonicalCookie::Create( https_url, "a", "b", "", "", creation_time, creation_time, false, false, CookieSameSite::STRICT_MODE, true, COOKIE_PRIORITY_DEFAULT)); - scoped_ptr<CanonicalCookie> https_cookie_secure_extended( + std::unique_ptr<CanonicalCookie> https_cookie_secure_extended( CanonicalCookie::Create( https_url, "a", "b", "", "", creation_time, creation_time, true, false, CookieSameSite::STRICT_MODE, true, COOKIE_PRIORITY_DEFAULT));
diff --git a/net/cookies/cookie_monster.cc b/net/cookies/cookie_monster.cc index 7846bc3..e208d33 100644 --- a/net/cookies/cookie_monster.cc +++ b/net/cookies/cookie_monster.cc
@@ -46,6 +46,7 @@ #include <algorithm> #include <functional> +#include <memory> #include <set> #include "base/bind.h" @@ -53,7 +54,7 @@ #include "base/location.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram.h" #include "base/profiler/scoped_tracker.h" @@ -977,7 +978,7 @@ const int CookieMonster::kDefaultCookieableSchemesCount = arraysize(kDefaultCookieableSchemes); -scoped_ptr<CookieStore::CookieChangedSubscription> +std::unique_ptr<CookieStore::CookieChangedSubscription> CookieMonster::AddCallbackForCookie(const GURL& gurl, const std::string& name, const CookieChangedCallback& callback) { @@ -1036,7 +1037,7 @@ last_time_seen_ = actual_creation_time; } - scoped_ptr<CanonicalCookie> cc(CanonicalCookie::Create( + std::unique_ptr<CanonicalCookie> cc(CanonicalCookie::Create( url, name, value, domain, path, actual_creation_time, expiration_time, secure, http_only, same_site, enforce_strict_secure, priority)); @@ -1718,7 +1719,7 @@ last_time_seen_ = creation_time; } - scoped_ptr<CanonicalCookie> cc( + std::unique_ptr<CanonicalCookie> cc( CanonicalCookie::Create(url, cookie_line, creation_time, options)); if (!cc.get()) { @@ -1728,7 +1729,7 @@ return SetCanonicalCookie(std::move(cc), options); } -bool CookieMonster::SetCanonicalCookie(scoped_ptr<CanonicalCookie> cc, +bool CookieMonster::SetCanonicalCookie(std::unique_ptr<CanonicalCookie> cc, const CookieOptions& options) { DCHECK(thread_checker_.CalledOnValidThread()); @@ -1786,7 +1787,7 @@ options.set_include_httponly(); for (const auto& cookie : list) { - if (!SetCanonicalCookie(make_scoped_ptr(new CanonicalCookie(cookie)), + if (!SetCanonicalCookie(base::WrapUnique(new CanonicalCookie(cookie)), options)) { return false; }
diff --git a/net/cookies/cookie_monster.h b/net/cookies/cookie_monster.h index 4d36c62..b31ac6d 100644 --- a/net/cookies/cookie_monster.h +++ b/net/cookies/cookie_monster.h
@@ -12,6 +12,7 @@ #include <deque> #include <map> +#include <memory> #include <queue> #include <set> #include <string> @@ -23,7 +24,6 @@ #include "base/macros.h" #include "base/memory/linked_ptr.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" #include "base/time/time.h" @@ -210,7 +210,7 @@ static const char* const kDefaultCookieableSchemes[]; static const int kDefaultCookieableSchemesCount; - scoped_ptr<CookieChangedSubscription> AddCallbackForCookie( + std::unique_ptr<CookieChangedSubscription> AddCallbackForCookie( const GURL& url, const std::string& name, const CookieChangedCallback& callback) override; @@ -519,7 +519,7 @@ // Helper function that sets a canonical cookie, deleting equivalents and // performing garbage collection. - bool SetCanonicalCookie(scoped_ptr<CanonicalCookie> cc, + bool SetCanonicalCookie(std::unique_ptr<CanonicalCookie> cc, const CookieOptions& options); // Helper function calling SetCanonicalCookie() for all cookies in |list|.
diff --git a/net/cookies/cookie_monster_perftest.cc b/net/cookies/cookie_monster_perftest.cc index 1dcb276..c56bef67 100644 --- a/net/cookies/cookie_monster_perftest.cc +++ b/net/cookies/cookie_monster_perftest.cc
@@ -3,10 +3,10 @@ // found in the LICENSE file. #include <algorithm> +#include <memory> #include "base/bind.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" @@ -35,7 +35,7 @@ CookieMonsterTest() : message_loop_(new base::MessageLoopForIO()) {} private: - scoped_ptr<base::MessageLoop> message_loop_; + std::unique_ptr<base::MessageLoop> message_loop_; }; class BaseCallback { @@ -121,7 +121,7 @@ } TEST_F(CookieMonsterTest, TestAddCookiesOnSingleHost) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); std::vector<std::string> cookies; for (int i = 0; i < kNumCookies; i++) { cookies.push_back(base::StringPrintf("a%03d=b", i)); @@ -154,7 +154,7 @@ } TEST_F(CookieMonsterTest, TestAddCookieOnManyHosts) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); std::string cookie(kCookieLine); std::vector<GURL> gurls; // just wanna have ffffuunnn for (int i = 0; i < kNumCookies; ++i) { @@ -187,7 +187,7 @@ } TEST_F(CookieMonsterTest, TestDomainTree) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); GetCookiesCallback getCookiesCallback; SetCookieCallback setCookieCallback; const char domain_cookie_format_tree[] = "a=b; domain=%s"; @@ -240,7 +240,7 @@ } TEST_F(CookieMonsterTest, TestDomainLine) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); SetCookieCallback setCookieCallback; GetCookiesCallback getCookiesCallback; std::vector<std::string> domain_list; @@ -301,7 +301,7 @@ store->SetLoadExpectation(true, initial_cookies); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); // Import will happen on first access. GURL gurl("www.google.com"); @@ -315,7 +315,7 @@ } TEST_F(CookieMonsterTest, TestGetKey) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); base::PerfTimeLogger timer("Cookie_monster_get_key"); for (int i = 0; i < kNumCookies; i++) cm->GetKey("www.google.com"); @@ -371,7 +371,7 @@ }; for (int ci = 0; ci < static_cast<int>(arraysize(test_cases)); ++ci) { const TestCase& test_case(test_cases[ci]); - scoped_ptr<CookieMonster> cm = CreateMonsterFromStoreForGC( + std::unique_ptr<CookieMonster> cm = CreateMonsterFromStoreForGC( test_case.num_cookies, test_case.num_old_cookies, 0, 0, CookieMonster::kSafeFromGlobalPurgeDays * 2);
diff --git a/net/cookies/cookie_monster_store_test.cc b/net/cookies/cookie_monster_store_test.cc index 4573d4a..5fef35c 100644 --- a/net/cookies/cookie_monster_store_test.cc +++ b/net/cookies/cookie_monster_store_test.cc
@@ -6,6 +6,7 @@ #include "base/bind.h" #include "base/location.h" +#include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/strings/stringprintf.h" #include "base/thread_task_runner_handle.h" @@ -123,7 +124,7 @@ MockCookieMonsterDelegate::~MockCookieMonsterDelegate() { } -scoped_ptr<CanonicalCookie> BuildCanonicalCookie( +std::unique_ptr<CanonicalCookie> BuildCanonicalCookie( const GURL& url, const std::string& cookie_line, const base::Time& creation_time) { @@ -151,7 +152,7 @@ const std::string& cookie_line, const base::Time& creation_time, std::vector<CanonicalCookie*>* out_list) { - scoped_ptr<CanonicalCookie> cookie( + std::unique_ptr<CanonicalCookie> cookie( BuildCanonicalCookie(url, cookie_line, creation_time)); out_list->push_back(cookie.release()); @@ -219,7 +220,7 @@ void MockSimplePersistentCookieStore::SetForceKeepSessionState() { } -scoped_ptr<CookieMonster> CreateMonsterFromStoreForGC( +std::unique_ptr<CookieMonster> CreateMonsterFromStoreForGC( int num_secure_cookies, int num_old_secure_cookies, int num_non_secure_cookies, @@ -258,7 +259,7 @@ store->AddCookie(cc); } - return make_scoped_ptr(new CookieMonster(store.get(), nullptr)); + return base::WrapUnique(new CookieMonster(store.get(), nullptr)); } MockSimplePersistentCookieStore::~MockSimplePersistentCookieStore() {
diff --git a/net/cookies/cookie_monster_store_test.h b/net/cookies/cookie_monster_store_test.h index aac83f8..9145e184 100644 --- a/net/cookies/cookie_monster_store_test.h +++ b/net/cookies/cookie_monster_store_test.h
@@ -13,12 +13,12 @@ #include <stdint.h> #include <map> +#include <memory> #include <string> #include <utility> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_monster.h" @@ -168,7 +168,7 @@ }; // Helper to build a single CanonicalCookie. -scoped_ptr<CanonicalCookie> BuildCanonicalCookie( +std::unique_ptr<CanonicalCookie> BuildCanonicalCookie( const GURL& url, const std::string& cookie_line, const base::Time& creation_time); @@ -223,7 +223,7 @@ // will be marked secure and non-secure, respectively. Do two SetCookies(). // Return whether each of the two SetCookies() took longer than |gc_perf_micros| // to complete, and how many cookie were left in the store afterwards. -scoped_ptr<CookieMonster> CreateMonsterFromStoreForGC( +std::unique_ptr<CookieMonster> CreateMonsterFromStoreForGC( int num_secure_cookies, int num_old_secure_cookies, int num_non_secure_cookies,
diff --git a/net/cookies/cookie_monster_unittest.cc b/net/cookies/cookie_monster_unittest.cc index 8abff91..66cbc08 100644 --- a/net/cookies/cookie_monster_unittest.cc +++ b/net/cookies/cookie_monster_unittest.cc
@@ -2,16 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "net/cookies/cookie_store_unittest.h" +#include "net/cookies/cookie_monster.h" #include <algorithm> +#include <memory> #include <string> #include <vector> #include "base/bind.h" #include "base/location.h" +#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/metrics/histogram.h" #include "base/metrics/histogram_samples.h" @@ -27,8 +28,8 @@ #include "base/time/time.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_constants.h" -#include "net/cookies/cookie_monster.h" #include "net/cookies/cookie_monster_store_test.h" // For CookieStore mock +#include "net/cookies/cookie_store_unittest.h" #include "net/cookies/cookie_util.h" #include "net/cookies/parsed_cookie.h" #include "testing/gmock/include/gmock/gmock.h" @@ -96,8 +97,8 @@ } struct CookieMonsterTestTraits { - static scoped_ptr<CookieStore> Create() { - return make_scoped_ptr(new CookieMonster(nullptr, nullptr)); + static std::unique_ptr<CookieStore> Create() { + return base::WrapUnique(new CookieMonster(nullptr, nullptr)); } static const bool supports_http_only = true; @@ -110,8 +111,8 @@ }; struct CookieMonsterEnforcingStrictSecure { - static scoped_ptr<CookieStore> Create() { - return make_scoped_ptr(new CookieMonster(nullptr, nullptr)); + static std::unique_ptr<CookieStore> Create() { + return base::WrapUnique(new CookieMonster(nullptr, nullptr)); } static const bool supports_http_only = true; @@ -309,7 +310,7 @@ (domain_max_cookies + domain_purge_cookies) * 2; // Add a bunch of cookies on a single host, should purge them. { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); for (int i = 0; i < more_than_enough_cookies; ++i) { std::string cookie = base::StringPrintf("a%03d=b", i); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), cookie)); @@ -327,7 +328,7 @@ // between them. We shouldn't go above kDomainMaxCookies for both together. GURL url_google_specific(http_www_google_.Format("http://www.gmail.%D")); { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); for (int i = 0; i < more_than_enough_cookies; ++i) { std::string cookie_general = base::StringPrintf("a%03d=b", i); EXPECT_TRUE( @@ -471,7 +472,7 @@ size_t expected_secure_cookies, size_t expected_non_secure_cookies, const AltHosts* alt_host_entries) { - scoped_ptr<CookieMonster> cm; + std::unique_ptr<CookieMonster> cm; if (alt_host_entries == nullptr) { cm.reset(new CookieMonster(nullptr, nullptr)); @@ -522,7 +523,7 @@ DCHECK_EQ(50U, CookieMonster::kDomainCookiesQuotaMedium); DCHECK_EQ(70U, CookieMonster::kDomainCookiesQuotaHigh); - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); // Each test case adds 181 cookies, so 31 cookies are evicted. // Cookie same priority, repeated for each priority. @@ -829,7 +830,7 @@ // Indicates whether ExpectLoadCall() has been called. bool expect_load_called_; // Stores the CookieMonster under test. - scoped_ptr<CookieMonster> cookie_monster_; + std::unique_ptr<CookieMonster> cookie_monster_; // Stores the mock PersistentCookieStore. scoped_refptr<NewMockPersistentCookieStore> persistent_store_; }; @@ -1100,7 +1101,7 @@ TEST_F(DeferredCookieTaskTest, DeferredDeleteCanonicalCookie) { std::vector<CanonicalCookie*> cookies; - scoped_ptr<CanonicalCookie> cookie = BuildCanonicalCookie( + std::unique_ptr<CanonicalCookie> cookie = BuildCanonicalCookie( http_www_google_.url(), "X=1; path=/", base::Time::Now()); MockDeleteCallback delete_cookie_callback; @@ -1174,7 +1175,7 @@ TEST_F(CookieMonsterTest, TestCookieDeleteAll) { scoped_refptr<MockPersistentCookieStore> store(new MockPersistentCookieStore); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); CookieOptions options; options.set_include_httponly(); @@ -1207,7 +1208,7 @@ } TEST_F(CookieMonsterTest, TestCookieDeleteAllCreatedBetweenTimestamps) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); Time now = Time::Now(); // Nothing has been added so nothing should be deleted. @@ -1248,7 +1249,7 @@ TEST_F(CookieMonsterTest, TestCookieDeleteAllCreatedBetweenTimestampsWithPredicate) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); Time now = Time::Now(); CanonicalCookie test_cookie; @@ -1298,7 +1299,7 @@ DeleteAllCreatedBetweenWithPredicate( cm.get(), now - TimeDelta::FromDays(2), now, true_predicate)); // Check our cookie values. - scoped_ptr<CanonicalCookie> expected_cookie = + std::unique_ptr<CanonicalCookie> expected_cookie = CanonicalCookie::Create(http_www_google_.url(), "T-1=Yesterday", now - TimeDelta::FromDays(1), CookieOptions()); EXPECT_THAT(test_cookie, CookieEquals(*expected_cookie)) @@ -1333,7 +1334,7 @@ static const int kAccessDelayMs = kLastAccessThresholdMilliseconds + 20; TEST_F(CookieMonsterTest, TestLastAccess) { - scoped_ptr<CookieMonster> cm( + std::unique_ptr<CookieMonster> cm( new CookieMonster(nullptr, nullptr, kLastAccessThresholdMilliseconds)); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=B")); @@ -1381,8 +1382,8 @@ } TEST_F(CookieMonsterTest, SetCookieableSchemes) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); - scoped_ptr<CookieMonster> cm_foo(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm_foo(new CookieMonster(nullptr, nullptr)); // Only cm_foo should allow foo:// cookies. std::vector<std::string> schemes; @@ -1399,7 +1400,7 @@ } TEST_F(CookieMonsterTest, GetAllCookiesForURL) { - scoped_ptr<CookieMonster> cm( + std::unique_ptr<CookieMonster> cm( new CookieMonster(nullptr, nullptr, kLastAccessThresholdMilliseconds)); // Create an httponly cookie. @@ -1468,7 +1469,7 @@ } TEST_F(CookieMonsterTest, GetAllCookiesForURLPathMatching) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); CookieOptions options; EXPECT_TRUE(SetCookieWithOptions(cm.get(), www_google_foo_.url(), @@ -1506,7 +1507,7 @@ } TEST_F(CookieMonsterTest, CookieSorting) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "B=B1; path=/")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "B=B2; path=/foo")); @@ -1536,7 +1537,7 @@ } TEST_F(CookieMonsterTest, DeleteCookieByName) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=A1; path=/")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=A2; path=/foo")); @@ -1612,7 +1613,7 @@ // Inject our initial cookies into the mock PersistentCookieStore. store->SetLoadExpectation(true, initial_cookies); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); // Verify that duplicates were not imported for path "/". // (If this had failed, GetCookies() would have also returned X=1, X=2, X=4). @@ -1668,7 +1669,7 @@ // Inject our initial cookies into the mock PersistentCookieStore. store->SetLoadExpectation(true, initial_cookies); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); CookieList list(GetAllCookies(cm.get())); EXPECT_EQ(2U, list.size()); @@ -1684,7 +1685,8 @@ scoped_refptr<MockPersistentCookieStore> store(new MockPersistentCookieStore); scoped_refptr<MockCookieMonsterDelegate> delegate( new MockCookieMonsterDelegate); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), delegate.get())); + std::unique_ptr<CookieMonster> cm( + new CookieMonster(store.get(), delegate.get())); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=B")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "C=D")); @@ -1764,7 +1766,7 @@ TEST_F(CookieMonsterTest, PredicateSeesAllCookies) { const std::string kTrueValue = "A"; - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); // We test that we can see all cookies with our predicated. This includes // host, http_only, host secure, and all domain cookies. CookiePredicate value_matcher = base::Bind(&CookieValuePredicate, kTrueValue); @@ -1784,7 +1786,7 @@ } TEST_F(CookieMonsterTest, UniqueCreationTime) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); CookieOptions options; // Add in three cookies through every public interface to the @@ -1847,7 +1849,7 @@ // Mainly a test of GetEffectiveDomain, or more specifically, of the // expected behavior of GetEffectiveDomain within the CookieMonster. TEST_F(CookieMonsterTest, GetKey) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); // This test is really only interesting if GetKey() actually does something. EXPECT_EQ("google.com", cm->GetKey("www.google.com")); @@ -1891,7 +1893,8 @@ // Create new cookies and flush them to the store. { - scoped_ptr<CookieMonster> cmout(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cmout( + new CookieMonster(store.get(), nullptr)); for (const CookiesInputInfo* p = input_info; p < &input_info[arraysize(input_info)]; p++) { EXPECT_TRUE(SetCookieWithDetails( @@ -1907,7 +1910,8 @@ // Create a new cookie monster and make sure that everything is correct { - scoped_ptr<CookieMonster> cmin(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cmin( + new CookieMonster(store.get(), nullptr)); CookieList cookies(GetAllCookies(cmin.get())); ASSERT_EQ(2u, cookies.size()); // Ordering is path length, then creation time. So second cookie @@ -1937,7 +1941,7 @@ TEST_F(CookieMonsterTest, CookieListOrdering) { // Put a random set of cookies into a monster and make sure // they're returned in the right order. - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); EXPECT_TRUE( SetCookie(cm.get(), GURL("http://d.c.b.a.google.com/aa/x.html"), "c=1")); EXPECT_TRUE(SetCookie(cm.get(), GURL("http://b.a.google.com/aa/bb/cc/x.html"), @@ -1994,7 +1998,7 @@ // First we check to make sure that a whole lot of recent cookies // doesn't get rid of anything after garbage collection is checked for. { - scoped_ptr<CookieMonster> cm( + std::unique_ptr<CookieMonster> cm( CreateMonsterForGC(CookieMonster::kMaxCookies * 2)); EXPECT_EQ(CookieMonster::kMaxCookies * 2, GetAllCookies(cm.get()).size()); SetCookie(cm.get(), GURL("http://newdomain.com"), "b=2"); @@ -2036,7 +2040,7 @@ for (int ci = 0; ci < static_cast<int>(arraysize(test_cases)); ++ci) { const TestCase* test_case = &test_cases[ci]; - scoped_ptr<CookieMonster> cm = CreateMonsterFromStoreForGC( + std::unique_ptr<CookieMonster> cm = CreateMonsterFromStoreForGC( test_case->num_cookies, test_case->num_old_cookies, 0, 0, CookieMonster::kSafeFromGlobalPurgeDays * 2); EXPECT_EQ(test_case->expected_initial_cookies, @@ -2057,7 +2061,7 @@ scoped_refptr<MockPersistentCookieStore> store(new MockPersistentCookieStore); store->set_store_load_commands(true); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); // Get all cookies task that queues a task to set a cookie when executed. ResultSavingCookieCallback<bool> set_cookie_callback; @@ -2109,7 +2113,7 @@ scoped_refptr<MockPersistentCookieStore> store(new MockPersistentCookieStore); store->set_store_load_commands(true); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); ResultSavingCookieCallback<int> delete_callback; cm->DeleteAllAsync(base::Bind(&ResultSavingCookieCallback<int>::Run, @@ -2150,7 +2154,7 @@ scoped_refptr<MockPersistentCookieStore> store(new MockPersistentCookieStore); store->set_store_load_commands(true); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); GetCookieListCallback get_cookie_list_callback1; cm->GetAllCookiesAsync( @@ -2202,7 +2206,7 @@ scoped_refptr<MockPersistentCookieStore> store(new MockPersistentCookieStore); store->set_store_load_commands(true); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); // Get all cookies task that queues a task to set a cookie when executed. ResultSavingCookieCallback<bool> set_cookie_callback; @@ -2304,7 +2308,7 @@ TEST_F(CookieMonsterTest, FlushStore) { scoped_refptr<CallbackCounter> counter(new CallbackCounter()); scoped_refptr<FlushablePersistentStore> store(new FlushablePersistentStore()); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); ASSERT_EQ(0, store->flush_count()); ASSERT_EQ(0, counter->callback_count()); @@ -2354,7 +2358,7 @@ TEST_F(CookieMonsterTest, SetAllCookies) { scoped_refptr<FlushablePersistentStore> store(new FlushablePersistentStore()); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); cm->SetPersistSessionCookies(true); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "U=V; path=/")); @@ -2400,56 +2404,59 @@ } TEST_F(CookieMonsterTest, ComputeCookieDiff) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); base::Time now = base::Time::Now(); base::Time creation_time = now - base::TimeDelta::FromSeconds(1); - scoped_ptr<CanonicalCookie> cookie1(CanonicalCookie::Create( + std::unique_ptr<CanonicalCookie> cookie1(CanonicalCookie::Create( http_www_google_.url(), "A", "B", http_www_google_.url().host(), "/", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, COOKIE_PRIORITY_DEFAULT)); - scoped_ptr<CanonicalCookie> cookie2(CanonicalCookie::Create( + std::unique_ptr<CanonicalCookie> cookie2(CanonicalCookie::Create( http_www_google_.url(), "C", "D", http_www_google_.url().host(), "/", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, COOKIE_PRIORITY_DEFAULT)); - scoped_ptr<CanonicalCookie> cookie3(CanonicalCookie::Create( + std::unique_ptr<CanonicalCookie> cookie3(CanonicalCookie::Create( http_www_google_.url(), "E", "F", http_www_google_.url().host(), "/", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, COOKIE_PRIORITY_DEFAULT)); - scoped_ptr<CanonicalCookie> cookie4(CanonicalCookie::Create( + std::unique_ptr<CanonicalCookie> cookie4(CanonicalCookie::Create( http_www_google_.url(), "G", "H", http_www_google_.url().host(), "/", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, COOKIE_PRIORITY_DEFAULT)); - scoped_ptr<CanonicalCookie> cookie4_with_new_value(CanonicalCookie::Create( - http_www_google_.url(), "G", "iamnew", http_www_google_.url().host(), "/", - creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, - false, COOKIE_PRIORITY_DEFAULT)); - scoped_ptr<CanonicalCookie> cookie5(CanonicalCookie::Create( + std::unique_ptr<CanonicalCookie> cookie4_with_new_value( + CanonicalCookie::Create( + http_www_google_.url(), "G", "iamnew", http_www_google_.url().host(), + "/", creation_time, base::Time(), false, false, + CookieSameSite::DEFAULT_MODE, false, COOKIE_PRIORITY_DEFAULT)); + std::unique_ptr<CanonicalCookie> cookie5(CanonicalCookie::Create( http_www_google_.url(), "I", "J", http_www_google_.url().host(), "/", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, COOKIE_PRIORITY_DEFAULT)); - scoped_ptr<CanonicalCookie> cookie5_with_new_creation_time( + std::unique_ptr<CanonicalCookie> cookie5_with_new_creation_time( CanonicalCookie::Create( http_www_google_.url(), "I", "J", http_www_google_.url().host(), "/", now, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, COOKIE_PRIORITY_DEFAULT)); - scoped_ptr<CanonicalCookie> cookie6(CanonicalCookie::Create( + std::unique_ptr<CanonicalCookie> cookie6(CanonicalCookie::Create( http_www_google_.url(), "K", "L", http_www_google_.url().host(), "/foo", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, COOKIE_PRIORITY_DEFAULT)); - scoped_ptr<CanonicalCookie> cookie6_with_new_path(CanonicalCookie::Create( - http_www_google_.url(), "K", "L", http_www_google_.url().host(), "/bar", - creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, - false, COOKIE_PRIORITY_DEFAULT)); - scoped_ptr<CanonicalCookie> cookie7(CanonicalCookie::Create( + std::unique_ptr<CanonicalCookie> cookie6_with_new_path( + CanonicalCookie::Create( + http_www_google_.url(), "K", "L", http_www_google_.url().host(), + "/bar", creation_time, base::Time(), false, false, + CookieSameSite::DEFAULT_MODE, false, COOKIE_PRIORITY_DEFAULT)); + std::unique_ptr<CanonicalCookie> cookie7(CanonicalCookie::Create( http_www_google_.url(), "M", "N", http_www_google_.url().host(), "/foo", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, COOKIE_PRIORITY_DEFAULT)); - scoped_ptr<CanonicalCookie> cookie7_with_new_path(CanonicalCookie::Create( - http_www_google_.url(), "M", "N", http_www_google_.url().host(), "/bar", - creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, - false, COOKIE_PRIORITY_DEFAULT)); + std::unique_ptr<CanonicalCookie> cookie7_with_new_path( + CanonicalCookie::Create( + http_www_google_.url(), "M", "N", http_www_google_.url().host(), + "/bar", creation_time, base::Time(), false, false, + CookieSameSite::DEFAULT_MODE, false, COOKIE_PRIORITY_DEFAULT)); CookieList old_cookies; old_cookies.push_back(*cookie1); @@ -2519,7 +2526,7 @@ // works). TEST_F(CookieMonsterTest, DeleteAll) { scoped_refptr<FlushablePersistentStore> store(new FlushablePersistentStore()); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); cm->SetPersistSessionCookies(true); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "X=Y; path=/")); @@ -2530,7 +2537,7 @@ } TEST_F(CookieMonsterTest, HistogramCheck) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); // Should match call in InitializeHistograms, but doesn't really matter // since the histogram should have been initialized by the CM construction // above. @@ -2538,21 +2545,21 @@ "Cookie.ExpirationDurationMinutes", 1, 10 * 365 * 24 * 60, 50, base::Histogram::kUmaTargetedHistogramFlag); - scoped_ptr<base::HistogramSamples> samples1( + std::unique_ptr<base::HistogramSamples> samples1( expired_histogram->SnapshotSamples()); ASSERT_TRUE(SetCookieWithDetails( cm.get(), GURL("http://fake.a.url"), "a", "b", "a.url", "/", base::Time(), base::Time::Now() + base::TimeDelta::FromMinutes(59), base::Time(), false, false, CookieSameSite::DEFAULT_MODE, COOKIE_PRIORITY_DEFAULT)); - scoped_ptr<base::HistogramSamples> samples2( + std::unique_ptr<base::HistogramSamples> samples2( expired_histogram->SnapshotSamples()); EXPECT_EQ(samples1->TotalCount() + 1, samples2->TotalCount()); // kValidCookieLine creates a session cookie. ASSERT_TRUE(SetCookie(cm.get(), http_www_google_.url(), kValidCookieLine)); - scoped_ptr<base::HistogramSamples> samples3( + std::unique_ptr<base::HistogramSamples> samples3( expired_histogram->SnapshotSamples()); EXPECT_EQ(samples2->TotalCount(), samples3->TotalCount()); } @@ -2560,7 +2567,7 @@ TEST_F(CookieMonsterTest, InvalidExpiryTime) { std::string cookie_line = std::string(kValidCookieLine) + "; expires=Blarg arg arg"; - scoped_ptr<CanonicalCookie> cookie(CanonicalCookie::Create( + std::unique_ptr<CanonicalCookie> cookie(CanonicalCookie::Create( http_www_google_.url(), cookie_line, Time::Now(), CookieOptions())); ASSERT_FALSE(cookie->IsPersistent()); } @@ -2569,7 +2576,7 @@ // CookieStore if the "persist session cookies" option is on. TEST_F(CookieMonsterTest, PersistSessionCookies) { scoped_refptr<MockPersistentCookieStore> store(new MockPersistentCookieStore); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); cm->SetPersistSessionCookies(true); // All cookies set with SetCookie are session cookies. @@ -2605,7 +2612,7 @@ // Test the commands sent to the persistent cookie store. TEST_F(CookieMonsterTest, PersisentCookieStorageTest) { scoped_refptr<MockPersistentCookieStore> store(new MockPersistentCookieStore); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); // Add a cookie. EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), @@ -2661,7 +2668,7 @@ // We have to manually build this cookie because it contains a control // character, and our cookie line parser rejects control characters. - scoped_ptr<CanonicalCookie> cc = CanonicalCookie::Create( + std::unique_ptr<CanonicalCookie> cc = CanonicalCookie::Create( url, "baz", "\x05" "boo", @@ -2674,7 +2681,7 @@ // Inject our initial cookies into the mock PersistentCookieStore. store->SetLoadExpectation(true, initial_cookies); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); EXPECT_EQ("foo=bar; hello=world", GetCookies(cm.get(), url)); } @@ -2685,7 +2692,7 @@ const std::string cookie_source_histogram = "Cookie.CookieSourceScheme"; scoped_refptr<MockPersistentCookieStore> store(new MockPersistentCookieStore); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); histograms.ExpectTotalCount(cookie_source_histogram, 0); @@ -2752,7 +2759,7 @@ const std::string cookie_source_histogram = "Cookie.CookieDeleteEquivalent"; scoped_refptr<MockPersistentCookieStore> store(new MockPersistentCookieStore); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); // Set a secure cookie from a secure origin EXPECT_TRUE(SetCookie(cm.get(), https_www_google_.url(), "A=B; Secure")); @@ -2817,7 +2824,7 @@ } TEST_F(CookieMonsterStrictSecureTest, SetSecureCookies) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); GURL http_url("http://www.google.com"); GURL http_superdomain_url("http://google.com"); GURL https_url("https://www.google.com"); @@ -3010,7 +3017,7 @@ // Tests that strict secure cookies doesn't trip equivalent cookie checks // accidentally. Regression test for https://crbug.com/569943. TEST_F(CookieMonsterStrictSecureTest, EquivalentCookies) { - scoped_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); GURL http_url("http://www.google.com"); GURL http_superdomain_url("http://google.com"); GURL https_url("https://www.google.com"); @@ -3035,7 +3042,7 @@ const std::string cookie_source_histogram = "Cookie.CookieDeleteEquivalent"; scoped_refptr<MockPersistentCookieStore> store(new MockPersistentCookieStore); - scoped_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); + std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); // Set a secure cookie from a secure origin EXPECT_TRUE(SetCookie(cm.get(), https_www_google_.url(), "A=B; Secure")); @@ -3121,7 +3128,7 @@ private: scoped_refptr<MockPersistentCookieStore> store_; - scoped_ptr<CookieMonster> monster_; + std::unique_ptr<CookieMonster> monster_; }; void RecordCookieChanges(std::vector<CanonicalCookie>* out_cookies, @@ -3136,7 +3143,7 @@ TEST_F(CookieMonsterNotificationTest, NoNotifyWithNoCookie) { std::vector<CanonicalCookie> cookies; - scoped_ptr<CookieStore::CookieChangedSubscription> sub( + std::unique_ptr<CookieStore::CookieChangedSubscription> sub( monster()->AddCallbackForCookie( test_url_, "abc", base::Bind(&RecordCookieChanges, &cookies, nullptr))); @@ -3148,7 +3155,7 @@ std::vector<CanonicalCookie> cookies; SetCookie(monster(), test_url_, "abc=def"); base::MessageLoop::current()->RunUntilIdle(); - scoped_ptr<CookieStore::CookieChangedSubscription> sub( + std::unique_ptr<CookieStore::CookieChangedSubscription> sub( monster()->AddCallbackForCookie( test_url_, "abc", base::Bind(&RecordCookieChanges, &cookies, nullptr))); @@ -3159,7 +3166,7 @@ TEST_F(CookieMonsterNotificationTest, NotifyOnSet) { std::vector<CanonicalCookie> cookies; std::vector<bool> removes; - scoped_ptr<CookieStore::CookieChangedSubscription> sub( + std::unique_ptr<CookieStore::CookieChangedSubscription> sub( monster()->AddCallbackForCookie( test_url_, "abc", base::Bind(&RecordCookieChanges, &cookies, &removes))); @@ -3176,7 +3183,7 @@ TEST_F(CookieMonsterNotificationTest, NotifyOnDelete) { std::vector<CanonicalCookie> cookies; std::vector<bool> removes; - scoped_ptr<CookieStore::CookieChangedSubscription> sub( + std::unique_ptr<CookieStore::CookieChangedSubscription> sub( monster()->AddCallbackForCookie( test_url_, "abc", base::Bind(&RecordCookieChanges, &cookies, &removes))); @@ -3198,7 +3205,7 @@ TEST_F(CookieMonsterNotificationTest, NotifyOnUpdate) { std::vector<CanonicalCookie> cookies; std::vector<bool> removes; - scoped_ptr<CookieStore::CookieChangedSubscription> sub( + std::unique_ptr<CookieStore::CookieChangedSubscription> sub( monster()->AddCallbackForCookie( test_url_, "abc", base::Bind(&RecordCookieChanges, &cookies, &removes))); @@ -3226,11 +3233,11 @@ TEST_F(CookieMonsterNotificationTest, MultipleNotifies) { std::vector<CanonicalCookie> cookies0; std::vector<CanonicalCookie> cookies1; - scoped_ptr<CookieStore::CookieChangedSubscription> sub0( + std::unique_ptr<CookieStore::CookieChangedSubscription> sub0( monster()->AddCallbackForCookie( test_url_, "abc", base::Bind(&RecordCookieChanges, &cookies0, nullptr))); - scoped_ptr<CookieStore::CookieChangedSubscription> sub1( + std::unique_ptr<CookieStore::CookieChangedSubscription> sub1( monster()->AddCallbackForCookie( test_url_, "def", base::Bind(&RecordCookieChanges, &cookies1, nullptr))); @@ -3247,11 +3254,11 @@ TEST_F(CookieMonsterNotificationTest, MultipleSameNotifies) { std::vector<CanonicalCookie> cookies0; std::vector<CanonicalCookie> cookies1; - scoped_ptr<CookieStore::CookieChangedSubscription> sub0( + std::unique_ptr<CookieStore::CookieChangedSubscription> sub0( monster()->AddCallbackForCookie( test_url_, "abc", base::Bind(&RecordCookieChanges, &cookies0, nullptr))); - scoped_ptr<CookieStore::CookieChangedSubscription> sub1( + std::unique_ptr<CookieStore::CookieChangedSubscription> sub1( monster()->AddCallbackForCookie( test_url_, "abc", base::Bind(&RecordCookieChanges, &cookies1, nullptr)));
diff --git a/net/cookies/cookie_store.h b/net/cookies/cookie_store.h index fa063636..aaf1b743 100644 --- a/net/cookies/cookie_store.h +++ b/net/cookies/cookie_store.h
@@ -7,12 +7,12 @@ #ifndef NET_COOKIES_COOKIE_STORE_H_ #define NET_COOKIES_COOKIE_STORE_H_ +#include <memory> #include <string> #include <vector> #include "base/callback_forward.h" #include "base/callback_list.h" -#include "base/memory/scoped_ptr.h" #include "base/time/time.h" #include "net/base/net_export.h" #include "net/cookies/canonical_cookie.h" @@ -198,7 +198,7 @@ // (url, name) pair are removed. If this method ever needs to support an // unbounded amount of such pairs, this contract needs to change and // implementors need to be improved to not behave this way. - virtual scoped_ptr<CookieChangedSubscription> AddCallbackForCookie( + virtual std::unique_ptr<CookieChangedSubscription> AddCallbackForCookie( const GURL& url, const std::string& name, const CookieChangedCallback& callback) = 0;
diff --git a/net/cookies/cookie_store_test_helpers.cc b/net/cookies/cookie_store_test_helpers.cc index 0606ec8..9189339 100644 --- a/net/cookies/cookie_store_test_helpers.cc +++ b/net/cookies/cookie_store_test_helpers.cc
@@ -205,13 +205,13 @@ ADD_FAILURE(); } -scoped_ptr<CookieStore::CookieChangedSubscription> +std::unique_ptr<CookieStore::CookieChangedSubscription> DelayedCookieMonster::AddCallbackForCookie( const GURL& url, const std::string& name, const CookieChangedCallback& callback) { ADD_FAILURE(); - return scoped_ptr<CookieStore::CookieChangedSubscription>(); + return std::unique_ptr<CookieStore::CookieChangedSubscription>(); } bool DelayedCookieMonster::IsEphemeral() {
diff --git a/net/cookies/cookie_store_test_helpers.h b/net/cookies/cookie_store_test_helpers.h index f0fe1f9..687261e 100644 --- a/net/cookies/cookie_store_test_helpers.h +++ b/net/cookies/cookie_store_test_helpers.h
@@ -89,9 +89,10 @@ void FlushStore(const base::Closure& callback) override; - scoped_ptr<CookieStore::CookieChangedSubscription> - AddCallbackForCookie(const GURL& url, const std::string& name, - const CookieChangedCallback& callback) override; + std::unique_ptr<CookieStore::CookieChangedSubscription> AddCallbackForCookie( + const GURL& url, + const std::string& name, + const CookieChangedCallback& callback) override; bool IsEphemeral() override; @@ -116,7 +117,7 @@ friend class base::RefCountedThreadSafe<DelayedCookieMonster>; - scoped_ptr<CookieMonster> cookie_monster_; + std::unique_ptr<CookieMonster> cookie_monster_; bool did_run_; bool result_;
diff --git a/net/cookies/cookie_store_unittest.cc b/net/cookies/cookie_store_unittest.cc index 73933659..a0c77f40 100644 --- a/net/cookies/cookie_store_unittest.cc +++ b/net/cookies/cookie_store_unittest.cc
@@ -2,11 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "net/cookies/cookie_store.h" + +#include <memory> #include <vector> #include "base/time/time.h" -#include "net/cookies/cookie_store.h" -#include "base/memory/scoped_ptr.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_options.h" #include "testing/gtest/include/gtest/gtest.h" @@ -19,7 +20,7 @@ // Helper for testing BuildCookieLine void MatchCookieLineToVector( const std::string& line, - const std::vector<scoped_ptr<CanonicalCookie>>& cookies) { + const std::vector<std::unique_ptr<CanonicalCookie>>& cookies) { // Test the std::vector<CanonicalCookie> variant // ('CookieMonster::CookieList'): std::vector<CanonicalCookie> list; @@ -38,7 +39,7 @@ } // namespace TEST(CookieStoreBaseTest, BuildCookieLine) { - std::vector<scoped_ptr<CanonicalCookie>> cookies; + std::vector<std::unique_ptr<CanonicalCookie>> cookies; GURL url("https://example.com/"); CookieOptions options; base::Time now = base::Time::Now();
diff --git a/net/cookies/cookie_store_unittest.h b/net/cookies/cookie_store_unittest.h index 2d228a9..d75d8f7 100644 --- a/net/cookies/cookie_store_unittest.h +++ b/net/cookies/cookie_store_unittest.h
@@ -42,7 +42,7 @@ // The CookieStoreTestTraits must have the following members: // struct CookieStoreTestTraits { // // Factory function. Will be called at most once per test. -// static scoped_ptr<CookieStore> Create(); +// static std::unique_ptr<CookieStore> Create(); // // // The cookie store supports cookies with the exclude_httponly() option. // static const bool supports_http_only; @@ -319,8 +319,8 @@ const CookieURLHelper http_foo_com_; const CookieURLHelper http_bar_com_; - scoped_ptr<base::WeakPtrFactory<base::MessageLoop> > weak_factory_; - scoped_ptr<base::MessageLoop> message_loop_; + std::unique_ptr<base::WeakPtrFactory<base::MessageLoop>> weak_factory_; + std::unique_ptr<base::MessageLoop> message_loop_; private: // Returns a set of strings of type "name=value". Fails in case of duplicate. @@ -332,7 +332,7 @@ return tokens; } - scoped_ptr<CookieStore> cookie_store_; + std::unique_ptr<CookieStore> cookie_store_; }; TYPED_TEST_CASE_P(CookieStoreTest);
diff --git a/net/data/http/http.dict b/net/data/http/http.dict new file mode 100644 index 0000000..20a84968 --- /dev/null +++ b/net/data/http/http.dict
@@ -0,0 +1,78 @@ +# Copyright 2016 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# Fuzzer dictionary targetting HTTP/1.x responses. + +# Entries that are generally useful in headers +":" +"\x0A" +"\x0D" +"0" +"50" +"500" +# Horizontal whitespace. Matters mostly in status line. +" " +"\x09" +# Header continuation +"\x0D\x0A\x09" +# Used in a lot of individual headers +";" +"=" +"," +"\"" + +# Status line components +"HTTP" +"/1.1" +"/1.0" +# More interesting status codes. Leading space so can be inserted into +# other status lines. +" 100" +" 200" +" 206" +" 301" +" 302" +" 303" +" 304" +" 307" +" 308" +" 401" +" 403" +" 404" +" 500" +" 501" +" 403" + +# Full status lines (Some with relevant following headers) +"HTTP/1.1 200 OK\x0A\x0A" +"HTTP/1.1 100 Continue\x0A\x0A" +"HTTP/1.1 401 Unauthorized\x0AWWW-Authenticate: Basic realm=\"Middle-Earth\"\x0A\xA0" +"HTTP/1.1 407 Proxy Authentication Required\x0AProxy-Authenticate: Digest realm=\"Middle-Earth\", nonce=\"aaaaaaaaaa\"\x0A\x0A" +"HTTP/1.0 301 Moved Permanently\x0ALocation: /a\x0A\x0A" +"HTTP/1.1 302 Found\x0ALocation: http://lost/\x0A\x0A" + +# Proxy authentication headers. Note that fuzzers don't support NTLM or +# negotiate. +"WWW-Authenticate" +"Proxy-Authenticate" +"Basic" +"Digest" +"realm" +"nonce" + +"Connection" +"Proxy-Connection" +"Keep-Alive" +"Close" +"\x0AConnection: Keep-Alive" +"\x0AConnection: Close" +"\x0AProxy-Connection: Keep-Alive" +"\x0AProxy-Connection: Close" + +"Content-Length" +"Transfer-Encoding" +"chunked" +"\x0AContent-Length: 0" +"\x0AContent-Length: 500" +"\x0ATransfer-Encoding: chunked\x0A\x0A5\x0A12345\x0A0\x0A\x0A"
diff --git a/net/data/verify_name_match_unittest/names/unicode-mixed-normalized.pem b/net/data/verify_name_match_unittest/names/unicode-mixed-normalized.pem new file mode 100644 index 0000000..209fad2 --- /dev/null +++ b/net/data/verify_name_match_unittest/names/unicode-mixed-normalized.pem
@@ -0,0 +1,36 @@ + 0:d=0 hl=3 l= 154 cons: SEQUENCE + 3:d=1 hl=2 l= 111 cons: SET + 5:d=2 hl=2 l= 9 cons: SEQUENCE + 7:d=3 hl=2 l= 3 prim: OBJECT :countryName + 12:d=3 hl=2 l= 2 prim: UTF8STRING :aa + 16:d=2 hl=2 l= 15 cons: SEQUENCE + 18:d=3 hl=2 l= 3 prim: OBJECT :localityName + 23:d=3 hl=2 l= 8 prim: UTF8STRING :ab東京 + 33:d=2 hl=2 l= 16 cons: SEQUENCE + 35:d=3 hl=2 l= 3 prim: OBJECT :organizationalUnitName + 40:d=3 hl=2 l= 9 prim: UTF8STRING :𝐀 a bc + 51:d=2 hl=2 l= 19 cons: SEQUENCE + 53:d=3 hl=2 l= 3 prim: OBJECT :stateOrProvinceName + 58:d=3 hl=2 l= 12 prim: T61STRING : AbCd Ef + 72:d=2 hl=2 l= 19 cons: SEQUENCE + 74:d=3 hl=2 l= 3 prim: OBJECT :organizationName + 79:d=3 hl=2 l= 12 prim: UTF8STRING :ab 東京 cd + 93:d=2 hl=2 l= 21 cons: SEQUENCE + 95:d=3 hl=2 l= 10 prim: OBJECT :domainComponent + 107:d=3 hl=2 l= 7 prim: UTF8STRING :example + 116:d=1 hl=2 l= 24 cons: SET + 118:d=2 hl=2 l= 10 cons: SEQUENCE + 120:d=3 hl=2 l= 3 prim: OBJECT :localityName + 125:d=3 hl=2 l= 3 prim: UTF8STRING :aaa + 130:d=2 hl=2 l= 10 cons: SEQUENCE + 132:d=3 hl=2 l= 3 prim: OBJECT :localityName + 137:d=3 hl=2 l= 3 prim: UTF8STRING :aaa + 142:d=1 hl=2 l= 13 cons: SET + 144:d=2 hl=2 l= 11 cons: SEQUENCE + 146:d=3 hl=2 l= 3 prim: OBJECT :localityName + 151:d=3 hl=2 l= 4 prim: UTF8STRING :cccc +-----BEGIN NAME----- +MIGaMW8wCQYDVQQGDAJhYTAPBgNVBAcMCGFi5p2x5LqsMBAGA1UECwwJ8J2QgCBhIGJjMBMGA1UE +CBQMICBBYkNkICBFZiAgMBMGA1UECgwMYWIg5p2x5LqsIGNkMBUGCgmSJomT8ixkARkMB2V4YW1w +bGUxGDAKBgNVBAcMA2FhYTAKBgNVBAcMA2FhYTENMAsGA1UEBwwEY2NjYw== +-----END NAME-----
diff --git a/net/data/verify_name_match_unittest/names/unicode-mixed-unnormalized.pem b/net/data/verify_name_match_unittest/names/unicode-mixed-unnormalized.pem new file mode 100644 index 0000000..fa66baab --- /dev/null +++ b/net/data/verify_name_match_unittest/names/unicode-mixed-unnormalized.pem
@@ -0,0 +1,37 @@ + 0:d=0 hl=3 l= 204 cons: SEQUENCE + 3:d=1 hl=3 l= 157 cons: SET + 6:d=2 hl=2 l= 9 cons: SEQUENCE + 8:d=3 hl=2 l= 3 prim: OBJECT :countryName + 13:d=3 hl=2 l= 2 prim: PRINTABLESTRING :AA + 17:d=2 hl=2 l= 18 cons: SEQUENCE + 19:d=3 hl=2 l= 3 prim: OBJECT :localityName + 24:d=3 hl=2 l= 11 prim: UTF8STRING : Ab東京 + 37:d=2 hl=2 l= 19 cons: SEQUENCE + 39:d=3 hl=2 l= 3 prim: OBJECT :stateOrProvinceName + 44:d=3 hl=2 l= 12 prim: T61STRING : AbCd Ef + 58:d=2 hl=2 l= 21 cons: SEQUENCE + 60:d=3 hl=2 l= 10 prim: OBJECT :domainComponent + 72:d=3 hl=2 l= 7 prim: IA5STRING :eXaMpLe + 81:d=2 hl=2 l= 31 cons: SEQUENCE + 83:d=3 hl=2 l= 3 prim: OBJECT :organizationName + 88:d=3 hl=2 l= 24 prim: BMPSTRING + 114:d=2 hl=2 l= 47 cons: SEQUENCE + 116:d=3 hl=2 l= 3 prim: OBJECT :organizationalUnitName + 121:d=3 hl=2 l= 40 prim: UNIVERSALSTRING + 163:d=1 hl=2 l= 27 cons: SET + 165:d=2 hl=2 l= 10 cons: SEQUENCE + 167:d=3 hl=2 l= 3 prim: OBJECT :localityName + 172:d=3 hl=2 l= 3 prim: UTF8STRING :AAA + 177:d=2 hl=2 l= 13 cons: SEQUENCE + 179:d=3 hl=2 l= 3 prim: OBJECT :localityName + 184:d=3 hl=2 l= 6 prim: BMPSTRING + 192:d=1 hl=2 l= 13 cons: SET + 194:d=2 hl=2 l= 11 cons: SEQUENCE + 196:d=3 hl=2 l= 3 prim: OBJECT :localityName + 201:d=3 hl=2 l= 4 prim: PRINTABLESTRING :cCcC +-----BEGIN NAME----- +MIHMMYGdMAkGA1UEBhMCQUEwEgYDVQQHDAsgIEFi5p2x5LqsIDATBgNVBAgUDCAgQWJDZCAgRWYg +IDAVBgoJkiaJk/IsZAEZFgdlWGFNcExlMB8GA1UECh4YACAAYQBCACAAIGdxTqwAIAAgAGMARAAg +MC8GA1UECxwoAAAAIAAB1AAAAAAgAAAAIAAAAEEAAAAgAAAAIAAAAGIAAABDAAAAIDEbMAoGA1UE +BwwDQUFBMA0GA1UEBx4GAGEAYQBhMQ0wCwYDVQQHEwRjQ2ND +-----END NAME-----
diff --git a/net/data/verify_name_match_unittest/scripts/generate_names.py b/net/data/verify_name_match_unittest/scripts/generate_names.py index e3053301..ed509ce 100755 --- a/net/data/verify_name_match_unittest/scripts/generate_names.py +++ b/net/data/verify_name_match_unittest/scripts/generate_names.py
@@ -330,5 +330,46 @@ value=PRINTABLESTRING:"US" """, "valid-minimal") + # Single Name that exercises all of the string types, unicode (basic and + # supplemental planes), whitespace collapsing, case folding, as well as SET + # sorting. + n = NameGenerator() + rdn1 = n.add_rdn() + rdn1.add_attr('countryName', 'PRINTABLESTRING', 'AA') + rdn1.add_attr('stateOrProvinceName', 'T61STRING', ' AbCd Ef ') + rdn1.add_attr('localityName', 'UTF8', " Ab\xe6\x9d\xb1\xe4\xba\xac ", + "FORMAT:UTF8") + rdn1.add_attr('organizationName', + 'BMPSTRING', " aB \xe6\x9d\xb1\xe4\xba\xac cD ", + "FORMAT:UTF8") + rdn1.add_attr('organizationalUnitName', 'UNIVERSALSTRING', + " \xf0\x9d\x90\x80 A bC ", "FORMAT:UTF8") + rdn1.add_attr('domainComponent', 'IA5STRING', 'eXaMpLe') + rdn2 = n.add_rdn() + rdn2.add_attr('localityName', 'UTF8', "AAA") + rdn2.add_attr('localityName', 'BMPSTRING', "aaa") + rdn3 = n.add_rdn() + rdn3.add_attr('localityName', 'PRINTABLESTRING', "cCcC") + generate(n, "unicode-mixed-unnormalized") + # Expected normalized version of above. + n = NameGenerator() + rdn1 = n.add_rdn() + rdn1.add_attr('countryName', 'UTF8', 'aa') + rdn1.add_attr('stateOrProvinceName', 'T61STRING', ' AbCd Ef ') + rdn1.add_attr('localityName', 'UTF8', "ab\xe6\x9d\xb1\xe4\xba\xac", + "FORMAT:UTF8") + rdn1.add_attr('organizationName', 'UTF8', "ab \xe6\x9d\xb1\xe4\xba\xac cd", + "FORMAT:UTF8") + rdn1.add_attr('organizationalUnitName', 'UTF8', "\xf0\x9d\x90\x80 a bc", + "FORMAT:UTF8") + rdn1.add_attr('domainComponent', 'UTF8', 'example') + rdn2 = n.add_rdn() + rdn2.add_attr('localityName', 'UTF8', "aaa") + rdn2.add_attr('localityName', 'UTF8', "aaa") + rdn3 = n.add_rdn() + rdn3.add_attr('localityName', 'UTF8', "cccc") + generate(n, "unicode-mixed-normalized") + + if __name__ == '__main__': main()
diff --git a/net/disk_cache/blockfile/backend_impl.cc b/net/disk_cache/blockfile/backend_impl.cc index 7484339..b58f574 100644 --- a/net/disk_cache/blockfile/backend_impl.cc +++ b/net/disk_cache/blockfile/backend_impl.cc
@@ -498,12 +498,6 @@ int64_t use_hours = total_hours - no_use_hours; if (!cache_entry) { - CACHE_UMA(AGE_MS, "OpenTime.Miss", 0, start); - CACHE_UMA(COUNTS_10000, "AllOpenBySize.Miss", 0, current_size); - CACHE_UMA(HOURS, "AllOpenByTotalHours.Miss", 0, - static_cast<base::HistogramBase::Sample>(total_hours)); - CACHE_UMA(HOURS, "AllOpenByUseHours.Miss", 0, - static_cast<base::HistogramBase::Sample>(use_hours)); stats_.OnEvent(Stats::OPEN_MISS); return NULL; }
diff --git a/net/dns/address_sorter_win.cc b/net/dns/address_sorter_win.cc index 53645b4..fb5f087 100644 --- a/net/dns/address_sorter_win.cc +++ b/net/dns/address_sorter_win.cc
@@ -16,6 +16,7 @@ #include "base/threading/worker_pool.h" #include "base/win/windows_version.h" #include "net/base/address_list.h" +#include "net/base/ip_address.h" #include "net/base/ip_endpoint.h" #include "net/base/winsock_init.h" @@ -60,8 +61,8 @@ for (size_t i = 0; i < list.size(); ++i) { IPEndPoint ipe = list[i]; // Addresses must be sockaddr_in6. - if (ipe.GetFamily() == ADDRESS_FAMILY_IPV4) { - ipe = IPEndPoint(ConvertIPv4NumberToIPv6Number(ipe.address().bytes()), + if (ipe.address().IsIPv4()) { + ipe = IPEndPoint(ConvertIPv4ToIPv4MappedIPv6(ipe.address()), ipe.port()); } @@ -117,8 +118,8 @@ DCHECK(result) << "Unable to roundtrip between IPEndPoint and " << "SOCKET_ADDRESS!"; // Unmap V4MAPPED IPv6 addresses so that Happy Eyeballs works. - if (IsIPv4Mapped(ipe.address().bytes())) { - ipe = IPEndPoint(ConvertIPv4MappedToIPv4(ipe.address().bytes()), + if (ipe.address().IsIPv4MappedIPv6()) { + ipe = IPEndPoint(ConvertIPv4MappedIPv6ToIPv4(ipe.address()), ipe.port()); } list.push_back(ipe);
diff --git a/net/extras/sqlite/sqlite_channel_id_store.cc b/net/extras/sqlite/sqlite_channel_id_store.cc index 5b8b351b..238577fd 100644 --- a/net/extras/sqlite/sqlite_channel_id_store.cc +++ b/net/extras/sqlite/sqlite_channel_id_store.cc
@@ -4,6 +4,7 @@ #include "net/extras/sqlite/sqlite_channel_id_store.h" +#include <memory> #include <set> #include <utility> #include <vector> @@ -14,7 +15,6 @@ #include "base/location.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/histogram_macros.h" #include "base/sequenced_task_runner.h" #include "base/strings/string_util.h" @@ -83,7 +83,8 @@ } void LoadInBackground( - std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>>* channel_ids); + std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>>* + channel_ids); // Database upgrade statements. bool EnsureDatabaseVersion(); @@ -126,7 +127,7 @@ void KillDatabase(); const base::FilePath path_; - scoped_ptr<sql::Connection> db_; + std::unique_ptr<sql::Connection> db_; sql::MetaTable meta_table_; typedef std::list<PendingOperation*> PendingOperationsList; @@ -149,11 +150,12 @@ const LoadedCallback& loaded_callback) { // This function should be called only once per instance. DCHECK(!db_.get()); - scoped_ptr<std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>>> + std::unique_ptr< + std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>>> channel_ids( - new std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>>()); - std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>>* channel_ids_ptr = - channel_ids.get(); + new std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>>()); + std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>>* + channel_ids_ptr = channel_ids.get(); background_task_runner_->PostTaskAndReply( FROM_HERE, @@ -162,7 +164,8 @@ } void SQLiteChannelIDStore::Backend::LoadInBackground( - std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>>* channel_ids) { + std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>>* + channel_ids) { DCHECK(background_task_runner_->RunsTasksOnCurrentThread()); // This method should be called only once per instance. @@ -222,13 +225,13 @@ std::vector<uint8_t> private_key_from_db, public_key_from_db; smt.ColumnBlobAsVector(1, &private_key_from_db); smt.ColumnBlobAsVector(2, &public_key_from_db); - scoped_ptr<crypto::ECPrivateKey> key( + std::unique_ptr<crypto::ECPrivateKey> key( crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo( ChannelIDService::kEPKIPassword, private_key_from_db, public_key_from_db)); if (!key) continue; - scoped_ptr<DefaultChannelIDStore::ChannelID> channel_id( + std::unique_ptr<DefaultChannelIDStore::ChannelID> channel_id( new DefaultChannelIDStore::ChannelID( smt.ColumnString(0), // host base::Time::FromInternalValue(smt.ColumnInt64(3)), std::move(key))); @@ -412,7 +415,7 @@ static const size_t kCommitAfterBatchSize = 512; // We do a full copy of the cert here, and hopefully just here. - scoped_ptr<PendingOperation> po(new PendingOperation(op, channel_id)); + std::unique_ptr<PendingOperation> po(new PendingOperation(op, channel_id)); PendingOperationsList::size_type num_pending; { @@ -447,7 +450,7 @@ server_identifiers.end(); if (remove) { - scoped_ptr<PendingOperation> po(*it); + std::unique_ptr<PendingOperation> po(*it); it = pending_.erase(it); --num_pending_; } else { @@ -489,7 +492,7 @@ for (PendingOperationsList::iterator it = ops.begin(); it != ops.end(); ++it) { // Free the certs as we commit them to the database. - scoped_ptr<PendingOperation> po(*it); + std::unique_ptr<PendingOperation> po(*it); switch (po->op()) { case PendingOperation::CHANNEL_ID_ADD: { add_statement.Reset(true);
diff --git a/net/extras/sqlite/sqlite_channel_id_store_unittest.cc b/net/extras/sqlite/sqlite_channel_id_store_unittest.cc index 2b5e80a..89fbaad 100644 --- a/net/extras/sqlite/sqlite_channel_id_store_unittest.cc +++ b/net/extras/sqlite/sqlite_channel_id_store_unittest.cc
@@ -2,19 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "net/extras/sqlite/sqlite_channel_id_store.h" + +#include <memory> #include <vector> #include "base/bind.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" +#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "base/thread_task_runner_handle.h" #include "crypto/ec_private_key.h" #include "net/base/test_data_directory.h" #include "net/cert/asn1_util.h" -#include "net/extras/sqlite/sqlite_channel_id_store.h" #include "net/ssl/channel_id_service.h" #include "net/ssl/ssl_client_cert_type.h" #include "net/test/cert_test_util.h" @@ -29,8 +31,8 @@ class SQLiteChannelIDStoreTest : public testing::Test { public: - void Load( - std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>>* channel_ids) { + void Load(std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>>* + channel_ids) { base::RunLoop run_loop; store_->Load(base::Bind(&SQLiteChannelIDStoreTest::OnLoaded, base::Unretained(this), @@ -42,8 +44,8 @@ void OnLoaded( base::RunLoop* run_loop, - scoped_ptr<std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>>> - channel_ids) { + std::unique_ptr<std::vector< + std::unique_ptr<DefaultChannelIDStore::ChannelID>>> channel_ids) { channel_ids_.swap(*channel_ids); run_loop->Quit(); } @@ -51,7 +53,7 @@ protected: static void ReadTestKeyAndCert(std::string* key_data, std::string* cert_data, - scoped_ptr<crypto::ECPrivateKey>* key) { + std::unique_ptr<crypto::ECPrivateKey>* key) { base::FilePath key_path = GetTestCertsDirectory().AppendASCII("unittest.originbound.key.der"); base::FilePath cert_path = @@ -105,30 +107,30 @@ store_ = new SQLiteChannelIDStore( temp_dir_.path().Append(kTestChannelIDFilename), base::ThreadTaskRunnerHandle::Get()); - std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; + std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; Load(&channel_ids); ASSERT_EQ(0u, channel_ids.size()); // Make sure the store gets written at least once. google_key_.reset(crypto::ECPrivateKey::Create()); store_->AddChannelID(DefaultChannelIDStore::ChannelID( "google.com", base::Time::FromInternalValue(1), - make_scoped_ptr(google_key_->Copy()))); + base::WrapUnique(google_key_->Copy()))); } base::ScopedTempDir temp_dir_; scoped_refptr<SQLiteChannelIDStore> store_; - std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>> channel_ids_; - scoped_ptr<crypto::ECPrivateKey> google_key_; + std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids_; + std::unique_ptr<crypto::ECPrivateKey> google_key_; }; // Test if data is stored as expected in the SQLite database. TEST_F(SQLiteChannelIDStoreTest, TestPersistence) { - scoped_ptr<crypto::ECPrivateKey> foo_key(crypto::ECPrivateKey::Create()); + std::unique_ptr<crypto::ECPrivateKey> foo_key(crypto::ECPrivateKey::Create()); store_->AddChannelID(DefaultChannelIDStore::ChannelID( "foo.com", base::Time::FromInternalValue(3), - make_scoped_ptr(foo_key->Copy()))); + base::WrapUnique(foo_key->Copy()))); - std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; + std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; // Replace the store effectively destroying the current one and forcing it // to write its data to disk. Then we can see if after loading it again it // is still there. @@ -182,9 +184,9 @@ TEST_F(SQLiteChannelIDStoreTest, TestDeleteAll) { store_->AddChannelID(DefaultChannelIDStore::ChannelID( "foo.com", base::Time::FromInternalValue(3), - make_scoped_ptr(crypto::ECPrivateKey::Create()))); + base::WrapUnique(crypto::ECPrivateKey::Create()))); - std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; + std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; // Replace the store effectively destroying the current one and forcing it // to write its data to disk. Then we can see if after loading it again it // is still there. @@ -231,7 +233,7 @@ std::string key_data; std::string cert_data; - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; ASSERT_NO_FATAL_FAILURE(ReadTestKeyAndCert(&key_data, &cert_data, &key)); // Create a version 1 database. @@ -266,7 +268,7 @@ for (int i = 0; i < 2; ++i) { SCOPED_TRACE(i); - std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; + std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; store_ = new SQLiteChannelIDStore(v1_db_path, base::ThreadTaskRunnerHandle::Get()); @@ -299,7 +301,7 @@ std::string key_data; std::string cert_data; - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; ASSERT_NO_FATAL_FAILURE(ReadTestKeyAndCert(&key_data, &cert_data, &key)); // Create a version 2 database. @@ -338,7 +340,7 @@ for (int i = 0; i < 2; ++i) { SCOPED_TRACE(i); - std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; + std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; store_ = new SQLiteChannelIDStore(v2_db_path, base::ThreadTaskRunnerHandle::Get()); @@ -375,7 +377,7 @@ std::string key_data; std::string cert_data; - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; ASSERT_NO_FATAL_FAILURE(ReadTestKeyAndCert(&key_data, &cert_data, &key)); // Create a version 3 database. @@ -416,7 +418,7 @@ for (int i = 0; i < 2; ++i) { SCOPED_TRACE(i); - std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; + std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; store_ = new SQLiteChannelIDStore(v3_db_path, base::ThreadTaskRunnerHandle::Get()); @@ -453,7 +455,7 @@ std::string key_data; std::string cert_data; - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; ASSERT_NO_FATAL_FAILURE(ReadTestKeyAndCert(&key_data, &cert_data, &key)); // Create a version 4 database. @@ -510,7 +512,7 @@ for (int i = 0; i < 2; ++i) { SCOPED_TRACE(i); - std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; + std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; store_ = new SQLiteChannelIDStore(v4_db_path, base::ThreadTaskRunnerHandle::Get());
diff --git a/net/extras/sqlite/sqlite_persistent_cookie_store.cc b/net/extras/sqlite/sqlite_persistent_cookie_store.cc index 911f05a..8ee2d07 100644 --- a/net/extras/sqlite/sqlite_persistent_cookie_store.cc +++ b/net/extras/sqlite/sqlite_persistent_cookie_store.cc
@@ -5,6 +5,7 @@ #include "net/extras/sqlite/sqlite_persistent_cookie_store.h" #include <map> +#include <memory> #include <set> #include "base/bind.h" @@ -15,7 +16,6 @@ #include "base/logging.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/histogram_macros.h" #include "base/profiler/scoped_tracker.h" #include "base/sequenced_task_runner.h" @@ -242,7 +242,7 @@ bool success); const base::FilePath path_; - scoped_ptr<sql::Connection> db_; + std::unique_ptr<sql::Connection> db_; sql::MetaTable meta_table_; typedef std::list<PendingOperation*> PendingOperationsList; @@ -819,7 +819,7 @@ } else { value = smt.ColumnString(3); } - scoped_ptr<CanonicalCookie> cc(new CanonicalCookie( + std::unique_ptr<CanonicalCookie> cc(new CanonicalCookie( // The "source" URL is not used with persisted cookies. GURL(), // Source smt.ColumnString(2), // name @@ -1081,7 +1081,7 @@ DCHECK(!background_task_runner_->RunsTasksOnCurrentThread()); // We do a full copy of the cookie here, and hopefully just here. - scoped_ptr<PendingOperation> po(new PendingOperation(op, cc)); + std::unique_ptr<PendingOperation> po(new PendingOperation(op, cc)); PendingOperationsList::size_type num_pending; { @@ -1144,7 +1144,7 @@ for (PendingOperationsList::iterator it = ops.begin(); it != ops.end(); ++it) { // Free the cookies as we commit them to the database. - scoped_ptr<PendingOperation> po(*it); + std::unique_ptr<PendingOperation> po(*it); switch (po->op()) { case PendingOperation::COOKIE_ADD: add_smt.Reset(true);
diff --git a/net/extras/sqlite/sqlite_persistent_cookie_store_perftest.cc b/net/extras/sqlite/sqlite_persistent_cookie_store_perftest.cc index bbf594c..3aef494 100644 --- a/net/extras/sqlite/sqlite_persistent_cookie_store_perftest.cc +++ b/net/extras/sqlite/sqlite_persistent_cookie_store_perftest.cc
@@ -104,7 +104,7 @@ protected: base::MessageLoop main_loop_; - scoped_ptr<base::SequencedWorkerPoolOwner> pool_owner_; + std::unique_ptr<base::SequencedWorkerPoolOwner> pool_owner_; base::WaitableEvent loaded_event_; base::WaitableEvent key_loaded_event_; std::vector<CanonicalCookie*> cookies_;
diff --git a/net/extras/sqlite/sqlite_persistent_cookie_store_unittest.cc b/net/extras/sqlite/sqlite_persistent_cookie_store_unittest.cc index 8315d74..58382eb 100644 --- a/net/extras/sqlite/sqlite_persistent_cookie_store_unittest.cc +++ b/net/extras/sqlite/sqlite_persistent_cookie_store_unittest.cc
@@ -48,7 +48,7 @@ bool should_encrypt_; private: - scoped_ptr<crypto::SymmetricKey> key_; + std::unique_ptr<crypto::SymmetricKey> key_; crypto::Encryptor encryptor_; }; @@ -199,14 +199,14 @@ } protected: - scoped_ptr<base::SequencedWorkerPoolOwner> pool_owner_; + std::unique_ptr<base::SequencedWorkerPoolOwner> pool_owner_; base::WaitableEvent loaded_event_; base::WaitableEvent key_loaded_event_; base::WaitableEvent db_thread_event_; CanonicalCookieVector cookies_; base::ScopedTempDir temp_dir_; scoped_refptr<SQLitePersistentCookieStore> store_; - scoped_ptr<CookieCryptor> cookie_crypto_delegate_; + std::unique_ptr<CookieCryptor> cookie_crypto_delegate_; }; TEST_F(SQLitePersistentCookieStoreTest, TestInvalidMetaTableRecovery) {
diff --git a/net/filter/brotli_filter_unittest.cc b/net/filter/brotli_filter_unittest.cc index 38cfc82..f26aa84 100644 --- a/net/filter/brotli_filter_unittest.cc +++ b/net/filter/brotli_filter_unittest.cc
@@ -2,11 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "net/filter/brotli_filter.h" + +#include <memory> + #include "base/files/file_util.h" -#include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "net/base/io_buffer.h" -#include "net/filter/brotli_filter.h" #include "net/filter/mock_filter_context.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" @@ -135,7 +137,7 @@ const char* encoded_buffer() const { return encoded_buffer_.data(); } int encoded_len() const { return static_cast<int>(encoded_buffer_.size()); } - scoped_ptr<Filter> filter_; + std::unique_ptr<Filter> filter_; private: MockFilterContext filter_context_;
diff --git a/net/filter/filter.cc b/net/filter/filter.cc index 502ce5bb..be9b787 100644 --- a/net/filter/filter.cc +++ b/net/filter/filter.cc
@@ -359,7 +359,7 @@ // static Filter* Filter::InitBrotliFilter(FilterType type_id, int buffer_size) { - scoped_ptr<Filter> brotli_filter(CreateBrotliFilter(type_id)); + std::unique_ptr<Filter> brotli_filter(CreateBrotliFilter(type_id)); if (!brotli_filter.get()) return nullptr; @@ -369,7 +369,7 @@ // static Filter* Filter::InitGZipFilter(FilterType type_id, int buffer_size) { - scoped_ptr<GZipFilter> gz_filter(new GZipFilter(type_id)); + std::unique_ptr<GZipFilter> gz_filter(new GZipFilter(type_id)); gz_filter->InitBuffer(buffer_size); return gz_filter->InitDecoding(type_id) ? gz_filter.release() : NULL; } @@ -378,7 +378,8 @@ Filter* Filter::InitSdchFilter(FilterType type_id, const FilterContext& filter_context, int buffer_size) { - scoped_ptr<SdchFilter> sdch_filter(new SdchFilter(type_id, filter_context)); + std::unique_ptr<SdchFilter> sdch_filter( + new SdchFilter(type_id, filter_context)); sdch_filter->InitBuffer(buffer_size); return sdch_filter->InitDecoding(type_id) ? sdch_filter.release() : NULL; } @@ -388,7 +389,7 @@ const FilterContext& filter_context, int buffer_size, Filter* filter_list) { - scoped_ptr<Filter> first_filter; // Soon to be start of chain. + std::unique_ptr<Filter> first_filter; // Soon to be start of chain. switch (type_id) { case FILTER_TYPE_BROTLI: first_filter.reset(InitBrotliFilter(type_id, buffer_size));
diff --git a/net/filter/filter.h b/net/filter/filter.h index 31d08d4..39f82e72 100644 --- a/net/filter/filter.h +++ b/net/filter/filter.h
@@ -48,13 +48,13 @@ #include <stdint.h> +#include <memory> #include <string> #include <vector> #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/time/time.h" #include "net/base/net_export.h" #include "net/base/sdch_manager.h" @@ -308,7 +308,7 @@ int buffer_size); // An optional filter to process output from this filter. - scoped_ptr<Filter> next_filter_; + std::unique_ptr<Filter> next_filter_; // Remember what status or local filter last returned so we can better handle // chained filters.
diff --git a/net/filter/filter_unittest.cc b/net/filter/filter_unittest.cc index d10fadc..d2b6afcf 100644 --- a/net/filter/filter_unittest.cc +++ b/net/filter/filter_unittest.cc
@@ -149,9 +149,9 @@ // Make sure a series of three pass-through filters copies the data cleanly. // Regression test for http://crbug.com/418975. TEST(FilterTest, ThreeFilterChain) { - scoped_ptr<PassThroughFilter> filter1(new PassThroughFilter); - scoped_ptr<PassThroughFilter> filter2(new PassThroughFilter); - scoped_ptr<PassThroughFilter> filter3(new PassThroughFilter); + std::unique_ptr<PassThroughFilter> filter1(new PassThroughFilter); + std::unique_ptr<PassThroughFilter> filter2(new PassThroughFilter); + std::unique_ptr<PassThroughFilter> filter3(new PassThroughFilter); filter1->InitBuffer(32 * 1024); filter2->InitBuffer(32 * 1024);
diff --git a/net/filter/gzip_filter.h b/net/filter/gzip_filter.h index 67330d73..c0d80b6 100644 --- a/net/filter/gzip_filter.h +++ b/net/filter/gzip_filter.h
@@ -15,8 +15,9 @@ #ifndef NET_FILTER_GZIP_FILTER_H_ #define NET_FILTER_GZIP_FILTER_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/filter/filter.h" typedef struct z_stream_s z_stream; @@ -115,7 +116,7 @@ // Used to parse the gzip header in gzip stream. // It is used when the decoding_mode_ is DECODE_MODE_GZIP. - scoped_ptr<GZipHeader> gzip_header_; + std::unique_ptr<GZipHeader> gzip_header_; // Tracks the progress of parsing gzip header. // This variable is maintained by gzip_header_. @@ -131,7 +132,7 @@ // The control block of zlib which actually does the decoding. // This data structure is initialized by InitDecoding and updated only by // DoInflate, with InsertZlibHeader being the exception as a workaround. - scoped_ptr<z_stream> zlib_stream_; + std::unique_ptr<z_stream> zlib_stream_; // For robustness, when we see the solo sdch filter, we chain in a gzip filter // in front of it, with this flag to indicate that the gzip decoding might not
diff --git a/net/filter/gzip_filter_unittest.cc b/net/filter/gzip_filter_unittest.cc index e25cc1c8..a100b25 100644 --- a/net/filter/gzip_filter_unittest.cc +++ b/net/filter/gzip_filter_unittest.cc
@@ -2,15 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "net/filter/gzip_filter.h" + #include <fstream> +#include <memory> #include <ostream> #include "base/bit_cast.h" #include "base/files/file_util.h" -#include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "net/base/io_buffer.h" -#include "net/filter/gzip_filter.h" #include "net/filter/mock_filter_context.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" @@ -233,7 +234,7 @@ const char* source_buffer() const { return source_buffer_.data(); } int source_len() const { return static_cast<int>(source_buffer_.size()); } - scoped_ptr<Filter> filter_; + std::unique_ptr<Filter> filter_; std::string source_buffer_;
diff --git a/net/filter/mock_filter_context.h b/net/filter/mock_filter_context.h index 50858c4..3237829 100644 --- a/net/filter/mock_filter_context.h +++ b/net/filter/mock_filter_context.h
@@ -6,11 +6,12 @@ #define NET_FILTER_MOCK_FILTER_CONTEXT_H_ #include <stdint.h> + +#include <memory> #include <string> #include <utility> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/base/sdch_manager.h" #include "net/filter/filter.h" #include "net/log/net_log.h" @@ -30,7 +31,7 @@ void SetRequestTime(const base::Time time) { request_time_ = time; } void SetCached(bool is_cached) { is_cached_content_ = is_cached; } void SetResponseCode(int response_code) { response_code_ = response_code; } - void SetSdchResponse(scoped_ptr<SdchManager::DictionarySet> handle) { + void SetSdchResponse(std::unique_ptr<SdchManager::DictionarySet> handle) { dictionaries_handle_ = std::move(handle); } URLRequestContext* GetModifiableURLRequestContext() const { @@ -74,10 +75,10 @@ GURL gurl_; base::Time request_time_; bool is_cached_content_; - scoped_ptr<SdchManager::DictionarySet> dictionaries_handle_; + std::unique_ptr<SdchManager::DictionarySet> dictionaries_handle_; bool ok_to_call_get_url_; int response_code_; - scoped_ptr<URLRequestContext> context_; + std::unique_ptr<URLRequestContext> context_; BoundNetLog net_log_; DISALLOW_COPY_AND_ASSIGN(MockFilterContext);
diff --git a/net/filter/sdch_filter.cc b/net/filter/sdch_filter.cc index 67b4b10..85be890 100644 --- a/net/filter/sdch_filter.cc +++ b/net/filter/sdch_filter.cc
@@ -89,11 +89,11 @@ return cause_string; } -scoped_ptr<base::Value> NetLogSdchResponseCorruptionDetectionCallback( +std::unique_ptr<base::Value> NetLogSdchResponseCorruptionDetectionCallback( ResponseCorruptionDetectionCause cause, bool cached, NetLogCaptureMode capture_mode) { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetString("cause", ResponseCorruptionDetectionCauseToString(cause)); dict->SetBoolean("cached", cached); return std::move(dict);
diff --git a/net/filter/sdch_filter.h b/net/filter/sdch_filter.h index 83e29c5..3ba0693 100644 --- a/net/filter/sdch_filter.h +++ b/net/filter/sdch_filter.h
@@ -16,10 +16,10 @@ #include <stddef.h> +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/base/net_export.h" #include "net/base/sdch_dictionary.h" #include "net/base/sdch_manager.h" @@ -82,7 +82,8 @@ // The underlying decoder that processes data. // This data structure is initialized by InitDecoding and updated in // ReadFilteredData. - scoped_ptr<open_vcdiff::VCDiffStreamingDecoder> vcdiff_streaming_decoder_; + std::unique_ptr<open_vcdiff::VCDiffStreamingDecoder> + vcdiff_streaming_decoder_; // After the encoded response SDCH header is read, this variable contains // the server hash with trailing null byte. @@ -131,7 +132,7 @@ // If the response was encoded with a dictionary different than those // advertised (e.g. a cached response using an old dictionary), this // variable preserves that dictionary from deletion during decoding. - scoped_ptr<SdchManager::DictionarySet> unexpected_dictionary_handle_; + std::unique_ptr<SdchManager::DictionarySet> unexpected_dictionary_handle_; DISALLOW_COPY_AND_ASSIGN(SdchFilter); };
diff --git a/net/filter/sdch_filter_unittest.cc b/net/filter/sdch_filter_unittest.cc index 701aba0..c483f24 100644 --- a/net/filter/sdch_filter_unittest.cc +++ b/net/filter/sdch_filter_unittest.cc
@@ -2,16 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "net/filter/sdch_filter.h" + #include <limits.h> #include <algorithm> +#include <memory> #include <string> #include <vector> #include "base/bit_cast.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/test/histogram_tester.h" #include "base/test/simple_test_clock.h" #include "net/base/io_buffer.h" @@ -19,7 +21,6 @@ #include "net/base/sdch_manager.h" #include "net/base/sdch_observer.h" #include "net/filter/mock_filter_context.h" -#include "net/filter/sdch_filter.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_http_job.h" #include "testing/gtest/include/gtest/gtest.h" @@ -102,8 +103,8 @@ const std::string vcdiff_compressed_data_; const std::string expanded_; // Desired final, decompressed data. - scoped_ptr<SdchManager> sdch_manager_; - scoped_ptr<MockFilterContext> filter_context_; + std::unique_ptr<SdchManager> sdch_manager_; + std::unique_ptr<MockFilterContext> filter_context_; }; TEST_F(SdchFilterTest, Hashing) { @@ -132,7 +133,7 @@ CHECK_GT(input_block_length, 0u); Filter::FilterStatus status(Filter::FILTER_NEED_MORE_DATA); size_t source_index = 0; - scoped_ptr<char[]> output_buffer(new char[output_buffer_length]); + std::unique_ptr<char[]> output_buffer(new char[output_buffer_length]); size_t input_amount = std::min(input_block_length, static_cast<size_t>(filter->stream_buffer_size())); @@ -188,7 +189,8 @@ char output_buffer[20]; std::string url_string("http://ignore.com"); filter_context()->SetURL(GURL(url_string)); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); // With no input data, try to read output. int output_bytes_or_buffer_size = sizeof(output_buffer); @@ -208,7 +210,8 @@ char output_buffer[20]; std::string url_string("http://ignore.com"); filter_context()->SetURL(GURL(url_string)); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); // With no input data, try to read output. int output_bytes_or_buffer_size = sizeof(output_buffer); @@ -235,7 +238,8 @@ filter_context()->SetResponseCode(200); std::string url_string("http://ignore.com"); filter_context()->SetURL(GURL(url_string)); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); // Supply enough data to force a pass-through mode.. std::string non_gzip_content("not GZIPed data"); @@ -274,7 +278,8 @@ filter_context()->SetMimeType("text/html"); std::string url_string("http://ignore.com"); filter_context()->SetURL(GURL(url_string)); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); // Supply enough data to force a pass-through mode, which means we have // provided more than 9 characters that can't be a dictionary hash. @@ -315,7 +320,8 @@ filter_context()->SetMimeType("anything"); std::string url_string("http://ignore.com"); filter_context()->SetURL(GURL(url_string)); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); // Supply enough data to force a pass-through mode, which means we have // provided more than 9 characters that can't be a dictionary hash. @@ -350,7 +356,8 @@ filter_context()->SetMimeType("text/html"); std::string url_string("http://ignore.com"); filter_context()->SetURL(GURL(url_string)); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); // Supply enough data to force a pass-through mode, which means we have // provided more than 9 characters that can't be a dictionary hash. @@ -386,7 +393,8 @@ char output_buffer[20]; std::string url_string("http://ignore.com"); filter_context()->SetURL(GURL(url_string)); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); // Supply bogus data (which doesn't yet specify a full dictionary hash). // Dictionary hash is 8 characters followed by a null. @@ -471,7 +479,8 @@ SetupFilterContextWithGURL(url); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); size_t feed_block_size = 100; size_t output_block_size = 100; @@ -508,7 +517,8 @@ GURL filter_context_gurl("https://" + kSampleDomain); SetupFilterContextWithGURL(GURL("https://" + kSampleDomain)); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); const size_t feed_block_size(100); const size_t output_block_size(100); @@ -538,7 +548,8 @@ filter_types.push_back(Filter::FILTER_TYPE_SDCH); SetupFilterContextWithGURL(GURL("ftp://" + kSampleDomain)); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); const size_t feed_block_size(100); const size_t output_block_size(100); @@ -564,7 +575,8 @@ filter_types.push_back(Filter::FILTER_TYPE_SDCH); SetupFilterContextWithGURL(GURL("file://" + kSampleDomain)); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); const size_t feed_block_size(100); const size_t output_block_size(100); @@ -590,7 +602,8 @@ filter_types.push_back(Filter::FILTER_TYPE_SDCH); SetupFilterContextWithGURL(GURL("about://" + kSampleDomain)); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); const size_t feed_block_size(100); const size_t output_block_size(100); @@ -616,7 +629,8 @@ filter_types.push_back(Filter::FILTER_TYPE_SDCH); SetupFilterContextWithGURL(GURL("javascript://" + kSampleDomain)); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); const size_t feed_block_size(100); const size_t output_block_size(100); @@ -642,7 +656,8 @@ filter_types.push_back(Filter::FILTER_TYPE_SDCH); SetupFilterContextWithGURL(GURL("http://" + kSampleDomain)); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); const size_t feed_block_size(100); const size_t output_block_size(100); @@ -679,7 +694,8 @@ // This tests SdchManager::CanSet(). GURL wrong_domain_url("http://www.wrongdomain.com"); SetupFilterContextWithGURL(wrong_domain_url); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); size_t feed_block_size = 100; size_t output_block_size = 100; @@ -719,7 +735,8 @@ // Test decode the path data, arriving from a valid path. SetupFilterContextWithGURL(GURL(url_string + path)); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); size_t feed_block_size = 100; size_t output_block_size = 100; @@ -771,7 +788,8 @@ // Test decode the port data, arriving from a valid port. SetupFilterContextWithGURL(GURL(url_string + ":" + port)); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); size_t feed_block_size = 100; size_t output_block_size = 100; @@ -828,7 +846,7 @@ // Assume we can compress into similar buffer (add 100 bytes to be sure). size_t gzip_compressed_length = zlib_stream.avail_in + 100; - scoped_ptr<char[]> gzip_compressed(new char[gzip_compressed_length]); + std::unique_ptr<char[]> gzip_compressed(new char[gzip_compressed_length]); zlib_stream.next_out = bit_cast<Bytef*>(gzip_compressed.get()); zlib_stream.avail_out = gzip_compressed_length; @@ -900,9 +918,8 @@ CHECK_GT(kLargeInputBufferSize, sdch_compressed.size()); CHECK_GT(kLargeInputBufferSize, expanded_.size()); SetupFilterContextWithGURL(url); - scoped_ptr<Filter> filter( - SdchFilterChainingTest::Factory(filter_types, *filter_context(), - kLargeInputBufferSize)); + std::unique_ptr<Filter> filter(SdchFilterChainingTest::Factory( + filter_types, *filter_context(), kLargeInputBufferSize)); EXPECT_EQ(static_cast<int>(kLargeInputBufferSize), filter->stream_buffer_size()); @@ -985,7 +1002,8 @@ EXPECT_EQ(filter_types[1], Filter::FILTER_TYPE_GZIP_HELPING_SDCH); // First try with a large buffer (larger than test input, or compressed data). - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); // Verify that chained filter is waiting for data. char tiny_output_buffer[10]; @@ -1042,7 +1060,8 @@ EXPECT_EQ(filter_types[2], Filter::FILTER_TYPE_GZIP); // First try with a large buffer (larger than test input, or compressed data). - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); // Verify that chained filter is waiting for data. char tiny_output_buffer[10]; @@ -1096,7 +1115,8 @@ EXPECT_EQ(filter_types[1], Filter::FILTER_TYPE_GZIP_HELPING_SDCH); // First try with a large buffer (larger than test input, or compressed data). - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); // Verify that chained filter is waiting for data. char tiny_output_buffer[10]; @@ -1156,7 +1176,8 @@ EXPECT_EQ(filter_types[2], Filter::FILTER_TYPE_GZIP); // First try with a large buffer (larger than test input, or compressed data). - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); // Verify that chained filter is waiting for data. char tiny_output_buffer[10]; @@ -1196,7 +1217,8 @@ std::vector<Filter::FilterType> filter_types; filter_types.push_back(Filter::FILTER_TYPE_SDCH); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); // Setup another dictionary, expired. Don't add it to the filter context. // Delete stored dictionaries first to handle platforms which only @@ -1213,7 +1235,7 @@ SdchManager::GenerateHash(expired_dictionary, &client_hash, &server_hash); SdchProblemCode problem_code; - scoped_ptr<SdchManager::DictionarySet> hash_set( + std::unique_ptr<SdchManager::DictionarySet> hash_set( sdch_manager_->GetDictionarySetByHash(url, server_hash, &problem_code)); ASSERT_TRUE(hash_set); ASSERT_EQ(SDCH_OK, problem_code); @@ -1281,7 +1303,8 @@ SetupFilterContextWithGURL(url); - scoped_ptr<Filter> filter(Filter::Factory(filter_types, *filter_context())); + std::unique_ptr<Filter> filter( + Filter::Factory(filter_types, *filter_context())); size_t feed_block_size = 100; size_t output_block_size = 100;
diff --git a/net/ftp/ftp_ctrl_response_buffer.cc b/net/ftp/ftp_ctrl_response_buffer.cc index c2d8483..1195d66 100644 --- a/net/ftp/ftp_ctrl_response_buffer.cc +++ b/net/ftp/ftp_ctrl_response_buffer.cc
@@ -83,13 +83,13 @@ namespace { -scoped_ptr<base::Value> NetLogFtpCtrlResponseCallback( +std::unique_ptr<base::Value> NetLogFtpCtrlResponseCallback( const FtpCtrlResponse* response, NetLogCaptureMode capture_mode) { - scoped_ptr<base::ListValue> lines(new base::ListValue()); + std::unique_ptr<base::ListValue> lines(new base::ListValue()); lines->AppendStrings(response->lines); - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetInteger("status_code", response->status_code); dict->Set("lines", std::move(lines)); return std::move(dict);
diff --git a/net/ftp/ftp_network_layer.cc b/net/ftp/ftp_network_layer.cc index c8658d0..bc9c25a 100644 --- a/net/ftp/ftp_network_layer.cc +++ b/net/ftp/ftp_network_layer.cc
@@ -4,6 +4,7 @@ #include "net/ftp/ftp_network_layer.h" +#include "base/memory/ptr_util.h" #include "net/ftp/ftp_network_session.h" #include "net/ftp/ftp_network_transaction.h" #include "net/socket/client_socket_factory.h" @@ -18,11 +19,11 @@ FtpNetworkLayer::~FtpNetworkLayer() { } -scoped_ptr<FtpTransaction> FtpNetworkLayer::CreateTransaction() { +std::unique_ptr<FtpTransaction> FtpNetworkLayer::CreateTransaction() { if (suspended_) - return scoped_ptr<FtpTransaction>(); + return std::unique_ptr<FtpTransaction>(); - return make_scoped_ptr(new FtpNetworkTransaction( + return base::WrapUnique(new FtpNetworkTransaction( session_->host_resolver(), ClientSocketFactory::GetDefaultFactory())); }
diff --git a/net/ftp/ftp_network_layer.h b/net/ftp/ftp_network_layer.h index 877f8c01..9a904ac 100644 --- a/net/ftp/ftp_network_layer.h +++ b/net/ftp/ftp_network_layer.h
@@ -5,9 +5,10 @@ #ifndef NET_FTP_FTP_NETWORK_LAYER_H_ #define NET_FTP_FTP_NETWORK_LAYER_H_ +#include <memory> + #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/base/net_export.h" #include "net/ftp/ftp_transaction_factory.h" @@ -22,11 +23,11 @@ ~FtpNetworkLayer() override; // FtpTransactionFactory methods: - scoped_ptr<FtpTransaction> CreateTransaction() override; + std::unique_ptr<FtpTransaction> CreateTransaction() override; void Suspend(bool suspend) override; private: - scoped_ptr<FtpNetworkSession> session_; + std::unique_ptr<FtpNetworkSession> session_; bool suspended_; DISALLOW_COPY_AND_ASSIGN(FtpNetworkLayer); };
diff --git a/net/ftp/ftp_network_transaction.h b/net/ftp/ftp_network_transaction.h index ec0c1f8..d5fc67d4 100644 --- a/net/ftp/ftp_network_transaction.h +++ b/net/ftp/ftp_network_transaction.h
@@ -7,13 +7,13 @@ #include <stdint.h> +#include <memory> #include <string> #include <utility> #include "base/compiler_specific.h" #include "base/gtest_prod_util.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "net/base/address_list.h" #include "net/base/auth.h" #include "net/dns/host_resolver.h" @@ -213,7 +213,7 @@ // User buffer passed to the Read method for control socket. scoped_refptr<IOBuffer> read_ctrl_buf_; - scoped_ptr<FtpCtrlResponseBuffer> ctrl_response_buffer_; + std::unique_ptr<FtpCtrlResponseBuffer> ctrl_response_buffer_; scoped_refptr<IOBuffer> read_data_buf_; int read_data_buf_len_; @@ -249,8 +249,8 @@ ClientSocketFactory* socket_factory_; - scoped_ptr<StreamSocket> ctrl_socket_; - scoped_ptr<StreamSocket> data_socket_; + std::unique_ptr<StreamSocket> ctrl_socket_; + std::unique_ptr<StreamSocket> data_socket_; State next_state_;
diff --git a/net/ftp/ftp_network_transaction_unittest.cc b/net/ftp/ftp_network_transaction_unittest.cc index cf0b14e..1c0cc89 100644 --- a/net/ftp/ftp_network_transaction_unittest.cc +++ b/net/ftp/ftp_network_transaction_unittest.cc
@@ -884,7 +884,7 @@ MockRead(mock_data.c_str()), }; - scoped_ptr<StaticSocketDataProvider> data_socket( + std::unique_ptr<StaticSocketDataProvider> data_socket( new StaticSocketDataProvider(data_reads, arraysize(data_reads), NULL, 0)); mock_socket_factory_.AddSocketDataProvider(data_socket.get()); @@ -928,7 +928,7 @@ ExecuteTransaction(ctrl_socket, request, expected_result); } - scoped_ptr<MockHostResolver> host_resolver_; + std::unique_ptr<MockHostResolver> host_resolver_; MockClientSocketFactory mock_socket_factory_; FtpNetworkTransaction transaction_; TestCompletionCallback callback_;
diff --git a/net/ftp/ftp_transaction_factory.h b/net/ftp/ftp_transaction_factory.h index 6b7cdb9..5f4270f2 100644 --- a/net/ftp/ftp_transaction_factory.h +++ b/net/ftp/ftp_transaction_factory.h
@@ -5,7 +5,8 @@ #ifndef NET_FTP_FTP_TRANSACTION_FACTORY_H_ #define NET_FTP_FTP_TRANSACTION_FACTORY_H_ -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "net/base/net_export.h" namespace net { @@ -18,7 +19,7 @@ virtual ~FtpTransactionFactory() {} // Creates a FtpTransaction object. - virtual scoped_ptr<FtpTransaction> CreateTransaction() = 0; + virtual std::unique_ptr<FtpTransaction> CreateTransaction() = 0; // Suspends the creation of new transactions. If |suspend| is false, creation // of new transactions is resumed.
diff --git a/net/log/net_log.cc b/net/log/net_log.cc index a3fde00..008b675 100644 --- a/net/log/net_log.cc +++ b/net/log/net_log.cc
@@ -23,68 +23,74 @@ // the number of bytes transferred. If the capture mode allows logging byte // contents and |byte_count| > 0, then will include the actual bytes. The // bytes are hex-encoded, since base::StringValue only supports UTF-8. -scoped_ptr<base::Value> BytesTransferredCallback( +std::unique_ptr<base::Value> BytesTransferredCallback( int byte_count, const char* bytes, NetLogCaptureMode capture_mode) { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetInteger("byte_count", byte_count); if (capture_mode.include_socket_bytes() && byte_count > 0) dict->SetString("hex_encoded_bytes", base::HexEncode(bytes, byte_count)); return std::move(dict); } -scoped_ptr<base::Value> SourceEventParametersCallback( +std::unique_ptr<base::Value> SourceEventParametersCallback( const NetLog::Source source, NetLogCaptureMode /* capture_mode */) { if (!source.IsValid()) - return scoped_ptr<base::Value>(); - scoped_ptr<base::DictionaryValue> event_params(new base::DictionaryValue()); + return std::unique_ptr<base::Value>(); + std::unique_ptr<base::DictionaryValue> event_params( + new base::DictionaryValue()); source.AddToEventParameters(event_params.get()); return std::move(event_params); } -scoped_ptr<base::Value> NetLogBoolCallback( +std::unique_ptr<base::Value> NetLogBoolCallback( const char* name, bool value, NetLogCaptureMode /* capture_mode */) { - scoped_ptr<base::DictionaryValue> event_params(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> event_params( + new base::DictionaryValue()); event_params->SetBoolean(name, value); return std::move(event_params); } -scoped_ptr<base::Value> NetLogIntCallback( +std::unique_ptr<base::Value> NetLogIntCallback( const char* name, int value, NetLogCaptureMode /* capture_mode */) { - scoped_ptr<base::DictionaryValue> event_params(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> event_params( + new base::DictionaryValue()); event_params->SetInteger(name, value); return std::move(event_params); } -scoped_ptr<base::Value> NetLogInt64Callback( +std::unique_ptr<base::Value> NetLogInt64Callback( const char* name, int64_t value, NetLogCaptureMode /* capture_mode */) { - scoped_ptr<base::DictionaryValue> event_params(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> event_params( + new base::DictionaryValue()); event_params->SetString(name, base::Int64ToString(value)); return std::move(event_params); } -scoped_ptr<base::Value> NetLogStringCallback( +std::unique_ptr<base::Value> NetLogStringCallback( const char* name, const std::string* value, NetLogCaptureMode /* capture_mode */) { - scoped_ptr<base::DictionaryValue> event_params(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> event_params( + new base::DictionaryValue()); event_params->SetString(name, *value); return std::move(event_params); } -scoped_ptr<base::Value> NetLogString16Callback( +std::unique_ptr<base::Value> NetLogString16Callback( const char* name, const base::string16* value, NetLogCaptureMode /* capture_mode */) { - scoped_ptr<base::DictionaryValue> event_params(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> event_params( + new base::DictionaryValue()); event_params->SetString(name, *value); return std::move(event_params); } @@ -105,7 +111,7 @@ void NetLog::Source::AddToEventParameters( base::DictionaryValue* event_params) const { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetInteger("type", static_cast<int>(type)); dict->SetInteger("id", static_cast<int>(id)); event_params->Set("source_dependency", std::move(dict)); @@ -137,12 +143,14 @@ } base::Value* NetLog::Entry::ToValue() const { - scoped_ptr<base::DictionaryValue> entry_dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> entry_dict( + new base::DictionaryValue()); entry_dict->SetString("time", TickCountToString(data_->time)); // Set the entry source. - scoped_ptr<base::DictionaryValue> source_dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> source_dict( + new base::DictionaryValue()); source_dict->SetInteger("id", data_->source.id); source_dict->SetInteger("type", static_cast<int>(data_->source.type)); entry_dict->Set("source", std::move(source_dict)); @@ -153,7 +161,7 @@ // Set the event-specific parameters. if (data_->parameters_callback) { - scoped_ptr<base::Value> value( + std::unique_ptr<base::Value> value( data_->parameters_callback->Run(capture_mode_)); if (value) entry_dict->Set("params", std::move(value)); @@ -162,7 +170,7 @@ return entry_dict.release(); } -scoped_ptr<base::Value> NetLog::Entry::ParametersToValue() const { +std::unique_ptr<base::Value> NetLog::Entry::ParametersToValue() const { if (data_->parameters_callback) return data_->parameters_callback->Run(capture_mode_); return nullptr; @@ -298,7 +306,7 @@ // static base::Value* NetLog::GetEventTypesAsValue() { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); for (int i = 0; i < EVENT_COUNT; ++i) { dict->SetInteger(EventTypeToString(static_cast<EventType>(i)), i); } @@ -321,7 +329,7 @@ // static base::Value* NetLog::GetSourceTypesAsValue() { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); for (int i = 0; i < SOURCE_COUNT; ++i) { dict->SetInteger(SourceTypeToString(static_cast<SourceType>(i)), i); }
diff --git a/net/log/net_log.h b/net/log/net_log.h index 01b49b2..53de234 100644 --- a/net/log/net_log.h +++ b/net/log/net_log.h
@@ -7,19 +7,18 @@ #include <stdint.h> +#include <memory> #include <string> -#include "build/build_config.h" - #include "base/atomicops.h" #include "base/callback_forward.h" #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/observer_list.h" #include "base/strings/string16.h" #include "base/synchronization/lock.h" #include "base/time/time.h" +#include "build/build_config.h" #include "net/base/net_export.h" #include "net/log/net_log_capture_mode.h" @@ -74,7 +73,7 @@ // associated with an event. If called, it will be called synchronously, // so it need not have owning references. May be called more than once, or // not at all. May return NULL. - typedef base::Callback<scoped_ptr<base::Value>(NetLogCaptureMode)> + typedef base::Callback<std::unique_ptr<base::Value>(NetLogCaptureMode)> ParametersCallback; // Identifies the entity that generated this log. The |id| field should @@ -139,7 +138,7 @@ // Returns the parameters as a Value. Returns NULL if there are no // parameters. Caller takes ownership of returned Value. - scoped_ptr<base::Value> ParametersToValue() const; + std::unique_ptr<base::Value> ParametersToValue() const; private: const EntryData* const data_;
diff --git a/net/log/net_log_unittest.cc b/net/log/net_log_unittest.cc index 1a16facf..95de6d0 100644 --- a/net/log/net_log_unittest.cc +++ b/net/log/net_log_unittest.cc
@@ -8,6 +8,7 @@ #include "base/bind.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/synchronization/waitable_event.h" #include "base/threading/simple_thread.h" #include "base/values.h" @@ -38,13 +39,15 @@ return -1; } -scoped_ptr<base::Value> CaptureModeToValue(NetLogCaptureMode capture_mode) { - return make_scoped_ptr( +std::unique_ptr<base::Value> CaptureModeToValue( + NetLogCaptureMode capture_mode) { + return base::WrapUnique( new base::FundamentalValue(CaptureModeToInt(capture_mode))); } -scoped_ptr<base::Value> NetCaptureModeCallback(NetLogCaptureMode capture_mode) { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); +std::unique_ptr<base::Value> NetCaptureModeCallback( + NetLogCaptureMode capture_mode) { + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->Set("capture_mode", CaptureModeToValue(capture_mode)); return std::move(dict); } @@ -130,8 +133,8 @@ } void OnAddEntry(const NetLog::Entry& entry) override { - scoped_ptr<base::DictionaryValue> dict = - base::DictionaryValue::From(make_scoped_ptr(entry.ToValue())); + std::unique_ptr<base::DictionaryValue> dict = + base::DictionaryValue::From(base::WrapUnique(entry.ToValue())); ASSERT_TRUE(dict); values_.push_back(std::move(dict)); } @@ -142,7 +145,7 @@ } private: - std::vector<scoped_ptr<base::DictionaryValue>> values_; + std::vector<std::unique_ptr<base::DictionaryValue>> values_; }; void AddEvent(NetLog* net_log) {
diff --git a/net/log/net_log_util.cc b/net/log/net_log_util.cc index a0884207..2b5f6b5 100644 --- a/net/log/net_log_util.cc +++ b/net/log/net_log_util.cc
@@ -129,15 +129,17 @@ // Returns a Value representing the state of a pre-existing URLRequest when // net-internals was opened. -scoped_ptr<base::Value> GetRequestStateAsValue(const net::URLRequest* request, - NetLogCaptureMode capture_mode) { +std::unique_ptr<base::Value> GetRequestStateAsValue( + const net::URLRequest* request, + NetLogCaptureMode capture_mode) { return request->GetStateAsValue(); } } // namespace -scoped_ptr<base::DictionaryValue> GetNetConstants() { - scoped_ptr<base::DictionaryValue> constants_dict(new base::DictionaryValue()); +std::unique_ptr<base::DictionaryValue> GetNetConstants() { + std::unique_ptr<base::DictionaryValue> constants_dict( + new base::DictionaryValue()); // Version of the file format. constants_dict->SetInteger("logFormatVersion", kLogFormatVersion); @@ -149,7 +151,7 @@ // Add a dictionary with information about the relationship between CertStatus // flags and their symbolic names. { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); for (size_t i = 0; i < arraysize(kCertStatusFlags); i++) dict->SetInteger(kCertStatusFlags[i].name, kCertStatusFlags[i].constant); @@ -160,7 +162,7 @@ // Add a dictionary with information about the relationship between load flag // enums and their symbolic names. { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); for (size_t i = 0; i < arraysize(kLoadFlags); i++) dict->SetInteger(kLoadFlags[i].name, kLoadFlags[i].constant); @@ -171,7 +173,7 @@ // Add a dictionary with information about the relationship between load state // enums and their symbolic names. { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); for (size_t i = 0; i < arraysize(kLoadStateTable); i++) dict->SetInteger(kLoadStateTable[i].name, kLoadStateTable[i].constant); @@ -180,7 +182,7 @@ } { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); #define NET_INFO_SOURCE(label, string, value) \ dict->SetInteger(string, NET_INFO_##label); #include "net/base/net_info_source_list.h" @@ -191,7 +193,7 @@ // Add information on the relationship between net error codes and their // symbolic names. { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); for (size_t i = 0; i < arraysize(kNetErrors); i++) dict->SetInteger(ErrorToShortString(kNetErrors[i]), kNetErrors[i]); @@ -202,7 +204,7 @@ // Add information on the relationship between QUIC error codes and their // symbolic names. { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); for (QuicErrorCode error = QUIC_NO_ERROR; error < QUIC_LAST_ERROR; error = static_cast<QuicErrorCode>(error + 1)) { @@ -216,7 +218,7 @@ // Add information on the relationship between QUIC RST_STREAM error codes // and their symbolic names. { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); for (QuicRstStreamErrorCode error = QUIC_STREAM_NO_ERROR; error < QUIC_STREAM_LAST_ERROR; @@ -231,7 +233,7 @@ // Add information on the relationship between SDCH problem codes and their // symbolic names. { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); for (size_t i = 0; i < arraysize(kSdchProblems); i++) dict->SetInteger(kSdchProblems[i].name, kSdchProblems[i].constant); @@ -242,7 +244,7 @@ // Information about the relationship between event phase enums and their // symbolic names. { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetInteger("PHASE_BEGIN", NetLog::PHASE_BEGIN); dict->SetInteger("PHASE_END", NetLog::PHASE_END); @@ -263,7 +265,7 @@ // Information about the relationship between address family enums and // their symbolic names. { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetInteger("ADDRESS_FAMILY_UNSPECIFIED", ADDRESS_FAMILY_UNSPECIFIED); dict->SetInteger("ADDRESS_FAMILY_IPV4", ADDRESS_FAMILY_IPV4); @@ -315,20 +317,21 @@ return constants_dict; } -NET_EXPORT scoped_ptr<base::DictionaryValue> GetNetInfo( +NET_EXPORT std::unique_ptr<base::DictionaryValue> GetNetInfo( URLRequestContext* context, int info_sources) { // May only be called on the context's thread. DCHECK(context->CalledOnValidThread()); - scoped_ptr<base::DictionaryValue> net_info_dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> net_info_dict( + new base::DictionaryValue()); // TODO(mmenke): The code for most of these sources should probably be moved // into the sources themselves. if (info_sources & NET_INFO_PROXY_SETTINGS) { ProxyService* proxy_service = context->proxy_service(); - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); if (proxy_service->fetched_config().is_valid()) dict->Set("original", proxy_service->fetched_config().ToValue()); if (proxy_service->config().is_valid()) @@ -349,7 +352,7 @@ const std::string& proxy_uri = it->first; const ProxyRetryInfo& retry_info = it->second; - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetString("proxy_uri", proxy_uri); dict->SetString("bad_until", NetLog::TickCountToString(retry_info.bad_until)); @@ -365,8 +368,9 @@ DCHECK(host_resolver); HostCache* cache = host_resolver->GetHostCache(); if (cache) { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); - scoped_ptr<base::Value> dns_config = host_resolver->GetDnsConfigAsValue(); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::Value> dns_config = + host_resolver->GetDnsConfigAsValue(); if (dns_config) dict->Set("dns_config", std::move(dns_config)); @@ -499,7 +503,7 @@ } if (info_sources & NET_INFO_SDCH) { - scoped_ptr<base::Value> info_dict; + std::unique_ptr<base::Value> info_dict; SdchManager* sdch_manager = context->sdch_manager(); if (sdch_manager) { info_dict = sdch_manager->SdchInfoToValue();
diff --git a/net/log/net_log_util.h b/net/log/net_log_util.h index ae08f44..e6a65e4 100644 --- a/net/log/net_log_util.h +++ b/net/log/net_log_util.h
@@ -5,9 +5,9 @@ #ifndef NET_LOG_NET_LOG_UTIL_H_ #define NET_LOG_NET_LOG_UTIL_H_ +#include <memory> #include <set> -#include "base/memory/scoped_ptr.h" #include "net/base/net_export.h" #include "net/log/net_log.h" @@ -32,7 +32,7 @@ // Utility methods for creating NetLog dumps. // Create a dictionary containing a legend for net/ constants. -NET_EXPORT scoped_ptr<base::DictionaryValue> GetNetConstants(); +NET_EXPORT std::unique_ptr<base::DictionaryValue> GetNetConstants(); // Retrieves a dictionary containing information about the current state of // |context|. |info_sources| is a set of NetInfoSources OR'd together, @@ -40,7 +40,7 @@ // one top-level entry to the returned dictionary. // // May only be called on |context|'s thread. -NET_EXPORT scoped_ptr<base::DictionaryValue> GetNetInfo( +NET_EXPORT std::unique_ptr<base::DictionaryValue> GetNetInfo( URLRequestContext* context, int info_sources);
diff --git a/net/log/net_log_util_unittest.cc b/net/log/net_log_util_unittest.cc index c4c04697..f21be4d8 100644 --- a/net/log/net_log_util_unittest.cc +++ b/net/log/net_log_util_unittest.cc
@@ -4,11 +4,12 @@ #include "net/log/net_log_util.h" +#include <memory> #include <set> #include <vector> #include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/values.h" #include "net/base/net_errors.h" #include "net/base/test_completion_callback.h" @@ -25,7 +26,7 @@ // Make sure GetNetConstants doesn't crash. TEST(NetLogUtil, GetNetConstants) { - scoped_ptr<base::Value> constants(GetNetConstants()); + std::unique_ptr<base::Value> constants(GetNetConstants()); } // Make sure GetNetInfo doesn't crash when called on contexts with and without @@ -36,7 +37,7 @@ // Get NetInfo when there's no cache backend (It's only created on first use). EXPECT_FALSE(http_cache->GetCurrentBackend()); - scoped_ptr<base::DictionaryValue> net_info_without_cache( + std::unique_ptr<base::DictionaryValue> net_info_without_cache( GetNetInfo(&context, NET_INFO_ALL_SOURCES)); EXPECT_FALSE(http_cache->GetCurrentBackend()); EXPECT_GT(net_info_without_cache->size(), 0u); @@ -46,7 +47,7 @@ EXPECT_EQ(OK, context.http_transaction_factory()->GetCache()->GetBackend( &backend, TestCompletionCallback().callback())); EXPECT_TRUE(http_cache->GetCurrentBackend()); - scoped_ptr<base::DictionaryValue> net_info_with_cache( + std::unique_ptr<base::DictionaryValue> net_info_with_cache( GetNetInfo(&context, NET_INFO_ALL_SOURCES)); EXPECT_GT(net_info_with_cache->size(), 0u); @@ -64,7 +65,7 @@ context.Init(); TestDelegate delegate; for (size_t num_requests = 0; num_requests < 5; ++num_requests) { - std::vector<scoped_ptr<URLRequest>> requests; + std::vector<std::unique_ptr<URLRequest>> requests; for (size_t i = 0; i < num_requests; ++i) { requests.push_back(context.CreateRequest(GURL("about:life"), DEFAULT_PRIORITY, &delegate)); @@ -89,11 +90,11 @@ TestDelegate delegate; for (size_t num_requests = 0; num_requests < 5; ++num_requests) { NetLog net_log; - std::vector<scoped_ptr<TestURLRequestContext>> contexts; - std::vector<scoped_ptr<URLRequest>> requests; + std::vector<std::unique_ptr<TestURLRequestContext>> contexts; + std::vector<std::unique_ptr<URLRequest>> requests; std::set<URLRequestContext*> context_set; for (size_t i = 0; i < num_requests; ++i) { - contexts.push_back(make_scoped_ptr(new TestURLRequestContext(true))); + contexts.push_back(base::WrapUnique(new TestURLRequestContext(true))); contexts[i]->set_net_log(&net_log); contexts[i]->Init(); context_set.insert(contexts[i].get());
diff --git a/net/log/test_net_log.cc b/net/log/test_net_log.cc index c8d04cb..3287cf0a 100644 --- a/net/log/test_net_log.cc +++ b/net/log/test_net_log.cc
@@ -50,7 +50,7 @@ void OnAddEntry(const NetLog::Entry& entry) override { // Using Dictionaries instead of Values makes checking values a little // simpler. - scoped_ptr<base::DictionaryValue> param_dict = + std::unique_ptr<base::DictionaryValue> param_dict = base::DictionaryValue::From(entry.ParametersToValue()); // Only need to acquire the lock when accessing class variables.
diff --git a/net/log/test_net_log.h b/net/log/test_net_log.h index 3605a9c..6190ab87 100644 --- a/net/log/test_net_log.h +++ b/net/log/test_net_log.h
@@ -43,7 +43,7 @@ // The underlying observer class that does all the work. class Observer; - scoped_ptr<Observer> observer_; + std::unique_ptr<Observer> observer_; DISALLOW_COPY_AND_ASSIGN(TestNetLog); };
diff --git a/net/log/test_net_log_entry.cc b/net/log/test_net_log_entry.cc index e9fd982..be226718 100644 --- a/net/log/test_net_log_entry.cc +++ b/net/log/test_net_log_entry.cc
@@ -16,7 +16,7 @@ const base::TimeTicks& time, NetLog::Source source, NetLog::EventPhase phase, - scoped_ptr<base::DictionaryValue> params) + std::unique_ptr<base::DictionaryValue> params) : type(type), time(time), source(source),
diff --git a/net/log/test_net_log_entry.h b/net/log/test_net_log_entry.h index a13297a7..0508ede 100644 --- a/net/log/test_net_log_entry.h +++ b/net/log/test_net_log_entry.h
@@ -5,10 +5,10 @@ #ifndef NET_LOG_TEST_NET_LOG_ENTRY_H_ #define NET_LOG_TEST_NET_LOG_ENTRY_H_ +#include <memory> #include <string> #include <vector> -#include "base/memory/scoped_ptr.h" #include "base/time/time.h" #include "net/log/net_log.h" @@ -31,7 +31,7 @@ const base::TimeTicks& time, NetLog::Source source, NetLog::EventPhase phase, - scoped_ptr<base::DictionaryValue> params); + std::unique_ptr<base::DictionaryValue> params); // Copy constructor needed to store in a std::vector because of the // scoped_ptr. TestNetLogEntry(const TestNetLogEntry& entry); @@ -62,7 +62,7 @@ base::TimeTicks time; NetLog::Source source; NetLog::EventPhase phase; - scoped_ptr<base::DictionaryValue> params; + std::unique_ptr<base::DictionaryValue> params; }; } // namespace net
diff --git a/net/log/trace_net_log_observer.cc b/net/log/trace_net_log_observer.cc index 6fe44a8e..81d8d8a 100644 --- a/net/log/trace_net_log_observer.cc +++ b/net/log/trace_net_log_observer.cc
@@ -5,12 +5,13 @@ #include "net/log/trace_net_log_observer.h" #include <stdio.h> + +#include <memory> #include <string> #include <utility> #include "base/json/json_writer.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/trace_event/trace_event.h" #include "base/values.h" #include "net/log/net_log.h" @@ -24,7 +25,7 @@ class TracedValue : public base::trace_event::ConvertableToTraceFormat { public: - explicit TracedValue(scoped_ptr<base::Value> value) + explicit TracedValue(std::unique_ptr<base::Value> value) : value_(std::move(value)) {} private: @@ -41,7 +42,7 @@ } private: - scoped_ptr<base::Value> value_; + std::unique_ptr<base::Value> value_; }; } // namespace @@ -55,14 +56,14 @@ } void TraceNetLogObserver::OnAddEntry(const NetLog::Entry& entry) { - scoped_ptr<base::Value> params(entry.ParametersToValue()); + std::unique_ptr<base::Value> params(entry.ParametersToValue()); switch (entry.phase()) { case NetLog::PHASE_BEGIN: TRACE_EVENT_NESTABLE_ASYNC_BEGIN2( kNetLogTracingCategory, NetLog::EventTypeToString(entry.type()), entry.source().id, "source_type", NetLog::SourceTypeToString(entry.source().type), "params", - scoped_ptr<base::trace_event::ConvertableToTraceFormat>( + std::unique_ptr<base::trace_event::ConvertableToTraceFormat>( new TracedValue(std::move(params)))); break; case NetLog::PHASE_END: @@ -70,7 +71,7 @@ kNetLogTracingCategory, NetLog::EventTypeToString(entry.type()), entry.source().id, "source_type", NetLog::SourceTypeToString(entry.source().type), "params", - scoped_ptr<base::trace_event::ConvertableToTraceFormat>( + std::unique_ptr<base::trace_event::ConvertableToTraceFormat>( new TracedValue(std::move(params)))); break; case NetLog::PHASE_NONE: @@ -78,7 +79,7 @@ kNetLogTracingCategory, NetLog::EventTypeToString(entry.type()), entry.source().id, "source_type", NetLog::SourceTypeToString(entry.source().type), "params", - scoped_ptr<base::trace_event::ConvertableToTraceFormat>( + std::unique_ptr<base::trace_event::ConvertableToTraceFormat>( new TracedValue(std::move(params)))); break; }
diff --git a/net/log/trace_net_log_observer_unittest.cc b/net/log/trace_net_log_observer_unittest.cc index a56ab4c..5c63f41 100644 --- a/net/log/trace_net_log_observer_unittest.cc +++ b/net/log/trace_net_log_observer_unittest.cc
@@ -4,6 +4,7 @@ #include "net/log/trace_net_log_observer.h" +#include <memory> #include <string> #include <vector> @@ -11,7 +12,6 @@ #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/memory/ref_counted_memory.h" -#include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "base/strings/stringprintf.h" #include "base/trace_event/trace_buffer.h" @@ -75,7 +75,7 @@ trace_buffer_.AddFragment(events_str->data()); trace_buffer_.Finish(); - scoped_ptr<base::Value> trace_value; + std::unique_ptr<base::Value> trace_value; trace_value = base::JSONReader::Read( json_output_.json_output, base::JSON_PARSE_RFC | base::JSON_DETACHABLE_CHILDREN); @@ -109,9 +109,10 @@ trace_net_log_observer_.reset(trace_net_log_observer); } - static scoped_ptr<base::ListValue> FilterNetLogTraceEvents( + static std::unique_ptr<base::ListValue> FilterNetLogTraceEvents( const base::ListValue& trace_events) { - scoped_ptr<base::ListValue> filtered_trace_events(new base::ListValue()); + std::unique_ptr<base::ListValue> filtered_trace_events( + new base::ListValue()); for (size_t i = 0; i < trace_events.GetSize(); i++) { const base::DictionaryValue* dict = NULL; if (!trace_events.GetDictionary(i, &dict)) { @@ -140,11 +141,11 @@ } private: - scoped_ptr<base::ListValue> trace_events_; + std::unique_ptr<base::ListValue> trace_events_; base::trace_event::TraceResultBuffer trace_buffer_; base::trace_event::TraceResultBuffer::SimpleOutput json_output_; TestNetLog net_log_; - scoped_ptr<TraceNetLogObserver> trace_net_log_observer_; + std::unique_ptr<TraceNetLogObserver> trace_net_log_observer_; }; TEST_F(TraceNetLogObserverTest, TracingNotEnabled) {
diff --git a/net/log/write_to_file_net_log_observer.cc b/net/log/write_to_file_net_log_observer.cc index 3bc7814..f724da4 100644 --- a/net/log/write_to_file_net_log_observer.cc +++ b/net/log/write_to_file_net_log_observer.cc
@@ -5,12 +5,13 @@ #include "net/log/write_to_file_net_log_observer.h" #include <stdio.h> + +#include <memory> #include <set> #include <utility> #include "base/json/json_writer.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/values.h" #include "net/log/net_log_util.h" #include "net/url_request/url_request_context.h" @@ -90,7 +91,7 @@ // Add a comma and newline for every event but the first. Newlines are needed // so can load partial log files by just ignoring the last line. For this to // work, lines cannot be pretty printed. - scoped_ptr<base::Value> value(entry.ToValue()); + std::unique_ptr<base::Value> value(entry.ToValue()); std::string json; base::JSONWriter::Write(*value, &json); fprintf(file_.get(), "%s%s", (added_events_ ? ",\n" : ""), json.c_str());
diff --git a/net/log/write_to_file_net_log_observer_unittest.cc b/net/log/write_to_file_net_log_observer_unittest.cc index ddc8aa9..c1ab52f 100644 --- a/net/log/write_to_file_net_log_observer_unittest.cc +++ b/net/log/write_to_file_net_log_observer_unittest.cc
@@ -4,6 +4,7 @@ #include "net/log/write_to_file_net_log_observer.h" +#include <memory> #include <utility> #include "base/files/file_path.h" @@ -11,7 +12,6 @@ #include "base/files/scoped_file.h" #include "base/files/scoped_temp_dir.h" #include "base/json/json_reader.h" -#include "base/memory/scoped_ptr.h" #include "base/values.h" #include "net/log/net_log.h" #include "net/log/net_log_util.h" @@ -41,7 +41,8 @@ // Create and destroy a logger. base::ScopedFILE file(base::OpenFile(log_path_, "w")); ASSERT_TRUE(file); - scoped_ptr<WriteToFileNetLogObserver> logger(new WriteToFileNetLogObserver()); + std::unique_ptr<WriteToFileNetLogObserver> logger( + new WriteToFileNetLogObserver()); logger->StartObserving(&net_log_, std::move(file), nullptr, nullptr); logger->StopObserving(nullptr); logger.reset(); @@ -50,7 +51,7 @@ ASSERT_TRUE(base::ReadFileToString(log_path_, &input)); base::JSONReader reader; - scoped_ptr<base::Value> root(reader.ReadToValue(input)); + std::unique_ptr<base::Value> root(reader.ReadToValue(input)); ASSERT_TRUE(root) << reader.GetErrorMessage(); base::DictionaryValue* dict; @@ -83,7 +84,8 @@ TEST_F(WriteToFileNetLogObserverTest, GeneratesValidJSONWithOneEvent) { base::ScopedFILE file(base::OpenFile(log_path_, "w")); ASSERT_TRUE(file); - scoped_ptr<WriteToFileNetLogObserver> logger(new WriteToFileNetLogObserver()); + std::unique_ptr<WriteToFileNetLogObserver> logger( + new WriteToFileNetLogObserver()); logger->StartObserving(&net_log_, std::move(file), nullptr, nullptr); const int kDummyId = 1; @@ -100,7 +102,7 @@ ASSERT_TRUE(base::ReadFileToString(log_path_, &input)); base::JSONReader reader; - scoped_ptr<base::Value> root(reader.ReadToValue(input)); + std::unique_ptr<base::Value> root(reader.ReadToValue(input)); ASSERT_TRUE(root) << reader.GetErrorMessage(); base::DictionaryValue* dict; @@ -113,7 +115,8 @@ TEST_F(WriteToFileNetLogObserverTest, GeneratesValidJSONWithMultipleEvents) { base::ScopedFILE file(base::OpenFile(log_path_, "w")); ASSERT_TRUE(file); - scoped_ptr<WriteToFileNetLogObserver> logger(new WriteToFileNetLogObserver()); + std::unique_ptr<WriteToFileNetLogObserver> logger( + new WriteToFileNetLogObserver()); logger->StartObserving(&net_log_, std::move(file), nullptr, nullptr); const int kDummyId = 1; @@ -133,7 +136,7 @@ ASSERT_TRUE(base::ReadFileToString(log_path_, &input)); base::JSONReader reader; - scoped_ptr<base::Value> root(reader.ReadToValue(input)); + std::unique_ptr<base::Value> root(reader.ReadToValue(input)); ASSERT_TRUE(root) << reader.GetErrorMessage(); base::DictionaryValue* dict; @@ -145,10 +148,12 @@ TEST_F(WriteToFileNetLogObserverTest, CustomConstants) { const char kConstantString[] = "awesome constant"; - scoped_ptr<base::Value> constants(new base::StringValue(kConstantString)); + std::unique_ptr<base::Value> constants( + new base::StringValue(kConstantString)); base::ScopedFILE file(base::OpenFile(log_path_, "w")); ASSERT_TRUE(file); - scoped_ptr<WriteToFileNetLogObserver> logger(new WriteToFileNetLogObserver()); + std::unique_ptr<WriteToFileNetLogObserver> logger( + new WriteToFileNetLogObserver()); logger->StartObserving(&net_log_, std::move(file), constants.get(), nullptr); logger->StopObserving(nullptr); logger.reset(); @@ -157,7 +162,7 @@ ASSERT_TRUE(base::ReadFileToString(log_path_, &input)); base::JSONReader reader; - scoped_ptr<base::Value> root(reader.ReadToValue(input)); + std::unique_ptr<base::Value> root(reader.ReadToValue(input)); ASSERT_TRUE(root) << reader.GetErrorMessage(); base::DictionaryValue* dict; @@ -176,7 +181,8 @@ // Create and destroy a logger. base::ScopedFILE file(base::OpenFile(log_path_, "w")); ASSERT_TRUE(file); - scoped_ptr<WriteToFileNetLogObserver> logger(new WriteToFileNetLogObserver()); + std::unique_ptr<WriteToFileNetLogObserver> logger( + new WriteToFileNetLogObserver()); logger->StartObserving(&net_log_, std::move(file), nullptr, &context); logger->StopObserving(&context); logger.reset(); @@ -185,7 +191,7 @@ ASSERT_TRUE(base::ReadFileToString(log_path_, &input)); base::JSONReader reader; - scoped_ptr<base::Value> root(reader.ReadToValue(input)); + std::unique_ptr<base::Value> root(reader.ReadToValue(input)); ASSERT_TRUE(root) << reader.GetErrorMessage(); base::DictionaryValue* dict; @@ -208,14 +214,15 @@ TestDelegate delegate; // URL doesn't matter. Requests can't fail synchronously. - scoped_ptr<URLRequest> request( + std::unique_ptr<URLRequest> request( context.CreateRequest(GURL("blah:blah"), IDLE, &delegate)); request->Start(); // Create and destroy a logger. base::ScopedFILE file(base::OpenFile(log_path_, "w")); ASSERT_TRUE(file); - scoped_ptr<WriteToFileNetLogObserver> logger(new WriteToFileNetLogObserver()); + std::unique_ptr<WriteToFileNetLogObserver> logger( + new WriteToFileNetLogObserver()); logger->StartObserving(&net_log_, std::move(file), nullptr, &context); logger->StopObserving(&context); logger.reset(); @@ -224,7 +231,7 @@ ASSERT_TRUE(base::ReadFileToString(log_path_, &input)); base::JSONReader reader; - scoped_ptr<base::Value> root(reader.ReadToValue(input)); + std::unique_ptr<base::Value> root(reader.ReadToValue(input)); ASSERT_TRUE(root) << reader.GetErrorMessage(); base::DictionaryValue* dict;
diff --git a/net/sdch/sdch_owner.cc b/net/sdch/sdch_owner.cc index 03e268e..5dc949a 100644 --- a/net/sdch/sdch_owner.cc +++ b/net/sdch/sdch_owner.cc
@@ -10,6 +10,7 @@ #include "base/debug/alias.h" #include "base/logging.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_util.h" #include "base/time/default_clock.h" @@ -79,7 +80,7 @@ *result = &storage_; return true; } - void SetValue(scoped_ptr<base::DictionaryValue> value) override { + void SetValue(std::unique_ptr<base::DictionaryValue> value) override { storage_.Clear(); storage_.MergeDictionary(value.get()); } @@ -119,10 +120,10 @@ // above schema, removing anything previously in the store under // kPreferenceName. void InitializePrefStore(SdchOwner::PrefStorage* store) { - scoped_ptr<base::DictionaryValue> empty_store(new base::DictionaryValue); + std::unique_ptr<base::DictionaryValue> empty_store(new base::DictionaryValue); empty_store->SetInteger(kVersionKey, kVersion); empty_store->Set(kDictionariesKey, - make_scoped_ptr(new base::DictionaryValue)); + base::WrapUnique(new base::DictionaryValue)); store->SetValue(std::move(empty_store)); } @@ -338,7 +339,8 @@ } } -void SdchOwner::EnablePersistentStorage(scoped_ptr<PrefStorage> pref_store) { +void SdchOwner::EnablePersistentStorage( + std::unique_ptr<PrefStorage> pref_store) { DCHECK(!external_pref_store_); DCHECK(pref_store); external_pref_store_ = std::move(pref_store); @@ -483,7 +485,7 @@ total_dictionary_bytes_ += dictionary_text.size(); // Record the addition in the pref store. - scoped_ptr<base::DictionaryValue> dictionary_description( + std::unique_ptr<base::DictionaryValue> dictionary_description( new base::DictionaryValue()); dictionary_description->SetString(kDictionaryUrlKey, dictionary_url.spec()); dictionary_description->SetDouble(kDictionaryLastUsedKey, @@ -640,7 +642,7 @@ in_memory_pref_store_ = nullptr; } -void SdchOwner::SetClockForTesting(scoped_ptr<base::Clock> clock) { +void SdchOwner::SetClockForTesting(std::unique_ptr<base::Clock> clock) { clock_ = std::move(clock); } @@ -663,7 +665,7 @@ } void SdchOwner::SetFetcherForTesting( - scoped_ptr<SdchDictionaryFetcher> fetcher) { + std::unique_ptr<SdchDictionaryFetcher> fetcher) { fetcher_ = std::move(fetcher); }
diff --git a/net/sdch/sdch_owner.h b/net/sdch/sdch_owner.h index 6af0bf0..e6af266 100644 --- a/net/sdch/sdch_owner.h +++ b/net/sdch/sdch_owner.h
@@ -70,7 +70,7 @@ // Gets or sets the value in the preferences store. virtual bool GetValue(const base::DictionaryValue** result) const = 0; virtual bool GetMutableValue(base::DictionaryValue** result) = 0; - virtual void SetValue(scoped_ptr<base::DictionaryValue> value) = 0; + virtual void SetValue(std::unique_ptr<base::DictionaryValue> value) = 0; // Notifies the storage system that a value was changed via mutating the // result of GetMutableValue(). @@ -98,7 +98,7 @@ // Enables use of pref persistence. Ownership of the storage will be passed. // This routine may only be called once per SdchOwner instance. - void EnablePersistentStorage(scoped_ptr<PrefStorage> pref_store); + void EnablePersistentStorage(std::unique_ptr<PrefStorage> pref_store); // Defaults to kMaxTotalDictionarySize. void SetMaxTotalDictionarySize(size_t max_total_dictionary_size); @@ -131,7 +131,7 @@ const BoundNetLog& net_log, bool was_from_cache); - void SetClockForTesting(scoped_ptr<base::Clock> clock); + void SetClockForTesting(std::unique_ptr<base::Clock> clock); // Returns the total number of dictionaries loaded. int GetDictionaryCountForTesting() const; @@ -139,7 +139,7 @@ // Returns whether this SdchOwner has dictionary from |url| loaded. bool HasDictionaryFromURLForTesting(const GURL& url) const; - void SetFetcherForTesting(scoped_ptr<SdchDictionaryFetcher> fetcher); + void SetFetcherForTesting(std::unique_ptr<SdchDictionaryFetcher> fetcher); private: // For each active dictionary, stores local info. @@ -215,11 +215,11 @@ int use_count, DictionaryFate fate); net::SdchManager* manager_; - scoped_ptr<net::SdchDictionaryFetcher> fetcher_; + std::unique_ptr<net::SdchDictionaryFetcher> fetcher_; size_t total_dictionary_bytes_; - scoped_ptr<base::Clock> clock_; + std::unique_ptr<base::Clock> clock_; size_t max_total_dictionary_size_; size_t min_space_for_dictionary_fetch_; @@ -239,8 +239,8 @@ // be freed, and pref_store_ will point to the external one. // * |pref_store_| holds an unowned pointer to the currently // active pref store (one of the preceding two). - scoped_ptr<PrefStorage> in_memory_pref_store_; - scoped_ptr<PrefStorage> external_pref_store_; + std::unique_ptr<PrefStorage> in_memory_pref_store_; + std::unique_ptr<PrefStorage> external_pref_store_; PrefStorage* pref_store_; // The use counts of dictionaries when they were loaded from the persistent
diff --git a/net/sdch/sdch_owner_unittest.cc b/net/sdch/sdch_owner_unittest.cc index 91d1e6d51..7b36dee 100644 --- a/net/sdch/sdch_owner_unittest.cc +++ b/net/sdch/sdch_owner_unittest.cc
@@ -9,6 +9,7 @@ #include "base/location.h" #include "base/macros.h" #include "base/memory/memory_pressure_listener.h" +#include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/stringprintf.h" @@ -91,7 +92,7 @@ *result = &storage_; return true; } - void SetValue(scoped_ptr<base::DictionaryValue> value) override { + void SetValue(std::unique_ptr<base::DictionaryValue> value) override { storage_.Clear(); storage_.MergeDictionary(value.get()); } @@ -334,7 +335,7 @@ bool DictionaryPresentInManager(const std::string& server_hash) { // Presumes all tests use generic url. SdchProblemCode tmp; - scoped_ptr<SdchManager::DictionarySet> set( + std::unique_ptr<SdchManager::DictionarySet> set( sdch_manager_.GetDictionarySetByHash(GURL(generic_url), server_hash, &tmp)); return !!set.get(); @@ -405,7 +406,7 @@ MockURLRequestJobFactory job_factory_; URLRequestContext url_request_context_; SdchManager sdch_manager_; - scoped_ptr<SdchOwner> sdch_owner_; + std::unique_ptr<SdchOwner> sdch_owner_; DISALLOW_COPY_AND_ASSIGN(SdchOwnerTest); }; @@ -477,7 +478,7 @@ std::string server_hash_d3; base::SimpleTestClock* test_clock = new base::SimpleTestClock(); - sdch_owner().SetClockForTesting(make_scoped_ptr(test_clock)); + sdch_owner().SetClockForTesting(base::WrapUnique(test_clock)); test_clock->SetNow(base::Time::Now()); // Add two dictionaries, one recent, one more than a day in the past. @@ -734,13 +735,13 @@ // Pass ownership of the storage to the SdchOwner, but keep a pointer. TestPrefStorage* pref_store = new TestPrefStorage(true); sdch_owner().EnablePersistentStorage( - scoped_ptr<SdchOwner::PrefStorage>(pref_store)); + std::unique_ptr<SdchOwner::PrefStorage>(pref_store)); std::string server_hash_d1; EXPECT_TRUE(CreateAndAddDictionary(kMaxSizeForTesting / 2, base::Time::Now(), &server_hash_d1)); - scoped_ptr<SdchManager::DictionarySet> return_set( + std::unique_ptr<SdchManager::DictionarySet> return_set( sdch_manager().GetDictionarySet( GURL(std::string(generic_url) + "/x.html"))); ASSERT_TRUE(return_set.get()); @@ -758,7 +759,7 @@ EXPECT_TRUE(dict_result->Get("dictionaries", &result)); EXPECT_FALSE(dict_result->Get("dictionaries." + server_hash_d1, &result)); - scoped_ptr<SdchManager::DictionarySet> return_set2( + std::unique_ptr<SdchManager::DictionarySet> return_set2( sdch_manager().GetDictionarySet( GURL(std::string(generic_url) + "/x.html"))); EXPECT_FALSE(return_set2.get()); @@ -802,7 +803,7 @@ // If the storage points is non-null it will be saved as the persistent // storage for the SdchOwner. - void ResetOwner(scoped_ptr<SdchOwner::PrefStorage> storage) { + void ResetOwner(std::unique_ptr<SdchOwner::PrefStorage> storage) { // This has to be done first, since SdchOwner may be observing SdchManager, // and SdchManager can't be destroyed with a live observer. owner_.reset(NULL); @@ -813,7 +814,7 @@ owner_->SetMaxTotalDictionarySize(SdchOwnerTest::kMaxSizeForTesting); owner_->SetMinSpaceForDictionaryFetch( SdchOwnerTest::kMinFetchSpaceForTesting); - owner_->SetFetcherForTesting(make_scoped_ptr(fetcher_)); + owner_->SetFetcherForTesting(base::WrapUnique(fetcher_)); if (storage) owner_->EnablePersistentStorage(std::move(storage)); } @@ -842,24 +843,24 @@ protected: BoundNetLog net_log_; - scoped_ptr<SdchManager> manager_; + std::unique_ptr<SdchManager> manager_; MockSdchDictionaryFetcher* fetcher_; - scoped_ptr<SdchOwner> owner_; + std::unique_ptr<SdchOwner> owner_; TestURLRequestContext url_request_context_; }; // Test an empty persistence store. TEST_F(SdchOwnerPersistenceTest, Empty) { - ResetOwner(make_scoped_ptr(new TestPrefStorage(true))); + ResetOwner(base::WrapUnique(new TestPrefStorage(true))); EXPECT_EQ(0, owner_->GetDictionaryCountForTesting()); } // Test a persistence store with a bad version number. TEST_F(SdchOwnerPersistenceTest, Persistent_BadVersion) { - scoped_ptr<base::DictionaryValue> sdch_dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> sdch_dict(new base::DictionaryValue()); sdch_dict->SetInteger("version", 2); - scoped_ptr<TestPrefStorage> storage(new TestPrefStorage(true)); + std::unique_ptr<TestPrefStorage> storage(new TestPrefStorage(true)); storage->SetValue(std::move(sdch_dict)); TestPrefStorage* old_storage = storage.get(); // Save storage pointer. @@ -872,12 +873,12 @@ // Test a persistence store with an empty dictionaries map. TEST_F(SdchOwnerPersistenceTest, Persistent_EmptyDictList) { - scoped_ptr<base::DictionaryValue> sdch_dict(new base::DictionaryValue()); - scoped_ptr<base::DictionaryValue> dicts(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> sdch_dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dicts(new base::DictionaryValue()); sdch_dict->SetInteger("version", 1); sdch_dict->Set("dictionaries", std::move(dicts)); - scoped_ptr<TestPrefStorage> storage(new TestPrefStorage(true)); + std::unique_ptr<TestPrefStorage> storage(new TestPrefStorage(true)); storage->SetValue(std::move(sdch_dict)); ResetOwner(std::move(storage)); EXPECT_EQ(0, owner_->GetDictionaryCountForTesting()); @@ -886,7 +887,7 @@ TEST_F(SdchOwnerPersistenceTest, OneDict) { const GURL url("http://www.example.com/dict"); - scoped_ptr<TestPrefStorage> storage(new TestPrefStorage(true)); + std::unique_ptr<TestPrefStorage> storage(new TestPrefStorage(true)); TestPrefStorage* old_storage = storage.get(); // Save storage pointer. ResetOwner(std::move(storage)); // Takes ownership of storage pointer. EXPECT_EQ(0, owner_->GetDictionaryCountForTesting()); @@ -904,7 +905,7 @@ const GURL url0("http://www.example.com/dict0"); const GURL url1("http://www.example.com/dict1"); - scoped_ptr<TestPrefStorage> storage(new TestPrefStorage(true)); + std::unique_ptr<TestPrefStorage> storage(new TestPrefStorage(true)); TestPrefStorage* old_storage = storage.get(); // Save storage pointer. ResetOwner(std::move(storage)); // Takes ownership of storage pointer. InsertDictionaryForURL(url0, "0"); @@ -923,7 +924,7 @@ const GURL url0("http://www.example.com/dict0"); const GURL url1("http://www.example.com/dict1"); - scoped_ptr<TestPrefStorage> storage(new TestPrefStorage(true)); + std::unique_ptr<TestPrefStorage> storage(new TestPrefStorage(true)); TestPrefStorage* old_storage = storage.get(); // Save storage pointer. ResetOwner(std::move(storage)); // Takes ownership of storage. InsertDictionaryForURL(url0, "0"); @@ -946,7 +947,7 @@ TEST_F(SdchOwnerPersistenceTest, UsingDictionaryUpdatesUseCount) { const GURL url("http://www.example.com/dict"); - scoped_ptr<TestPrefStorage> storage(new TestPrefStorage(true)); + std::unique_ptr<TestPrefStorage> storage(new TestPrefStorage(true)); TestPrefStorage* old_storage = storage.get(); // Save storage pointer. ResetOwner(std::move(storage)); // Takes ownership of storage pointer. InsertDictionaryForURL(url, "0"); @@ -980,13 +981,13 @@ const GURL url0("http://www.example.com/dict0"); const GURL url1("http://www.example.com/dict1"); - scoped_ptr<TestPrefStorage> storage(new TestPrefStorage(true)); + std::unique_ptr<TestPrefStorage> storage(new TestPrefStorage(true)); TestPrefStorage* old_storage = storage.get(); // Save storage pointer. ResetOwner(std::move(storage)); // Takes ownership of storage pointer. InsertDictionaryForURL(url1, "1"); storage.reset(new TestPrefStorage(*old_storage)); - ResetOwner(scoped_ptr<SdchOwner::PrefStorage>()); + ResetOwner(std::unique_ptr<SdchOwner::PrefStorage>()); InsertDictionaryForURL(url0, "0"); EXPECT_EQ(1, owner_->GetDictionaryCountForTesting()); owner_->EnablePersistentStorage(std::move(storage)); @@ -998,7 +999,7 @@ const GURL url0("http://www.example.com/dict0"); const GURL url1("http://www.example.com/dict1"); - scoped_ptr<TestPrefStorage> storage(new TestPrefStorage(true)); + std::unique_ptr<TestPrefStorage> storage(new TestPrefStorage(true)); TestPrefStorage* old_storage = storage.get(); // Save storage pointer. ResetOwner(std::move(storage)); // Takes ownership of storage pointer.
diff --git a/net/server/http_connection.cc b/net/server/http_connection.cc index d4d16ca..6933043 100644 --- a/net/server/http_connection.cc +++ b/net/server/http_connection.cc
@@ -150,7 +150,7 @@ return pending_data_.front().size() - consumed; } -HttpConnection::HttpConnection(int id, scoped_ptr<StreamSocket> socket) +HttpConnection::HttpConnection(int id, std::unique_ptr<StreamSocket> socket) : id_(id), socket_(std::move(socket)), read_buf_(new ReadIOBuffer()), @@ -159,7 +159,7 @@ HttpConnection::~HttpConnection() { } -void HttpConnection::SetWebSocket(scoped_ptr<WebSocket> web_socket) { +void HttpConnection::SetWebSocket(std::unique_ptr<WebSocket> web_socket) { DCHECK(!web_socket_); web_socket_ = std::move(web_socket); }
diff --git a/net/server/http_connection.h b/net/server/http_connection.h index 8103e4e..e708d35 100644 --- a/net/server/http_connection.h +++ b/net/server/http_connection.h
@@ -5,12 +5,12 @@ #ifndef NET_SERVER_HTTP_CONNECTION_H_ #define NET_SERVER_HTTP_CONNECTION_H_ +#include <memory> #include <queue> #include <string> #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "net/base/io_buffer.h" namespace net { @@ -110,7 +110,7 @@ DISALLOW_COPY_AND_ASSIGN(QueuedWriteIOBuffer); }; - HttpConnection(int id, scoped_ptr<StreamSocket> socket); + HttpConnection(int id, std::unique_ptr<StreamSocket> socket); ~HttpConnection(); int id() const { return id_; } @@ -119,15 +119,15 @@ QueuedWriteIOBuffer* write_buf() const { return write_buf_.get(); } WebSocket* web_socket() const { return web_socket_.get(); } - void SetWebSocket(scoped_ptr<WebSocket> web_socket); + void SetWebSocket(std::unique_ptr<WebSocket> web_socket); private: const int id_; - const scoped_ptr<StreamSocket> socket_; + const std::unique_ptr<StreamSocket> socket_; const scoped_refptr<ReadIOBuffer> read_buf_; const scoped_refptr<QueuedWriteIOBuffer> write_buf_; - scoped_ptr<WebSocket> web_socket_; + std::unique_ptr<WebSocket> web_socket_; DISALLOW_COPY_AND_ASSIGN(HttpConnection); };
diff --git a/net/server/http_server.cc b/net/server/http_server.cc index ab05af8..d33aaec8 100644 --- a/net/server/http_server.cc +++ b/net/server/http_server.cc
@@ -10,6 +10,7 @@ #include "base/compiler_specific.h" #include "base/location.h" #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" @@ -29,7 +30,7 @@ namespace net { -HttpServer::HttpServer(scoped_ptr<ServerSocket> server_socket, +HttpServer::HttpServer(std::unique_ptr<ServerSocket> server_socket, HttpServer::Delegate* delegate) : server_socket_(std::move(server_socket)), delegate_(delegate), @@ -239,7 +240,7 @@ if (request.HasHeaderValue("connection", "upgrade")) { connection->SetWebSocket( - make_scoped_ptr(new WebSocket(this, connection))); + base::WrapUnique(new WebSocket(this, connection))); read_buf->DidConsume(pos); delegate_->OnWebSocketRequest(connection->id(), request); if (HasClosedConnection(connection))
diff --git a/net/server/http_server.h b/net/server/http_server.h index 7e103dd..a0062d6 100644 --- a/net/server/http_server.h +++ b/net/server/http_server.h
@@ -9,10 +9,10 @@ #include <stdint.h> #include <map> +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "net/http/http_status_code.h" @@ -48,7 +48,7 @@ // listening, but not accepting. This constructor schedules accepting // connections asynchronously in case when |delegate| is not ready to get // callbacks yet. - HttpServer(scoped_ptr<ServerSocket> server_socket, + HttpServer(std::unique_ptr<ServerSocket> server_socket, HttpServer::Delegate* delegate); ~HttpServer(); @@ -109,8 +109,8 @@ // Whether or not Close() has been called during delegate callback processing. bool HasClosedConnection(HttpConnection* connection); - const scoped_ptr<ServerSocket> server_socket_; - scoped_ptr<StreamSocket> accepted_socket_; + const std::unique_ptr<ServerSocket> server_socket_; + std::unique_ptr<StreamSocket> accepted_socket_; HttpServer::Delegate* const delegate_; int last_id_;
diff --git a/net/server/http_server_unittest.cc b/net/server/http_server_unittest.cc index 2b4c9e6e..8ab1b37 100644 --- a/net/server/http_server_unittest.cc +++ b/net/server/http_server_unittest.cc
@@ -2,9 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "net/server/http_server.h" + #include <stdint.h> #include <algorithm> +#include <memory> #include <utility> #include <vector> @@ -16,8 +19,8 @@ #include "base/location.h" #include "base/logging.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" @@ -34,7 +37,6 @@ #include "net/http/http_response_headers.h" #include "net/http/http_util.h" #include "net/log/net_log.h" -#include "net/server/http_server.h" #include "net/server/http_server_request_info.h" #include "net/socket/tcp_client_socket.h" #include "net/socket/tcp_server_socket.h" @@ -173,7 +175,7 @@ scoped_refptr<IOBufferWithSize> read_buffer_; scoped_refptr<DrainableIOBuffer> write_buffer_; - scoped_ptr<TCPClientSocket> socket_; + std::unique_ptr<TCPClientSocket> socket_; int connect_result_; }; @@ -185,7 +187,7 @@ HttpServerTest() : quit_after_request_count_(0) {} void SetUp() override { - scoped_ptr<ServerSocket> server_socket( + std::unique_ptr<ServerSocket> server_socket( new TCPServerSocket(NULL, NetLog::Source())); server_socket->ListenWithAddressAndPort("127.0.0.1", 0, 1); server_.reset(new HttpServer(std::move(server_socket), this)); @@ -232,13 +234,13 @@ return requests_[request_index].second; } - void HandleAcceptResult(scoped_ptr<StreamSocket> socket) { + void HandleAcceptResult(std::unique_ptr<StreamSocket> socket) { server_->accepted_socket_.reset(socket.release()); server_->HandleAcceptResult(OK); } protected: - scoped_ptr<HttpServer> server_; + std::unique_ptr<HttpServer> server_; IPEndPoint server_address_; base::Closure run_loop_quit_func_; std::vector<std::pair<HttpServerRequestInfo, int> > requests_; @@ -423,7 +425,7 @@ scoped_refptr<URLRequestContextGetter> request_context_getter( new TestURLRequestContextGetter(base::ThreadTaskRunnerHandle::Get())); - scoped_ptr<URLFetcher> fetcher = + std::unique_ptr<URLFetcher> fetcher = URLFetcher::Create(GURL(base::StringPrintf("http://127.0.0.1:%d/test", server_address_.port())), URLFetcher::GET, &delegate); @@ -568,7 +570,7 @@ TEST_F(HttpServerTest, RequestWithBodySplitAcrossPackets) { MockStreamSocket* socket = new MockStreamSocket(); - HandleAcceptResult(make_scoped_ptr<StreamSocket>(socket)); + HandleAcceptResult(base::WrapUnique<StreamSocket>(socket)); std::string body("body"); std::string request_text = base::StringPrintf( "GET /test HTTP/1.1\r\n"
diff --git a/net/server/web_socket.h b/net/server/web_socket.h index 19e9c71a..aa01f11 100644 --- a/net/server/web_socket.h +++ b/net/server/web_socket.h
@@ -5,10 +5,10 @@ #ifndef NET_SERVER_WEB_SOCKET_H_ #define NET_SERVER_WEB_SOCKET_H_ +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string_piece.h" namespace net { @@ -40,7 +40,7 @@ HttpServer* const server_; HttpConnection* const connection_; - scoped_ptr<WebSocketEncoder> encoder_; + std::unique_ptr<WebSocketEncoder> encoder_; bool closed_; DISALLOW_COPY_AND_ASSIGN(WebSocket);
diff --git a/net/server/web_socket_encoder.cc b/net/server/web_socket_encoder.cc index d90a156..60a9a47 100644 --- a/net/server/web_socket_encoder.cc +++ b/net/server/web_socket_encoder.cc
@@ -9,6 +9,7 @@ #include <vector> #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "net/base/io_buffer.h" @@ -186,12 +187,12 @@ } // anonymous namespace // static -scoped_ptr<WebSocketEncoder> WebSocketEncoder::CreateServer() { - return make_scoped_ptr(new WebSocketEncoder(FOR_SERVER, nullptr, nullptr)); +std::unique_ptr<WebSocketEncoder> WebSocketEncoder::CreateServer() { + return base::WrapUnique(new WebSocketEncoder(FOR_SERVER, nullptr, nullptr)); } // static -scoped_ptr<WebSocketEncoder> WebSocketEncoder::CreateServer( +std::unique_ptr<WebSocketEncoder> WebSocketEncoder::CreateServer( const std::string& extensions, WebSocketDeflateParameters* deflate_parameters) { WebSocketExtensionParser parser; @@ -218,9 +219,9 @@ } DCHECK(response.IsValidAsResponse()); DCHECK(offer.IsCompatibleWith(response)); - auto deflater = make_scoped_ptr( + auto deflater = base::WrapUnique( new WebSocketDeflater(response.server_context_take_over_mode())); - auto inflater = make_scoped_ptr( + auto inflater = base::WrapUnique( new WebSocketInflater(kInflaterChunkSize, kInflaterChunkSize)); if (!deflater->Initialize(response.PermissiveServerMaxWindowBits()) || !inflater->Initialize(response.PermissiveClientMaxWindowBits())) { @@ -228,16 +229,16 @@ continue; } *deflate_parameters = response; - return make_scoped_ptr(new WebSocketEncoder(FOR_SERVER, std::move(deflater), - std::move(inflater))); + return base::WrapUnique(new WebSocketEncoder( + FOR_SERVER, std::move(deflater), std::move(inflater))); } // We cannot find an acceptable offer. - return make_scoped_ptr(new WebSocketEncoder(FOR_SERVER, nullptr, nullptr)); + return base::WrapUnique(new WebSocketEncoder(FOR_SERVER, nullptr, nullptr)); } // static -scoped_ptr<WebSocketEncoder> WebSocketEncoder::CreateClient( +std::unique_ptr<WebSocketEncoder> WebSocketEncoder::CreateClient( const std::string& response_extensions) { // TODO(yhirano): Add a way to return an error. @@ -248,12 +249,12 @@ // 2) There is a malformed Sec-WebSocketExtensions header. // We should return a deflate-disabled encoder for the former case and // fail the connection for the latter case. - return make_scoped_ptr(new WebSocketEncoder(FOR_CLIENT, nullptr, nullptr)); + return base::WrapUnique(new WebSocketEncoder(FOR_CLIENT, nullptr, nullptr)); } if (parser.extensions().size() != 1) { // Only permessage-deflate extension is supported. // TODO (yhirano): Fail the connection. - return make_scoped_ptr(new WebSocketEncoder(FOR_CLIENT, nullptr, nullptr)); + return base::WrapUnique(new WebSocketEncoder(FOR_CLIENT, nullptr, nullptr)); } const auto& extension = parser.extensions()[0]; WebSocketDeflateParameters params; @@ -261,26 +262,26 @@ if (!params.Initialize(extension, &failure_message) || !params.IsValidAsResponse(&failure_message)) { // TODO (yhirano): Fail the connection. - return make_scoped_ptr(new WebSocketEncoder(FOR_CLIENT, nullptr, nullptr)); + return base::WrapUnique(new WebSocketEncoder(FOR_CLIENT, nullptr, nullptr)); } - auto deflater = make_scoped_ptr( + auto deflater = base::WrapUnique( new WebSocketDeflater(params.client_context_take_over_mode())); - auto inflater = make_scoped_ptr( + auto inflater = base::WrapUnique( new WebSocketInflater(kInflaterChunkSize, kInflaterChunkSize)); if (!deflater->Initialize(params.PermissiveClientMaxWindowBits()) || !inflater->Initialize(params.PermissiveServerMaxWindowBits())) { // TODO (yhirano): Fail the connection. - return make_scoped_ptr(new WebSocketEncoder(FOR_CLIENT, nullptr, nullptr)); + return base::WrapUnique(new WebSocketEncoder(FOR_CLIENT, nullptr, nullptr)); } - return make_scoped_ptr(new WebSocketEncoder(FOR_CLIENT, std::move(deflater), - std::move(inflater))); + return base::WrapUnique(new WebSocketEncoder(FOR_CLIENT, std::move(deflater), + std::move(inflater))); } WebSocketEncoder::WebSocketEncoder(Type type, - scoped_ptr<WebSocketDeflater> deflater, - scoped_ptr<WebSocketInflater> inflater) + std::unique_ptr<WebSocketDeflater> deflater, + std::unique_ptr<WebSocketInflater> inflater) : type_(type), deflater_(std::move(deflater)), inflater_(std::move(inflater)) {}
diff --git a/net/server/web_socket_encoder.h b/net/server/web_socket_encoder.h index caeec94..af81228 100644 --- a/net/server/web_socket_encoder.h +++ b/net/server/web_socket_encoder.h
@@ -5,10 +5,10 @@ #ifndef NET_SERVER_WEB_SOCKET_ENCODER_H_ #define NET_SERVER_WEB_SOCKET_ENCODER_H_ +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string_piece.h" #include "net/server/web_socket.h" #include "net/websockets/websocket_deflater.h" @@ -25,14 +25,14 @@ ~WebSocketEncoder(); // Creates and returns an encoder for a server without extensions. - static scoped_ptr<WebSocketEncoder> CreateServer(); + static std::unique_ptr<WebSocketEncoder> CreateServer(); // Creates and returns an encoder. // |extensions| is the value of a Sec-WebSocket-Extensions header. // Returns nullptr when there is an error. - static scoped_ptr<WebSocketEncoder> CreateServer( + static std::unique_ptr<WebSocketEncoder> CreateServer( const std::string& extensions, WebSocketDeflateParameters* params); - static scoped_ptr<WebSocketEncoder> CreateClient( + static std::unique_ptr<WebSocketEncoder> CreateClient( const std::string& response_extensions); WebSocket::ParseResult DecodeFrame(const base::StringPiece& frame, @@ -51,15 +51,15 @@ }; WebSocketEncoder(Type type, - scoped_ptr<WebSocketDeflater> deflater, - scoped_ptr<WebSocketInflater> inflater); + std::unique_ptr<WebSocketDeflater> deflater, + std::unique_ptr<WebSocketInflater> inflater); bool Inflate(std::string* message); bool Deflate(const std::string& message, std::string* output); Type type_; - scoped_ptr<WebSocketDeflater> deflater_; - scoped_ptr<WebSocketInflater> inflater_; + std::unique_ptr<WebSocketDeflater> deflater_; + std::unique_ptr<WebSocketInflater> inflater_; DISALLOW_COPY_AND_ASSIGN(WebSocketEncoder); };
diff --git a/net/server/web_socket_encoder_unittest.cc b/net/server/web_socket_encoder_unittest.cc index 27babda..711a852 100644 --- a/net/server/web_socket_encoder_unittest.cc +++ b/net/server/web_socket_encoder_unittest.cc
@@ -12,7 +12,7 @@ TEST(WebSocketEncoderHandshakeTest, EmptyRequestShouldBeRejected) { WebSocketDeflateParameters params; - scoped_ptr<WebSocketEncoder> server = + std::unique_ptr<WebSocketEncoder> server = WebSocketEncoder::CreateServer("", ¶ms); EXPECT_FALSE(server); @@ -21,7 +21,7 @@ TEST(WebSocketEncoderHandshakeTest, CreateServerWithoutClientMaxWindowBitsParameter) { WebSocketDeflateParameters params; - scoped_ptr<WebSocketEncoder> server = + std::unique_ptr<WebSocketEncoder> server = WebSocketEncoder::CreateServer("permessage-deflate", ¶ms); ASSERT_TRUE(server); @@ -32,7 +32,7 @@ TEST(WebSocketEncoderHandshakeTest, CreateServerWithServerNoContextTakeoverParameter) { WebSocketDeflateParameters params; - scoped_ptr<WebSocketEncoder> server = WebSocketEncoder::CreateServer( + std::unique_ptr<WebSocketEncoder> server = WebSocketEncoder::CreateServer( "permessage-deflate; server_no_context_takeover", ¶ms); ASSERT_TRUE(server); EXPECT_TRUE(server->deflate_enabled()); @@ -42,7 +42,7 @@ TEST(WebSocketEncoderHandshakeTest, FirstExtensionShouldBeChosen) { WebSocketDeflateParameters params; - scoped_ptr<WebSocketEncoder> server = WebSocketEncoder::CreateServer( + std::unique_ptr<WebSocketEncoder> server = WebSocketEncoder::CreateServer( "permessage-deflate; server_no_context_takeover," "permessage-deflate; server_max_window_bits=15", ¶ms); @@ -55,7 +55,7 @@ TEST(WebSocketEncoderHandshakeTest, FirstValidExtensionShouldBeChosen) { WebSocketDeflateParameters params; - scoped_ptr<WebSocketEncoder> server = WebSocketEncoder::CreateServer( + std::unique_ptr<WebSocketEncoder> server = WebSocketEncoder::CreateServer( "permessage-deflate; Xserver_no_context_takeover," "permessage-deflate; server_max_window_bits=15", ¶ms); @@ -68,7 +68,7 @@ TEST(WebSocketEncoderHandshakeTest, AllExtensionsAreUnknownOrMalformed) { WebSocketDeflateParameters params; - scoped_ptr<WebSocketEncoder> server = + std::unique_ptr<WebSocketEncoder> server = WebSocketEncoder::CreateServer("unknown, permessage-deflate; x", ¶ms); ASSERT_TRUE(server); @@ -87,8 +87,8 @@ } protected: - scoped_ptr<WebSocketEncoder> server_; - scoped_ptr<WebSocketEncoder> client_; + std::unique_ptr<WebSocketEncoder> server_; + std::unique_ptr<WebSocketEncoder> client_; }; class WebSocketEncoderCompressionTest : public WebSocketEncoderTest { @@ -108,8 +108,8 @@ }; TEST_F(WebSocketEncoderTest, DeflateDisabledEncoder) { - scoped_ptr<WebSocketEncoder> server = WebSocketEncoder::CreateServer(); - scoped_ptr<WebSocketEncoder> client = WebSocketEncoder::CreateClient(""); + std::unique_ptr<WebSocketEncoder> server = WebSocketEncoder::CreateServer(); + std::unique_ptr<WebSocketEncoder> client = WebSocketEncoder::CreateClient(""); ASSERT_TRUE(server); ASSERT_TRUE(client);
diff --git a/net/spdy/hpack/hpack_huffman_decoder.cc b/net/spdy/hpack/hpack_huffman_decoder.cc index 3573744..926223f 100644 --- a/net/spdy/hpack/hpack_huffman_decoder.cc +++ b/net/spdy/hpack/hpack_huffman_decoder.cc
@@ -158,7 +158,7 @@ }; // clang-format on -#ifndef NDEBUG +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) // Only used in DLOG. bool IsEOSPrefix(HuffmanWord bits, HuffmanCodeLength bits_available) { @@ -171,7 +171,7 @@ return bits == expected; } -#endif // NDEBUG +#endif // NDEBUG && !defined(DCHECK_ALWAYS_ON) } // namespace
diff --git a/net/ssl/channel_id_service.cc b/net/ssl/channel_id_service.cc index 7cae014..163a56b 100644 --- a/net/ssl/channel_id_service.cc +++ b/net/ssl/channel_id_service.cc
@@ -6,6 +6,7 @@ #include <algorithm> #include <limits> +#include <memory> #include <utility> #include "base/atomic_sequence_num.h" @@ -17,7 +18,6 @@ #include "base/logging.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/histogram_macros.h" #include "base/rand_util.h" #include "base/single_thread_task_runner.h" @@ -86,14 +86,14 @@ // Otherwise, returns NULL, and |*error| will be set to a net error code. // |serial_number| is passed in because base::RandInt cannot be called from an // unjoined thread, due to relying on a non-leaked LazyInstance -scoped_ptr<ChannelIDStore::ChannelID> GenerateChannelID( +std::unique_ptr<ChannelIDStore::ChannelID> GenerateChannelID( const std::string& server_identifier, int* error) { - scoped_ptr<ChannelIDStore::ChannelID> result; + std::unique_ptr<ChannelIDStore::ChannelID> result; base::TimeTicks start = base::TimeTicks::Now(); base::Time creation_time = base::Time::Now(); - scoped_ptr<crypto::ECPrivateKey> key(crypto::ECPrivateKey::Create()); + std::unique_ptr<crypto::ECPrivateKey> key(crypto::ECPrivateKey::Create()); if (!key) { DLOG(ERROR) << "Unable to create channel ID key pair"; @@ -119,10 +119,9 @@ // itself once Start() is called. class ChannelIDServiceWorker { public: - typedef base::Callback<void( - const std::string&, - int, - scoped_ptr<ChannelIDStore::ChannelID>)> WorkerDoneCallback; + typedef base::Callback< + void(const std::string&, int, std::unique_ptr<ChannelIDStore::ChannelID>)> + WorkerDoneCallback; ChannelIDServiceWorker(const std::string& server_identifier, const WorkerDoneCallback& callback) @@ -145,7 +144,7 @@ void Run() { // Runs on a worker thread. int error = ERR_FAILED; - scoped_ptr<ChannelIDStore::ChannelID> channel_id = + std::unique_ptr<ChannelIDStore::ChannelID> channel_id = GenerateChannelID(server_identifier_, &error); #if !defined(USE_OPENSSL) // Detach the thread from NSPR. @@ -186,7 +185,7 @@ requests_.push_back(request); } - void HandleResult(int error, scoped_ptr<crypto::ECPrivateKey> key) { + void HandleResult(int error, std::unique_ptr<crypto::ECPrivateKey> key) { PostAll(error, std::move(key)); } @@ -199,13 +198,13 @@ } private: - void PostAll(int error, scoped_ptr<crypto::ECPrivateKey> key) { + void PostAll(int error, std::unique_ptr<crypto::ECPrivateKey> key) { std::vector<ChannelIDService::Request*> requests; requests_.swap(requests); for (std::vector<ChannelIDService::Request*>::iterator i = requests.begin(); i != requests.end(); i++) { - scoped_ptr<crypto::ECPrivateKey> key_copy; + std::unique_ptr<crypto::ECPrivateKey> key_copy; if (key) key_copy.reset(key->Copy()); (*i)->Post(error, std::move(key_copy)); @@ -240,7 +239,7 @@ ChannelIDService* service, base::TimeTicks request_start, const CompletionCallback& callback, - scoped_ptr<crypto::ECPrivateKey>* key, + std::unique_ptr<crypto::ECPrivateKey>* key, ChannelIDServiceJob* job) { DCHECK(service_ == NULL); service_ = service; @@ -250,8 +249,9 @@ job_ = job; } -void ChannelIDService::Request::Post(int error, - scoped_ptr<crypto::ECPrivateKey> key) { +void ChannelIDService::Request::Post( + int error, + std::unique_ptr<crypto::ECPrivateKey> key) { switch (error) { case OK: { base::TimeDelta request_time = base::TimeTicks::Now() - request_start_; @@ -314,7 +314,7 @@ int ChannelIDService::GetOrCreateChannelID( const std::string& host, - scoped_ptr<crypto::ECPrivateKey>* key, + std::unique_ptr<crypto::ECPrivateKey>* key, const CompletionCallback& callback, Request* out_req) { DVLOG(1) << __FUNCTION__ << " " << host; @@ -369,7 +369,7 @@ } int ChannelIDService::GetChannelID(const std::string& host, - scoped_ptr<crypto::ECPrivateKey>* key, + std::unique_ptr<crypto::ECPrivateKey>* key, const CompletionCallback& callback, Request* out_req) { DVLOG(1) << __FUNCTION__ << " " << host; @@ -403,7 +403,7 @@ void ChannelIDService::GotChannelID(int err, const std::string& server_identifier, - scoped_ptr<crypto::ECPrivateKey> key) { + std::unique_ptr<crypto::ECPrivateKey> key) { DCHECK(CalledOnValidThread()); std::map<std::string, ChannelIDServiceJob*>::iterator j; @@ -448,10 +448,10 @@ void ChannelIDService::GeneratedChannelID( const std::string& server_identifier, int error, - scoped_ptr<ChannelIDStore::ChannelID> channel_id) { + std::unique_ptr<ChannelIDStore::ChannelID> channel_id) { DCHECK(CalledOnValidThread()); - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; if (error == OK) { key.reset(channel_id->key()->Copy()); channel_id_store_->SetChannelID(std::move(channel_id)); @@ -461,7 +461,7 @@ void ChannelIDService::HandleResult(int error, const std::string& server_identifier, - scoped_ptr<crypto::ECPrivateKey> key) { + std::unique_ptr<crypto::ECPrivateKey> key) { DCHECK(CalledOnValidThread()); std::map<std::string, ChannelIDServiceJob*>::iterator j; @@ -480,7 +480,7 @@ bool ChannelIDService::JoinToInFlightRequest( const base::TimeTicks& request_start, const std::string& domain, - scoped_ptr<crypto::ECPrivateKey>* key, + std::unique_ptr<crypto::ECPrivateKey>* key, bool create_if_missing, const CompletionCallback& callback, Request* out_req) { @@ -501,12 +501,13 @@ return false; } -int ChannelIDService::LookupChannelID(const base::TimeTicks& request_start, - const std::string& domain, - scoped_ptr<crypto::ECPrivateKey>* key, - bool create_if_missing, - const CompletionCallback& callback, - Request* out_req) { +int ChannelIDService::LookupChannelID( + const base::TimeTicks& request_start, + const std::string& domain, + std::unique_ptr<crypto::ECPrivateKey>* key, + bool create_if_missing, + const CompletionCallback& callback, + Request* out_req) { // Check if a channel ID key already exists for this domain. int err = channel_id_store_->GetChannelID( domain, key, base::Bind(&ChannelIDService::GotChannelID,
diff --git a/net/ssl/channel_id_service.h b/net/ssl/channel_id_service.h index ef57797..767973c 100644 --- a/net/ssl/channel_id_service.h +++ b/net/ssl/channel_id_service.h
@@ -8,11 +8,11 @@ #include <stdint.h> #include <map> +#include <memory> #include <string> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/threading/non_thread_safe.h" #include "base/time/time.h" @@ -58,15 +58,15 @@ void RequestStarted(ChannelIDService* service, base::TimeTicks request_start, const CompletionCallback& callback, - scoped_ptr<crypto::ECPrivateKey>* key, + std::unique_ptr<crypto::ECPrivateKey>* key, ChannelIDServiceJob* job); - void Post(int error, scoped_ptr<crypto::ECPrivateKey> key); + void Post(int error, std::unique_ptr<crypto::ECPrivateKey> key); ChannelIDService* service_; base::TimeTicks request_start_; CompletionCallback callback_; - scoped_ptr<crypto::ECPrivateKey>* key_; + std::unique_ptr<crypto::ECPrivateKey>* key_; ChannelIDServiceJob* job_; }; @@ -102,7 +102,7 @@ // // |*out_req| will be initialized with a handle to the async request. int GetOrCreateChannelID(const std::string& host, - scoped_ptr<crypto::ECPrivateKey>* key, + std::unique_ptr<crypto::ECPrivateKey>* key, const CompletionCallback& callback, Request* out_req); @@ -122,7 +122,7 @@ // // |*out_req| will be initialized with a handle to the async request. int GetChannelID(const std::string& host, - scoped_ptr<crypto::ECPrivateKey>* key, + std::unique_ptr<crypto::ECPrivateKey>* key, const CompletionCallback& callback, Request* out_req); @@ -143,21 +143,21 @@ private: void GotChannelID(int err, const std::string& server_identifier, - scoped_ptr<crypto::ECPrivateKey> key); + std::unique_ptr<crypto::ECPrivateKey> key); void GeneratedChannelID( const std::string& server_identifier, int error, - scoped_ptr<ChannelIDStore::ChannelID> channel_id); + std::unique_ptr<ChannelIDStore::ChannelID> channel_id); void HandleResult(int error, const std::string& server_identifier, - scoped_ptr<crypto::ECPrivateKey> key); + std::unique_ptr<crypto::ECPrivateKey> key); // Searches for an in-flight request for the same domain. If found, // attaches to the request and returns true. Returns false if no in-flight // request is found. bool JoinToInFlightRequest(const base::TimeTicks& request_start, const std::string& domain, - scoped_ptr<crypto::ECPrivateKey>* key, + std::unique_ptr<crypto::ECPrivateKey>* key, bool create_if_missing, const CompletionCallback& callback, Request* out_req); @@ -168,12 +168,12 @@ // failure (including failure to find a channel ID of |domain|). int LookupChannelID(const base::TimeTicks& request_start, const std::string& domain, - scoped_ptr<crypto::ECPrivateKey>* key, + std::unique_ptr<crypto::ECPrivateKey>* key, bool create_if_missing, const CompletionCallback& callback, Request* out_req); - scoped_ptr<ChannelIDStore> channel_id_store_; + std::unique_ptr<ChannelIDStore> channel_id_store_; scoped_refptr<base::TaskRunner> task_runner_; const int id_;
diff --git a/net/ssl/channel_id_service_unittest.cc b/net/ssl/channel_id_service_unittest.cc index 1e98b61..578ce56 100644 --- a/net/ssl/channel_id_service_unittest.cc +++ b/net/ssl/channel_id_service_unittest.cc
@@ -4,13 +4,14 @@ #include "net/ssl/channel_id_service.h" +#include <memory> #include <string> #include <vector> #include "base/bind.h" #include "base/location.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" @@ -62,10 +63,10 @@ : DefaultChannelIDStore(NULL), channel_id_count_(0) {} int GetChannelID(const std::string& server_identifier, - scoped_ptr<crypto::ECPrivateKey>* key_result, + std::unique_ptr<crypto::ECPrivateKey>* key_result, const GetChannelIDCallback& callback) override; - void SetChannelID(scoped_ptr<ChannelID> channel_id) override { + void SetChannelID(std::unique_ptr<ChannelID> channel_id) override { channel_id_count_ = 1; } @@ -81,7 +82,7 @@ int MockChannelIDStoreWithAsyncGet::GetChannelID( const std::string& server_identifier, - scoped_ptr<crypto::ECPrivateKey>* key_result, + std::unique_ptr<crypto::ECPrivateKey>* key_result, const GetChannelIDCallback& callback) { server_identifier_ = server_identifier; callback_ = callback; @@ -101,7 +102,7 @@ base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback_, err, server_identifier_, - base::Passed(make_scoped_ptr(key ? key->Copy() : nullptr)))); + base::Passed(base::WrapUnique(key ? key->Copy() : nullptr)))); } class ChannelIDServiceTest : public testing::Test { @@ -111,7 +112,7 @@ base::ThreadTaskRunnerHandle::Get())) {} protected: - scoped_ptr<ChannelIDService> service_; + std::unique_ptr<ChannelIDService> service_; }; TEST_F(ChannelIDServiceTest, GetDomainForHost) { @@ -141,7 +142,7 @@ ChannelIDService::Request request; // Synchronous completion, because the store is initialized. - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; EXPECT_EQ(0, service_->channel_id_count()); error = service_->GetChannelID(host, &key, callback.callback(), &request); EXPECT_EQ(ERR_FILE_NOT_FOUND, error); @@ -158,7 +159,7 @@ ChannelIDService::Request request; // Asynchronous completion. - scoped_ptr<crypto::ECPrivateKey> key1; + std::unique_ptr<crypto::ECPrivateKey> key1; EXPECT_EQ(0, service_->channel_id_count()); error = service_->GetOrCreateChannelID(host, &key1, callback.callback(), &request); @@ -171,7 +172,7 @@ EXPECT_FALSE(request.is_active()); // Synchronous completion. - scoped_ptr<crypto::ECPrivateKey> key2; + std::unique_ptr<crypto::ECPrivateKey> key2; error = service_->GetOrCreateChannelID(host, &key2, callback.callback(), &request); EXPECT_FALSE(request.is_active()); @@ -180,7 +181,7 @@ EXPECT_TRUE(KeysEqual(key1.get(), key2.get())); // Synchronous get. - scoped_ptr<crypto::ECPrivateKey> key3; + std::unique_ptr<crypto::ECPrivateKey> key3; error = service_->GetChannelID(host, &key3, callback.callback(), &request); EXPECT_FALSE(request.is_active()); EXPECT_EQ(OK, error); @@ -198,7 +199,7 @@ ChannelIDService::Request request; std::string host1("encrypted.google.com"); - scoped_ptr<crypto::ECPrivateKey> key1; + std::unique_ptr<crypto::ECPrivateKey> key1; EXPECT_EQ(0, service_->channel_id_count()); error = service_->GetOrCreateChannelID(host1, &key1, callback.callback(), &request); @@ -209,7 +210,7 @@ EXPECT_EQ(1, service_->channel_id_count()); std::string host2("www.verisign.com"); - scoped_ptr<crypto::ECPrivateKey> key2; + std::unique_ptr<crypto::ECPrivateKey> key2; error = service_->GetOrCreateChannelID(host2, &key2, callback.callback(), &request); EXPECT_EQ(ERR_IO_PENDING, error); @@ -219,7 +220,7 @@ EXPECT_EQ(2, service_->channel_id_count()); std::string host3("www.twitter.com"); - scoped_ptr<crypto::ECPrivateKey> key3; + std::unique_ptr<crypto::ECPrivateKey> key3; error = service_->GetOrCreateChannelID(host3, &key3, callback.callback(), &request); EXPECT_EQ(ERR_IO_PENDING, error); @@ -238,11 +239,11 @@ std::string host("encrypted.google.com"); int error; - scoped_ptr<crypto::ECPrivateKey> key1; + std::unique_ptr<crypto::ECPrivateKey> key1; TestCompletionCallback callback1; ChannelIDService::Request request1; - scoped_ptr<crypto::ECPrivateKey> key2; + std::unique_ptr<crypto::ECPrivateKey> key2; TestCompletionCallback callback2; ChannelIDService::Request request2; @@ -272,11 +273,11 @@ std::string host("encrypted.google.com"); int error; - scoped_ptr<crypto::ECPrivateKey> key1; + std::unique_ptr<crypto::ECPrivateKey> key1; TestCompletionCallback callback1; ChannelIDService::Request request1; - scoped_ptr<crypto::ECPrivateKey> key2; + std::unique_ptr<crypto::ECPrivateKey> key2; TestCompletionCallback callback2; ChannelIDService::Request request2; @@ -304,7 +305,7 @@ // Tests that the callback of a canceled request is never made. TEST_F(ChannelIDServiceTest, CancelRequest) { std::string host("encrypted.google.com"); - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; int error; ChannelIDService::Request request; @@ -327,9 +328,9 @@ // Tests that destructing the Request cancels the request. TEST_F(ChannelIDServiceTest, CancelRequestByHandleDestruction) { std::string host("encrypted.google.com"); - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; int error; - scoped_ptr<ChannelIDService::Request> request( + std::unique_ptr<ChannelIDService::Request> request( new ChannelIDService::Request()); error = service_->GetOrCreateChannelID(host, &key, base::Bind(&FailTest), @@ -351,7 +352,7 @@ TEST_F(ChannelIDServiceTest, DestructionWithPendingRequest) { std::string host("encrypted.google.com"); - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; int error; ChannelIDService::Request request; @@ -382,7 +383,7 @@ // Make a request that will force synchronous completion. std::string host("encrypted.google.com"); - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; int error; ChannelIDService::Request request; @@ -398,17 +399,17 @@ int error; std::string host1("encrypted.google.com"); - scoped_ptr<crypto::ECPrivateKey> key1; + std::unique_ptr<crypto::ECPrivateKey> key1; TestCompletionCallback callback1; ChannelIDService::Request request1; std::string host2("foo.com"); - scoped_ptr<crypto::ECPrivateKey> key2; + std::unique_ptr<crypto::ECPrivateKey> key2; TestCompletionCallback callback2; ChannelIDService::Request request2; std::string host3("bar.com"); - scoped_ptr<crypto::ECPrivateKey> key3; + std::unique_ptr<crypto::ECPrivateKey> key3; TestCompletionCallback callback3; ChannelIDService::Request request3; @@ -449,7 +450,7 @@ TEST_F(ChannelIDServiceTest, AsyncStoreGetOrCreateNoChannelIDsInStore) { MockChannelIDStoreWithAsyncGet* mock_store = new MockChannelIDStoreWithAsyncGet(); - service_ = scoped_ptr<ChannelIDService>( + service_ = std::unique_ptr<ChannelIDService>( new ChannelIDService(mock_store, base::ThreadTaskRunnerHandle::Get())); std::string host("encrypted.google.com"); @@ -459,7 +460,7 @@ ChannelIDService::Request request; // Asynchronous completion with no certs in the store. - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; EXPECT_EQ(0, service_->channel_id_count()); error = service_->GetOrCreateChannelID(host, &key, callback.callback(), &request); @@ -478,7 +479,7 @@ TEST_F(ChannelIDServiceTest, AsyncStoreGetNoChannelIDsInStore) { MockChannelIDStoreWithAsyncGet* mock_store = new MockChannelIDStoreWithAsyncGet(); - service_ = scoped_ptr<ChannelIDService>( + service_ = std::unique_ptr<ChannelIDService>( new ChannelIDService(mock_store, base::ThreadTaskRunnerHandle::Get())); std::string host("encrypted.google.com"); @@ -488,7 +489,7 @@ ChannelIDService::Request request; // Asynchronous completion with no certs in the store. - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; EXPECT_EQ(0, service_->channel_id_count()); error = service_->GetChannelID(host, &key, callback.callback(), &request); EXPECT_EQ(ERR_IO_PENDING, error); @@ -507,7 +508,7 @@ TEST_F(ChannelIDServiceTest, AsyncStoreGetOrCreateOneCertInStore) { MockChannelIDStoreWithAsyncGet* mock_store = new MockChannelIDStoreWithAsyncGet(); - service_ = scoped_ptr<ChannelIDService>( + service_ = std::unique_ptr<ChannelIDService>( new ChannelIDService(mock_store, base::ThreadTaskRunnerHandle::Get())); std::string host("encrypted.google.com"); @@ -517,14 +518,15 @@ ChannelIDService::Request request; // Asynchronous completion with a cert in the store. - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; EXPECT_EQ(0, service_->channel_id_count()); error = service_->GetOrCreateChannelID(host, &key, callback.callback(), &request); EXPECT_EQ(ERR_IO_PENDING, error); EXPECT_TRUE(request.is_active()); - scoped_ptr<crypto::ECPrivateKey> expected_key(crypto::ECPrivateKey::Create()); + std::unique_ptr<crypto::ECPrivateKey> expected_key( + crypto::ECPrivateKey::Create()); mock_store->CallGetChannelIDCallbackWithResult(OK, expected_key.get()); error = callback.WaitForResult(); @@ -543,7 +545,7 @@ TEST_F(ChannelIDServiceTest, AsyncStoreGetOneCertInStore) { MockChannelIDStoreWithAsyncGet* mock_store = new MockChannelIDStoreWithAsyncGet(); - service_ = scoped_ptr<ChannelIDService>( + service_ = std::unique_ptr<ChannelIDService>( new ChannelIDService(mock_store, base::ThreadTaskRunnerHandle::Get())); std::string host("encrypted.google.com"); @@ -553,14 +555,15 @@ ChannelIDService::Request request; // Asynchronous completion with a cert in the store. - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; std::string private_key, spki; EXPECT_EQ(0, service_->channel_id_count()); error = service_->GetChannelID(host, &key, callback.callback(), &request); EXPECT_EQ(ERR_IO_PENDING, error); EXPECT_TRUE(request.is_active()); - scoped_ptr<crypto::ECPrivateKey> expected_key(crypto::ECPrivateKey::Create()); + std::unique_ptr<crypto::ECPrivateKey> expected_key( + crypto::ECPrivateKey::Create()); mock_store->CallGetChannelIDCallbackWithResult(OK, expected_key.get()); error = callback.WaitForResult(); @@ -578,7 +581,7 @@ TEST_F(ChannelIDServiceTest, AsyncStoreGetThenCreateNoCertsInStore) { MockChannelIDStoreWithAsyncGet* mock_store = new MockChannelIDStoreWithAsyncGet(); - service_ = scoped_ptr<ChannelIDService>( + service_ = std::unique_ptr<ChannelIDService>( new ChannelIDService(mock_store, base::ThreadTaskRunnerHandle::Get())); std::string host("encrypted.google.com"); @@ -588,7 +591,7 @@ // Asynchronous get with no certs in the store. TestCompletionCallback callback1; ChannelIDService::Request request1; - scoped_ptr<crypto::ECPrivateKey> key1; + std::unique_ptr<crypto::ECPrivateKey> key1; EXPECT_EQ(0, service_->channel_id_count()); error = service_->GetChannelID(host, &key1, callback1.callback(), &request1); EXPECT_EQ(ERR_IO_PENDING, error); @@ -597,7 +600,7 @@ // Asynchronous get/create with no certs in the store. TestCompletionCallback callback2; ChannelIDService::Request request2; - scoped_ptr<crypto::ECPrivateKey> key2; + std::unique_ptr<crypto::ECPrivateKey> key2; EXPECT_EQ(0, service_->channel_id_count()); error = service_->GetOrCreateChannelID(host, &key2, callback2.callback(), &request2);
diff --git a/net/ssl/channel_id_store.cc b/net/ssl/channel_id_store.cc index 1345da1..1d0078b 100644 --- a/net/ssl/channel_id_store.cc +++ b/net/ssl/channel_id_store.cc
@@ -15,7 +15,7 @@ ChannelIDStore::ChannelID::ChannelID(const std::string& server_identifier, base::Time creation_time, - scoped_ptr<crypto::ECPrivateKey> key) + std::unique_ptr<crypto::ECPrivateKey> key) : server_identifier_(server_identifier), creation_time_(creation_time), key_(std::move(key)) {} @@ -42,7 +42,7 @@ void ChannelIDStore::InitializeFrom(const ChannelIDList& list) { for (ChannelIDList::const_iterator i = list.begin(); i != list.end(); ++i) { - SetChannelID(scoped_ptr<ChannelID>(new ChannelID(*i))); + SetChannelID(std::unique_ptr<ChannelID>(new ChannelID(*i))); } }
diff --git a/net/ssl/channel_id_store.h b/net/ssl/channel_id_store.h index 3eb9d67..21c513a 100644 --- a/net/ssl/channel_id_store.h +++ b/net/ssl/channel_id_store.h
@@ -6,10 +6,10 @@ #define NET_SSL_CHANNEL_ID_STORE_H_ #include <list> +#include <memory> #include <string> #include "base/callback.h" -#include "base/memory/scoped_ptr.h" #include "base/threading/non_thread_safe.h" #include "base/time/time.h" #include "crypto/ec_private_key.h" @@ -32,7 +32,7 @@ ChannelID(); ChannelID(const std::string& server_identifier, base::Time creation_time, - scoped_ptr<crypto::ECPrivateKey> key); + std::unique_ptr<crypto::ECPrivateKey> key); ChannelID(const ChannelID& other); ChannelID& operator=(const ChannelID& other); ~ChannelID(); @@ -49,13 +49,13 @@ private: std::string server_identifier_; base::Time creation_time_; - scoped_ptr<crypto::ECPrivateKey> key_; + std::unique_ptr<crypto::ECPrivateKey> key_; }; typedef std::list<ChannelID> ChannelIDList; typedef base::Callback< - void(int, const std::string&, scoped_ptr<crypto::ECPrivateKey>)> + void(int, const std::string&, std::unique_ptr<crypto::ECPrivateKey>)> GetChannelIDCallback; typedef base::Callback<void(const ChannelIDList&)> GetChannelIDListCallback; @@ -68,11 +68,11 @@ // return ERR_IO_PENDING and the callback will be called with the result // asynchronously. virtual int GetChannelID(const std::string& server_identifier, - scoped_ptr<crypto::ECPrivateKey>* key_result, + std::unique_ptr<crypto::ECPrivateKey>* key_result, const GetChannelIDCallback& callback) = 0; // Adds the keypair for a hostname to the store. - virtual void SetChannelID(scoped_ptr<ChannelID> channel_id) = 0; + virtual void SetChannelID(std::unique_ptr<ChannelID> channel_id) = 0; // Removes a keypair from the store. virtual void DeleteChannelID(
diff --git a/net/ssl/client_cert_store_nss.cc b/net/ssl/client_cert_store_nss.cc index 073745ef..e46458ad 100644 --- a/net/ssl/client_cert_store_nss.cc +++ b/net/ssl/client_cert_store_nss.cc
@@ -8,13 +8,13 @@ #include <ssl.h> #include <algorithm> +#include <memory> #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/location.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string_piece.h" #include "base/threading/worker_pool.h" #include "crypto/nss_crypto_module_delegate.h" @@ -32,7 +32,8 @@ void ClientCertStoreNSS::GetClientCerts(const SSLCertRequestInfo& request, CertificateList* selected_certs, const base::Closure& callback) { - scoped_ptr<crypto::CryptoModuleBlockingPasswordDelegate> password_delegate; + std::unique_ptr<crypto::CryptoModuleBlockingPasswordDelegate> + password_delegate; if (!password_delegate_factory_.is_null()) { password_delegate.reset( password_delegate_factory_.Run(request.host_and_port)); @@ -114,7 +115,8 @@ } void ClientCertStoreNSS::GetAndFilterCertsOnWorkerThread( - scoped_ptr<crypto::CryptoModuleBlockingPasswordDelegate> password_delegate, + std::unique_ptr<crypto::CryptoModuleBlockingPasswordDelegate> + password_delegate, const SSLCertRequestInfo* request, CertificateList* selected_certs) { CertificateList platform_certs; @@ -124,7 +126,8 @@ // static void ClientCertStoreNSS::GetPlatformCertsOnWorkerThread( - scoped_ptr<crypto::CryptoModuleBlockingPasswordDelegate> password_delegate, + std::unique_ptr<crypto::CryptoModuleBlockingPasswordDelegate> + password_delegate, net::CertificateList* certs) { CERTCertList* found_certs = CERT_FindUserCertsByUsage(CERT_GetDefaultCertDB(), certUsageSSLClient,
diff --git a/net/ssl/client_cert_store_nss.h b/net/ssl/client_cert_store_nss.h index 5583661a..60f6e214 100644 --- a/net/ssl/client_cert_store_nss.h +++ b/net/ssl/client_cert_store_nss.h
@@ -5,9 +5,10 @@ #ifndef NET_SSL_CLIENT_CERT_STORE_NSS_H_ #define NET_SSL_CLIENT_CERT_STORE_NSS_H_ +#include <memory> + #include "base/callback.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/base/net_export.h" #include "net/ssl/client_cert_store.h" @@ -48,13 +49,13 @@ // |certs|. |password_delegate| is used to unlock slots if required. // Must be called from a worker thread. static void GetPlatformCertsOnWorkerThread( - scoped_ptr<crypto::CryptoModuleBlockingPasswordDelegate> + std::unique_ptr<crypto::CryptoModuleBlockingPasswordDelegate> password_delegate, net::CertificateList* certs); private: void GetAndFilterCertsOnWorkerThread( - scoped_ptr<crypto::CryptoModuleBlockingPasswordDelegate> + std::unique_ptr<crypto::CryptoModuleBlockingPasswordDelegate> password_delegate, const SSLCertRequestInfo* request, CertificateList* selected_certs);
diff --git a/net/ssl/client_cert_store_unittest-inl.h b/net/ssl/client_cert_store_unittest-inl.h index 8a8f98b..9f1f9329 100644 --- a/net/ssl/client_cert_store_unittest-inl.h +++ b/net/ssl/client_cert_store_unittest-inl.h
@@ -5,12 +5,12 @@ #ifndef NET_SSL_CLIENT_CERT_STORE_UNITTEST_INL_H_ #define NET_SSL_CLIENT_CERT_STORE_UNITTEST_INL_H_ +#include <memory> #include <string> #include <vector> #include "base/files/file_path.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "net/base/test_data_directory.h" #include "net/ssl/ssl_cert_request_info.h" #include "net/test/cert_test_util.h"
diff --git a/net/ssl/client_key_store.h b/net/ssl/client_key_store.h index bab45f3..b9f182b3 100644 --- a/net/ssl/client_key_store.h +++ b/net/ssl/client_key_store.h
@@ -5,12 +5,12 @@ #ifndef NET_SSL_CLIENT_KEY_STORE_H_ #define NET_SSL_CLIENT_KEY_STORE_H_ +#include <memory> #include <vector> #include "base/callback.h" #include "base/lazy_instance.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/synchronization/lock.h" #include "net/base/net_export.h"
diff --git a/net/ssl/default_channel_id_store.cc b/net/ssl/default_channel_id_store.cc index 184fccd..8287077 100644 --- a/net/ssl/default_channel_id_store.cc +++ b/net/ssl/default_channel_id_store.cc
@@ -64,7 +64,7 @@ void DefaultChannelIDStore::GetChannelIDTask::Run( DefaultChannelIDStore* store) { - scoped_ptr<crypto::ECPrivateKey> key_result; + std::unique_ptr<crypto::ECPrivateKey> key_result; int err = store->GetChannelID(server_identifier_, &key_result, GetChannelIDCallback()); DCHECK(err != ERR_IO_PENDING); @@ -78,16 +78,16 @@ class DefaultChannelIDStore::SetChannelIDTask : public DefaultChannelIDStore::Task { public: - SetChannelIDTask(scoped_ptr<ChannelID> channel_id); + SetChannelIDTask(std::unique_ptr<ChannelID> channel_id); ~SetChannelIDTask() override; void Run(DefaultChannelIDStore* store) override; private: - scoped_ptr<ChannelID> channel_id_; + std::unique_ptr<ChannelID> channel_id_; }; DefaultChannelIDStore::SetChannelIDTask::SetChannelIDTask( - scoped_ptr<ChannelID> channel_id) + std::unique_ptr<ChannelID> channel_id) : channel_id_(std::move(channel_id)) {} DefaultChannelIDStore::SetChannelIDTask::~SetChannelIDTask() { @@ -213,13 +213,13 @@ int DefaultChannelIDStore::GetChannelID( const std::string& server_identifier, - scoped_ptr<crypto::ECPrivateKey>* key_result, + std::unique_ptr<crypto::ECPrivateKey>* key_result, const GetChannelIDCallback& callback) { DCHECK(CalledOnValidThread()); InitIfNecessary(); if (!loaded_) { - EnqueueTask(scoped_ptr<Task>( + EnqueueTask(std::unique_ptr<Task>( new GetChannelIDTask(server_identifier, callback))); return ERR_IO_PENDING; } @@ -235,15 +235,16 @@ return OK; } -void DefaultChannelIDStore::SetChannelID(scoped_ptr<ChannelID> channel_id) { +void DefaultChannelIDStore::SetChannelID( + std::unique_ptr<ChannelID> channel_id) { auto task = new SetChannelIDTask(std::move(channel_id)); - RunOrEnqueueTask(scoped_ptr<Task>(task)); + RunOrEnqueueTask(std::unique_ptr<Task>(task)); } void DefaultChannelIDStore::DeleteChannelID( const std::string& server_identifier, const base::Closure& callback) { - RunOrEnqueueTask(scoped_ptr<Task>( + RunOrEnqueueTask(std::unique_ptr<Task>( new DeleteChannelIDTask(server_identifier, callback))); } @@ -251,7 +252,7 @@ base::Time delete_begin, base::Time delete_end, const base::Closure& callback) { - RunOrEnqueueTask(scoped_ptr<Task>( + RunOrEnqueueTask(std::unique_ptr<Task>( new DeleteAllCreatedBetweenTask(delete_begin, delete_end, callback))); } @@ -262,7 +263,7 @@ void DefaultChannelIDStore::GetAllChannelIDs( const GetChannelIDListCallback& callback) { - RunOrEnqueueTask(scoped_ptr<Task>(new GetAllChannelIDsTask(callback))); + RunOrEnqueueTask(std::unique_ptr<Task>(new GetAllChannelIDsTask(callback))); } int DefaultChannelIDStore::GetChannelIDCount() { @@ -303,9 +304,10 @@ } void DefaultChannelIDStore::OnLoaded( - scoped_ptr<std::vector<scoped_ptr<ChannelID>>> channel_ids) { + std::unique_ptr<std::vector<std::unique_ptr<ChannelID>>> channel_ids) { DCHECK(CalledOnValidThread()); - for (std::vector<scoped_ptr<ChannelID>>::iterator it = channel_ids->begin(); + for (std::vector<std::unique_ptr<ChannelID>>::iterator it = + channel_ids->begin(); it != channel_ids->end(); ++it) { DCHECK(channel_ids_.find((*it)->server_identifier()) == channel_ids_.end()); @@ -328,12 +330,13 @@ UMA_HISTOGRAM_COUNTS_100("DomainBoundCerts.TaskWaitCount", waiting_tasks_.size()); - for (scoped_ptr<Task>& i : waiting_tasks_) + for (std::unique_ptr<Task>& i : waiting_tasks_) i->Run(this); waiting_tasks_.clear(); } -void DefaultChannelIDStore::SyncSetChannelID(scoped_ptr<ChannelID> channel_id) { +void DefaultChannelIDStore::SyncSetChannelID( + std::unique_ptr<ChannelID> channel_id) { DCHECK(CalledOnValidThread()); DCHECK(loaded_); @@ -378,7 +381,7 @@ channel_id_list->push_back(*it->second); } -void DefaultChannelIDStore::EnqueueTask(scoped_ptr<Task> task) { +void DefaultChannelIDStore::EnqueueTask(std::unique_ptr<Task> task) { DCHECK(CalledOnValidThread()); DCHECK(!loaded_); if (waiting_tasks_.empty()) @@ -386,7 +389,7 @@ waiting_tasks_.push_back(std::move(task)); } -void DefaultChannelIDStore::RunOrEnqueueTask(scoped_ptr<Task> task) { +void DefaultChannelIDStore::RunOrEnqueueTask(std::unique_ptr<Task> task) { DCHECK(CalledOnValidThread()); InitIfNecessary(); @@ -415,7 +418,7 @@ } void DefaultChannelIDStore::InternalInsertChannelID( - scoped_ptr<ChannelID> channel_id) { + std::unique_ptr<ChannelID> channel_id) { DCHECK(CalledOnValidThread()); DCHECK(loaded_);
diff --git a/net/ssl/default_channel_id_store.h b/net/ssl/default_channel_id_store.h index fed0319..dc7e85f 100644 --- a/net/ssl/default_channel_id_store.h +++ b/net/ssl/default_channel_id_store.h
@@ -6,6 +6,7 @@ #define NET_SSL_DEFAULT_CHANNEL_ID_STORE_H_ #include <map> +#include <memory> #include <string> #include <vector> @@ -13,7 +14,6 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/memory/weak_ptr.h" #include "net/base/net_export.h" @@ -49,9 +49,9 @@ // ChannelIDStore implementation. int GetChannelID(const std::string& server_identifier, - scoped_ptr<crypto::ECPrivateKey>* key_result, + std::unique_ptr<crypto::ECPrivateKey>* key_result, const GetChannelIDCallback& callback) override; - void SetChannelID(scoped_ptr<ChannelID> channel_id) override; + void SetChannelID(std::unique_ptr<ChannelID> channel_id) override; void DeleteChannelID(const std::string& server_identifier, const base::Closure& callback) override; void DeleteAllCreatedBetween(base::Time delete_begin, @@ -95,21 +95,21 @@ void InitStore(); // Callback for backing store loading completion. - void OnLoaded(scoped_ptr<std::vector<scoped_ptr<ChannelID>>> certs); + void OnLoaded(std::unique_ptr<std::vector<std::unique_ptr<ChannelID>>> certs); // Syncronous methods which do the actual work. Can only be called after // initialization is complete. - void SyncSetChannelID(scoped_ptr<ChannelID> channel_id); + void SyncSetChannelID(std::unique_ptr<ChannelID> channel_id); void SyncDeleteChannelID(const std::string& server_identifier); void SyncDeleteAllCreatedBetween(base::Time delete_begin, base::Time delete_end); void SyncGetAllChannelIDs(ChannelIDList* channel_id_list); // Add |task| to |waiting_tasks_|. - void EnqueueTask(scoped_ptr<Task> task); + void EnqueueTask(std::unique_ptr<Task> task); // If already initialized, run |task| immediately. Otherwise add it to // |waiting_tasks_|. - void RunOrEnqueueTask(scoped_ptr<Task> task); + void RunOrEnqueueTask(std::unique_ptr<Task> task); // Deletes the channel id for the specified server, if such a channel id // exists, from the in-memory store. Deletes it from |store_| if |store_| @@ -118,7 +118,7 @@ // Adds the channel id to the in-memory store and adds it to |store_| if // |store_| is not NULL. - void InternalInsertChannelID(scoped_ptr<ChannelID> channel_id); + void InternalInsertChannelID(std::unique_ptr<ChannelID> channel_id); // Indicates whether the channel id store has been initialized. This happens // lazily in InitIfNecessary(). @@ -129,7 +129,7 @@ bool loaded_; // Tasks that are waiting to be run once we finish loading. - std::vector<scoped_ptr<Task>> waiting_tasks_; + std::vector<std::unique_ptr<Task>> waiting_tasks_; base::TimeTicks waiting_tasks_start_time_; scoped_refptr<PersistentStore> store_; @@ -147,7 +147,8 @@ class NET_EXPORT DefaultChannelIDStore::PersistentStore : public RefcountedPersistentStore { public: - typedef base::Callback<void(scoped_ptr<std::vector<scoped_ptr<ChannelID>>>)> + typedef base::Callback<void( + std::unique_ptr<std::vector<std::unique_ptr<ChannelID>>>)> LoadedCallback; // Initializes the store and retrieves the existing channel_ids. This will be
diff --git a/net/ssl/default_channel_id_store_unittest.cc b/net/ssl/default_channel_id_store_unittest.cc index 80f0657c..97f6add 100644 --- a/net/ssl/default_channel_id_store_unittest.cc +++ b/net/ssl/default_channel_id_store_unittest.cc
@@ -5,6 +5,7 @@ #include "net/ssl/default_channel_id_store.h" #include <map> +#include <memory> #include <string> #include <utility> #include <vector> @@ -13,7 +14,7 @@ #include "base/compiler_specific.h" #include "base/location.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/single_thread_task_runner.h" #include "base/thread_task_runner_handle.h" @@ -33,7 +34,7 @@ void GetChannelIDCallbackNotCalled( int err, const std::string& server_identifier, - scoped_ptr<crypto::ECPrivateKey> key_result) { + std::unique_ptr<crypto::ECPrivateKey> key_result) { ADD_FAILURE() << "Unexpected callback execution."; } @@ -43,7 +44,7 @@ void Callback(int err, const std::string& server_identifier, - scoped_ptr<crypto::ECPrivateKey> key_result) { + std::unique_ptr<crypto::ECPrivateKey> key_result) { err_ = err; server_identifier_ = server_identifier; key_ = std::move(key_result); @@ -52,7 +53,7 @@ int err_; std::string server_identifier_; - scoped_ptr<crypto::ECPrivateKey> key_; + std::unique_ptr<crypto::ECPrivateKey> key_; bool called_; }; @@ -88,14 +89,15 @@ MockPersistentStore::MockPersistentStore() {} void MockPersistentStore::Load(const LoadedCallback& loaded_callback) { - scoped_ptr<std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>>> + std::unique_ptr< + std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>>> channel_ids( - new std::vector<scoped_ptr<DefaultChannelIDStore::ChannelID>>()); + new std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>>()); ChannelIDMap::iterator it; for (it = channel_ids_.begin(); it != channel_ids_.end(); ++it) { channel_ids->push_back( - make_scoped_ptr(new DefaultChannelIDStore::ChannelID(it->second))); + base::WrapUnique(new DefaultChannelIDStore::ChannelID(it->second))); } base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -123,24 +125,24 @@ persistent_store->AddChannelID(DefaultChannelIDStore::ChannelID( "google.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create()))); + base::WrapUnique(crypto::ECPrivateKey::Create()))); persistent_store->AddChannelID(DefaultChannelIDStore::ChannelID( "verisign.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create()))); + base::WrapUnique(crypto::ECPrivateKey::Create()))); // Make sure channel_ids load properly. DefaultChannelIDStore store(persistent_store.get()); // Load has not occurred yet. EXPECT_EQ(0, store.GetChannelIDCount()); - store.SetChannelID(make_scoped_ptr(new ChannelIDStore::ChannelID( + store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( "verisign.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create())))); + base::WrapUnique(crypto::ECPrivateKey::Create())))); // Wait for load & queued set task. base::MessageLoop::current()->RunUntilIdle(); EXPECT_EQ(2, store.GetChannelIDCount()); - store.SetChannelID(make_scoped_ptr(new ChannelIDStore::ChannelID( + store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( "twitter.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create())))); + base::WrapUnique(crypto::ECPrivateKey::Create())))); // Set should be synchronous now that load is done. EXPECT_EQ(3, store.GetChannelIDCount()); } @@ -149,17 +151,18 @@ TEST(DefaultChannelIDStoreTest, TestSettingAndGetting) { // No persistent store, all calls will be synchronous. DefaultChannelIDStore store(NULL); - scoped_ptr<crypto::ECPrivateKey> expected_key(crypto::ECPrivateKey::Create()); + std::unique_ptr<crypto::ECPrivateKey> expected_key( + crypto::ECPrivateKey::Create()); - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; EXPECT_EQ(0, store.GetChannelIDCount()); EXPECT_EQ(ERR_FILE_NOT_FOUND, store.GetChannelID("verisign.com", &key, base::Bind(&GetChannelIDCallbackNotCalled))); EXPECT_FALSE(key); - store.SetChannelID(make_scoped_ptr(new ChannelIDStore::ChannelID( + store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( "verisign.com", base::Time::FromInternalValue(123), - make_scoped_ptr(expected_key->Copy())))); + base::WrapUnique(expected_key->Copy())))); EXPECT_EQ(OK, store.GetChannelID("verisign.com", &key, base::Bind(&GetChannelIDCallbackNotCalled))); EXPECT_TRUE(KeysEqual(expected_key.get(), key.get())); @@ -168,16 +171,17 @@ TEST(DefaultChannelIDStoreTest, TestDuplicateChannelIds) { scoped_refptr<MockPersistentStore> persistent_store(new MockPersistentStore); DefaultChannelIDStore store(persistent_store.get()); - scoped_ptr<crypto::ECPrivateKey> expected_key(crypto::ECPrivateKey::Create()); + std::unique_ptr<crypto::ECPrivateKey> expected_key( + crypto::ECPrivateKey::Create()); - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; EXPECT_EQ(0, store.GetChannelIDCount()); - store.SetChannelID(make_scoped_ptr(new ChannelIDStore::ChannelID( + store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( "verisign.com", base::Time::FromInternalValue(123), - make_scoped_ptr(crypto::ECPrivateKey::Create())))); - store.SetChannelID(make_scoped_ptr(new ChannelIDStore::ChannelID( + base::WrapUnique(crypto::ECPrivateKey::Create())))); + store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( "verisign.com", base::Time::FromInternalValue(456), - make_scoped_ptr(expected_key->Copy())))); + base::WrapUnique(expected_key->Copy())))); // Wait for load & queued set tasks. base::MessageLoop::current()->RunUntilIdle(); @@ -189,14 +193,15 @@ TEST(DefaultChannelIDStoreTest, TestAsyncGet) { scoped_refptr<MockPersistentStore> persistent_store(new MockPersistentStore); - scoped_ptr<crypto::ECPrivateKey> expected_key(crypto::ECPrivateKey::Create()); + std::unique_ptr<crypto::ECPrivateKey> expected_key( + crypto::ECPrivateKey::Create()); persistent_store->AddChannelID(ChannelIDStore::ChannelID( "verisign.com", base::Time::FromInternalValue(123), - make_scoped_ptr(expected_key->Copy()))); + base::WrapUnique(expected_key->Copy()))); DefaultChannelIDStore store(persistent_store.get()); AsyncGetChannelIDHelper helper; - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; EXPECT_EQ(0, store.GetChannelIDCount()); EXPECT_EQ(ERR_IO_PENDING, store.GetChannelID("verisign.com", &key, @@ -217,15 +222,15 @@ scoped_refptr<MockPersistentStore> persistent_store(new MockPersistentStore); DefaultChannelIDStore store(persistent_store.get()); - store.SetChannelID(make_scoped_ptr(new ChannelIDStore::ChannelID( + store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( "verisign.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create())))); - store.SetChannelID(make_scoped_ptr(new ChannelIDStore::ChannelID( + base::WrapUnique(crypto::ECPrivateKey::Create())))); + store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( "google.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create())))); - store.SetChannelID(make_scoped_ptr(new ChannelIDStore::ChannelID( + base::WrapUnique(crypto::ECPrivateKey::Create())))); + store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( "harvard.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create())))); + base::WrapUnique(crypto::ECPrivateKey::Create())))); // Wait for load & queued set tasks. base::MessageLoop::current()->RunUntilIdle(); @@ -240,10 +245,10 @@ scoped_refptr<MockPersistentStore> persistent_store(new MockPersistentStore); persistent_store->AddChannelID(ChannelIDStore::ChannelID( "verisign.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create()))); + base::WrapUnique(crypto::ECPrivateKey::Create()))); persistent_store->AddChannelID(ChannelIDStore::ChannelID( "google.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create()))); + base::WrapUnique(crypto::ECPrivateKey::Create()))); ChannelIDStore::ChannelIDList pre_channel_ids; ChannelIDStore::ChannelIDList post_channel_ids; @@ -266,17 +271,17 @@ scoped_refptr<MockPersistentStore> persistent_store(new MockPersistentStore); DefaultChannelIDStore store(persistent_store.get()); - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; EXPECT_EQ(0, store.GetChannelIDCount()); - store.SetChannelID(make_scoped_ptr(new ChannelIDStore::ChannelID( + store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( "verisign.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create())))); + base::WrapUnique(crypto::ECPrivateKey::Create())))); // Wait for load & queued set task. base::MessageLoop::current()->RunUntilIdle(); - store.SetChannelID(make_scoped_ptr(new ChannelIDStore::ChannelID( + store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( "google.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create())))); + base::WrapUnique(crypto::ECPrivateKey::Create())))); EXPECT_EQ(2, store.GetChannelIDCount()); int delete_finished = 0; @@ -301,13 +306,14 @@ TEST(DefaultChannelIDStoreTest, TestAsyncDelete) { scoped_refptr<MockPersistentStore> persistent_store(new MockPersistentStore); - scoped_ptr<crypto::ECPrivateKey> expected_key(crypto::ECPrivateKey::Create()); + std::unique_ptr<crypto::ECPrivateKey> expected_key( + crypto::ECPrivateKey::Create()); persistent_store->AddChannelID(ChannelIDStore::ChannelID( "a.com", base::Time::FromInternalValue(1), - make_scoped_ptr(crypto::ECPrivateKey::Create()))); + base::WrapUnique(crypto::ECPrivateKey::Create()))); persistent_store->AddChannelID( ChannelIDStore::ChannelID("b.com", base::Time::FromInternalValue(3), - make_scoped_ptr(expected_key->Copy()))); + base::WrapUnique(expected_key->Copy()))); DefaultChannelIDStore store(persistent_store.get()); int delete_finished = 0; store.DeleteChannelID("a.com", @@ -315,7 +321,7 @@ AsyncGetChannelIDHelper a_helper; AsyncGetChannelIDHelper b_helper; - scoped_ptr<crypto::ECPrivateKey> key; + std::unique_ptr<crypto::ECPrivateKey> key; EXPECT_EQ(0, store.GetChannelIDCount()); EXPECT_EQ(ERR_IO_PENDING, store.GetChannelID("a.com", &key, @@ -349,18 +355,18 @@ DefaultChannelIDStore store(persistent_store.get()); EXPECT_EQ(0, store.GetChannelIDCount()); - store.SetChannelID(make_scoped_ptr(new ChannelIDStore::ChannelID( + store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( "verisign.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create())))); - store.SetChannelID(make_scoped_ptr(new ChannelIDStore::ChannelID( + base::WrapUnique(crypto::ECPrivateKey::Create())))); + store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( "google.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create())))); - store.SetChannelID(make_scoped_ptr(new ChannelIDStore::ChannelID( + base::WrapUnique(crypto::ECPrivateKey::Create())))); + store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( "harvard.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create())))); - store.SetChannelID(make_scoped_ptr(new ChannelIDStore::ChannelID( + base::WrapUnique(crypto::ECPrivateKey::Create())))); + store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( "mit.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create())))); + base::WrapUnique(crypto::ECPrivateKey::Create())))); // Wait for load & queued set tasks. base::MessageLoop::current()->RunUntilIdle(); @@ -373,17 +379,19 @@ TEST(DefaultChannelIDStoreTest, TestInitializeFrom) { scoped_refptr<MockPersistentStore> persistent_store(new MockPersistentStore); DefaultChannelIDStore store(persistent_store.get()); - scoped_ptr<crypto::ECPrivateKey> preexisting_key( + std::unique_ptr<crypto::ECPrivateKey> preexisting_key( crypto::ECPrivateKey::Create()); - scoped_ptr<crypto::ECPrivateKey> both_key(crypto::ECPrivateKey::Create()); - scoped_ptr<crypto::ECPrivateKey> copied_key(crypto::ECPrivateKey::Create()); + std::unique_ptr<crypto::ECPrivateKey> both_key( + crypto::ECPrivateKey::Create()); + std::unique_ptr<crypto::ECPrivateKey> copied_key( + crypto::ECPrivateKey::Create()); - store.SetChannelID(make_scoped_ptr( - new ChannelIDStore::ChannelID("preexisting.com", base::Time(), - make_scoped_ptr(preexisting_key->Copy())))); - store.SetChannelID(make_scoped_ptr(new ChannelIDStore::ChannelID( + store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( + "preexisting.com", base::Time(), + base::WrapUnique(preexisting_key->Copy())))); + store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( "both.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create())))); + base::WrapUnique(crypto::ECPrivateKey::Create())))); // Wait for load & queued set tasks. base::MessageLoop::current()->RunUntilIdle(); EXPECT_EQ(2, store.GetChannelIDCount()); @@ -392,9 +400,9 @@ source_channel_ids.push_back(ChannelIDStore::ChannelID( "both.com", base::Time(), // Key differs from above to test that existing entries are overwritten. - make_scoped_ptr(both_key->Copy()))); + base::WrapUnique(both_key->Copy()))); source_channel_ids.push_back(ChannelIDStore::ChannelID( - "copied.com", base::Time(), make_scoped_ptr(copied_key->Copy()))); + "copied.com", base::Time(), base::WrapUnique(copied_key->Copy()))); store.InitializeFrom(source_channel_ids); EXPECT_EQ(3, store.GetChannelIDCount()); @@ -417,26 +425,28 @@ TEST(DefaultChannelIDStoreTest, TestAsyncInitializeFrom) { scoped_refptr<MockPersistentStore> persistent_store(new MockPersistentStore); - scoped_ptr<crypto::ECPrivateKey> preexisting_key( + std::unique_ptr<crypto::ECPrivateKey> preexisting_key( crypto::ECPrivateKey::Create()); - scoped_ptr<crypto::ECPrivateKey> both_key(crypto::ECPrivateKey::Create()); - scoped_ptr<crypto::ECPrivateKey> copied_key(crypto::ECPrivateKey::Create()); + std::unique_ptr<crypto::ECPrivateKey> both_key( + crypto::ECPrivateKey::Create()); + std::unique_ptr<crypto::ECPrivateKey> copied_key( + crypto::ECPrivateKey::Create()); persistent_store->AddChannelID( ChannelIDStore::ChannelID("preexisting.com", base::Time(), - make_scoped_ptr(preexisting_key->Copy()))); + base::WrapUnique(preexisting_key->Copy()))); persistent_store->AddChannelID(ChannelIDStore::ChannelID( "both.com", base::Time(), - make_scoped_ptr(crypto::ECPrivateKey::Create()))); + base::WrapUnique(crypto::ECPrivateKey::Create()))); DefaultChannelIDStore store(persistent_store.get()); ChannelIDStore::ChannelIDList source_channel_ids; source_channel_ids.push_back(ChannelIDStore::ChannelID( "both.com", base::Time(), // Key differs from above to test that existing entries are overwritten. - make_scoped_ptr(both_key->Copy()))); + base::WrapUnique(both_key->Copy()))); source_channel_ids.push_back(ChannelIDStore::ChannelID( - "copied.com", base::Time(), make_scoped_ptr(copied_key->Copy()))); + "copied.com", base::Time(), base::WrapUnique(copied_key->Copy()))); store.InitializeFrom(source_channel_ids); EXPECT_EQ(0, store.GetChannelIDCount()); // Wait for load & queued tasks.
diff --git a/net/ssl/openssl_client_key_store.cc b/net/ssl/openssl_client_key_store.cc index de1199f1..9b1b876 100644 --- a/net/ssl/openssl_client_key_store.cc +++ b/net/ssl/openssl_client_key_store.cc
@@ -6,9 +6,10 @@ #include <openssl/evp.h> #include <openssl/x509.h> -#include <algorithm> -#include "base/memory/scoped_ptr.h" +#include <algorithm> +#include <memory> + #include "base/memory/singleton.h" #include "net/cert/x509_certificate.h"
diff --git a/net/ssl/openssl_client_key_store.h b/net/ssl/openssl_client_key_store.h index 269565bf..63559ded 100644 --- a/net/ssl/openssl_client_key_store.h +++ b/net/ssl/openssl_client_key_store.h
@@ -7,10 +7,10 @@ #include <openssl/evp.h> +#include <memory> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "crypto/openssl_util.h" #include "crypto/scoped_openssl_types.h"
diff --git a/net/ssl/openssl_ssl_util.cc b/net/ssl/openssl_ssl_util.cc index ae3834a..af7082d 100644 --- a/net/ssl/openssl_ssl_util.cc +++ b/net/ssl/openssl_ssl_util.cc
@@ -117,12 +117,12 @@ } } -scoped_ptr<base::Value> NetLogOpenSSLErrorCallback( +std::unique_ptr<base::Value> NetLogOpenSSLErrorCallback( int net_error, int ssl_error, const OpenSSLErrorInfo& error_info, NetLogCaptureMode /* capture_mode */) { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetInteger("net_error", net_error); dict->SetInteger("ssl_error", ssl_error); if (error_info.error_code != 0) {
diff --git a/net/ssl/ssl_client_session_cache_openssl.cc b/net/ssl/ssl_client_session_cache_openssl.cc index a413eeeaf..d481269 100644 --- a/net/ssl/ssl_client_session_cache_openssl.cc +++ b/net/ssl/ssl_client_session_cache_openssl.cc
@@ -52,7 +52,7 @@ base::AutoLock lock(lock_); // Make a new entry. - scoped_ptr<CacheEntry> entry(new CacheEntry); + std::unique_ptr<CacheEntry> entry(new CacheEntry); entry->session.reset(SSL_SESSION_up_ref(session)); entry->creation_time = clock_->Now(); @@ -67,7 +67,7 @@ } void SSLClientSessionCacheOpenSSL::SetClockForTesting( - scoped_ptr<base::Clock> clock) { + std::unique_ptr<base::Clock> clock) { clock_ = std::move(clock); }
diff --git a/net/ssl/ssl_client_session_cache_openssl.h b/net/ssl/ssl_client_session_cache_openssl.h index a432b595..a289e43 100644 --- a/net/ssl/ssl_client_session_cache_openssl.h +++ b/net/ssl/ssl_client_session_cache_openssl.h
@@ -8,11 +8,11 @@ #include <openssl/ssl.h> #include <stddef.h> +#include <memory> #include <string> #include "base/containers/mru_cache.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/synchronization/lock.h" #include "base/threading/thread_checker.h" #include "base/time/time.h" @@ -53,7 +53,7 @@ // Removes all entries from the cache. void Flush(); - void SetClockForTesting(scoped_ptr<base::Clock> clock); + void SetClockForTesting(std::unique_ptr<base::Clock> clock); private: struct CacheEntry { @@ -66,7 +66,7 @@ }; using CacheEntryMap = - base::HashingMRUCache<std::string, scoped_ptr<CacheEntry>>; + base::HashingMRUCache<std::string, std::unique_ptr<CacheEntry>>; // Returns true if |entry| is expired as of |now|. bool IsExpired(CacheEntry* entry, const base::Time& now); @@ -74,7 +74,7 @@ // Removes all expired sessions from the cache. void FlushExpiredSessions(); - scoped_ptr<base::Clock> clock_; + std::unique_ptr<base::Clock> clock_; Config config_; CacheEntryMap cache_; size_t lookups_since_flush_;
diff --git a/net/ssl/ssl_client_session_cache_openssl_unittest.cc b/net/ssl/ssl_client_session_cache_openssl_unittest.cc index ee579f00..566e0499 100644 --- a/net/ssl/ssl_client_session_cache_openssl_unittest.cc +++ b/net/ssl/ssl_client_session_cache_openssl_unittest.cc
@@ -6,6 +6,7 @@ #include <openssl/ssl.h> +#include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/test/simple_test_clock.h" #include "net/ssl/scoped_openssl_types.h" @@ -146,7 +147,7 @@ config.timeout = kTimeout; SSLClientSessionCacheOpenSSL cache(config); base::SimpleTestClock* clock = new base::SimpleTestClock; - cache.SetClockForTesting(make_scoped_ptr(clock)); + cache.SetClockForTesting(base::WrapUnique(clock)); // Add |kNumEntries - 1| entries. for (size_t i = 0; i < kNumEntries - 1; i++) { @@ -194,7 +195,7 @@ config.timeout = kTimeout; SSLClientSessionCacheOpenSSL cache(config); base::SimpleTestClock* clock = new base::SimpleTestClock; - cache.SetClockForTesting(make_scoped_ptr(clock)); + cache.SetClockForTesting(base::WrapUnique(clock)); // Insert an entry into the session cache. ScopedSSL_SESSION session(SSL_SESSION_new());
diff --git a/net/ssl/ssl_key_logger.h b/net/ssl/ssl_key_logger.h index dcaf6c6..c1e8f5b0 100644 --- a/net/ssl/ssl_key_logger.h +++ b/net/ssl/ssl_key_logger.h
@@ -5,11 +5,11 @@ #ifndef NET_SSL_SSL_KEY_LOGGER_H_ #define NET_SSL_SSL_KEY_LOGGER_H_ +#include <memory> #include <string> #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" namespace base { class FilePath; @@ -40,7 +40,7 @@ scoped_refptr<base::SequencedTaskRunner> task_runner_; // Destroyed on |task_runner_|. - scoped_ptr<Core> core_; + std::unique_ptr<Core> core_; DISALLOW_COPY_AND_ASSIGN(SSLKeyLogger); };
diff --git a/net/ssl/ssl_platform_key.h b/net/ssl/ssl_platform_key.h index a6d5313..10d63a3 100644 --- a/net/ssl/ssl_platform_key.h +++ b/net/ssl/ssl_platform_key.h
@@ -5,9 +5,10 @@ #ifndef NET_SSL_SSL_PLATFORM_KEY_H_ #define NET_SSL_SSL_PLATFORM_KEY_H_ +#include <memory> + #include "base/lazy_instance.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "net/base/net_export.h" namespace base {
diff --git a/net/ssl/ssl_platform_key_android.cc b/net/ssl/ssl_platform_key_android.cc index 6a6595c..800107a 100644 --- a/net/ssl/ssl_platform_key_android.cc +++ b/net/ssl/ssl_platform_key_android.cc
@@ -6,10 +6,12 @@ #include <openssl/digest.h> #include <openssl/evp.h> + #include <utility> #include "base/logging.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "crypto/scoped_openssl_types.h" #include "net/base/net_errors.h" #include "net/ssl/openssl_client_key_store.h" @@ -120,7 +122,7 @@ return nullptr; } return make_scoped_refptr(new ThreadedSSLPrivateKey( - make_scoped_ptr(new SSLPlatformKeyAndroid(std::move(key), type)), + base::WrapUnique(new SSLPlatformKeyAndroid(std::move(key), type)), GetSSLPlatformKeyTaskRunner())); }
diff --git a/net/ssl/ssl_platform_key_chromecast.cc b/net/ssl/ssl_platform_key_chromecast.cc index ef1fef5..6ee005d 100644 --- a/net/ssl/ssl_platform_key_chromecast.cc +++ b/net/ssl/ssl_platform_key_chromecast.cc
@@ -2,21 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "net/ssl/ssl_platform_key.h" - #include <keyhi.h> +#include <openssl/rsa.h> #include <pk11pub.h> #include <prerror.h> -#include <openssl/rsa.h> - #include "base/logging.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/sequenced_task_runner.h" #include "crypto/scoped_nss_types.h" #include "crypto/scoped_openssl_types.h" #include "net/cert/x509_certificate.h" #include "net/ssl/client_key_store.h" +#include "net/ssl/ssl_platform_key.h" #include "net/ssl/ssl_platform_key_task_runner.h" #include "net/ssl/ssl_private_key.h" #include "net/ssl/threaded_ssl_private_key.h" @@ -129,7 +128,7 @@ } return make_scoped_refptr(new ThreadedSSLPrivateKey( - make_scoped_ptr(new SSLPlatformKeyChromecast(std::move(key))), + base::WrapUnique(new SSLPlatformKeyChromecast(std::move(key))), GetSSLPlatformKeyTaskRunner())); }
diff --git a/net/ssl/ssl_platform_key_mac.cc b/net/ssl/ssl_platform_key_mac.cc index 050189b..35628f8 100644 --- a/net/ssl/ssl_platform_key_mac.cc +++ b/net/ssl/ssl_platform_key_mac.cc
@@ -4,23 +4,24 @@ #include "net/ssl/ssl_platform_key.h" -#include <openssl/ecdsa.h> -#include <openssl/obj.h> -#include <openssl/rsa.h> - -#include <Security/cssm.h> #include <Security/SecBase.h> #include <Security/SecCertificate.h> #include <Security/SecIdentity.h> #include <Security/SecKey.h> +#include <Security/cssm.h> +#include <openssl/ecdsa.h> +#include <openssl/obj.h> +#include <openssl/rsa.h> + +#include <memory> #include "base/location.h" #include "base/logging.h" #include "base/mac/mac_logging.h" #include "base/mac/scoped_cftyperef.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/memory/scoped_policy.h" -#include "base/memory/scoped_ptr.h" #include "base/sequenced_task_runner.h" #include "base/synchronization/lock.h" #include "crypto/mac_security_services_lock.h" @@ -242,7 +243,7 @@ return nullptr; } return make_scoped_refptr(new ThreadedSSLPrivateKey( - make_scoped_ptr(new SSLPlatformKeyMac(private_key.get(), cssm_key)), + base::WrapUnique(new SSLPlatformKeyMac(private_key.get(), cssm_key)), GetSSLPlatformKeyTaskRunner())); }
diff --git a/net/ssl/ssl_platform_key_nss.cc b/net/ssl/ssl_platform_key_nss.cc index 858ffb9..fc05976e 100644 --- a/net/ssl/ssl_platform_key_nss.cc +++ b/net/ssl/ssl_platform_key_nss.cc
@@ -2,23 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "net/ssl/ssl_platform_key.h" - #include <keyhi.h> #include <openssl/bn.h> #include <openssl/ecdsa.h> #include <openssl/rsa.h> #include <pk11pub.h> #include <prerror.h> + #include <utility> #include "base/logging.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/sequenced_task_runner.h" #include "crypto/scoped_nss_types.h" #include "crypto/scoped_openssl_types.h" #include "net/cert/x509_certificate.h" #include "net/ssl/client_key_store.h" +#include "net/ssl/ssl_platform_key.h" #include "net/ssl/ssl_platform_key_task_runner.h" #include "net/ssl/ssl_private_key.h" #include "net/ssl/threaded_ssl_private_key.h" @@ -182,7 +183,7 @@ return nullptr; } return make_scoped_refptr(new ThreadedSSLPrivateKey( - make_scoped_ptr(new SSLPlatformKeyNSS(type, std::move(key))), + base::WrapUnique(new SSLPlatformKeyNSS(type, std::move(key))), GetSSLPlatformKeyTaskRunner())); }
diff --git a/net/ssl/ssl_platform_key_win.cc b/net/ssl/ssl_platform_key_win.cc index 49fc31a6..d49d72f 100644 --- a/net/ssl/ssl_platform_key_win.cc +++ b/net/ssl/ssl_platform_key_win.cc
@@ -351,7 +351,7 @@ // transferred. CHECK_EQ(must_free, TRUE); - scoped_ptr<ThreadedSSLPrivateKey::Delegate> delegate; + std::unique_ptr<ThreadedSSLPrivateKey::Delegate> delegate; if (key_spec == CERT_NCRYPT_KEY_SPEC) { delegate.reset(new SSLPlatformKeyCNG(prov_or_key, key_type, max_length)); } else {
diff --git a/net/ssl/test_ssl_private_key.cc b/net/ssl/test_ssl_private_key.cc index 99ed33b..6d420b0e 100644 --- a/net/ssl/test_ssl_private_key.cc +++ b/net/ssl/test_ssl_private_key.cc
@@ -6,10 +6,12 @@ #include <openssl/digest.h> #include <openssl/evp.h> + #include <utility> #include "base/logging.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "crypto/scoped_openssl_types.h" #include "net/base/net_errors.h" #include "net/ssl/ssl_platform_key_task_runner.h" @@ -121,7 +123,7 @@ return nullptr; } return make_scoped_refptr(new ThreadedSSLPrivateKey( - make_scoped_ptr(new TestSSLPlatformKey(std::move(key), type)), + base::WrapUnique(new TestSSLPlatformKey(std::move(key), type)), GetSSLPlatformKeyTaskRunner())); }
diff --git a/net/ssl/threaded_ssl_private_key.cc b/net/ssl/threaded_ssl_private_key.cc index d2f1d95..93865add 100644 --- a/net/ssl/threaded_ssl_private_key.cc +++ b/net/ssl/threaded_ssl_private_key.cc
@@ -30,7 +30,7 @@ class ThreadedSSLPrivateKey::Core : public base::RefCountedThreadSafe<ThreadedSSLPrivateKey::Core> { public: - Core(scoped_ptr<ThreadedSSLPrivateKey::Delegate> delegate) + Core(std::unique_ptr<ThreadedSSLPrivateKey::Delegate> delegate) : delegate_(std::move(delegate)) {} ThreadedSSLPrivateKey::Delegate* delegate() { return delegate_.get(); } @@ -45,11 +45,11 @@ friend class base::RefCountedThreadSafe<Core>; ~Core() {} - scoped_ptr<ThreadedSSLPrivateKey::Delegate> delegate_; + std::unique_ptr<ThreadedSSLPrivateKey::Delegate> delegate_; }; ThreadedSSLPrivateKey::ThreadedSSLPrivateKey( - scoped_ptr<ThreadedSSLPrivateKey::Delegate> delegate, + std::unique_ptr<ThreadedSSLPrivateKey::Delegate> delegate, scoped_refptr<base::TaskRunner> task_runner) : core_(new Core(std::move(delegate))), task_runner_(std::move(task_runner)),
diff --git a/net/ssl/threaded_ssl_private_key.h b/net/ssl/threaded_ssl_private_key.h index 23aed37c..c2fe228 100644 --- a/net/ssl/threaded_ssl_private_key.h +++ b/net/ssl/threaded_ssl_private_key.h
@@ -8,11 +8,11 @@ #include <stddef.h> #include <stdint.h> +#include <memory> #include <vector> #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/strings/string_piece.h" #include "net/ssl/ssl_private_key.h" @@ -52,7 +52,7 @@ DISALLOW_COPY_AND_ASSIGN(Delegate); }; - ThreadedSSLPrivateKey(scoped_ptr<Delegate> delegate, + ThreadedSSLPrivateKey(std::unique_ptr<Delegate> delegate, scoped_refptr<base::TaskRunner> task_runner); // SSLPrivateKey implementation.
diff --git a/net/test/embedded_test_server/default_handlers.cc b/net/test/embedded_test_server/default_handlers.cc index 7496721..2410db3 100644 --- a/net/test/embedded_test_server/default_handlers.cc +++ b/net/test/embedded_test_server/default_handlers.cc
@@ -46,11 +46,11 @@ // method: CONNECT // Responses with a BAD_REQUEST to any CONNECT requests. -scoped_ptr<HttpResponse> HandleDefaultConnect(const HttpRequest& request) { +std::unique_ptr<HttpResponse> HandleDefaultConnect(const HttpRequest& request) { if (request.method != METHOD_CONNECT) return nullptr; - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_code(HTTP_BAD_REQUEST); http_response->set_content( "Your client has issued a malformed or illegal request."); @@ -60,8 +60,8 @@ // /cachetime // Returns a cacheable response. -scoped_ptr<HttpResponse> HandleCacheTime(const HttpRequest& request) { - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); +std::unique_ptr<HttpResponse> HandleCacheTime(const HttpRequest& request) { + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_content( "<html><head><title>Cache: max-age=60</title></head></html>"); http_response->set_content_type("text/html"); @@ -72,13 +72,13 @@ // /echoheader | /echoheadercache // Responds with the headers echoed in the message body. // echoheader does not cache the results, while echoheadercache does. -scoped_ptr<HttpResponse> HandleEchoHeader(const std::string& url, - const std::string& cache_control, - const HttpRequest& request) { +std::unique_ptr<HttpResponse> HandleEchoHeader(const std::string& url, + const std::string& cache_control, + const HttpRequest& request) { if (!ShouldHandle(request, url)) return nullptr; - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); GURL request_url = request.GetURL(); if (request_url.has_query()) { @@ -98,8 +98,8 @@ // /echo?status=STATUS // Responds with the request body as the response body and // a status code of STATUS. -scoped_ptr<HttpResponse> HandleEcho(const HttpRequest& request) { - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); +std::unique_ptr<HttpResponse> HandleEcho(const HttpRequest& request) { + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); GURL request_url = request.GetURL(); if (request_url.has_query()) { @@ -119,8 +119,8 @@ // /echotitle // Responds with the request body as the title. -scoped_ptr<HttpResponse> HandleEchoTitle(const HttpRequest& request) { - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); +std::unique_ptr<HttpResponse> HandleEchoTitle(const HttpRequest& request) { + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_content_type("text/html"); http_response->set_content("<html><head><title>" + request.content + "</title></head></html>"); @@ -129,8 +129,8 @@ // /echoall?QUERY // Responds with the list of QUERY and the request headers. -scoped_ptr<HttpResponse> HandleEchoAll(const HttpRequest& request) { - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); +std::unique_ptr<HttpResponse> HandleEchoAll(const HttpRequest& request) { + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); std::string body = "<html><head><style>" @@ -161,8 +161,8 @@ // /set-cookie?COOKIES // Sets response cookies to be COOKIES. -scoped_ptr<HttpResponse> HandleSetCookie(const HttpRequest& request) { - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); +std::unique_ptr<HttpResponse> HandleSetCookie(const HttpRequest& request) { + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_content_type("text/html"); std::string content; GURL request_url = request.GetURL(); @@ -181,7 +181,7 @@ // /set-many-cookies?N // Sets N cookies in the response. -scoped_ptr<HttpResponse> HandleSetManyCookies(const HttpRequest& request) { +std::unique_ptr<HttpResponse> HandleSetManyCookies(const HttpRequest& request) { std::string content; GURL request_url = request.GetURL(); @@ -189,7 +189,7 @@ if (request_url.has_query()) num = std::atoi(request_url.query().c_str()); - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_content_type("text/html"); for (size_t i = 0; i < num; ++i) { http_response->AddCustomHeader("Set-Cookie", "a="); @@ -203,7 +203,8 @@ // /expect-and-set-cookie?expect=EXPECTED&set=SET&data=DATA // Verifies that the request cookies match EXPECTED and then returns cookies // that match SET and a content that matches DATA. -scoped_ptr<HttpResponse> HandleExpectAndSetCookie(const HttpRequest& request) { +std::unique_ptr<HttpResponse> HandleExpectAndSetCookie( + const HttpRequest& request) { std::vector<std::string> received_cookies; if (request.headers.find("Cookie") != request.headers.end()) { received_cookies = @@ -225,7 +226,7 @@ } } - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_content_type("text/html"); if (got_all_expected) { for (const auto& cookie : query_list.at("set")) { @@ -246,12 +247,12 @@ // /set-header?HEADERS // Returns a response with HEADERS set as the response headers. -scoped_ptr<HttpResponse> HandleSetHeader(const HttpRequest& request) { +std::unique_ptr<HttpResponse> HandleSetHeader(const HttpRequest& request) { std::string content; GURL request_url = request.GetURL(); - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_content_type("text/html"); if (request_url.has_query()) { RequestQuery headers = ParseQuery(request_url); @@ -272,23 +273,23 @@ // /nocontent // Returns a NO_CONTENT response. -scoped_ptr<HttpResponse> HandleNoContent(const HttpRequest& request) { - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); +std::unique_ptr<HttpResponse> HandleNoContent(const HttpRequest& request) { + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_code(HTTP_NO_CONTENT); return std::move(http_response); } // /close-socket // Immediately closes the connection. -scoped_ptr<HttpResponse> HandleCloseSocket(const HttpRequest& request) { - scoped_ptr<RawHttpResponse> http_response(new RawHttpResponse("", "")); +std::unique_ptr<HttpResponse> HandleCloseSocket(const HttpRequest& request) { + std::unique_ptr<RawHttpResponse> http_response(new RawHttpResponse("", "")); return std::move(http_response); } // /auth-basic?password=PASS&realm=REALM // Performs "Basic" HTTP authentication using expected password PASS and // realm REALM. -scoped_ptr<HttpResponse> HandleAuthBasic(const HttpRequest& request) { +std::unique_ptr<HttpResponse> HandleAuthBasic(const HttpRequest& request) { GURL request_url = request.GetURL(); RequestQuery query = ParseQuery(request_url); @@ -329,7 +330,7 @@ } } - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); if (!authed) { http_response->set_code(HTTP_UNAUTHORIZED); http_response->set_content_type("text/html"); @@ -378,7 +379,7 @@ // /auth-digest // Performs "Digest" HTTP authentication. -scoped_ptr<HttpResponse> HandleAuthDigest(const HttpRequest& request) { +std::unique_ptr<HttpResponse> HandleAuthDigest(const HttpRequest& request) { std::string nonce = base::MD5String( base::StringPrintf("privatekey%s", request.relative_url.c_str())); std::string opaque = base::MD5String("opaque"); @@ -446,7 +447,7 @@ } } - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); if (!authed) { http_response->set_code(HTTP_UNAUTHORIZED); http_response->set_content_type("text/html"); @@ -476,12 +477,12 @@ // /server-redirect?URL // Returns a server-redirect (301) to URL. -scoped_ptr<HttpResponse> HandleServerRedirect(const HttpRequest& request) { +std::unique_ptr<HttpResponse> HandleServerRedirect(const HttpRequest& request) { GURL request_url = request.GetURL(); std::string dest = net::UnescapeURLComponent(request_url.query(), kUnescapeAll); - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_code(HTTP_MOVED_PERMANENTLY); http_response->AddCustomHeader("Location", dest); http_response->set_content_type("text/html"); @@ -493,8 +494,9 @@ // /cross-site?URL // Returns a cross-site redirect to URL. -scoped_ptr<HttpResponse> HandleCrossSiteRedirect(EmbeddedTestServer* server, - const HttpRequest& request) { +std::unique_ptr<HttpResponse> HandleCrossSiteRedirect( + EmbeddedTestServer* server, + const HttpRequest& request) { if (!ShouldHandle(request, "/cross-site")) return nullptr; @@ -510,7 +512,7 @@ dest_all.substr(delimiter + 1).c_str()); } - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_code(HTTP_MOVED_PERMANENTLY); http_response->AddCustomHeader("Location", dest); http_response->set_content_type("text/html"); @@ -522,12 +524,12 @@ // /client-redirect?URL // Returns a meta redirect to URL. -scoped_ptr<HttpResponse> HandleClientRedirect(const HttpRequest& request) { +std::unique_ptr<HttpResponse> HandleClientRedirect(const HttpRequest& request) { GURL request_url = request.GetURL(); std::string dest = net::UnescapeURLComponent(request_url.query(), kUnescapeAll); - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_content_type("text/html"); http_response->set_content(base::StringPrintf( "<html><head><meta http-equiv=\"refresh\" content=\"0;url=%s\"></head>" @@ -538,8 +540,9 @@ // /defaultresponse // Returns a valid 200 response. -scoped_ptr<HttpResponse> HandleDefaultResponse(const HttpRequest& request) { - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); +std::unique_ptr<HttpResponse> HandleDefaultResponse( + const HttpRequest& request) { + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_content_type("text/html"); http_response->set_content("Default response given for path: " + request.relative_url); @@ -566,14 +569,15 @@ // /slow?N // Returns a response to the server delayed by N seconds. -scoped_ptr<HttpResponse> HandleSlowServer(const HttpRequest& request) { +std::unique_ptr<HttpResponse> HandleSlowServer(const HttpRequest& request) { double delay = 1.0f; GURL request_url = request.GetURL(); if (request_url.has_query()) delay = std::atof(request_url.query().c_str()); - scoped_ptr<BasicHttpResponse> http_response(new DelayedHttpResponse(delay)); + std::unique_ptr<BasicHttpResponse> http_response( + new DelayedHttpResponse(delay)); http_response->set_content_type("text/plain"); http_response->set_content(base::StringPrintf("waited %.1f seconds", delay)); return std::move(http_response);
diff --git a/net/test/embedded_test_server/embedded_test_server.cc b/net/test/embedded_test_server/embedded_test_server.cc index eb09b96..152d460 100644 --- a/net/test/embedded_test_server/embedded_test_server.cc +++ b/net/test/embedded_test_server/embedded_test_server.cc
@@ -131,7 +131,7 @@ std::vector<uint8_t> key_vector; key_vector.assign(pem_tokenizer.data().begin(), pem_tokenizer.data().end()); - scoped_ptr<crypto::RSAPrivateKey> server_key( + std::unique_ptr<crypto::RSAPrivateKey> server_key( crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(key_vector)); context_ = CreateSSLServerContext(GetCertificate().get(), *server_key, ssl_config_); @@ -167,10 +167,10 @@ } void EmbeddedTestServer::HandleRequest(HttpConnection* connection, - scoped_ptr<HttpRequest> request) { + std::unique_ptr<HttpRequest> request) { DCHECK(io_thread_->task_runner()->BelongsToCurrentThread()); - scoped_ptr<HttpResponse> response; + std::unique_ptr<HttpResponse> response; for (const auto& handler : request_handlers_) { response = handler.Run(*request); @@ -189,7 +189,8 @@ if (!response) { LOG(WARNING) << "Request not handled. Returning 404: " << request->relative_url; - scoped_ptr<BasicHttpResponse> not_found_response(new BasicHttpResponse); + std::unique_ptr<BasicHttpResponse> not_found_response( + new BasicHttpResponse); not_found_response->set_code(HTTP_NOT_FOUND); response = std::move(not_found_response); } @@ -295,8 +296,8 @@ default_request_handlers_.push_back(callback); } -scoped_ptr<StreamSocket> EmbeddedTestServer::DoSSLUpgrade( - scoped_ptr<StreamSocket> connection) { +std::unique_ptr<StreamSocket> EmbeddedTestServer::DoSSLUpgrade( + std::unique_ptr<StreamSocket> connection) { DCHECK(io_thread_->task_runner()->BelongsToCurrentThread()); return context_->CreateSSLServerSocket(std::move(connection)); @@ -327,7 +328,8 @@ DidClose(connection); } -void EmbeddedTestServer::HandleAcceptResult(scoped_ptr<StreamSocket> socket) { +void EmbeddedTestServer::HandleAcceptResult( + std::unique_ptr<StreamSocket> socket) { DCHECK(io_thread_->task_runner()->BelongsToCurrentThread()); if (connection_listener_) connection_listener_->AcceptedSocket(*socket); @@ -419,7 +421,7 @@ // // To handle this situation, create temporary message loop to support the // PostTaskAndReply operation if the current thread as no message loop. - scoped_ptr<base::MessageLoop> temporary_loop; + std::unique_ptr<base::MessageLoop> temporary_loop; if (!base::MessageLoop::current()) temporary_loop.reset(new base::MessageLoop());
diff --git a/net/test/embedded_test_server/embedded_test_server.h b/net/test/embedded_test_server/embedded_test_server.h index 00952f9..93ba690 100644 --- a/net/test/embedded_test_server/embedded_test_server.h +++ b/net/test/embedded_test_server/embedded_test_server.h
@@ -8,6 +8,7 @@ #include <stdint.h> #include <map> +#include <memory> #include <string> #include <vector> @@ -16,7 +17,6 @@ #include "base/files/file_path.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread.h" #include "base/threading/thread_checker.h" @@ -57,12 +57,12 @@ // base::Bind(&FooTest::HandleRequest, base::Unretained(this))); // } // -// scoped_ptr<HttpResponse> HandleRequest(const HttpRequest& request) { +// std::unique_ptr<HttpResponse> HandleRequest(const HttpRequest& request) { // GURL absolute_url = test_server_->GetURL(request.relative_url); // if (absolute_url.path() != "/test") -// return scoped_ptr<HttpResponse>(); +// return std::unique_ptr<HttpResponse>(); // -// scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse()); +// std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse()); // http_response->set_code(test_server::SUCCESS); // http_response->set_content("hello"); // http_response->set_content_type("text/plain"); @@ -114,8 +114,9 @@ CERT_COMMON_NAME_IS_DOMAIN, }; - typedef base::Callback<scoped_ptr<HttpResponse>( - const HttpRequest& request)> HandleRequestCallback; + typedef base::Callback<std::unique_ptr<HttpResponse>( + const HttpRequest& request)> + HandleRequestCallback; // Creates a http test server. Start() must be called to start the server. // |type| indicates the protocol type of the server (HTTP/HTTPS). @@ -215,7 +216,8 @@ void ShutdownOnIOThread(); // Upgrade the TCP connection to one over SSL. - scoped_ptr<StreamSocket> DoSSLUpgrade(scoped_ptr<StreamSocket> connection); + std::unique_ptr<StreamSocket> DoSSLUpgrade( + std::unique_ptr<StreamSocket> connection); // Handles async callback when the SSL handshake has been completed. void OnHandshakeDone(HttpConnection* connection, int rv); @@ -226,7 +228,7 @@ void OnAcceptCompleted(int rv); // Adds the new |socket| to the list of clients and begins the reading // data. - void HandleAcceptResult(scoped_ptr<StreamSocket> socket); + void HandleAcceptResult(std::unique_ptr<StreamSocket> socket); // Attempts to read data from the |connection|'s socket. void ReadData(HttpConnection* connection); @@ -242,7 +244,7 @@ // Handles a request when it is parsed. It passes the request to registered // request handlers and sends a http response. void HandleRequest(HttpConnection* connection, - scoped_ptr<HttpRequest> request); + std::unique_ptr<HttpRequest> request); // Initializes the SSLServerContext so that SSLServerSocket connections may // share the same cache @@ -256,10 +258,10 @@ const bool is_using_ssl_; - scoped_ptr<base::Thread> io_thread_; + std::unique_ptr<base::Thread> io_thread_; - scoped_ptr<TCPServerSocket> listen_socket_; - scoped_ptr<StreamSocket> accepted_socket_; + std::unique_ptr<TCPServerSocket> listen_socket_; + std::unique_ptr<StreamSocket> accepted_socket_; EmbeddedTestServerConnectionListener* connection_listener_; uint16_t port_; @@ -277,7 +279,7 @@ net::SSLServerConfig ssl_config_; ServerCertificate cert_; - scoped_ptr<SSLServerContext> context_; + std::unique_ptr<SSLServerContext> context_; base::WeakPtrFactory<EmbeddedTestServer> weak_factory_;
diff --git a/net/test/embedded_test_server/embedded_test_server_unittest.cc b/net/test/embedded_test_server/embedded_test_server_unittest.cc index 0e3f56a..d994b00 100644 --- a/net/test/embedded_test_server/embedded_test_server_unittest.cc +++ b/net/test/embedded_test_server/embedded_test_server_unittest.cc
@@ -7,6 +7,7 @@ #include <utility> #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" #include "base/path_service.h" #include "base/run_loop.h" @@ -167,16 +168,16 @@ // Handles |request| sent to |path| and returns the response per |content|, // |content type|, and |code|. Saves the request URL for verification. - scoped_ptr<HttpResponse> HandleRequest(const std::string& path, - const std::string& content, - const std::string& content_type, - HttpStatusCode code, - const HttpRequest& request) { + std::unique_ptr<HttpResponse> HandleRequest(const std::string& path, + const std::string& content, + const std::string& content_type, + HttpStatusCode code, + const HttpRequest& request) { request_relative_url_ = request.relative_url; GURL absolute_url = server_->GetURL(request.relative_url); if (absolute_url.path() == path) { - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_code(code); http_response->set_content(content); http_response->set_content_type(content_type); @@ -193,7 +194,7 @@ base::Thread io_thread_; scoped_refptr<TestURLRequestContextGetter> request_context_getter_; TestConnectionListener connection_listener_; - scoped_ptr<EmbeddedTestServer> server_; + std::unique_ptr<EmbeddedTestServer> server_; }; TEST_P(EmbeddedTestServerTest, GetBaseURL) { @@ -243,7 +244,7 @@ HTTP_OK)); ASSERT_TRUE(server_->Start()); - scoped_ptr<URLFetcher> fetcher = + std::unique_ptr<URLFetcher> fetcher = URLFetcher::Create(server_->GetURL("/test?q=foo"), URLFetcher::GET, this); fetcher->SetRequestContext(request_context_getter_.get()); fetcher->Start(); @@ -264,7 +265,7 @@ src_dir.AppendASCII("net").AppendASCII("data")); ASSERT_TRUE(server_->Start()); - scoped_ptr<URLFetcher> fetcher = + std::unique_ptr<URLFetcher> fetcher = URLFetcher::Create(server_->GetURL("/test.html"), URLFetcher::GET, this); fetcher->SetRequestContext(request_context_getter_.get()); fetcher->Start(); @@ -279,7 +280,7 @@ TEST_P(EmbeddedTestServerTest, DefaultNotFoundResponse) { ASSERT_TRUE(server_->Start()); - scoped_ptr<URLFetcher> fetcher = URLFetcher::Create( + std::unique_ptr<URLFetcher> fetcher = URLFetcher::Create( server_->GetURL("/non-existent"), URLFetcher::GET, this); fetcher->SetRequestContext(request_context_getter_.get()); @@ -296,7 +297,7 @@ net::AddressList address_list; EXPECT_TRUE(server_->GetAddressList(&address_list)); - scoped_ptr<StreamSocket> socket = + std::unique_ptr<StreamSocket> socket = ClientSocketFactory::GetDefaultFactory()->CreateTransportClientSocket( address_list, NULL, &net_log, NetLog::Source()); TestCompletionCallback callback; @@ -311,7 +312,7 @@ TEST_P(EmbeddedTestServerTest, ConnectionListenerRead) { ASSERT_TRUE(server_->Start()); - scoped_ptr<URLFetcher> fetcher = URLFetcher::Create( + std::unique_ptr<URLFetcher> fetcher = URLFetcher::Create( server_->GetURL("/non-existent"), URLFetcher::GET, this); fetcher->SetRequestContext(request_context_getter_.get()); @@ -345,13 +346,13 @@ HTTP_NOT_FOUND)); ASSERT_TRUE(server_->Start()); - scoped_ptr<URLFetcher> fetcher1 = + std::unique_ptr<URLFetcher> fetcher1 = URLFetcher::Create(server_->GetURL("/test1"), URLFetcher::GET, this); fetcher1->SetRequestContext(request_context_getter_.get()); - scoped_ptr<URLFetcher> fetcher2 = + std::unique_ptr<URLFetcher> fetcher2 = URLFetcher::Create(server_->GetURL("/test2"), URLFetcher::GET, this); fetcher2->SetRequestContext(request_context_getter_.get()); - scoped_ptr<URLFetcher> fetcher3 = + std::unique_ptr<URLFetcher> fetcher3 = URLFetcher::Create(server_->GetURL("/test3"), URLFetcher::GET, this); fetcher3->SetRequestContext(request_context_getter_.get()); @@ -423,8 +424,9 @@ DISALLOW_COPY_AND_ASSIGN(InfiniteResponse); }; -scoped_ptr<HttpResponse> HandleInfiniteRequest(const HttpRequest& request) { - return make_scoped_ptr(new InfiniteResponse); +std::unique_ptr<HttpResponse> HandleInfiniteRequest( + const HttpRequest& request) { + return base::WrapUnique(new InfiniteResponse); } } @@ -440,7 +442,7 @@ &HandlePrefixedRequest, "/infinite", base::Bind(&HandleInfiniteRequest))); ASSERT_TRUE(server_->Start()); - scoped_ptr<URLRequest> request = context.CreateRequest( + std::unique_ptr<URLRequest> request = context.CreateRequest( server_->GetURL("/infinite"), DEFAULT_PRIORITY, &cancel_delegate); request->Start(); cancel_delegate.WaitUntilDone(); @@ -534,7 +536,7 @@ ASSERT_TRUE(io_thread.StartWithOptions(thread_options)); io_thread_runner = io_thread.task_runner(); - scoped_ptr<base::MessageLoop> loop; + std::unique_ptr<base::MessageLoop> loop; if (message_loop_present_on_initialize_) loop.reset(new base::MessageLoopForIO); @@ -548,7 +550,7 @@ if (!loop) loop.reset(new base::MessageLoopForIO); - scoped_ptr<URLFetcher> fetcher = + std::unique_ptr<URLFetcher> fetcher = URLFetcher::Create(server.GetURL("/test?q=foo"), URLFetcher::GET, this); fetcher->SetRequestContext( new TestURLRequestContextGetter(loop->task_runner()));
diff --git a/net/test/embedded_test_server/http_connection.cc b/net/test/embedded_test_server/http_connection.cc index ce95f436..2f3e906 100644 --- a/net/test/embedded_test_server/http_connection.cc +++ b/net/test/embedded_test_server/http_connection.cc
@@ -12,7 +12,7 @@ namespace net { namespace test_server { -HttpConnection::HttpConnection(scoped_ptr<StreamSocket> socket, +HttpConnection::HttpConnection(std::unique_ptr<StreamSocket> socket, const HandleRequestCallback& callback) : socket_(std::move(socket)), callback_(callback),
diff --git a/net/test/embedded_test_server/http_connection.h b/net/test/embedded_test_server/http_connection.h index 4f4e555..0b87fcb2 100644 --- a/net/test/embedded_test_server/http_connection.h +++ b/net/test/embedded_test_server/http_connection.h
@@ -5,10 +5,11 @@ #ifndef NET_TEST_EMBEDDED_TEST_SERVER_HTTP_CONNECTION_H_ #define NET_TEST_EMBEDDED_TEST_SERVER_HTTP_CONNECTION_H_ +#include <memory> + #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/strings/string_piece.h" #include "net/base/completion_callback.h" @@ -28,14 +29,14 @@ // Calblack called when a request is parsed. Response should be sent // using HttpConnection::SendResponse() on the |connection| argument. typedef base::Callback<void(HttpConnection* connection, - scoped_ptr<HttpRequest> request)> + std::unique_ptr<HttpRequest> request)> HandleRequestCallback; // Wraps the connection socket. Accepts incoming data and sends responses. // If a valid request is parsed, then |callback_| is invoked. class HttpConnection { public: - HttpConnection(scoped_ptr<StreamSocket> socket, + HttpConnection(std::unique_ptr<StreamSocket> socket, const HandleRequestCallback& callback); ~HttpConnection(); @@ -61,7 +62,7 @@ base::WeakPtr<HttpConnection> GetWeakPtr(); - scoped_ptr<StreamSocket> socket_; + std::unique_ptr<StreamSocket> socket_; const HandleRequestCallback callback_; HttpRequestParser request_parser_; scoped_refptr<IOBufferWithSize> read_buf_;
diff --git a/net/test/embedded_test_server/http_request.cc b/net/test/embedded_test_server/http_request.cc index a1332be..2c247c6 100644 --- a/net/test/embedded_test_server/http_request.cc +++ b/net/test/embedded_test_server/http_request.cc
@@ -217,9 +217,9 @@ return WAITING; } -scoped_ptr<HttpRequest> HttpRequestParser::GetRequest() { +std::unique_ptr<HttpRequest> HttpRequestParser::GetRequest() { DCHECK_EQ(STATE_ACCEPTED, state_); - scoped_ptr<HttpRequest> result = std::move(http_request_); + std::unique_ptr<HttpRequest> result = std::move(http_request_); // Prepare for parsing a new request. state_ = STATE_HEADERS;
diff --git a/net/test/embedded_test_server/http_request.h b/net/test/embedded_test_server/http_request.h index d9e54b8..b58f774 100644 --- a/net/test/embedded_test_server/http_request.h +++ b/net/test/embedded_test_server/http_request.h
@@ -8,10 +8,10 @@ #include <stddef.h> #include <map> +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "url/gurl.h" @@ -73,7 +73,7 @@ // void OnDataChunkReceived(Socket* socket, const char* data, int size) { // parser.ProcessChunk(std::string(data, size)); // if (parser.ParseRequest() == HttpRequestParser::ACCEPTED) { -// scoped_ptr<HttpRequest> request = parser.GetRequest(); +// std::unique_ptr<HttpRequest> request = parser.GetRequest(); // (... process the request ...) // } class HttpRequestParser { @@ -106,7 +106,7 @@ // Retrieves parsed request. Can be only called, when the parser is in // STATE_ACCEPTED state. After calling it, the parser is ready to parse // another request. - scoped_ptr<HttpRequest> GetRequest(); + std::unique_ptr<HttpRequest> GetRequest(); private: HttpMethod GetMethodType(const std::string& token) const; @@ -124,14 +124,14 @@ // no line available. std::string ShiftLine(); - scoped_ptr<HttpRequest> http_request_; + std::unique_ptr<HttpRequest> http_request_; std::string buffer_; size_t buffer_position_; // Current position in the internal buffer. State state_; // Content length of the request currently being parsed. size_t declared_content_length_; - scoped_ptr<HttpChunkedDecoder> chunked_decoder_; + std::unique_ptr<HttpChunkedDecoder> chunked_decoder_; DISALLOW_COPY_AND_ASSIGN(HttpRequestParser); };
diff --git a/net/test/embedded_test_server/http_request_unittest.cc b/net/test/embedded_test_server/http_request_unittest.cc index ff2ae3c..64761cf 100644 --- a/net/test/embedded_test_server/http_request_unittest.cc +++ b/net/test/embedded_test_server/http_request_unittest.cc
@@ -4,7 +4,8 @@ #include "net/test/embedded_test_server/http_request.h" -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "testing/gtest/include/gtest/gtest.h" namespace net { @@ -34,7 +35,7 @@ // Fetch the first request and validate it. { - scoped_ptr<HttpRequest> request = parser.GetRequest(); + std::unique_ptr<HttpRequest> request = parser.GetRequest(); EXPECT_EQ("/foobar.html", request->relative_url); EXPECT_EQ("POST", request->method_string); EXPECT_EQ(METHOD_POST, request->method); @@ -70,7 +71,7 @@ parser.ProcessChunk("Content-Length: 0\r\n\r\n"); ASSERT_EQ(HttpRequestParser::ACCEPTED, parser.ParseRequest()); - scoped_ptr<HttpRequest> request = parser.GetRequest(); + std::unique_ptr<HttpRequest> request = parser.GetRequest(); EXPECT_EQ("", request->content); EXPECT_TRUE(request->has_content); EXPECT_EQ(1u, request->headers.count("Content-Length")); @@ -88,7 +89,7 @@ parser.ProcessChunk("0\r\n\r\n"); ASSERT_EQ(HttpRequestParser::ACCEPTED, parser.ParseRequest()); - scoped_ptr<HttpRequest> request = parser.GetRequest(); + std::unique_ptr<HttpRequest> request = parser.GetRequest(); EXPECT_EQ("hello world", request->content); EXPECT_TRUE(request->has_content); EXPECT_EQ(1u, request->headers.count("Transfer-Encoding")); @@ -112,7 +113,7 @@ } // All chunked data has been sent, the last ParseRequest should give ACCEPTED. ASSERT_EQ(HttpRequestParser::ACCEPTED, parser.ParseRequest()); - scoped_ptr<HttpRequest> request = parser.GetRequest(); + std::unique_ptr<HttpRequest> request = parser.GetRequest(); EXPECT_EQ("hello", request->content); EXPECT_TRUE(request->has_content); EXPECT_EQ(1u, request->headers.count("Transfer-Encoding")); @@ -125,7 +126,7 @@ parser.ProcessChunk("POST /foobar.html HTTP/1.1\r\n\r\n"); ASSERT_EQ(HttpRequestParser::ACCEPTED, parser.ParseRequest()); - scoped_ptr<HttpRequest> request = parser.GetRequest(); + std::unique_ptr<HttpRequest> request = parser.GetRequest(); EXPECT_EQ("", request->content); EXPECT_FALSE(request->has_content); } @@ -136,7 +137,7 @@ parser.ProcessChunk("GET /foobar.html HTTP/1.1\r\n\r\n"); ASSERT_EQ(HttpRequestParser::ACCEPTED, parser.ParseRequest()); - scoped_ptr<HttpRequest> request = parser.GetRequest(); + std::unique_ptr<HttpRequest> request = parser.GetRequest(); EXPECT_EQ("/foobar.html", request->relative_url); EXPECT_EQ("GET", request->method_string); EXPECT_EQ(METHOD_GET, request->method);
diff --git a/net/test/embedded_test_server/request_handler_util.cc b/net/test/embedded_test_server/request_handler_util.cc index db3f3a6..b555578f2 100644 --- a/net/test/embedded_test_server/request_handler_util.cc +++ b/net/test/embedded_test_server/request_handler_util.cc
@@ -5,6 +5,7 @@ #include "net/test/embedded_test_server/request_handler_util.h" #include <stdlib.h> + #include <ctime> #include <sstream> #include <utility> @@ -12,6 +13,7 @@ #include "base/base64.h" #include "base/files/file_util.h" #include "base/format_macros.h" +#include "base/memory/ptr_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_restrictions.h" @@ -75,7 +77,7 @@ base::CompareCase::SENSITIVE); } -scoped_ptr<HttpResponse> HandlePrefixedRequest( +std::unique_ptr<HttpResponse> HandlePrefixedRequest( const std::string& prefix, const EmbeddedTestServer::HandleRequestCallback& handler, const HttpRequest& request) { @@ -118,8 +120,9 @@ } // Handles |request| by serving a file from under |server_root|. -scoped_ptr<HttpResponse> HandleFileRequest(const base::FilePath& server_root, - const HttpRequest& request) { +std::unique_ptr<HttpResponse> HandleFileRequest( + const base::FilePath& server_root, + const HttpRequest& request) { // This is a test-only server. Ignore I/O thread restrictions. // TODO(svaldez): Figure out why thread is I/O restricted in the first place. base::ThreadRestrictions::ScopedAllowIO allow_io; @@ -139,7 +142,7 @@ RequestQuery query = ParseQuery(request_url); - scoped_ptr<BasicHttpResponse> failed_response(new BasicHttpResponse); + std::unique_ptr<BasicHttpResponse> failed_response(new BasicHttpResponse); failed_response->set_code(HTTP_NOT_FOUND); if (query.find("expected_body") != query.end()) { @@ -197,11 +200,11 @@ if (!base::ReadFileToString(headers_path, &headers_contents)) return nullptr; - return make_scoped_ptr( + return base::WrapUnique( new RawHttpResponse(headers_contents, file_contents)); } - scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); + std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_code(HTTP_OK); if (request.headers.find("Range") != request.headers.end()) {
diff --git a/net/test/embedded_test_server/request_handler_util.h b/net/test/embedded_test_server/request_handler_util.h index 2ed8d13..fe86755 100644 --- a/net/test/embedded_test_server/request_handler_util.h +++ b/net/test/embedded_test_server/request_handler_util.h
@@ -6,12 +6,12 @@ #define NET_TEST_EMBEDDED_TEST_SERVER_REQUEST_HANDLER_UTIL_H_ #include <map> +#include <memory> #include <string> #include <vector> #include "base/files/file_path.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string_split.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_response.h" @@ -34,7 +34,7 @@ bool ShouldHandle(const HttpRequest& request, const std::string& prefix_path); // Calls |handler| if the |request| URL starts with |prefix|. -scoped_ptr<HttpResponse> HandlePrefixedRequest( +std::unique_ptr<HttpResponse> HandlePrefixedRequest( const std::string& prefix, const EmbeddedTestServer::HandleRequestCallback& handler, const HttpRequest& request); @@ -54,8 +54,9 @@ std::string* replacement_path); // Handles |request| by serving a file from under |server_root|. -scoped_ptr<HttpResponse> HandleFileRequest(const base::FilePath& server_root, - const HttpRequest& request); +std::unique_ptr<HttpResponse> HandleFileRequest( + const base::FilePath& server_root, + const HttpRequest& request); } // namespace test_server } // namespace net
diff --git a/net/test/python_utils.cc b/net/test/python_utils.cc index 7d137b7..208e1b92 100644 --- a/net/test/python_utils.cc +++ b/net/test/python_utils.cc
@@ -4,6 +4,8 @@ #include "net/test/python_utils.h" +#include <memory> + #include "base/base_paths.h" #include "base/command_line.h" #include "base/environment.h" @@ -11,7 +13,6 @@ #include "base/files/file_util.h" #include "base/lazy_instance.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/process/launch.h" #include "base/strings/string_util.h" @@ -24,7 +25,7 @@ const char kPythonPathEnv[] = "PYTHONPATH"; void AppendToPythonPath(const base::FilePath& dir) { - scoped_ptr<base::Environment> env(base::Environment::Create()); + std::unique_ptr<base::Environment> env(base::Environment::Create()); std::string old_path; std::string dir_path; #if defined(OS_WIN)
diff --git a/net/test/python_utils_unittest.cc b/net/test/python_utils_unittest.cc index a713e72f..48eb97376 100644 --- a/net/test/python_utils_unittest.cc +++ b/net/test/python_utils_unittest.cc
@@ -2,16 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "net/test/python_utils.h" + +#include <memory> #include <string> #include "base/command_line.h" #include "base/environment.h" #include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" #include "base/process/launch.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" -#include "net/test/python_utils.h" #include "testing/gtest/include/gtest/gtest.h" TEST(PythonUtils, Append) { @@ -20,7 +21,7 @@ const base::FilePath::CharType kAppendDir2[] = FILE_PATH_LITERAL("test/path_append2"); - scoped_ptr<base::Environment> env(base::Environment::Create()); + std::unique_ptr<base::Environment> env(base::Environment::Create()); std::string python_path; base::FilePath append_path1(kAppendDir1);
diff --git a/net/test/spawned_test_server/base_test_server.cc b/net/test/spawned_test_server/base_test_server.cc index ecf5af5..2ef7417 100644 --- a/net/test/spawned_test_server/base_test_server.cc +++ b/net/test/spawned_test_server/base_test_server.cc
@@ -114,8 +114,9 @@ return true; } -scoped_ptr<base::ListValue> GetTokenBindingParams(std::vector<int> params) { - scoped_ptr<base::ListValue> values(new base::ListValue()); +std::unique_ptr<base::ListValue> GetTokenBindingParams( + std::vector<int> params) { + std::unique_ptr<base::ListValue> values(new base::ListValue()); for (int param : params) { values->Append(new base::FundamentalValue(param)); } @@ -265,7 +266,8 @@ bool BaseTestServer::GetAddressList(AddressList* address_list) const { DCHECK(address_list); - scoped_ptr<HostResolver> resolver(HostResolver::CreateDefaultResolver(NULL)); + std::unique_ptr<HostResolver> resolver( + HostResolver::CreateDefaultResolver(NULL)); HostResolver::RequestInfo info(host_port_pair_); // Limit the lookup to IPv4. When started with the default // address of kLocalhost, testserver.py only supports IPv4. @@ -406,7 +408,7 @@ bool BaseTestServer::ParseServerData(const std::string& server_data) { VLOG(1) << "Server data: " << server_data; base::JSONReader json_reader; - scoped_ptr<base::Value> value(json_reader.ReadToValue(server_data)); + std::unique_ptr<base::Value> value(json_reader.ReadToValue(server_data)); if (!value.get() || !value->IsType(base::Value::TYPE_DICTIONARY)) { LOG(ERROR) << "Could not parse server data: " << json_reader.GetErrorMessage(); @@ -490,7 +492,7 @@ // Check the client certificate related arguments. if (ssl_options_.request_client_certificate) arguments->Set("ssl-client-auth", base::Value::CreateNullValue()); - scoped_ptr<base::ListValue> ssl_client_certs(new base::ListValue()); + std::unique_ptr<base::ListValue> ssl_client_certs(new base::ListValue()); std::vector<base::FilePath>::const_iterator it; for (it = ssl_options_.client_authorities.begin(); @@ -506,7 +508,7 @@ if (ssl_client_certs->GetSize()) arguments->Set("ssl-client-ca", ssl_client_certs.release()); - scoped_ptr<base::ListValue> client_cert_types(new base::ListValue()); + std::unique_ptr<base::ListValue> client_cert_types(new base::ListValue()); for (size_t i = 0; i < ssl_options_.client_cert_types.size(); i++) { client_cert_types->Append(new base::StringValue( GetClientCertType(ssl_options_.client_cert_types[i]))); @@ -527,12 +529,12 @@ } // Check key exchange argument. - scoped_ptr<base::ListValue> key_exchange_values(new base::ListValue()); + std::unique_ptr<base::ListValue> key_exchange_values(new base::ListValue()); GetKeyExchangesList(ssl_options_.key_exchanges, key_exchange_values.get()); if (key_exchange_values->GetSize()) arguments->Set("ssl-key-exchange", key_exchange_values.release()); // Check bulk cipher argument. - scoped_ptr<base::ListValue> bulk_cipher_values(new base::ListValue()); + std::unique_ptr<base::ListValue> bulk_cipher_values(new base::ListValue()); GetCiphersList(ssl_options_.bulk_ciphers, bulk_cipher_values.get()); if (bulk_cipher_values->GetSize()) arguments->Set("ssl-bulk-cipher", bulk_cipher_values.release()); @@ -558,7 +560,7 @@ base::Value::CreateNullValue()); } if (!ssl_options_.npn_protocols.empty()) { - scoped_ptr<base::ListValue> npn_protocols(new base::ListValue()); + std::unique_ptr<base::ListValue> npn_protocols(new base::ListValue()); for (const std::string& proto : ssl_options_.npn_protocols) { npn_protocols->Append(new base::StringValue(proto)); } @@ -574,7 +576,8 @@ base::Value::CreateNullValue()); } if (!ssl_options_.supported_token_binding_params.empty()) { - scoped_ptr<base::ListValue> token_binding_params(new base::ListValue()); + std::unique_ptr<base::ListValue> token_binding_params( + new base::ListValue()); arguments->Set( "token-binding-params", GetTokenBindingParams(ssl_options_.supported_token_binding_params));
diff --git a/net/test/spawned_test_server/base_test_server.h b/net/test/spawned_test_server/base_test_server.h index 60d37e1..4856801 100644 --- a/net/test/spawned_test_server/base_test_server.h +++ b/net/test/spawned_test_server/base_test_server.h
@@ -7,6 +7,7 @@ #include <stdint.h> +#include <memory> #include <string> #include <utility> #include <vector> @@ -15,7 +16,6 @@ #include "base/files/file_path.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "net/base/host_port_pair.h" #include "net/ssl/ssl_client_cert_type.h" @@ -343,7 +343,7 @@ HostPortPair host_port_pair_; // Holds the data sent from the server (e.g., port number). - scoped_ptr<base::DictionaryValue> server_data_; + std::unique_ptr<base::DictionaryValue> server_data_; // If |type_| is TYPE_HTTPS or TYPE_WSS, the TLS settings to use for the test // server. @@ -363,7 +363,7 @@ // Disable creation of anonymous FTP user? bool no_anonymous_ftp_user_; - scoped_ptr<ScopedPortException> allowed_port_; + std::unique_ptr<ScopedPortException> allowed_port_; DISALLOW_COPY_AND_ASSIGN(BaseTestServer); };
diff --git a/net/test/spawned_test_server/remote_test_server.h b/net/test/spawned_test_server/remote_test_server.h index 0de5c7f63..788f68d 100644 --- a/net/test/spawned_test_server/remote_test_server.h +++ b/net/test/spawned_test_server/remote_test_server.h
@@ -61,7 +61,7 @@ // Helper to start and stop instances of the Python test server that runs on // the host machine. - scoped_ptr<SpawnerCommunicator> spawner_communicator_; + std::unique_ptr<SpawnerCommunicator> spawner_communicator_; DISALLOW_COPY_AND_ASSIGN(RemoteTestServer); };
diff --git a/net/test/spawned_test_server/spawner_communicator.cc b/net/test/spawned_test_server/spawner_communicator.cc index 8851f9f8..be23202 100644 --- a/net/test/spawned_test_server/spawner_communicator.cc +++ b/net/test/spawned_test_server/spawner_communicator.cc
@@ -190,7 +190,7 @@ cur_request_->set_method("GET"); } else { cur_request_->set_method("POST"); - scoped_ptr<UploadElementReader> reader( + std::unique_ptr<UploadElementReader> reader( UploadOwnedBytesElementReader::CreateWithString(post_data)); cur_request_->set_upload( ElementsUploadDataStream::CreateWithReader(std::move(reader), 0)); @@ -340,7 +340,8 @@ return false; // Check whether the data returned from spawner server is JSON-formatted. - scoped_ptr<base::Value> value = base::JSONReader::Read(server_return_data); + std::unique_ptr<base::Value> value = + base::JSONReader::Read(server_return_data); if (!value.get() || !value->IsType(base::Value::TYPE_DICTIONARY)) { LOG(ERROR) << "Invalid server data: " << server_return_data.c_str(); return false;
diff --git a/net/test/spawned_test_server/spawner_communicator.h b/net/test/spawned_test_server/spawner_communicator.h index c066016..44527825 100644 --- a/net/test/spawned_test_server/spawner_communicator.h +++ b/net/test/spawned_test_server/spawner_communicator.h
@@ -7,10 +7,10 @@ #include <stdint.h> +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" @@ -127,16 +127,16 @@ const uint16_t port_; // Helper to add |port_| to the list of the globally explicitly allowed ports. - scoped_ptr<ScopedPortException> allowed_port_; + std::unique_ptr<ScopedPortException> allowed_port_; // The next ID to use for |cur_request_| (monotonically increasing). int next_id_; // Request context used by |cur_request_|. - scoped_ptr<URLRequestContext> context_; + std::unique_ptr<URLRequestContext> context_; // The current (in progress) request, or NULL. - scoped_ptr<URLRequest> cur_request_; + std::unique_ptr<URLRequest> cur_request_; // Only gets/sets |is_running_| on user's thread to avoid race-condition. bool is_running_;
diff --git a/net/test/url_request/ssl_certificate_error_job.cc b/net/test/url_request/ssl_certificate_error_job.cc index 83e7fd0c..2d6fd75 100644 --- a/net/test/url_request/ssl_certificate_error_job.cc +++ b/net/test/url_request/ssl_certificate_error_job.cc
@@ -55,7 +55,7 @@ URLRequestFilter* filter = URLRequestFilter::GetInstance(); filter->AddHostnameInterceptor( "https", kMockHostname, - scoped_ptr<URLRequestInterceptor>(new MockJobInterceptor())); + std::unique_ptr<URLRequestInterceptor>(new MockJobInterceptor())); } GURL SSLCertificateErrorJob::GetMockUrl() {
diff --git a/net/test/url_request/url_request_failed_job.cc b/net/test/url_request/url_request_failed_job.cc index 890a061..3457dc8 100644 --- a/net/test/url_request/url_request_failed_job.cc +++ b/net/test/url_request/url_request_failed_job.cc
@@ -136,10 +136,10 @@ // Add |hostname| to URLRequestFilter for HTTP and HTTPS. filter->AddHostnameInterceptor( "http", hostname, - scoped_ptr<URLRequestInterceptor>(new MockJobInterceptor())); + std::unique_ptr<URLRequestInterceptor>(new MockJobInterceptor())); filter->AddHostnameInterceptor( "https", hostname, - scoped_ptr<URLRequestInterceptor>(new MockJobInterceptor())); + std::unique_ptr<URLRequestInterceptor>(new MockJobInterceptor())); } // static
diff --git a/net/test/url_request/url_request_mock_data_job.cc b/net/test/url_request/url_request_mock_data_job.cc index 8c67dc5..e69c473 100644 --- a/net/test/url_request/url_request_mock_data_job.cc +++ b/net/test/url_request/url_request_mock_data_job.cc
@@ -7,6 +7,7 @@ #include "base/bind.h" #include "base/location.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" @@ -182,9 +183,9 @@ // Add |hostname| to URLRequestFilter for HTTP and HTTPS. URLRequestFilter* filter = URLRequestFilter::GetInstance(); filter->AddHostnameInterceptor("http", hostname, - make_scoped_ptr(new MockJobInterceptor())); + base::WrapUnique(new MockJobInterceptor())); filter->AddHostnameInterceptor("https", hostname, - make_scoped_ptr(new MockJobInterceptor())); + base::WrapUnique(new MockJobInterceptor())); } // static
diff --git a/net/test/url_request/url_request_mock_http_job.cc b/net/test/url_request/url_request_mock_http_job.cc index cf2cc6c..bd893062 100644 --- a/net/test/url_request/url_request_mock_http_job.cc +++ b/net/test/url_request/url_request_mock_http_job.cc
@@ -120,19 +120,19 @@ } // static -scoped_ptr<URLRequestInterceptor> URLRequestMockHTTPJob::CreateInterceptor( +std::unique_ptr<URLRequestInterceptor> URLRequestMockHTTPJob::CreateInterceptor( const base::FilePath& base_path, const scoped_refptr<base::SequencedWorkerPool>& worker_pool) { - return scoped_ptr<URLRequestInterceptor>( + return std::unique_ptr<URLRequestInterceptor>( new MockJobInterceptor(base_path, false, worker_pool)); } // static -scoped_ptr<URLRequestInterceptor> +std::unique_ptr<URLRequestInterceptor> URLRequestMockHTTPJob::CreateInterceptorForSingleFile( const base::FilePath& file, const scoped_refptr<base::SequencedWorkerPool>& worker_pool) { - return scoped_ptr<URLRequestInterceptor>( + return std::unique_ptr<URLRequestInterceptor>( new MockJobInterceptor(file, true, worker_pool)); }
diff --git a/net/test/url_request/url_request_mock_http_job.h b/net/test/url_request/url_request_mock_http_job.h index 7a931fec..41a1255 100644 --- a/net/test/url_request/url_request_mock_http_job.h +++ b/net/test/url_request/url_request_mock_http_job.h
@@ -7,11 +7,11 @@ #ifndef NET_TEST_URL_REQUEST_URL_REQUEST_MOCK_HTTP_JOB_H_ #define NET_TEST_URL_REQUEST_URL_REQUEST_MOCK_HTTP_JOB_H_ +#include <memory> #include <string> #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "net/url_request/url_request_file_job.h" #include "url/gurl.h" @@ -55,14 +55,14 @@ // URLRequestMockHTTPJob's responding like an HTTP server. |base_path| is the // file path leading to the root of the directory to use as the root of the // HTTP server. - static scoped_ptr<URLRequestInterceptor> CreateInterceptor( + static std::unique_ptr<URLRequestInterceptor> CreateInterceptor( const base::FilePath& base_path, const scoped_refptr<base::SequencedWorkerPool>& worker_pool); // Returns a URLRequestJobFactory::ProtocolHandler that serves // URLRequestMockHTTPJob's responding like an HTTP server. It responds to all // requests with the contents of |file|. - static scoped_ptr<URLRequestInterceptor> CreateInterceptorForSingleFile( + static std::unique_ptr<URLRequestInterceptor> CreateInterceptorForSingleFile( const base::FilePath& file, const scoped_refptr<base::SequencedWorkerPool>& worker_pool);
diff --git a/net/test/url_request/url_request_slow_download_job.cc b/net/test/url_request/url_request_slow_download_job.cc index ac4beb0..890f805 100644 --- a/net/test/url_request/url_request_slow_download_job.cc +++ b/net/test/url_request/url_request_slow_download_job.cc
@@ -72,16 +72,16 @@ URLRequestFilter* filter = URLRequestFilter::GetInstance(); filter->AddUrlInterceptor( GURL(kUnknownSizeUrl), - scoped_ptr<URLRequestInterceptor>(new Interceptor())); + std::unique_ptr<URLRequestInterceptor>(new Interceptor())); filter->AddUrlInterceptor( GURL(kKnownSizeUrl), - scoped_ptr<URLRequestInterceptor>(new Interceptor())); + std::unique_ptr<URLRequestInterceptor>(new Interceptor())); filter->AddUrlInterceptor( GURL(kFinishDownloadUrl), - scoped_ptr<URLRequestInterceptor>(new Interceptor())); + std::unique_ptr<URLRequestInterceptor>(new Interceptor())); filter->AddUrlInterceptor( GURL(kErrorDownloadUrl), - scoped_ptr<URLRequestInterceptor>(new Interceptor())); + std::unique_ptr<URLRequestInterceptor>(new Interceptor())); } // static
diff --git a/net/tools/balsa/balsa_frame_test.cc b/net/tools/balsa/balsa_frame_test.cc index 4a00a660..fb41415 100644 --- a/net/tools/balsa/balsa_frame_test.cc +++ b/net/tools/balsa/balsa_frame_test.cc
@@ -5,8 +5,8 @@ #include "net/tools/balsa/balsa_frame.h" #include <iterator> +#include <memory> -#include "base/memory/scoped_ptr.h" #include "base/strings/string_piece.h" #include "net/tools/balsa/balsa_enums.h" #include "net/tools/balsa/balsa_headers.h" @@ -66,9 +66,9 @@ }; protected: - scoped_ptr<BalsaFrame> frame_; - scoped_ptr<BalsaHeaders> frame_headers_; - scoped_ptr<Visitor> visitor_; + std::unique_ptr<BalsaFrame> frame_; + std::unique_ptr<BalsaHeaders> frame_headers_; + std::unique_ptr<Visitor> visitor_; }; TEST_F(BalsaFrameTest, EmptyFrame) {
diff --git a/net/tools/balsa/balsa_headers_test.cc b/net/tools/balsa/balsa_headers_test.cc index 3dc8eb3..98b9cc2 100644 --- a/net/tools/balsa/balsa_headers_test.cc +++ b/net/tools/balsa/balsa_headers_test.cc
@@ -5,10 +5,10 @@ #include "net/tools/balsa/balsa_headers.h" #include <iterator> +#include <memory> #include <string> #include <vector> -#include "base/memory/scoped_ptr.h" #include "base/strings/string_piece.h" #include "net/tools/balsa/balsa_enums.h" #include "testing/gtest/include/gtest/gtest.h" @@ -25,8 +25,8 @@ } protected: - scoped_ptr<BalsaBuffer> buffer_; - scoped_ptr<BalsaBuffer> anotherBuffer_; + std::unique_ptr<BalsaBuffer> buffer_; + std::unique_ptr<BalsaBuffer> anotherBuffer_; }; namespace { @@ -36,7 +36,7 @@ void SetUp() override { headers_.reset(new BalsaHeaders); } protected: - scoped_ptr<BalsaHeaders> headers_; + std::unique_ptr<BalsaHeaders> headers_; }; class StringBuffer {
diff --git a/net/tools/cachetool/cachetool.cc b/net/tools/cachetool/cachetool.cc index c186400..50c2d8d 100644 --- a/net/tools/cachetool/cachetool.cc +++ b/net/tools/cachetool/cachetool.cc
@@ -3,12 +3,12 @@ // found in the LICENSE file. #include <iostream> +#include <memory> #include "base/at_exit.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/strings/string_number_conversions.h" #include "net/base/io_buffer.h" @@ -25,7 +25,7 @@ // Print all of a cache's keys to stdout. bool ListKeys(Backend* cache_backend) { - scoped_ptr<Backend::Iterator> entry_iterator = + std::unique_ptr<Backend::Iterator> entry_iterator = cache_backend->CreateIterator(); Entry* entry = nullptr; net::TestCompletionCallback cb; @@ -152,7 +152,7 @@ return 1; } - scoped_ptr<Backend> cache_backend; + std::unique_ptr<Backend> cache_backend; net::TestCompletionCallback cb; int rv = disk_cache::CreateCacheBackend( net::DISK_CACHE, backend_type, cache_path, INT_MAX, false,
diff --git a/net/tools/content_decoder_tool/content_decoder_tool.cc b/net/tools/content_decoder_tool/content_decoder_tool.cc index 0eae2553..7b295e0 100644 --- a/net/tools/content_decoder_tool/content_decoder_tool.cc +++ b/net/tools/content_decoder_tool/content_decoder_tool.cc
@@ -50,7 +50,7 @@ } net::MockFilterContext filter_context; - scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); + std::unique_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); if (!filter) { std::cerr << "Couldn't create the decoder." << std::endl; return 1;
diff --git a/net/tools/disk_cache_memory_test/disk_cache_memory_test.cc b/net/tools/disk_cache_memory_test/disk_cache_memory_test.cc index bcf5412..be9a70d 100644 --- a/net/tools/disk_cache_memory_test/disk_cache_memory_test.cc +++ b/net/tools/disk_cache_memory_test/disk_cache_memory_test.cc
@@ -5,6 +5,7 @@ #include <cstdlib> #include <fstream> #include <iostream> +#include <memory> #include <string> #include <vector> @@ -14,7 +15,6 @@ #include "base/command_line.h" #include "base/files/file_path.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" @@ -44,16 +44,16 @@ struct CacheSpec { public: - static scoped_ptr<CacheSpec> Parse(const std::string& spec_string) { + static std::unique_ptr<CacheSpec> Parse(const std::string& spec_string) { std::vector<std::string> tokens = base::SplitString( spec_string, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); if (tokens.size() != 3) - return scoped_ptr<CacheSpec>(); + return std::unique_ptr<CacheSpec>(); if (tokens[0] != kBlockFileBackendType && tokens[0] != kSimpleBackendType) - return scoped_ptr<CacheSpec>(); + return std::unique_ptr<CacheSpec>(); if (tokens[1] != kDiskCacheType && tokens[1] != kAppCacheType) - return scoped_ptr<CacheSpec>(); - return scoped_ptr<CacheSpec>(new CacheSpec( + return std::unique_ptr<CacheSpec>(); + return std::unique_ptr<CacheSpec>(new CacheSpec( tokens[0] == kBlockFileBackendType ? net::CACHE_BACKEND_BLOCKFILE : net::CACHE_BACKEND_SIMPLE, tokens[1] == kDiskCacheType ? net::DISK_CACHE : net::APP_CACHE, @@ -85,9 +85,9 @@ run_loop->Quit(); } -scoped_ptr<Backend> CreateAndInitBackend(const CacheSpec& spec) { - scoped_ptr<Backend> result; - scoped_ptr<Backend> backend; +std::unique_ptr<Backend> CreateAndInitBackend(const CacheSpec& spec) { + std::unique_ptr<Backend> result; + std::unique_ptr<Backend> backend; bool succeeded = false; base::RunLoop run_loop; const net::CompletionCallback callback = base::Bind( @@ -223,10 +223,10 @@ return total_size; } -bool CacheMemTest(const std::vector<scoped_ptr<CacheSpec>>& specs) { - std::vector<scoped_ptr<Backend>> backends; +bool CacheMemTest(const std::vector<std::unique_ptr<CacheSpec>>& specs) { + std::vector<std::unique_ptr<Backend>> backends; for (const auto& it : specs) { - scoped_ptr<Backend> backend = CreateAndInitBackend(*it); + std::unique_ptr<Backend> backend = CreateAndInitBackend(*it); if (!backend) return false; std::cout << "Number of entries in " << it->path.LossyDisplayName() << " : " @@ -252,8 +252,8 @@ } bool ParseAndStoreSpec(const std::string& spec_str, - std::vector<scoped_ptr<CacheSpec>>* specs) { - scoped_ptr<CacheSpec> spec = CacheSpec::Parse(spec_str); + std::vector<std::unique_ptr<CacheSpec>>* specs) { + std::unique_ptr<CacheSpec> spec = CacheSpec::Parse(spec_str); if (!spec) { PrintUsage(&std::cerr); return false; @@ -280,7 +280,7 @@ PrintUsage(&std::cerr); return false; } - std::vector<scoped_ptr<CacheSpec>> specs; + std::vector<std::unique_ptr<CacheSpec>> specs; const std::string spec_str_1 = command_line.GetSwitchValueASCII("spec-1"); if (!ParseAndStoreSpec(spec_str_1, &specs)) return false;
diff --git a/net/tools/dns_fuzz_stub/dns_fuzz_stub.cc b/net/tools/dns_fuzz_stub/dns_fuzz_stub.cc index 2a2c88e..ed2a7579 100644 --- a/net/tools/dns_fuzz_stub/dns_fuzz_stub.cc +++ b/net/tools/dns_fuzz_stub/dns_fuzz_stub.cc
@@ -6,6 +6,7 @@ #include <algorithm> #include <limits> +#include <memory> #include <sstream> #include <string> #include <vector> @@ -13,7 +14,6 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" -#include "base/memory/scoped_ptr.h" #include "base/time/time.h" #include "base/values.h" #include "net/base/address_list.h" @@ -62,7 +62,7 @@ return false; } - scoped_ptr<base::Value> value = base::JSONReader::Read(json); + std::unique_ptr<base::Value> value = base::JSONReader::Read(json); if (!value.get()) { LOG(ERROR) << filename << ": couldn't parse JSON."; return false;
diff --git a/net/tools/epoll_server/epoll_server.h b/net/tools/epoll_server/epoll_server.h index 460db3d..3953b8b 100644 --- a/net/tools/epoll_server/epoll_server.h +++ b/net/tools/epoll_server/epoll_server.h
@@ -11,6 +11,7 @@ #include <sys/queue.h> #include <map> +#include <memory> #include <string> #include <vector> @@ -36,7 +37,6 @@ #include "base/compiler_specific.h" #include "base/containers/hash_tables.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include <sys/epoll.h> namespace net { @@ -940,7 +940,7 @@ // The callback registered to the fds below. As the purpose of their // registration is to wake the epoll server it just clears the pipe and // returns. - scoped_ptr<ReadPipeCallback> wake_cb_; + std::unique_ptr<ReadPipeCallback> wake_cb_; // A pipe owned by the epoll server. The server will be registered to listen // on read_fd_ and can be woken by Wake() which writes to write_fd_.
diff --git a/net/tools/flip_server/http_interface.h b/net/tools/flip_server/http_interface.h index 73618bc7..8bd72aa 100644 --- a/net/tools/flip_server/http_interface.h +++ b/net/tools/flip_server/http_interface.h
@@ -125,7 +125,7 @@ void GetOutput() override; private: - scoped_ptr<BalsaFrame> http_framer_; + std::unique_ptr<BalsaFrame> http_framer_; BalsaHeaders headers_; uint32_t stream_id_; int32_t server_idx_;
diff --git a/net/tools/flip_server/http_interface_test.cc b/net/tools/flip_server/http_interface_test.cc index 34b2390..9123f9f 100644 --- a/net/tools/flip_server/http_interface_test.cc +++ b/net/tools/flip_server/http_interface_test.cc
@@ -5,8 +5,8 @@ #include "net/tools/flip_server/http_interface.h" #include <list> +#include <memory> -#include "base/memory/scoped_ptr.h" #include "base/stl_util.h" #include "base/strings/string_piece.h" #include "net/tools/balsa/balsa_enums.h" @@ -100,12 +100,12 @@ } protected: - scoped_ptr<MockSMInterface> mock_another_interface_; - scoped_ptr<MemoryCache> memory_cache_; - scoped_ptr<FlipAcceptor> acceptor_; - scoped_ptr<EpollServer> epoll_server_; - scoped_ptr<MockSMConnection> connection_; - scoped_ptr<HttpSM> interface_; + std::unique_ptr<MockSMInterface> mock_another_interface_; + std::unique_ptr<MemoryCache> memory_cache_; + std::unique_ptr<FlipAcceptor> acceptor_; + std::unique_ptr<EpollServer> epoll_server_; + std::unique_ptr<MockSMConnection> connection_; + std::unique_ptr<HttpSM> interface_; }; class FlipHttpSMProxyTest : public FlipHttpSMTest { @@ -147,7 +147,7 @@ } TEST_F(FlipHttpSMTest, InitSMInterface) { - scoped_ptr<MockSMInterface> mock(new MockSMInterface); + std::unique_ptr<MockSMInterface> mock(new MockSMInterface); { InSequence s; EXPECT_CALL(*mock_another_interface_, SendEOF(_));
diff --git a/net/tools/flip_server/mem_cache.cc b/net/tools/flip_server/mem_cache.cc index 15c4f79..dae5d40 100644 --- a/net/tools/flip_server/mem_cache.cc +++ b/net/tools/flip_server/mem_cache.cc
@@ -16,6 +16,7 @@ #include <map> #include <string> +#include "base/memory/ptr_util.h" #include "base/strings/string_util.h" #include "net/tools/balsa/balsa_frame.h" #include "net/tools/balsa/balsa_headers.h" @@ -230,7 +231,7 @@ it->second.reset(file_data); } else { files_.insert( - std::make_pair(file_data->filename(), make_scoped_ptr(file_data))); + std::make_pair(file_data->filename(), base::WrapUnique(file_data))); } }
diff --git a/net/tools/flip_server/mem_cache.h b/net/tools/flip_server/mem_cache.h index 6b85149..f073cb6 100644 --- a/net/tools/flip_server/mem_cache.h +++ b/net/tools/flip_server/mem_cache.h
@@ -9,11 +9,11 @@ #include <stdint.h> #include <map> +#include <memory> #include <string> #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/tools/balsa/balsa_headers.h" #include "net/tools/balsa/balsa_visitor_interface.h" #include "net/tools/flip_server/constants.h" @@ -78,7 +78,7 @@ const std::string& body() { return body_; } private: - scoped_ptr<BalsaHeaders> headers_; + std::unique_ptr<BalsaHeaders> headers_; std::string filename_; std::string body_; @@ -114,7 +114,7 @@ class MemoryCache { public: - using Files = std::map<std::string, scoped_ptr<FileData>>; + using Files = std::map<std::string, std::unique_ptr<FileData>>; public: MemoryCache();
diff --git a/net/tools/flip_server/mem_cache_test.cc b/net/tools/flip_server/mem_cache_test.cc index 87dca685..0ddb74b 100644 --- a/net/tools/flip_server/mem_cache_test.cc +++ b/net/tools/flip_server/mem_cache_test.cc
@@ -27,7 +27,7 @@ FlipMemoryCacheTest() : mem_cache_(new MemoryCacheWithFakeReadToString) {} protected: - scoped_ptr<MemoryCacheWithFakeReadToString> mem_cache_; + std::unique_ptr<MemoryCacheWithFakeReadToString> mem_cache_; }; TEST_F(FlipMemoryCacheTest, EmptyCache) {
diff --git a/net/tools/flip_server/ring_buffer.h b/net/tools/flip_server/ring_buffer.h index 9b0edfc..538595c 100644 --- a/net/tools/flip_server/ring_buffer.h +++ b/net/tools/flip_server/ring_buffer.h
@@ -5,8 +5,9 @@ #ifndef NET_TOOLS_FLIP_SERVER_RING_BUFFER_H__ #define NET_TOOLS_FLIP_SERVER_RING_BUFFER_H__ +#include <memory> + #include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" #include "net/tools/balsa/buffer_interface.h" namespace net { @@ -97,7 +98,7 @@ int set_write_idx(int idx) { return write_idx_ = idx; } private: - scoped_ptr<char[]> buffer_; + std::unique_ptr<char[]> buffer_; int buffer_size_; int bytes_used_; int read_idx_;
diff --git a/net/tools/flip_server/spdy_interface.h b/net/tools/flip_server/spdy_interface.h index 3d1cfa0a6..3ce8a40 100644 --- a/net/tools/flip_server/spdy_interface.h +++ b/net/tools/flip_server/spdy_interface.h
@@ -9,11 +9,11 @@ #include <stdint.h> #include <map> +#include <memory> #include <string> #include <vector> #include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" #include "net/spdy/buffered_spdy_framer.h" #include "net/spdy/spdy_protocol.h" #include "net/tools/balsa/balsa_headers.h" @@ -218,7 +218,7 @@ void GetOutput() override; private: - scoped_ptr<BufferedSpdyFramer> buffered_spdy_framer_; + std::unique_ptr<BufferedSpdyFramer> buffered_spdy_framer_; bool valid_spdy_session_; // True if we have seen valid data on this session. // Use this to fail fast when junk is sent to our // port.
diff --git a/net/tools/flip_server/spdy_interface_test.cc b/net/tools/flip_server/spdy_interface_test.cc index dc172fc..e5e7dd93 100644 --- a/net/tools/flip_server/spdy_interface_test.cc +++ b/net/tools/flip_server/spdy_interface_test.cc
@@ -5,8 +5,8 @@ #include "net/tools/flip_server/spdy_interface.h" #include <list> +#include <memory> -#include "base/memory/scoped_ptr.h" #include "base/strings/string_piece.h" #include "net/spdy/buffered_spdy_framer.h" #include "net/tools/balsa/balsa_enums.h" @@ -194,14 +194,14 @@ } protected: - scoped_ptr<MockSMInterface> mock_another_interface_; - scoped_ptr<MemoryCache> memory_cache_; - scoped_ptr<FlipAcceptor> acceptor_; - scoped_ptr<EpollServer> epoll_server_; - scoped_ptr<FakeSMConnection> connection_; - scoped_ptr<TestSpdySM> interface_; - scoped_ptr<BufferedSpdyFramer> spdy_framer_; - scoped_ptr<SpdyFramerVisitor> spdy_framer_visitor_; + std::unique_ptr<MockSMInterface> mock_another_interface_; + std::unique_ptr<MemoryCache> memory_cache_; + std::unique_ptr<FlipAcceptor> acceptor_; + std::unique_ptr<EpollServer> epoll_server_; + std::unique_ptr<FakeSMConnection> connection_; + std::unique_ptr<TestSpdySM> interface_; + std::unique_ptr<BufferedSpdyFramer> spdy_framer_; + std::unique_ptr<SpdyFramerVisitor> spdy_framer_visitor_; }; class SpdySMProxyTest : public SpdySMTestBase { @@ -230,13 +230,13 @@ TEST_P(SpdySMProxyTest, OnStreamFrameData) { BufferedSpdyFramerVisitorInterface* visitor = interface_.get(); - scoped_ptr<MockSMInterface> mock_interface(new MockSMInterface); + std::unique_ptr<MockSMInterface> mock_interface(new MockSMInterface); uint32_t stream_id = 92; uint32_t associated_id = 43; SpdyHeaderBlock block; testing::MockFunction<void(int)> checkpoint; // NOLINT - scoped_ptr<SpdySerializedFrame> frame( + std::unique_ptr<SpdySerializedFrame> frame( spdy_framer_->CreatePingFrame(12, false)); block[":method"] = "GET"; block[":host"] = "www.example.com";
diff --git a/net/tools/gdig/file_net_log.cc b/net/tools/gdig/file_net_log.cc index 5020f6de..1281f8a 100644 --- a/net/tools/gdig/file_net_log.cc +++ b/net/tools/gdig/file_net_log.cc
@@ -2,13 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "net/tools/gdig/file_net_log.h" + #include <stdio.h> +#include <memory> + #include "base/json/json_string_value_serializer.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/values.h" -#include "net/tools/gdig/file_net_log.h" namespace net { @@ -27,7 +29,7 @@ const char* source = NetLog::SourceTypeToString(entry.source().type); const char* type = NetLog::EventTypeToString(entry.type()); - scoped_ptr<base::Value> param_value(entry.ParametersToValue()); + std::unique_ptr<base::Value> param_value(entry.ParametersToValue()); std::string params; if (param_value.get() != NULL) { JSONStringValueSerializer serializer(¶ms);
diff --git a/net/tools/gdig/gdig.cc b/net/tools/gdig/gdig.cc index 7d9410d..c3df21f 100644 --- a/net/tools/gdig/gdig.cc +++ b/net/tools/gdig/gdig.cc
@@ -3,6 +3,8 @@ // found in the LICENSE file. #include <stdio.h> + +#include <memory> #include <string> #include <utility> @@ -12,7 +14,6 @@ #include "base/command_line.h" #include "base/files/file_util.h" #include "base/location.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" @@ -225,10 +226,10 @@ Result result_; base::CancelableClosure timeout_closure_; - scoped_ptr<DnsConfigService> dns_config_service_; - scoped_ptr<FileNetLogObserver> log_observer_; - scoped_ptr<NetLog> log_; - scoped_ptr<HostResolver> resolver_; + std::unique_ptr<DnsConfigService> dns_config_service_; + std::unique_ptr<FileNetLogObserver> log_observer_; + std::unique_ptr<NetLog> log_; + std::unique_ptr<HostResolver> resolver_; #if defined(OS_MACOSX) // Without this there will be a mem leak on osx. @@ -426,12 +427,12 @@ return; } - scoped_ptr<DnsClient> dns_client(DnsClient::CreateClient(NULL)); + std::unique_ptr<DnsClient> dns_client(DnsClient::CreateClient(NULL)); dns_client->SetConfig(dns_config); HostResolver::Options options; options.max_concurrent_resolves = parallellism_; options.max_retry_attempts = 1u; - scoped_ptr<HostResolverImpl> resolver( + std::unique_ptr<HostResolverImpl> resolver( new HostResolverImpl(options, log_.get())); resolver->SetDnsClient(std::move(dns_client)); resolver_ = std::move(resolver);
diff --git a/net/tools/get_server_time/get_server_time.cc b/net/tools/get_server_time/get_server_time.cc index 65279d57..6bb3471 100644 --- a/net/tools/get_server_time/get_server_time.cc +++ b/net/tools/get_server_time/get_server_time.cc
@@ -11,6 +11,7 @@ #include <cstdio> #include <cstdlib> +#include <memory> #include <string> #include "base/at_exit.h" @@ -21,8 +22,8 @@ #include "base/json/json_writer.h" #include "base/logging.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" @@ -119,7 +120,7 @@ net::NetLog::EventTypeToString(entry.type()); const char* const event_phase = net::NetLog::EventPhaseToString(entry.phase()); - scoped_ptr<base::Value> params(entry.ParametersToValue()); + std::unique_ptr<base::Value> params(entry.ParametersToValue()); std::string params_str; if (params.get()) { base::JSONWriter::Write(*params, ¶ms_str); @@ -135,8 +136,8 @@ }; // Builds a URLRequestContext assuming there's only a single loop. -scoped_ptr<net::URLRequestContext> -BuildURLRequestContext(net::NetLog* net_log) { +std::unique_ptr<net::URLRequestContext> BuildURLRequestContext( + net::NetLog* net_log) { net::URLRequestContextBuilder builder; #if defined(OS_LINUX) // On Linux, use a fixed ProxyConfigService, since the default one @@ -144,9 +145,9 @@ // // TODO(akalin): Remove this once http://crbug.com/146421 is fixed. builder.set_proxy_config_service( - make_scoped_ptr(new net::ProxyConfigServiceFixed(net::ProxyConfig()))); + base::WrapUnique(new net::ProxyConfigServiceFixed(net::ProxyConfig()))); #endif - scoped_ptr<net::URLRequestContext> context(builder.Build()); + std::unique_ptr<net::URLRequestContext> context(builder.Build()); context->set_net_log(net_log); return context; } @@ -230,9 +231,9 @@ net::NetLogCaptureMode::IncludeSocketBytes()); QuitDelegate delegate; - scoped_ptr<net::URLFetcher> fetcher = + std::unique_ptr<net::URLFetcher> fetcher = net::URLFetcher::Create(url, net::URLFetcher::HEAD, &delegate); - scoped_ptr<net::URLRequestContext> url_request_context( + std::unique_ptr<net::URLRequestContext> url_request_context( BuildURLRequestContext(&net_log)); fetcher->SetRequestContext( // Since there's only a single thread, there's no need to worry
diff --git a/net/tools/net_watcher/net_watcher.cc b/net/tools/net_watcher/net_watcher.cc index 9f07513c..a4a289b9 100644 --- a/net/tools/net_watcher/net_watcher.cc +++ b/net/tools/net_watcher/net_watcher.cc
@@ -4,6 +4,7 @@ // This is a small utility that watches for and logs network changes. +#include <memory> #include <string> #include "base/at_exit.h" @@ -12,7 +13,6 @@ #include "base/json/json_writer.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/strings/string_split.h" #include "base/values.h" @@ -69,7 +69,7 @@ } std::string ProxyConfigToString(const net::ProxyConfig& config) { - scoped_ptr<base::Value> config_value(config.ToValue()); + std::unique_ptr<base::Value> config_value(config.ToValue()); std::string str; base::JSONWriter::Write(*config_value, &str); return str; @@ -177,15 +177,15 @@ ignored_interfaces.insert(ignored_netif); } } - scoped_ptr<net::NetworkChangeNotifier> network_change_notifier( + std::unique_ptr<net::NetworkChangeNotifier> network_change_notifier( new net::NetworkChangeNotifierLinux(ignored_interfaces)); #else - scoped_ptr<net::NetworkChangeNotifier> network_change_notifier( + std::unique_ptr<net::NetworkChangeNotifier> network_change_notifier( net::NetworkChangeNotifier::Create()); #endif // Use the network loop as the file loop also. - scoped_ptr<net::ProxyConfigService> proxy_config_service( + std::unique_ptr<net::ProxyConfigService> proxy_config_service( net::ProxyService::CreateSystemProxyConfigService( network_loop.task_runner(), network_loop.task_runner()));
diff --git a/net/tools/quic/end_to_end_test.cc b/net/tools/quic/end_to_end_test.cc index 68cb1a39..55e1bf4 100644 --- a/net/tools/quic/end_to_end_test.cc +++ b/net/tools/quic/end_to_end_test.cc
@@ -6,10 +6,10 @@ #include <sys/epoll.h> #include <list> +#include <memory> #include <string> #include <vector> -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/strings/string_number_conversions.h" #include "base/synchronization/waitable_event.h" @@ -507,8 +507,8 @@ bool initialized_; IPEndPoint server_address_; string server_hostname_; - scoped_ptr<ServerThread> server_thread_; - scoped_ptr<QuicTestClient> client_; + std::unique_ptr<ServerThread> server_thread_; + std::unique_ptr<QuicTestClient> client_; PacketDroppingTestWriter* client_writer_; PacketDroppingTestWriter* server_writer_; bool server_started_; @@ -588,7 +588,7 @@ TEST_P(EndToEndTest, MultipleClients) { ASSERT_TRUE(Initialize()); - scoped_ptr<QuicTestClient> client2(CreateQuicClient(nullptr)); + std::unique_ptr<QuicTestClient> client2(CreateQuicClient(nullptr)); HTTPMessage request(HttpConstants::HTTP_1_1, HttpConstants::POST, "/foo"); request.AddHeader("content-length", "3"); @@ -1738,7 +1738,8 @@ header.rejected_packet_number = 10101; QuicFramer framer(server_supported_versions_, QuicTime::Zero(), Perspective::IS_SERVER); - scoped_ptr<QuicEncryptedPacket> packet(framer.BuildPublicResetPacket(header)); + std::unique_ptr<QuicEncryptedPacket> packet( + framer.BuildPublicResetPacket(header)); testing::NiceMock<MockQuicConnectionDebugVisitor> visitor; client_->client()->session()->connection()->set_debug_visitor(&visitor); EXPECT_CALL(visitor, OnIncorrectConnectionId(incorrect_connection_id)) @@ -1773,7 +1774,8 @@ header.rejected_packet_number = 10101; QuicFramer framer(server_supported_versions_, QuicTime::Zero(), Perspective::IS_CLIENT); - scoped_ptr<QuicEncryptedPacket> packet(framer.BuildPublicResetPacket(header)); + std::unique_ptr<QuicEncryptedPacket> packet( + framer.BuildPublicResetPacket(header)); client_writer_->WritePacket( packet->data(), packet->length(), client_->client()->GetLatestClientAddress().address(), server_address_, @@ -1792,7 +1794,7 @@ // Send the version negotiation packet. QuicConnectionId incorrect_connection_id = client_->client()->session()->connection()->connection_id() + 1; - scoped_ptr<QuicEncryptedPacket> packet( + std::unique_ptr<QuicEncryptedPacket> packet( QuicFramer::BuildVersionNegotiationPacket(incorrect_connection_id, server_supported_versions_)); testing::NiceMock<MockQuicConnectionDebugVisitor> visitor; @@ -1895,7 +1897,7 @@ EXPECT_EQ(kFooResponseBody, client_->SendSynchronousRequest("/foo")); EXPECT_EQ(200u, client_->response_headers()->parsed_response_code()); - scoped_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket( + std::unique_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket( client_->client()->session()->connection()->connection_id(), false, false, false, kDefaultPathId, 1, "At least 20 characters.", PACKET_8BYTE_CONNECTION_ID, PACKET_6BYTE_PACKET_NUMBER));
diff --git a/net/tools/quic/quic_client.h b/net/tools/quic/quic_client.h index 56a0246..f738712 100644 --- a/net/tools/quic/quic_client.h +++ b/net/tools/quic/quic_client.h
@@ -10,11 +10,11 @@ #include <stddef.h> +#include <memory> #include <string> #include "base/command_line.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string_piece.h" #include "net/base/ip_address.h" #include "net/base/ip_endpoint.h" @@ -261,7 +261,7 @@ linked_hash_map<int, IPEndPoint> fd_address_map_; // Listens for full responses. - scoped_ptr<ResponseListener> response_listener_; + std::unique_ptr<ResponseListener> response_listener_; // Tracks if the client is initialized to connect. bool initialized_; @@ -297,7 +297,7 @@ // // TODO(rtenneti): Chromium code doesn't use |packet_reader_|. Add support for // QuicPacketReader - scoped_ptr<QuicPacketReader> packet_reader_; + std::unique_ptr<QuicPacketReader> packet_reader_; std::unique_ptr<ClientQuicDataToResend> push_promise_data_to_resend_;
diff --git a/net/tools/quic/quic_client_base.h b/net/tools/quic/quic_client_base.h index af44bda..00c86fc 100644 --- a/net/tools/quic/quic_client_base.h +++ b/net/tools/quic/quic_client_base.h
@@ -8,10 +8,10 @@ #ifndef NET_TOOLS_QUIC_QUIC_CLIENT_BASE_H_ #define NET_TOOLS_QUIC_QUIC_CLIENT_BASE_H_ +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/base/ip_endpoint.h" #include "net/log/net_log.h" #include "net/quic/crypto/crypto_handshake.h" @@ -199,14 +199,14 @@ QuicCryptoClientConfig crypto_config_; // Helper to be used by created connections. Needs to outlive |session_|. - scoped_ptr<QuicConnectionHelperInterface> helper_; + std::unique_ptr<QuicConnectionHelperInterface> helper_; // Writer used to actually send packets to the wire. Needs to outlive // |session_|. - scoped_ptr<QuicPacketWriter> writer_; + std::unique_ptr<QuicPacketWriter> writer_; // Session which manages streams. - scoped_ptr<QuicClientSession> session_; + std::unique_ptr<QuicClientSession> session_; // This vector contains QUIC versions which we currently support. // This should be ordered such that the highest supported version is the first
diff --git a/net/tools/quic/quic_client_bin.cc b/net/tools/quic/quic_client_bin.cc index ead19bae..7a61c0a 100644 --- a/net/tools/quic/quic_client_bin.cc +++ b/net/tools/quic/quic_client_bin.cc
@@ -114,7 +114,7 @@ net::CRLSet* crl_set, net::CertVerifyResult* verify_result, const net::CompletionCallback& callback, - scoped_ptr<net::CertVerifier::Request>* out_req, + std::unique_ptr<net::CertVerifier::Request>* out_req, const net::BoundNetLog& net_log) override { return net::OK; } @@ -275,14 +275,14 @@ versions.push_back(static_cast<net::QuicVersion>(FLAGS_quic_version)); } // For secure QUIC we need to verify the cert chain. - scoped_ptr<CertVerifier> cert_verifier(CertVerifier::CreateDefault()); + std::unique_ptr<CertVerifier> cert_verifier(CertVerifier::CreateDefault()); if (line->HasSwitch("disable-certificate-verification")) { cert_verifier.reset(new FakeCertVerifier()); } - scoped_ptr<TransportSecurityState> transport_security_state( + std::unique_ptr<TransportSecurityState> transport_security_state( new TransportSecurityState); transport_security_state.reset(new TransportSecurityState); - scoped_ptr<CTVerifier> ct_verifier(new MultiLogCTVerifier()); + std::unique_ptr<CTVerifier> ct_verifier(new MultiLogCTVerifier()); ProofVerifierChromium* proof_verifier = new ProofVerifierChromium( cert_verifier.get(), nullptr, transport_security_state.get(), ct_verifier.get());
diff --git a/net/tools/quic/quic_client_session.h b/net/tools/quic/quic_client_session.h index 321c17f..a0cc45c 100644 --- a/net/tools/quic/quic_client_session.h +++ b/net/tools/quic/quic_client_session.h
@@ -81,7 +81,7 @@ QuicCryptoClientConfig* crypto_config() { return crypto_config_; } private: - scoped_ptr<QuicCryptoClientStreamBase> crypto_stream_; + std::unique_ptr<QuicCryptoClientStreamBase> crypto_stream_; QuicServerId server_id_; QuicCryptoClientConfig* crypto_config_;
diff --git a/net/tools/quic/quic_client_session_test.cc b/net/tools/quic/quic_client_session_test.cc index 1619eed..09ace38 100644 --- a/net/tools/quic/quic_client_session_test.cc +++ b/net/tools/quic/quic_client_session_test.cc
@@ -121,7 +121,7 @@ QuicCryptoClientConfig crypto_config_; MockConnectionHelper helper_; PacketSavingConnection* connection_; - scoped_ptr<TestQuicClientSession> session_; + std::unique_ptr<TestQuicClientSession> session_; QuicClientPushPromiseIndex push_promise_index_; SpdyHeaderBlock push_promise_; string promise_url_; @@ -263,9 +263,9 @@ // Verify that a non-decryptable packet doesn't close the connection. QuicConnectionId connection_id = session_->connection()->connection_id(); - scoped_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket( + std::unique_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket( connection_id, false, false, false, kDefaultPathId, 100, "data")); - scoped_ptr<QuicReceivedPacket> received( + std::unique_ptr<QuicReceivedPacket> received( ConstructReceivedPacket(*packet, QuicTime::Zero())); // Change the last byte of the encrypted data. *(const_cast<char*>(received->data() + received->length() - 1)) += 1; @@ -286,10 +286,10 @@ // Verify that a decryptable packet with bad frames does close the connection. QuicConnectionId connection_id = session_->connection()->connection_id(); - scoped_ptr<QuicEncryptedPacket> packet(ConstructMisFramedEncryptedPacket( + std::unique_ptr<QuicEncryptedPacket> packet(ConstructMisFramedEncryptedPacket( connection_id, false, false, false, kDefaultPathId, 100, "data", PACKET_8BYTE_CONNECTION_ID, PACKET_6BYTE_PACKET_NUMBER, nullptr)); - scoped_ptr<QuicReceivedPacket> received( + std::unique_ptr<QuicReceivedPacket> received( ConstructReceivedPacket(*packet, QuicTime::Zero())); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(1); session_->ProcessUdpPacket(client_address, server_address, *received);
diff --git a/net/tools/quic/quic_client_test.cc b/net/tools/quic/quic_client_test.cc index 373a2d8..8a98657 100644 --- a/net/tools/quic/quic_client_test.cc +++ b/net/tools/quic/quic_client_test.cc
@@ -65,7 +65,7 @@ // in additional FDs being opened. const int kNumClients = 50; for (int i = 0; i < kNumClients; ++i) { - scoped_ptr<QuicClient> client( + std::unique_ptr<QuicClient> client( CreateAndInitializeQuicClient(&eps, net::test::kTestPort + i)); // Initializing the client will create a new FD. @@ -84,7 +84,7 @@ EpollServer eps; int number_of_open_fds = NumOpenFDs(); - scoped_ptr<QuicClient> client( + std::unique_ptr<QuicClient> client( CreateAndInitializeQuicClient(&eps, net::test::kTestPort)); EXPECT_EQ(number_of_open_fds + 1, NumOpenFDs()); // Create more UDP sockets.
diff --git a/net/tools/quic/quic_dispatcher.h b/net/tools/quic/quic_dispatcher.h index 763280a8..1c9c7cc 100644 --- a/net/tools/quic/quic_dispatcher.h +++ b/net/tools/quic/quic_dispatcher.h
@@ -8,12 +8,12 @@ #ifndef NET_TOOLS_QUIC_QUIC_DISPATCHER_H_ #define NET_TOOLS_QUIC_QUIC_DISPATCHER_H_ +#include <memory> #include <unordered_map> #include <vector> #include "base/containers/hash_tables.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/base/ip_endpoint.h" #include "net/base/linked_hash_map.h" #include "net/quic/crypto/quic_compressed_certs_cache.h" @@ -235,19 +235,19 @@ SessionMap session_map_; // Entity that manages connection_ids in time wait state. - scoped_ptr<QuicTimeWaitListManager> time_wait_list_manager_; + std::unique_ptr<QuicTimeWaitListManager> time_wait_list_manager_; // The list of closed but not-yet-deleted sessions. std::vector<QuicServerSessionBase*> closed_session_list_; // The helper used for all connections. - scoped_ptr<QuicConnectionHelperInterface> helper_; + std::unique_ptr<QuicConnectionHelperInterface> helper_; // An alarm which deletes closed sessions. - scoped_ptr<QuicAlarm> delete_sessions_alarm_; + std::unique_ptr<QuicAlarm> delete_sessions_alarm_; // The writer to write to the socket with. - scoped_ptr<QuicPacketWriter> writer_; + std::unique_ptr<QuicPacketWriter> writer_; // This vector contains QUIC versions which we currently support. // This should be ordered such that the highest supported version is the first
diff --git a/net/tools/quic/quic_dispatcher_test.cc b/net/tools/quic/quic_dispatcher_test.cc index a8c8ab4..32542c01 100644 --- a/net/tools/quic/quic_dispatcher_test.cc +++ b/net/tools/quic/quic_dispatcher_test.cc
@@ -230,10 +230,10 @@ QuicPacketNumberLength packet_number_length, QuicPacketNumber packet_number) { QuicVersionVector versions(SupportedVersions(version)); - scoped_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket( + std::unique_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket( connection_id, has_version_flag, false, false, 0, packet_number, data, connection_id_length, packet_number_length, &versions)); - scoped_ptr<QuicReceivedPacket> received_packet( + std::unique_ptr<QuicReceivedPacket> received_packet( ConstructReceivedPacket(*packet, helper_.GetClock()->Now())); data_ = string(packet->data(), packet->length()); @@ -358,9 +358,9 @@ packet.public_header.version_flag = false; packet.rejected_packet_number = 19191; packet.nonce_proof = 132232; - scoped_ptr<QuicEncryptedPacket> encrypted( + std::unique_ptr<QuicEncryptedPacket> encrypted( QuicFramer::BuildPublicResetPacket(packet)); - scoped_ptr<QuicReceivedPacket> received( + std::unique_ptr<QuicReceivedPacket> received( ConstructReceivedPacket(*encrypted, helper_.GetClock()->Now())); EXPECT_CALL(*session1_, OnConnectionClosed(QUIC_PUBLIC_RESET, _, ConnectionCloseSource::FROM_PEER))
diff --git a/net/tools/quic/quic_in_memory_cache.h b/net/tools/quic/quic_in_memory_cache.h index 72b210a..10d408e1 100644 --- a/net/tools/quic/quic_in_memory_cache.h +++ b/net/tools/quic/quic_in_memory_cache.h
@@ -227,7 +227,7 @@ ResponseMap responses_; // The default response for cache misses, if set. - scoped_ptr<Response> default_response_; + std::unique_ptr<Response> default_response_; // A map from request URL to associated server push responses (if any). std::multimap<std::string, ServerPushInfo> server_push_resources_;
diff --git a/net/tools/quic/quic_packet_writer_wrapper.h b/net/tools/quic/quic_packet_writer_wrapper.h index 92044c02..34642a6 100644 --- a/net/tools/quic/quic_packet_writer_wrapper.h +++ b/net/tools/quic/quic_packet_writer_wrapper.h
@@ -7,8 +7,9 @@ #include <stddef.h> +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/quic/quic_packet_writer.h" namespace net { @@ -38,7 +39,7 @@ void set_writer(QuicPacketWriter* writer); private: - scoped_ptr<QuicPacketWriter> writer_; + std::unique_ptr<QuicPacketWriter> writer_; DISALLOW_COPY_AND_ASSIGN(QuicPacketWriterWrapper); };
diff --git a/net/tools/quic/quic_server.cc b/net/tools/quic/quic_server.cc index c67e554f..723536e 100644 --- a/net/tools/quic/quic_server.cc +++ b/net/tools/quic/quic_server.cc
@@ -93,7 +93,7 @@ QuicEpollClock clock(&epoll_server_); - scoped_ptr<CryptoHandshakeMessage> scfg(crypto_config_.AddDefaultConfig( + std::unique_ptr<CryptoHandshakeMessage> scfg(crypto_config_.AddDefaultConfig( QuicRandom::GetInstance(), &clock, crypto_config_options_)); }
diff --git a/net/tools/quic/quic_server.h b/net/tools/quic/quic_server.h index 24523de..76ff17a4 100644 --- a/net/tools/quic/quic_server.h +++ b/net/tools/quic/quic_server.h
@@ -13,8 +13,9 @@ #include <stddef.h> +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/base/ip_endpoint.h" #include "net/quic/crypto/quic_crypto_server_config.h" #include "net/quic/quic_chromium_connection_helper.h" @@ -94,7 +95,7 @@ void Initialize(); // Accepts data from the framer and demuxes clients to sessions. - scoped_ptr<QuicDispatcher> dispatcher_; + std::unique_ptr<QuicDispatcher> dispatcher_; // Frames incoming packets and hands them to the dispatcher. EpollServer epoll_server_; @@ -129,7 +130,7 @@ // Point to a QuicPacketReader object on the heap. The reader allocates more // space than allowed on the stack. - scoped_ptr<QuicPacketReader> packet_reader_; + std::unique_ptr<QuicPacketReader> packet_reader_; DISALLOW_COPY_AND_ASSIGN(QuicServer); };
diff --git a/net/tools/quic/quic_server_session_base.h b/net/tools/quic/quic_server_session_base.h index 294dc480..d9b321e3 100644 --- a/net/tools/quic/quic_server_session_base.h +++ b/net/tools/quic/quic_server_session_base.h
@@ -9,13 +9,13 @@ #include <stdint.h> +#include <memory> #include <set> #include <string> #include <vector> #include "base/containers/hash_tables.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/quic/crypto/quic_compressed_certs_cache.h" #include "net/quic/quic_crypto_server_stream.h" #include "net/quic/quic_protocol.h" @@ -124,7 +124,7 @@ // Owned by QuicDispatcher. QuicCompressedCertsCache* compressed_certs_cache_; - scoped_ptr<QuicCryptoServerStreamBase> crypto_stream_; + std::unique_ptr<QuicCryptoServerStreamBase> crypto_stream_; QuicServerSessionVisitor* visitor_; // Whether bandwidth resumption is enabled for this connection.
diff --git a/net/tools/quic/quic_server_session_base_test.cc b/net/tools/quic/quic_server_session_base_test.cc index 2e08f14..7a32d4e0 100644 --- a/net/tools/quic/quic_server_session_base_test.cc +++ b/net/tools/quic/quic_server_session_base_test.cc
@@ -150,8 +150,8 @@ QuicConfig config_; QuicCryptoServerConfig crypto_config_; QuicCompressedCertsCache compressed_certs_cache_; - scoped_ptr<TestServerSession> session_; - scoped_ptr<CryptoHandshakeMessage> handshake_message_; + std::unique_ptr<TestServerSession> session_; + std::unique_ptr<CryptoHandshakeMessage> handshake_message_; QuicConnectionVisitorInterface* visitor_; };
diff --git a/net/tools/quic/quic_simple_client.cc b/net/tools/quic/quic_simple_client.cc index a3d0850f..c04d0b6 100644 --- a/net/tools/quic/quic_simple_client.cc +++ b/net/tools/quic/quic_simple_client.cc
@@ -100,7 +100,7 @@ } bool QuicSimpleClient::CreateUDPSocket() { - scoped_ptr<UDPClientSocket> socket( + std::unique_ptr<UDPClientSocket> socket( new UDPClientSocket(DatagramSocket::DEFAULT_BIND, RandIntCallback(), &net_log_, NetLog::Source()));
diff --git a/net/tools/quic/quic_simple_client.h b/net/tools/quic/quic_simple_client.h index bcd0bda..151fc6e9 100644 --- a/net/tools/quic/quic_simple_client.h +++ b/net/tools/quic/quic_simple_client.h
@@ -10,11 +10,11 @@ #include <stddef.h> +#include <memory> #include <string> #include "base/command_line.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string_piece.h" #include "net/base/ip_address.h" #include "net/base/ip_endpoint.h" @@ -220,10 +220,10 @@ int local_port_; // UDP socket connected to the server. - scoped_ptr<UDPClientSocket> socket_; + std::unique_ptr<UDPClientSocket> socket_; // Listens for full responses. - scoped_ptr<ResponseListener> response_listener_; + std::unique_ptr<ResponseListener> response_listener_; // Tracks if the client is initialized to connect. bool initialized_; @@ -255,7 +255,7 @@ // The log used for the sockets. NetLog net_log_; - scoped_ptr<QuicChromiumPacketReader> packet_reader_; + std::unique_ptr<QuicChromiumPacketReader> packet_reader_; bool packet_reader_started_;
diff --git a/net/tools/quic/quic_simple_client_bin.cc b/net/tools/quic/quic_simple_client_bin.cc index d7f5ef5..bd58aee 100644 --- a/net/tools/quic/quic_simple_client_bin.cc +++ b/net/tools/quic/quic_simple_client_bin.cc
@@ -114,7 +114,7 @@ net::CRLSet* crl_set, net::CertVerifyResult* verify_result, const net::CompletionCallback& callback, - scoped_ptr<net::CertVerifier::Request>* out_req, + std::unique_ptr<net::CertVerifier::Request>* out_req, const net::BoundNetLog& net_log) override { return net::OK; } @@ -276,13 +276,13 @@ versions.push_back(static_cast<net::QuicVersion>(FLAGS_quic_version)); } // For secure QUIC we need to verify the cert chain. - scoped_ptr<CertVerifier> cert_verifier(CertVerifier::CreateDefault()); + std::unique_ptr<CertVerifier> cert_verifier(CertVerifier::CreateDefault()); if (line->HasSwitch("disable-certificate-verification")) { cert_verifier.reset(new FakeCertVerifier()); } - scoped_ptr<TransportSecurityState> transport_security_state( + std::unique_ptr<TransportSecurityState> transport_security_state( new TransportSecurityState); - scoped_ptr<CTVerifier> ct_verifier(new MultiLogCTVerifier()); + std::unique_ptr<CTVerifier> ct_verifier(new MultiLogCTVerifier()); ProofVerifierChromium* proof_verifier = new ProofVerifierChromium( cert_verifier.get(), nullptr, transport_security_state.get(), ct_verifier.get());
diff --git a/net/tools/quic/quic_simple_server.cc b/net/tools/quic/quic_simple_server.cc index 77139862..ecc15dc 100644 --- a/net/tools/quic/quic_simple_server.cc +++ b/net/tools/quic/quic_simple_server.cc
@@ -99,7 +99,7 @@ kInitialSessionFlowControlWindow); } - scoped_ptr<CryptoHandshakeMessage> scfg(crypto_config_.AddDefaultConfig( + std::unique_ptr<CryptoHandshakeMessage> scfg(crypto_config_.AddDefaultConfig( helper_->GetRandomGenerator(), helper_->GetClock(), QuicCryptoServerConfig::ConfigOptions())); } @@ -107,7 +107,7 @@ QuicSimpleServer::~QuicSimpleServer() {} int QuicSimpleServer::Listen(const IPEndPoint& address) { - scoped_ptr<UDPServerSocket> socket( + std::unique_ptr<UDPServerSocket> socket( new UDPServerSocket(&net_log_, NetLog::Source())); socket->AllowAddressReuse();
diff --git a/net/tools/quic/quic_simple_server.h b/net/tools/quic/quic_simple_server.h index 21c39bf7..e9dcdca 100644 --- a/net/tools/quic/quic_simple_server.h +++ b/net/tools/quic/quic_simple_server.h
@@ -8,8 +8,9 @@ #ifndef NET_QUIC_TOOLS_QUIC_SIMPLE_SERVER_H_ #define NET_QUIC_TOOLS_QUIC_SIMPLE_SERVER_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/base/io_buffer.h" #include "net/base/ip_endpoint.h" #include "net/log/net_log.h" @@ -64,7 +65,7 @@ void Initialize(); // Accepts data from the framer and demuxes clients to sessions. - scoped_ptr<QuicDispatcher> dispatcher_; + std::unique_ptr<QuicDispatcher> dispatcher_; // Used by the helper_ to time alarms. QuicClock clock_; @@ -73,7 +74,7 @@ QuicChromiumConnectionHelper* helper_; // Listening socket. Also used for outbound client communication. - scoped_ptr<UDPServerSocket> socket_; + std::unique_ptr<UDPServerSocket> socket_; // config_ contains non-crypto parameters that are negotiated in the crypto // handshake.
diff --git a/net/tools/quic/quic_simple_server_session.h b/net/tools/quic/quic_simple_server_session.h index 2754f36..a700544 100644 --- a/net/tools/quic/quic_simple_server_session.h +++ b/net/tools/quic/quic_simple_server_session.h
@@ -11,13 +11,13 @@ #include <deque> #include <list> +#include <memory> #include <set> #include <string> #include <vector> #include "base/containers/hash_tables.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/quic/quic_crypto_server_stream.h" #include "net/quic/quic_protocol.h" #include "net/quic/quic_spdy_session.h"
diff --git a/net/tools/quic/quic_simple_server_session_test.cc b/net/tools/quic/quic_simple_server_session_test.cc index 40760eb..fb40263 100644 --- a/net/tools/quic/quic_simple_server_session_test.cc +++ b/net/tools/quic/quic_simple_server_session_test.cc
@@ -189,8 +189,8 @@ QuicConfig config_; QuicCryptoServerConfig crypto_config_; QuicCompressedCertsCache compressed_certs_cache_; - scoped_ptr<QuicSimpleServerSession> session_; - scoped_ptr<CryptoHandshakeMessage> handshake_message_; + std::unique_ptr<QuicSimpleServerSession> session_; + std::unique_ptr<CryptoHandshakeMessage> handshake_message_; QuicConnectionVisitorInterface* visitor_; MockQuicHeadersStream* headers_stream_; };
diff --git a/net/tools/quic/quic_spdy_client_stream_test.cc b/net/tools/quic/quic_spdy_client_stream_test.cc index 53e414d..698da70 100644 --- a/net/tools/quic/quic_spdy_client_stream_test.cc +++ b/net/tools/quic/quic_spdy_client_stream_test.cc
@@ -88,8 +88,8 @@ QuicClientPushPromiseIndex push_promise_index_; MockQuicClientSession session_; - scoped_ptr<QuicSpdyClientStream> stream_; - scoped_ptr<StreamVisitor> stream_visitor_; + std::unique_ptr<QuicSpdyClientStream> stream_; + std::unique_ptr<StreamVisitor> stream_visitor_; BalsaHeaders headers_; string headers_string_; string body_;
diff --git a/net/tools/quic/quic_time_wait_list_manager.cc b/net/tools/quic/quic_time_wait_list_manager.cc index 91c48d0..788caa9 100644 --- a/net/tools/quic/quic_time_wait_list_manager.cc +++ b/net/tools/quic/quic_time_wait_list_manager.cc
@@ -6,9 +6,10 @@ #include <errno.h> +#include <memory> + #include "base/logging.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/stl_util.h" #include "net/base/ip_endpoint.h" #include "net/quic/crypto/crypto_protocol.h" @@ -68,7 +69,7 @@ private: const IPEndPoint server_address_; const IPEndPoint client_address_; - scoped_ptr<QuicEncryptedPacket> packet_; + std::unique_ptr<QuicEncryptedPacket> packet_; DISALLOW_COPY_AND_ASSIGN(QueuedPacket); };
diff --git a/net/tools/quic/quic_time_wait_list_manager_test.cc b/net/tools/quic/quic_time_wait_list_manager_test.cc index 58c9112d..35681e0 100644 --- a/net/tools/quic/quic_time_wait_list_manager_test.cc +++ b/net/tools/quic/quic_time_wait_list_manager_test.cc
@@ -219,7 +219,7 @@ } TEST_F(QuicTimeWaitListManagerTest, SendVersionNegotiationPacket) { - scoped_ptr<QuicEncryptedPacket> packet( + std::unique_ptr<QuicEncryptedPacket> packet( QuicFramer::BuildVersionNegotiationPacket(connection_id_, QuicSupportedVersions())); EXPECT_CALL(writer_, @@ -374,7 +374,7 @@ EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id)); AddConnectionId(connection_id); QuicPacketNumber packet_number = 234; - scoped_ptr<QuicEncryptedPacket> packet( + std::unique_ptr<QuicEncryptedPacket> packet( ConstructEncryptedPacket(connection_id, packet_number)); // Let first write through. EXPECT_CALL(writer_, @@ -400,7 +400,7 @@ EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(other_connection_id)); AddConnectionId(other_connection_id); QuicPacketNumber other_packet_number = 23423; - scoped_ptr<QuicEncryptedPacket> other_packet( + std::unique_ptr<QuicEncryptedPacket> other_packet( ConstructEncryptedPacket(other_connection_id, other_packet_number)); EXPECT_CALL(writer_, WritePacket(_, _, _, _, _)).Times(0); EXPECT_CALL(visitor_, OnWriteBlocked(&time_wait_list_manager_));
diff --git a/net/tools/quic/spdy_balsa_utils.cc b/net/tools/quic/spdy_balsa_utils.cc index dd24c99..2209d2f 100644 --- a/net/tools/quic/spdy_balsa_utils.cc +++ b/net/tools/quic/spdy_balsa_utils.cc
@@ -4,9 +4,9 @@ #include "net/tools/quic/spdy_balsa_utils.h" +#include <memory> #include <string> -#include "base/memory/scoped_ptr.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h"
diff --git a/net/tools/quic/synchronous_host_resolver.cc b/net/tools/quic/synchronous_host_resolver.cc index 2808cc7..9b9c7b6 100644 --- a/net/tools/quic/synchronous_host_resolver.cc +++ b/net/tools/quic/synchronous_host_resolver.cc
@@ -59,7 +59,7 @@ net::HostResolver::Options options; options.max_concurrent_resolves = 6; options.max_retry_attempts = 3u; - scoped_ptr<net::HostResolverImpl> resolver_impl( + std::unique_ptr<net::HostResolverImpl> resolver_impl( new net::HostResolverImpl(options, &net_log)); SingleRequestHostResolver resolver(resolver_impl.get());
diff --git a/net/tools/quic/test_tools/packet_dropping_test_writer.h b/net/tools/quic/test_tools/packet_dropping_test_writer.h index 20d2c27..5f8c84d 100644 --- a/net/tools/quic/test_tools/packet_dropping_test_writer.h +++ b/net/tools/quic/test_tools/packet_dropping_test_writer.h
@@ -9,11 +9,11 @@ #include <stdint.h> #include <list> +#include <memory> #include <string> #include "base/logging.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/synchronization/lock.h" #include "net/base/ip_address.h" #include "net/quic/quic_alarm.h" @@ -153,9 +153,9 @@ typedef std::list<DelayedWrite> DelayedPacketList; const QuicClock* clock_; - scoped_ptr<QuicAlarm> write_unblocked_alarm_; - scoped_ptr<QuicAlarm> delay_alarm_; - scoped_ptr<Delegate> on_can_write_; + std::unique_ptr<QuicAlarm> write_unblocked_alarm_; + std::unique_ptr<QuicAlarm> delay_alarm_; + std::unique_ptr<Delegate> on_can_write_; net::test::SimpleRandom simple_random_; // Stored packets delayed by fake packet delay or bandwidth restrictions. DelayedPacketList delayed_packets_;
diff --git a/net/tools/quic/test_tools/quic_test_client.cc b/net/tools/quic/test_tools/quic_test_client.cc index 3984046..37f4759 100644 --- a/net/tools/quic/test_tools/quic_test_client.cc +++ b/net/tools/quic/test_tools/quic_test_client.cc
@@ -52,7 +52,7 @@ const string& signature, const ProofVerifyContext* context, string* error_details, - scoped_ptr<ProofVerifyDetails>* details, + std::unique_ptr<ProofVerifyDetails>* details, ProofVerifierCallback* callback) override { common_name_.clear(); if (certs.empty()) { @@ -311,7 +311,7 @@ // CHECK(message.body_chunks().empty()) // << "HTTPMessage::body_chunks not supported"; - scoped_ptr<BalsaHeaders> munged_headers(MungeHeaders(message.headers())); + std::unique_ptr<BalsaHeaders> munged_headers(MungeHeaders(message.headers())); ssize_t ret = GetOrCreateStreamAndSendRequest( (munged_headers.get() ? munged_headers.get() : message.headers()), message.body(), message.has_complete_message(), nullptr);
diff --git a/net/tools/quic/test_tools/quic_test_client.h b/net/tools/quic/test_tools/quic_test_client.h index b8530f4..80b7eb21 100644 --- a/net/tools/quic/test_tools/quic_test_client.h +++ b/net/tools/quic/test_tools/quic_test_client.h
@@ -8,10 +8,10 @@ #include <stddef.h> #include <stdint.h> +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "net/base/ip_address.h" #include "net/base/ip_endpoint.h" #include "net/quic/proto/cached_network_parameters.pb.h" @@ -233,7 +233,7 @@ bool HaveActiveStream(); EpollServer epoll_server_; - scoped_ptr<MockableQuicClient> client_; // The actual client + std::unique_ptr<MockableQuicClient> client_; // The actual client QuicSpdyClientStream* stream_; QuicRstStreamErrorCode stream_error_;
diff --git a/net/tools/quic/test_tools/quic_test_server.h b/net/tools/quic/test_tools/quic_test_server.h index 7af5f51..b4ddee0 100644 --- a/net/tools/quic/test_tools/quic_test_server.h +++ b/net/tools/quic/test_tools/quic_test_server.h
@@ -5,9 +5,9 @@ #ifndef NET_TOOLS_QUIC_TEST_TOOLS_QUIC_TEST_SERVER_H_ #define NET_TOOLS_QUIC_TEST_TOOLS_QUIC_TEST_SERVER_H_ +#include <memory> #include <string> -#include "base/memory/scoped_ptr.h" #include "net/base/ip_endpoint.h" #include "net/quic/quic_session.h" #include "net/tools/quic/quic_dispatcher.h"
diff --git a/net/tools/quic/test_tools/server_thread.h b/net/tools/quic/test_tools/server_thread.h index 244a87c..8bb486c 100644 --- a/net/tools/quic/test_tools/server_thread.h +++ b/net/tools/quic/test_tools/server_thread.h
@@ -63,7 +63,7 @@ base::WaitableEvent resume_; // Notified when the server should resume. base::WaitableEvent quit_; // Notified when the server should quit. - scoped_ptr<QuicServer> server_; + std::unique_ptr<QuicServer> server_; IPEndPoint address_; base::Lock port_lock_; int port_;
diff --git a/net/tools/testserver/run_testserver.cc b/net/tools/testserver/run_testserver.cc index 717fee1..6da829d 100644 --- a/net/tools/testserver/run_testserver.cc +++ b/net/tools/testserver/run_testserver.cc
@@ -95,7 +95,7 @@ return -1; } - scoped_ptr<net::SpawnedTestServer> test_server; + std::unique_ptr<net::SpawnedTestServer> test_server; if (net::SpawnedTestServer::UsingSSL(server_type)) { test_server.reset( new net::SpawnedTestServer(server_type, ssl_options, doc_root));
diff --git a/net/udp/udp_net_log_parameters.cc b/net/udp/udp_net_log_parameters.cc index d157fe83..e903036c 100644 --- a/net/udp/udp_net_log_parameters.cc +++ b/net/udp/udp_net_log_parameters.cc
@@ -15,12 +15,12 @@ namespace { -scoped_ptr<base::Value> NetLogUDPDataTranferCallback( +std::unique_ptr<base::Value> NetLogUDPDataTranferCallback( int byte_count, const char* bytes, const IPEndPoint* address, NetLogCaptureMode capture_mode) { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetInteger("byte_count", byte_count); if (capture_mode.include_socket_bytes()) dict->SetString("hex_encoded_bytes", base::HexEncode(bytes, byte_count)); @@ -29,10 +29,10 @@ return std::move(dict); } -scoped_ptr<base::Value> NetLogUDPConnectCallback( +std::unique_ptr<base::Value> NetLogUDPConnectCallback( const IPEndPoint* address, NetLogCaptureMode /* capture_mode */) { - scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetString("address", address->ToString()); return std::move(dict); }
diff --git a/net/udp/udp_socket_perftest.cc b/net/udp/udp_socket_perftest.cc index 67804a7e..8441a0e 100644 --- a/net/udp/udp_socket_perftest.cc +++ b/net/udp/udp_socket_perftest.cc
@@ -88,7 +88,7 @@ // Setup the server to listen. IPEndPoint bind_address; CreateUDPAddress("127.0.0.1", kPort, &bind_address); - scoped_ptr<UDPServerSocket> server( + std::unique_ptr<UDPServerSocket> server( new UDPServerSocket(nullptr, NetLog::Source())); #if defined(OS_WIN) if (use_nonblocking_io) @@ -100,7 +100,7 @@ // Setup the client. IPEndPoint server_address; CreateUDPAddress("127.0.0.1", kPort, &server_address); - scoped_ptr<UDPClientSocket> client( + std::unique_ptr<UDPClientSocket> client( new UDPClientSocket(DatagramSocket::DEFAULT_BIND, RandIntCallback(), nullptr, NetLog::Source())); #if defined(OS_WIN)
diff --git a/net/udp/udp_socket_posix.cc b/net/udp/udp_socket_posix.cc index 7e75b860..f869256c 100644 --- a/net/udp/udp_socket_posix.cc +++ b/net/udp/udp_socket_posix.cc
@@ -151,7 +151,7 @@ SockaddrStorage storage; if (getpeername(socket_, storage.addr, &storage.addr_len)) return MapSystemError(errno); - scoped_ptr<IPEndPoint> address(new IPEndPoint()); + std::unique_ptr<IPEndPoint> address(new IPEndPoint()); if (!address->FromSockAddr(storage.addr, storage.addr_len)) return ERR_ADDRESS_INVALID; remote_address_.reset(address.release()); @@ -171,7 +171,7 @@ SockaddrStorage storage; if (getsockname(socket_, storage.addr, &storage.addr_len)) return MapSystemError(errno); - scoped_ptr<IPEndPoint> address(new IPEndPoint()); + std::unique_ptr<IPEndPoint> address(new IPEndPoint()); if (!address->FromSockAddr(storage.addr, storage.addr_len)) return ERR_ADDRESS_INVALID; local_address_.reset(address.release());
diff --git a/net/udp/udp_socket_posix.h b/net/udp/udp_socket_posix.h index 60b095c..7da58c1 100644 --- a/net/udp/udp_socket_posix.h +++ b/net/udp/udp_socket_posix.h
@@ -7,9 +7,10 @@ #include <stdint.h> +#include <memory> + #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/threading/non_thread_safe.h" #include "net/base/address_family.h" @@ -280,8 +281,8 @@ // These are mutable since they're just cached copies to make // GetPeerAddress/GetLocalAddress smarter. - mutable scoped_ptr<IPEndPoint> local_address_; - mutable scoped_ptr<IPEndPoint> remote_address_; + mutable std::unique_ptr<IPEndPoint> local_address_; + mutable std::unique_ptr<IPEndPoint> remote_address_; // The socket's posix wrappers base::MessageLoopForIO::FileDescriptorWatcher read_socket_watcher_; @@ -299,7 +300,7 @@ // The buffer used by InternalWrite() to retry Write requests scoped_refptr<IOBuffer> write_buf_; int write_buf_len_; - scoped_ptr<IPEndPoint> send_to_address_; + std::unique_ptr<IPEndPoint> send_to_address_; // External callback; called when read is complete. CompletionCallback read_callback_;
diff --git a/net/udp/udp_socket_unittest.cc b/net/udp/udp_socket_unittest.cc index 28f29cc..be3b1aa 100644 --- a/net/udp/udp_socket_unittest.cc +++ b/net/udp/udp_socket_unittest.cc
@@ -159,7 +159,7 @@ IPEndPoint bind_address; CreateUDPAddress("127.0.0.1", kPort, &bind_address); TestNetLog server_log; - scoped_ptr<UDPServerSocket> server( + std::unique_ptr<UDPServerSocket> server( new UDPServerSocket(&server_log, NetLog::Source())); #if defined(OS_WIN) if (use_nonblocking_io) @@ -173,7 +173,7 @@ IPEndPoint server_address; CreateUDPAddress("127.0.0.1", kPort, &server_address); TestNetLog client_log; - scoped_ptr<UDPClientSocket> client( + std::unique_ptr<UDPClientSocket> client( new UDPClientSocket(DatagramSocket::DEFAULT_BIND, RandIntCallback(), &client_log, NetLog::Source())); #if defined(OS_WIN) @@ -287,9 +287,9 @@ CreateUDPAddress("0.0.0.0", kPort, &listen_address); TestNetLog server1_log, server2_log; - scoped_ptr<UDPServerSocket> server1( + std::unique_ptr<UDPServerSocket> server1( new UDPServerSocket(&server1_log, NetLog::Source())); - scoped_ptr<UDPServerSocket> server2( + std::unique_ptr<UDPServerSocket> server2( new UDPServerSocket(&server2_log, NetLog::Source())); server1->AllowAddressReuse(); server1->AllowBroadcast(); @@ -380,11 +380,8 @@ base::Bind(&TestPrng::GetNext, base::Unretained(&test_prng)); // Create a socket with random binding policy and connect. - scoped_ptr<UDPClientSocket> test_socket( - new UDPClientSocket(DatagramSocket::RANDOM_BIND, - rand_int_cb, - NULL, - NetLog::Source())); + std::unique_ptr<UDPClientSocket> test_socket(new UDPClientSocket( + DatagramSocket::RANDOM_BIND, rand_int_cb, NULL, NetLog::Source())); EXPECT_EQ(OK, test_socket->Connect(peer_address)); // Make sure that the last port number in the |used_ports| was used. @@ -412,11 +409,9 @@ IPEndPoint peer_address; CreateUDPAddress("0.0.0.0", 53, &peer_address); - scoped_ptr<UDPSocket> socket( - new UDPSocket(DatagramSocket::RANDOM_BIND, - base::Bind(&PrivilegedRand), - NULL, - NetLog::Source())); + std::unique_ptr<UDPSocket> socket(new UDPSocket(DatagramSocket::RANDOM_BIND, + base::Bind(&PrivilegedRand), + NULL, NetLog::Source())); int rv = socket->Open(peer_address.GetFamily()); EXPECT_EQ(OK, rv); rv = socket->Connect(peer_address);
diff --git a/net/udp/udp_socket_win.cc b/net/udp/udp_socket_win.cc index c1628229..ca1ffb9e 100644 --- a/net/udp/udp_socket_win.cc +++ b/net/udp/udp_socket_win.cc
@@ -329,7 +329,7 @@ SockaddrStorage storage; if (getpeername(socket_, storage.addr, &storage.addr_len)) return MapSystemError(WSAGetLastError()); - scoped_ptr<IPEndPoint> remote_address(new IPEndPoint()); + std::unique_ptr<IPEndPoint> remote_address(new IPEndPoint()); if (!remote_address->FromSockAddr(storage.addr, storage.addr_len)) return ERR_ADDRESS_INVALID; remote_address_.reset(remote_address.release()); @@ -350,7 +350,7 @@ SockaddrStorage storage; if (getsockname(socket_, storage.addr, &storage.addr_len)) return MapSystemError(WSAGetLastError()); - scoped_ptr<IPEndPoint> local_address(new IPEndPoint()); + std::unique_ptr<IPEndPoint> local_address(new IPEndPoint()); if (!local_address->FromSockAddr(storage.addr, storage.addr_len)) return ERR_ADDRESS_INVALID; local_address_.reset(local_address.release());
diff --git a/net/udp/udp_socket_win.h b/net/udp/udp_socket_win.h index 62c3e11..14b801e3 100644 --- a/net/udp/udp_socket_win.h +++ b/net/udp/udp_socket_win.h
@@ -9,10 +9,11 @@ #include <stdint.h> #include <winsock2.h> +#include <memory> + #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/threading/non_thread_safe.h" #include "base/win/object_watcher.h" #include "base/win/scoped_handle.h" @@ -273,8 +274,8 @@ // These are mutable since they're just cached copies to make // GetPeerAddress/GetLocalAddress smarter. - mutable scoped_ptr<IPEndPoint> local_address_; - mutable scoped_ptr<IPEndPoint> remote_address_; + mutable std::unique_ptr<IPEndPoint> local_address_; + mutable std::unique_ptr<IPEndPoint> remote_address_; // The core of the socket that can live longer than the socket itself. We pass // resources to the Windows async IO functions and we have to make sure that @@ -301,7 +302,7 @@ // Cached copy of the current address we're sending to, if any. Used for // logging. - scoped_ptr<IPEndPoint> send_to_address_; + std::unique_ptr<IPEndPoint> send_to_address_; // External callback; called when read is complete. CompletionCallback read_callback_;
diff --git a/net/url_request/url_request_test_util.cc b/net/url_request/url_request_test_util.cc index f45c283..3f9ffb5 100644 --- a/net/url_request/url_request_test_util.cc +++ b/net/url_request/url_request_test_util.cc
@@ -93,6 +93,18 @@ context_storage_.set_http_server_properties( std::unique_ptr<HttpServerProperties>(new HttpServerPropertiesImpl())); } + // In-memory cookie store. + if (!cookie_store()) { + context_storage_.set_cookie_store( + base::WrapUnique(new CookieMonster(nullptr, nullptr))); + } + // In-memory Channel ID service. Must be created before the + // HttpNetworkSession. + if (!channel_id_service()) { + context_storage_.set_channel_id_service(base::WrapUnique( + new ChannelIDService(new DefaultChannelIDStore(nullptr), + base::WorkerPool::GetTaskRunner(true)))); + } if (http_transaction_factory()) { // Make sure we haven't been passed an object we're not going to use. EXPECT_FALSE(client_socket_factory_); @@ -121,17 +133,6 @@ new HttpCache(context_storage_.http_network_session(), HttpCache::DefaultBackend::InMemory(0), false))); } - // In-memory cookie store. - if (!cookie_store()) { - context_storage_.set_cookie_store( - base::WrapUnique(new CookieMonster(nullptr, nullptr))); - } - // In-memory Channel ID service. - if (!channel_id_service()) { - context_storage_.set_channel_id_service(base::WrapUnique( - new ChannelIDService(new DefaultChannelIDStore(nullptr), - base::WorkerPool::GetTaskRunner(true)))); - } if (!http_user_agent_settings()) { context_storage_.set_http_user_agent_settings(base::WrapUnique( new StaticHttpUserAgentSettings("en-us,fr", std::string())));
diff --git a/pdf/DEPS b/pdf/DEPS index cbfcfbf..74181cea 100644 --- a/pdf/DEPS +++ b/pdf/DEPS
@@ -1,12 +1,7 @@ include_rules = [ "+chrome/common/content_restriction.h", - "+gin", "+net", "+ppapi", - "+printing/pdf_transform.h", - "+printing/units.h", - "+third_party/pdfium/public", "+ui/events/keycodes/keyboard_codes.h", - "+ui/gfx/geometry/rect.h", "+v8/include/v8.h" ]
diff --git a/pdf/pdfium/DEPS b/pdf/pdfium/DEPS new file mode 100644 index 0000000..1f87653 --- /dev/null +++ b/pdf/pdfium/DEPS
@@ -0,0 +1,8 @@ +include_rules = [ + "+gin/array_buffer.h", + "+gin/public", + "+printing/pdf_transform.h", + "+printing/units.h", + "+third_party/pdfium/public", + "+ui/gfx/geometry/rect.h", +]
diff --git a/ppapi/BUILD.gn b/ppapi/BUILD.gn index 6cac3cf..9ae8d5f 100644 --- a/ppapi/BUILD.gn +++ b/ppapi/BUILD.gn
@@ -7,6 +7,10 @@ assert(!is_android || enable_plugins, "//ppapi should not be referenced when is_android && !enable_plugins") +if (is_mac) { + import("//build/config/mac/rules.gni") +} + copy("copy_test_files") { visibility = [ ":*" ] sources = [ @@ -72,7 +76,7 @@ ] } -loadable_module("blink_deprecated_test_plugin") { +source_set("blink_deprecated_test_plugin_sources") { sources = [ "tests/blink_deprecated_test_plugin.cc", ] @@ -85,7 +89,21 @@ ] } -loadable_module("blink_test_plugin") { +if (!is_mac) { + loadable_module("blink_deprecated_test_plugin") { + deps = [ + ":blink_deprecated_test_plugin_sources", + ] + } +} else { + mac_plugin_bundle("blink_deprecated_test_plugin") { + deps = [ + ":blink_deprecated_test_plugin_sources", + ] + } +} + +source_set("blink_test_plugin_sources") { sources = [ "tests/blink_test_plugin.cc", ] @@ -98,6 +116,20 @@ ] } +if (!is_mac) { + loadable_module("blink_test_plugin") { + deps = [ + ":blink_test_plugin_sources", + ] + } +} else { + mac_plugin_bundle("blink_test_plugin") { + deps = [ + ":blink_test_plugin_sources", + ] + } +} + test("ppapi_unittests") { sources = [ "host/resource_message_filter_unittest.cc",
diff --git a/ppapi/utility/completion_callback_factory_thread_traits.h b/ppapi/utility/completion_callback_factory_thread_traits.h index a1dbc64e..ac0b31a 100644 --- a/ppapi/utility/completion_callback_factory_thread_traits.h +++ b/ppapi/utility/completion_callback_factory_thread_traits.h
@@ -85,7 +85,7 @@ /// Default constructor. In debug mode, this checks that the object is being /// created on the main thread. RefCount() : ref_(0) { -#ifndef NDEBUG +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) is_main_thread_ = Module::Get()->core()->IsMainThread(); #endif } @@ -113,7 +113,7 @@ private: int32_t ref_; -#ifndef NDEBUG +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) bool is_main_thread_; #endif }; @@ -126,7 +126,7 @@ class Lock { public: Lock() { -#ifndef NDEBUG +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) is_main_thread_ = Module::Get()->core()->IsMainThread(); lock_held_ = false; #endif @@ -139,7 +139,7 @@ /// Acquires the fake "lock". This does nothing except perform checks in /// debug mode. void Acquire() { -#ifndef NDEBUG +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) PP_DCHECK(!lock_held_); lock_held_ = true; #endif @@ -148,14 +148,14 @@ /// Releases the fake "lock". This does nothing except perform checks in /// debug mode. void Release() { -#ifndef NDEBUG +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) PP_DCHECK(lock_held_); lock_held_ = false; #endif } private: -#ifndef NDEBUG +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) bool is_main_thread_; bool lock_held_; #endif
diff --git a/remoting/android/BUILD.gn b/remoting/android/BUILD.gn index ee4e40b..8730d27 100644 --- a/remoting/android/BUILD.gn +++ b/remoting/android/BUILD.gn
@@ -184,6 +184,7 @@ android_manifest = "host/AndroidManifest.xml" native_libs = [ "libremoting_host_jni.so" ] java_files = [ + "host/src/org/chromium/chromoting/host/RemotingApplication.java", "host/src/org/chromium/chromoting/host/MainActivity.java", "host/src/org/chromium/chromoting/host/jni/Host.java", ]
diff --git a/remoting/android/apk/src/org/chromium/chromoting/RemotingApplication.java b/remoting/android/apk/src/org/chromium/chromoting/RemotingApplication.java index 7ebc667..2a7176d5 100644 --- a/remoting/android/apk/src/org/chromium/chromoting/RemotingApplication.java +++ b/remoting/android/apk/src/org/chromium/chromoting/RemotingApplication.java
@@ -9,12 +9,15 @@ import org.chromium.chromoting.accountswitcher.AccountSwitcherFactory; import org.chromium.chromoting.help.HelpAndFeedbackBasic; import org.chromium.chromoting.help.HelpSingleton; +import org.chromium.chromoting.jni.JniInterface; /** Main context for the application. */ public class RemotingApplication extends Application { @Override public void onCreate() { super.onCreate(); + JniInterface.loadLibrary(this); + AccountSwitcherFactory.setInstance(new AccountSwitcherFactory()); HelpSingleton.setInstance(new HelpAndFeedbackBasic()); }
diff --git a/remoting/android/host/AndroidManifest.xml b/remoting/android/host/AndroidManifest.xml index 17aed71..2708d00 100644 --- a/remoting/android/host/AndroidManifest.xml +++ b/remoting/android/host/AndroidManifest.xml
@@ -9,6 +9,7 @@ package="org.chromium.chromoting.host"> <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="23"/> <application android:label="CRD Host" + android:name="org.chromium.chromoting.host.RemotingApplication" android:theme="@style/Theme.AppCompat.Light.NoActionBar" android:allowBackup="false"> <activity android:name="org.chromium.chromoting.host.MainActivity"
diff --git a/remoting/android/host/src/org/chromium/chromoting/host/MainActivity.java b/remoting/android/host/src/org/chromium/chromoting/host/MainActivity.java index ddbc11e6..649fd42 100644 --- a/remoting/android/host/src/org/chromium/chromoting/host/MainActivity.java +++ b/remoting/android/host/src/org/chromium/chromoting/host/MainActivity.java
@@ -8,8 +8,6 @@ import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; -import org.chromium.chromoting.host.jni.Host; - /** * Main screen of the Chromoting Host application. */ @@ -19,8 +17,6 @@ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - Host.loadLibrary(this); - setContentView(R.layout.main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
diff --git a/remoting/android/host/src/org/chromium/chromoting/host/RemotingApplication.java b/remoting/android/host/src/org/chromium/chromoting/host/RemotingApplication.java new file mode 100644 index 0000000..d695041 --- /dev/null +++ b/remoting/android/host/src/org/chromium/chromoting/host/RemotingApplication.java
@@ -0,0 +1,17 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chromoting.host; + +import android.app.Application; + +import org.chromium.chromoting.host.jni.Host; + +/** Main context for the application. */ +public class RemotingApplication extends Application { + @Override + public void onCreate() { + Host.loadLibrary(this); + } +}
diff --git a/remoting/android/host/src/org/chromium/chromoting/host/jni/Host.java b/remoting/android/host/src/org/chromium/chromoting/host/jni/Host.java index a85adcd..f8f7fb9 100644 --- a/remoting/android/host/src/org/chromium/chromoting/host/jni/Host.java +++ b/remoting/android/host/src/org/chromium/chromoting/host/jni/Host.java
@@ -18,16 +18,14 @@ // Pointer to the C++ object, cast to a |long|. private long mNativeJniHost; - private static boolean sLoaded; - - // Called once from the main Activity. Loads and initializes the native - // code. + /** + * To be called once from the Application context singleton. Loads and initializes the native + * code. Called on the UI thread. + * @param context The Application context. + */ public static void loadLibrary(Context context) { - if (sLoaded) return; - System.loadLibrary("remoting_host_jni"); - ContextUtils.initApplicationContext(context.getApplicationContext()); - sLoaded = true; + ContextUtils.initApplicationContext(context); } public Host() {
diff --git a/remoting/android/java/src/org/chromium/chromoting/Chromoting.java b/remoting/android/java/src/org/chromium/chromoting/Chromoting.java index 6fc8b7d..ae8ccc5 100644 --- a/remoting/android/java/src/org/chromium/chromoting/Chromoting.java +++ b/remoting/android/java/src/org/chromium/chromoting/Chromoting.java
@@ -38,7 +38,6 @@ import org.chromium.chromoting.help.HelpSingleton; import org.chromium.chromoting.jni.Client; import org.chromium.chromoting.jni.ConnectionListener; -import org.chromium.chromoting.jni.JniInterface; import java.util.ArrayList; import java.util.Arrays; @@ -276,9 +275,6 @@ LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); navigationDrawer.addView(switcherView, 0); - - // Bring native components online. - JniInterface.loadLibrary(this); } @Override
diff --git a/remoting/android/java/src/org/chromium/chromoting/jni/JniInterface.java b/remoting/android/java/src/org/chromium/chromoting/jni/JniInterface.java index 85347af..95b1671 100644 --- a/remoting/android/java/src/org/chromium/chromoting/jni/JniInterface.java +++ b/remoting/android/java/src/org/chromium/chromoting/jni/JniInterface.java
@@ -19,24 +19,16 @@ */ @JNINamespace("remoting") public class JniInterface { - /* - * Library-loading state machine. - */ - /** Whether the library has been loaded. Accessed on the UI thread. */ - private static boolean sLoaded = false; - /** - * To be called once from the main Activity. Loads and initializes the native code. - * Called on the UI thread. + * To be called once from the Application context singleton. Loads and initializes the native + * code. Called on the UI thread. + * @param context The Application context. */ public static void loadLibrary(Context context) { - if (sLoaded) return; - System.loadLibrary("remoting_client_jni"); - ContextUtils.initApplicationContext(context.getApplicationContext()); + ContextUtils.initApplicationContext(context); nativeLoadNative(); - sLoaded = true; } /** Performs the native portion of the initialization. */
diff --git a/remoting/host/basic_desktop_environment.cc b/remoting/host/basic_desktop_environment.cc index d73bfac..b047c26 100644 --- a/remoting/host/basic_desktop_environment.cc +++ b/remoting/host/basic_desktop_environment.cc
@@ -20,10 +20,6 @@ #include "third_party/webrtc/modules/desktop_capture/mouse_cursor_monitor.h" #include "third_party/webrtc/modules/desktop_capture/screen_capturer.h" -#if defined(OS_CHROMEOS) -#include "remoting/host/chromeos/aura_desktop_capturer.h" -#include "remoting/host/chromeos/mouse_cursor_monitor_aura.h" -#endif #if defined(USE_X11) #include "remoting/host/linux/x11_util.h" #endif @@ -55,16 +51,8 @@ std::unique_ptr<webrtc::MouseCursorMonitor> BasicDesktopEnvironment::CreateMouseCursorMonitor() { - std::unique_ptr<webrtc::MouseCursorMonitor> cursor_monitor; - -#if defined(OS_CHROMEOS) - cursor_monitor.reset(new MouseCursorMonitorAura()); -#else - cursor_monitor.reset(webrtc::MouseCursorMonitor::CreateForScreen( - *desktop_capture_options_, webrtc::kFullDesktopScreenId)); -#endif return base::WrapUnique(new MouseCursorMonitorProxy( - video_capture_task_runner_, std::move(cursor_monitor))); + video_capture_task_runner_, *desktop_capture_options_)); } std::string BasicDesktopEnvironment::GetCapabilities() const { @@ -81,16 +69,8 @@ BasicDesktopEnvironment::CreateVideoCapturer() { DCHECK(caller_task_runner_->BelongsToCurrentThread()); - std::unique_ptr<webrtc::DesktopCapturer> capturer; - -#if defined(OS_CHROMEOS) - capturer.reset(new AuraDesktopCapturer()); -#else // !defined(OS_CHROMEOS) - capturer.reset(webrtc::ScreenCapturer::Create(*desktop_capture_options_)); -#endif // !defined(OS_CHROMEOS) - return base::WrapUnique(new DesktopCapturerProxy(video_capture_task_runner_, - std::move(capturer))); + *desktop_capture_options_)); } BasicDesktopEnvironment::BasicDesktopEnvironment(
diff --git a/remoting/host/desktop_capturer_proxy.cc b/remoting/host/desktop_capturer_proxy.cc index 897ed50..3faeb6a 100644 --- a/remoting/host/desktop_capturer_proxy.cc +++ b/remoting/host/desktop_capturer_proxy.cc
@@ -15,18 +15,24 @@ #include "base/single_thread_task_runner.h" #include "base/thread_task_runner_handle.h" #include "remoting/proto/control.pb.h" +#include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_frame.h" #include "third_party/webrtc/modules/desktop_capture/desktop_region.h" +#include "third_party/webrtc/modules/desktop_capture/screen_capturer.h" + +#if defined(OS_CHROMEOS) +#include "remoting/host/chromeos/aura_desktop_capturer.h" +#endif namespace remoting { class DesktopCapturerProxy::Core : public webrtc::DesktopCapturer::Callback { public: - Core(base::WeakPtr<DesktopCapturerProxy> proxy, - scoped_refptr<base::SingleThreadTaskRunner> capture_task_runner, - std::unique_ptr<webrtc::DesktopCapturer> capturer); + explicit Core(base::WeakPtr<DesktopCapturerProxy> proxy); ~Core() override; + void CreateCapturer(const webrtc::DesktopCaptureOptions& options); + void Start(); void SetSharedMemoryFactory( std::unique_ptr<webrtc::SharedMemoryFactory> shared_memory_factory); @@ -45,13 +51,8 @@ DISALLOW_COPY_AND_ASSIGN(Core); }; -DesktopCapturerProxy::Core::Core( - base::WeakPtr<DesktopCapturerProxy> proxy, - scoped_refptr<base::SingleThreadTaskRunner> capture_task_runner, - std::unique_ptr<webrtc::DesktopCapturer> capturer) - : proxy_(proxy), - caller_task_runner_(base::ThreadTaskRunnerHandle::Get()), - capturer_(std::move(capturer)) { +DesktopCapturerProxy::Core::Core(base::WeakPtr<DesktopCapturerProxy> proxy) + : proxy_(proxy), caller_task_runner_(base::ThreadTaskRunnerHandle::Get()) { thread_checker_.DetachFromThread(); } @@ -59,21 +60,42 @@ DCHECK(thread_checker_.CalledOnValidThread()); } +void DesktopCapturerProxy::Core::CreateCapturer( + const webrtc::DesktopCaptureOptions& options) { + DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK(!capturer_); + +#if defined(OS_CHROMEOS) + capturer_.reset(new AuraDesktopCapturer()); +#else // !defined(OS_CHROMEOS) + capturer_.reset(webrtc::ScreenCapturer::Create(options)); +#endif // !defined(OS_CHROMEOS) + if (!capturer_) + LOG(ERROR) << "Failed to initialize screen capturer."; +} + void DesktopCapturerProxy::Core::Start() { DCHECK(thread_checker_.CalledOnValidThread()); - capturer_->Start(this); + if (capturer_) + capturer_->Start(this); } void DesktopCapturerProxy::Core::SetSharedMemoryFactory( std::unique_ptr<webrtc::SharedMemoryFactory> shared_memory_factory) { DCHECK(thread_checker_.CalledOnValidThread()); - capturer_->SetSharedMemoryFactory( - rtc_make_scoped_ptr(shared_memory_factory.release())); + if (capturer_) { + capturer_->SetSharedMemoryFactory( + rtc_make_scoped_ptr(shared_memory_factory.release())); + } } void DesktopCapturerProxy::Core::Capture(const webrtc::DesktopRegion& rect) { DCHECK(thread_checker_.CalledOnValidThread()); - capturer_->Capture(rect); + if (capturer_) { + capturer_->Capture(rect); + } else { + OnCaptureCompleted(nullptr); + } } void DesktopCapturerProxy::Core::OnCaptureCompleted( @@ -87,10 +109,12 @@ DesktopCapturerProxy::DesktopCapturerProxy( scoped_refptr<base::SingleThreadTaskRunner> capture_task_runner, - std::unique_ptr<webrtc::DesktopCapturer> capturer) + const webrtc::DesktopCaptureOptions& options) : capture_task_runner_(capture_task_runner), weak_factory_(this) { - core_.reset(new Core(weak_factory_.GetWeakPtr(), capture_task_runner, - std::move(capturer))); + core_.reset(new Core(weak_factory_.GetWeakPtr())); + capture_task_runner_->PostTask( + FROM_HERE, base::Bind(&Core::CreateCapturer, + base::Unretained(core_.get()), options)); } DesktopCapturerProxy::~DesktopCapturerProxy() {
diff --git a/remoting/host/desktop_capturer_proxy.h b/remoting/host/desktop_capturer_proxy.h index 959fc39..df06413 100644 --- a/remoting/host/desktop_capturer_proxy.h +++ b/remoting/host/desktop_capturer_proxy.h
@@ -17,6 +17,10 @@ class SingleThreadTaskRunner; } // namespace base +namespace webrtc { +class DesktopCaptureOptions; +} // namespace webrtc + namespace remoting { namespace protocol { @@ -29,7 +33,7 @@ public: DesktopCapturerProxy( scoped_refptr<base::SingleThreadTaskRunner> capture_task_runner, - std::unique_ptr<webrtc::DesktopCapturer> capturer); + const webrtc::DesktopCaptureOptions& options); ~DesktopCapturerProxy() override; // webrtc::DesktopCapturer interface.
diff --git a/remoting/host/mouse_cursor_monitor_proxy.cc b/remoting/host/mouse_cursor_monitor_proxy.cc index 77d356e..0579d484 100644 --- a/remoting/host/mouse_cursor_monitor_proxy.cc +++ b/remoting/host/mouse_cursor_monitor_proxy.cc
@@ -9,23 +9,31 @@ #include "base/macros.h" #include "base/single_thread_task_runner.h" #include "base/thread_task_runner_handle.h" +#include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_frame.h" #include "third_party/webrtc/modules/desktop_capture/mouse_cursor.h" #include "third_party/webrtc/modules/desktop_capture/mouse_cursor_monitor.h" +#if defined(OS_CHROMEOS) +#include "remoting/host/chromeos/mouse_cursor_monitor_aura.h" +#endif + namespace remoting { class MouseCursorMonitorProxy::Core : public webrtc::MouseCursorMonitor::Callback { public: - Core(base::WeakPtr<MouseCursorMonitorProxy> proxy, - scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner, - std::unique_ptr<webrtc::MouseCursorMonitor> mouse_cursor_monitor); + explicit Core(base::WeakPtr<MouseCursorMonitorProxy> proxy); ~Core() override; + void CreateMouseCursorMonitor(const webrtc::DesktopCaptureOptions& options); + void Init(webrtc::MouseCursorMonitor::Mode mode); void Capture(); + void SetMouseCursorMonitorForTests( + std::unique_ptr<webrtc::MouseCursorMonitor> mouse_cursor_monitor); + private: // webrtc::MouseCursorMonitor::Callback implementation. void OnMouseCursor(webrtc::MouseCursor* mouse_cursor) override; @@ -42,12 +50,8 @@ }; MouseCursorMonitorProxy::Core::Core( - base::WeakPtr<MouseCursorMonitorProxy> proxy, - scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner, - std::unique_ptr<webrtc::MouseCursorMonitor> mouse_cursor_monitor) - : proxy_(proxy), - caller_task_runner_(caller_task_runner), - mouse_cursor_monitor_(std::move(mouse_cursor_monitor)) { + base::WeakPtr<MouseCursorMonitorProxy> proxy) + : proxy_(proxy), caller_task_runner_(base::ThreadTaskRunnerHandle::Get()) { thread_checker_.DetachFromThread(); } @@ -55,17 +59,38 @@ DCHECK(thread_checker_.CalledOnValidThread()); } +void MouseCursorMonitorProxy::Core::CreateMouseCursorMonitor( + const webrtc::DesktopCaptureOptions& options) { + DCHECK(thread_checker_.CalledOnValidThread()); + +#if defined(OS_CHROMEOS) + mouse_cursor_monitor_.reset(new MouseCursorMonitorAura()); +#else // defined(OS_CHROMEOS) + mouse_cursor_monitor_.reset(webrtc::MouseCursorMonitor::CreateForScreen( + options, webrtc::kFullDesktopScreenId)); +#endif // defined(OS_CHROMEOS) + if (!mouse_cursor_monitor_) + LOG(ERROR) << "Failed to initialize MouseCursorMonitor."; +} + void MouseCursorMonitorProxy::Core::Init( webrtc::MouseCursorMonitor::Mode mode) { DCHECK(thread_checker_.CalledOnValidThread()); - mouse_cursor_monitor_->Init(this, mode); + if (mouse_cursor_monitor_) + mouse_cursor_monitor_->Init(this, mode); } void MouseCursorMonitorProxy::Core::Capture() { DCHECK(thread_checker_.CalledOnValidThread()); - mouse_cursor_monitor_->Capture(); + if (mouse_cursor_monitor_) + mouse_cursor_monitor_->Capture(); +} + +void MouseCursorMonitorProxy::Core::SetMouseCursorMonitorForTests( + std::unique_ptr<webrtc::MouseCursorMonitor> mouse_cursor_monitor) { + mouse_cursor_monitor_ = std::move(mouse_cursor_monitor); } void MouseCursorMonitorProxy::Core::OnMouseCursor(webrtc::MouseCursor* cursor) { @@ -89,11 +114,12 @@ MouseCursorMonitorProxy::MouseCursorMonitorProxy( scoped_refptr<base::SingleThreadTaskRunner> capture_task_runner, - std::unique_ptr<webrtc::MouseCursorMonitor> mouse_cursor_monitor) + const webrtc::DesktopCaptureOptions& options) : capture_task_runner_(capture_task_runner), weak_factory_(this) { - core_.reset(new Core(weak_factory_.GetWeakPtr(), - base::ThreadTaskRunnerHandle::Get(), - std::move(mouse_cursor_monitor))); + core_.reset(new Core(weak_factory_.GetWeakPtr())); + capture_task_runner_->PostTask( + FROM_HERE, base::Bind(&Core::CreateMouseCursorMonitor, + base::Unretained(core_.get()), options)); } MouseCursorMonitorProxy::~MouseCursorMonitorProxy() { @@ -113,6 +139,14 @@ FROM_HERE, base::Bind(&Core::Capture, base::Unretained(core_.get()))); } +void MouseCursorMonitorProxy::SetMouseCursorMonitorForTests( + std::unique_ptr<webrtc::MouseCursorMonitor> mouse_cursor_monitor) { + capture_task_runner_->PostTask( + FROM_HERE, base::Bind(&Core::SetMouseCursorMonitorForTests, + base::Unretained(core_.get()), + base::Passed(&mouse_cursor_monitor))); +} + void MouseCursorMonitorProxy::OnMouseCursor( std::unique_ptr<webrtc::MouseCursor> cursor) { DCHECK(thread_checker_.CalledOnValidThread());
diff --git a/remoting/host/mouse_cursor_monitor_proxy.h b/remoting/host/mouse_cursor_monitor_proxy.h index d583f70..916c2a1c 100644 --- a/remoting/host/mouse_cursor_monitor_proxy.h +++ b/remoting/host/mouse_cursor_monitor_proxy.h
@@ -16,19 +16,26 @@ class SingleThreadTaskRunner; } // namespace base +namespace webrtc { +class DesktopCaptureOptions; +} // namespace webrtc + namespace remoting { class MouseCursorMonitorProxy : public webrtc::MouseCursorMonitor { public: MouseCursorMonitorProxy( scoped_refptr<base::SingleThreadTaskRunner> capture_task_runner, - std::unique_ptr<webrtc::MouseCursorMonitor> mouse_cursor_monitor); + const webrtc::DesktopCaptureOptions& options); ~MouseCursorMonitorProxy() override; // webrtc::MouseCursorMonitor interface. void Init(Callback* callback, Mode mode) override; void Capture() override; + void SetMouseCursorMonitorForTests( + std::unique_ptr<webrtc::MouseCursorMonitor> mouse_cursor_monitor); + private: class Core;
diff --git a/remoting/host/mouse_cursor_monitor_proxy_unittest.cc b/remoting/host/mouse_cursor_monitor_proxy_unittest.cc index d27a6c94..fee618d 100644 --- a/remoting/host/mouse_cursor_monitor_proxy_unittest.cc +++ b/remoting/host/mouse_cursor_monitor_proxy_unittest.cc
@@ -16,6 +16,7 @@ #include "remoting/protocol/protocol_mock_objects.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_frame.h" #include "third_party/webrtc/modules/desktop_capture/mouse_cursor.h" #include "third_party/webrtc/modules/desktop_capture/mouse_cursor_monitor.h" @@ -119,12 +120,12 @@ } TEST_F(MouseCursorMonitorProxyTest, CursorShape) { - std::unique_ptr<ThreadCheckMouseCursorMonitor> cursor_monitor( - new ThreadCheckMouseCursorMonitor(capture_thread_.task_runner())); - // Initialize the proxy. - proxy_.reset(new MouseCursorMonitorProxy(capture_thread_.task_runner(), - std::move(cursor_monitor))); + proxy_.reset(new MouseCursorMonitorProxy( + capture_thread_.task_runner(), + webrtc::DesktopCaptureOptions::CreateDefault())); + proxy_->SetMouseCursorMonitorForTests(base::WrapUnique( + new ThreadCheckMouseCursorMonitor(capture_thread_.task_runner()))); proxy_->Init(this, webrtc::MouseCursorMonitor::SHAPE_ONLY); proxy_->Capture();
diff --git a/services/catalog/entry.cc b/services/catalog/entry.cc index def30aa6..c501bfa 100644 --- a/services/catalog/entry.cc +++ b/services/catalog/entry.cc
@@ -200,6 +200,10 @@ return entry; } +bool Entry::ProvidesClass(const std::string& clazz) const { + return capabilities_.provided.find(clazz) != capabilities_.provided.end(); +} + bool Entry::operator==(const Entry& other) const { return other.name_ == name_ && other.qualifier_ == qualifier_ && other.display_name_ == display_name_ && @@ -231,4 +235,14 @@ return result; } +// static +catalog::mojom::EntryPtr + TypeConverter<catalog::mojom::EntryPtr, catalog::Entry>::Convert( + const catalog::Entry& input) { + catalog::mojom::EntryPtr result(catalog::mojom::Entry::New()); + result->name = input.name(); + result->display_name = input.display_name(); + return result; +} + } // namespace mojo
diff --git a/services/catalog/entry.h b/services/catalog/entry.h index 6d382e6b..0923b40 100644 --- a/services/catalog/entry.h +++ b/services/catalog/entry.h
@@ -10,6 +10,7 @@ #include "base/files/file_path.h" #include "base/memory/scoped_ptr.h" +#include "services/catalog/public/interfaces/entry.mojom.h" #include "services/shell/public/cpp/capabilities.h" namespace base { @@ -33,6 +34,8 @@ // applications(). static scoped_ptr<Entry> Deserialize(const base::DictionaryValue& value); + bool ProvidesClass(const std::string& clazz) const; + bool operator==(const Entry& other) const; bool operator<(const Entry& other) const; @@ -71,6 +74,12 @@ struct TypeConverter<shell::mojom::ResolveResultPtr, catalog::Entry> { static shell::mojom::ResolveResultPtr Convert(const catalog::Entry& input); }; -} + +template<> +struct TypeConverter<catalog::mojom::EntryPtr, catalog::Entry> { + static catalog::mojom::EntryPtr Convert(const catalog::Entry& input); +}; + +} // namespace mojo #endif // SERVICES_CATALOG_ENTRY_H_
diff --git a/services/catalog/manifest.json b/services/catalog/manifest.json index 770cc26..2ae1be8 100644 --- a/services/catalog/manifest.json +++ b/services/catalog/manifest.json
@@ -1,7 +1,7 @@ { "manifest_version": 1, "name": "mojo:catalog", - "display_name": "Catalog", + "display_name": "Application Resolver", "capabilities": { "required": { "mojo:shell": { "classes": [ "all_users" ] }
diff --git a/services/catalog/public/interfaces/BUILD.gn b/services/catalog/public/interfaces/BUILD.gn index 1c0d6af6..0a694af 100644 --- a/services/catalog/public/interfaces/BUILD.gn +++ b/services/catalog/public/interfaces/BUILD.gn
@@ -7,6 +7,7 @@ mojom("interfaces") { sources = [ "catalog.mojom", + "entry.mojom", "resolver.mojom", ] }
diff --git a/services/catalog/public/interfaces/catalog.mojom b/services/catalog/public/interfaces/catalog.mojom index ab95fa0..f445881 100644 --- a/services/catalog/public/interfaces/catalog.mojom +++ b/services/catalog/public/interfaces/catalog.mojom
@@ -4,11 +4,9 @@ module catalog.mojom; -struct CatalogEntry { - string display_name; -}; +import "services/catalog/public/interfaces/entry.mojom"; interface Catalog { // If |names| is null, all available entries are returned. - GetEntries(array<string>? names) => (map<string, CatalogEntry> entries); + GetEntries(array<string>? names) => (array<Entry> entries); };
diff --git a/services/catalog/public/interfaces/entry.mojom b/services/catalog/public/interfaces/entry.mojom new file mode 100644 index 0000000..fbd2bb1 --- /dev/null +++ b/services/catalog/public/interfaces/entry.mojom
@@ -0,0 +1,10 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module catalog.mojom; + +struct Entry { + string name; + string display_name; +};
diff --git a/services/catalog/public/interfaces/resolver.mojom b/services/catalog/public/interfaces/resolver.mojom index 0faf7e1..9ddd0b4 100644 --- a/services/catalog/public/interfaces/resolver.mojom +++ b/services/catalog/public/interfaces/resolver.mojom
@@ -4,12 +4,14 @@ module catalog.mojom; +import "services/catalog/public/interfaces/entry.mojom"; + // Resolves various things to Mojo names that can be passed to mojo::Shell's // ConnectToApplication(). interface Resolver { - // Returns the mojo: name of the service that exports to the caller every - // interface in |interfaces|. - ResolveInterfaces(array<string> interfaces) => (string resolved_mojo_name); + // Returns the entry(ies) for applications that export to the caller the + // specified class. + ResolveClass(string clazz) => (array<Entry> entries); // Returns the mojo: name of the service that will handle content of type // |mime_type|.
diff --git a/services/catalog/resolver.cc b/services/catalog/resolver.cc index 255e28b..c729fafb 100644 --- a/services/catalog/resolver.cc +++ b/services/catalog/resolver.cc
@@ -14,11 +14,11 @@ namespace catalog { namespace { -void AddEntryToMap(const Entry& entry, - mojo::Map<mojo::String, mojom::CatalogEntryPtr>* map) { - mojom::CatalogEntryPtr entry_ptr(mojom::CatalogEntry::New()); +void AddEntry(const Entry& entry, mojo::Array<mojom::EntryPtr>* ary) { + mojom::EntryPtr entry_ptr(mojom::Entry::New()); + entry_ptr->name = entry.name(); entry_ptr->display_name = entry.display_name(); - (*map)[entry.name()] = std::move(entry_ptr); + ary->push_back(std::move(entry_ptr)); } } // namespace @@ -68,9 +68,13 @@ //////////////////////////////////////////////////////////////////////////////// // Resolver, mojom::Resolver: -void Resolver::ResolveInterfaces(mojo::Array<mojo::String> interfaces, - const ResolveInterfacesCallback& callback) { - // TODO(beng): implement. +void Resolver::ResolveClass(const mojo::String& clazz, + const ResolveClassCallback& callback) { + mojo::Array<mojom::EntryPtr> entries; + for (const auto& entry : *system_catalog_) + if (entry.second->ProvidesClass(clazz)) + entries.push_back(mojom::Entry::From(*entry.second)); + callback.Run(std::move(entries)); } void Resolver::ResolveMIMEType(const mojo::String& mime_type, @@ -120,11 +124,11 @@ const GetEntriesCallback& callback) { DCHECK(system_catalog_); - mojo::Map<mojo::String, mojom::CatalogEntryPtr> entries; + mojo::Array<mojom::EntryPtr> entries; if (names.is_null()) { // TODO(beng): user catalog. for (const auto& entry : *system_catalog_) - AddEntryToMap(*entry.second, &entries); + AddEntry(*entry.second, &entries); } else { std::vector<mojo::String> names_vec = names.PassStorage(); for (const std::string& name : names_vec) { @@ -134,7 +138,7 @@ entry = (*system_catalog_)[name].get(); else continue; - AddEntryToMap(*entry, &entries); + AddEntry(*entry, &entries); } } callback.Run(std::move(entries));
diff --git a/services/catalog/resolver.h b/services/catalog/resolver.h index ba2de87..3f284a3 100644 --- a/services/catalog/resolver.h +++ b/services/catalog/resolver.h
@@ -43,8 +43,8 @@ std::map<std::string, std::pair<std::string, std::string>>; // mojom::Resolver: - void ResolveInterfaces(mojo::Array<mojo::String> interfaces, - const ResolveInterfacesCallback& callback) override; + void ResolveClass(const mojo::String& clazz, + const ResolveClassCallback& callback) override; void ResolveMIMEType(const mojo::String& mime_type, const ResolveMIMETypeCallback& callback) override; void ResolveProtocolScheme(
diff --git a/services/shell/manifest.json b/services/shell/manifest.json index 24a6f77..d3303f9 100644 --- a/services/shell/manifest.json +++ b/services/shell/manifest.json
@@ -1,7 +1,7 @@ { "manifest_version": 1, "name": "mojo:shell", - "display_name": "Shell", + "display_name": "Service Manager", "capabilities": { "provided": { "user_id": [ ],
diff --git a/services/shell/runner/host/child_process_host.cc b/services/shell/runner/host/child_process_host.cc index 85f5920..7ded376c 100644 --- a/services/shell/runner/host/child_process_host.cc +++ b/services/shell/runner/host/child_process_host.cc
@@ -125,6 +125,7 @@ } else { LOG(ERROR) << "Failed to start child process"; mojo_ipc_channel_.reset(); + callback.Run(base::kNullProcessId); } }
diff --git a/services/shell/shell.cc b/services/shell/shell.cc index a542ae4..659f24b3 100644 --- a/services/shell/shell.cc +++ b/services/shell/shell.cc
@@ -120,7 +120,7 @@ allow_any_application_(capability_spec.required.count("*") == 1), pid_receiver_binding_(this), weak_factory_(this) { - if (identity_.name() == kShellName) + if (identity_.name() == kShellName || identity_.name() == kCatalogName) pid_ = base::Process::Current().Pid(); DCHECK_NE(mojom::kInvalidInstanceID, id_); } @@ -376,6 +376,10 @@ } void PIDAvailable(base::ProcessId pid) { + if (pid == base::kNullProcessId) { + shell_->OnInstanceError(this); + return; + } pid_ = pid; shell_->NotifyPIDAvailable(id_, pid_); }
diff --git a/services/shell/shell.gyp b/services/shell/shell.gyp index beb82ac5..9163435 100644 --- a/services/shell/shell.gyp +++ b/services/shell/shell.gyp
@@ -9,6 +9,7 @@ 'variables': { 'mojom_files': [ '../catalog/public/interfaces/catalog.mojom', + '../catalog/public/interfaces/entry.mojom', '../catalog/public/interfaces/resolver.mojom', 'public/interfaces/capabilities.mojom', 'public/interfaces/connector.mojom',
diff --git a/skia/PRESUBMIT.py b/skia/PRESUBMIT.py deleted file mode 100644 index 6ba31dc..0000000 --- a/skia/PRESUBMIT.py +++ /dev/null
@@ -1,16 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Top-level presubmit script for skia/ - -See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts -for more details about the presubmit API built into depot_tools. -""" - -def GetPreferredTryMasters(project, change): - return { - 'tryserver.blink': { - 'linux_blink_rel': set(['defaulttests']), - }, - }
diff --git a/skia/config/SkUserConfig.h b/skia/config/SkUserConfig.h index 72920b15..3e42d05 100644 --- a/skia/config/SkUserConfig.h +++ b/skia/config/SkUserConfig.h
@@ -218,10 +218,6 @@ # define SK_SUPPORT_LEGACY_ANISOTROPIC_MIPMAP_SCALE #endif -#ifndef SK_SUPPORT_LEGACY_REFENCODEDDATA_NOCTX -# define SK_SUPPORT_LEGACY_REFENCODEDDATA_NOCTX -#endif - #ifndef SK_IGNORE_ETC1_SUPPORT # define SK_IGNORE_ETC1_SUPPORT #endif
diff --git a/sql/BUILD.gn b/sql/BUILD.gn index b2ca6384..00b7ff6 100644 --- a/sql/BUILD.gn +++ b/sql/BUILD.gn
@@ -72,7 +72,7 @@ bundle_data("sql_unittests_bundle_data") { testonly = true sources = [ - "test/data", + "test/data/recovery_387868", ] outputs = [ "{{bundle_resources_dir}}/" +
diff --git a/sync/engine/model_type_worker.cc b/sync/engine/model_type_worker.cc index 4b1d2f7e..a34b94c 100644 --- a/sync/engine/model_type_worker.cc +++ b/sync/engine/model_type_worker.cc
@@ -237,8 +237,8 @@ sync_pb::SyncEntity* commit_entity = commit_entities.Add(); int64_t sequence_number = -1; - entity->PrepareCommitProto(commit_entity, &sequence_number); - HelpInitializeCommitEntity(commit_entity); + entity->PopulateCommitProto(commit_entity, &sequence_number); + AdjustCommitProto(commit_entity); sequence_numbers.push_back(sequence_number); space_remaining--; @@ -301,13 +301,12 @@ return true; } -void ModelTypeWorker::HelpInitializeCommitEntity( - sync_pb::SyncEntity* sync_entity) { +void ModelTypeWorker::AdjustCommitProto(sync_pb::SyncEntity* sync_entity) { DCHECK(CanCommitItems()); // Initial commits need our help to generate a client ID. - if (!sync_entity->has_id_string()) { - DCHECK_EQ(kUncommittedVersion, sync_entity->version()); + if (sync_entity->version() == kUncommittedVersion) { + DCHECK(!sync_entity->has_id_string()); // TODO(stanisc): This is incorrect for bookmarks for two reasons: // 1) Won't be able to match previously committed bookmarks to the ones // with server ID. @@ -316,6 +315,9 @@ // would result in a duplication. // We should generate client ID on the frontend side instead. sync_entity->set_id_string(base::GenerateGUID()); + sync_entity->set_version(0); + } else { + DCHECK(sync_entity->has_id_string()); } // Encrypt the specifics and hide the title if necessary.
diff --git a/sync/engine/model_type_worker.h b/sync/engine/model_type_worker.h index 2fcc9a4..fae02f0 100644 --- a/sync/engine/model_type_worker.h +++ b/sync/engine/model_type_worker.h
@@ -113,11 +113,10 @@ // settings in a good state. bool CanCommitItems() const; - // Initializes the parts of a commit entity that are the responsibility of - // this class, and not the WorkerEntityTracker. Some fields, like the - // client-assigned ID, can only be set by an entity with knowledge of the - // entire data type's state. - void HelpInitializeCommitEntity(sync_pb::SyncEntity* commit_entity); + // Takes |commit_entity| populated from fields of WorkerEntityTracker and + // adjusts some fields before committing to server. Adjustments include + // generating client-assigned ID, encrypting data, etc. + void AdjustCommitProto(sync_pb::SyncEntity* commit_entity); // Attempts to decrypt encrypted updates stored in the EntityMap. If // successful, will remove the update from the its tracker and forward
diff --git a/sync/engine/model_type_worker_unittest.cc b/sync/engine/model_type_worker_unittest.cc index 8cca17ce..edcc3af51 100644 --- a/sync/engine/model_type_worker_unittest.cc +++ b/sync/engine/model_type_worker_unittest.cc
@@ -698,7 +698,7 @@ ASSERT_TRUE(HasCommitEntityOnServer("tag1")); const sync_pb::SyncEntity& entity = GetLatestCommitEntityOnServer("tag1"); EXPECT_FALSE(entity.id_string().empty()); - EXPECT_EQ(kUncommittedVersion, entity.version()); + EXPECT_EQ(0, entity.version()); EXPECT_NE(0, entity.mtime()); EXPECT_NE(0, entity.ctime()); EXPECT_FALSE(entity.name().empty());
diff --git a/sync/engine/worker_entity_tracker.cc b/sync/engine/worker_entity_tracker.cc index b8049fb..3bcf710 100644 --- a/sync/engine/worker_entity_tracker.cc +++ b/sync/engine/worker_entity_tracker.cc
@@ -31,8 +31,9 @@ return !!pending_commit_; } -void WorkerEntityTracker::PrepareCommitProto(sync_pb::SyncEntity* commit_entity, - int64_t* sequence_number) const { +void WorkerEntityTracker::PopulateCommitProto( + sync_pb::SyncEntity* commit_entity, + int64_t* sequence_number) const { DCHECK(HasPendingCommit()); DCHECK(!client_tag_hash_.empty());
diff --git a/sync/engine/worker_entity_tracker.h b/sync/engine/worker_entity_tracker.h index 0f3a337f..fd8645a7 100644 --- a/sync/engine/worker_entity_tracker.h +++ b/sync/engine/worker_entity_tracker.h
@@ -45,8 +45,8 @@ // Populates a sync_pb::SyncEntity for a commit. Also sets the // |sequence_number|, so we can track it throughout the commit process. - void PrepareCommitProto(sync_pb::SyncEntity* commit_entity, - int64_t* sequence_number) const; + void PopulateCommitProto(sync_pb::SyncEntity* commit_entity, + int64_t* sequence_number) const; // Updates this entity with data from the latest version that the // model asked us to commit. May clobber state related to the
diff --git a/sync/engine/worker_entity_tracker_unittest.cc b/sync/engine/worker_entity_tracker_unittest.cc index 93f7f44..5bc4e00 100644 --- a/sync/engine/worker_entity_tracker_unittest.cc +++ b/sync/engine/worker_entity_tracker_unittest.cc
@@ -97,7 +97,7 @@ ASSERT_TRUE(entity_->HasPendingCommit()); sync_pb::SyncEntity pb_entity; int64_t sequence_number = 0; - entity_->PrepareCommitProto(&pb_entity, &sequence_number); + entity_->PopulateCommitProto(&pb_entity, &sequence_number); EXPECT_EQ(kSequenceNumber, sequence_number); EXPECT_EQ(kServerId, pb_entity.id_string()); EXPECT_EQ(kClientTagHash, pb_entity.client_defined_unique_tag());
diff --git a/testing/libfuzzer/clusterfuzz.md b/testing/libfuzzer/clusterfuzz.md index b8e785e8..513b45ea 100644 --- a/testing/libfuzzer/clusterfuzz.md +++ b/testing/libfuzzer/clusterfuzz.md
@@ -13,6 +13,7 @@ * [Buildbot] - status of all libFuzzer builds. * [ClusterFuzz Fuzzer Status] - fuzzing metrics, links to crashes and coverage reports. +* [ClusterFuzz libFuzzer Logs] - individual fuzzer run logs. * [Corpus GCS Bucket] - current corpus for each fuzzer. Can be used to upload bootstrapped corpus. @@ -25,6 +26,7 @@ builds fuzzers with multiple sanitizers and uploads binaries to a special GCS bucket. Build bot recipe is defined in [chromium_libfuzzer.py]. * ClusterFuzz downloads new binaries once a day and runs fuzzers continuously. +* Fuzzer run logs are uploaded to [ClusterFuzz libFuzzer Logs] GCS bucket. * Fuzzing corpus is maintained for each fuzzer in [Corpus GCS Bucket]. Once a day corpus is minimized to reduce number of duplicates and/or reduce effect of parasitic coverage. @@ -37,4 +39,5 @@ [fuzzer_test.gni]: https://code.google.com/p/chromium/codesearch#chromium/src/testing/libfuzzer/fuzzer_test.gni [chromium_libfuzzer.py]: https://code.google.com/p/chromium/codesearch#chromium/build/scripts/slave/recipes/chromium_libfuzzer.py [ClusterFuzz Fuzzer Status]: https://goto.google.com/libfuzzer-clusterfuzz-status +[ClusterFuzz libFuzzer Logs]: https://goto.google.com/libfuzzer-clusterfuzz-logs [Corpus GCS Bucket]: https://goto.google.com/libfuzzer-clusterfuzz-corpus
diff --git a/testing/libfuzzer/getting_started.md b/testing/libfuzzer/getting_started.md index 8a27979..4ddbb2c 100644 --- a/testing/libfuzzer/getting_started.md +++ b/testing/libfuzzer/getting_started.md
@@ -25,6 +25,7 @@ |--------------|----| | is_asan=true | enables [Address Sanitizer] to catch problems like buffer overruns. | | is_msan=true | enables [Memory Sanitizer] to catch problems like uninitialed reads. | +| is_ubsan_security=true | enables [Undefined Behavior Sanitizer] to catch undefined behavior like integer overflow. | ## Write Fuzzer Function @@ -102,6 +103,7 @@ [Address Sanitizer]: http://clang.llvm.org/docs/AddressSanitizer.html [Memory Sanitizer]: http://clang.llvm.org/docs/MemorySanitizer.html +[Undefined Behavior Sanitizer]: http://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html [url_parse_fuzzer.cc]: https://code.google.com/p/chromium/codesearch#chromium/src/testing/libfuzzer/fuzzers/url_parse_fuzzer.cc [ClusterFuzz status]: clusterfuzz.md#Status-Links [Efficient Fuzzer Guide]: efficient_fuzzer.md
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/site-per-process b/third_party/WebKit/LayoutTests/FlagExpectations/site-per-process index 93c07fd..32afaaa1 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/site-per-process +++ b/third_party/WebKit/LayoutTests/FlagExpectations/site-per-process
@@ -1,25 +1,28 @@ # These tests currently fail when they run with --site-per-process. # See https://crbug.com/477150. -# https://crbug.com/584984 - Recent, uninvestigated yet regression. -http/tests/security/opened-document-security-origin-resets-on-navigation.html [ Crash ] - # https://crbug.com/582494 - [sigsegv / av] blink::Document::styleEngine. http/tests/security/mixedContent/insecure-plugin-in-iframe.html [ Crash ] -# Uninvestigated failures (https://crbug.com/495132 is fixed): -http/tests/history/cross-origin-redirect-on-back.html [ Timeout Crash ] +# https://crbug.com/602818 - Incorrect process transfer for blob URL +http/tests/fileapi/blob-url-in-subframe.html [ Timeout ] + +# https://crbug.com/584984 - Check failed: bindings_ == kInvalidBindings || bindings_ == bindings http/tests/inspector-enabled/console-log-before-frame-navigation.html [ Crash ] http/tests/inspector/change-iframe-src.html [ Crash ] http/tests/navigation/cross-origin-fragment-navigation-is-async.html [ Crash Failure ] -http/tests/security/cross-frame-access-document-direct.html [ Crash Timeout ] http/tests/security/frameNavigation/xss-ALLOWED-targeted-subframe-navigation-change.html [ Crash Timeout ] -http/tests/security/referrer-policy-origin-when-crossorigin-is-crossorigin.html [ Crash Timeout ] -http/tests/security/xssAuditor/anchor-url-dom-write-location-inline-event.html [ Crash ] +http/tests/security/opened-document-security-origin-resets-on-navigation.html [ Crash ] http/tests/security/xssAuditor/anchor-url-dom-write-location-inline-event-null-char.html [ Crash Timeout ] +http/tests/security/xssAuditor/anchor-url-dom-write-location-inline-event.html [ Crash ] http/tests/security/xssAuditor/dom-write-location-inline-event.html [ Crash ] http/tests/serviceworker/windowclient-navigate.html [ Crash ] +# Uninvestigated timeouts (possibly variants of https://crbug.com/584984) +http/tests/history/cross-origin-redirect-on-back.html [ Timeout Crash ] +http/tests/security/cross-frame-access-document-direct.html [ Crash Timeout ] +http/tests/security/referrer-policy-origin-when-crossorigin-is-crossorigin.html [ Crash Timeout ] + # https://crbug.com/582289 - dumpResourceLoadCallbacks test flag is not replicated into OOPIFs. http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny.html [ Failure ] @@ -50,9 +53,6 @@ http/tests/security/xssAuditor/full-block-post-from-iframe.html [ Failure ] http/tests/security/xssAuditor/xss-protection-parsing-01.html [ Failure ] -# https://crbug.com/582522 - extra mixedContent checks reported with --site-per-process -http/tests/security/mixedContent/insecure-iframe-in-iframe.html [ Failure ] - # https://crbug.com/582176 - InspectorTest.changeExecutionContext doesn't like OOPIFs. http/tests/inspector/console-cd-completions.html [ Failure ] http/tests/inspector/console-cd.html [ Failure ] @@ -60,13 +60,15 @@ # https://crbug.com/554119 - Popup menu is in the wrong location. http/tests/webfont/popup-menu-load-webfont-after-open.html [ Failure ] -# https://crbug.com/582525 - testRunner.setAllowDisplayOfInsecureContent is not replicated to OOPIFs. -http/tests/security/mixedContent/active-subresource-in-http-iframe-not-blocked.https.html [ Failure Timeout ] +# https://crbug.com/602493 - Layout tests harness doesn't support history dump across OOPIFs +http/tests/security/mixedContent/insecure-iframe-in-main-frame.html [ Crash ] + +# https://crbug.com/582522 - extra mixedContent checks reported with --site-per-process +# https://crbug.com/602497 - Inconsistent console messages about mixed content, +# when running with or without --site-per-process +http/tests/security/mixedContent/active-subresource-in-http-iframe-not-blocked.https.html [ Failure ] +http/tests/security/mixedContent/insecure-iframe-in-iframe.html [ Failure ] http/tests/security/mixedContent/insecure-iframe-in-main-frame-allowed.html [ Failure ] -http/tests/security/mixedContent/insecure-iframe-in-main-frame.html [ Failure Crash ] -http/tests/security/mixedContent/insecure-image-in-main-frame-allowed.html [ Failure ] -http/tests/security/mixedContent/insecure-script-in-main-frame-allowed.html [ Failure ] -http/tests/security/referrer-policy-conflicting-policies.html [ Failure ] # https://crbug.com/585171 - iframe restored from history should be excluded from performance entries. http/tests/misc/resource-timing-iframe-restored-from-history.html [ Failure Timeout ]
diff --git a/third_party/WebKit/LayoutTests/MSANExpectations b/third_party/WebKit/LayoutTests/MSANExpectations index 5cd87e1..8dd3cdb 100644 --- a/third_party/WebKit/LayoutTests/MSANExpectations +++ b/third_party/WebKit/LayoutTests/MSANExpectations
@@ -21,6 +21,13 @@ crbug.com/420606 [ Linux ] virtual/slimmingpaint/fast/workers/worker-constructor.html [ Skip ] crbug.com/420606 [ Linux ] virtual/sharedarraybuffer/fast/workers/worker-constructor.html [ Skip ] +# heap-use-after-free in bluethooth notifications tests. http://crbug.com/604318 +crbug.com/604318 bluetooth/notifications/concurrent-starts.html [ Skip ] +crbug.com/604318 bluetooth/notifications/start-before-stop-resolves.html [ Skip ] +crbug.com/604318 bluetooth/notifications/add-listener-after-promise.html [ Skip ] +crbug.com/604318 bluetooth/notifications/gc-with-pending-start.html [ Skip ] +crbug.com/604318 bluetooth/notifications/start-twice-in-a-row.html [ Skip ] +crbug.com/604318 bluetooth/notifications/start-succeeds.html [ Skip ] # Flaky under MSan (hang forever). crbug.com/422982 [ Linux ] virtual/threaded [ Skip ]
diff --git a/third_party/WebKit/LayoutTests/PRESUBMIT.py b/third_party/WebKit/LayoutTests/PRESUBMIT.py index de31265..12ebecc4 100644 --- a/third_party/WebKit/LayoutTests/PRESUBMIT.py +++ b/third_party/WebKit/LayoutTests/PRESUBMIT.py
@@ -36,19 +36,14 @@ dirty_files = set(input_api.LocalPaths()) groups = [[ + 'imported/web-platform-tests/resources/testharness.js', 'resources/testharness.js', - 'http/tests/resources/testharness.js', - 'http/tests/w3c/resources/testharness.js', ], [ + 'imported/web-platform-tests/resources/testharnessreport.js', 'resources/testharnessreport.js', - 'http/tests/resources/testharnessreport.js', - 'http/tests/w3c/resources/testharnessreport.js', ], [ + 'imported/web-platform-tests/resources/idlharness.js', 'resources/idlharness.js', - 'http/tests/w3c/resources/idlharness.js', - ], [ - 'resources/WebIDLParser.js', - 'http/tests/w3c/resources/WebIDLParser.js', ], [ 'resources/testharness-helpers.js', 'http/tests/resources/testharness-helpers.js',
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index 49d0d384..b1f22232 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -514,7 +514,6 @@ # expectation files. The following tests with [ Failure ] don't have failure # expectation files because they contain local path names. # Use crbug.com/490511 for untriaged failures. -crbug.com/490511 imported/web-platform-tests/dom/nodes/Document-contentType/contentType/contenttype_txt.html [ Timeout ] crbug.com/490511 [ Linux Win ] imported/web-platform-tests/html/rendering/bindings/the-input-element-as-a-text-entry-widget/unrecognized-type-should-fallback-as-text-type.html [ Failure ] crbug.com/526898 imported/web-platform-tests/html/rendering/non-replaced-elements/phrasing-content-0/font-element-text-decoration-color/001-x.xhtml [ Failure ] crbug.com/108417 imported/web-platform-tests/html/rendering/non-replaced-elements/tables/table-border-1.html [ Failure ] @@ -1258,7 +1257,7 @@ crbug.com/577380 [ Linux Debug ] http/tests/serviceworker/chromium/registration-stress.html [ Failure ] crbug.com/581038 fast/text/first-letter-bad-line-boxes-crash.html [ Crash Pass ] - +crbug.com/442484 fast/forms/range/range-appearance-basic.html [ NeedsManualRebaseline ] crbug.com/587136 [ Linux Debug ] http/tests/security/xss-DENIED-cross-origin-stack-overflow.html [ Timeout Pass ] crbug.com/587593 [ Android ] fast/js/pic/cached-single-entry-transition.html [ Pass Failure ]
diff --git a/third_party/WebKit/LayoutTests/css3/device-adapt/viewport-user-agent-style.html b/third_party/WebKit/LayoutTests/css3/device-adapt/viewport-user-agent-style.html index a4830f0..3fe504c 100644 --- a/third_party/WebKit/LayoutTests/css3/device-adapt/viewport-user-agent-style.html +++ b/third_party/WebKit/LayoutTests/css3/device-adapt/viewport-user-agent-style.html
@@ -7,7 +7,6 @@ <script> if (window.testRunner) { internals.settings.setViewportEnabled(true); - internals.settings.setUseMobileViewportStyle(true); } </script> <style> @@ -18,8 +17,14 @@ <div id="log"></div> <script> test(function(){ + internals.settings.setViewportStyle("mobile"); assert_equals(document.body.offsetWidth, 980); - }, "Check that we get a viewport width of 980px from the user agent stylesheet."); + }, "Check that we get a viewport width of 980px from viewportAndroid.css."); + + test(function(){ + internals.settings.setViewportStyle("television"); + assert_equals(document.body.offsetWidth, 1280); + }, "Check that we get a viewport width of 1280px from viewportTelevision.css."); </script> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-liveness-expected.html b/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-liveness-expected.html index f917dad3..e35800e 100644 --- a/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-liveness-expected.html +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-liveness-expected.html
@@ -5,5 +5,5 @@ ctx.fillStyle = '#0f0'; ctx.fillRect(25, 25, 50, 40); ctx.fillStyle = '#000'; -ctx.fillRect(25, 65, 50, 10); +ctx.fillRect(25, 65, 50, 5); </script>
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-modified-expected.html b/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-modified-expected.html index 84ab00e2..b40e54a 100644 --- a/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-modified-expected.html +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-modified-expected.html
@@ -12,9 +12,10 @@ <script> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); -ctx.filter = 'url(#blurX)'; +ctx.font = '20px sans-serif'; +ctx.filter = 'drop-shadow(0em 1em green) url(#blurX)'; ctx.fillStyle = '#0f0'; ctx.fillRect(20, 20, 20, 20); -ctx.filter = 'url(#blurY)'; +ctx.filter = 'drop-shadow(0em 1em green) url(#blurY)'; ctx.fillRect(60, 20, 20, 20); </script>
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-modified.html b/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-modified.html index 76cb332..3f67331 100644 --- a/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-modified.html +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-modified.html
@@ -9,9 +9,11 @@ <script> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); -ctx.filter = 'url(#blur)'; +ctx.font = '20px sans-serif'; +ctx.filter = 'drop-shadow(0em 1em green) url(#blur)'; ctx.fillStyle = '#0f0'; ctx.fillRect(20, 20, 20, 20); +ctx.font = '30px sans-serif'; document.getElementById('blurElement').setAttribute('stdDeviation', '0, 5'); ctx.fillRect(60, 20, 20, 20); </script>
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-units-em-liveness-expected.html b/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-units-em-liveness-expected.html index 2e59060..54f88906 100644 --- a/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-units-em-liveness-expected.html +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-units-em-liveness-expected.html
@@ -3,5 +3,6 @@ var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.fillStyle = 'green'; -ctx.fillRect(25, 25, 50, 50); +ctx.fillRect(25, 25, 25, 50); +ctx.fillRect(60, 25, 25, 50); </script>
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-units-em-liveness.html b/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-units-em-liveness.html index c791bf90..ce7279f 100644 --- a/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-units-em-liveness.html +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-filter-units-em-liveness.html
@@ -4,8 +4,9 @@ var ctx = canvas.getContext('2d'); ctx.font = '20px sans-serif'; ctx.filter = 'drop-shadow(0em 1em green)'; +ctx.font = '5px sans-serif'; ctx.fillStyle = 'green'; ctx.fillRect(25, 25, 25, 30); ctx.font = '10px sans-serif'; -ctx.fillRect(50, 25, 25, 40); +ctx.fillRect(60, 25, 25, 30); </script>
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-hit-regions-event-test.html b/third_party/WebKit/LayoutTests/fast/canvas/canvas-hit-regions-event-test.html index d970e785..93947520 100644 --- a/third_party/WebKit/LayoutTests/fast/canvas/canvas-hit-regions-event-test.html +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-hit-regions-event-test.html
@@ -109,10 +109,8 @@ { type: 'mousemove', target: button, region: 'button' }, { type: 'mousedown', target: button, region: 'button' }, { type: 'mouseup', target: button, region: 'button' }, - // TODO(zino): The expected value of region should be "button" instead of - // null in case of mouseout/mouseleave. Please see http://crbug.com/592992. - { type: 'mouseout', target: button, region: null }, - { type: 'mouseleave', target: button, region: null }, + { type: 'mouseout', target: button, region: 'button' }, + { type: 'mouseleave', target: button, region: 'button' }, { type: 'touchstart', target: button, region: 'button' }, { type: 'touchend', target: button, region: 'button' }, ]; @@ -147,6 +145,53 @@ }, 'Rerouting mouse/touch event test'); async_test(function() { + context.rect(1, 1, 50, 50); + context.fill(); + context.addHitRegion({ control: button }); + + var expected = [ + { type: 'mouseover', target: button, region: null }, + { type: 'mouseenter', target: button, region: null }, + { type: 'mousemove', target: button, region: null }, + { type: 'mousemove', target: button, region: null }, + { type: 'mousedown', target: button, region: null }, + { type: 'mouseup', target: button, region: null }, + { type: 'mouseout', target: button, region: null }, + { type: 'mouseleave', target: button, region: null }, + { type: 'touchstart', target: button, region: null }, + { type: 'touchend', target: button, region: null }, + ]; + var actual = []; + + button.addEventListener('mouseover', e => actual.push(e)); + button.addEventListener('mouseenter', e => actual.push(e)); + button.addEventListener('mousemove', e => actual.push(e)); + button.addEventListener('mousedown', e => actual.push(e)); + button.addEventListener('mouseup', e => actual.push(e)); + button.addEventListener('mouseout', e => actual.push(e)); + button.addEventListener('mouseleave', e => actual.push(e)); + button.addEventListener('touchstart', e => actual.push(e)); + button.addEventListener('touchend', e => actual.push(e)); + + if (eventSender) { + eventSender.mouseMoveTo(0, 0); + eventSender.mouseMoveTo(10, 10); + eventSender.mouseDown(); + eventSender.mouseUp(); + eventSender.mouseMoveTo(60, 60); + + eventSender.clearTouchPoints(); + eventSender.addTouchPoint(10, 10); + eventSender.touchStart(); + eventSender.releaseTouchPoint(0); + eventSender.touchEnd(); + } + + assert_event_array_equivalent(actual, expected); + this.done(); +}, 'Rerouting mouse/touch event test but the id of hit region is unset.'); + +async_test(function() { context.clearRect(0, 0, 400, 400); context.rect(0, 0, 50, 50); context.fill();
diff --git a/third_party/WebKit/LayoutTests/fast/css-grid-layout/floated-grid-container-percentage-tracks.html b/third_party/WebKit/LayoutTests/fast/css-grid-layout/floated-grid-container-percentage-tracks.html new file mode 100644 index 0000000..c5ccf8b --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/css-grid-layout/floated-grid-container-percentage-tracks.html
@@ -0,0 +1,99 @@ +<!DOCTYPE html> +<link href="resources/grid.css" rel="stylesheet"> +<style> + +.wrapper { + position: relative; + clear: both; +} + +.grid { + float: left; + font: 10px/1 Ahem; +} + +.fixedSize { + width: 200px; + height: 200px; +} + +.oneRowOneColumn { + grid-template-rows: 100%; + grid-template-columns: 100%; +} + +.twoRowsTwoColumns { + grid-template-rows: 25% 75%; + grid-template-columns: 60% 40%; +} + +</style> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="../../resources/check-layout-th.js"></script> +<body onload="checkLayout('.grid')"> +<div id="log"></div> + +<p>This test checks that percentage tracks are properly resolved for floated grid containers.</p> + +<div class="wrapper"> + <div class="grid oneRowOneColumn"> + <div class="firstRowFirstColumn" + data-offset-x="0" data-offset-y="0" data-expected-width="30" data-expected-height="10"> + XXX + </div> + </div> +</div> + +<div class="wrapper"> + <div class="grid oneRowOneColumn fixedSize"> + <div class="firstRowFirstColumn" + data-offset-x="0" data-offset-y="0" data-expected-width="200" data-expected-height="200"> + XXX + </div> + </div> +</div> + +<div class="wrapper"> + <div class="grid twoRowsTwoColumns"> + <div class="firstRowFirstColumn" + data-offset-x="0" data-offset-y="0" data-expected-width="30" data-expected-height="10"> + XXX + </div> + <div class="firstRowSecondColumn" + data-offset-x="30" data-offset-y="0" data-expected-width="30" data-expected-height="10"> + XXX + </div> + <div class="secondRowFirstColumn" + data-offset-x="0" data-offset-y="10" data-expected-width="30" data-expected-height="10"> + XXX + </div> + <div class="secondRowSecondColumn" + data-offset-x="30" data-offset-y="10" data-expected-width="30" data-expected-height="10"> + XXX + </div> + </div> +</div> + +<div class="wrapper"> + <div class="grid twoRowsTwoColumns fixedSize"> + <div class="firstRowFirstColumn" + data-offset-x="0" data-offset-y="0" data-expected-width="120" data-expected-height="50"> + XXX + </div> + <div class="firstRowSecondColumn" + data-offset-x="120" data-offset-y="0" data-expected-width="80" data-expected-height="50"> + XXX + </div> + <div class="secondRowFirstColumn" + data-offset-x="0" data-offset-y="50" data-expected-width="120" data-expected-height="150"> + XXX + </div> + <div class="secondRowSecondColumn" + data-offset-x="120" data-offset-y="50" data-expected-width="80" data-expected-height="150"> + XXX + </div> + </div> +</div> + +</body>
diff --git a/third_party/WebKit/LayoutTests/fast/css-grid-layout/grid-content-alignment-and-self-alignment-expected.txt b/third_party/WebKit/LayoutTests/fast/css-grid-layout/grid-content-alignment-and-self-alignment-spanning-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/fast/css-grid-layout/grid-content-alignment-and-self-alignment-expected.txt rename to third_party/WebKit/LayoutTests/fast/css-grid-layout/grid-content-alignment-and-self-alignment-spanning-expected.txt
diff --git a/third_party/WebKit/LayoutTests/fast/css-grid-layout/grid-content-alignment-and-self-alignment-spanning.html b/third_party/WebKit/LayoutTests/fast/css-grid-layout/grid-content-alignment-and-self-alignment-spanning.html new file mode 100644 index 0000000..60aa726 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/css-grid-layout/grid-content-alignment-and-self-alignment-spanning.html
@@ -0,0 +1,549 @@ +<!DOCTYPE html> +<html> +<head> +<link href="resources/grid.css" rel="stylesheet"> +<link href="resources/grid-alignment.css" rel="stylesheet"> +<script src="../../resources/check-layout.js"></script> +<style> +body { + margin: 0px; +} + +.grid { + position: relative; +} +.spanningTwo { + grid-auto-columns: 20px; + grid-auto-rows: 40px; + grid-template-areas: "a a b" + "c d b"; + width: 300px; + height: 200px; +} +.spanningThree { + grid-auto-columns: 50px; + grid-auto-rows: 50px; + grid-template-areas: ". . . . . ." + ". b b b c ." + ". . . . c ." + ". . . . c ." + ". . . . . ."; + width: 550px; + height: 450px; +} + +.gridRowColumnGaps { + grid-row-gap: 20px; + grid-column-gap: 10px; +} + +.i1 { grid-row: 1; } +.i2 { grid-row: 2; } +.i3 { grid-row: 3; grid-column: 6; } +.i4 { grid-row: 4; grid-column: 6; } +.i5 { grid-row: 5; grid-column: 6; } + +.a { + grid-area: a; + background-color: blue; +} +.b { + grid-area: b; + background-color: lime; +} +.c { + grid-area: c; + background-color: purple; +} +.d { + grid-area: d; + background-color: orange; +} +.stretchedGrid { + grid-auto-columns: minmax(20px, auto); + grid-auto-rows: minmax(40px, auto); +} + +.cell { + width: 20px; + height: 40px; +} +.cell1 { + width: 20px; + height: 20px; +} +</style> +</head> +<body onload="checkLayout('.grid')"> + +<p>This test checks that Content Distribution alignment works fine in combination with Self Alignmet and items span more than one track.</p> + +<div style="position: relative"> + <p>direction: LTR | distribution: 'space-between' | self-alignment: center</p> + <div class="grid spanningTwo contentSpaceBetween" data-expected-width="300" data-expected-height="200"> + <div class="a cell justifySelfCenter" data-offset-x="70" data-offset-y="0" data-expected-width="20" data-expected-height="40"></div> + <div class="b cell alignSelfCenter" data-offset-x="280" data-offset-y="80" data-expected-width="20" data-expected-height="40"></div> + <div class="c" data-offset-x="0" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> + <div class="d" data-offset-x="140" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: LTR | distribution: 'space-between' | self-alignment: end</p> + <div class="grid spanningTwo contentSpaceBetween" data-expected-width="300" data-expected-height="200"> + <div class="a cell justifySelfEnd" data-offset-x="140" data-offset-y="0" data-expected-width="20" data-expected-height="40"></div> + <div class="b cell alignSelfEnd" data-offset-x="280" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> + <div class="c" data-offset-x="0" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> + <div class="d" data-offset-x="140" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: LTR | distribution: 'space-around' | self-alignment: center</p> + <div class="grid spanningTwo contentSpaceAround" data-expected-width="300" data-expected-height="200"> + <div class="a cell justifySelfCenter" data-offset-x="90" data-offset-y="30" data-expected-width="20" data-expected-height="40"></div> + <div class="b cell alignSelfCenter" data-offset-x="240" data-offset-y="80" data-expected-width="20" data-expected-height="40"></div> + <div class="c" data-offset-x="40" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> + <div class="d" data-offset-x="140" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: LTR | distribution: 'space-around' | self-alignment: end</p> + <div class="grid spanningTwo contentSpaceAround" data-expected-width="300" data-expected-height="200"> + <div class="a cell justifySelfEnd" data-offset-x="140" data-offset-y="30" data-expected-width="20" data-expected-height="40"></div> + <div class="b cell alignSelfEnd" data-offset-x="240" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> + <div class="c" data-offset-x="40" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> + <div class="d" data-offset-x="140" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: LTR | distribution: 'space-evenly' | self-alignment: center</p> + <div class="grid spanningTwo contentSpaceEvenly" data-expected-width="300" data-expected-height="200"> + <div class="a cell justifySelfCenter" data-offset-x="100" data-offset-y="40" data-expected-width="20" data-expected-height="40"></div> + <div class="b cell alignSelfCenter" data-offset-x="220" data-offset-y="80" data-expected-width="20" data-expected-height="40"></div> + <div class="c" data-offset-x="60" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> + <div class="d" data-offset-x="140" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: LTR | distribution: 'space-evenly' | self-alignment: end</p> + <div class="grid spanningTwo contentSpaceEvenly" data-expected-width="300" data-expected-height="200"> + <div class="a cell justifySelfEnd" data-offset-x="140" data-offset-y="40" data-expected-width="20" data-expected-height="40"></div> + <div class="b cell alignSelfEnd" data-offset-x="220" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> + <div class="c" data-offset-x="60" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> + <div class="d" data-offset-x="140" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: LTR | distribution: 'stretch' | self-alignment: center</p> + <div class="grid spanningTwo stretchedGrid contentStretch" data-expected-width="300" data-expected-height="200"> + <div class="a cell justifySelfCenter alignSelfCenter" data-offset-x="90" data-offset-y="30" data-expected-width="20" data-expected-height="40"></div> + <div class="b cell justifySelfCenter alignSelfCenter" data-offset-x="240" data-offset-y="80" data-expected-width="20" data-expected-height="40"></div> + <div class="c" data-offset-x="0" data-offset-y="100" data-expected-width="100" data-expected-height="100"></div> + <div class="d" data-offset-x="100" data-offset-y="100" data-expected-width="100" data-expected-height="100"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: LTR | distribution: 'stretch' | self-alignment: end</p> + <div class="grid spanningTwo stretchedGrid contentStretch" data-expected-width="300" data-expected-height="200"> + <div class="a cell justifySelfEnd alignSelfEnd" data-offset-x="180" data-offset-y="60" data-expected-width="20" data-expected-height="40"></div> + <div class="b cell justifySelfEnd alignSelfEnd" data-offset-x="280" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> + <div class="c" data-offset-x="0" data-offset-y="100" data-expected-width="100" data-expected-height="100"></div> + <div class="d" data-offset-x="100" data-offset-y="100" data-expected-width="100" data-expected-height="100"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: LTR | distribution: 'default' | self-alignment: center</p> + <div class="grid spanningThree"> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i2" style="background: red"></div> + <div class="i2" style="background: blue"></div> + <div class="b cell1 justifySelfCenter" data-offset-x="115" data-offset-y="50" data-expected-width="20" data-expected-height="20"></div> + <div class="c cell1 alignSelfCenter" data-offset-x="200" data-offset-y="115" data-expected-width="20" data-expected-height="20"></div> + <div class="i3" style="background: red"></div> + <div class="i4" style="background: blue"></div> + <div class="i5" style="background: red"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: LTR | distribution: 'default' | self-alignment: end</p> + <div class="grid spanningThree"> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i2" style="background: red"></div> + <div class="i2" style="background: blue"></div> + <div class="b cell1 justifySelfEnd" data-offset-x="180" data-offset-y="50" data-expected-width="20" data-expected-height="20"></div> + <div class="c cell1 alignSelfEnd" data-offset-x="200" data-offset-y="180" data-expected-width="20" data-expected-height="20"></div> + <div class="i3" style="background: red"></div> + <div class="i4" style="background: blue"></div> + <div class="i5" style="background: red"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: LTR | distribution: 'space-between' | self-alignment: center</p> + <div class="grid spanningThree contentSpaceBetween"> + <div class="i1" style="background: blue;"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i2" style="background: red"></div> + <div class="i2" style="background: blue"></div> + <div class="b cell1 justifySelfCenter" data-offset-x="215" data-offset-y="100" data-expected-width="20" data-expected-height="20"></div> + <div class="c cell1 alignSelfCenter" data-offset-x="400" data-offset-y="215" data-expected-width="20" data-expected-height="20"></div> + <div class="i3" style="background: red"></div> + <div class="i4" style="background: blue"></div> + <div class="i5" style="background: red"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: LTR | distribution: 'space-between' | self-alignment: end</p> + <div class="grid spanningThree contentSpaceBetween"> + <div class="i1" style="background: blue;"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i2" style="background: red"></div> + <div class="i2" style="background: blue"></div> + <div class="b cell1 justifySelfEnd" data-offset-x="330" data-offset-y="100" data-expected-width="20" data-expected-height="20"></div> + <div class="c cell1 alignSelfEnd" data-offset-x="400" data-offset-y="330" data-expected-width="20" data-expected-height="20"></div> + <div class="i3" style="background: red"></div> + <div class="i4" style="background: blue"></div> + <div class="i5" style="background: red"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: LTR | rows/columns gap: 20px/40px | distribution: 'default' | self-alignment: center</p> + <div class="grid spanningThree gridRowColumnGaps"> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i2" style="background: red"></div> + <div class="i2" style="background: blue"></div> + <div class="b cell1 justifySelfCenter" data-offset-x="135" data-offset-y="70" data-expected-width="20" data-expected-height="20"></div> + <div class="c cell1 alignSelfCenter" data-offset-x="240" data-offset-y="155" data-expected-width="20" data-expected-height="20"></div> + <div class="i3" style="background: red"></div> + <div class="i4" style="background: blue"></div> + <div class="i5" style="background: red"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: LTR | rows/columns gap: 20px/40px | distribution: 'default' | self-alignment: end</p> + <div class="grid spanningThree gridRowColumnGaps"> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i2" style="background: red"></div> + <div class="i2" style="background: blue"></div> + <div class="b cell1 justifySelfEnd" data-offset-x="210" data-offset-y="70" data-expected-width="20" data-expected-height="20"></div> + <div class="c cell1 alignSelfEnd" data-offset-x="240" data-offset-y="240" data-expected-width="20" data-expected-height="20"></div> + <div class="i3" style="background: red"></div> + <div class="i4" style="background: blue"></div> + <div class="i5" style="background: red"></div> + </div> +</div> + +<!-- Same expected result than without gaps because space-between just use the remaining availalbe space. --> +<div style="position: relative"> + <p>direction: LTR | rows/columns gap: 20px/40px | distribution: 'space-between' | self-alignment: center</p> + <div class="grid spanningThree contentSpaceBetween gridRowColumnGaps"> + <div class="i1" style="background: blue;"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i2" style="background: red"></div> + <div class="i2" style="background: blue"></div> + <div class="b cell1 justifySelfCenter" data-offset-x="215" data-offset-y="100" data-expected-width="20" data-expected-height="20"></div> + <div class="c cell1 alignSelfCenter" data-offset-x="400" data-offset-y="215" data-expected-width="20" data-expected-height="20"></div> + <div class="i3" style="background: red"></div> + <div class="i4" style="background: blue"></div> + <div class="i5" style="background: red"></div> + </div> +</div> + +<!-- Same expected result than without gaps because space-between just use the remaining availalbe space. --> +<div style="position: relative"> + <p>direction: LTR | rows/columns gap: 20px/40px | distribution: 'space-between' | self-alignment: end</p> + <div class="grid spanningThree contentSpaceBetween gridRowColumnGaps"> + <div class="i1" style="background: blue;"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i2" style="background: red"></div> + <div class="i2" style="background: blue"></div> + <div class="b cell1 justifySelfEnd" data-offset-x="330" data-offset-y="100" data-expected-width="20" data-expected-height="20"></div> + <div class="c cell1 alignSelfEnd" data-offset-x="400" data-offset-y="330" data-expected-width="20" data-expected-height="20"></div> + <div class="i3" style="background: red"></div> + <div class="i4" style="background: blue"></div> + <div class="i5" style="background: red"></div> + </div> +</div> + +<!-- RTL direction. --> +<div style="position: relative"> + <p>direction: RTL | distribution: 'space-between' | self-alignment: center</p> + <div class="grid spanningTwo contentSpaceBetween directionRTL" data-expected-width="300" data-expected-height="200"> + <div class="a cell justifySelfCenter" data-offset-x="210" data-offset-y="0" data-expected-width="20" data-expected-height="40"></div> + <div class="b cell alignSelfCenter" data-offset-x="0" data-offset-y="80" data-expected-width="20" data-expected-height="40"></div> + <div class="c" data-offset-x="280" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> + <div class="d" data-offset-x="140" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: RTL | distribution: 'space-between' | self-alignment: end</p> + <div class="grid spanningTwo contentSpaceBetween directionRTL" data-expected-width="300" data-expected-height="200"> + <div class="a cell justifySelfEnd" data-offset-x="140" data-offset-y="0" data-expected-width="20" data-expected-height="40"></div> + <div class="b cell alignSelfEnd" data-offset-x="0" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> + <div class="c" data-offset-x="280" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> + <div class="d" data-offset-x="140" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: RTL | distribution: 'space-around' | self-alignment: center</p> + <div class="grid spanningTwo contentSpaceAround directionRTL" data-expected-width="300" data-expected-height="200"> + <div class="a cell justifySelfCenter" data-offset-x="190" data-offset-y="30" data-expected-width="20" data-expected-height="40"></div> + <div class="b cell alignSelfCenter" data-offset-x="40" data-offset-y="80" data-expected-width="20" data-expected-height="40"></div> + <div class="c" data-offset-x="240" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> + <div class="d" data-offset-x="140" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: RTL | distribution: 'space-around' | self-alignment: end</p> + <div class="grid spanningTwo contentSpaceAround directionRTL" data-expected-width="300" data-expected-height="200"> + <div class="a cell justifySelfEnd" data-offset-x="140" data-offset-y="30" data-expected-width="20" data-expected-height="40"></div> + <div class="b cell alignSelfEnd" data-offset-x="40" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> + <div class="c" data-offset-x="240" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> + <div class="d" data-offset-x="140" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: RTL | distribution: 'space-evenly' | self-alignment: center</p> + <div class="grid spanningTwo contentSpaceEvenly directionRTL" data-expected-width="300" data-expected-height="200"> + <div class="a cell justifySelfCenter" data-offset-x="180" data-offset-y="40" data-expected-width="20" data-expected-height="40"></div> + <div class="b cell alignSelfCenter" data-offset-x="60" data-offset-y="80" data-expected-width="20" data-expected-height="40"></div> + <div class="c" data-offset-x="220" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> + <div class="d" data-offset-x="140" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: RTL | distribution: 'space-evenly' | self-alignment: end</p> + <div class="grid spanningTwo contentSpaceEvenly directionRTL" data-expected-width="300" data-expected-height="200"> + <div class="a cell justifySelfEnd" data-offset-x="140" data-offset-y="40" data-expected-width="20" data-expected-height="40"></div> + <div class="b cell alignSelfEnd" data-offset-x="60" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> + <div class="c" data-offset-x="220" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> + <div class="d" data-offset-x="140" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: RTL | distribution: 'stretch' | self-alignment: center</p> + <div class="grid spanningTwo stretchedGrid contentStretch directionRTL" data-expected-width="300" data-expected-height="200"> + <div class="a cell justifySelfCenter alignSelfCenter" data-offset-x="190" data-offset-y="30" data-expected-width="20" data-expected-height="40"></div> + <div class="b cell justifySelfCenter alignSelfCenter" data-offset-x="40" data-offset-y="80" data-expected-width="20" data-expected-height="40"></div> + <div class="c" data-offset-x="200" data-offset-y="100" data-expected-width="100" data-expected-height="100"></div> + <div class="d" data-offset-x="100" data-offset-y="100" data-expected-width="100" data-expected-height="100"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: RTL | distribution: 'stretch' | self-alignment: end</p> + <div class="grid spanningTwo stretchedGrid contentStretch directionRTL" data-expected-width="300" data-expected-height="200"> + <div class="a cell justifySelfEnd alignSelfEnd" data-offset-x="100" data-offset-y="60" data-expected-width="20" data-expected-height="40"></div> + <div class="b cell justifySelfEnd alignSelfEnd" data-offset-x="0" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> + <div class="c" data-offset-x="200" data-offset-y="100" data-expected-width="100" data-expected-height="100"></div> + <div class="d" data-offset-x="100" data-offset-y="100" data-expected-width="100" data-expected-height="100"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: RTL | distribution: 'default' | self-alignment: center</p> + <div class="grid spanningThree directionRTL"> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i2" style="background: red"></div> + <div class="i2" style="background: blue"></div> + <div class="b cell1 justifySelfCenter" data-offset-x="415" data-offset-y="50" data-expected-width="20" data-expected-height="20"></div> + <div class="c cell1 alignSelfCenter" data-offset-x="330" data-offset-y="115" data-expected-width="20" data-expected-height="20"></div> + <div class="i3" style="background: red"></div> + <div class="i4" style="background: blue"></div> + <div class="i5" style="background: red"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: RTL | distribution: 'default' | self-alignment: end</p> + <div class="grid spanningThree directionRTL"> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i2" style="background: red"></div> + <div class="i2" style="background: blue"></div> + <div class="b cell1 justifySelfEnd" data-offset-x="350" data-offset-y="50" data-expected-width="20" data-expected-height="20"></div> + <div class="c cell1 alignSelfEnd" data-offset-x="330" data-offset-y="180" data-expected-width="20" data-expected-height="20"></div> + <div class="i3" style="background: red"></div> + <div class="i4" style="background: blue"></div> + <div class="i5" style="background: red"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: RTL | distribution: 'space-between' | self-alignment: center</p> + <div class="grid spanningThree contentSpaceBetween directionRTL"> + <div class="i1" style="background: blue;"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i2" style="background: red"></div> + <div class="i2" style="background: blue"></div> + <div class="b cell1 justifySelfCenter" data-offset-x="315" data-offset-y="100" data-expected-width="20" data-expected-height="20"></div> + <div class="c cell1 alignSelfCenter" data-offset-x="130" data-offset-y="215" data-expected-width="20" data-expected-height="20"></div> + <div class="i3" style="background: red"></div> + <div class="i4" style="background: blue"></div> + <div class="i5" style="background: red"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: RTL | distribution: 'space-between' | self-alignment: end</p> + <div class="grid spanningThree contentSpaceBetween directionRTL"> + <div class="i1" style="background: blue;"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i2" style="background: red"></div> + <div class="i2" style="background: blue"></div> + <div class="b cell1 justifySelfEnd" data-offset-x="200" data-offset-y="100" data-expected-width="20" data-expected-height="20"></div> + <div class="c cell1 alignSelfEnd" data-offset-x="130" data-offset-y="330" data-expected-width="20" data-expected-height="20"></div> + <div class="i3" style="background: red"></div> + <div class="i4" style="background: blue"></div> + <div class="i5" style="background: red"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: RTL | rows/columns gap: 20px/40px | distribution: 'default' | self-alignment: center</p> + <div class="grid spanningThree gridRowColumnGaps directionRTL"> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i2" style="background: red"></div> + <div class="i2" style="background: blue"></div> + <div class="b cell1 justifySelfCenter" data-offset-x="395" data-offset-y="70" data-expected-width="20" data-expected-height="20"></div> + <div class="c cell1 alignSelfCenter" data-offset-x="290" data-offset-y="155" data-expected-width="20" data-expected-height="20"></div> + <div class="i3" style="background: red"></div> + <div class="i4" style="background: blue"></div> + <div class="i5" style="background: red"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: RTL | rows/columns gap: 20px/40px | distribution: 'default' | self-alignment: end</p> + <div class="grid spanningThree gridRowColumnGaps directionRTL"> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i2" style="background: red"></div> + <div class="i2" style="background: blue"></div> + <div class="b cell1 justifySelfEnd" data-offset-x="320" data-offset-y="70" data-expected-width="20" data-expected-height="20"></div> + <div class="c cell1 alignSelfEnd" data-offset-x="290" data-offset-y="240" data-expected-width="20" data-expected-height="20"></div> + <div class="i3" style="background: red"></div> + <div class="i4" style="background: blue"></div> + <div class="i5" style="background: red"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: RTL | rows/columns gap: 20px/40px | distribution: 'space-between' | self-alignment: center</p> + <div class="grid spanningThree contentSpaceBetween gridRowColumnGaps directionRTL"> + <div class="i1" style="background: blue;"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i2" style="background: red"></div> + <div class="i2" style="background: blue"></div> + <div class="b cell1 justifySelfCenter" data-offset-x="315" data-offset-y="100" data-expected-width="20" data-expected-height="20"></div> + <div class="c cell1 alignSelfCenter" data-offset-x="130" data-offset-y="215" data-expected-width="20" data-expected-height="20"></div> + <div class="i3" style="background: red"></div> + <div class="i4" style="background: blue"></div> + <div class="i5" style="background: red"></div> + </div> +</div> + +<div style="position: relative"> + <p>direction: RTL | rows/columns gap: 20px/40px | distribution: 'space-between' | self-alignment: end</p> + <div class="grid spanningThree contentSpaceBetween gridRowColumnGaps directionRTL"> + <div class="i1" style="background: blue;"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i1" style="background: blue"></div> + <div class="i1" style="background: red"></div> + <div class="i2" style="background: red"></div> + <div class="i2" style="background: blue"></div> + <div class="b cell1 justifySelfEnd" data-offset-x="200" data-offset-y="100" data-expected-width="20" data-expected-height="20"></div> + <div class="c cell1 alignSelfEnd" data-offset-x="130" data-offset-y="330" data-expected-width="20" data-expected-height="20"></div> + <div class="i3" style="background: red"></div> + <div class="i4" style="background: blue"></div> + <div class="i5" style="background: red"></div> + </div> +</div> + +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/fast/css-grid-layout/grid-content-alignment-and-self-alignment.html b/third_party/WebKit/LayoutTests/fast/css-grid-layout/grid-content-alignment-and-self-alignment.html index 60aa726..bc8df8d3 100644 --- a/third_party/WebKit/LayoutTests/fast/css-grid-layout/grid-content-alignment-and-self-alignment.html +++ b/third_party/WebKit/LayoutTests/fast/css-grid-layout/grid-content-alignment-and-self-alignment.html
@@ -1,549 +1,462 @@ <!DOCTYPE html> -<html> -<head> <link href="resources/grid.css" rel="stylesheet"> <link href="resources/grid-alignment.css" rel="stylesheet"> -<script src="../../resources/check-layout.js"></script> <style> -body { - margin: 0px; -} .grid { + grid-template-columns: 200px 100px; + grid-template-rows: 100px 50px; + width: 500px; + height: 350px; position: relative; -} -.spanningTwo { - grid-auto-columns: 20px; - grid-auto-rows: 40px; - grid-template-areas: "a a b" - "c d b"; - width: 300px; - height: 200px; -} -.spanningThree { - grid-auto-columns: 50px; - grid-auto-rows: 50px; - grid-template-areas: ". . . . . ." - ". b b b c ." - ". . . . c ." - ". . . . c ." - ". . . . . ."; - width: 550px; - height: 450px; + font: 10px/1 Ahem; } -.gridRowColumnGaps { - grid-row-gap: 20px; - grid-column-gap: 10px; +.gridGaps { + grid-gap: 10px 20px; } -.i1 { grid-row: 1; } -.i2 { grid-row: 2; } -.i3 { grid-row: 3; grid-column: 6; } -.i4 { grid-row: 4; grid-column: 6; } -.i5 { grid-row: 5; grid-column: 6; } - -.a { - grid-area: a; - background-color: blue; -} -.b { - grid-area: b; - background-color: lime; -} -.c { - grid-area: c; - background-color: purple; -} -.d { - grid-area: d; - background-color: orange; -} -.stretchedGrid { - grid-auto-columns: minmax(20px, auto); - grid-auto-rows: minmax(40px, auto); -} - -.cell { - width: 20px; - height: 40px; -} -.cell1 { - width: 20px; - height: 20px; -} </style> -</head> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="../../resources/check-layout-th.js"></script> <body onload="checkLayout('.grid')"> +<div id="log"></div> -<p>This test checks that Content Distribution alignment works fine in combination with Self Alignmet and items span more than one track.</p> +<p>This test checks that Content Distribution alignment works fine in combination with Self Alignmet and items in just one cell.</p> -<div style="position: relative"> - <p>direction: LTR | distribution: 'space-between' | self-alignment: center</p> - <div class="grid spanningTwo contentSpaceBetween" data-expected-width="300" data-expected-height="200"> - <div class="a cell justifySelfCenter" data-offset-x="70" data-offset-y="0" data-expected-width="20" data-expected-height="40"></div> - <div class="b cell alignSelfCenter" data-offset-x="280" data-offset-y="80" data-expected-width="20" data-expected-height="40"></div> - <div class="c" data-offset-x="0" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> - <div class="d" data-offset-x="140" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> - </div> +<p>direction: LTR | distribution: 'space-between' | self-alignment: center</p> +<div class="grid contentSpaceBetween itemsCenter"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="95" data-offset-y="45" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="445" data-offset-y="45" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="95" data-offset-y="320" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="445" data-offset-y="320" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: LTR | distribution: 'space-between' | self-alignment: end</p> - <div class="grid spanningTwo contentSpaceBetween" data-expected-width="300" data-expected-height="200"> - <div class="a cell justifySelfEnd" data-offset-x="140" data-offset-y="0" data-expected-width="20" data-expected-height="40"></div> - <div class="b cell alignSelfEnd" data-offset-x="280" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> - <div class="c" data-offset-x="0" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> - <div class="d" data-offset-x="140" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> - </div> +<p>direction: LTR | distribution: 'space-between' | self-alignment: end</p> +<div class="grid contentSpaceBetween itemsEnd"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="190" data-offset-y="90" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="490" data-offset-y="90" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="190" data-offset-y="340" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="490" data-offset-y="340" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: LTR | distribution: 'space-around' | self-alignment: center</p> - <div class="grid spanningTwo contentSpaceAround" data-expected-width="300" data-expected-height="200"> - <div class="a cell justifySelfCenter" data-offset-x="90" data-offset-y="30" data-expected-width="20" data-expected-height="40"></div> - <div class="b cell alignSelfCenter" data-offset-x="240" data-offset-y="80" data-expected-width="20" data-expected-height="40"></div> - <div class="c" data-offset-x="40" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> - <div class="d" data-offset-x="140" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> - </div> +<p>direction: LTR | distribution: 'space-around' | self-alignment: center</p> +<div class="grid contentSpaceAround itemsCenter"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="145" data-offset-y="95" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="395" data-offset-y="95" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="145" data-offset-y="270" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="395" data-offset-y="270" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: LTR | distribution: 'space-around' | self-alignment: end</p> - <div class="grid spanningTwo contentSpaceAround" data-expected-width="300" data-expected-height="200"> - <div class="a cell justifySelfEnd" data-offset-x="140" data-offset-y="30" data-expected-width="20" data-expected-height="40"></div> - <div class="b cell alignSelfEnd" data-offset-x="240" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> - <div class="c" data-offset-x="40" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> - <div class="d" data-offset-x="140" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> - </div> +<p>direction: LTR | distribution: 'space-around' | self-alignment: end</p> +<div class="grid contentSpaceAround itemsEnd"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="240" data-offset-y="140" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="440" data-offset-y="140" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="240" data-offset-y="290" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="440" data-offset-y="290" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: LTR | distribution: 'space-evenly' | self-alignment: center</p> - <div class="grid spanningTwo contentSpaceEvenly" data-expected-width="300" data-expected-height="200"> - <div class="a cell justifySelfCenter" data-offset-x="100" data-offset-y="40" data-expected-width="20" data-expected-height="40"></div> - <div class="b cell alignSelfCenter" data-offset-x="220" data-offset-y="80" data-expected-width="20" data-expected-height="40"></div> - <div class="c" data-offset-x="60" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> - <div class="d" data-offset-x="140" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> - </div> +<p>direction: LTR | distribution: 'space-evenly' | self-alignment: center</p> +<div class="grid contentSpaceEvenly itemsCenter"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="162" data-offset-y="112" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="378" data-offset-y="112" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="162" data-offset-y="253" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="378" data-offset-y="253" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: LTR | distribution: 'space-evenly' | self-alignment: end</p> - <div class="grid spanningTwo contentSpaceEvenly" data-expected-width="300" data-expected-height="200"> - <div class="a cell justifySelfEnd" data-offset-x="140" data-offset-y="40" data-expected-width="20" data-expected-height="40"></div> - <div class="b cell alignSelfEnd" data-offset-x="220" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> - <div class="c" data-offset-x="60" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> - <div class="d" data-offset-x="140" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> - </div> +<p>direction: LTR | distribution: 'space-evenly' | self-alignment: end</p> +<div class="grid contentSpaceEvenly itemsEnd"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="257" data-offset-y="157" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="423" data-offset-y="157" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="257" data-offset-y="273" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="423" data-offset-y="273" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: LTR | distribution: 'stretch' | self-alignment: center</p> - <div class="grid spanningTwo stretchedGrid contentStretch" data-expected-width="300" data-expected-height="200"> - <div class="a cell justifySelfCenter alignSelfCenter" data-offset-x="90" data-offset-y="30" data-expected-width="20" data-expected-height="40"></div> - <div class="b cell justifySelfCenter alignSelfCenter" data-offset-x="240" data-offset-y="80" data-expected-width="20" data-expected-height="40"></div> - <div class="c" data-offset-x="0" data-offset-y="100" data-expected-width="100" data-expected-height="100"></div> - <div class="d" data-offset-x="100" data-offset-y="100" data-expected-width="100" data-expected-height="100"></div> - </div> +<p>direction: LTR | grid-gap: 10px 20px | distribution: 'space-between' | self-alignment: center</p> +<div class="grid gridGaps contentSpaceBetween itemsCenter"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="95" data-offset-y="45" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="445" data-offset-y="45" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="95" data-offset-y="320" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="445" data-offset-y="320" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: LTR | distribution: 'stretch' | self-alignment: end</p> - <div class="grid spanningTwo stretchedGrid contentStretch" data-expected-width="300" data-expected-height="200"> - <div class="a cell justifySelfEnd alignSelfEnd" data-offset-x="180" data-offset-y="60" data-expected-width="20" data-expected-height="40"></div> - <div class="b cell justifySelfEnd alignSelfEnd" data-offset-x="280" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> - <div class="c" data-offset-x="0" data-offset-y="100" data-expected-width="100" data-expected-height="100"></div> - <div class="d" data-offset-x="100" data-offset-y="100" data-expected-width="100" data-expected-height="100"></div> - </div> +<p>direction: LTR | grid-gap: 10px 20px | distribution: 'space-between' | self-alignment: end</p> +<div class="grid gridGaps contentSpaceBetween itemsEnd"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="190" data-offset-y="90" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="490" data-offset-y="90" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="190" data-offset-y="340" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="490" data-offset-y="340" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: LTR | distribution: 'default' | self-alignment: center</p> - <div class="grid spanningThree"> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i2" style="background: red"></div> - <div class="i2" style="background: blue"></div> - <div class="b cell1 justifySelfCenter" data-offset-x="115" data-offset-y="50" data-expected-width="20" data-expected-height="20"></div> - <div class="c cell1 alignSelfCenter" data-offset-x="200" data-offset-y="115" data-expected-width="20" data-expected-height="20"></div> - <div class="i3" style="background: red"></div> - <div class="i4" style="background: blue"></div> - <div class="i5" style="background: red"></div> - </div> +<p>direction: LTR | grid-gap: 10px 20px | distribution: 'space-around' | self-alignment: center</p> +<div class="grid gridGaps contentSpaceAround itemsCenter"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="140" data-offset-y="93" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="400" data-offset-y="93" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="140" data-offset-y="273" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="400" data-offset-y="273" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: LTR | distribution: 'default' | self-alignment: end</p> - <div class="grid spanningThree"> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i2" style="background: red"></div> - <div class="i2" style="background: blue"></div> - <div class="b cell1 justifySelfEnd" data-offset-x="180" data-offset-y="50" data-expected-width="20" data-expected-height="20"></div> - <div class="c cell1 alignSelfEnd" data-offset-x="200" data-offset-y="180" data-expected-width="20" data-expected-height="20"></div> - <div class="i3" style="background: red"></div> - <div class="i4" style="background: blue"></div> - <div class="i5" style="background: red"></div> - </div> +<p>direction: LTR | grid-gap: 10px 20px | distribution: 'space-around' | self-alignment: end</p> +<div class="grid gridGaps contentSpaceAround itemsEnd"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="235" data-offset-y="138" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="445" data-offset-y="138" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="235" data-offset-y="293" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="445" data-offset-y="293" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: LTR | distribution: 'space-between' | self-alignment: center</p> - <div class="grid spanningThree contentSpaceBetween"> - <div class="i1" style="background: blue;"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i2" style="background: red"></div> - <div class="i2" style="background: blue"></div> - <div class="b cell1 justifySelfCenter" data-offset-x="215" data-offset-y="100" data-expected-width="20" data-expected-height="20"></div> - <div class="c cell1 alignSelfCenter" data-offset-x="400" data-offset-y="215" data-expected-width="20" data-expected-height="20"></div> - <div class="i3" style="background: red"></div> - <div class="i4" style="background: blue"></div> - <div class="i5" style="background: red"></div> - </div> +<p>direction: LTR | grid-gap: 10px 20px | distribution: 'space-evenly' | self-alignment: center</p> +<div class="grid gridGaps contentSpaceEvenly itemsCenter"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="155" data-offset-y="108" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="385" data-offset-y="108" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="155" data-offset-y="257" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="385" data-offset-y="257" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: LTR | distribution: 'space-between' | self-alignment: end</p> - <div class="grid spanningThree contentSpaceBetween"> - <div class="i1" style="background: blue;"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i2" style="background: red"></div> - <div class="i2" style="background: blue"></div> - <div class="b cell1 justifySelfEnd" data-offset-x="330" data-offset-y="100" data-expected-width="20" data-expected-height="20"></div> - <div class="c cell1 alignSelfEnd" data-offset-x="400" data-offset-y="330" data-expected-width="20" data-expected-height="20"></div> - <div class="i3" style="background: red"></div> - <div class="i4" style="background: blue"></div> - <div class="i5" style="background: red"></div> - </div> -</div> +<p>direction: LTR | grid-gap: 10px 20px | distribution: 'space-evenly' | self-alignment: end</p> +<div class="grid gridGaps contentSpaceEvenly itemsEnd"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> -<div style="position: relative"> - <p>direction: LTR | rows/columns gap: 20px/40px | distribution: 'default' | self-alignment: center</p> - <div class="grid spanningThree gridRowColumnGaps"> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i2" style="background: red"></div> - <div class="i2" style="background: blue"></div> - <div class="b cell1 justifySelfCenter" data-offset-x="135" data-offset-y="70" data-expected-width="20" data-expected-height="20"></div> - <div class="c cell1 alignSelfCenter" data-offset-x="240" data-offset-y="155" data-expected-width="20" data-expected-height="20"></div> - <div class="i3" style="background: red"></div> - <div class="i4" style="background: blue"></div> - <div class="i5" style="background: red"></div> - </div> -</div> - -<div style="position: relative"> - <p>direction: LTR | rows/columns gap: 20px/40px | distribution: 'default' | self-alignment: end</p> - <div class="grid spanningThree gridRowColumnGaps"> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i2" style="background: red"></div> - <div class="i2" style="background: blue"></div> - <div class="b cell1 justifySelfEnd" data-offset-x="210" data-offset-y="70" data-expected-width="20" data-expected-height="20"></div> - <div class="c cell1 alignSelfEnd" data-offset-x="240" data-offset-y="240" data-expected-width="20" data-expected-height="20"></div> - <div class="i3" style="background: red"></div> - <div class="i4" style="background: blue"></div> - <div class="i5" style="background: red"></div> - </div> -</div> - -<!-- Same expected result than without gaps because space-between just use the remaining availalbe space. --> -<div style="position: relative"> - <p>direction: LTR | rows/columns gap: 20px/40px | distribution: 'space-between' | self-alignment: center</p> - <div class="grid spanningThree contentSpaceBetween gridRowColumnGaps"> - <div class="i1" style="background: blue;"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i2" style="background: red"></div> - <div class="i2" style="background: blue"></div> - <div class="b cell1 justifySelfCenter" data-offset-x="215" data-offset-y="100" data-expected-width="20" data-expected-height="20"></div> - <div class="c cell1 alignSelfCenter" data-offset-x="400" data-offset-y="215" data-expected-width="20" data-expected-height="20"></div> - <div class="i3" style="background: red"></div> - <div class="i4" style="background: blue"></div> - <div class="i5" style="background: red"></div> - </div> -</div> - -<!-- Same expected result than without gaps because space-between just use the remaining availalbe space. --> -<div style="position: relative"> - <p>direction: LTR | rows/columns gap: 20px/40px | distribution: 'space-between' | self-alignment: end</p> - <div class="grid spanningThree contentSpaceBetween gridRowColumnGaps"> - <div class="i1" style="background: blue;"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i2" style="background: red"></div> - <div class="i2" style="background: blue"></div> - <div class="b cell1 justifySelfEnd" data-offset-x="330" data-offset-y="100" data-expected-width="20" data-expected-height="20"></div> - <div class="c cell1 alignSelfEnd" data-offset-x="400" data-offset-y="330" data-expected-width="20" data-expected-height="20"></div> - <div class="i3" style="background: red"></div> - <div class="i4" style="background: blue"></div> - <div class="i5" style="background: red"></div> - </div> + <div class="firstRowFirstColumn" + data-offset-x="250" data-offset-y="153" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="430" data-offset-y="153" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="250" data-offset-y="277" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="430" data-offset-y="277" data-expected-width="10" data-expected-height="10">X</div> </div> <!-- RTL direction. --> -<div style="position: relative"> - <p>direction: RTL | distribution: 'space-between' | self-alignment: center</p> - <div class="grid spanningTwo contentSpaceBetween directionRTL" data-expected-width="300" data-expected-height="200"> - <div class="a cell justifySelfCenter" data-offset-x="210" data-offset-y="0" data-expected-width="20" data-expected-height="40"></div> - <div class="b cell alignSelfCenter" data-offset-x="0" data-offset-y="80" data-expected-width="20" data-expected-height="40"></div> - <div class="c" data-offset-x="280" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> - <div class="d" data-offset-x="140" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> - </div> + +<p>direction: RTL | distribution: 'space-between' | self-alignment: center</p> +<div class="grid directionRTL contentSpaceBetween itemsCenter"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="395" data-offset-y="45" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="45" data-offset-y="45" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="395" data-offset-y="320" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="45" data-offset-y="320" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: RTL | distribution: 'space-between' | self-alignment: end</p> - <div class="grid spanningTwo contentSpaceBetween directionRTL" data-expected-width="300" data-expected-height="200"> - <div class="a cell justifySelfEnd" data-offset-x="140" data-offset-y="0" data-expected-width="20" data-expected-height="40"></div> - <div class="b cell alignSelfEnd" data-offset-x="0" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> - <div class="c" data-offset-x="280" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> - <div class="d" data-offset-x="140" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> - </div> +<p>direction: RTL | distribution: 'space-between' | self-alignment: end</p> +<div class="grid directionRTL contentSpaceBetween itemsEnd"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="300" data-offset-y="90" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="0" data-offset-y="90" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="300" data-offset-y="340" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="0" data-offset-y="340" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: RTL | distribution: 'space-around' | self-alignment: center</p> - <div class="grid spanningTwo contentSpaceAround directionRTL" data-expected-width="300" data-expected-height="200"> - <div class="a cell justifySelfCenter" data-offset-x="190" data-offset-y="30" data-expected-width="20" data-expected-height="40"></div> - <div class="b cell alignSelfCenter" data-offset-x="40" data-offset-y="80" data-expected-width="20" data-expected-height="40"></div> - <div class="c" data-offset-x="240" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> - <div class="d" data-offset-x="140" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> - </div> +<p>direction: RTL | distribution: 'space-around' | self-alignment: center</p> +<div class="grid directionRTL contentSpaceAround itemsCenter"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="345" data-offset-y="95" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="95" data-offset-y="95" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="345" data-offset-y="270" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="95" data-offset-y="270" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: RTL | distribution: 'space-around' | self-alignment: end</p> - <div class="grid spanningTwo contentSpaceAround directionRTL" data-expected-width="300" data-expected-height="200"> - <div class="a cell justifySelfEnd" data-offset-x="140" data-offset-y="30" data-expected-width="20" data-expected-height="40"></div> - <div class="b cell alignSelfEnd" data-offset-x="40" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> - <div class="c" data-offset-x="240" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> - <div class="d" data-offset-x="140" data-offset-y="130" data-expected-width="20" data-expected-height="40"></div> - </div> +<p>direction: RTL | distribution: 'space-around' | self-alignment: end</p> +<div class="grid directionRTL contentSpaceAround itemsEnd"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="250" data-offset-y="140" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="50" data-offset-y="140" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="250" data-offset-y="290" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="50" data-offset-y="290" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: RTL | distribution: 'space-evenly' | self-alignment: center</p> - <div class="grid spanningTwo contentSpaceEvenly directionRTL" data-expected-width="300" data-expected-height="200"> - <div class="a cell justifySelfCenter" data-offset-x="180" data-offset-y="40" data-expected-width="20" data-expected-height="40"></div> - <div class="b cell alignSelfCenter" data-offset-x="60" data-offset-y="80" data-expected-width="20" data-expected-height="40"></div> - <div class="c" data-offset-x="220" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> - <div class="d" data-offset-x="140" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> - </div> +<p>direction: RTL | distribution: 'space-evenly' | self-alignment: center</p> +<div class="grid directionRTL contentSpaceEvenly itemsCenter"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="328" data-offset-y="112" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="112" data-offset-y="112" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="328" data-offset-y="253" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="112" data-offset-y="253" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: RTL | distribution: 'space-evenly' | self-alignment: end</p> - <div class="grid spanningTwo contentSpaceEvenly directionRTL" data-expected-width="300" data-expected-height="200"> - <div class="a cell justifySelfEnd" data-offset-x="140" data-offset-y="40" data-expected-width="20" data-expected-height="40"></div> - <div class="b cell alignSelfEnd" data-offset-x="60" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> - <div class="c" data-offset-x="220" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> - <div class="d" data-offset-x="140" data-offset-y="120" data-expected-width="20" data-expected-height="40"></div> - </div> +<p>direction: RTL | distribution: 'space-evenly' | self-alignment: end</p> +<div class="grid directionRTL contentSpaceEvenly itemsEnd"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="233" data-offset-y="157" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="67" data-offset-y="157" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="233" data-offset-y="273" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="67" data-offset-y="273" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: RTL | distribution: 'stretch' | self-alignment: center</p> - <div class="grid spanningTwo stretchedGrid contentStretch directionRTL" data-expected-width="300" data-expected-height="200"> - <div class="a cell justifySelfCenter alignSelfCenter" data-offset-x="190" data-offset-y="30" data-expected-width="20" data-expected-height="40"></div> - <div class="b cell justifySelfCenter alignSelfCenter" data-offset-x="40" data-offset-y="80" data-expected-width="20" data-expected-height="40"></div> - <div class="c" data-offset-x="200" data-offset-y="100" data-expected-width="100" data-expected-height="100"></div> - <div class="d" data-offset-x="100" data-offset-y="100" data-expected-width="100" data-expected-height="100"></div> - </div> +<p>direction: RTL | grid-gap: 10px 20px | distribution: 'space-between' | self-alignment: center</p> +<div class="grid directionRTL gridGaps contentSpaceBetween itemsCenter"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="395" data-offset-y="45" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="45" data-offset-y="45" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="395" data-offset-y="320" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="45" data-offset-y="320" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: RTL | distribution: 'stretch' | self-alignment: end</p> - <div class="grid spanningTwo stretchedGrid contentStretch directionRTL" data-expected-width="300" data-expected-height="200"> - <div class="a cell justifySelfEnd alignSelfEnd" data-offset-x="100" data-offset-y="60" data-expected-width="20" data-expected-height="40"></div> - <div class="b cell justifySelfEnd alignSelfEnd" data-offset-x="0" data-offset-y="160" data-expected-width="20" data-expected-height="40"></div> - <div class="c" data-offset-x="200" data-offset-y="100" data-expected-width="100" data-expected-height="100"></div> - <div class="d" data-offset-x="100" data-offset-y="100" data-expected-width="100" data-expected-height="100"></div> - </div> +<p>direction: RTL | grid-gap: 10px 20px | distribution: 'space-between' | self-alignment: end</p> +<div class="grid directionRTL gridGaps contentSpaceBetween itemsEnd"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="300" data-offset-y="90" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="0" data-offset-y="90" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="300" data-offset-y="340" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="0" data-offset-y="340" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: RTL | distribution: 'default' | self-alignment: center</p> - <div class="grid spanningThree directionRTL"> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i2" style="background: red"></div> - <div class="i2" style="background: blue"></div> - <div class="b cell1 justifySelfCenter" data-offset-x="415" data-offset-y="50" data-expected-width="20" data-expected-height="20"></div> - <div class="c cell1 alignSelfCenter" data-offset-x="330" data-offset-y="115" data-expected-width="20" data-expected-height="20"></div> - <div class="i3" style="background: red"></div> - <div class="i4" style="background: blue"></div> - <div class="i5" style="background: red"></div> - </div> +<p>direction: RTL | grid-gap: 10px 20px | distribution: 'space-around' | self-alignment: center</p> +<div class="grid directionRTL gridGaps contentSpaceAround itemsCenter"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="350" data-offset-y="93" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="90" data-offset-y="93" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="350" data-offset-y="273" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="90" data-offset-y="273" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: RTL | distribution: 'default' | self-alignment: end</p> - <div class="grid spanningThree directionRTL"> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i2" style="background: red"></div> - <div class="i2" style="background: blue"></div> - <div class="b cell1 justifySelfEnd" data-offset-x="350" data-offset-y="50" data-expected-width="20" data-expected-height="20"></div> - <div class="c cell1 alignSelfEnd" data-offset-x="330" data-offset-y="180" data-expected-width="20" data-expected-height="20"></div> - <div class="i3" style="background: red"></div> - <div class="i4" style="background: blue"></div> - <div class="i5" style="background: red"></div> - </div> +<p>direction: RTL | grid-gap: 10px 20px | distribution: 'space-around' | self-alignment: end</p> +<div class="grid directionRTL gridGaps contentSpaceAround itemsEnd"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="255" data-offset-y="138" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="45" data-offset-y="138" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="255" data-offset-y="293" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="45" data-offset-y="293" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: RTL | distribution: 'space-between' | self-alignment: center</p> - <div class="grid spanningThree contentSpaceBetween directionRTL"> - <div class="i1" style="background: blue;"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i2" style="background: red"></div> - <div class="i2" style="background: blue"></div> - <div class="b cell1 justifySelfCenter" data-offset-x="315" data-offset-y="100" data-expected-width="20" data-expected-height="20"></div> - <div class="c cell1 alignSelfCenter" data-offset-x="130" data-offset-y="215" data-expected-width="20" data-expected-height="20"></div> - <div class="i3" style="background: red"></div> - <div class="i4" style="background: blue"></div> - <div class="i5" style="background: red"></div> - </div> +<p>direction: RTL | grid-gap: 10px 20px | distribution: 'space-evenly' | self-alignment: center</p> +<div class="grid directionRTL gridGaps contentSpaceEvenly itemsCenter"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> + + <div class="firstRowFirstColumn" + data-offset-x="335" data-offset-y="108" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="105" data-offset-y="108" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="335" data-offset-y="257" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="105" data-offset-y="257" data-expected-width="10" data-expected-height="10">X</div> </div> -<div style="position: relative"> - <p>direction: RTL | distribution: 'space-between' | self-alignment: end</p> - <div class="grid spanningThree contentSpaceBetween directionRTL"> - <div class="i1" style="background: blue;"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i2" style="background: red"></div> - <div class="i2" style="background: blue"></div> - <div class="b cell1 justifySelfEnd" data-offset-x="200" data-offset-y="100" data-expected-width="20" data-expected-height="20"></div> - <div class="c cell1 alignSelfEnd" data-offset-x="130" data-offset-y="330" data-expected-width="20" data-expected-height="20"></div> - <div class="i3" style="background: red"></div> - <div class="i4" style="background: blue"></div> - <div class="i5" style="background: red"></div> - </div> -</div> +<p>direction: RTL | grid-gap: 10px 20px | distribution: 'space-evenly' | self-alignment: end</p> +<div class="grid directionRTL gridGaps contentSpaceEvenly itemsEnd"> + <!-- Dummy DIVs to help checking the result visually. --> + <div class="firstRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="firstRowSecondColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowFirstColumn justifySelfStretch alignSelfStretch"></div> + <div class="secondRowSecondColumn justifySelfStretch alignSelfStretch"></div> -<div style="position: relative"> - <p>direction: RTL | rows/columns gap: 20px/40px | distribution: 'default' | self-alignment: center</p> - <div class="grid spanningThree gridRowColumnGaps directionRTL"> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i2" style="background: red"></div> - <div class="i2" style="background: blue"></div> - <div class="b cell1 justifySelfCenter" data-offset-x="395" data-offset-y="70" data-expected-width="20" data-expected-height="20"></div> - <div class="c cell1 alignSelfCenter" data-offset-x="290" data-offset-y="155" data-expected-width="20" data-expected-height="20"></div> - <div class="i3" style="background: red"></div> - <div class="i4" style="background: blue"></div> - <div class="i5" style="background: red"></div> - </div> -</div> - -<div style="position: relative"> - <p>direction: RTL | rows/columns gap: 20px/40px | distribution: 'default' | self-alignment: end</p> - <div class="grid spanningThree gridRowColumnGaps directionRTL"> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i2" style="background: red"></div> - <div class="i2" style="background: blue"></div> - <div class="b cell1 justifySelfEnd" data-offset-x="320" data-offset-y="70" data-expected-width="20" data-expected-height="20"></div> - <div class="c cell1 alignSelfEnd" data-offset-x="290" data-offset-y="240" data-expected-width="20" data-expected-height="20"></div> - <div class="i3" style="background: red"></div> - <div class="i4" style="background: blue"></div> - <div class="i5" style="background: red"></div> - </div> -</div> - -<div style="position: relative"> - <p>direction: RTL | rows/columns gap: 20px/40px | distribution: 'space-between' | self-alignment: center</p> - <div class="grid spanningThree contentSpaceBetween gridRowColumnGaps directionRTL"> - <div class="i1" style="background: blue;"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i2" style="background: red"></div> - <div class="i2" style="background: blue"></div> - <div class="b cell1 justifySelfCenter" data-offset-x="315" data-offset-y="100" data-expected-width="20" data-expected-height="20"></div> - <div class="c cell1 alignSelfCenter" data-offset-x="130" data-offset-y="215" data-expected-width="20" data-expected-height="20"></div> - <div class="i3" style="background: red"></div> - <div class="i4" style="background: blue"></div> - <div class="i5" style="background: red"></div> - </div> -</div> - -<div style="position: relative"> - <p>direction: RTL | rows/columns gap: 20px/40px | distribution: 'space-between' | self-alignment: end</p> - <div class="grid spanningThree contentSpaceBetween gridRowColumnGaps directionRTL"> - <div class="i1" style="background: blue;"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i1" style="background: blue"></div> - <div class="i1" style="background: red"></div> - <div class="i2" style="background: red"></div> - <div class="i2" style="background: blue"></div> - <div class="b cell1 justifySelfEnd" data-offset-x="200" data-offset-y="100" data-expected-width="20" data-expected-height="20"></div> - <div class="c cell1 alignSelfEnd" data-offset-x="130" data-offset-y="330" data-expected-width="20" data-expected-height="20"></div> - <div class="i3" style="background: red"></div> - <div class="i4" style="background: blue"></div> - <div class="i5" style="background: red"></div> - </div> + <div class="firstRowFirstColumn" + data-offset-x="240" data-offset-y="153" data-expected-width="10" data-expected-height="10">X</div> + <div class="firstRowSecondColumn" + data-offset-x="60" data-offset-y="153" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowFirstColumn" + data-offset-x="240" data-offset-y="277" data-expected-width="10" data-expected-height="10">X</div> + <div class="secondRowSecondColumn" + data-offset-x="60" data-offset-y="277" data-expected-width="10" data-expected-height="10">X</div> </div> </body> -</html>
diff --git a/third_party/WebKit/LayoutTests/fast/multicol/doubly-nested-with-increasing-row-heights-crash-expected.txt b/third_party/WebKit/LayoutTests/fast/multicol/doubly-nested-with-increasing-row-heights-crash-expected.txt new file mode 100644 index 0000000..3a793fa --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/multicol/doubly-nested-with-increasing-row-heights-crash-expected.txt
@@ -0,0 +1,11 @@ +PASS if no crash or assertion failure. + + + + + + + + + +
diff --git a/third_party/WebKit/LayoutTests/fast/multicol/doubly-nested-with-increasing-row-heights-crash.html b/third_party/WebKit/LayoutTests/fast/multicol/doubly-nested-with-increasing-row-heights-crash.html new file mode 100644 index 0000000..1e4d92d --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/multicol/doubly-nested-with-increasing-row-heights-crash.html
@@ -0,0 +1,23 @@ +<!DOCTYPE html> +<script> + if (window.testRunner) + testRunner.dumpAsText(); +</script> +<p>PASS if no crash or assertion failure.</p> +<div style="columns:2; column-fill:auto; height:40px; line-height:20px;"> + <div style="height:8px;"></div> + <div style="columns:2;"> + <div style="height:1em;"></div> + <div style="columns:2;"> + <br> + <br> + <br> + <br> + <br> + <br> + <br> + <br> + </div> + <div style="height:1px;"></div> + </div> +</div>
diff --git a/third_party/WebKit/LayoutTests/fast/multicol/nested-balanced-inner-column-count-1-with-forced-break-expected.html b/third_party/WebKit/LayoutTests/fast/multicol/nested-balanced-inner-column-count-1-with-forced-break-expected.html new file mode 100644 index 0000000..662da64 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/multicol/nested-balanced-inner-column-count-1-with-forced-break-expected.html
@@ -0,0 +1,6 @@ +<!DOCTYPE html> +<p>There should be a papayawhip square below. It should be aligned in + the bottom right corner of a hotpink rectangle with a black border.</p> +<div style="width:80px; height:46px; border:1px solid black; background:hotpink;"> + <div style="float:right; width:40px; height:40px; margin-top:6px; background:papayawhip;"></div> +</div>
diff --git a/third_party/WebKit/LayoutTests/fast/multicol/nested-balanced-inner-column-count-1-with-forced-break.html b/third_party/WebKit/LayoutTests/fast/multicol/nested-balanced-inner-column-count-1-with-forced-break.html new file mode 100644 index 0000000..f6fce3d1 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/multicol/nested-balanced-inner-column-count-1-with-forced-break.html
@@ -0,0 +1,13 @@ +<!DOCTYPE html> +<p>There should be a papayawhip square below. It should be aligned in + the bottom right corner of a hotpink rectangle with a black border.</p> +<div style="columns:2; column-fill:auto; column-gap:0; width:80px; line-height:20px; border:1px solid black; background:hotpink;"> + <div style="columns:1;"> + <div style="height:1px;"></div> + <div style="height:6px; break-before:column;"></div> + <div style="width:40px; background:papayawhip;"> + <br> + <br> + </div> + </div> +</div>
diff --git a/third_party/WebKit/LayoutTests/hittesting/inner-border-radius-hittest-expected.txt b/third_party/WebKit/LayoutTests/hittesting/inner-border-radius-hittest-expected.txt index c247cec..32ddf81b 100644 --- a/third_party/WebKit/LayoutTests/hittesting/inner-border-radius-hittest-expected.txt +++ b/third_party/WebKit/LayoutTests/hittesting/inner-border-radius-hittest-expected.txt
@@ -21,4 +21,6 @@ PASS document.elementFromPoint(x + 230, y + 230).id is 'roundedBoxWithScrollbarsChild' PASS document.elementFromPoint(x + 265, y + 265).id is 'roundedBoxWithScrollbars' PASS document.elementFromPoint(x + 275, y + 275).id is 'container' +PASS document.elementFromPoint(x + 150, y + 240).id is 'roundedBoxWithScrollbars' +PASS document.elementFromPoint(x + 240, y + 150).id is 'roundedBoxWithScrollbars'
diff --git a/third_party/WebKit/LayoutTests/hittesting/inner-border-radius-hittest.html b/third_party/WebKit/LayoutTests/hittesting/inner-border-radius-hittest.html index 1ab0440..6cf239f 100644 --- a/third_party/WebKit/LayoutTests/hittesting/inner-border-radius-hittest.html +++ b/third_party/WebKit/LayoutTests/hittesting/inner-border-radius-hittest.html
@@ -11,13 +11,13 @@ // At top-left corner, inside outer border radius. shouldBe("document.elementFromPoint(x + 35, y + 35).id", "'roundedBoxWithoutScrollbars'"); shouldBe("document.elementFromPoint(x + 60, y + 60).id", "'roundedBoxWithoutScrollbars'"); - // At top-left corner, insider inner border radius. + // At top-left corner, inside inner border radius. shouldBe("document.elementFromPoint(x + 68, y + 68).id", "'roundedBoxChildWithoutScrollbars'"); // At top-left corner, fully inside border. shouldBe("document.elementFromPoint(x + 80, y + 80).id", "'roundedBoxChildWithoutScrollbars'"); // At bottom-right corner, inside inner border radius. shouldBe("document.elementFromPoint(x + 230, y + 230).id", "'roundedBoxChildWithoutScrollbars'"); - // At bottom-right corner, insider inner border radius. + // At bottom-right corner, inside inner border radius. shouldBe("document.elementFromPoint(x + 240, y + 240).id", "'roundedBoxWithoutScrollbars'"); shouldBe("document.elementFromPoint(x + 265, y + 265).id", "'roundedBoxWithoutScrollbars'"); // At bottom-right corner, outside the outer border radius. @@ -31,16 +31,20 @@ // At top-left corner with scrollbars, inside outer border radius. shouldBe("document.elementFromPoint(x + 35, y + 35).id", "'roundedBoxWithScrollbars'"); shouldBe("document.elementFromPoint(x + 60, y + 60).id", "'roundedBoxWithScrollbars'"); - // At top-left corner with scrollbars, insider inner border radius. + // At top-left corner with scrollbars, inside inner border radius. shouldBe("document.elementFromPoint(x + 68, y + 68).id", "'roundedBoxWithScrollbarsChild'"); // At top-left corner with scrollbars, fully inside border. shouldBe("document.elementFromPoint(x + 80, y + 80).id", "'roundedBoxWithScrollbarsChild'"); // At bottom-right corner with scrollbars, inside inner border radius. shouldBe("document.elementFromPoint(x + 230, y + 230).id", "'roundedBoxWithScrollbarsChild'"); - // At bottom-right corner with scrollbars, insider inner border radius. + // At bottom-right corner with scrollbars, inside inner border radius. shouldBe("document.elementFromPoint(x + 265, y + 265).id", "'roundedBoxWithScrollbars'"); // At bottom-right corner with scrollbars, outside the outer border radius. shouldBe("document.elementFromPoint(x + 275, y + 275).id", "'container'"); + // At bottom-center on scrollbar and inside inner border radius. + shouldBe("document.elementFromPoint(x + 150, y + 240).id", "'roundedBoxWithScrollbars'"); + // At center-right on scrollbar and inside inner border radius. + shouldBe("document.elementFromPoint(x + 240, y + 150).id", "'roundedBoxWithScrollbars'"); } </script> <style>
diff --git a/third_party/WebKit/LayoutTests/http/tests/local/formdata/formdata-methods.html b/third_party/WebKit/LayoutTests/http/tests/local/formdata/formdata-methods.html index 2db54ed..66b1ea500 100644 --- a/third_party/WebKit/LayoutTests/http/tests/local/formdata/formdata-methods.html +++ b/third_party/WebKit/LayoutTests/http/tests/local/formdata/formdata-methods.html
@@ -1,7 +1,7 @@ <!DOCTYPE html> <title>FormData interface</title> -<script src="../../resources/testharness.js"></script> -<script src="../../resources/testharnessreport.js"></script> +<script src="../../../../resources/testharness.js"></script> +<script src="../../../../resources/testharnessreport.js"></script> <script> // Helpers
diff --git a/third_party/WebKit/LayoutTests/http/tests/local/serviceworker/fetch-request-body-file.html b/third_party/WebKit/LayoutTests/http/tests/local/serviceworker/fetch-request-body-file.html index a56ac524..a73baee 100644 --- a/third_party/WebKit/LayoutTests/http/tests/local/serviceworker/fetch-request-body-file.html +++ b/third_party/WebKit/LayoutTests/http/tests/local/serviceworker/fetch-request-body-file.html
@@ -1,6 +1,6 @@ <!DOCTYPE html> -<script src="../../resources/testharness.js"></script> -<script src="../../resources/testharnessreport.js"></script> +<script src="../../../../resources/testharness.js"></script> +<script src="../../../../resources/testharnessreport.js"></script> <script src="../../serviceworker/resources/test-helpers.js"></script> <script src="../../resources/get-host-info.js"></script> <body>
diff --git a/third_party/WebKit/LayoutTests/http/tests/resources/testharness.css b/third_party/WebKit/LayoutTests/http/tests/resources/testharness.css deleted file mode 100644 index e2ed5a04..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/resources/testharness.css +++ /dev/null
@@ -1,102 +0,0 @@ -html { - font-family:DejaVu Sans, Bitstream Vera Sans, Arial, Sans; -} - -#log .warning, -#log .warning a { - color: black; - background: yellow; -} - -#log .error, -#log .error a { - color: white; - background: red; -} - -section#summary { - margin-bottom:1em; -} - -table#results { - border-collapse:collapse; - table-layout:fixed; - width:100%; -} - -table#results th:first-child, -table#results td:first-child { - width:4em; -} - -table#results th:last-child, -table#results td:last-child { - width:50%; -} - -table#results.assertions th:last-child, -table#results.assertions td:last-child { - width:35%; -} - -table#results th { - padding:0; - padding-bottom:0.5em; - border-bottom:medium solid black; -} - -table#results td { - padding:1em; - padding-bottom:0.5em; - border-bottom:thin solid black; -} - -tr.pass > td:first-child { - color:green; -} - -tr.fail > td:first-child { - color:red; -} - -tr.timeout > td:first-child { - color:red; -} - -tr.notrun > td:first-child { - color:blue; -} - -.pass > td:first-child, .fail > td:first-child, .timeout > td:first-child, .notrun > td:first-child { - font-variant:small-caps; -} - -table#results span { - display:block; -} - -table#results span.expected { - font-family:DejaVu Sans Mono, Bitstream Vera Sans Mono, Monospace; - white-space:pre; -} - -table#results span.actual { - font-family:DejaVu Sans Mono, Bitstream Vera Sans Mono, Monospace; - white-space:pre; -} - -span.ok { - color:green; -} - -tr.error { - color:red; -} - -span.timeout { - color:red; -} - -span.ok, span.timeout, span.error { - font-variant:small-caps; -} \ No newline at end of file
diff --git a/third_party/WebKit/LayoutTests/http/tests/resources/testharness.js b/third_party/WebKit/LayoutTests/http/tests/resources/testharness.js deleted file mode 100644 index 7920ccd4..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/resources/testharness.js +++ /dev/null
@@ -1,2659 +0,0 @@ -/*global self*/ -/*jshint latedef: nofunc*/ -/* -Distributed under both the W3C Test Suite License [1] and the W3C -3-clause BSD License [2]. To contribute to a W3C Test Suite, see the -policies and contribution forms [3]. - -[1] http://www.w3.org/Consortium/Legal/2008/04-testsuite-license -[2] http://www.w3.org/Consortium/Legal/2008/03-bsd-license -[3] http://www.w3.org/2004/10/27-testcases -*/ - -/* Documentation is in docs/api.md */ - -(function () -{ - var debug = false; - // default timeout is 10 seconds, test can override if needed - var settings = { - output:true, - harness_timeout:{ - "normal":10000, - "long":60000 - }, - test_timeout:null, - message_events: ["start", "test_state", "result", "completion"] - }; - - var xhtml_ns = "http://www.w3.org/1999/xhtml"; - - /* - * TestEnvironment is an abstraction for the environment in which the test - * harness is used. Each implementation of a test environment has to provide - * the following interface: - * - * interface TestEnvironment { - * // Invoked after the global 'tests' object has been created and it's - * // safe to call add_*_callback() to register event handlers. - * void on_tests_ready(); - * - * // Invoked after setup() has been called to notify the test environment - * // of changes to the test harness properties. - * void on_new_harness_properties(object properties); - * - * // Should return a new unique default test name. - * DOMString next_default_test_name(); - * - * // Should return the test harness timeout duration in milliseconds. - * float test_timeout(); - * - * // Should return the global scope object. - * object global_scope(); - * }; - */ - - /* - * A test environment with a DOM. The global object is 'window'. By default - * test results are displayed in a table. Any parent windows receive - * callbacks or messages via postMessage() when test events occur. See - * apisample11.html and apisample12.html. - */ - function WindowTestEnvironment() { - this.name_counter = 0; - this.window_cache = null; - this.output_handler = null; - this.all_loaded = false; - var this_obj = this; - this.message_events = []; - - this.message_functions = { - start: [add_start_callback, remove_start_callback, - function (properties) { - this_obj._dispatch("start_callback", [properties], - {type: "start", properties: properties}); - }], - - test_state: [add_test_state_callback, remove_test_state_callback, - function(test) { - this_obj._dispatch("test_state_callback", [test], - {type: "test_state", - test: test.structured_clone()}); - }], - result: [add_result_callback, remove_result_callback, - function (test) { - this_obj.output_handler.show_status(); - this_obj._dispatch("result_callback", [test], - {type: "result", - test: test.structured_clone()}); - }], - completion: [add_completion_callback, remove_completion_callback, - function (tests, harness_status) { - var cloned_tests = map(tests, function(test) { - return test.structured_clone(); - }); - this_obj._dispatch("completion_callback", [tests, harness_status], - {type: "complete", - tests: cloned_tests, - status: harness_status.structured_clone()}); - }] - } - - on_event(window, 'load', function() { - this_obj.all_loaded = true; - }); - } - - WindowTestEnvironment.prototype._dispatch = function(selector, callback_args, message_arg) { - this._forEach_windows( - function(w, same_origin) { - if (same_origin) { - try { - var has_selector = selector in w; - } catch(e) { - // If document.domain was set at some point same_origin can be - // wrong and the above will fail. - has_selector = false; - } - if (has_selector) { - try { - w[selector].apply(undefined, callback_args); - } catch (e) { - if (debug) { - throw e; - } - } - } - } - if (supports_post_message(w) && w !== self) { - w.postMessage(message_arg, "*"); - } - }); - }; - - WindowTestEnvironment.prototype._forEach_windows = function(callback) { - // Iterate of the the windows [self ... top, opener]. The callback is passed - // two objects, the first one is the windows object itself, the second one - // is a boolean indicating whether or not its on the same origin as the - // current window. - var cache = this.window_cache; - if (!cache) { - cache = [[self, true]]; - var w = self; - var i = 0; - var so; - var origins = location.ancestorOrigins; - while (w != w.parent) { - w = w.parent; - // In WebKit, calls to parent windows' properties that aren't on the same - // origin cause an error message to be displayed in the error console but - // don't throw an exception. This is a deviation from the current HTML5 - // spec. See: https://bugs.webkit.org/show_bug.cgi?id=43504 - // The problem with WebKit's behavior is that it pollutes the error console - // with error messages that can't be caught. - // - // This issue can be mitigated by relying on the (for now) proprietary - // `location.ancestorOrigins` property which returns an ordered list of - // the origins of enclosing windows. See: - // http://trac.webkit.org/changeset/113945. - if (origins) { - so = (location.origin == origins[i]); - } else { - so = is_same_origin(w); - } - cache.push([w, so]); - i++; - } - w = window.opener; - if (w) { - // window.opener isn't included in the `location.ancestorOrigins` prop. - // We'll just have to deal with a simple check and an error msg on WebKit - // browsers in this case. - cache.push([w, is_same_origin(w)]); - } - this.window_cache = cache; - } - - forEach(cache, - function(a) { - callback.apply(null, a); - }); - }; - - WindowTestEnvironment.prototype.on_tests_ready = function() { - var output = new Output(); - this.output_handler = output; - - var this_obj = this; - - add_start_callback(function (properties) { - this_obj.output_handler.init(properties); - }); - - add_test_state_callback(function(test) { - this_obj.output_handler.show_status(); - }); - - add_result_callback(function (test) { - this_obj.output_handler.show_status(); - }); - - add_completion_callback(function (tests, harness_status) { - this_obj.output_handler.show_results(tests, harness_status); - }); - this.setup_messages(settings.message_events); - }; - - WindowTestEnvironment.prototype.setup_messages = function(new_events) { - var this_obj = this; - forEach(settings.message_events, function(x) { - var current_dispatch = this_obj.message_events.indexOf(x) !== -1; - var new_dispatch = new_events.indexOf(x) !== -1; - if (!current_dispatch && new_dispatch) { - this_obj.message_functions[x][0](this_obj.message_functions[x][2]); - } else if (current_dispatch && !new_dispatch) { - this_obj.message_functions[x][1](this_obj.message_functions[x][2]); - } - }); - this.message_events = new_events; - } - - WindowTestEnvironment.prototype.next_default_test_name = function() { - //Don't use document.title to work around an Opera bug in XHTML documents - var title = document.getElementsByTagName("title")[0]; - var prefix = (title && title.firstChild && title.firstChild.data) || "Untitled"; - var suffix = this.name_counter > 0 ? " " + this.name_counter : ""; - this.name_counter++; - return prefix + suffix; - }; - - WindowTestEnvironment.prototype.on_new_harness_properties = function(properties) { - this.output_handler.setup(properties); - if (properties.hasOwnProperty("message_events")) { - this.setup_messages(properties.message_events); - } - }; - - WindowTestEnvironment.prototype.add_on_loaded_callback = function(callback) { - on_event(window, 'load', callback); - }; - - WindowTestEnvironment.prototype.test_timeout = function() { - var metas = document.getElementsByTagName("meta"); - for (var i = 0; i < metas.length; i++) { - if (metas[i].name == "timeout") { - if (metas[i].content == "long") { - return settings.harness_timeout.long; - } - break; - } - } - return settings.harness_timeout.normal; - }; - - WindowTestEnvironment.prototype.global_scope = function() { - return window; - }; - - /* - * Base TestEnvironment implementation for a generic web worker. - * - * Workers accumulate test results. One or more clients can connect and - * retrieve results from a worker at any time. - * - * WorkerTestEnvironment supports communicating with a client via a - * MessagePort. The mechanism for determining the appropriate MessagePort - * for communicating with a client depends on the type of worker and is - * implemented by the various specializations of WorkerTestEnvironment - * below. - * - * A client document using testharness can use fetch_tests_from_worker() to - * retrieve results from a worker. See apisample16.html. - */ - function WorkerTestEnvironment() { - this.name_counter = 0; - this.all_loaded = true; - this.message_list = []; - this.message_ports = []; - } - - WorkerTestEnvironment.prototype._dispatch = function(message) { - this.message_list.push(message); - for (var i = 0; i < this.message_ports.length; ++i) - { - this.message_ports[i].postMessage(message); - } - }; - - // The only requirement is that port has a postMessage() method. It doesn't - // have to be an instance of a MessagePort, and often isn't. - WorkerTestEnvironment.prototype._add_message_port = function(port) { - this.message_ports.push(port); - for (var i = 0; i < this.message_list.length; ++i) - { - port.postMessage(this.message_list[i]); - } - }; - - WorkerTestEnvironment.prototype.next_default_test_name = function() { - var suffix = this.name_counter > 0 ? " " + this.name_counter : ""; - this.name_counter++; - return "Untitled" + suffix; - }; - - WorkerTestEnvironment.prototype.on_new_harness_properties = function() {}; - - WorkerTestEnvironment.prototype.on_tests_ready = function() { - var this_obj = this; - add_start_callback( - function(properties) { - this_obj._dispatch({ - type: "start", - properties: properties, - }); - }); - add_test_state_callback( - function(test) { - this_obj._dispatch({ - type: "test_state", - test: test.structured_clone() - }); - }); - add_result_callback( - function(test) { - this_obj._dispatch({ - type: "result", - test: test.structured_clone() - }); - }); - add_completion_callback( - function(tests, harness_status) { - this_obj._dispatch({ - type: "complete", - tests: map(tests, - function(test) { - return test.structured_clone(); - }), - status: harness_status.structured_clone() - }); - }); - }; - - WorkerTestEnvironment.prototype.add_on_loaded_callback = function() {}; - - WorkerTestEnvironment.prototype.test_timeout = function() { - // Tests running in a worker don't have a default timeout. I.e. all - // worker tests behave as if settings.explicit_timeout is true. - return null; - }; - - WorkerTestEnvironment.prototype.global_scope = function() { - return self; - }; - - /* - * Dedicated web workers. - * https://html.spec.whatwg.org/multipage/workers.html#dedicatedworkerglobalscope - * - * This class is used as the test_environment when testharness is running - * inside a dedicated worker. - */ - function DedicatedWorkerTestEnvironment() { - WorkerTestEnvironment.call(this); - // self is an instance of DedicatedWorkerGlobalScope which exposes - // a postMessage() method for communicating via the message channel - // established when the worker is created. - this._add_message_port(self); - } - DedicatedWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype); - - DedicatedWorkerTestEnvironment.prototype.on_tests_ready = function() { - WorkerTestEnvironment.prototype.on_tests_ready.call(this); - // In the absence of an onload notification, we a require dedicated - // workers to explicitly signal when the tests are done. - tests.wait_for_finish = true; - }; - - /* - * Shared web workers. - * https://html.spec.whatwg.org/multipage/workers.html#sharedworkerglobalscope - * - * This class is used as the test_environment when testharness is running - * inside a shared web worker. - */ - function SharedWorkerTestEnvironment() { - WorkerTestEnvironment.call(this); - var this_obj = this; - // Shared workers receive message ports via the 'onconnect' event for - // each connection. - self.addEventListener("connect", - function(message_event) { - this_obj._add_message_port(message_event.source); - }); - } - SharedWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype); - - SharedWorkerTestEnvironment.prototype.on_tests_ready = function() { - WorkerTestEnvironment.prototype.on_tests_ready.call(this); - // In the absence of an onload notification, we a require shared - // workers to explicitly signal when the tests are done. - tests.wait_for_finish = true; - }; - - /* - * Service workers. - * http://www.w3.org/TR/service-workers/ - * - * This class is used as the test_environment when testharness is running - * inside a service worker. - */ - function ServiceWorkerTestEnvironment() { - WorkerTestEnvironment.call(this); - this.all_loaded = false; - this.on_loaded_callback = null; - var this_obj = this; - self.addEventListener("message", - function(event) { - if (event.data.type && event.data.type === "connect") { - if (event.ports && event.ports[0]) { - // If a MessageChannel was passed, then use it to - // send results back to the main window. This - // allows the tests to work even if the browser - // does not fully support MessageEvent.source in - // ServiceWorkers yet. - this_obj._add_message_port(event.ports[0]); - event.ports[0].start(); - } else { - // If there is no MessageChannel, then attempt to - // use the MessageEvent.source to send results - // back to the main window. - this_obj._add_message_port(event.source); - } - } - }); - - // The oninstall event is received after the service worker script and - // all imported scripts have been fetched and executed. It's the - // equivalent of an onload event for a document. All tests should have - // been added by the time this event is received, thus it's not - // necessary to wait until the onactivate event. - on_event(self, "install", - function(event) { - this_obj.all_loaded = true; - if (this_obj.on_loaded_callback) { - this_obj.on_loaded_callback(); - } - }); - } - ServiceWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype); - - ServiceWorkerTestEnvironment.prototype.add_on_loaded_callback = function(callback) { - if (this.all_loaded) { - callback(); - } else { - this.on_loaded_callback = callback; - } - }; - - function create_test_environment() { - if ('document' in self) { - return new WindowTestEnvironment(); - } - if ('DedicatedWorkerGlobalScope' in self && - self instanceof DedicatedWorkerGlobalScope) { - return new DedicatedWorkerTestEnvironment(); - } - if ('SharedWorkerGlobalScope' in self && - self instanceof SharedWorkerGlobalScope) { - return new SharedWorkerTestEnvironment(); - } - if ('ServiceWorkerGlobalScope' in self && - self instanceof ServiceWorkerGlobalScope) { - return new ServiceWorkerTestEnvironment(); - } - throw new Error("Unsupported test environment"); - } - - var test_environment = create_test_environment(); - - function is_shared_worker(worker) { - return 'SharedWorker' in self && worker instanceof SharedWorker; - } - - function is_service_worker(worker) { - return 'ServiceWorker' in self && worker instanceof ServiceWorker; - } - - /* - * API functions - */ - - function test(func, name, properties) - { - var test_name = name ? name : test_environment.next_default_test_name(); - properties = properties ? properties : {}; - var test_obj = new Test(test_name, properties); - test_obj.step(func, test_obj, test_obj); - if (test_obj.phase === test_obj.phases.STARTED) { - test_obj.done(); - } - } - - function async_test(func, name, properties) - { - if (typeof func !== "function") { - properties = name; - name = func; - func = null; - } - var test_name = name ? name : test_environment.next_default_test_name(); - properties = properties ? properties : {}; - var test_obj = new Test(test_name, properties); - if (func) { - test_obj.step(func, test_obj, test_obj); - } - return test_obj; - } - - function promise_test(func, name, properties) { - var test = async_test(name, properties); - // If there is no promise tests queue make one. - test.step(function() { - if (!tests.promise_tests) { - tests.promise_tests = Promise.resolve(); - } - }); - tests.promise_tests = tests.promise_tests.then(function() { - return Promise.resolve(test.step(func, test, test)) - .then( - function() { - test.done(); - }) - .catch(test.step_func( - function(value) { - if (value instanceof AssertionError) { - throw value; - } - assert(false, "promise_test", null, - "Unhandled rejection with value: ${value}", {value:value}); - })); - }); - } - - function promise_rejects(test, expected, promise) { - return promise.then(test.unreached_func("Should have rejected.")).catch(function(e) { - assert_throws(expected, function() { throw e }); - }); - } - - /** - * This constructor helper allows DOM events to be handled using Promises, - * which can make it a lot easier to test a very specific series of events, - * including ensuring that unexpected events are not fired at any point. - */ - function EventWatcher(test, watchedNode, eventTypes) - { - if (typeof eventTypes == 'string') { - eventTypes = [eventTypes]; - } - - var waitingFor = null; - - var eventHandler = test.step_func(function(evt) { - assert_true(!!waitingFor, - 'Not expecting event, but got ' + evt.type + ' event'); - assert_equals(evt.type, waitingFor.types[0], - 'Expected ' + waitingFor.types[0] + ' event, but got ' + - evt.type + ' event instead'); - if (waitingFor.types.length > 1) { - // Pop first event from array - waitingFor.types.shift(); - return; - } - // We need to null out waitingFor before calling the resolve function - // since the Promise's resolve handlers may call wait_for() which will - // need to set waitingFor. - var resolveFunc = waitingFor.resolve; - waitingFor = null; - resolveFunc(evt); - }); - - for (var i = 0; i < eventTypes.length; i++) { - watchedNode.addEventListener(eventTypes[i], eventHandler); - } - - /** - * Returns a Promise that will resolve after the specified event or - * series of events has occured. - */ - this.wait_for = function(types) { - if (waitingFor) { - return Promise.reject('Already waiting for an event or events'); - } - if (typeof types == 'string') { - types = [types]; - } - return new Promise(function(resolve, reject) { - waitingFor = { - types: types, - resolve: resolve, - reject: reject - }; - }); - }; - - function stop_watching() { - for (var i = 0; i < eventTypes.length; i++) { - watchedNode.removeEventListener(eventTypes[i], eventHandler); - } - }; - - test.add_cleanup(stop_watching); - - return this; - } - expose(EventWatcher, 'EventWatcher'); - - function setup(func_or_properties, maybe_properties) - { - var func = null; - var properties = {}; - if (arguments.length === 2) { - func = func_or_properties; - properties = maybe_properties; - } else if (func_or_properties instanceof Function) { - func = func_or_properties; - } else { - properties = func_or_properties; - } - tests.setup(func, properties); - test_environment.on_new_harness_properties(properties); - } - - function done() { - if (tests.tests.length === 0) { - tests.set_file_is_test(); - } - if (tests.file_is_test) { - tests.tests[0].done(); - } - tests.end_wait(); - } - - function generate_tests(func, args, properties) { - forEach(args, function(x, i) - { - var name = x[0]; - test(function() - { - func.apply(this, x.slice(1)); - }, - name, - Array.isArray(properties) ? properties[i] : properties); - }); - } - - function on_event(object, event, callback) - { - object.addEventListener(event, callback, false); - } - - function step_timeout(f, t) { - var outer_this = this; - var args = Array.prototype.slice.call(arguments, 2); - return setTimeout(function() { - f.apply(outer_this, args); - }, t * tests.timeout_multiplier); - } - - expose(test, 'test'); - expose(async_test, 'async_test'); - expose(promise_test, 'promise_test'); - expose(promise_rejects, 'promise_rejects'); - expose(generate_tests, 'generate_tests'); - expose(setup, 'setup'); - expose(done, 'done'); - expose(on_event, 'on_event'); - expose(step_timeout, 'step_timeout'); - - /* - * Return a string truncated to the given length, with ... added at the end - * if it was longer. - */ - function truncate(s, len) - { - if (s.length > len) { - return s.substring(0, len - 3) + "..."; - } - return s; - } - - /* - * Return true if object is probably a Node object. - */ - function is_node(object) - { - // I use duck-typing instead of instanceof, because - // instanceof doesn't work if the node is from another window (like an - // iframe's contentWindow): - // http://www.w3.org/Bugs/Public/show_bug.cgi?id=12295 - if ("nodeType" in object && - "nodeName" in object && - "nodeValue" in object && - "childNodes" in object) { - try { - object.nodeType; - } catch (e) { - // The object is probably Node.prototype or another prototype - // object that inherits from it, and not a Node instance. - return false; - } - return true; - } - return false; - } - - /* - * Convert a value to a nice, human-readable string - */ - function format_value(val, seen) - { - if (!seen) { - seen = []; - } - if (typeof val === "object" && val !== null) { - if (seen.indexOf(val) >= 0) { - return "[...]"; - } - seen.push(val); - } - if (Array.isArray(val)) { - return "[" + val.map(function(x) {return format_value(x, seen);}).join(", ") + "]"; - } - - switch (typeof val) { - case "string": - val = val.replace("\\", "\\\\"); - for (var i = 0; i < 32; i++) { - var replace = "\\"; - switch (i) { - case 0: replace += "0"; break; - case 1: replace += "x01"; break; - case 2: replace += "x02"; break; - case 3: replace += "x03"; break; - case 4: replace += "x04"; break; - case 5: replace += "x05"; break; - case 6: replace += "x06"; break; - case 7: replace += "x07"; break; - case 8: replace += "b"; break; - case 9: replace += "t"; break; - case 10: replace += "n"; break; - case 11: replace += "v"; break; - case 12: replace += "f"; break; - case 13: replace += "r"; break; - case 14: replace += "x0e"; break; - case 15: replace += "x0f"; break; - case 16: replace += "x10"; break; - case 17: replace += "x11"; break; - case 18: replace += "x12"; break; - case 19: replace += "x13"; break; - case 20: replace += "x14"; break; - case 21: replace += "x15"; break; - case 22: replace += "x16"; break; - case 23: replace += "x17"; break; - case 24: replace += "x18"; break; - case 25: replace += "x19"; break; - case 26: replace += "x1a"; break; - case 27: replace += "x1b"; break; - case 28: replace += "x1c"; break; - case 29: replace += "x1d"; break; - case 30: replace += "x1e"; break; - case 31: replace += "x1f"; break; - } - val = val.replace(RegExp(String.fromCharCode(i), "g"), replace); - } - return '"' + val.replace(/"/g, '\\"') + '"'; - case "boolean": - case "undefined": - return String(val); - case "number": - // In JavaScript, -0 === 0 and String(-0) == "0", so we have to - // special-case. - if (val === -0 && 1/val === -Infinity) { - return "-0"; - } - return String(val); - case "object": - if (val === null) { - return "null"; - } - - // Special-case Node objects, since those come up a lot in my tests. I - // ignore namespaces. - if (is_node(val)) { - switch (val.nodeType) { - case Node.ELEMENT_NODE: - var ret = "<" + val.localName; - for (var i = 0; i < val.attributes.length; i++) { - ret += " " + val.attributes[i].name + '="' + val.attributes[i].value + '"'; - } - ret += ">" + val.innerHTML + "</" + val.localName + ">"; - return "Element node " + truncate(ret, 60); - case Node.TEXT_NODE: - return 'Text node "' + truncate(val.data, 60) + '"'; - case Node.PROCESSING_INSTRUCTION_NODE: - return "ProcessingInstruction node with target " + format_value(truncate(val.target, 60)) + " and data " + format_value(truncate(val.data, 60)); - case Node.COMMENT_NODE: - return "Comment node <!--" + truncate(val.data, 60) + "-->"; - case Node.DOCUMENT_NODE: - return "Document node with " + val.childNodes.length + (val.childNodes.length == 1 ? " child" : " children"); - case Node.DOCUMENT_TYPE_NODE: - return "DocumentType node"; - case Node.DOCUMENT_FRAGMENT_NODE: - return "DocumentFragment node with " + val.childNodes.length + (val.childNodes.length == 1 ? " child" : " children"); - default: - return "Node object of unknown type"; - } - } - - /* falls through */ - default: - return typeof val + ' "' + truncate(String(val), 60) + '"'; - } - } - expose(format_value, "format_value"); - - /* - * Assertions - */ - - function assert_true(actual, description) - { - assert(actual === true, "assert_true", description, - "expected true got ${actual}", {actual:actual}); - } - expose(assert_true, "assert_true"); - - function assert_false(actual, description) - { - assert(actual === false, "assert_false", description, - "expected false got ${actual}", {actual:actual}); - } - expose(assert_false, "assert_false"); - - function same_value(x, y) { - if (y !== y) { - //NaN case - return x !== x; - } - if (x === 0 && y === 0) { - //Distinguish +0 and -0 - return 1/x === 1/y; - } - return x === y; - } - - function assert_equals(actual, expected, description) - { - /* - * Test if two primitives are equal or two objects - * are the same object - */ - if (typeof actual != typeof expected) { - assert(false, "assert_equals", description, - "expected (" + typeof expected + ") ${expected} but got (" + typeof actual + ") ${actual}", - {expected:expected, actual:actual}); - return; - } - assert(same_value(actual, expected), "assert_equals", description, - "expected ${expected} but got ${actual}", - {expected:expected, actual:actual}); - } - expose(assert_equals, "assert_equals"); - - function assert_not_equals(actual, expected, description) - { - /* - * Test if two primitives are unequal or two objects - * are different objects - */ - assert(!same_value(actual, expected), "assert_not_equals", description, - "got disallowed value ${actual}", - {actual:actual}); - } - expose(assert_not_equals, "assert_not_equals"); - - function assert_in_array(actual, expected, description) - { - assert(expected.indexOf(actual) != -1, "assert_in_array", description, - "value ${actual} not in array ${expected}", - {actual:actual, expected:expected}); - } - expose(assert_in_array, "assert_in_array"); - - function assert_object_equals(actual, expected, description) - { - //This needs to be improved a great deal - function check_equal(actual, expected, stack) - { - stack.push(actual); - - var p; - for (p in actual) { - assert(expected.hasOwnProperty(p), "assert_object_equals", description, - "unexpected property ${p}", {p:p}); - - if (typeof actual[p] === "object" && actual[p] !== null) { - if (stack.indexOf(actual[p]) === -1) { - check_equal(actual[p], expected[p], stack); - } - } else { - assert(same_value(actual[p], expected[p]), "assert_object_equals", description, - "property ${p} expected ${expected} got ${actual}", - {p:p, expected:expected, actual:actual}); - } - } - for (p in expected) { - assert(actual.hasOwnProperty(p), - "assert_object_equals", description, - "expected property ${p} missing", {p:p}); - } - stack.pop(); - } - check_equal(actual, expected, []); - } - expose(assert_object_equals, "assert_object_equals"); - - function assert_array_equals(actual, expected, description) - { - assert(actual.length === expected.length, - "assert_array_equals", description, - "lengths differ, expected ${expected} got ${actual}", - {expected:expected.length, actual:actual.length}); - - for (var i = 0; i < actual.length; i++) { - assert(actual.hasOwnProperty(i) === expected.hasOwnProperty(i), - "assert_array_equals", description, - "property ${i}, property expected to be ${expected} but was ${actual}", - {i:i, expected:expected.hasOwnProperty(i) ? "present" : "missing", - actual:actual.hasOwnProperty(i) ? "present" : "missing"}); - assert(same_value(expected[i], actual[i]), - "assert_array_equals", description, - "property ${i}, expected ${expected} but got ${actual}", - {i:i, expected:expected[i], actual:actual[i]}); - } - } - expose(assert_array_equals, "assert_array_equals"); - - function assert_approx_equals(actual, expected, epsilon, description) - { - /* - * Test if two primitive numbers are equal withing +/- epsilon - */ - assert(typeof actual === "number", - "assert_approx_equals", description, - "expected a number but got a ${type_actual}", - {type_actual:typeof actual}); - - assert(Math.abs(actual - expected) <= epsilon, - "assert_approx_equals", description, - "expected ${expected} +/- ${epsilon} but got ${actual}", - {expected:expected, actual:actual, epsilon:epsilon}); - } - expose(assert_approx_equals, "assert_approx_equals"); - - function assert_less_than(actual, expected, description) - { - /* - * Test if a primitive number is less than another - */ - assert(typeof actual === "number", - "assert_less_than", description, - "expected a number but got a ${type_actual}", - {type_actual:typeof actual}); - - assert(actual < expected, - "assert_less_than", description, - "expected a number less than ${expected} but got ${actual}", - {expected:expected, actual:actual}); - } - expose(assert_less_than, "assert_less_than"); - - function assert_greater_than(actual, expected, description) - { - /* - * Test if a primitive number is greater than another - */ - assert(typeof actual === "number", - "assert_greater_than", description, - "expected a number but got a ${type_actual}", - {type_actual:typeof actual}); - - assert(actual > expected, - "assert_greater_than", description, - "expected a number greater than ${expected} but got ${actual}", - {expected:expected, actual:actual}); - } - expose(assert_greater_than, "assert_greater_than"); - - function assert_between_exclusive(actual, lower, upper, description) - { - /* - * Test if a primitive number is between two others - */ - assert(typeof actual === "number", - "assert_between_exclusive", description, - "expected a number but got a ${type_actual}", - {type_actual:typeof actual}); - - assert(actual > lower && actual < upper, - "assert_between_exclusive", description, - "expected a number greater than ${lower} " + - "and less than ${upper} but got ${actual}", - {lower:lower, upper:upper, actual:actual}); - } - expose(assert_between_exclusive, "assert_between_exclusive"); - - function assert_less_than_equal(actual, expected, description) - { - /* - * Test if a primitive number is less than or equal to another - */ - assert(typeof actual === "number", - "assert_less_than_equal", description, - "expected a number but got a ${type_actual}", - {type_actual:typeof actual}); - - assert(actual <= expected, - "assert_less_than_equal", description, - "expected a number less than or equal to ${expected} but got ${actual}", - {expected:expected, actual:actual}); - } - expose(assert_less_than_equal, "assert_less_than_equal"); - - function assert_greater_than_equal(actual, expected, description) - { - /* - * Test if a primitive number is greater than or equal to another - */ - assert(typeof actual === "number", - "assert_greater_than_equal", description, - "expected a number but got a ${type_actual}", - {type_actual:typeof actual}); - - assert(actual >= expected, - "assert_greater_than_equal", description, - "expected a number greater than or equal to ${expected} but got ${actual}", - {expected:expected, actual:actual}); - } - expose(assert_greater_than_equal, "assert_greater_than_equal"); - - function assert_between_inclusive(actual, lower, upper, description) - { - /* - * Test if a primitive number is between to two others or equal to either of them - */ - assert(typeof actual === "number", - "assert_between_inclusive", description, - "expected a number but got a ${type_actual}", - {type_actual:typeof actual}); - - assert(actual >= lower && actual <= upper, - "assert_between_inclusive", description, - "expected a number greater than or equal to ${lower} " + - "and less than or equal to ${upper} but got ${actual}", - {lower:lower, upper:upper, actual:actual}); - } - expose(assert_between_inclusive, "assert_between_inclusive"); - - function assert_regexp_match(actual, expected, description) { - /* - * Test if a string (actual) matches a regexp (expected) - */ - assert(expected.test(actual), - "assert_regexp_match", description, - "expected ${expected} but got ${actual}", - {expected:expected, actual:actual}); - } - expose(assert_regexp_match, "assert_regexp_match"); - - function assert_class_string(object, class_string, description) { - assert_equals({}.toString.call(object), "[object " + class_string + "]", - description); - } - expose(assert_class_string, "assert_class_string"); - - - function _assert_own_property(name) { - return function(object, property_name, description) - { - assert(object.hasOwnProperty(property_name), - name, description, - "expected property ${p} missing", {p:property_name}); - }; - } - expose(_assert_own_property("assert_exists"), "assert_exists"); - expose(_assert_own_property("assert_own_property"), "assert_own_property"); - - function assert_not_exists(object, property_name, description) - { - assert(!object.hasOwnProperty(property_name), - "assert_not_exists", description, - "unexpected property ${p} found", {p:property_name}); - } - expose(assert_not_exists, "assert_not_exists"); - - function _assert_inherits(name) { - return function (object, property_name, description) - { - assert(typeof object === "object" || typeof object === "function", - name, description, - "provided value is not an object"); - - assert("hasOwnProperty" in object, - name, description, - "provided value is an object but has no hasOwnProperty method"); - - assert(!object.hasOwnProperty(property_name), - name, description, - "property ${p} found on object expected in prototype chain", - {p:property_name}); - - assert(property_name in object, - name, description, - "property ${p} not found in prototype chain", - {p:property_name}); - }; - } - expose(_assert_inherits("assert_inherits"), "assert_inherits"); - expose(_assert_inherits("assert_idl_attribute"), "assert_idl_attribute"); - - function assert_readonly(object, property_name, description) - { - var initial_value = object[property_name]; - try { - //Note that this can have side effects in the case where - //the property has PutForwards - object[property_name] = initial_value + "a"; //XXX use some other value here? - assert(same_value(object[property_name], initial_value), - "assert_readonly", description, - "changing property ${p} succeeded", - {p:property_name}); - } finally { - object[property_name] = initial_value; - } - } - expose(assert_readonly, "assert_readonly"); - - function assert_throws(code, func, description) - { - try { - func.call(this); - assert(false, "assert_throws", description, - "${func} did not throw", {func:func}); - } catch (e) { - if (e instanceof AssertionError) { - throw e; - } - if (code === null) { - return; - } - if (typeof code === "object") { - assert(typeof e == "object" && "name" in e && e.name == code.name, - "assert_throws", description, - "${func} threw ${actual} (${actual_name}) expected ${expected} (${expected_name})", - {func:func, actual:e, actual_name:e.name, - expected:code, - expected_name:code.name}); - return; - } - - var code_name_map = { - INDEX_SIZE_ERR: 'IndexSizeError', - HIERARCHY_REQUEST_ERR: 'HierarchyRequestError', - WRONG_DOCUMENT_ERR: 'WrongDocumentError', - INVALID_CHARACTER_ERR: 'InvalidCharacterError', - NO_MODIFICATION_ALLOWED_ERR: 'NoModificationAllowedError', - NOT_FOUND_ERR: 'NotFoundError', - NOT_SUPPORTED_ERR: 'NotSupportedError', - INUSE_ATTRIBUTE_ERR: 'InUseAttributeError', - INVALID_STATE_ERR: 'InvalidStateError', - SYNTAX_ERR: 'SyntaxError', - INVALID_MODIFICATION_ERR: 'InvalidModificationError', - NAMESPACE_ERR: 'NamespaceError', - INVALID_ACCESS_ERR: 'InvalidAccessError', - TYPE_MISMATCH_ERR: 'TypeMismatchError', - SECURITY_ERR: 'SecurityError', - NETWORK_ERR: 'NetworkError', - ABORT_ERR: 'AbortError', - URL_MISMATCH_ERR: 'URLMismatchError', - QUOTA_EXCEEDED_ERR: 'QuotaExceededError', - TIMEOUT_ERR: 'TimeoutError', - INVALID_NODE_TYPE_ERR: 'InvalidNodeTypeError', - DATA_CLONE_ERR: 'DataCloneError' - }; - - var name = code in code_name_map ? code_name_map[code] : code; - - var name_code_map = { - IndexSizeError: 1, - HierarchyRequestError: 3, - WrongDocumentError: 4, - InvalidCharacterError: 5, - NoModificationAllowedError: 7, - NotFoundError: 8, - NotSupportedError: 9, - InUseAttributeError: 10, - InvalidStateError: 11, - SyntaxError: 12, - InvalidModificationError: 13, - NamespaceError: 14, - InvalidAccessError: 15, - TypeMismatchError: 17, - SecurityError: 18, - NetworkError: 19, - AbortError: 20, - URLMismatchError: 21, - QuotaExceededError: 22, - TimeoutError: 23, - InvalidNodeTypeError: 24, - DataCloneError: 25, - - EncodingError: 0, - NotReadableError: 0, - UnknownError: 0, - ConstraintError: 0, - DataError: 0, - TransactionInactiveError: 0, - ReadOnlyError: 0, - VersionError: 0, - OperationError: 0, - }; - - if (!(name in name_code_map)) { - throw new AssertionError('Test bug: unrecognized DOMException code "' + code + '" passed to assert_throws()'); - } - - var required_props = { code: name_code_map[name] }; - - if (required_props.code === 0 || - (typeof e == "object" && - "name" in e && - e.name !== e.name.toUpperCase() && - e.name !== "DOMException")) { - // New style exception: also test the name property. - required_props.name = name; - } - - //We'd like to test that e instanceof the appropriate interface, - //but we can't, because we don't know what window it was created - //in. It might be an instanceof the appropriate interface on some - //unknown other window. TODO: Work around this somehow? - - assert(typeof e == "object", - "assert_throws", description, - "${func} threw ${e} with type ${type}, not an object", - {func:func, e:e, type:typeof e}); - - for (var prop in required_props) { - assert(typeof e == "object" && prop in e && e[prop] == required_props[prop], - "assert_throws", description, - "${func} threw ${e} that is not a DOMException " + code + ": property ${prop} is equal to ${actual}, expected ${expected}", - {func:func, e:e, prop:prop, actual:e[prop], expected:required_props[prop]}); - } - } - } - expose(assert_throws, "assert_throws"); - - function assert_unreached(description) { - assert(false, "assert_unreached", description, - "Reached unreachable code"); - } - expose(assert_unreached, "assert_unreached"); - - function assert_any(assert_func, actual, expected_array) - { - var args = [].slice.call(arguments, 3); - var errors = []; - var passed = false; - forEach(expected_array, - function(expected) - { - try { - assert_func.apply(this, [actual, expected].concat(args)); - passed = true; - } catch (e) { - errors.push(e.message); - } - }); - if (!passed) { - throw new AssertionError(errors.join("\n\n")); - } - } - expose(assert_any, "assert_any"); - - function Test(name, properties) - { - if (tests.file_is_test && tests.tests.length) { - throw new Error("Tried to create a test with file_is_test"); - } - this.name = name; - - this.phase = this.phases.INITIAL; - - this.status = this.NOTRUN; - this.timeout_id = null; - this.index = null; - - this.properties = properties; - var timeout = properties.timeout ? properties.timeout : settings.test_timeout; - if (timeout !== null) { - this.timeout_length = timeout * tests.timeout_multiplier; - } else { - this.timeout_length = null; - } - - this.message = null; - this.stack = null; - - this.steps = []; - - this.cleanup_callbacks = []; - - tests.push(this); - } - - Test.statuses = { - PASS:0, - FAIL:1, - TIMEOUT:2, - NOTRUN:3 - }; - - Test.prototype = merge({}, Test.statuses); - - Test.prototype.phases = { - INITIAL:0, - STARTED:1, - HAS_RESULT:2, - COMPLETE:3 - }; - - Test.prototype.structured_clone = function() - { - if (!this._structured_clone) { - var msg = this.message; - msg = msg ? String(msg) : msg; - this._structured_clone = merge({ - name:String(this.name), - properties:merge({}, this.properties), - }, Test.statuses); - } - this._structured_clone.status = this.status; - this._structured_clone.message = this.message; - this._structured_clone.stack = this.stack; - this._structured_clone.index = this.index; - return this._structured_clone; - }; - - Test.prototype.step = function(func, this_obj) - { - if (this.phase > this.phases.STARTED) { - return; - } - this.phase = this.phases.STARTED; - //If we don't get a result before the harness times out that will be a test timout - this.set_status(this.TIMEOUT, "Test timed out"); - - tests.started = true; - tests.notify_test_state(this); - - if (this.timeout_id === null) { - this.set_timeout(); - } - - this.steps.push(func); - - if (arguments.length === 1) { - this_obj = this; - } - - try { - return func.apply(this_obj, Array.prototype.slice.call(arguments, 2)); - } catch (e) { - if (this.phase >= this.phases.HAS_RESULT) { - return; - } - var message = String((typeof e === "object" && e !== null) ? e.message : e); - var stack = e.stack ? e.stack : null; - - this.set_status(this.FAIL, message, stack); - this.phase = this.phases.HAS_RESULT; - this.done(); - } - }; - - Test.prototype.step_func = function(func, this_obj) - { - var test_this = this; - - if (arguments.length === 1) { - this_obj = test_this; - } - - return function() - { - return test_this.step.apply(test_this, [func, this_obj].concat( - Array.prototype.slice.call(arguments))); - }; - }; - - Test.prototype.step_func_done = function(func, this_obj) - { - var test_this = this; - - if (arguments.length === 1) { - this_obj = test_this; - } - - return function() - { - if (func) { - test_this.step.apply(test_this, [func, this_obj].concat( - Array.prototype.slice.call(arguments))); - } - test_this.done(); - }; - }; - - Test.prototype.unreached_func = function(description) - { - return this.step_func(function() { - assert_unreached(description); - }); - }; - - Test.prototype.step_timeout = function(f, timeout) { - var test_this = this; - var args = Array.prototype.slice.call(arguments, 2); - return setTimeout(this.step_func(function() { - return f.apply(test_this, args); - }, timeout * tests.timeout_multiplier)); - } - - Test.prototype.add_cleanup = function(callback) { - this.cleanup_callbacks.push(callback); - }; - - Test.prototype.force_timeout = function() { - this.set_status(this.TIMEOUT); - this.phase = this.phases.HAS_RESULT; - }; - - Test.prototype.set_timeout = function() - { - if (this.timeout_length !== null) { - var this_obj = this; - this.timeout_id = setTimeout(function() - { - this_obj.timeout(); - }, this.timeout_length); - } - }; - - Test.prototype.set_status = function(status, message, stack) - { - this.status = status; - this.message = message; - this.stack = stack ? stack : null; - }; - - Test.prototype.timeout = function() - { - this.timeout_id = null; - this.set_status(this.TIMEOUT, "Test timed out"); - this.phase = this.phases.HAS_RESULT; - this.done(); - }; - - Test.prototype.done = function() - { - if (this.phase == this.phases.COMPLETE) { - return; - } - - if (this.phase <= this.phases.STARTED) { - this.set_status(this.PASS, null); - } - - this.phase = this.phases.COMPLETE; - - clearTimeout(this.timeout_id); - tests.result(this); - this.cleanup(); - }; - - Test.prototype.cleanup = function() { - forEach(this.cleanup_callbacks, - function(cleanup_callback) { - cleanup_callback(); - }); - }; - - /* - * A RemoteTest object mirrors a Test object on a remote worker. The - * associated RemoteWorker updates the RemoteTest object in response to - * received events. In turn, the RemoteTest object replicates these events - * on the local document. This allows listeners (test result reporting - * etc..) to transparently handle local and remote events. - */ - function RemoteTest(clone) { - var this_obj = this; - Object.keys(clone).forEach( - function(key) { - this_obj[key] = clone[key]; - }); - this.index = null; - this.phase = this.phases.INITIAL; - this.update_state_from(clone); - tests.push(this); - } - - RemoteTest.prototype.structured_clone = function() { - var clone = {}; - Object.keys(this).forEach( - (function(key) { - if (typeof(this[key]) === "object") { - clone[key] = merge({}, this[key]); - } else { - clone[key] = this[key]; - } - }).bind(this)); - clone.phases = merge({}, this.phases); - return clone; - }; - - RemoteTest.prototype.cleanup = function() {}; - RemoteTest.prototype.phases = Test.prototype.phases; - RemoteTest.prototype.update_state_from = function(clone) { - this.status = clone.status; - this.message = clone.message; - this.stack = clone.stack; - if (this.phase === this.phases.INITIAL) { - this.phase = this.phases.STARTED; - } - }; - RemoteTest.prototype.done = function() { - this.phase = this.phases.COMPLETE; - } - - /* - * A RemoteWorker listens for test events from a worker. These events are - * then used to construct and maintain RemoteTest objects that mirror the - * tests running on the remote worker. - */ - function RemoteWorker(worker) { - this.running = true; - this.tests = new Array(); - - var this_obj = this; - worker.onerror = function(error) { this_obj.worker_error(error); }; - - var message_port; - - if (is_service_worker(worker)) { - if (window.MessageChannel) { - // The ServiceWorker's implicit MessagePort is currently not - // reliably accessible from the ServiceWorkerGlobalScope due to - // Blink setting MessageEvent.source to null for messages sent - // via ServiceWorker.postMessage(). Until that's resolved, - // create an explicit MessageChannel and pass one end to the - // worker. - var message_channel = new MessageChannel(); - message_port = message_channel.port1; - message_port.start(); - worker.postMessage({type: "connect"}, [message_channel.port2]); - } else { - // If MessageChannel is not available, then try the - // ServiceWorker.postMessage() approach using MessageEvent.source - // on the other end. - message_port = navigator.serviceWorker; - worker.postMessage({type: "connect"}); - } - } else if (is_shared_worker(worker)) { - message_port = worker.port; - } else { - message_port = worker; - } - - // Keeping a reference to the worker until worker_done() is seen - // prevents the Worker object and its MessageChannel from going away - // before all the messages are dispatched. - this.worker = worker; - - message_port.onmessage = - function(message) { - if (this_obj.running && (message.data.type in this_obj.message_handlers)) { - this_obj.message_handlers[message.data.type].call(this_obj, message.data); - } - }; - } - - RemoteWorker.prototype.worker_error = function(error) { - var message = error.message || String(error); - var filename = (error.filename ? " " + error.filename: ""); - // FIXME: Display worker error states separately from main document - // error state. - this.worker_done({ - status: { - status: tests.status.ERROR, - message: "Error in worker" + filename + ": " + message, - stack: error.stack - } - }); - error.preventDefault(); - }; - - RemoteWorker.prototype.test_state = function(data) { - var remote_test = this.tests[data.test.index]; - if (!remote_test) { - remote_test = new RemoteTest(data.test); - this.tests[data.test.index] = remote_test; - } - remote_test.update_state_from(data.test); - tests.notify_test_state(remote_test); - }; - - RemoteWorker.prototype.test_done = function(data) { - var remote_test = this.tests[data.test.index]; - remote_test.update_state_from(data.test); - remote_test.done(); - tests.result(remote_test); - }; - - RemoteWorker.prototype.worker_done = function(data) { - if (tests.status.status === null && - data.status.status !== data.status.OK) { - tests.status.status = data.status.status; - tests.status.message = data.status.message; - tests.status.stack = data.status.stack; - } - this.running = false; - this.worker = null; - if (tests.all_done()) { - tests.complete(); - } - }; - - RemoteWorker.prototype.message_handlers = { - test_state: RemoteWorker.prototype.test_state, - result: RemoteWorker.prototype.test_done, - complete: RemoteWorker.prototype.worker_done - }; - - /* - * Harness - */ - - function TestsStatus() - { - this.status = null; - this.message = null; - this.stack = null; - } - - TestsStatus.statuses = { - OK:0, - ERROR:1, - TIMEOUT:2 - }; - - TestsStatus.prototype = merge({}, TestsStatus.statuses); - - TestsStatus.prototype.structured_clone = function() - { - if (!this._structured_clone) { - var msg = this.message; - msg = msg ? String(msg) : msg; - this._structured_clone = merge({ - status:this.status, - message:msg, - stack:this.stack - }, TestsStatus.statuses); - } - return this._structured_clone; - }; - - function Tests() - { - this.tests = []; - this.num_pending = 0; - - this.phases = { - INITIAL:0, - SETUP:1, - HAVE_TESTS:2, - HAVE_RESULTS:3, - COMPLETE:4 - }; - this.phase = this.phases.INITIAL; - - this.properties = {}; - - this.wait_for_finish = false; - this.processing_callbacks = false; - - this.allow_uncaught_exception = false; - - this.file_is_test = false; - - this.timeout_multiplier = 1; - this.timeout_length = test_environment.test_timeout(); - this.timeout_id = null; - - this.start_callbacks = []; - this.test_state_callbacks = []; - this.test_done_callbacks = []; - this.all_done_callbacks = []; - - this.pending_workers = []; - - this.status = new TestsStatus(); - - var this_obj = this; - - test_environment.add_on_loaded_callback(function() { - if (this_obj.all_done()) { - this_obj.complete(); - } - }); - - this.set_timeout(); - } - - Tests.prototype.setup = function(func, properties) - { - if (this.phase >= this.phases.HAVE_RESULTS) { - return; - } - - if (this.phase < this.phases.SETUP) { - this.phase = this.phases.SETUP; - } - - this.properties = properties; - - for (var p in properties) { - if (properties.hasOwnProperty(p)) { - var value = properties[p]; - if (p == "allow_uncaught_exception") { - this.allow_uncaught_exception = value; - } else if (p == "explicit_done" && value) { - this.wait_for_finish = true; - } else if (p == "explicit_timeout" && value) { - this.timeout_length = null; - if (this.timeout_id) - { - clearTimeout(this.timeout_id); - } - } else if (p == "timeout_multiplier") { - this.timeout_multiplier = value; - } - } - } - - if (func) { - try { - func(); - } catch (e) { - this.status.status = this.status.ERROR; - this.status.message = String(e); - this.status.stack = e.stack ? e.stack : null; - } - } - this.set_timeout(); - }; - - Tests.prototype.set_file_is_test = function() { - if (this.tests.length > 0) { - throw new Error("Tried to set file as test after creating a test"); - } - this.wait_for_finish = true; - this.file_is_test = true; - // Create the test, which will add it to the list of tests - async_test(); - }; - - Tests.prototype.set_timeout = function() { - var this_obj = this; - clearTimeout(this.timeout_id); - if (this.timeout_length !== null) { - this.timeout_id = setTimeout(function() { - this_obj.timeout(); - }, this.timeout_length); - } - }; - - Tests.prototype.timeout = function() { - if (this.status.status === null) { - this.status.status = this.status.TIMEOUT; - } - this.complete(); - }; - - Tests.prototype.end_wait = function() - { - this.wait_for_finish = false; - if (this.all_done()) { - this.complete(); - } - }; - - Tests.prototype.push = function(test) - { - if (this.phase < this.phases.HAVE_TESTS) { - this.start(); - } - this.num_pending++; - test.index = this.tests.push(test); - this.notify_test_state(test); - }; - - Tests.prototype.notify_test_state = function(test) { - var this_obj = this; - forEach(this.test_state_callbacks, - function(callback) { - callback(test, this_obj); - }); - }; - - Tests.prototype.all_done = function() { - return (this.tests.length > 0 && test_environment.all_loaded && - this.num_pending === 0 && !this.wait_for_finish && - !this.processing_callbacks && - !this.pending_workers.some(function(w) { return w.running; })); - }; - - Tests.prototype.start = function() { - this.phase = this.phases.HAVE_TESTS; - this.notify_start(); - }; - - Tests.prototype.notify_start = function() { - var this_obj = this; - forEach (this.start_callbacks, - function(callback) - { - callback(this_obj.properties); - }); - }; - - Tests.prototype.result = function(test) - { - if (this.phase > this.phases.HAVE_RESULTS) { - return; - } - this.phase = this.phases.HAVE_RESULTS; - this.num_pending--; - this.notify_result(test); - }; - - Tests.prototype.notify_result = function(test) { - var this_obj = this; - this.processing_callbacks = true; - forEach(this.test_done_callbacks, - function(callback) - { - callback(test, this_obj); - }); - this.processing_callbacks = false; - if (this_obj.all_done()) { - this_obj.complete(); - } - }; - - Tests.prototype.complete = function() { - if (this.phase === this.phases.COMPLETE) { - return; - } - this.phase = this.phases.COMPLETE; - var this_obj = this; - this.tests.forEach( - function(x) - { - if (x.phase < x.phases.COMPLETE) { - this_obj.notify_result(x); - x.cleanup(); - x.phase = x.phases.COMPLETE; - } - } - ); - this.notify_complete(); - }; - - Tests.prototype.notify_complete = function() { - var this_obj = this; - if (this.status.status === null) { - this.status.status = this.status.OK; - } - - forEach (this.all_done_callbacks, - function(callback) - { - callback(this_obj.tests, this_obj.status); - }); - }; - - Tests.prototype.fetch_tests_from_worker = function(worker) { - if (this.phase >= this.phases.COMPLETE) { - return; - } - - this.pending_workers.push(new RemoteWorker(worker)); - }; - - function fetch_tests_from_worker(port) { - tests.fetch_tests_from_worker(port); - } - expose(fetch_tests_from_worker, 'fetch_tests_from_worker'); - - function timeout() { - if (tests.timeout_length === null) { - tests.timeout(); - } - } - expose(timeout, 'timeout'); - - function add_start_callback(callback) { - tests.start_callbacks.push(callback); - } - - function add_test_state_callback(callback) { - tests.test_state_callbacks.push(callback); - } - - function add_result_callback(callback) { - tests.test_done_callbacks.push(callback); - } - - function add_completion_callback(callback) { - tests.all_done_callbacks.push(callback); - } - - expose(add_start_callback, 'add_start_callback'); - expose(add_test_state_callback, 'add_test_state_callback'); - expose(add_result_callback, 'add_result_callback'); - expose(add_completion_callback, 'add_completion_callback'); - - function remove(array, item) { - var index = array.indexOf(item); - if (index > -1) { - array.splice(index, 1); - } - } - - function remove_start_callback(callback) { - remove(tests.start_callbacks, callback); - } - - function remove_test_state_callback(callback) { - remove(tests.test_state_callbacks, callback); - } - - function remove_result_callback(callback) { - remove(tests.test_done_callbacks, callback); - } - - function remove_completion_callback(callback) { - remove(tests.all_done_callbacks, callback); - } - - /* - * Output listener - */ - - function Output() { - this.output_document = document; - this.output_node = null; - this.enabled = settings.output; - this.phase = this.INITIAL; - } - - Output.prototype.INITIAL = 0; - Output.prototype.STARTED = 1; - Output.prototype.HAVE_RESULTS = 2; - Output.prototype.COMPLETE = 3; - - Output.prototype.setup = function(properties) { - if (this.phase > this.INITIAL) { - return; - } - - //If output is disabled in testharnessreport.js the test shouldn't be - //able to override that - this.enabled = this.enabled && (properties.hasOwnProperty("output") ? - properties.output : settings.output); - }; - - Output.prototype.init = function(properties) { - if (this.phase >= this.STARTED) { - return; - } - if (properties.output_document) { - this.output_document = properties.output_document; - } else { - this.output_document = document; - } - this.phase = this.STARTED; - }; - - Output.prototype.resolve_log = function() { - var output_document; - if (typeof this.output_document === "function") { - output_document = this.output_document.apply(undefined); - } else { - output_document = this.output_document; - } - if (!output_document) { - return; - } - var node = output_document.getElementById("log"); - if (!node) { - if (!document.body || document.readyState == "loading") { - return; - } - node = output_document.createElement("div"); - node.id = "log"; - output_document.body.appendChild(node); - } - this.output_document = output_document; - this.output_node = node; - }; - - Output.prototype.show_status = function() { - if (this.phase < this.STARTED) { - this.init(); - } - if (!this.enabled) { - return; - } - if (this.phase < this.HAVE_RESULTS) { - this.resolve_log(); - this.phase = this.HAVE_RESULTS; - } - var done_count = tests.tests.length - tests.num_pending; - if (this.output_node) { - if (done_count < 100 || - (done_count < 1000 && done_count % 100 === 0) || - done_count % 1000 === 0) { - this.output_node.textContent = "Running, " + - done_count + " complete, " + - tests.num_pending + " remain"; - } - } - }; - - Output.prototype.show_results = function (tests, harness_status) { - if (this.phase >= this.COMPLETE) { - return; - } - if (!this.enabled) { - return; - } - if (!this.output_node) { - this.resolve_log(); - } - this.phase = this.COMPLETE; - - var log = this.output_node; - if (!log) { - return; - } - var output_document = this.output_document; - - while (log.lastChild) { - log.removeChild(log.lastChild); - } - - var harness_url = get_harness_url(); - if (harness_url !== null) { - var stylesheet = output_document.createElementNS(xhtml_ns, "link"); - stylesheet.setAttribute("rel", "stylesheet"); - stylesheet.setAttribute("href", harness_url + "testharness.css"); - var heads = output_document.getElementsByTagName("head"); - if (heads.length) { - heads[0].appendChild(stylesheet); - } - } - - var status_text_harness = {}; - status_text_harness[harness_status.OK] = "OK"; - status_text_harness[harness_status.ERROR] = "Error"; - status_text_harness[harness_status.TIMEOUT] = "Timeout"; - - var status_text = {}; - status_text[Test.prototype.PASS] = "Pass"; - status_text[Test.prototype.FAIL] = "Fail"; - status_text[Test.prototype.TIMEOUT] = "Timeout"; - status_text[Test.prototype.NOTRUN] = "Not Run"; - - var status_number = {}; - forEach(tests, - function(test) { - var status = status_text[test.status]; - if (status_number.hasOwnProperty(status)) { - status_number[status] += 1; - } else { - status_number[status] = 1; - } - }); - - function status_class(status) - { - return status.replace(/\s/g, '').toLowerCase(); - } - - var summary_template = ["section", {"id":"summary"}, - ["h2", {}, "Summary"], - function() - { - - var status = status_text_harness[harness_status.status]; - var rv = [["section", {}, - ["p", {}, - "Harness status: ", - ["span", {"class":status_class(status)}, - status - ], - ] - ]]; - - if (harness_status.status === harness_status.ERROR) { - rv[0].push(["pre", {}, harness_status.message]); - if (harness_status.stack) { - rv[0].push(["pre", {}, harness_status.stack]); - } - } - return rv; - }, - ["p", {}, "Found ${num_tests} tests"], - function() { - var rv = [["div", {}]]; - var i = 0; - while (status_text.hasOwnProperty(i)) { - if (status_number.hasOwnProperty(status_text[i])) { - var status = status_text[i]; - rv[0].push(["div", {"class":status_class(status)}, - ["label", {}, - ["input", {type:"checkbox", checked:"checked"}], - status_number[status] + " " + status]]); - } - i++; - } - return rv; - }, - ]; - - log.appendChild(render(summary_template, {num_tests:tests.length}, output_document)); - - forEach(output_document.querySelectorAll("section#summary label"), - function(element) - { - on_event(element, "click", - function(e) - { - if (output_document.getElementById("results") === null) { - e.preventDefault(); - return; - } - var result_class = element.parentNode.getAttribute("class"); - var style_element = output_document.querySelector("style#hide-" + result_class); - var input_element = element.querySelector("input"); - if (!style_element && !input_element.checked) { - style_element = output_document.createElementNS(xhtml_ns, "style"); - style_element.id = "hide-" + result_class; - style_element.textContent = "table#results > tbody > tr."+result_class+"{display:none}"; - output_document.body.appendChild(style_element); - } else if (style_element && input_element.checked) { - style_element.parentNode.removeChild(style_element); - } - }); - }); - - // This use of innerHTML plus manual escaping is not recommended in - // general, but is necessary here for performance. Using textContent - // on each individual <td> adds tens of seconds of execution time for - // large test suites (tens of thousands of tests). - function escape_html(s) - { - return s.replace(/\&/g, "&") - .replace(/</g, "<") - .replace(/"/g, """) - .replace(/'/g, "'"); - } - - function has_assertions() - { - for (var i = 0; i < tests.length; i++) { - if (tests[i].properties.hasOwnProperty("assert")) { - return true; - } - } - return false; - } - - function get_assertion(test) - { - if (test.properties.hasOwnProperty("assert")) { - if (Array.isArray(test.properties.assert)) { - return test.properties.assert.join(' '); - } - return test.properties.assert; - } - return ''; - } - - log.appendChild(document.createElementNS(xhtml_ns, "section")); - var assertions = has_assertions(); - var html = "<h2>Details</h2><table id='results' " + (assertions ? "class='assertions'" : "" ) + ">" + - "<thead><tr><th>Result</th><th>Test Name</th>" + - (assertions ? "<th>Assertion</th>" : "") + - "<th>Message</th></tr></thead>" + - "<tbody>"; - for (var i = 0; i < tests.length; i++) { - html += '<tr class="' + - escape_html(status_class(status_text[tests[i].status])) + - '"><td>' + - escape_html(status_text[tests[i].status]) + - "</td><td>" + - escape_html(tests[i].name) + - "</td><td>" + - (assertions ? escape_html(get_assertion(tests[i])) + "</td><td>" : "") + - escape_html(tests[i].message ? tests[i].message : " ") + - (tests[i].stack ? "<pre>" + - escape_html(tests[i].stack) + - "</pre>": "") + - "</td></tr>"; - } - html += "</tbody></table>"; - try { - log.lastChild.innerHTML = html; - } catch (e) { - log.appendChild(document.createElementNS(xhtml_ns, "p")) - .textContent = "Setting innerHTML for the log threw an exception."; - log.appendChild(document.createElementNS(xhtml_ns, "pre")) - .textContent = html; - } - }; - - /* - * Template code - * - * A template is just a javascript structure. An element is represented as: - * - * [tag_name, {attr_name:attr_value}, child1, child2] - * - * the children can either be strings (which act like text nodes), other templates or - * functions (see below) - * - * A text node is represented as - * - * ["{text}", value] - * - * String values have a simple substitution syntax; ${foo} represents a variable foo. - * - * It is possible to embed logic in templates by using a function in a place where a - * node would usually go. The function must either return part of a template or null. - * - * In cases where a set of nodes are required as output rather than a single node - * with children it is possible to just use a list - * [node1, node2, node3] - * - * Usage: - * - * render(template, substitutions) - take a template and an object mapping - * variable names to parameters and return either a DOM node or a list of DOM nodes - * - * substitute(template, substitutions) - take a template and variable mapping object, - * make the variable substitutions and return the substituted template - * - */ - - function is_single_node(template) - { - return typeof template[0] === "string"; - } - - function substitute(template, substitutions) - { - if (typeof template === "function") { - var replacement = template(substitutions); - if (!replacement) { - return null; - } - - return substitute(replacement, substitutions); - } - - if (is_single_node(template)) { - return substitute_single(template, substitutions); - } - - return filter(map(template, function(x) { - return substitute(x, substitutions); - }), function(x) {return x !== null;}); - } - - function substitute_single(template, substitutions) - { - var substitution_re = /\$\{([^ }]*)\}/g; - - function do_substitution(input) { - var components = input.split(substitution_re); - var rv = []; - for (var i = 0; i < components.length; i += 2) { - rv.push(components[i]); - if (components[i + 1]) { - rv.push(String(substitutions[components[i + 1]])); - } - } - return rv; - } - - function substitute_attrs(attrs, rv) - { - rv[1] = {}; - for (var name in template[1]) { - if (attrs.hasOwnProperty(name)) { - var new_name = do_substitution(name).join(""); - var new_value = do_substitution(attrs[name]).join(""); - rv[1][new_name] = new_value; - } - } - } - - function substitute_children(children, rv) - { - for (var i = 0; i < children.length; i++) { - if (children[i] instanceof Object) { - var replacement = substitute(children[i], substitutions); - if (replacement !== null) { - if (is_single_node(replacement)) { - rv.push(replacement); - } else { - extend(rv, replacement); - } - } - } else { - extend(rv, do_substitution(String(children[i]))); - } - } - return rv; - } - - var rv = []; - rv.push(do_substitution(String(template[0])).join("")); - - if (template[0] === "{text}") { - substitute_children(template.slice(1), rv); - } else { - substitute_attrs(template[1], rv); - substitute_children(template.slice(2), rv); - } - - return rv; - } - - function make_dom_single(template, doc) - { - var output_document = doc || document; - var element; - if (template[0] === "{text}") { - element = output_document.createTextNode(""); - for (var i = 1; i < template.length; i++) { - element.data += template[i]; - } - } else { - element = output_document.createElementNS(xhtml_ns, template[0]); - for (var name in template[1]) { - if (template[1].hasOwnProperty(name)) { - element.setAttribute(name, template[1][name]); - } - } - for (var i = 2; i < template.length; i++) { - if (template[i] instanceof Object) { - var sub_element = make_dom(template[i]); - element.appendChild(sub_element); - } else { - var text_node = output_document.createTextNode(template[i]); - element.appendChild(text_node); - } - } - } - - return element; - } - - function make_dom(template, substitutions, output_document) - { - if (is_single_node(template)) { - return make_dom_single(template, output_document); - } - - return map(template, function(x) { - return make_dom_single(x, output_document); - }); - } - - function render(template, substitutions, output_document) - { - return make_dom(substitute(template, substitutions), output_document); - } - - /* - * Utility funcions - */ - function assert(expected_true, function_name, description, error, substitutions) - { - if (tests.tests.length === 0) { - tests.set_file_is_test(); - } - if (expected_true !== true) { - var msg = make_message(function_name, description, - error, substitutions); - throw new AssertionError(msg); - } - } - - function AssertionError(message) - { - this.message = message; - this.stack = this.get_stack(); - } - - AssertionError.prototype = Object.create(Error.prototype); - - AssertionError.prototype.get_stack = function() { - var stack = new Error().stack; - // IE11 does not initialize 'Error.stack' until the object is thrown. - if (!stack) { - try { - throw new Error(); - } catch (e) { - stack = e.stack; - } - } - - var lines = stack.split("\n"); - - // Create a pattern to match stack frames originating within testharness.js. These include the - // script URL, followed by the line/col (e.g., '/resources/testharness.js:120:21'). - var re = new RegExp((get_script_url() || "\\btestharness.js") + ":\\d+:\\d+"); - - // Some browsers include a preamble that specifies the type of the error object. Skip this by - // advancing until we find the first stack frame originating from testharness.js. - var i = 0; - while (!re.test(lines[i]) && i < lines.length) { - i++; - } - - // Then skip the top frames originating from testharness.js to begin the stack at the test code. - while (re.test(lines[i]) && i < lines.length) { - i++; - } - - // Paranoid check that we didn't skip all frames. If so, return the original stack unmodified. - if (i >= lines.length) { - return stack; - } - - return lines.slice(i).join("\n"); - } - - function make_message(function_name, description, error, substitutions) - { - for (var p in substitutions) { - if (substitutions.hasOwnProperty(p)) { - substitutions[p] = format_value(substitutions[p]); - } - } - var node_form = substitute(["{text}", "${function_name}: ${description}" + error], - merge({function_name:function_name, - description:(description?description + " ":"")}, - substitutions)); - return node_form.slice(1).join(""); - } - - function filter(array, callable, thisObj) { - var rv = []; - for (var i = 0; i < array.length; i++) { - if (array.hasOwnProperty(i)) { - var pass = callable.call(thisObj, array[i], i, array); - if (pass) { - rv.push(array[i]); - } - } - } - return rv; - } - - function map(array, callable, thisObj) - { - var rv = []; - rv.length = array.length; - for (var i = 0; i < array.length; i++) { - if (array.hasOwnProperty(i)) { - rv[i] = callable.call(thisObj, array[i], i, array); - } - } - return rv; - } - - function extend(array, items) - { - Array.prototype.push.apply(array, items); - } - - function forEach(array, callback, thisObj) - { - for (var i = 0; i < array.length; i++) { - if (array.hasOwnProperty(i)) { - callback.call(thisObj, array[i], i, array); - } - } - } - - function merge(a,b) - { - var rv = {}; - var p; - for (p in a) { - rv[p] = a[p]; - } - for (p in b) { - rv[p] = b[p]; - } - return rv; - } - - function expose(object, name) - { - var components = name.split("."); - var target = test_environment.global_scope(); - for (var i = 0; i < components.length - 1; i++) { - if (!(components[i] in target)) { - target[components[i]] = {}; - } - target = target[components[i]]; - } - target[components[components.length - 1]] = object; - } - - function is_same_origin(w) { - try { - 'random_prop' in w; - return true; - } catch (e) { - return false; - } - } - - /** Returns the 'src' URL of the first <script> tag in the page to include the file 'testharness.js'. */ - function get_script_url() - { - if (!('document' in self)) { - return undefined; - } - - var scripts = document.getElementsByTagName("script"); - for (var i = 0; i < scripts.length; i++) { - var src; - if (scripts[i].src) { - src = scripts[i].src; - } else if (scripts[i].href) { - //SVG case - src = scripts[i].href.baseVal; - } - - var matches = src && src.match(/^(.*\/|)testharness\.js$/); - if (matches) { - return src; - } - } - return undefined; - } - - /** Returns the URL path at which the files for testharness.js are assumed to reside (e.g., '/resources/'). - The path is derived from inspecting the 'src' of the <script> tag that included 'testharness.js'. */ - function get_harness_url() - { - var script_url = get_script_url(); - - // Exclude the 'testharness.js' file from the returned path, but '+ 1' to include the trailing slash. - return script_url ? script_url.slice(0, script_url.lastIndexOf('/') + 1) : undefined; - } - - function supports_post_message(w) - { - var supports; - var type; - // Given IE implements postMessage across nested iframes but not across - // windows or tabs, you can't infer cross-origin communication from the presence - // of postMessage on the current window object only. - // - // Touching the postMessage prop on a window can throw if the window is - // not from the same origin AND post message is not supported in that - // browser. So just doing an existence test here won't do, you also need - // to wrap it in a try..cacth block. - try { - type = typeof w.postMessage; - if (type === "function") { - supports = true; - } - - // IE8 supports postMessage, but implements it as a host object which - // returns "object" as its `typeof`. - else if (type === "object") { - supports = true; - } - - // This is the case where postMessage isn't supported AND accessing a - // window property across origins does NOT throw (e.g. old Safari browser). - else { - supports = false; - } - } catch (e) { - // This is the case where postMessage isn't supported AND accessing a - // window property across origins throws (e.g. old Firefox browser). - supports = false; - } - return supports; - } - - /** - * Setup globals - */ - - var tests = new Tests(); - - addEventListener("error", function(e) { - if (tests.file_is_test) { - var test = tests.tests[0]; - if (test.phase >= test.phases.HAS_RESULT) { - return; - } - test.set_status(test.FAIL, e.message, e.stack); - test.phase = test.phases.HAS_RESULT; - test.done(); - done(); - } else if (!tests.allow_uncaught_exception) { - tests.status.status = tests.status.ERROR; - tests.status.message = e.message; - tests.status.stack = e.stack; - } - }); - - test_environment.on_tests_ready(); - -})(); -// vim: set expandtab shiftwidth=4 tabstop=4:
diff --git a/third_party/WebKit/LayoutTests/http/tests/resources/testharnessreport.js b/third_party/WebKit/LayoutTests/http/tests/resources/testharnessreport.js deleted file mode 100644 index 56dcac54..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/resources/testharnessreport.js +++ /dev/null
@@ -1,142 +0,0 @@ -/* - * THIS FILE INTENTIONALLY LEFT BLANK - * - * More specifically, this file is intended for vendors to implement - * code needed to integrate testharness.js tests with their own test systems. - * - * Typically such integration will attach callbacks when each test is - * has run, using add_result_callback(callback(test)), or when the whole test file has - * completed, using add_completion_callback(callback(tests, harness_status)). - * - * For more documentation about the callback functions and the - * parameters they are called with see testharness.js - */ - -(function() { - - // Setup for WebKit JavaScript tests - if (self.testRunner) { - testRunner.dumpAsText(); - testRunner.waitUntilDone(); - testRunner.setCanOpenWindows(); - testRunner.setCloseRemainingWindowsWhenComplete(true); - } - - // Disable the default output of testharness.js. The default output formats - // test results into an HTML table. When that table is dumped as text, no - // spacing between cells is preserved, and it is therefore not readable. By - // setting output to false, the HTML table will not be created. - setup({"output":false}); - - // Function used to convert the test status code into the corresponding - // string - function convertResult(resultStatus) { - switch (resultStatus) { - case 0: - return "PASS"; - case 1: - return "FAIL"; - case 2: - return "TIMEOUT"; - default: - return "NOTRUN"; - } - } - - // Sanitizes the given text for display in test results. - function sanitize(text) { - if (!text) { - return ""; - } - // Escape null characters, otherwise diff will think the file is binary. - text = text.replace(/\0/g, "\\0"); - // Escape carriage returns as they break rietveld's difftools. - return text.replace(/\r/g, "\\r"); - } - - // If the test has a meta tag named flags and the content contains "dom", - // then it's a CSSWG test. - function isCSSWGTest() { - var flags = document.querySelector('meta[name=flags]'), - content = flags ? flags.getAttribute('content') : null; - return content && content.match(/\bdom\b/); - } - - function isJSTest() { - return !!document.querySelector('script[src*="/resources/testharness"]'); - } - - var didDispatchLoadEvent = false; - var handleLoad = function() { - didDispatchLoadEvent = true; - window.removeEventListener('load', handleLoad); - }; - window.addEventListener('load', handleLoad, false); - - // Using a callback function, test results will be added to the page in a - // manner that allows dumpAsText to produce readable test results. - add_completion_callback(function (tests, harness_status) { - - // Create element to hold results. - var results = document.createElement("pre"); - - // Declare result string. - var resultStr = "This is a testharness.js-based test.\n"; - - // Check harness_status. If it is not 0, tests did not execute - // correctly, output the error code and message. - if (harness_status.status != 0) { - resultStr += "Harness Error. harness_status.status = " + - harness_status.status + - " , harness_status.message = " + - harness_status.message + - "\n"; - } else { - // Iterate through tests array and build string that contains - // results for all tests. - for (var i = 0; i < tests.length; ++i) { - resultStr += convertResult(tests[i].status) + " " + - sanitize(tests[i].name) + " " + - sanitize(tests[i].message) + "\n"; - } - } - resultStr += "Harness: the test ran to completion.\n"; - - // Set results element's textContent to the results string. - results.textContent = resultStr; - - function done() { - if (self.testRunner) { - var logDiv = document.getElementById('log'); - if ((isCSSWGTest() || isJSTest()) && logDiv) { - // Assume it's a CSSWG style test, and anything other than - // the log div isn't material to the testrunner output, so - // should be hidden from the text dump. - document.body.textContent = ''; - } - } - - // Add results element to document. - if (!document.body) { - if (!document.documentElement) - document.appendChild(document.createElement('html')); - document.documentElement.appendChild(document.createElement("body")); - } - document.body.appendChild(results); - - if (self.testRunner) - testRunner.notifyDone(); - } - - if (didDispatchLoadEvent || document.readyState != 'loading') { - // This function might not be the last 'completion callback', and - // another completion callback might generate more results. So, we - // don't dump the results immediately. - setTimeout(done, 0); - } else { - // Parsing the test HTML isn't finished yet. - window.addEventListener('load', done); - } - }); - -})();
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/foreign-fetch-basics.html b/third_party/WebKit/LayoutTests/http/tests/serviceworker/foreign-fetch-basics.html index 4ad7097..a782978 100644 --- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/foreign-fetch-basics.html +++ b/third_party/WebKit/LayoutTests/http/tests/serviceworker/foreign-fetch-basics.html
@@ -1,27 +1,56 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> +<script src="../resources/get-host-info.js"></script> <script src="resources/test-helpers.js"></script> <body> <script> +var host_info = get_host_info(); + function worker_for_origins(origins) { - var worker = 'resources/foreign-fetch-worker.js?'; - return worker + encodeURIComponent(JSON.stringify(origins)); + var worker = 'foreign-fetch-worker.js?'; + var params = {origins: origins, relscopes: ['/intercept']}; + return worker + encodeURIComponent(JSON.stringify(params)); +} + +function worker_for_scopes(relative_scopes) { + var worker = 'foreign-fetch-worker.js?'; + var params = {relscopes: relative_scopes}; + return worker + encodeURIComponent(JSON.stringify(params)); +} + +function install_cross_origin_worker(t, worker, scope) { + return with_iframe(host_info.HTTPS_REMOTE_ORIGIN + + '/serviceworker/resources/install-worker-helper.html') + .then(frame => new Promise((resolve, reject) => { + var channel = new MessageChannel(); + frame.contentWindow.postMessage({worker: worker, + options: {scope: scope}, + port: channel.port1}, + '*', [channel.port1]); + channel.port2.onmessage = reply => { + if (reply.data == 'success') resolve(); + else reject(reply.data); + }; + })); +} + +function intercepted_url(scope) { + return host_info.HTTPS_REMOTE_ORIGIN + '/serviceworker/resources/' + + scope + '/intercept/foo?basic'; +} + +function non_intercepted_url(scope) { + return host_info.HTTPS_REMOTE_ORIGIN + '/serviceworker/resources/' + + scope + '/foo?basic'; } promise_test(t => { - var scope = 'resources/foreign-fetch/scope'; - return service_worker_unregister_and_register( - t, worker_for_origins(['*']), scope) - .then(r => { - add_completion_callback(() => r.unregister()); - return wait_for_state(t, r.installing, 'activated'); - }) - .then(() => fetch(scope + '/foo')) - .then(response => { - assert_equals(response.status, 404); - return fetch(scope + '/intercept/foo'); - }) + var scope = 'foreign-fetch/scope/wildcard'; + return install_cross_origin_worker(t, worker_for_origins(['*']), scope) + .then(() => promise_rejects(t, new TypeError(), + fetch(non_intercepted_url(scope)))) + .then(() => fetch(intercepted_url(scope))) .then(response => response.text()) .then(response_text => { assert_equals(response_text, 'Foreign Fetch'); @@ -29,14 +58,10 @@ }, 'Service Worker intercepts fetches in scope with wildcard origin.'); promise_test(t => { - var scope = 'resources/foreign-fetch/scope/match-origin'; - return service_worker_unregister_and_register( + var scope = 'foreign-fetch/scope/match-origin'; + return install_cross_origin_worker( t, worker_for_origins([location.origin]), scope) - .then(r => { - add_completion_callback(() => r.unregister()); - return wait_for_state(t, r.installing, 'activated'); - }) - .then(() => fetch(scope + '/intercept/foo')) + .then(() => fetch(intercepted_url(scope))) .then(response => response.text()) .then(response_text => { assert_equals(response_text, 'Foreign Fetch'); @@ -44,33 +69,53 @@ }, 'Service Worker intercepts fetches in scope with explicit origin.'); promise_test(t => { - var scope = 'resources/foreign-fetch/scope/nomatch-origin'; - return service_worker_unregister_and_register( + var scope = 'foreign-fetch/scope/nomatch-origin'; + return install_cross_origin_worker( t, worker_for_origins(['https://example.com']), scope) - .then(r => { - add_completion_callback(() => r.unregister()); - return wait_for_state(t, r.installing, 'activated'); - }) - .then(() => fetch(scope + '/intercept/foo')) - .then(response => { - assert_equals(response.status, 404); - }); + .then(() => promise_rejects(t, new TypeError(), + fetch(non_intercepted_url(scope)))); }, 'Service Worker doesn\'t intercept fetches with non matching origin.'); promise_test(t => { - var scope = 'resources/foreign-fetch/scope/origin-list'; - return service_worker_unregister_and_register( + var scope = 'foreign-fetch/scope/origin-list'; + return install_cross_origin_worker( t, worker_for_origins([location.origin, 'https://example.com']), scope) - .then(r => { - add_completion_callback(() => r.unregister()); - return wait_for_state(t, r.installing, 'activated'); - }) - .then(() => fetch(scope + '/intercept/foo')) + .then(() => fetch(intercepted_url(scope))) .then(response => response.text()) .then(response_text => { assert_equals(response_text, 'Foreign Fetch'); }); }, 'Service Worker intercepts fetches in scope with explicit origin list.'); +promise_test(t => { + var scope = 'resources/foreign-fetch/same-origin'; + return service_worker_unregister_and_register( + t, 'resources/' + worker_for_origins(['*']), scope) + .then(r => { + add_completion_callback(() => r.unregister()); + return wait_for_state(t, r.installing, 'activated'); + }) + .then(() => fetch(scope + '/intercept/foo?basic')) + .then(response => { + assert_equals(response.status, 404); + }); + }, 'Service Worker does not intercept same origin fetches.'); + +promise_test(t => { + var scope = 'reply-to-message.html?onmessage'; + var remote_url = + host_info.HTTPS_REMOTE_ORIGIN + '/serviceworker/resources/' + scope; + return install_cross_origin_worker(t, worker_for_scopes(['']), scope) + .then(() => with_iframe(remote_url)) + .then(frame => new Promise(resolve => { + var channel = new MessageChannel(); + frame.contentWindow.postMessage('ping', '*', [channel.port1]); + channel.port2.onmessage = reply => resolve(reply.data); + })) + .then(reply => { + assert_equals(reply, 'ping'); + }); + }, 'Service Worker does not intercept navigations.'); + </script> </body>
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/foreign-fetch-worker.js b/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/foreign-fetch-worker.js index 2be0db2..765972c7 100644 --- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/foreign-fetch-worker.js +++ b/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/foreign-fetch-worker.js
@@ -1,9 +1,47 @@ self.addEventListener('install', function(event) { - var origins = JSON.parse(decodeURIComponent(location.search.substring(1))); - event.registerForeignFetch({scopes: [registration.scope + '/intercept'], - origins: origins}); + var params = JSON.parse(decodeURIComponent(location.search.substring(1))); + if (!('scopes' in params)) { + if ('relscopes' in params) { + params.scopes = params.relscopes.map(s => registration.scope + s); + } else { + params.scopes = [registration.scope]; + } + } + if (!('origins' in params)) + params.origins = ['*']; + event.registerForeignFetch(params); }); +function handle_basic(event) { + event.respondWith({response: + new Response('Foreign Fetch', + {headers: {'Access-Control-Allow-Origin': '*'}})}); +} + +function handle_onmessage(event) { + event.respondWith({response: + new Response('<script>window.onmessage = e => e.ports[0].postMessage("failed");</script>', + {headers: {'Content-Type': 'text/html', 'Access-Control-Allow-Origin': '*'}})}); +} + self.addEventListener('foreignfetch', function(event) { - event.respondWith({response: new Response('Foreign Fetch')}); + var url = event.request.url; + var handlers = [ + { pattern: '?basic', fn: handle_basic }, + { pattern: '?onmessage', fn: handle_onmessage } + ]; + + var handler = null; + for (var i = 0; i < handlers.length; ++i) { + if (url.indexOf(handlers[i].pattern) != -1) { + handler = handlers[i]; + break; + } + } + + if (handler) { + handler.fn(event); + } else { + event.respondWith(new Response('unexpected request')); + } });
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/install-worker-helper.html b/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/install-worker-helper.html new file mode 100644 index 0000000..1de9baf --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/install-worker-helper.html
@@ -0,0 +1,22 @@ +<!DOCTYPE html> +<script src="test-helpers.js"></script> +<script> +window.addEventListener('message', event => { + var port = event.ports[0]; + navigator.serviceWorker.getRegistration(event.data.options.scope) + .then(r => { + if (r) return r.unregister(); + }) + .then(() => navigator.serviceWorker.register(event.data.worker, + event.data.options)) + .then(r => new Promise(resolve => { + window.addEventListener('unload', () => r.unregister()); + var worker = r.installing; + worker.addEventListener('statechange', () => { + if (worker.state === 'activated') resolve(); + }); + })) + .then(() => port.postMessage('success')) + .catch((e) => port.postMessage('failure:' + e)); + }); +</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/reply-to-message.html b/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/reply-to-message.html new file mode 100644 index 0000000..8a70e2a --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/reply-to-message.html
@@ -0,0 +1,7 @@ +<!DOCTYPE html> +<script> +window.addEventListener('message', event => { + var port = event.ports[0]; + port.postMessage(event.data); + }); +</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/w3c/resources/WebIDLParser.js b/third_party/WebKit/LayoutTests/http/tests/w3c/resources/WebIDLParser.js deleted file mode 100644 index 71030cf..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/w3c/resources/WebIDLParser.js +++ /dev/null
@@ -1,1012 +0,0 @@ - - -(function () { - var tokenise = function (str) { - var tokens = [] - , re = { - "float": /^-?(([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([Ee][-+]?[0-9]+)?|[0-9]+[Ee][-+]?[0-9]+)/ - , "integer": /^-?(0([Xx][0-9A-Fa-f]+|[0-7]*)|[1-9][0-9]*)/ - , "identifier": /^[A-Z_a-z][0-9A-Z_a-z]*/ - , "string": /^"[^"]*"/ - , "whitespace": /^(?:[\t\n\r ]+|[\t\n\r ]*((\/\/.*|\/\*(.|\n|\r)*?\*\/)[\t\n\r ]*))+/ - , "other": /^[^\t\n\r 0-9A-Z_a-z]/ - } - , types = [] - ; - for (var k in re) types.push(k); - while (str.length > 0) { - var matched = false; - for (var i = 0, n = types.length; i < n; i++) { - var type = types[i]; - str = str.replace(re[type], function (tok) { - tokens.push({ type: type, value: tok }); - matched = true; - return ""; - }); - if (matched) break; - } - if (matched) continue; - throw new Error("Token stream not progressing"); - } - return tokens; - }; - - var parse = function (tokens, opt) { - var line = 1; - tokens = tokens.slice(); - - var FLOAT = "float" - , INT = "integer" - , ID = "identifier" - , STR = "string" - , OTHER = "other" - ; - - var WebIDLParseError = function (str, line, input, tokens) { - this.message = str; - this.line = line; - this.input = input; - this.tokens = tokens; - }; - WebIDLParseError.prototype.toString = function () { - return this.message + ", line " + this.line + " (tokens: '" + this.input + "')\n" + - JSON.stringify(this.tokens, null, 4); - }; - - var error = function (str) { - var tok = "", numTokens = 0, maxTokens = 5; - while (numTokens < maxTokens && tokens.length > numTokens) { - tok += tokens[numTokens].value; - numTokens++; - } - throw new WebIDLParseError(str, line, tok, tokens.slice(0, 5)); - }; - - var last_token = null; - - var consume = function (type, value) { - if (!tokens.length || tokens[0].type !== type) return; - if (typeof value === "undefined" || tokens[0].value === value) { - last_token = tokens.shift(); - if (type === ID) last_token.value = last_token.value.replace(/^_/, ""); - return last_token; - } - }; - - var ws = function () { - if (!tokens.length) return; - if (tokens[0].type === "whitespace") { - var t = tokens.shift(); - t.value.replace(/\n/g, function (m) { line++; return m; }); - return t; - } - }; - - var all_ws = function (store, pea) { // pea == post extended attribute, tpea = same for types - var t = { type: "whitespace", value: "" }; - while (true) { - var w = ws(); - if (!w) break; - t.value += w.value; - } - if (t.value.length > 0) { - if (store) { - var w = t.value - , re = { - "ws": /^([\t\n\r ]+)/ - , "line-comment": /^\/\/(.*)\n?/m - , "multiline-comment": /^\/\*((?:.|\n|\r)*?)\*\// - } - , wsTypes = [] - ; - for (var k in re) wsTypes.push(k); - while (w.length) { - var matched = false; - for (var i = 0, n = wsTypes.length; i < n; i++) { - var type = wsTypes[i]; - w = w.replace(re[type], function (tok, m1) { - store.push({ type: type + (pea ? ("-" + pea) : ""), value: m1 }); - matched = true; - return ""; - }); - if (matched) break; - } - if (matched) continue; - throw new Error("Surprising white space construct."); // this shouldn't happen - } - } - return t; - } - }; - - var integer_type = function () { - var ret = ""; - all_ws(); - if (consume(ID, "unsigned")) ret = "unsigned "; - all_ws(); - if (consume(ID, "short")) return ret + "short"; - if (consume(ID, "long")) { - ret += "long"; - all_ws(); - if (consume(ID, "long")) return ret + " long"; - return ret; - } - if (ret) error("Failed to parse integer type"); - }; - - var float_type = function () { - var ret = ""; - all_ws(); - if (consume(ID, "unrestricted")) ret = "unrestricted "; - all_ws(); - if (consume(ID, "float")) return ret + "float"; - if (consume(ID, "double")) return ret + "double"; - if (ret) error("Failed to parse float type"); - }; - - var primitive_type = function () { - var num_type = integer_type() || float_type(); - if (num_type) return num_type; - all_ws(); - if (consume(ID, "boolean")) return "boolean"; - if (consume(ID, "byte")) return "byte"; - if (consume(ID, "octet")) return "octet"; - }; - - var const_value = function () { - if (consume(ID, "true")) return { type: "boolean", value: true }; - if (consume(ID, "false")) return { type: "boolean", value: false }; - if (consume(ID, "null")) return { type: "null" }; - if (consume(ID, "Infinity")) return { type: "Infinity", negative: false }; - if (consume(ID, "NaN")) return { type: "NaN" }; - var ret = consume(FLOAT) || consume(INT); - if (ret) return { type: "number", value: 1 * ret.value }; - var tok = consume(OTHER, "-"); - if (tok) { - if (consume(ID, "Infinity")) return { type: "Infinity", negative: true }; - else tokens.unshift(tok); - } - }; - - var type_suffix = function (obj) { - while (true) { - all_ws(); - if (consume(OTHER, "?")) { - if (obj.nullable) error("Can't nullable more than once"); - obj.nullable = true; - } - else if (consume(OTHER, "[")) { - all_ws(); - consume(OTHER, "]") || error("Unterminated array type"); - if (!obj.array) { - obj.array = 1; - obj.nullableArray = [obj.nullable]; - } - else { - obj.array++; - obj.nullableArray.push(obj.nullable); - } - obj.nullable = false; - } - else return; - } - }; - - var single_type = function () { - var prim = primitive_type() - , ret = { sequence: false, generic: null, nullable: false, array: false, union: false } - , name - , value - ; - if (prim) { - ret.idlType = prim; - } - else if (name = consume(ID)) { - value = name.value; - all_ws(); - // Generic types - if (consume(OTHER, "<")) { - // backwards compat - if (value === "sequence") { - ret.sequence = true; - } - ret.generic = value; - ret.idlType = type() || error("Error parsing generic type " + value); - all_ws(); - if (!consume(OTHER, ">")) error("Unterminated generic type " + value); - type_suffix(ret); - return ret; - } - else { - ret.idlType = value; - } - } - else { - return; - } - type_suffix(ret); - if (ret.nullable && !ret.array && ret.idlType === "any") error("Type any cannot be made nullable"); - return ret; - }; - - var union_type = function () { - all_ws(); - if (!consume(OTHER, "(")) return; - var ret = { sequence: false, generic: null, nullable: false, array: false, union: true, idlType: [] }; - var fst = type() || error("Union type with no content"); - ret.idlType.push(fst); - while (true) { - all_ws(); - if (!consume(ID, "or")) break; - var typ = type() || error("No type after 'or' in union type"); - ret.idlType.push(typ); - } - if (!consume(OTHER, ")")) error("Unterminated union type"); - type_suffix(ret); - return ret; - }; - - var type = function () { - return single_type() || union_type(); - }; - - var argument = function (store) { - var ret = { optional: false, variadic: false }; - ret.extAttrs = extended_attrs(store); - all_ws(store, "pea"); - var opt_token = consume(ID, "optional"); - if (opt_token) { - ret.optional = true; - all_ws(); - } - ret.idlType = type(); - if (!ret.idlType) { - if (opt_token) tokens.unshift(opt_token); - return; - } - var type_token = last_token; - if (!ret.optional) { - all_ws(); - if (tokens.length >= 3 && - tokens[0].type === "other" && tokens[0].value === "." && - tokens[1].type === "other" && tokens[1].value === "." && - tokens[2].type === "other" && tokens[2].value === "." - ) { - tokens.shift(); - tokens.shift(); - tokens.shift(); - ret.variadic = true; - } - } - all_ws(); - var name = consume(ID); - if (!name) { - if (opt_token) tokens.unshift(opt_token); - tokens.unshift(type_token); - return; - } - ret.name = name.value; - if (ret.optional) { - all_ws(); - ret["default"] = default_(); - } - return ret; - }; - - var argument_list = function (store) { - var ret = [] - , arg = argument(store ? ret : null) - ; - if (!arg) return; - ret.push(arg); - while (true) { - all_ws(store ? ret : null); - if (!consume(OTHER, ",")) return ret; - var nxt = argument(store ? ret : null) || error("Trailing comma in arguments list"); - ret.push(nxt); - } - }; - - var type_pair = function () { - all_ws(); - var k = type(); - if (!k) return; - all_ws() - if (!consume(OTHER, ",")) return; - all_ws(); - var v = type(); - if (!v) return; - return [k, v]; - }; - - var simple_extended_attr = function (store) { - all_ws(); - var name = consume(ID); - if (!name) return; - var ret = { - name: name.value - , "arguments": null - }; - all_ws(); - var eq = consume(OTHER, "="); - if (eq) { - var rhs; - all_ws(); - if (rhs = consume(ID)) { - ret.rhs = rhs - } - else if (consume(OTHER, "(")) { - // [Exposed=(Window,Worker)] - rhs = []; - var id = consume(ID); - if (id) { - rhs = [id.value]; - } - identifiers(rhs); - consume(OTHER, ")") || error("Unexpected token in extended attribute argument list or type pair"); - ret.rhs = { - type: "identifier-list", - value: rhs - }; - } - if (!ret.rhs) return error("No right hand side to extended attribute assignment"); - } - all_ws(); - if (consume(OTHER, "(")) { - var args, pair; - // [Constructor(DOMString str)] - if (args = argument_list(store)) { - ret["arguments"] = args; - } - // [MapClass(DOMString, DOMString)] - else if (pair = type_pair()) { - ret.typePair = pair; - } - // [Constructor()] - else { - ret["arguments"] = []; - } - all_ws(); - consume(OTHER, ")") || error("Unexpected token in extended attribute argument list or type pair"); - } - return ret; - }; - - // Note: we parse something simpler than the official syntax. It's all that ever - // seems to be used - var extended_attrs = function (store) { - var eas = []; - all_ws(store); - if (!consume(OTHER, "[")) return eas; - eas[0] = simple_extended_attr(store) || error("Extended attribute with not content"); - all_ws(); - while (consume(OTHER, ",")) { - eas.push(simple_extended_attr(store) || error("Trailing comma in extended attribute")); - all_ws(); - } - consume(OTHER, "]") || error("No end of extended attribute"); - return eas; - }; - - var default_ = function () { - all_ws(); - if (consume(OTHER, "=")) { - all_ws(); - var def = const_value(); - if (def) { - return def; - } - else if (consume(OTHER, "[")) { - if (!consume(OTHER, "]")) error("Default sequence value must be empty"); - return { type: "sequence", value: [] }; - } - else { - var str = consume(STR) || error("No value for default"); - str.value = str.value.replace(/^"/, "").replace(/"$/, ""); - return str; - } - } - }; - - var const_ = function (store) { - all_ws(store, "pea"); - if (!consume(ID, "const")) return; - var ret = { type: "const", nullable: false }; - all_ws(); - var typ = primitive_type(); - if (!typ) { - typ = consume(ID) || error("No type for const"); - typ = typ.value; - } - ret.idlType = typ; - all_ws(); - if (consume(OTHER, "?")) { - ret.nullable = true; - all_ws(); - } - var name = consume(ID) || error("No name for const"); - ret.name = name.value; - all_ws(); - consume(OTHER, "=") || error("No value assignment for const"); - all_ws(); - var cnt = const_value(); - if (cnt) ret.value = cnt; - else error("No value for const"); - all_ws(); - consume(OTHER, ";") || error("Unterminated const"); - return ret; - }; - - var inheritance = function () { - all_ws(); - if (consume(OTHER, ":")) { - all_ws(); - var inh = consume(ID) || error ("No type in inheritance"); - return inh.value; - } - }; - - var operation_rest = function (ret, store) { - all_ws(); - if (!ret) ret = {}; - var name = consume(ID); - ret.name = name ? name.value : null; - all_ws(); - consume(OTHER, "(") || error("Invalid operation"); - ret["arguments"] = argument_list(store) || []; - all_ws(); - consume(OTHER, ")") || error("Unterminated operation"); - all_ws(); - consume(OTHER, ";") || error("Unterminated operation"); - return ret; - }; - - var callback = function (store) { - all_ws(store, "pea"); - var ret; - if (!consume(ID, "callback")) return; - all_ws(); - var tok = consume(ID, "interface"); - if (tok) { - tokens.unshift(tok); - ret = interface_(); - ret.type = "callback interface"; - return ret; - } - var name = consume(ID) || error("No name for callback"); - ret = { type: "callback", name: name.value }; - all_ws(); - consume(OTHER, "=") || error("No assignment in callback"); - all_ws(); - ret.idlType = return_type(); - all_ws(); - consume(OTHER, "(") || error("No arguments in callback"); - ret["arguments"] = argument_list(store) || []; - all_ws(); - consume(OTHER, ")") || error("Unterminated callback"); - all_ws(); - consume(OTHER, ";") || error("Unterminated callback"); - return ret; - }; - - var attribute = function (store) { - all_ws(store, "pea"); - var grabbed = [] - , ret = { - type: "attribute" - , "static": false - , stringifier: false - , inherit: false - , readonly: false - }; - if (consume(ID, "static")) { - ret["static"] = true; - grabbed.push(last_token); - } - else if (consume(ID, "stringifier")) { - ret.stringifier = true; - grabbed.push(last_token); - } - var w = all_ws(); - if (w) grabbed.push(w); - if (consume(ID, "inherit")) { - if (ret["static"] || ret.stringifier) error("Cannot have a static or stringifier inherit"); - ret.inherit = true; - grabbed.push(last_token); - var w = all_ws(); - if (w) grabbed.push(w); - } - if (consume(ID, "readonly")) { - ret.readonly = true; - grabbed.push(last_token); - var w = all_ws(); - if (w) grabbed.push(w); - } - if (!consume(ID, "attribute")) { - tokens = grabbed.concat(tokens); - return; - } - all_ws(); - ret.idlType = type() || error("No type in attribute"); - if (ret.idlType.sequence) error("Attributes cannot accept sequence types"); - all_ws(); - var name = consume(ID) || error("No name in attribute"); - ret.name = name.value; - all_ws(); - consume(OTHER, ";") || error("Unterminated attribute"); - return ret; - }; - - var return_type = function () { - var typ = type(); - if (!typ) { - if (consume(ID, "void")) { - return "void"; - } - else error("No return type"); - } - return typ; - }; - - var operation = function (store) { - all_ws(store, "pea"); - var ret = { - type: "operation" - , getter: false - , setter: false - , creator: false - , deleter: false - , legacycaller: false - , "static": false - , stringifier: false - }; - while (true) { - all_ws(); - if (consume(ID, "getter")) ret.getter = true; - else if (consume(ID, "setter")) ret.setter = true; - else if (consume(ID, "creator")) ret.creator = true; - else if (consume(ID, "deleter")) ret.deleter = true; - else if (consume(ID, "legacycaller")) ret.legacycaller = true; - else break; - } - if (ret.getter || ret.setter || ret.creator || ret.deleter || ret.legacycaller) { - all_ws(); - ret.idlType = return_type(); - operation_rest(ret, store); - return ret; - } - if (consume(ID, "static")) { - ret["static"] = true; - ret.idlType = return_type(); - operation_rest(ret, store); - return ret; - } - else if (consume(ID, "stringifier")) { - ret.stringifier = true;- - all_ws(); - if (consume(OTHER, ";")) return ret; - ret.idlType = return_type(); - operation_rest(ret, store); - return ret; - } - ret.idlType = return_type(); - all_ws(); - if (consume(ID, "iterator")) { - all_ws(); - ret.type = "iterator"; - if (consume(ID, "object")) { - ret.iteratorObject = "object"; - } - else if (consume(OTHER, "=")) { - all_ws(); - var name = consume(ID) || error("No right hand side in iterator"); - ret.iteratorObject = name.value; - } - all_ws(); - consume(OTHER, ";") || error("Unterminated iterator"); - return ret; - } - else { - operation_rest(ret, store); - return ret; - } - }; - - var identifiers = function (arr) { - while (true) { - all_ws(); - if (consume(OTHER, ",")) { - all_ws(); - var name = consume(ID) || error("Trailing comma in identifiers list"); - arr.push(name.value); - } - else break; - } - }; - - var serialiser = function (store) { - all_ws(store, "pea"); - if (!consume(ID, "serializer")) return; - var ret = { type: "serializer" }; - all_ws(); - if (consume(OTHER, "=")) { - all_ws(); - if (consume(OTHER, "{")) { - ret.patternMap = true; - all_ws(); - var id = consume(ID); - if (id && id.value === "getter") { - ret.names = ["getter"]; - } - else if (id && id.value === "inherit") { - ret.names = ["inherit"]; - identifiers(ret.names); - } - else if (id) { - ret.names = [id.value]; - identifiers(ret.names); - } - else { - ret.names = []; - } - all_ws(); - consume(OTHER, "}") || error("Unterminated serializer pattern map"); - } - else if (consume(OTHER, "[")) { - ret.patternList = true; - all_ws(); - var id = consume(ID); - if (id && id.value === "getter") { - ret.names = ["getter"]; - } - else if (id) { - ret.names = [id.value]; - identifiers(ret.names); - } - else { - ret.names = []; - } - all_ws(); - consume(OTHER, "]") || error("Unterminated serializer pattern list"); - } - else { - var name = consume(ID) || error("Invalid serializer"); - ret.name = name.value; - } - all_ws(); - consume(OTHER, ";") || error("Unterminated serializer"); - return ret; - } - else if (consume(OTHER, ";")) { - // noop, just parsing - } - else { - ret.idlType = return_type(); - all_ws(); - ret.operation = operation_rest(null, store); - } - return ret; - }; - - var iterable_type = function() { - if (consume(ID, "iterable")) return "iterable"; - else if (consume(ID, "legacyiterable")) return "legacyiterable"; - else if (consume(ID, "maplike")) return "maplike"; - else if (consume(ID, "setlike")) return "setlike"; - else return; - } - - var readonly_iterable_type = function() { - if (consume(ID, "maplike")) return "maplike"; - else if (consume(ID, "setlike")) return "setlike"; - else return; - } - - var iterable = function (store) { - all_ws(store, "pea"); - var grabbed = [], - ret = {type: null, idlType: null, readonly: false}; - if (consume(ID, "readonly")) { - ret.readonly = true; - grabbed.push(last_token); - var w = all_ws(); - if (w) grabbed.push(w); - } - var consumeItType = ret.readonly ? readonly_iterable_type : iterable_type; - - var ittype = consumeItType(); - if (!ittype) { - tokens = grabbed.concat(tokens); - return; - } - - var secondTypeRequired = ittype === "maplike"; - var secondTypeAllowed = secondTypeRequired || ittype === "iterable"; - ret.type = ittype; - if (ret.type !== 'maplike' && ret.type !== 'setlike') - delete ret.readonly; - all_ws(); - if (consume(OTHER, "<")) { - ret.idlType = type() || error("Error parsing " + ittype + " declaration"); - all_ws(); - if (secondTypeAllowed) { - var type2 = null; - if (consume(OTHER, ",")) { - all_ws(); - type2 = type(); - all_ws(); - } - if (type2) - ret.idlType = [ret.idlType, type2]; - else if (secondTypeRequired) - error("Missing second type argument in " + ittype + " declaration"); - } - if (!consume(OTHER, ">")) error("Unterminated " + ittype + " declaration"); - all_ws(); - if (!consume(OTHER, ";")) error("Missing semicolon after " + ittype + " declaration"); - } - else - error("Error parsing " + ittype + " declaration"); - - return ret; - } - - var interface_ = function (isPartial, store) { - all_ws(isPartial ? null : store, "pea"); - if (!consume(ID, "interface")) return; - all_ws(); - var name = consume(ID) || error("No name for interface"); - var mems = [] - , ret = { - type: "interface" - , name: name.value - , partial: false - , members: mems - }; - if (!isPartial) ret.inheritance = inheritance() || null; - all_ws(); - consume(OTHER, "{") || error("Bodyless interface"); - while (true) { - all_ws(store ? mems : null); - if (consume(OTHER, "}")) { - all_ws(); - consume(OTHER, ";") || error("Missing semicolon after interface"); - return ret; - } - var ea = extended_attrs(store ? mems : null); - all_ws(); - var cnt = const_(store ? mems : null); - if (cnt) { - cnt.extAttrs = ea; - ret.members.push(cnt); - continue; - } - var mem = (opt.allowNestedTypedefs && typedef(store ? mems : null)) || - iterable(store ? mems : null) || - serialiser(store ? mems : null) || - attribute(store ? mems : null) || - operation(store ? mems : null) || - error("Unknown member"); - mem.extAttrs = ea; - ret.members.push(mem); - } - }; - - var partial = function (store) { - all_ws(store, "pea"); - if (!consume(ID, "partial")) return; - var thing = dictionary(true, store) || - interface_(true, store) || - error("Partial doesn't apply to anything"); - thing.partial = true; - return thing; - }; - - var dictionary = function (isPartial, store) { - all_ws(isPartial ? null : store, "pea"); - if (!consume(ID, "dictionary")) return; - all_ws(); - var name = consume(ID) || error("No name for dictionary"); - var mems = [] - , ret = { - type: "dictionary" - , name: name.value - , partial: false - , members: mems - }; - if (!isPartial) ret.inheritance = inheritance() || null; - all_ws(); - consume(OTHER, "{") || error("Bodyless dictionary"); - while (true) { - all_ws(store ? mems : null); - if (consume(OTHER, "}")) { - all_ws(); - consume(OTHER, ";") || error("Missing semicolon after dictionary"); - return ret; - } - var ea = extended_attrs(store ? mems : null); - all_ws(store ? mems : null, "pea"); - var required = consume(ID, "required"); - var typ = type() || error("No type for dictionary member"); - all_ws(); - var name = consume(ID) || error("No name for dictionary member"); - var dflt = default_(); - if (required && dflt) error("Required member must not have a default"); - ret.members.push({ - type: "field" - , name: name.value - , required: !!required - , idlType: typ - , extAttrs: ea - , "default": dflt - }); - all_ws(); - consume(OTHER, ";") || error("Unterminated dictionary member"); - } - }; - - var exception = function (store) { - all_ws(store, "pea"); - if (!consume(ID, "exception")) return; - all_ws(); - var name = consume(ID) || error("No name for exception"); - var mems = [] - , ret = { - type: "exception" - , name: name.value - , members: mems - }; - ret.inheritance = inheritance() || null; - all_ws(); - consume(OTHER, "{") || error("Bodyless exception"); - while (true) { - all_ws(store ? mems : null); - if (consume(OTHER, "}")) { - all_ws(); - consume(OTHER, ";") || error("Missing semicolon after exception"); - return ret; - } - var ea = extended_attrs(store ? mems : null); - all_ws(store ? mems : null, "pea"); - var cnt = const_(); - if (cnt) { - cnt.extAttrs = ea; - ret.members.push(cnt); - } - else { - var typ = type(); - all_ws(); - var name = consume(ID); - all_ws(); - if (!typ || !name || !consume(OTHER, ";")) error("Unknown member in exception body"); - ret.members.push({ - type: "field" - , name: name.value - , idlType: typ - , extAttrs: ea - }); - } - } - }; - - var enum_ = function (store) { - all_ws(store, "pea"); - if (!consume(ID, "enum")) return; - all_ws(); - var name = consume(ID) || error("No name for enum"); - var vals = [] - , ret = { - type: "enum" - , name: name.value - , values: vals - }; - all_ws(); - consume(OTHER, "{") || error("No curly for enum"); - var saw_comma = false; - while (true) { - all_ws(store ? vals : null); - if (consume(OTHER, "}")) { - all_ws(); - consume(OTHER, ";") || error("No semicolon after enum"); - return ret; - } - var val = consume(STR) || error("Unexpected value in enum"); - ret.values.push(val.value.replace(/"/g, "")); - all_ws(store ? vals : null); - if (consume(OTHER, ",")) { - if (store) vals.push({ type: "," }); - all_ws(store ? vals : null); - saw_comma = true; - } - else { - saw_comma = false; - } - } - }; - - var typedef = function (store) { - all_ws(store, "pea"); - if (!consume(ID, "typedef")) return; - var ret = { - type: "typedef" - }; - all_ws(); - ret.typeExtAttrs = extended_attrs(); - all_ws(store, "tpea"); - ret.idlType = type() || error("No type in typedef"); - all_ws(); - var name = consume(ID) || error("No name in typedef"); - ret.name = name.value; - all_ws(); - consume(OTHER, ";") || error("Unterminated typedef"); - return ret; - }; - - var implements_ = function (store) { - all_ws(store, "pea"); - var target = consume(ID); - if (!target) return; - var w = all_ws(); - if (consume(ID, "implements")) { - var ret = { - type: "implements" - , target: target.value - }; - all_ws(); - var imp = consume(ID) || error("Incomplete implements statement"); - ret["implements"] = imp.value; - all_ws(); - consume(OTHER, ";") || error("No terminating ; for implements statement"); - return ret; - } - else { - // rollback - tokens.unshift(w); - tokens.unshift(target); - } - }; - - var definition = function (store) { - return callback(store) || - interface_(false, store) || - partial(store) || - dictionary(false, store) || - exception(store) || - enum_(store) || - typedef(store) || - implements_(store) - ; - }; - - var definitions = function (store) { - if (!tokens.length) return []; - var defs = []; - while (true) { - var ea = extended_attrs(store ? defs : null) - , def = definition(store ? defs : null); - if (!def) { - if (ea.length) error("Stray extended attributes"); - break; - } - def.extAttrs = ea; - defs.push(def); - } - return defs; - }; - var res = definitions(opt.ws); - if (tokens.length) error("Unrecognised tokens"); - return res; - }; - - var inNode = typeof module !== "undefined" && module.exports - , obj = { - parse: function (str, opt) { - if (!opt) opt = {}; - var tokens = tokenise(str); - return parse(tokens, opt); - } - }; - - if (inNode) module.exports = obj; - else self.WebIDL2 = obj; -}());
diff --git a/third_party/WebKit/LayoutTests/http/tests/w3c/resources/idlharness.js b/third_party/WebKit/LayoutTests/http/tests/w3c/resources/idlharness.js deleted file mode 100644 index 02304ca..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/w3c/resources/idlharness.js +++ /dev/null
@@ -1,1725 +0,0 @@ -/* -Distributed under both the W3C Test Suite License [1] and the W3C -3-clause BSD License [2]. To contribute to a W3C Test Suite, see the -policies and contribution forms [3]. - -[1] http://www.w3.org/Consortium/Legal/2008/04-testsuite-license -[2] http://www.w3.org/Consortium/Legal/2008/03-bsd-license -[3] http://www.w3.org/2004/10/27-testcases -*/ - -/* For user documentation see docs/idlharness.md */ - -/** - * Notes for people who want to edit this file (not just use it as a library): - * - * Most of the interesting stuff happens in the derived classes of IdlObject, - * especially IdlInterface. The entry point for all IdlObjects is .test(), - * which is called by IdlArray.test(). An IdlObject is conceptually just - * "thing we want to run tests on", and an IdlArray is an array of IdlObjects - * with some additional data thrown in. - * - * The object model is based on what WebIDLParser.js produces, which is in turn - * based on its pegjs grammar. If you want to figure out what properties an - * object will have from WebIDLParser.js, the best way is to look at the - * grammar: - * - * https://github.com/darobin/webidl.js/blob/master/lib/grammar.peg - * - * So for instance: - * - * // interface definition - * interface - * = extAttrs:extendedAttributeList? S? "interface" S name:identifier w herit:ifInheritance? w "{" w mem:ifMember* w "}" w ";" w - * { return { type: "interface", name: name, inheritance: herit, members: mem, extAttrs: extAttrs }; } - * - * This means that an "interface" object will have a .type property equal to - * the string "interface", a .name property equal to the identifier that the - * parser found, an .inheritance property equal to either null or the result of - * the "ifInheritance" production found elsewhere in the grammar, and so on. - * After each grammatical production is a JavaScript function in curly braces - * that gets called with suitable arguments and returns some JavaScript value. - * - * (Note that the version of WebIDLParser.js we use might sometimes be - * out-of-date or forked.) - * - * The members and methods of the classes defined by this file are all at least - * briefly documented, hopefully. - */ -(function(){ -"use strict"; -/// Helpers /// -function constValue (cnt) { - if (cnt.type === "null") return null; - if (cnt.type === "NaN") return NaN; - if (cnt.type === "Infinity") return cnt.negative ? -Infinity : Infinity; - return cnt.value; -} - -function minOverloadLength(overloads) { - if (!overloads.length) { - return 0; - } - - return overloads.map(function(attr) { - return attr.arguments ? attr.arguments.filter(function(arg) { - return !arg.optional && !arg.variadic; - }).length : 0; - }) - .reduce(function(m, n) { return Math.min(m, n); }); -} - -/// IdlArray /// -// Entry point -self.IdlArray = function() -//@{ -{ - /** - * A map from strings to the corresponding named IdlObject, such as - * IdlInterface or IdlException. These are the things that test() will run - * tests on. - */ - this.members = {}; - - /** - * A map from strings to arrays of strings. The keys are interface or - * exception names, and are expected to also exist as keys in this.members - * (otherwise they'll be ignored). This is populated by add_objects() -- - * see documentation at the start of the file. The actual tests will be - * run by calling this.members[name].test_object(obj) for each obj in - * this.objects[name]. obj is a string that will be eval'd to produce a - * JavaScript value, which is supposed to be an object implementing the - * given IdlObject (interface, exception, etc.). - */ - this.objects = {}; - - /** - * When adding multiple collections of IDLs one at a time, an earlier one - * might contain a partial interface or implements statement that depends - * on a later one. Save these up and handle them right before we run - * tests. - * - * .partials is simply an array of objects from WebIDLParser.js' - * "partialinterface" production. .implements maps strings to arrays of - * strings, such that - * - * A implements B; - * A implements C; - * D implements E; - * - * results in { A: ["B", "C"], D: ["E"] }. - */ - this.partials = []; - this["implements"] = {}; -}; - -//@} -IdlArray.prototype.add_idls = function(raw_idls) -//@{ -{ - /** Entry point. See documentation at beginning of file. */ - this.internal_add_idls(WebIDL2.parse(raw_idls)); -}; - -//@} -IdlArray.prototype.add_untested_idls = function(raw_idls) -//@{ -{ - /** Entry point. See documentation at beginning of file. */ - var parsed_idls = WebIDL2.parse(raw_idls); - for (var i = 0; i < parsed_idls.length; i++) - { - parsed_idls[i].untested = true; - if ("members" in parsed_idls[i]) - { - for (var j = 0; j < parsed_idls[i].members.length; j++) - { - parsed_idls[i].members[j].untested = true; - } - } - } - this.internal_add_idls(parsed_idls); -}; - -//@} -IdlArray.prototype.internal_add_idls = function(parsed_idls) -//@{ -{ - /** - * Internal helper called by add_idls() and add_untested_idls(). - * parsed_idls is an array of objects that come from WebIDLParser.js's - * "definitions" production. The add_untested_idls() entry point - * additionally sets an .untested property on each object (and its - * .members) so that they'll be skipped by test() -- they'll only be - * used for base interfaces of tested interfaces, return types, etc. - */ - parsed_idls.forEach(function(parsed_idl) - { - if (parsed_idl.type == "interface" && parsed_idl.partial) - { - this.partials.push(parsed_idl); - return; - } - - if (parsed_idl.type == "implements") - { - if (!(parsed_idl.target in this["implements"])) - { - this["implements"][parsed_idl.target] = []; - } - this["implements"][parsed_idl.target].push(parsed_idl["implements"]); - return; - } - - parsed_idl.array = this; - if (parsed_idl.name in this.members) - { - throw "Duplicate identifier " + parsed_idl.name; - } - switch(parsed_idl.type) - { - case "interface": - this.members[parsed_idl.name] = - new IdlInterface(parsed_idl, /* is_callback = */ false); - break; - - case "dictionary": - // Nothing to test, but we need the dictionary info around for type - // checks - this.members[parsed_idl.name] = new IdlDictionary(parsed_idl); - break; - - case "typedef": - this.members[parsed_idl.name] = new IdlTypedef(parsed_idl); - break; - - case "callback": - // TODO - console.log("callback not yet supported"); - break; - - case "enum": - this.members[parsed_idl.name] = new IdlEnum(parsed_idl); - break; - - case "callback interface": - this.members[parsed_idl.name] = - new IdlInterface(parsed_idl, /* is_callback = */ true); - break; - - default: - throw parsed_idl.name + ": " + parsed_idl.type + " not yet supported"; - } - }.bind(this)); -}; - -//@} -IdlArray.prototype.add_objects = function(dict) -//@{ -{ - /** Entry point. See documentation at beginning of file. */ - for (var k in dict) - { - if (k in this.objects) - { - this.objects[k] = this.objects[k].concat(dict[k]); - } - else - { - this.objects[k] = dict[k]; - } - } -}; - -//@} -IdlArray.prototype.prevent_multiple_testing = function(name) -//@{ -{ - /** Entry point. See documentation at beginning of file. */ - this.members[name].prevent_multiple_testing = true; -}; - -//@} -IdlArray.prototype.recursively_get_implements = function(interface_name) -//@{ -{ - /** - * Helper function for test(). Returns an array of things that implement - * interface_name, so if the IDL contains - * - * A implements B; - * B implements C; - * B implements D; - * - * then recursively_get_implements("A") should return ["B", "C", "D"]. - */ - var ret = this["implements"][interface_name]; - if (ret === undefined) - { - return []; - } - for (var i = 0; i < this["implements"][interface_name].length; i++) - { - ret = ret.concat(this.recursively_get_implements(ret[i])); - if (ret.indexOf(ret[i]) != ret.lastIndexOf(ret[i])) - { - throw "Circular implements statements involving " + ret[i]; - } - } - return ret; -}; - -//@} -IdlArray.prototype.test = function() -//@{ -{ - /** Entry point. See documentation at beginning of file. */ - - // First merge in all the partial interfaces and implements statements we - // encountered. - this.partials.forEach(function(parsed_idl) - { - if (!(parsed_idl.name in this.members) - || !(this.members[parsed_idl.name] instanceof IdlInterface)) - { - throw "Partial interface " + parsed_idl.name + " with no original interface"; - } - if (parsed_idl.extAttrs) - { - parsed_idl.extAttrs.forEach(function(extAttr) - { - this.members[parsed_idl.name].extAttrs.push(extAttr); - }.bind(this)); - } - parsed_idl.members.forEach(function(member) - { - this.members[parsed_idl.name].members.push(new IdlInterfaceMember(member)); - }.bind(this)); - }.bind(this)); - this.partials = []; - - for (var lhs in this["implements"]) - { - this.recursively_get_implements(lhs).forEach(function(rhs) - { - var errStr = lhs + " implements " + rhs + ", but "; - if (!(lhs in this.members)) throw errStr + lhs + " is undefined."; - if (!(this.members[lhs] instanceof IdlInterface)) throw errStr + lhs + " is not an interface."; - if (!(rhs in this.members)) throw errStr + rhs + " is undefined."; - if (!(this.members[rhs] instanceof IdlInterface)) throw errStr + rhs + " is not an interface."; - this.members[rhs].members.forEach(function(member) - { - this.members[lhs].members.push(new IdlInterfaceMember(member)); - }.bind(this)); - }.bind(this)); - } - this["implements"] = {}; - - // Now run test() on every member, and test_object() for every object. - for (var name in this.members) - { - this.members[name].test(); - if (name in this.objects) - { - this.objects[name].forEach(function(str) - { - this.members[name].test_object(str); - }.bind(this)); - } - } -}; - -//@} -IdlArray.prototype.assert_type_is = function(value, type) -//@{ -{ - /** - * Helper function that tests that value is an instance of type according - * to the rules of WebIDL. value is any JavaScript value, and type is an - * object produced by WebIDLParser.js' "type" production. That production - * is fairly elaborate due to the complexity of WebIDL's types, so it's - * best to look at the grammar to figure out what properties it might have. - */ - if (type.idlType == "any") - { - // No assertions to make - return; - } - - if (type.nullable && value === null) - { - // This is fine - return; - } - - if (type.array) - { - // TODO: not supported yet - return; - } - - if (type.sequence) - { - assert_true(Array.isArray(value), "is not array"); - if (!value.length) - { - // Nothing we can do. - return; - } - this.assert_type_is(value[0], type.idlType.idlType); - return; - } - - type = type.idlType; - - switch(type) - { - case "void": - assert_equals(value, undefined); - return; - - case "boolean": - assert_equals(typeof value, "boolean"); - return; - - case "byte": - assert_equals(typeof value, "number"); - assert_equals(value, Math.floor(value), "not an integer"); - assert_true(-128 <= value && value <= 127, "byte " + value + " not in range [-128, 127]"); - return; - - case "octet": - assert_equals(typeof value, "number"); - assert_equals(value, Math.floor(value), "not an integer"); - assert_true(0 <= value && value <= 255, "octet " + value + " not in range [0, 255]"); - return; - - case "short": - assert_equals(typeof value, "number"); - assert_equals(value, Math.floor(value), "not an integer"); - assert_true(-32768 <= value && value <= 32767, "short " + value + " not in range [-32768, 32767]"); - return; - - case "unsigned short": - assert_equals(typeof value, "number"); - assert_equals(value, Math.floor(value), "not an integer"); - assert_true(0 <= value && value <= 65535, "unsigned short " + value + " not in range [0, 65535]"); - return; - - case "long": - assert_equals(typeof value, "number"); - assert_equals(value, Math.floor(value), "not an integer"); - assert_true(-2147483648 <= value && value <= 2147483647, "long " + value + " not in range [-2147483648, 2147483647]"); - return; - - case "unsigned long": - assert_equals(typeof value, "number"); - assert_equals(value, Math.floor(value), "not an integer"); - assert_true(0 <= value && value <= 4294967295, "unsigned long " + value + " not in range [0, 4294967295]"); - return; - - case "long long": - assert_equals(typeof value, "number"); - return; - - case "unsigned long long": - case "DOMTimeStamp": - assert_equals(typeof value, "number"); - assert_true(0 <= value, "unsigned long long is negative"); - return; - - case "float": - case "double": - case "DOMHighResTimeStamp": - case "unrestricted float": - case "unrestricted double": - // TODO: distinguish these cases - assert_equals(typeof value, "number"); - return; - - case "DOMString": - case "ByteString": - case "USVString": - // TODO: https://github.com/w3c/testharness.js/issues/92 - assert_equals(typeof value, "string"); - return; - - case "object": - assert_true(typeof value == "object" || typeof value == "function", "wrong type: not object or function"); - return; - } - - if (!(type in this.members)) - { - throw "Unrecognized type " + type; - } - - if (this.members[type] instanceof IdlInterface) - { - // We don't want to run the full - // IdlInterface.prototype.test_instance_of, because that could result - // in an infinite loop. TODO: This means we don't have tests for - // NoInterfaceObject interfaces, and we also can't test objects that - // come from another self. - assert_true(typeof value == "object" || typeof value == "function", "wrong type: not object or function"); - if (value instanceof Object - && !this.members[type].has_extended_attribute("NoInterfaceObject") - && type in self) - { - assert_true(value instanceof self[type], "not instanceof " + type); - } - } - else if (this.members[type] instanceof IdlEnum) - { - assert_equals(typeof value, "string"); - } - else if (this.members[type] instanceof IdlDictionary) - { - // TODO: Test when we actually have something to test this on - } - else if (this.members[type] instanceof IdlTypedef) - { - // TODO: Test when we actually have something to test this on - } - else - { - throw "Type " + type + " isn't an interface or dictionary"; - } -}; -//@} - -/// IdlObject /// -function IdlObject() {} -IdlObject.prototype.test = function() -//@{ -{ - /** - * By default, this does nothing, so no actual tests are run for IdlObjects - * that don't define any (e.g., IdlDictionary at the time of this writing). - */ -}; - -//@} -IdlObject.prototype.has_extended_attribute = function(name) -//@{ -{ - /** - * This is only meaningful for things that support extended attributes, - * such as interfaces, exceptions, and members. - */ - return this.extAttrs.some(function(o) - { - return o.name == name; - }); -}; - -//@} - -/// IdlDictionary /// -// Used for IdlArray.prototype.assert_type_is -function IdlDictionary(obj) -//@{ -{ - /** - * obj is an object produced by the WebIDLParser.js "dictionary" - * production. - */ - - /** Self-explanatory. */ - this.name = obj.name; - - /** An array of objects produced by the "dictionaryMember" production. */ - this.members = obj.members; - - /** - * The name (as a string) of the dictionary type we inherit from, or null - * if there is none. - */ - this.base = obj.inheritance; -} - -//@} -IdlDictionary.prototype = Object.create(IdlObject.prototype); - -/// IdlInterface /// -function IdlInterface(obj, is_callback) { - /** - * obj is an object produced by the WebIDLParser.js "exception" or - * "interface" production, as appropriate. - */ - - /** Self-explanatory. */ - this.name = obj.name; - - /** A back-reference to our IdlArray. */ - this.array = obj.array; - - /** - * An indicator of whether we should run tests on the (exception) interface - * object and (exception) interface prototype object. Tests on members are - * controlled by .untested on each member, not this. - */ - this.untested = obj.untested; - - /** An array of objects produced by the "ExtAttr" production. */ - this.extAttrs = obj.extAttrs; - - /** An array of IdlInterfaceMembers. */ - this.members = obj.members.map(function(m){return new IdlInterfaceMember(m); }); - if (this.has_extended_attribute("Unforgeable")) { - this.members - .filter(function(m) { return !m["static"] && (m.type == "attribute" || m.type == "operation"); }) - .forEach(function(m) { return m.isUnforgeable = true; }); - } - - /** - * The name (as a string) of the type we inherit from, or null if there is - * none. - */ - this.base = obj.inheritance; - - this._is_callback = is_callback; -} -IdlInterface.prototype = Object.create(IdlObject.prototype); -IdlInterface.prototype.is_callback = function() -//@{ -{ - return this._is_callback; -}; -//@} - -IdlInterface.prototype.has_constants = function() -//@{ -{ - return this.members.some(function(member) { - return member.type === "const"; - }); -}; -//@} - -IdlInterface.prototype.is_global = function() -//@{ -{ - return this.extAttrs.some(function(attribute) { - return attribute.name === "Global" || - attribute.name === "PrimaryGlobal"; - }); -}; -//@} - -IdlInterface.prototype.test = function() -//@{ -{ - if (this.has_extended_attribute("NoInterfaceObject")) - { - // No tests to do without an instance. TODO: We should still be able - // to run tests on the prototype object, if we obtain one through some - // other means. - return; - } - - if (!this.untested) - { - // First test things to do with the exception/interface object and - // exception/interface prototype object. - this.test_self(); - } - // Then test things to do with its members (constants, fields, attributes, - // operations, . . .). These are run even if .untested is true, because - // members might themselves be marked as .untested. This might happen to - // interfaces if the interface itself is untested but a partial interface - // that extends it is tested -- then the interface itself and its initial - // members will be marked as untested, but the members added by the partial - // interface are still tested. - this.test_members(); -}; -//@} - -IdlInterface.prototype.test_self = function() -//@{ -{ - test(function() - { - // This function tests WebIDL as of 2015-01-13. - // TODO: Consider [Exposed]. - - // "For every interface that is exposed in a given ECMAScript global - // environment and: - // * is a callback interface that has constants declared on it, or - // * is a non-callback interface that is not declared with the - // [NoInterfaceObject] extended attribute, - // a corresponding property MUST exist on the ECMAScript global object. - // The name of the property is the identifier of the interface, and its - // value is an object called the interface object. - // The property has the attributes { [[Writable]]: true, - // [[Enumerable]]: false, [[Configurable]]: true }." - if (this.is_callback() && !this.has_constants()) { - return; - } - - // TODO: Should we test here that the property is actually writable - // etc., or trust getOwnPropertyDescriptor? - assert_own_property(self, this.name, - "self does not have own property " + format_value(this.name)); - var desc = Object.getOwnPropertyDescriptor(self, this.name); - assert_false("get" in desc, "self's property " + format_value(this.name) + " has getter"); - assert_false("set" in desc, "self's property " + format_value(this.name) + " has setter"); - assert_true(desc.writable, "self's property " + format_value(this.name) + " is not writable"); - assert_false(desc.enumerable, "self's property " + format_value(this.name) + " is enumerable"); - assert_true(desc.configurable, "self's property " + format_value(this.name) + " is not configurable"); - - if (this.is_callback()) { - // "The internal [[Prototype]] property of an interface object for - // a callback interface MUST be the Object.prototype object." - assert_equals(Object.getPrototypeOf(self[this.name]), Object.prototype, - "prototype of self's property " + format_value(this.name) + " is not Object.prototype"); - - return; - } - - // "The interface object for a given non-callback interface is a - // function object." - // "If an object is defined to be a function object, then it has - // characteristics as follows:" - - // Its [[Prototype]] internal property is otherwise specified (see - // below). - - // "* Its [[Get]] internal property is set as described in ECMA-262 - // section 9.1.8." - // Not much to test for this. - - // "* Its [[Construct]] internal property is set as described in - // ECMA-262 section 19.2.2.3." - // Tested below if no constructor is defined. TODO: test constructors - // if defined. - - // "* Its @@hasInstance property is set as described in ECMA-262 - // section 19.2.3.8, unless otherwise specified." - // TODO - - // ES6 (rev 30) 19.1.3.6: - // "Else, if O has a [[Call]] internal method, then let builtinTag be - // "Function"." - assert_class_string(self[this.name], "Function", "class string of " + this.name); - - // "The [[Prototype]] internal property of an interface object for a - // non-callback interface is determined as follows:" - var prototype = Object.getPrototypeOf(self[this.name]); - if (this.base) { - // "* If the interface inherits from some other interface, the - // value of [[Prototype]] is the interface object for that other - // interface." - var has_interface_object = - !this.array - .members[this.base] - .has_extended_attribute("NoInterfaceObject"); - if (has_interface_object) { - assert_own_property(self, this.base, - 'should inherit from ' + this.base + - ', but self has no such property'); - assert_equals(prototype, self[this.base], - 'prototype of ' + this.name + ' is not ' + - this.base); - } - } else { - // "If the interface doesn't inherit from any other interface, the - // value of [[Prototype]] is %FunctionPrototype% ([ECMA-262], - // section 6.1.7.4)." - assert_equals(prototype, Function.prototype, - "prototype of self's property " + format_value(this.name) + " is not Function.prototype"); - } - - if (!this.has_extended_attribute("Constructor")) { - // "The internal [[Call]] method of the interface object behaves as - // follows . . . - // - // "If I was not declared with a [Constructor] extended attribute, - // then throw a TypeError." - assert_throws(new TypeError(), function() { - self[this.name](); - }.bind(this), "interface object didn't throw TypeError when called as a function"); - assert_throws(new TypeError(), function() { - new self[this.name](); - }.bind(this), "interface object didn't throw TypeError when called as a constructor"); - } - }.bind(this), this.name + " interface: existence and properties of interface object"); - - if (!this.is_callback()) { - test(function() { - // This function tests WebIDL as of 2014-10-25. - // https://heycam.github.io/webidl/#es-interface-call - - assert_own_property(self, this.name, - "self does not have own property " + format_value(this.name)); - - // "Interface objects for non-callback interfaces MUST have a - // property named “length” with attributes { [[Writable]]: false, - // [[Enumerable]]: false, [[Configurable]]: true } whose value is - // a Number." - assert_own_property(self[this.name], "length"); - var desc = Object.getOwnPropertyDescriptor(self[this.name], "length"); - assert_false("get" in desc, this.name + ".length has getter"); - assert_false("set" in desc, this.name + ".length has setter"); - assert_false(desc.writable, this.name + ".length is writable"); - assert_false(desc.enumerable, this.name + ".length is enumerable"); - assert_true(desc.configurable, this.name + ".length is not configurable"); - - var constructors = this.extAttrs - .filter(function(attr) { return attr.name == "Constructor"; }); - var expected_length = minOverloadLength(constructors); - assert_equals(self[this.name].length, expected_length, "wrong value for " + this.name + ".length"); - }.bind(this), this.name + " interface object length"); - } - - if (!this.is_callback() || this.has_constants()) { - test(function() { - // This function tests WebIDL as of 2015-11-17. - // https://heycam.github.io/webidl/#interface-object - - assert_own_property(self, this.name, - "self does not have own property " + format_value(this.name)); - - // "All interface objects must have a property named “name” with - // attributes { [[Writable]]: false, [[Enumerable]]: false, - // [[Configurable]]: true } whose value is the identifier of the - // corresponding interface." - - assert_own_property(self[this.name], "name"); - var desc = Object.getOwnPropertyDescriptor(self[this.name], "name"); - assert_false("get" in desc, this.name + ".name has getter"); - assert_false("set" in desc, this.name + ".name has setter"); - assert_false(desc.writable, this.name + ".name is writable"); - assert_false(desc.enumerable, this.name + ".name is enumerable"); - assert_true(desc.configurable, this.name + ".name is not configurable"); - assert_equals(self[this.name].name, this.name, "wrong value for " + this.name + ".name"); - }.bind(this), this.name + " interface object name"); - } - - // TODO: Test named constructors if I find any interfaces that have them. - - test(function() - { - // This function tests WebIDL as of 2015-01-21. - // https://heycam.github.io/webidl/#interface-object - - if (this.is_callback() && !this.has_constants()) { - return; - } - - assert_own_property(self, this.name, - "self does not have own property " + format_value(this.name)); - - if (this.is_callback()) { - assert_false("prototype" in self[this.name], - this.name + ' should not have a "prototype" property'); - return; - } - - // "An interface object for a non-callback interface must have a - // property named “prototype” with attributes { [[Writable]]: false, - // [[Enumerable]]: false, [[Configurable]]: false } whose value is an - // object called the interface prototype object. This object has - // properties that correspond to the regular attributes and regular - // operations defined on the interface, and is described in more detail - // in section 4.5.4 below." - assert_own_property(self[this.name], "prototype", - 'interface "' + this.name + '" does not have own property "prototype"'); - var desc = Object.getOwnPropertyDescriptor(self[this.name], "prototype"); - assert_false("get" in desc, this.name + ".prototype has getter"); - assert_false("set" in desc, this.name + ".prototype has setter"); - assert_false(desc.writable, this.name + ".prototype is writable"); - assert_false(desc.enumerable, this.name + ".prototype is enumerable"); - assert_false(desc.configurable, this.name + ".prototype is configurable"); - - // Next, test that the [[Prototype]] of the interface prototype object - // is correct. (This is made somewhat difficult by the existence of - // [NoInterfaceObject].) - // TODO: Aryeh thinks there's at least other place in this file where - // we try to figure out if an interface prototype object is - // correct. Consolidate that code. - - // "The interface prototype object for a given interface A must have an - // internal [[Prototype]] property whose value is returned from the - // following steps: - // "If A is declared with the [Global] or [PrimaryGlobal] extended - // attribute, and A supports named properties, then return the named - // properties object for A, as defined in section 4.5.5 below. - // "Otherwise, if A is declared to inherit from another interface, then - // return the interface prototype object for the inherited interface. - // "Otherwise, if A is declared with the [ArrayClass] extended - // attribute, then return %ArrayPrototype% ([ECMA-262], section - // 6.1.7.4). - // "Otherwise, return %ObjectPrototype% ([ECMA-262], section 6.1.7.4). - // ([ECMA-262], section 15.2.4). - if (this.name === "Window") { - assert_class_string(Object.getPrototypeOf(self[this.name].prototype), - 'WindowProperties', - 'Class name for prototype of Window' + - '.prototype is not "WindowProperties"'); - } else { - var inherit_interface, inherit_interface_has_interface_object; - if (this.base) { - inherit_interface = this.base; - inherit_interface_has_interface_object = - !this.array - .members[inherit_interface] - .has_extended_attribute("NoInterfaceObject"); - } else if (this.has_extended_attribute('ArrayClass')) { - inherit_interface = 'Array'; - inherit_interface_has_interface_object = true; - } else { - inherit_interface = 'Object'; - inherit_interface_has_interface_object = true; - } - if (inherit_interface_has_interface_object) { - assert_own_property(self, inherit_interface, - 'should inherit from ' + inherit_interface + ', but self has no such property'); - assert_own_property(self[inherit_interface], 'prototype', - 'should inherit from ' + inherit_interface + ', but that object has no "prototype" property'); - assert_equals(Object.getPrototypeOf(self[this.name].prototype), - self[inherit_interface].prototype, - 'prototype of ' + this.name + '.prototype is not ' + inherit_interface + '.prototype'); - } else { - // We can't test that we get the correct object, because this is the - // only way to get our hands on it. We only test that its class - // string, at least, is correct. - assert_class_string(Object.getPrototypeOf(self[this.name].prototype), - inherit_interface + 'Prototype', - 'Class name for prototype of ' + this.name + - '.prototype is not "' + inherit_interface + 'Prototype"'); - } - } - - // "The class string of an interface prototype object is the - // concatenation of the interface’s identifier and the string - // “Prototype”." - assert_class_string(self[this.name].prototype, this.name + "Prototype", - "class string of " + this.name + ".prototype"); - // String() should end up calling {}.toString if nothing defines a - // stringifier. - if (!this.has_stringifier()) { - assert_equals(String(self[this.name].prototype), "[object " + this.name + "Prototype]", - "String(" + this.name + ".prototype)"); - } - }.bind(this), this.name + " interface: existence and properties of interface prototype object"); - - test(function() - { - if (this.is_callback() && !this.has_constants()) { - return; - } - - assert_own_property(self, this.name, - "self does not have own property " + format_value(this.name)); - - if (this.is_callback()) { - assert_false("prototype" in self[this.name], - this.name + ' should not have a "prototype" property'); - return; - } - - assert_own_property(self[this.name], "prototype", - 'interface "' + this.name + '" does not have own property "prototype"'); - - // "If the [NoInterfaceObject] extended attribute was not specified on - // the interface, then the interface prototype object must also have a - // property named “constructor” with attributes { [[Writable]]: true, - // [[Enumerable]]: false, [[Configurable]]: true } whose value is a - // reference to the interface object for the interface." - assert_own_property(self[this.name].prototype, "constructor", - this.name + '.prototype does not have own property "constructor"'); - var desc = Object.getOwnPropertyDescriptor(self[this.name].prototype, "constructor"); - assert_false("get" in desc, this.name + ".prototype.constructor has getter"); - assert_false("set" in desc, this.name + ".prototype.constructor has setter"); - assert_true(desc.writable, this.name + ".prototype.constructor is not writable"); - assert_false(desc.enumerable, this.name + ".prototype.constructor is enumerable"); - assert_true(desc.configurable, this.name + ".prototype.constructor in not configurable"); - assert_equals(self[this.name].prototype.constructor, self[this.name], - this.name + '.prototype.constructor is not the same object as ' + this.name); - }.bind(this), this.name + ' interface: existence and properties of interface prototype object\'s "constructor" property'); -}; - -//@} -IdlInterface.prototype.test_member_const = function(member) -//@{ -{ - test(function() - { - if (this.is_callback() && !this.has_constants()) { - return; - } - - assert_own_property(self, this.name, - "self does not have own property " + format_value(this.name)); - - // "For each constant defined on an interface A, there must be - // a corresponding property on the interface object, if it - // exists." - assert_own_property(self[this.name], member.name); - // "The value of the property is that which is obtained by - // converting the constant’s IDL value to an ECMAScript - // value." - assert_equals(self[this.name][member.name], constValue(member.value), - "property has wrong value"); - // "The property has attributes { [[Writable]]: false, - // [[Enumerable]]: true, [[Configurable]]: false }." - var desc = Object.getOwnPropertyDescriptor(self[this.name], member.name); - assert_false("get" in desc, "property has getter"); - assert_false("set" in desc, "property has setter"); - assert_false(desc.writable, "property is writable"); - assert_true(desc.enumerable, "property is not enumerable"); - assert_false(desc.configurable, "property is configurable"); - }.bind(this), this.name + " interface: constant " + member.name + " on interface object"); - // "In addition, a property with the same characteristics must - // exist on the interface prototype object." - test(function() - { - if (this.is_callback() && !this.has_constants()) { - return; - } - - assert_own_property(self, this.name, - "self does not have own property " + format_value(this.name)); - - if (this.is_callback()) { - assert_false("prototype" in self[this.name], - this.name + ' should not have a "prototype" property'); - return; - } - - assert_own_property(self[this.name], "prototype", - 'interface "' + this.name + '" does not have own property "prototype"'); - - assert_own_property(self[this.name].prototype, member.name); - assert_equals(self[this.name].prototype[member.name], constValue(member.value), - "property has wrong value"); - var desc = Object.getOwnPropertyDescriptor(self[this.name], member.name); - assert_false("get" in desc, "property has getter"); - assert_false("set" in desc, "property has setter"); - assert_false(desc.writable, "property is writable"); - assert_true(desc.enumerable, "property is not enumerable"); - assert_false(desc.configurable, "property is configurable"); - }.bind(this), this.name + " interface: constant " + member.name + " on interface prototype object"); -}; - - -//@} -IdlInterface.prototype.test_member_attribute = function(member) -//@{ -{ - test(function() - { - if (this.is_callback() && !this.has_constants()) { - return; - } - - assert_own_property(self, this.name, - "self does not have own property " + format_value(this.name)); - assert_own_property(self[this.name], "prototype", - 'interface "' + this.name + '" does not have own property "prototype"'); - - if (member["static"]) { - assert_own_property(self[this.name], member.name, - "The interface object must have a property " + - format_value(member.name)); - } else if (this.is_global()) { - assert_own_property(self, member.name, - "The global object must have a property " + - format_value(member.name)); - assert_false(member.name in self[this.name].prototype, - "The prototype object must not have a property " + - format_value(member.name)); - - // Try/catch around the get here, since it can legitimately throw. - // If it does, we obviously can't check for equality with direct - // invocation of the getter. - var gotValue; - var propVal; - try { - propVal = self[member.name]; - gotValue = true; - } catch (e) { - gotValue = false; - } - if (gotValue) { - var getter = Object.getOwnPropertyDescriptor(self, member.name).get; - assert_equals(typeof(getter), "function", - format_value(member.name) + " must have a getter"); - assert_equals(propVal, getter.call(undefined), - "Gets on a global should not require an explicit this"); - } - this.do_interface_attribute_asserts(self, member); - } else { - assert_true(member.name in self[this.name].prototype, - "The prototype object must have a property " + - format_value(member.name)); - - if (!member.has_extended_attribute("LenientThis")) { - assert_throws(new TypeError(), function() { - self[this.name].prototype[member.name]; - }.bind(this), "getting property on prototype object must throw TypeError"); - } else { - assert_equals(self[this.name].prototype[member.name], undefined, - "getting property on prototype object must return undefined"); - } - this.do_interface_attribute_asserts(self[this.name].prototype, member); - } - }.bind(this), this.name + " interface: attribute " + member.name); -}; - -//@} -IdlInterface.prototype.test_member_operation = function(member) -//@{ -{ - test(function() - { - if (this.is_callback() && !this.has_constants()) { - return; - } - - assert_own_property(self, this.name, - "self does not have own property " + format_value(this.name)); - - if (this.is_callback()) { - assert_false("prototype" in self[this.name], - this.name + ' should not have a "prototype" property'); - return; - } - - assert_own_property(self[this.name], "prototype", - 'interface "' + this.name + '" does not have own property "prototype"'); - - // "For each unique identifier of an operation defined on the - // interface, there must be a corresponding property on the - // interface prototype object (if it is a regular operation) or - // the interface object (if it is a static operation), unless - // the effective overload set for that identifier and operation - // and with an argument count of 0 (for the ECMAScript language - // binding) has no entries." - // - var memberHolderObject; - if (member["static"]) { - assert_own_property(self[this.name], member.name, - "interface object missing static operation"); - memberHolderObject = self[this.name]; - } else if (this.is_global()) { - assert_own_property(self, member.name, - "global object missing non-static operation"); - memberHolderObject = self; - } else { - assert_own_property(self[this.name].prototype, member.name, - "interface prototype object missing non-static operation"); - memberHolderObject = self[this.name].prototype; - } - - this.do_member_operation_asserts(memberHolderObject, member); - }.bind(this), this.name + " interface: operation " + member.name + - "(" + member.arguments.map(function(m) { return m.idlType.idlType; }) + - ")"); -}; - -//@} -IdlInterface.prototype.do_member_operation_asserts = function(memberHolderObject, member) -//@{ -{ - var operationUnforgeable = member.isUnforgeable; - var desc = Object.getOwnPropertyDescriptor(memberHolderObject, member.name); - // "The property has attributes { [[Writable]]: B, - // [[Enumerable]]: true, [[Configurable]]: B }, where B is false if the - // operation is unforgeable on the interface, and true otherwise". - assert_false("get" in desc, "property has getter"); - assert_false("set" in desc, "property has setter"); - assert_equals(desc.writable, !operationUnforgeable, - "property should be writable if and only if not unforgeable"); - assert_true(desc.enumerable, "property is not enumerable"); - assert_equals(desc.configurable, !operationUnforgeable, - "property should be configurable if and only if not unforgeable"); - // "The value of the property is a Function object whose - // behavior is as follows . . ." - assert_equals(typeof memberHolderObject[member.name], "function", - "property must be a function"); - // "The value of the Function object’s “length” property is - // a Number determined as follows: - // ". . . - // "Return the length of the shortest argument list of the - // entries in S." - assert_equals(memberHolderObject[member.name].length, - minOverloadLength(this.members.filter(function(m) { - return m.type == "operation" && m.name == member.name; - })), - "property has wrong .length"); - - // Make some suitable arguments - var args = member.arguments.map(function(arg) { - return create_suitable_object(arg.idlType); - }); - - // "Let O be a value determined as follows: - // ". . . - // "Otherwise, throw a TypeError." - // This should be hit if the operation is not static, there is - // no [ImplicitThis] attribute, and the this value is null. - // - // TODO: We currently ignore the [ImplicitThis] case. Except we manually - // check for globals, since otherwise we'll invoke window.close(). And we - // have to skip this test for anything that on the proto chain of "self", - // since that does in fact have implicit-this behavior. - if (!member["static"]) { - if (!this.is_global() && - memberHolderObject[member.name] != self[member.name]) - { - assert_throws(new TypeError(), function() { - memberHolderObject[member.name].apply(null, args); - }, "calling operation with this = null didn't throw TypeError"); - } - - // ". . . If O is not null and is also not a platform object - // that implements interface I, throw a TypeError." - // - // TODO: Test a platform object that implements some other - // interface. (Have to be sure to get inheritance right.) - assert_throws(new TypeError(), function() { - memberHolderObject[member.name].apply({}, args); - }, "calling operation with this = {} didn't throw TypeError"); - } -} - -//@} -IdlInterface.prototype.test_member_stringifier = function(member) -//@{ -{ - test(function() - { - if (this.is_callback() && !this.has_constants()) { - return; - } - - assert_own_property(self, this.name, - "self does not have own property " + format_value(this.name)); - - if (this.is_callback()) { - assert_false("prototype" in self[this.name], - this.name + ' should not have a "prototype" property'); - return; - } - - assert_own_property(self[this.name], "prototype", - 'interface "' + this.name + '" does not have own property "prototype"'); - - // ". . . the property exists on the interface prototype object." - var interfacePrototypeObject = self[this.name].prototype; - assert_own_property(self[this.name].prototype, "toString", - "interface prototype object missing non-static operation"); - - var stringifierUnforgeable = member.isUnforgeable; - var desc = Object.getOwnPropertyDescriptor(interfacePrototypeObject, "toString"); - // "The property has attributes { [[Writable]]: B, - // [[Enumerable]]: true, [[Configurable]]: B }, where B is false if the - // stringifier is unforgeable on the interface, and true otherwise." - assert_false("get" in desc, "property has getter"); - assert_false("set" in desc, "property has setter"); - assert_equals(desc.writable, !stringifierUnforgeable, - "property should be writable if and only if not unforgeable"); - assert_true(desc.enumerable, "property is not enumerable"); - assert_equals(desc.configurable, !stringifierUnforgeable, - "property should be configurable if and only if not unforgeable"); - // "The value of the property is a Function object, which behaves as - // follows . . ." - assert_equals(typeof interfacePrototypeObject.toString, "function", - "property must be a function"); - // "The value of the Function object’s “length” property is the Number - // value 0." - assert_equals(interfacePrototypeObject.toString.length, 0, - "property has wrong .length"); - - // "Let O be the result of calling ToObject on the this value." - assert_throws(new TypeError(), function() { - self[this.name].prototype.toString.apply(null, []); - }, "calling stringifier with this = null didn't throw TypeError"); - - // "If O is not an object that implements the interface on which the - // stringifier was declared, then throw a TypeError." - // - // TODO: Test a platform object that implements some other - // interface. (Have to be sure to get inheritance right.) - assert_throws(new TypeError(), function() { - self[this.name].prototype.toString.apply({}, []); - }, "calling stringifier with this = {} didn't throw TypeError"); - }.bind(this), this.name + " interface: stringifier"); -}; - -//@} -IdlInterface.prototype.test_members = function() -//@{ -{ - for (var i = 0; i < this.members.length; i++) - { - var member = this.members[i]; - if (member.untested) { - continue; - } - - switch (member.type) { - case "const": - this.test_member_const(member); - break; - - case "attribute": - // For unforgeable attributes, we do the checks in - // test_interface_of instead. - if (!member.isUnforgeable) - { - this.test_member_attribute(member); - } - break; - - case "operation": - // TODO: Need to correctly handle multiple operations with the same - // identifier. - // For unforgeable operations, we do the checks in - // test_interface_of instead. - if (member.name) { - if (!member.isUnforgeable) - { - this.test_member_operation(member); - } - } else if (member.stringifier) { - this.test_member_stringifier(member); - } - break; - - default: - // TODO: check more member types. - break; - } - } -}; - -//@} -IdlInterface.prototype.test_object = function(desc) -//@{ -{ - var obj, exception = null; - try - { - obj = eval(desc); - } - catch(e) - { - exception = e; - } - - var expected_typeof = - this.members.some(function(member) { return member.legacycaller; }) - ? "function" - : "object"; - - this.test_primary_interface_of(desc, obj, exception, expected_typeof); - var current_interface = this; - while (current_interface) - { - if (!(current_interface.name in this.array.members)) - { - throw "Interface " + current_interface.name + " not found (inherited by " + this.name + ")"; - } - if (current_interface.prevent_multiple_testing && current_interface.already_tested) - { - return; - } - current_interface.test_interface_of(desc, obj, exception, expected_typeof); - current_interface = this.array.members[current_interface.base]; - } -}; - -//@} -IdlInterface.prototype.test_primary_interface_of = function(desc, obj, exception, expected_typeof) -//@{ -{ - // We can't easily test that its prototype is correct if there's no - // interface object, or the object is from a different global environment - // (not instanceof Object). TODO: test in this case that its prototype at - // least looks correct, even if we can't test that it's actually correct. - if (!this.has_extended_attribute("NoInterfaceObject") - && (typeof obj != expected_typeof || obj instanceof Object)) - { - test(function() - { - assert_equals(exception, null, "Unexpected exception when evaluating object"); - assert_equals(typeof obj, expected_typeof, "wrong typeof object"); - assert_own_property(self, this.name, - "self does not have own property " + format_value(this.name)); - assert_own_property(self[this.name], "prototype", - 'interface "' + this.name + '" does not have own property "prototype"'); - - // "The value of the internal [[Prototype]] property of the - // platform object is the interface prototype object of the primary - // interface from the platform object’s associated global - // environment." - assert_equals(Object.getPrototypeOf(obj), - self[this.name].prototype, - desc + "'s prototype is not " + this.name + ".prototype"); - }.bind(this), this.name + " must be primary interface of " + desc); - } - - // "The class string of a platform object that implements one or more - // interfaces must be the identifier of the primary interface of the - // platform object." - test(function() - { - assert_equals(exception, null, "Unexpected exception when evaluating object"); - assert_equals(typeof obj, expected_typeof, "wrong typeof object"); - assert_class_string(obj, this.name, "class string of " + desc); - if (!this.has_stringifier()) - { - assert_equals(String(obj), "[object " + this.name + "]", "String(" + desc + ")"); - } - }.bind(this), "Stringification of " + desc); -}; - -//@} -IdlInterface.prototype.test_interface_of = function(desc, obj, exception, expected_typeof) -//@{ -{ - // TODO: Indexed and named properties, more checks on interface members - this.already_tested = true; - - for (var i = 0; i < this.members.length; i++) - { - var member = this.members[i]; - if (member.type == "attribute" && member.isUnforgeable) - { - test(function() - { - assert_equals(exception, null, "Unexpected exception when evaluating object"); - assert_equals(typeof obj, expected_typeof, "wrong typeof object"); - this.do_interface_attribute_asserts(obj, member); - }.bind(this), this.name + " interface: " + desc + ' must have own property "' + member.name + '"'); - } - else if (member.type == "operation" && - member.name && - member.isUnforgeable) - { - test(function() - { - assert_equals(exception, null, "Unexpected exception when evaluating object"); - assert_equals(typeof obj, expected_typeof, "wrong typeof object"); - assert_own_property(obj, member.name, - "Doesn't have the unforgeable operation property"); - this.do_member_operation_asserts(obj, member); - }.bind(this), this.name + " interface: " + desc + ' must have own property "' + member.name + '"'); - } - else if ((member.type == "const" - || member.type == "attribute" - || member.type == "operation") - && member.name) - { - test(function() - { - assert_equals(exception, null, "Unexpected exception when evaluating object"); - assert_equals(typeof obj, expected_typeof, "wrong typeof object"); - if (!member["static"]) { - if (!this.is_global()) { - assert_inherits(obj, member.name); - } else { - assert_own_property(obj, member.name); - } - - if (member.type == "const") - { - assert_equals(obj[member.name], constValue(member.value)); - } - if (member.type == "attribute") - { - // Attributes are accessor properties, so they might - // legitimately throw an exception rather than returning - // anything. - var property, thrown = false; - try - { - property = obj[member.name]; - } - catch (e) - { - thrown = true; - } - if (!thrown) - { - this.array.assert_type_is(property, member.idlType); - } - } - if (member.type == "operation") - { - assert_equals(typeof obj[member.name], "function"); - } - } - }.bind(this), this.name + " interface: " + desc + ' must inherit property "' + member.name + '" with the proper type (' + i + ')'); - } - // TODO: This is wrong if there are multiple operations with the same - // identifier. - // TODO: Test passing arguments of the wrong type. - if (member.type == "operation" && member.name && member.arguments.length) - { - test(function() - { - assert_equals(exception, null, "Unexpected exception when evaluating object"); - assert_equals(typeof obj, expected_typeof, "wrong typeof object"); - if (!member["static"]) { - if (!this.is_global() && !member.isUnforgeable) { - assert_inherits(obj, member.name); - } else { - assert_own_property(obj, member.name); - } - } - else - { - assert_false(member.name in obj); - } - - var minLength = minOverloadLength(this.members.filter(function(m) { - return m.type == "operation" && m.name == member.name; - })); - var args = []; - for (var i = 0; i < minLength; i++) { - assert_throws(new TypeError(), function() - { - obj[member.name].apply(obj, args); - }.bind(this), "Called with " + i + " arguments"); - - args.push(create_suitable_object(member.arguments[i].idlType)); - } - }.bind(this), this.name + " interface: calling " + member.name + - "(" + member.arguments.map(function(m) { return m.idlType.idlType; }) + - ") on " + desc + " with too few arguments must throw TypeError"); - } - } -}; - -//@} -IdlInterface.prototype.has_stringifier = function() -//@{ -{ - if (this.members.some(function(member) { return member.stringifier; })) { - return true; - } - if (this.base && - this.array.members[this.base].has_stringifier()) { - return true; - } - return false; -}; - -//@} -IdlInterface.prototype.do_interface_attribute_asserts = function(obj, member) -//@{ -{ - // This function tests WebIDL as of 2015-01-27. - // TODO: Consider [Exposed]. - - // This is called by test_member_attribute() with the prototype as obj if - // it is not a global, and the global otherwise, and by test_interface_of() - // with the object as obj. - - // "For each exposed attribute of the interface, whether it was declared on - // the interface itself or one of its consequential interfaces, there MUST - // exist a corresponding property. The characteristics of this property are - // as follows:" - - // "The name of the property is the identifier of the attribute." - assert_own_property(obj, member.name); - - // "The property has attributes { [[Get]]: G, [[Set]]: S, [[Enumerable]]: - // true, [[Configurable]]: configurable }, where: - // "configurable is false if the attribute was declared with the - // [Unforgeable] extended attribute and true otherwise; - // "G is the attribute getter, defined below; and - // "S is the attribute setter, also defined below." - var desc = Object.getOwnPropertyDescriptor(obj, member.name); - assert_false("value" in desc, 'property descriptor has value but is supposed to be accessor'); - assert_false("writable" in desc, 'property descriptor has "writable" field but is supposed to be accessor'); - assert_true(desc.enumerable, "property is not enumerable"); - if (member.isUnforgeable) - { - assert_false(desc.configurable, "[Unforgeable] property must not be configurable"); - } - else - { - assert_true(desc.configurable, "property must be configurable"); - } - - - // "The attribute getter is a Function object whose behavior when invoked - // is as follows:" - assert_equals(typeof desc.get, "function", "getter must be Function"); - - // "If the attribute is a regular attribute, then:" - if (!member["static"]) { - // "If O is not a platform object that implements I, then: - // "If the attribute was specified with the [LenientThis] extended - // attribute, then return undefined. - // "Otherwise, throw a TypeError." - if (!member.has_extended_attribute("LenientThis")) { - assert_throws(new TypeError(), function() { - desc.get.call({}); - }.bind(this), "calling getter on wrong object type must throw TypeError"); - } else { - assert_equals(desc.get.call({}), undefined, - "calling getter on wrong object type must return undefined"); - } - } - - // "The value of the Function object’s “length” property is the Number - // value 0." - assert_equals(desc.get.length, 0, "getter length must be 0"); - - - // TODO: Test calling setter on the interface prototype (should throw - // TypeError in most cases). - if (member.readonly - && !member.has_extended_attribute("PutForwards") - && !member.has_extended_attribute("Replaceable")) - { - // "The attribute setter is undefined if the attribute is declared - // readonly and has neither a [PutForwards] nor a [Replaceable] - // extended attribute declared on it." - assert_equals(desc.set, undefined, "setter must be undefined for readonly attributes"); - } - else - { - // "Otherwise, it is a Function object whose behavior when - // invoked is as follows:" - assert_equals(typeof desc.set, "function", "setter must be function for PutForwards, Replaceable, or non-readonly attributes"); - - // "If the attribute is a regular attribute, then:" - if (!member["static"]) { - // "If /validThis/ is false and the attribute was not specified - // with the [LenientThis] extended attribute, then throw a - // TypeError." - // "If the attribute is declared with a [Replaceable] extended - // attribute, then: ..." - // "If validThis is false, then return." - if (!member.has_extended_attribute("LenientThis")) { - assert_throws(new TypeError(), function() { - desc.set.call({}); - }.bind(this), "calling setter on wrong object type must throw TypeError"); - } else { - assert_equals(desc.set.call({}), undefined, - "calling setter on wrong object type must return undefined"); - } - } - - // "The value of the Function object’s “length” property is the Number - // value 1." - assert_equals(desc.set.length, 1, "setter length must be 1"); - } -} -//@} - -/// IdlInterfaceMember /// -function IdlInterfaceMember(obj) -//@{ -{ - /** - * obj is an object produced by the WebIDLParser.js "ifMember" production. - * We just forward all properties to this object without modification, - * except for special extAttrs handling. - */ - for (var k in obj) - { - this[k] = obj[k]; - } - if (!("extAttrs" in this)) - { - this.extAttrs = []; - } - - this.isUnforgeable = this.has_extended_attribute("Unforgeable"); -} - -//@} -IdlInterfaceMember.prototype = Object.create(IdlObject.prototype); - -/// Internal helper functions /// -function create_suitable_object(type) -//@{ -{ - /** - * type is an object produced by the WebIDLParser.js "type" production. We - * return a JavaScript value that matches the type, if we can figure out - * how. - */ - if (type.nullable) - { - return null; - } - switch (type.idlType) - { - case "any": - case "boolean": - return true; - - case "byte": case "octet": case "short": case "unsigned short": - case "long": case "unsigned long": case "long long": - case "unsigned long long": case "float": case "double": - case "unrestricted float": case "unrestricted double": - return 7; - - case "DOMString": - case "ByteString": - case "USVString": - return "foo"; - - case "object": - return {a: "b"}; - - case "Node": - return document.createTextNode("abc"); - } - return null; -} -//@} - -/// IdlEnum /// -// Used for IdlArray.prototype.assert_type_is -function IdlEnum(obj) -//@{ -{ - /** - * obj is an object produced by the WebIDLParser.js "dictionary" - * production. - */ - - /** Self-explanatory. */ - this.name = obj.name; - - /** An array of values produced by the "enum" production. */ - this.values = obj.values; - -} -//@} - -IdlEnum.prototype = Object.create(IdlObject.prototype); - -/// IdlTypedef /// -// Used for IdlArray.prototype.assert_type_is -function IdlTypedef(obj) -//@{ -{ - /** - * obj is an object produced by the WebIDLParser.js "typedef" - * production. - */ - - /** Self-explanatory. */ - this.name = obj.name; - - /** An array of values produced by the "typedef" production. */ - this.values = obj.values; - -} -//@} - -IdlTypedef.prototype = Object.create(IdlObject.prototype); - -}()); -// vim: set expandtab shiftwidth=4 tabstop=4 foldmarker=@{,@} foldmethod=marker:
diff --git a/third_party/WebKit/LayoutTests/http/tests/w3c/resources/testharness.css b/third_party/WebKit/LayoutTests/http/tests/w3c/resources/testharness.css deleted file mode 100644 index e2ed5a04..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/w3c/resources/testharness.css +++ /dev/null
@@ -1,102 +0,0 @@ -html { - font-family:DejaVu Sans, Bitstream Vera Sans, Arial, Sans; -} - -#log .warning, -#log .warning a { - color: black; - background: yellow; -} - -#log .error, -#log .error a { - color: white; - background: red; -} - -section#summary { - margin-bottom:1em; -} - -table#results { - border-collapse:collapse; - table-layout:fixed; - width:100%; -} - -table#results th:first-child, -table#results td:first-child { - width:4em; -} - -table#results th:last-child, -table#results td:last-child { - width:50%; -} - -table#results.assertions th:last-child, -table#results.assertions td:last-child { - width:35%; -} - -table#results th { - padding:0; - padding-bottom:0.5em; - border-bottom:medium solid black; -} - -table#results td { - padding:1em; - padding-bottom:0.5em; - border-bottom:thin solid black; -} - -tr.pass > td:first-child { - color:green; -} - -tr.fail > td:first-child { - color:red; -} - -tr.timeout > td:first-child { - color:red; -} - -tr.notrun > td:first-child { - color:blue; -} - -.pass > td:first-child, .fail > td:first-child, .timeout > td:first-child, .notrun > td:first-child { - font-variant:small-caps; -} - -table#results span { - display:block; -} - -table#results span.expected { - font-family:DejaVu Sans Mono, Bitstream Vera Sans Mono, Monospace; - white-space:pre; -} - -table#results span.actual { - font-family:DejaVu Sans Mono, Bitstream Vera Sans Mono, Monospace; - white-space:pre; -} - -span.ok { - color:green; -} - -tr.error { - color:red; -} - -span.timeout { - color:red; -} - -span.ok, span.timeout, span.error { - font-variant:small-caps; -} \ No newline at end of file
diff --git a/third_party/WebKit/LayoutTests/http/tests/w3c/resources/testharness.js b/third_party/WebKit/LayoutTests/http/tests/w3c/resources/testharness.js deleted file mode 100644 index 7920ccd4..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/w3c/resources/testharness.js +++ /dev/null
@@ -1,2659 +0,0 @@ -/*global self*/ -/*jshint latedef: nofunc*/ -/* -Distributed under both the W3C Test Suite License [1] and the W3C -3-clause BSD License [2]. To contribute to a W3C Test Suite, see the -policies and contribution forms [3]. - -[1] http://www.w3.org/Consortium/Legal/2008/04-testsuite-license -[2] http://www.w3.org/Consortium/Legal/2008/03-bsd-license -[3] http://www.w3.org/2004/10/27-testcases -*/ - -/* Documentation is in docs/api.md */ - -(function () -{ - var debug = false; - // default timeout is 10 seconds, test can override if needed - var settings = { - output:true, - harness_timeout:{ - "normal":10000, - "long":60000 - }, - test_timeout:null, - message_events: ["start", "test_state", "result", "completion"] - }; - - var xhtml_ns = "http://www.w3.org/1999/xhtml"; - - /* - * TestEnvironment is an abstraction for the environment in which the test - * harness is used. Each implementation of a test environment has to provide - * the following interface: - * - * interface TestEnvironment { - * // Invoked after the global 'tests' object has been created and it's - * // safe to call add_*_callback() to register event handlers. - * void on_tests_ready(); - * - * // Invoked after setup() has been called to notify the test environment - * // of changes to the test harness properties. - * void on_new_harness_properties(object properties); - * - * // Should return a new unique default test name. - * DOMString next_default_test_name(); - * - * // Should return the test harness timeout duration in milliseconds. - * float test_timeout(); - * - * // Should return the global scope object. - * object global_scope(); - * }; - */ - - /* - * A test environment with a DOM. The global object is 'window'. By default - * test results are displayed in a table. Any parent windows receive - * callbacks or messages via postMessage() when test events occur. See - * apisample11.html and apisample12.html. - */ - function WindowTestEnvironment() { - this.name_counter = 0; - this.window_cache = null; - this.output_handler = null; - this.all_loaded = false; - var this_obj = this; - this.message_events = []; - - this.message_functions = { - start: [add_start_callback, remove_start_callback, - function (properties) { - this_obj._dispatch("start_callback", [properties], - {type: "start", properties: properties}); - }], - - test_state: [add_test_state_callback, remove_test_state_callback, - function(test) { - this_obj._dispatch("test_state_callback", [test], - {type: "test_state", - test: test.structured_clone()}); - }], - result: [add_result_callback, remove_result_callback, - function (test) { - this_obj.output_handler.show_status(); - this_obj._dispatch("result_callback", [test], - {type: "result", - test: test.structured_clone()}); - }], - completion: [add_completion_callback, remove_completion_callback, - function (tests, harness_status) { - var cloned_tests = map(tests, function(test) { - return test.structured_clone(); - }); - this_obj._dispatch("completion_callback", [tests, harness_status], - {type: "complete", - tests: cloned_tests, - status: harness_status.structured_clone()}); - }] - } - - on_event(window, 'load', function() { - this_obj.all_loaded = true; - }); - } - - WindowTestEnvironment.prototype._dispatch = function(selector, callback_args, message_arg) { - this._forEach_windows( - function(w, same_origin) { - if (same_origin) { - try { - var has_selector = selector in w; - } catch(e) { - // If document.domain was set at some point same_origin can be - // wrong and the above will fail. - has_selector = false; - } - if (has_selector) { - try { - w[selector].apply(undefined, callback_args); - } catch (e) { - if (debug) { - throw e; - } - } - } - } - if (supports_post_message(w) && w !== self) { - w.postMessage(message_arg, "*"); - } - }); - }; - - WindowTestEnvironment.prototype._forEach_windows = function(callback) { - // Iterate of the the windows [self ... top, opener]. The callback is passed - // two objects, the first one is the windows object itself, the second one - // is a boolean indicating whether or not its on the same origin as the - // current window. - var cache = this.window_cache; - if (!cache) { - cache = [[self, true]]; - var w = self; - var i = 0; - var so; - var origins = location.ancestorOrigins; - while (w != w.parent) { - w = w.parent; - // In WebKit, calls to parent windows' properties that aren't on the same - // origin cause an error message to be displayed in the error console but - // don't throw an exception. This is a deviation from the current HTML5 - // spec. See: https://bugs.webkit.org/show_bug.cgi?id=43504 - // The problem with WebKit's behavior is that it pollutes the error console - // with error messages that can't be caught. - // - // This issue can be mitigated by relying on the (for now) proprietary - // `location.ancestorOrigins` property which returns an ordered list of - // the origins of enclosing windows. See: - // http://trac.webkit.org/changeset/113945. - if (origins) { - so = (location.origin == origins[i]); - } else { - so = is_same_origin(w); - } - cache.push([w, so]); - i++; - } - w = window.opener; - if (w) { - // window.opener isn't included in the `location.ancestorOrigins` prop. - // We'll just have to deal with a simple check and an error msg on WebKit - // browsers in this case. - cache.push([w, is_same_origin(w)]); - } - this.window_cache = cache; - } - - forEach(cache, - function(a) { - callback.apply(null, a); - }); - }; - - WindowTestEnvironment.prototype.on_tests_ready = function() { - var output = new Output(); - this.output_handler = output; - - var this_obj = this; - - add_start_callback(function (properties) { - this_obj.output_handler.init(properties); - }); - - add_test_state_callback(function(test) { - this_obj.output_handler.show_status(); - }); - - add_result_callback(function (test) { - this_obj.output_handler.show_status(); - }); - - add_completion_callback(function (tests, harness_status) { - this_obj.output_handler.show_results(tests, harness_status); - }); - this.setup_messages(settings.message_events); - }; - - WindowTestEnvironment.prototype.setup_messages = function(new_events) { - var this_obj = this; - forEach(settings.message_events, function(x) { - var current_dispatch = this_obj.message_events.indexOf(x) !== -1; - var new_dispatch = new_events.indexOf(x) !== -1; - if (!current_dispatch && new_dispatch) { - this_obj.message_functions[x][0](this_obj.message_functions[x][2]); - } else if (current_dispatch && !new_dispatch) { - this_obj.message_functions[x][1](this_obj.message_functions[x][2]); - } - }); - this.message_events = new_events; - } - - WindowTestEnvironment.prototype.next_default_test_name = function() { - //Don't use document.title to work around an Opera bug in XHTML documents - var title = document.getElementsByTagName("title")[0]; - var prefix = (title && title.firstChild && title.firstChild.data) || "Untitled"; - var suffix = this.name_counter > 0 ? " " + this.name_counter : ""; - this.name_counter++; - return prefix + suffix; - }; - - WindowTestEnvironment.prototype.on_new_harness_properties = function(properties) { - this.output_handler.setup(properties); - if (properties.hasOwnProperty("message_events")) { - this.setup_messages(properties.message_events); - } - }; - - WindowTestEnvironment.prototype.add_on_loaded_callback = function(callback) { - on_event(window, 'load', callback); - }; - - WindowTestEnvironment.prototype.test_timeout = function() { - var metas = document.getElementsByTagName("meta"); - for (var i = 0; i < metas.length; i++) { - if (metas[i].name == "timeout") { - if (metas[i].content == "long") { - return settings.harness_timeout.long; - } - break; - } - } - return settings.harness_timeout.normal; - }; - - WindowTestEnvironment.prototype.global_scope = function() { - return window; - }; - - /* - * Base TestEnvironment implementation for a generic web worker. - * - * Workers accumulate test results. One or more clients can connect and - * retrieve results from a worker at any time. - * - * WorkerTestEnvironment supports communicating with a client via a - * MessagePort. The mechanism for determining the appropriate MessagePort - * for communicating with a client depends on the type of worker and is - * implemented by the various specializations of WorkerTestEnvironment - * below. - * - * A client document using testharness can use fetch_tests_from_worker() to - * retrieve results from a worker. See apisample16.html. - */ - function WorkerTestEnvironment() { - this.name_counter = 0; - this.all_loaded = true; - this.message_list = []; - this.message_ports = []; - } - - WorkerTestEnvironment.prototype._dispatch = function(message) { - this.message_list.push(message); - for (var i = 0; i < this.message_ports.length; ++i) - { - this.message_ports[i].postMessage(message); - } - }; - - // The only requirement is that port has a postMessage() method. It doesn't - // have to be an instance of a MessagePort, and often isn't. - WorkerTestEnvironment.prototype._add_message_port = function(port) { - this.message_ports.push(port); - for (var i = 0; i < this.message_list.length; ++i) - { - port.postMessage(this.message_list[i]); - } - }; - - WorkerTestEnvironment.prototype.next_default_test_name = function() { - var suffix = this.name_counter > 0 ? " " + this.name_counter : ""; - this.name_counter++; - return "Untitled" + suffix; - }; - - WorkerTestEnvironment.prototype.on_new_harness_properties = function() {}; - - WorkerTestEnvironment.prototype.on_tests_ready = function() { - var this_obj = this; - add_start_callback( - function(properties) { - this_obj._dispatch({ - type: "start", - properties: properties, - }); - }); - add_test_state_callback( - function(test) { - this_obj._dispatch({ - type: "test_state", - test: test.structured_clone() - }); - }); - add_result_callback( - function(test) { - this_obj._dispatch({ - type: "result", - test: test.structured_clone() - }); - }); - add_completion_callback( - function(tests, harness_status) { - this_obj._dispatch({ - type: "complete", - tests: map(tests, - function(test) { - return test.structured_clone(); - }), - status: harness_status.structured_clone() - }); - }); - }; - - WorkerTestEnvironment.prototype.add_on_loaded_callback = function() {}; - - WorkerTestEnvironment.prototype.test_timeout = function() { - // Tests running in a worker don't have a default timeout. I.e. all - // worker tests behave as if settings.explicit_timeout is true. - return null; - }; - - WorkerTestEnvironment.prototype.global_scope = function() { - return self; - }; - - /* - * Dedicated web workers. - * https://html.spec.whatwg.org/multipage/workers.html#dedicatedworkerglobalscope - * - * This class is used as the test_environment when testharness is running - * inside a dedicated worker. - */ - function DedicatedWorkerTestEnvironment() { - WorkerTestEnvironment.call(this); - // self is an instance of DedicatedWorkerGlobalScope which exposes - // a postMessage() method for communicating via the message channel - // established when the worker is created. - this._add_message_port(self); - } - DedicatedWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype); - - DedicatedWorkerTestEnvironment.prototype.on_tests_ready = function() { - WorkerTestEnvironment.prototype.on_tests_ready.call(this); - // In the absence of an onload notification, we a require dedicated - // workers to explicitly signal when the tests are done. - tests.wait_for_finish = true; - }; - - /* - * Shared web workers. - * https://html.spec.whatwg.org/multipage/workers.html#sharedworkerglobalscope - * - * This class is used as the test_environment when testharness is running - * inside a shared web worker. - */ - function SharedWorkerTestEnvironment() { - WorkerTestEnvironment.call(this); - var this_obj = this; - // Shared workers receive message ports via the 'onconnect' event for - // each connection. - self.addEventListener("connect", - function(message_event) { - this_obj._add_message_port(message_event.source); - }); - } - SharedWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype); - - SharedWorkerTestEnvironment.prototype.on_tests_ready = function() { - WorkerTestEnvironment.prototype.on_tests_ready.call(this); - // In the absence of an onload notification, we a require shared - // workers to explicitly signal when the tests are done. - tests.wait_for_finish = true; - }; - - /* - * Service workers. - * http://www.w3.org/TR/service-workers/ - * - * This class is used as the test_environment when testharness is running - * inside a service worker. - */ - function ServiceWorkerTestEnvironment() { - WorkerTestEnvironment.call(this); - this.all_loaded = false; - this.on_loaded_callback = null; - var this_obj = this; - self.addEventListener("message", - function(event) { - if (event.data.type && event.data.type === "connect") { - if (event.ports && event.ports[0]) { - // If a MessageChannel was passed, then use it to - // send results back to the main window. This - // allows the tests to work even if the browser - // does not fully support MessageEvent.source in - // ServiceWorkers yet. - this_obj._add_message_port(event.ports[0]); - event.ports[0].start(); - } else { - // If there is no MessageChannel, then attempt to - // use the MessageEvent.source to send results - // back to the main window. - this_obj._add_message_port(event.source); - } - } - }); - - // The oninstall event is received after the service worker script and - // all imported scripts have been fetched and executed. It's the - // equivalent of an onload event for a document. All tests should have - // been added by the time this event is received, thus it's not - // necessary to wait until the onactivate event. - on_event(self, "install", - function(event) { - this_obj.all_loaded = true; - if (this_obj.on_loaded_callback) { - this_obj.on_loaded_callback(); - } - }); - } - ServiceWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype); - - ServiceWorkerTestEnvironment.prototype.add_on_loaded_callback = function(callback) { - if (this.all_loaded) { - callback(); - } else { - this.on_loaded_callback = callback; - } - }; - - function create_test_environment() { - if ('document' in self) { - return new WindowTestEnvironment(); - } - if ('DedicatedWorkerGlobalScope' in self && - self instanceof DedicatedWorkerGlobalScope) { - return new DedicatedWorkerTestEnvironment(); - } - if ('SharedWorkerGlobalScope' in self && - self instanceof SharedWorkerGlobalScope) { - return new SharedWorkerTestEnvironment(); - } - if ('ServiceWorkerGlobalScope' in self && - self instanceof ServiceWorkerGlobalScope) { - return new ServiceWorkerTestEnvironment(); - } - throw new Error("Unsupported test environment"); - } - - var test_environment = create_test_environment(); - - function is_shared_worker(worker) { - return 'SharedWorker' in self && worker instanceof SharedWorker; - } - - function is_service_worker(worker) { - return 'ServiceWorker' in self && worker instanceof ServiceWorker; - } - - /* - * API functions - */ - - function test(func, name, properties) - { - var test_name = name ? name : test_environment.next_default_test_name(); - properties = properties ? properties : {}; - var test_obj = new Test(test_name, properties); - test_obj.step(func, test_obj, test_obj); - if (test_obj.phase === test_obj.phases.STARTED) { - test_obj.done(); - } - } - - function async_test(func, name, properties) - { - if (typeof func !== "function") { - properties = name; - name = func; - func = null; - } - var test_name = name ? name : test_environment.next_default_test_name(); - properties = properties ? properties : {}; - var test_obj = new Test(test_name, properties); - if (func) { - test_obj.step(func, test_obj, test_obj); - } - return test_obj; - } - - function promise_test(func, name, properties) { - var test = async_test(name, properties); - // If there is no promise tests queue make one. - test.step(function() { - if (!tests.promise_tests) { - tests.promise_tests = Promise.resolve(); - } - }); - tests.promise_tests = tests.promise_tests.then(function() { - return Promise.resolve(test.step(func, test, test)) - .then( - function() { - test.done(); - }) - .catch(test.step_func( - function(value) { - if (value instanceof AssertionError) { - throw value; - } - assert(false, "promise_test", null, - "Unhandled rejection with value: ${value}", {value:value}); - })); - }); - } - - function promise_rejects(test, expected, promise) { - return promise.then(test.unreached_func("Should have rejected.")).catch(function(e) { - assert_throws(expected, function() { throw e }); - }); - } - - /** - * This constructor helper allows DOM events to be handled using Promises, - * which can make it a lot easier to test a very specific series of events, - * including ensuring that unexpected events are not fired at any point. - */ - function EventWatcher(test, watchedNode, eventTypes) - { - if (typeof eventTypes == 'string') { - eventTypes = [eventTypes]; - } - - var waitingFor = null; - - var eventHandler = test.step_func(function(evt) { - assert_true(!!waitingFor, - 'Not expecting event, but got ' + evt.type + ' event'); - assert_equals(evt.type, waitingFor.types[0], - 'Expected ' + waitingFor.types[0] + ' event, but got ' + - evt.type + ' event instead'); - if (waitingFor.types.length > 1) { - // Pop first event from array - waitingFor.types.shift(); - return; - } - // We need to null out waitingFor before calling the resolve function - // since the Promise's resolve handlers may call wait_for() which will - // need to set waitingFor. - var resolveFunc = waitingFor.resolve; - waitingFor = null; - resolveFunc(evt); - }); - - for (var i = 0; i < eventTypes.length; i++) { - watchedNode.addEventListener(eventTypes[i], eventHandler); - } - - /** - * Returns a Promise that will resolve after the specified event or - * series of events has occured. - */ - this.wait_for = function(types) { - if (waitingFor) { - return Promise.reject('Already waiting for an event or events'); - } - if (typeof types == 'string') { - types = [types]; - } - return new Promise(function(resolve, reject) { - waitingFor = { - types: types, - resolve: resolve, - reject: reject - }; - }); - }; - - function stop_watching() { - for (var i = 0; i < eventTypes.length; i++) { - watchedNode.removeEventListener(eventTypes[i], eventHandler); - } - }; - - test.add_cleanup(stop_watching); - - return this; - } - expose(EventWatcher, 'EventWatcher'); - - function setup(func_or_properties, maybe_properties) - { - var func = null; - var properties = {}; - if (arguments.length === 2) { - func = func_or_properties; - properties = maybe_properties; - } else if (func_or_properties instanceof Function) { - func = func_or_properties; - } else { - properties = func_or_properties; - } - tests.setup(func, properties); - test_environment.on_new_harness_properties(properties); - } - - function done() { - if (tests.tests.length === 0) { - tests.set_file_is_test(); - } - if (tests.file_is_test) { - tests.tests[0].done(); - } - tests.end_wait(); - } - - function generate_tests(func, args, properties) { - forEach(args, function(x, i) - { - var name = x[0]; - test(function() - { - func.apply(this, x.slice(1)); - }, - name, - Array.isArray(properties) ? properties[i] : properties); - }); - } - - function on_event(object, event, callback) - { - object.addEventListener(event, callback, false); - } - - function step_timeout(f, t) { - var outer_this = this; - var args = Array.prototype.slice.call(arguments, 2); - return setTimeout(function() { - f.apply(outer_this, args); - }, t * tests.timeout_multiplier); - } - - expose(test, 'test'); - expose(async_test, 'async_test'); - expose(promise_test, 'promise_test'); - expose(promise_rejects, 'promise_rejects'); - expose(generate_tests, 'generate_tests'); - expose(setup, 'setup'); - expose(done, 'done'); - expose(on_event, 'on_event'); - expose(step_timeout, 'step_timeout'); - - /* - * Return a string truncated to the given length, with ... added at the end - * if it was longer. - */ - function truncate(s, len) - { - if (s.length > len) { - return s.substring(0, len - 3) + "..."; - } - return s; - } - - /* - * Return true if object is probably a Node object. - */ - function is_node(object) - { - // I use duck-typing instead of instanceof, because - // instanceof doesn't work if the node is from another window (like an - // iframe's contentWindow): - // http://www.w3.org/Bugs/Public/show_bug.cgi?id=12295 - if ("nodeType" in object && - "nodeName" in object && - "nodeValue" in object && - "childNodes" in object) { - try { - object.nodeType; - } catch (e) { - // The object is probably Node.prototype or another prototype - // object that inherits from it, and not a Node instance. - return false; - } - return true; - } - return false; - } - - /* - * Convert a value to a nice, human-readable string - */ - function format_value(val, seen) - { - if (!seen) { - seen = []; - } - if (typeof val === "object" && val !== null) { - if (seen.indexOf(val) >= 0) { - return "[...]"; - } - seen.push(val); - } - if (Array.isArray(val)) { - return "[" + val.map(function(x) {return format_value(x, seen);}).join(", ") + "]"; - } - - switch (typeof val) { - case "string": - val = val.replace("\\", "\\\\"); - for (var i = 0; i < 32; i++) { - var replace = "\\"; - switch (i) { - case 0: replace += "0"; break; - case 1: replace += "x01"; break; - case 2: replace += "x02"; break; - case 3: replace += "x03"; break; - case 4: replace += "x04"; break; - case 5: replace += "x05"; break; - case 6: replace += "x06"; break; - case 7: replace += "x07"; break; - case 8: replace += "b"; break; - case 9: replace += "t"; break; - case 10: replace += "n"; break; - case 11: replace += "v"; break; - case 12: replace += "f"; break; - case 13: replace += "r"; break; - case 14: replace += "x0e"; break; - case 15: replace += "x0f"; break; - case 16: replace += "x10"; break; - case 17: replace += "x11"; break; - case 18: replace += "x12"; break; - case 19: replace += "x13"; break; - case 20: replace += "x14"; break; - case 21: replace += "x15"; break; - case 22: replace += "x16"; break; - case 23: replace += "x17"; break; - case 24: replace += "x18"; break; - case 25: replace += "x19"; break; - case 26: replace += "x1a"; break; - case 27: replace += "x1b"; break; - case 28: replace += "x1c"; break; - case 29: replace += "x1d"; break; - case 30: replace += "x1e"; break; - case 31: replace += "x1f"; break; - } - val = val.replace(RegExp(String.fromCharCode(i), "g"), replace); - } - return '"' + val.replace(/"/g, '\\"') + '"'; - case "boolean": - case "undefined": - return String(val); - case "number": - // In JavaScript, -0 === 0 and String(-0) == "0", so we have to - // special-case. - if (val === -0 && 1/val === -Infinity) { - return "-0"; - } - return String(val); - case "object": - if (val === null) { - return "null"; - } - - // Special-case Node objects, since those come up a lot in my tests. I - // ignore namespaces. - if (is_node(val)) { - switch (val.nodeType) { - case Node.ELEMENT_NODE: - var ret = "<" + val.localName; - for (var i = 0; i < val.attributes.length; i++) { - ret += " " + val.attributes[i].name + '="' + val.attributes[i].value + '"'; - } - ret += ">" + val.innerHTML + "</" + val.localName + ">"; - return "Element node " + truncate(ret, 60); - case Node.TEXT_NODE: - return 'Text node "' + truncate(val.data, 60) + '"'; - case Node.PROCESSING_INSTRUCTION_NODE: - return "ProcessingInstruction node with target " + format_value(truncate(val.target, 60)) + " and data " + format_value(truncate(val.data, 60)); - case Node.COMMENT_NODE: - return "Comment node <!--" + truncate(val.data, 60) + "-->"; - case Node.DOCUMENT_NODE: - return "Document node with " + val.childNodes.length + (val.childNodes.length == 1 ? " child" : " children"); - case Node.DOCUMENT_TYPE_NODE: - return "DocumentType node"; - case Node.DOCUMENT_FRAGMENT_NODE: - return "DocumentFragment node with " + val.childNodes.length + (val.childNodes.length == 1 ? " child" : " children"); - default: - return "Node object of unknown type"; - } - } - - /* falls through */ - default: - return typeof val + ' "' + truncate(String(val), 60) + '"'; - } - } - expose(format_value, "format_value"); - - /* - * Assertions - */ - - function assert_true(actual, description) - { - assert(actual === true, "assert_true", description, - "expected true got ${actual}", {actual:actual}); - } - expose(assert_true, "assert_true"); - - function assert_false(actual, description) - { - assert(actual === false, "assert_false", description, - "expected false got ${actual}", {actual:actual}); - } - expose(assert_false, "assert_false"); - - function same_value(x, y) { - if (y !== y) { - //NaN case - return x !== x; - } - if (x === 0 && y === 0) { - //Distinguish +0 and -0 - return 1/x === 1/y; - } - return x === y; - } - - function assert_equals(actual, expected, description) - { - /* - * Test if two primitives are equal or two objects - * are the same object - */ - if (typeof actual != typeof expected) { - assert(false, "assert_equals", description, - "expected (" + typeof expected + ") ${expected} but got (" + typeof actual + ") ${actual}", - {expected:expected, actual:actual}); - return; - } - assert(same_value(actual, expected), "assert_equals", description, - "expected ${expected} but got ${actual}", - {expected:expected, actual:actual}); - } - expose(assert_equals, "assert_equals"); - - function assert_not_equals(actual, expected, description) - { - /* - * Test if two primitives are unequal or two objects - * are different objects - */ - assert(!same_value(actual, expected), "assert_not_equals", description, - "got disallowed value ${actual}", - {actual:actual}); - } - expose(assert_not_equals, "assert_not_equals"); - - function assert_in_array(actual, expected, description) - { - assert(expected.indexOf(actual) != -1, "assert_in_array", description, - "value ${actual} not in array ${expected}", - {actual:actual, expected:expected}); - } - expose(assert_in_array, "assert_in_array"); - - function assert_object_equals(actual, expected, description) - { - //This needs to be improved a great deal - function check_equal(actual, expected, stack) - { - stack.push(actual); - - var p; - for (p in actual) { - assert(expected.hasOwnProperty(p), "assert_object_equals", description, - "unexpected property ${p}", {p:p}); - - if (typeof actual[p] === "object" && actual[p] !== null) { - if (stack.indexOf(actual[p]) === -1) { - check_equal(actual[p], expected[p], stack); - } - } else { - assert(same_value(actual[p], expected[p]), "assert_object_equals", description, - "property ${p} expected ${expected} got ${actual}", - {p:p, expected:expected, actual:actual}); - } - } - for (p in expected) { - assert(actual.hasOwnProperty(p), - "assert_object_equals", description, - "expected property ${p} missing", {p:p}); - } - stack.pop(); - } - check_equal(actual, expected, []); - } - expose(assert_object_equals, "assert_object_equals"); - - function assert_array_equals(actual, expected, description) - { - assert(actual.length === expected.length, - "assert_array_equals", description, - "lengths differ, expected ${expected} got ${actual}", - {expected:expected.length, actual:actual.length}); - - for (var i = 0; i < actual.length; i++) { - assert(actual.hasOwnProperty(i) === expected.hasOwnProperty(i), - "assert_array_equals", description, - "property ${i}, property expected to be ${expected} but was ${actual}", - {i:i, expected:expected.hasOwnProperty(i) ? "present" : "missing", - actual:actual.hasOwnProperty(i) ? "present" : "missing"}); - assert(same_value(expected[i], actual[i]), - "assert_array_equals", description, - "property ${i}, expected ${expected} but got ${actual}", - {i:i, expected:expected[i], actual:actual[i]}); - } - } - expose(assert_array_equals, "assert_array_equals"); - - function assert_approx_equals(actual, expected, epsilon, description) - { - /* - * Test if two primitive numbers are equal withing +/- epsilon - */ - assert(typeof actual === "number", - "assert_approx_equals", description, - "expected a number but got a ${type_actual}", - {type_actual:typeof actual}); - - assert(Math.abs(actual - expected) <= epsilon, - "assert_approx_equals", description, - "expected ${expected} +/- ${epsilon} but got ${actual}", - {expected:expected, actual:actual, epsilon:epsilon}); - } - expose(assert_approx_equals, "assert_approx_equals"); - - function assert_less_than(actual, expected, description) - { - /* - * Test if a primitive number is less than another - */ - assert(typeof actual === "number", - "assert_less_than", description, - "expected a number but got a ${type_actual}", - {type_actual:typeof actual}); - - assert(actual < expected, - "assert_less_than", description, - "expected a number less than ${expected} but got ${actual}", - {expected:expected, actual:actual}); - } - expose(assert_less_than, "assert_less_than"); - - function assert_greater_than(actual, expected, description) - { - /* - * Test if a primitive number is greater than another - */ - assert(typeof actual === "number", - "assert_greater_than", description, - "expected a number but got a ${type_actual}", - {type_actual:typeof actual}); - - assert(actual > expected, - "assert_greater_than", description, - "expected a number greater than ${expected} but got ${actual}", - {expected:expected, actual:actual}); - } - expose(assert_greater_than, "assert_greater_than"); - - function assert_between_exclusive(actual, lower, upper, description) - { - /* - * Test if a primitive number is between two others - */ - assert(typeof actual === "number", - "assert_between_exclusive", description, - "expected a number but got a ${type_actual}", - {type_actual:typeof actual}); - - assert(actual > lower && actual < upper, - "assert_between_exclusive", description, - "expected a number greater than ${lower} " + - "and less than ${upper} but got ${actual}", - {lower:lower, upper:upper, actual:actual}); - } - expose(assert_between_exclusive, "assert_between_exclusive"); - - function assert_less_than_equal(actual, expected, description) - { - /* - * Test if a primitive number is less than or equal to another - */ - assert(typeof actual === "number", - "assert_less_than_equal", description, - "expected a number but got a ${type_actual}", - {type_actual:typeof actual}); - - assert(actual <= expected, - "assert_less_than_equal", description, - "expected a number less than or equal to ${expected} but got ${actual}", - {expected:expected, actual:actual}); - } - expose(assert_less_than_equal, "assert_less_than_equal"); - - function assert_greater_than_equal(actual, expected, description) - { - /* - * Test if a primitive number is greater than or equal to another - */ - assert(typeof actual === "number", - "assert_greater_than_equal", description, - "expected a number but got a ${type_actual}", - {type_actual:typeof actual}); - - assert(actual >= expected, - "assert_greater_than_equal", description, - "expected a number greater than or equal to ${expected} but got ${actual}", - {expected:expected, actual:actual}); - } - expose(assert_greater_than_equal, "assert_greater_than_equal"); - - function assert_between_inclusive(actual, lower, upper, description) - { - /* - * Test if a primitive number is between to two others or equal to either of them - */ - assert(typeof actual === "number", - "assert_between_inclusive", description, - "expected a number but got a ${type_actual}", - {type_actual:typeof actual}); - - assert(actual >= lower && actual <= upper, - "assert_between_inclusive", description, - "expected a number greater than or equal to ${lower} " + - "and less than or equal to ${upper} but got ${actual}", - {lower:lower, upper:upper, actual:actual}); - } - expose(assert_between_inclusive, "assert_between_inclusive"); - - function assert_regexp_match(actual, expected, description) { - /* - * Test if a string (actual) matches a regexp (expected) - */ - assert(expected.test(actual), - "assert_regexp_match", description, - "expected ${expected} but got ${actual}", - {expected:expected, actual:actual}); - } - expose(assert_regexp_match, "assert_regexp_match"); - - function assert_class_string(object, class_string, description) { - assert_equals({}.toString.call(object), "[object " + class_string + "]", - description); - } - expose(assert_class_string, "assert_class_string"); - - - function _assert_own_property(name) { - return function(object, property_name, description) - { - assert(object.hasOwnProperty(property_name), - name, description, - "expected property ${p} missing", {p:property_name}); - }; - } - expose(_assert_own_property("assert_exists"), "assert_exists"); - expose(_assert_own_property("assert_own_property"), "assert_own_property"); - - function assert_not_exists(object, property_name, description) - { - assert(!object.hasOwnProperty(property_name), - "assert_not_exists", description, - "unexpected property ${p} found", {p:property_name}); - } - expose(assert_not_exists, "assert_not_exists"); - - function _assert_inherits(name) { - return function (object, property_name, description) - { - assert(typeof object === "object" || typeof object === "function", - name, description, - "provided value is not an object"); - - assert("hasOwnProperty" in object, - name, description, - "provided value is an object but has no hasOwnProperty method"); - - assert(!object.hasOwnProperty(property_name), - name, description, - "property ${p} found on object expected in prototype chain", - {p:property_name}); - - assert(property_name in object, - name, description, - "property ${p} not found in prototype chain", - {p:property_name}); - }; - } - expose(_assert_inherits("assert_inherits"), "assert_inherits"); - expose(_assert_inherits("assert_idl_attribute"), "assert_idl_attribute"); - - function assert_readonly(object, property_name, description) - { - var initial_value = object[property_name]; - try { - //Note that this can have side effects in the case where - //the property has PutForwards - object[property_name] = initial_value + "a"; //XXX use some other value here? - assert(same_value(object[property_name], initial_value), - "assert_readonly", description, - "changing property ${p} succeeded", - {p:property_name}); - } finally { - object[property_name] = initial_value; - } - } - expose(assert_readonly, "assert_readonly"); - - function assert_throws(code, func, description) - { - try { - func.call(this); - assert(false, "assert_throws", description, - "${func} did not throw", {func:func}); - } catch (e) { - if (e instanceof AssertionError) { - throw e; - } - if (code === null) { - return; - } - if (typeof code === "object") { - assert(typeof e == "object" && "name" in e && e.name == code.name, - "assert_throws", description, - "${func} threw ${actual} (${actual_name}) expected ${expected} (${expected_name})", - {func:func, actual:e, actual_name:e.name, - expected:code, - expected_name:code.name}); - return; - } - - var code_name_map = { - INDEX_SIZE_ERR: 'IndexSizeError', - HIERARCHY_REQUEST_ERR: 'HierarchyRequestError', - WRONG_DOCUMENT_ERR: 'WrongDocumentError', - INVALID_CHARACTER_ERR: 'InvalidCharacterError', - NO_MODIFICATION_ALLOWED_ERR: 'NoModificationAllowedError', - NOT_FOUND_ERR: 'NotFoundError', - NOT_SUPPORTED_ERR: 'NotSupportedError', - INUSE_ATTRIBUTE_ERR: 'InUseAttributeError', - INVALID_STATE_ERR: 'InvalidStateError', - SYNTAX_ERR: 'SyntaxError', - INVALID_MODIFICATION_ERR: 'InvalidModificationError', - NAMESPACE_ERR: 'NamespaceError', - INVALID_ACCESS_ERR: 'InvalidAccessError', - TYPE_MISMATCH_ERR: 'TypeMismatchError', - SECURITY_ERR: 'SecurityError', - NETWORK_ERR: 'NetworkError', - ABORT_ERR: 'AbortError', - URL_MISMATCH_ERR: 'URLMismatchError', - QUOTA_EXCEEDED_ERR: 'QuotaExceededError', - TIMEOUT_ERR: 'TimeoutError', - INVALID_NODE_TYPE_ERR: 'InvalidNodeTypeError', - DATA_CLONE_ERR: 'DataCloneError' - }; - - var name = code in code_name_map ? code_name_map[code] : code; - - var name_code_map = { - IndexSizeError: 1, - HierarchyRequestError: 3, - WrongDocumentError: 4, - InvalidCharacterError: 5, - NoModificationAllowedError: 7, - NotFoundError: 8, - NotSupportedError: 9, - InUseAttributeError: 10, - InvalidStateError: 11, - SyntaxError: 12, - InvalidModificationError: 13, - NamespaceError: 14, - InvalidAccessError: 15, - TypeMismatchError: 17, - SecurityError: 18, - NetworkError: 19, - AbortError: 20, - URLMismatchError: 21, - QuotaExceededError: 22, - TimeoutError: 23, - InvalidNodeTypeError: 24, - DataCloneError: 25, - - EncodingError: 0, - NotReadableError: 0, - UnknownError: 0, - ConstraintError: 0, - DataError: 0, - TransactionInactiveError: 0, - ReadOnlyError: 0, - VersionError: 0, - OperationError: 0, - }; - - if (!(name in name_code_map)) { - throw new AssertionError('Test bug: unrecognized DOMException code "' + code + '" passed to assert_throws()'); - } - - var required_props = { code: name_code_map[name] }; - - if (required_props.code === 0 || - (typeof e == "object" && - "name" in e && - e.name !== e.name.toUpperCase() && - e.name !== "DOMException")) { - // New style exception: also test the name property. - required_props.name = name; - } - - //We'd like to test that e instanceof the appropriate interface, - //but we can't, because we don't know what window it was created - //in. It might be an instanceof the appropriate interface on some - //unknown other window. TODO: Work around this somehow? - - assert(typeof e == "object", - "assert_throws", description, - "${func} threw ${e} with type ${type}, not an object", - {func:func, e:e, type:typeof e}); - - for (var prop in required_props) { - assert(typeof e == "object" && prop in e && e[prop] == required_props[prop], - "assert_throws", description, - "${func} threw ${e} that is not a DOMException " + code + ": property ${prop} is equal to ${actual}, expected ${expected}", - {func:func, e:e, prop:prop, actual:e[prop], expected:required_props[prop]}); - } - } - } - expose(assert_throws, "assert_throws"); - - function assert_unreached(description) { - assert(false, "assert_unreached", description, - "Reached unreachable code"); - } - expose(assert_unreached, "assert_unreached"); - - function assert_any(assert_func, actual, expected_array) - { - var args = [].slice.call(arguments, 3); - var errors = []; - var passed = false; - forEach(expected_array, - function(expected) - { - try { - assert_func.apply(this, [actual, expected].concat(args)); - passed = true; - } catch (e) { - errors.push(e.message); - } - }); - if (!passed) { - throw new AssertionError(errors.join("\n\n")); - } - } - expose(assert_any, "assert_any"); - - function Test(name, properties) - { - if (tests.file_is_test && tests.tests.length) { - throw new Error("Tried to create a test with file_is_test"); - } - this.name = name; - - this.phase = this.phases.INITIAL; - - this.status = this.NOTRUN; - this.timeout_id = null; - this.index = null; - - this.properties = properties; - var timeout = properties.timeout ? properties.timeout : settings.test_timeout; - if (timeout !== null) { - this.timeout_length = timeout * tests.timeout_multiplier; - } else { - this.timeout_length = null; - } - - this.message = null; - this.stack = null; - - this.steps = []; - - this.cleanup_callbacks = []; - - tests.push(this); - } - - Test.statuses = { - PASS:0, - FAIL:1, - TIMEOUT:2, - NOTRUN:3 - }; - - Test.prototype = merge({}, Test.statuses); - - Test.prototype.phases = { - INITIAL:0, - STARTED:1, - HAS_RESULT:2, - COMPLETE:3 - }; - - Test.prototype.structured_clone = function() - { - if (!this._structured_clone) { - var msg = this.message; - msg = msg ? String(msg) : msg; - this._structured_clone = merge({ - name:String(this.name), - properties:merge({}, this.properties), - }, Test.statuses); - } - this._structured_clone.status = this.status; - this._structured_clone.message = this.message; - this._structured_clone.stack = this.stack; - this._structured_clone.index = this.index; - return this._structured_clone; - }; - - Test.prototype.step = function(func, this_obj) - { - if (this.phase > this.phases.STARTED) { - return; - } - this.phase = this.phases.STARTED; - //If we don't get a result before the harness times out that will be a test timout - this.set_status(this.TIMEOUT, "Test timed out"); - - tests.started = true; - tests.notify_test_state(this); - - if (this.timeout_id === null) { - this.set_timeout(); - } - - this.steps.push(func); - - if (arguments.length === 1) { - this_obj = this; - } - - try { - return func.apply(this_obj, Array.prototype.slice.call(arguments, 2)); - } catch (e) { - if (this.phase >= this.phases.HAS_RESULT) { - return; - } - var message = String((typeof e === "object" && e !== null) ? e.message : e); - var stack = e.stack ? e.stack : null; - - this.set_status(this.FAIL, message, stack); - this.phase = this.phases.HAS_RESULT; - this.done(); - } - }; - - Test.prototype.step_func = function(func, this_obj) - { - var test_this = this; - - if (arguments.length === 1) { - this_obj = test_this; - } - - return function() - { - return test_this.step.apply(test_this, [func, this_obj].concat( - Array.prototype.slice.call(arguments))); - }; - }; - - Test.prototype.step_func_done = function(func, this_obj) - { - var test_this = this; - - if (arguments.length === 1) { - this_obj = test_this; - } - - return function() - { - if (func) { - test_this.step.apply(test_this, [func, this_obj].concat( - Array.prototype.slice.call(arguments))); - } - test_this.done(); - }; - }; - - Test.prototype.unreached_func = function(description) - { - return this.step_func(function() { - assert_unreached(description); - }); - }; - - Test.prototype.step_timeout = function(f, timeout) { - var test_this = this; - var args = Array.prototype.slice.call(arguments, 2); - return setTimeout(this.step_func(function() { - return f.apply(test_this, args); - }, timeout * tests.timeout_multiplier)); - } - - Test.prototype.add_cleanup = function(callback) { - this.cleanup_callbacks.push(callback); - }; - - Test.prototype.force_timeout = function() { - this.set_status(this.TIMEOUT); - this.phase = this.phases.HAS_RESULT; - }; - - Test.prototype.set_timeout = function() - { - if (this.timeout_length !== null) { - var this_obj = this; - this.timeout_id = setTimeout(function() - { - this_obj.timeout(); - }, this.timeout_length); - } - }; - - Test.prototype.set_status = function(status, message, stack) - { - this.status = status; - this.message = message; - this.stack = stack ? stack : null; - }; - - Test.prototype.timeout = function() - { - this.timeout_id = null; - this.set_status(this.TIMEOUT, "Test timed out"); - this.phase = this.phases.HAS_RESULT; - this.done(); - }; - - Test.prototype.done = function() - { - if (this.phase == this.phases.COMPLETE) { - return; - } - - if (this.phase <= this.phases.STARTED) { - this.set_status(this.PASS, null); - } - - this.phase = this.phases.COMPLETE; - - clearTimeout(this.timeout_id); - tests.result(this); - this.cleanup(); - }; - - Test.prototype.cleanup = function() { - forEach(this.cleanup_callbacks, - function(cleanup_callback) { - cleanup_callback(); - }); - }; - - /* - * A RemoteTest object mirrors a Test object on a remote worker. The - * associated RemoteWorker updates the RemoteTest object in response to - * received events. In turn, the RemoteTest object replicates these events - * on the local document. This allows listeners (test result reporting - * etc..) to transparently handle local and remote events. - */ - function RemoteTest(clone) { - var this_obj = this; - Object.keys(clone).forEach( - function(key) { - this_obj[key] = clone[key]; - }); - this.index = null; - this.phase = this.phases.INITIAL; - this.update_state_from(clone); - tests.push(this); - } - - RemoteTest.prototype.structured_clone = function() { - var clone = {}; - Object.keys(this).forEach( - (function(key) { - if (typeof(this[key]) === "object") { - clone[key] = merge({}, this[key]); - } else { - clone[key] = this[key]; - } - }).bind(this)); - clone.phases = merge({}, this.phases); - return clone; - }; - - RemoteTest.prototype.cleanup = function() {}; - RemoteTest.prototype.phases = Test.prototype.phases; - RemoteTest.prototype.update_state_from = function(clone) { - this.status = clone.status; - this.message = clone.message; - this.stack = clone.stack; - if (this.phase === this.phases.INITIAL) { - this.phase = this.phases.STARTED; - } - }; - RemoteTest.prototype.done = function() { - this.phase = this.phases.COMPLETE; - } - - /* - * A RemoteWorker listens for test events from a worker. These events are - * then used to construct and maintain RemoteTest objects that mirror the - * tests running on the remote worker. - */ - function RemoteWorker(worker) { - this.running = true; - this.tests = new Array(); - - var this_obj = this; - worker.onerror = function(error) { this_obj.worker_error(error); }; - - var message_port; - - if (is_service_worker(worker)) { - if (window.MessageChannel) { - // The ServiceWorker's implicit MessagePort is currently not - // reliably accessible from the ServiceWorkerGlobalScope due to - // Blink setting MessageEvent.source to null for messages sent - // via ServiceWorker.postMessage(). Until that's resolved, - // create an explicit MessageChannel and pass one end to the - // worker. - var message_channel = new MessageChannel(); - message_port = message_channel.port1; - message_port.start(); - worker.postMessage({type: "connect"}, [message_channel.port2]); - } else { - // If MessageChannel is not available, then try the - // ServiceWorker.postMessage() approach using MessageEvent.source - // on the other end. - message_port = navigator.serviceWorker; - worker.postMessage({type: "connect"}); - } - } else if (is_shared_worker(worker)) { - message_port = worker.port; - } else { - message_port = worker; - } - - // Keeping a reference to the worker until worker_done() is seen - // prevents the Worker object and its MessageChannel from going away - // before all the messages are dispatched. - this.worker = worker; - - message_port.onmessage = - function(message) { - if (this_obj.running && (message.data.type in this_obj.message_handlers)) { - this_obj.message_handlers[message.data.type].call(this_obj, message.data); - } - }; - } - - RemoteWorker.prototype.worker_error = function(error) { - var message = error.message || String(error); - var filename = (error.filename ? " " + error.filename: ""); - // FIXME: Display worker error states separately from main document - // error state. - this.worker_done({ - status: { - status: tests.status.ERROR, - message: "Error in worker" + filename + ": " + message, - stack: error.stack - } - }); - error.preventDefault(); - }; - - RemoteWorker.prototype.test_state = function(data) { - var remote_test = this.tests[data.test.index]; - if (!remote_test) { - remote_test = new RemoteTest(data.test); - this.tests[data.test.index] = remote_test; - } - remote_test.update_state_from(data.test); - tests.notify_test_state(remote_test); - }; - - RemoteWorker.prototype.test_done = function(data) { - var remote_test = this.tests[data.test.index]; - remote_test.update_state_from(data.test); - remote_test.done(); - tests.result(remote_test); - }; - - RemoteWorker.prototype.worker_done = function(data) { - if (tests.status.status === null && - data.status.status !== data.status.OK) { - tests.status.status = data.status.status; - tests.status.message = data.status.message; - tests.status.stack = data.status.stack; - } - this.running = false; - this.worker = null; - if (tests.all_done()) { - tests.complete(); - } - }; - - RemoteWorker.prototype.message_handlers = { - test_state: RemoteWorker.prototype.test_state, - result: RemoteWorker.prototype.test_done, - complete: RemoteWorker.prototype.worker_done - }; - - /* - * Harness - */ - - function TestsStatus() - { - this.status = null; - this.message = null; - this.stack = null; - } - - TestsStatus.statuses = { - OK:0, - ERROR:1, - TIMEOUT:2 - }; - - TestsStatus.prototype = merge({}, TestsStatus.statuses); - - TestsStatus.prototype.structured_clone = function() - { - if (!this._structured_clone) { - var msg = this.message; - msg = msg ? String(msg) : msg; - this._structured_clone = merge({ - status:this.status, - message:msg, - stack:this.stack - }, TestsStatus.statuses); - } - return this._structured_clone; - }; - - function Tests() - { - this.tests = []; - this.num_pending = 0; - - this.phases = { - INITIAL:0, - SETUP:1, - HAVE_TESTS:2, - HAVE_RESULTS:3, - COMPLETE:4 - }; - this.phase = this.phases.INITIAL; - - this.properties = {}; - - this.wait_for_finish = false; - this.processing_callbacks = false; - - this.allow_uncaught_exception = false; - - this.file_is_test = false; - - this.timeout_multiplier = 1; - this.timeout_length = test_environment.test_timeout(); - this.timeout_id = null; - - this.start_callbacks = []; - this.test_state_callbacks = []; - this.test_done_callbacks = []; - this.all_done_callbacks = []; - - this.pending_workers = []; - - this.status = new TestsStatus(); - - var this_obj = this; - - test_environment.add_on_loaded_callback(function() { - if (this_obj.all_done()) { - this_obj.complete(); - } - }); - - this.set_timeout(); - } - - Tests.prototype.setup = function(func, properties) - { - if (this.phase >= this.phases.HAVE_RESULTS) { - return; - } - - if (this.phase < this.phases.SETUP) { - this.phase = this.phases.SETUP; - } - - this.properties = properties; - - for (var p in properties) { - if (properties.hasOwnProperty(p)) { - var value = properties[p]; - if (p == "allow_uncaught_exception") { - this.allow_uncaught_exception = value; - } else if (p == "explicit_done" && value) { - this.wait_for_finish = true; - } else if (p == "explicit_timeout" && value) { - this.timeout_length = null; - if (this.timeout_id) - { - clearTimeout(this.timeout_id); - } - } else if (p == "timeout_multiplier") { - this.timeout_multiplier = value; - } - } - } - - if (func) { - try { - func(); - } catch (e) { - this.status.status = this.status.ERROR; - this.status.message = String(e); - this.status.stack = e.stack ? e.stack : null; - } - } - this.set_timeout(); - }; - - Tests.prototype.set_file_is_test = function() { - if (this.tests.length > 0) { - throw new Error("Tried to set file as test after creating a test"); - } - this.wait_for_finish = true; - this.file_is_test = true; - // Create the test, which will add it to the list of tests - async_test(); - }; - - Tests.prototype.set_timeout = function() { - var this_obj = this; - clearTimeout(this.timeout_id); - if (this.timeout_length !== null) { - this.timeout_id = setTimeout(function() { - this_obj.timeout(); - }, this.timeout_length); - } - }; - - Tests.prototype.timeout = function() { - if (this.status.status === null) { - this.status.status = this.status.TIMEOUT; - } - this.complete(); - }; - - Tests.prototype.end_wait = function() - { - this.wait_for_finish = false; - if (this.all_done()) { - this.complete(); - } - }; - - Tests.prototype.push = function(test) - { - if (this.phase < this.phases.HAVE_TESTS) { - this.start(); - } - this.num_pending++; - test.index = this.tests.push(test); - this.notify_test_state(test); - }; - - Tests.prototype.notify_test_state = function(test) { - var this_obj = this; - forEach(this.test_state_callbacks, - function(callback) { - callback(test, this_obj); - }); - }; - - Tests.prototype.all_done = function() { - return (this.tests.length > 0 && test_environment.all_loaded && - this.num_pending === 0 && !this.wait_for_finish && - !this.processing_callbacks && - !this.pending_workers.some(function(w) { return w.running; })); - }; - - Tests.prototype.start = function() { - this.phase = this.phases.HAVE_TESTS; - this.notify_start(); - }; - - Tests.prototype.notify_start = function() { - var this_obj = this; - forEach (this.start_callbacks, - function(callback) - { - callback(this_obj.properties); - }); - }; - - Tests.prototype.result = function(test) - { - if (this.phase > this.phases.HAVE_RESULTS) { - return; - } - this.phase = this.phases.HAVE_RESULTS; - this.num_pending--; - this.notify_result(test); - }; - - Tests.prototype.notify_result = function(test) { - var this_obj = this; - this.processing_callbacks = true; - forEach(this.test_done_callbacks, - function(callback) - { - callback(test, this_obj); - }); - this.processing_callbacks = false; - if (this_obj.all_done()) { - this_obj.complete(); - } - }; - - Tests.prototype.complete = function() { - if (this.phase === this.phases.COMPLETE) { - return; - } - this.phase = this.phases.COMPLETE; - var this_obj = this; - this.tests.forEach( - function(x) - { - if (x.phase < x.phases.COMPLETE) { - this_obj.notify_result(x); - x.cleanup(); - x.phase = x.phases.COMPLETE; - } - } - ); - this.notify_complete(); - }; - - Tests.prototype.notify_complete = function() { - var this_obj = this; - if (this.status.status === null) { - this.status.status = this.status.OK; - } - - forEach (this.all_done_callbacks, - function(callback) - { - callback(this_obj.tests, this_obj.status); - }); - }; - - Tests.prototype.fetch_tests_from_worker = function(worker) { - if (this.phase >= this.phases.COMPLETE) { - return; - } - - this.pending_workers.push(new RemoteWorker(worker)); - }; - - function fetch_tests_from_worker(port) { - tests.fetch_tests_from_worker(port); - } - expose(fetch_tests_from_worker, 'fetch_tests_from_worker'); - - function timeout() { - if (tests.timeout_length === null) { - tests.timeout(); - } - } - expose(timeout, 'timeout'); - - function add_start_callback(callback) { - tests.start_callbacks.push(callback); - } - - function add_test_state_callback(callback) { - tests.test_state_callbacks.push(callback); - } - - function add_result_callback(callback) { - tests.test_done_callbacks.push(callback); - } - - function add_completion_callback(callback) { - tests.all_done_callbacks.push(callback); - } - - expose(add_start_callback, 'add_start_callback'); - expose(add_test_state_callback, 'add_test_state_callback'); - expose(add_result_callback, 'add_result_callback'); - expose(add_completion_callback, 'add_completion_callback'); - - function remove(array, item) { - var index = array.indexOf(item); - if (index > -1) { - array.splice(index, 1); - } - } - - function remove_start_callback(callback) { - remove(tests.start_callbacks, callback); - } - - function remove_test_state_callback(callback) { - remove(tests.test_state_callbacks, callback); - } - - function remove_result_callback(callback) { - remove(tests.test_done_callbacks, callback); - } - - function remove_completion_callback(callback) { - remove(tests.all_done_callbacks, callback); - } - - /* - * Output listener - */ - - function Output() { - this.output_document = document; - this.output_node = null; - this.enabled = settings.output; - this.phase = this.INITIAL; - } - - Output.prototype.INITIAL = 0; - Output.prototype.STARTED = 1; - Output.prototype.HAVE_RESULTS = 2; - Output.prototype.COMPLETE = 3; - - Output.prototype.setup = function(properties) { - if (this.phase > this.INITIAL) { - return; - } - - //If output is disabled in testharnessreport.js the test shouldn't be - //able to override that - this.enabled = this.enabled && (properties.hasOwnProperty("output") ? - properties.output : settings.output); - }; - - Output.prototype.init = function(properties) { - if (this.phase >= this.STARTED) { - return; - } - if (properties.output_document) { - this.output_document = properties.output_document; - } else { - this.output_document = document; - } - this.phase = this.STARTED; - }; - - Output.prototype.resolve_log = function() { - var output_document; - if (typeof this.output_document === "function") { - output_document = this.output_document.apply(undefined); - } else { - output_document = this.output_document; - } - if (!output_document) { - return; - } - var node = output_document.getElementById("log"); - if (!node) { - if (!document.body || document.readyState == "loading") { - return; - } - node = output_document.createElement("div"); - node.id = "log"; - output_document.body.appendChild(node); - } - this.output_document = output_document; - this.output_node = node; - }; - - Output.prototype.show_status = function() { - if (this.phase < this.STARTED) { - this.init(); - } - if (!this.enabled) { - return; - } - if (this.phase < this.HAVE_RESULTS) { - this.resolve_log(); - this.phase = this.HAVE_RESULTS; - } - var done_count = tests.tests.length - tests.num_pending; - if (this.output_node) { - if (done_count < 100 || - (done_count < 1000 && done_count % 100 === 0) || - done_count % 1000 === 0) { - this.output_node.textContent = "Running, " + - done_count + " complete, " + - tests.num_pending + " remain"; - } - } - }; - - Output.prototype.show_results = function (tests, harness_status) { - if (this.phase >= this.COMPLETE) { - return; - } - if (!this.enabled) { - return; - } - if (!this.output_node) { - this.resolve_log(); - } - this.phase = this.COMPLETE; - - var log = this.output_node; - if (!log) { - return; - } - var output_document = this.output_document; - - while (log.lastChild) { - log.removeChild(log.lastChild); - } - - var harness_url = get_harness_url(); - if (harness_url !== null) { - var stylesheet = output_document.createElementNS(xhtml_ns, "link"); - stylesheet.setAttribute("rel", "stylesheet"); - stylesheet.setAttribute("href", harness_url + "testharness.css"); - var heads = output_document.getElementsByTagName("head"); - if (heads.length) { - heads[0].appendChild(stylesheet); - } - } - - var status_text_harness = {}; - status_text_harness[harness_status.OK] = "OK"; - status_text_harness[harness_status.ERROR] = "Error"; - status_text_harness[harness_status.TIMEOUT] = "Timeout"; - - var status_text = {}; - status_text[Test.prototype.PASS] = "Pass"; - status_text[Test.prototype.FAIL] = "Fail"; - status_text[Test.prototype.TIMEOUT] = "Timeout"; - status_text[Test.prototype.NOTRUN] = "Not Run"; - - var status_number = {}; - forEach(tests, - function(test) { - var status = status_text[test.status]; - if (status_number.hasOwnProperty(status)) { - status_number[status] += 1; - } else { - status_number[status] = 1; - } - }); - - function status_class(status) - { - return status.replace(/\s/g, '').toLowerCase(); - } - - var summary_template = ["section", {"id":"summary"}, - ["h2", {}, "Summary"], - function() - { - - var status = status_text_harness[harness_status.status]; - var rv = [["section", {}, - ["p", {}, - "Harness status: ", - ["span", {"class":status_class(status)}, - status - ], - ] - ]]; - - if (harness_status.status === harness_status.ERROR) { - rv[0].push(["pre", {}, harness_status.message]); - if (harness_status.stack) { - rv[0].push(["pre", {}, harness_status.stack]); - } - } - return rv; - }, - ["p", {}, "Found ${num_tests} tests"], - function() { - var rv = [["div", {}]]; - var i = 0; - while (status_text.hasOwnProperty(i)) { - if (status_number.hasOwnProperty(status_text[i])) { - var status = status_text[i]; - rv[0].push(["div", {"class":status_class(status)}, - ["label", {}, - ["input", {type:"checkbox", checked:"checked"}], - status_number[status] + " " + status]]); - } - i++; - } - return rv; - }, - ]; - - log.appendChild(render(summary_template, {num_tests:tests.length}, output_document)); - - forEach(output_document.querySelectorAll("section#summary label"), - function(element) - { - on_event(element, "click", - function(e) - { - if (output_document.getElementById("results") === null) { - e.preventDefault(); - return; - } - var result_class = element.parentNode.getAttribute("class"); - var style_element = output_document.querySelector("style#hide-" + result_class); - var input_element = element.querySelector("input"); - if (!style_element && !input_element.checked) { - style_element = output_document.createElementNS(xhtml_ns, "style"); - style_element.id = "hide-" + result_class; - style_element.textContent = "table#results > tbody > tr."+result_class+"{display:none}"; - output_document.body.appendChild(style_element); - } else if (style_element && input_element.checked) { - style_element.parentNode.removeChild(style_element); - } - }); - }); - - // This use of innerHTML plus manual escaping is not recommended in - // general, but is necessary here for performance. Using textContent - // on each individual <td> adds tens of seconds of execution time for - // large test suites (tens of thousands of tests). - function escape_html(s) - { - return s.replace(/\&/g, "&") - .replace(/</g, "<") - .replace(/"/g, """) - .replace(/'/g, "'"); - } - - function has_assertions() - { - for (var i = 0; i < tests.length; i++) { - if (tests[i].properties.hasOwnProperty("assert")) { - return true; - } - } - return false; - } - - function get_assertion(test) - { - if (test.properties.hasOwnProperty("assert")) { - if (Array.isArray(test.properties.assert)) { - return test.properties.assert.join(' '); - } - return test.properties.assert; - } - return ''; - } - - log.appendChild(document.createElementNS(xhtml_ns, "section")); - var assertions = has_assertions(); - var html = "<h2>Details</h2><table id='results' " + (assertions ? "class='assertions'" : "" ) + ">" + - "<thead><tr><th>Result</th><th>Test Name</th>" + - (assertions ? "<th>Assertion</th>" : "") + - "<th>Message</th></tr></thead>" + - "<tbody>"; - for (var i = 0; i < tests.length; i++) { - html += '<tr class="' + - escape_html(status_class(status_text[tests[i].status])) + - '"><td>' + - escape_html(status_text[tests[i].status]) + - "</td><td>" + - escape_html(tests[i].name) + - "</td><td>" + - (assertions ? escape_html(get_assertion(tests[i])) + "</td><td>" : "") + - escape_html(tests[i].message ? tests[i].message : " ") + - (tests[i].stack ? "<pre>" + - escape_html(tests[i].stack) + - "</pre>": "") + - "</td></tr>"; - } - html += "</tbody></table>"; - try { - log.lastChild.innerHTML = html; - } catch (e) { - log.appendChild(document.createElementNS(xhtml_ns, "p")) - .textContent = "Setting innerHTML for the log threw an exception."; - log.appendChild(document.createElementNS(xhtml_ns, "pre")) - .textContent = html; - } - }; - - /* - * Template code - * - * A template is just a javascript structure. An element is represented as: - * - * [tag_name, {attr_name:attr_value}, child1, child2] - * - * the children can either be strings (which act like text nodes), other templates or - * functions (see below) - * - * A text node is represented as - * - * ["{text}", value] - * - * String values have a simple substitution syntax; ${foo} represents a variable foo. - * - * It is possible to embed logic in templates by using a function in a place where a - * node would usually go. The function must either return part of a template or null. - * - * In cases where a set of nodes are required as output rather than a single node - * with children it is possible to just use a list - * [node1, node2, node3] - * - * Usage: - * - * render(template, substitutions) - take a template and an object mapping - * variable names to parameters and return either a DOM node or a list of DOM nodes - * - * substitute(template, substitutions) - take a template and variable mapping object, - * make the variable substitutions and return the substituted template - * - */ - - function is_single_node(template) - { - return typeof template[0] === "string"; - } - - function substitute(template, substitutions) - { - if (typeof template === "function") { - var replacement = template(substitutions); - if (!replacement) { - return null; - } - - return substitute(replacement, substitutions); - } - - if (is_single_node(template)) { - return substitute_single(template, substitutions); - } - - return filter(map(template, function(x) { - return substitute(x, substitutions); - }), function(x) {return x !== null;}); - } - - function substitute_single(template, substitutions) - { - var substitution_re = /\$\{([^ }]*)\}/g; - - function do_substitution(input) { - var components = input.split(substitution_re); - var rv = []; - for (var i = 0; i < components.length; i += 2) { - rv.push(components[i]); - if (components[i + 1]) { - rv.push(String(substitutions[components[i + 1]])); - } - } - return rv; - } - - function substitute_attrs(attrs, rv) - { - rv[1] = {}; - for (var name in template[1]) { - if (attrs.hasOwnProperty(name)) { - var new_name = do_substitution(name).join(""); - var new_value = do_substitution(attrs[name]).join(""); - rv[1][new_name] = new_value; - } - } - } - - function substitute_children(children, rv) - { - for (var i = 0; i < children.length; i++) { - if (children[i] instanceof Object) { - var replacement = substitute(children[i], substitutions); - if (replacement !== null) { - if (is_single_node(replacement)) { - rv.push(replacement); - } else { - extend(rv, replacement); - } - } - } else { - extend(rv, do_substitution(String(children[i]))); - } - } - return rv; - } - - var rv = []; - rv.push(do_substitution(String(template[0])).join("")); - - if (template[0] === "{text}") { - substitute_children(template.slice(1), rv); - } else { - substitute_attrs(template[1], rv); - substitute_children(template.slice(2), rv); - } - - return rv; - } - - function make_dom_single(template, doc) - { - var output_document = doc || document; - var element; - if (template[0] === "{text}") { - element = output_document.createTextNode(""); - for (var i = 1; i < template.length; i++) { - element.data += template[i]; - } - } else { - element = output_document.createElementNS(xhtml_ns, template[0]); - for (var name in template[1]) { - if (template[1].hasOwnProperty(name)) { - element.setAttribute(name, template[1][name]); - } - } - for (var i = 2; i < template.length; i++) { - if (template[i] instanceof Object) { - var sub_element = make_dom(template[i]); - element.appendChild(sub_element); - } else { - var text_node = output_document.createTextNode(template[i]); - element.appendChild(text_node); - } - } - } - - return element; - } - - function make_dom(template, substitutions, output_document) - { - if (is_single_node(template)) { - return make_dom_single(template, output_document); - } - - return map(template, function(x) { - return make_dom_single(x, output_document); - }); - } - - function render(template, substitutions, output_document) - { - return make_dom(substitute(template, substitutions), output_document); - } - - /* - * Utility funcions - */ - function assert(expected_true, function_name, description, error, substitutions) - { - if (tests.tests.length === 0) { - tests.set_file_is_test(); - } - if (expected_true !== true) { - var msg = make_message(function_name, description, - error, substitutions); - throw new AssertionError(msg); - } - } - - function AssertionError(message) - { - this.message = message; - this.stack = this.get_stack(); - } - - AssertionError.prototype = Object.create(Error.prototype); - - AssertionError.prototype.get_stack = function() { - var stack = new Error().stack; - // IE11 does not initialize 'Error.stack' until the object is thrown. - if (!stack) { - try { - throw new Error(); - } catch (e) { - stack = e.stack; - } - } - - var lines = stack.split("\n"); - - // Create a pattern to match stack frames originating within testharness.js. These include the - // script URL, followed by the line/col (e.g., '/resources/testharness.js:120:21'). - var re = new RegExp((get_script_url() || "\\btestharness.js") + ":\\d+:\\d+"); - - // Some browsers include a preamble that specifies the type of the error object. Skip this by - // advancing until we find the first stack frame originating from testharness.js. - var i = 0; - while (!re.test(lines[i]) && i < lines.length) { - i++; - } - - // Then skip the top frames originating from testharness.js to begin the stack at the test code. - while (re.test(lines[i]) && i < lines.length) { - i++; - } - - // Paranoid check that we didn't skip all frames. If so, return the original stack unmodified. - if (i >= lines.length) { - return stack; - } - - return lines.slice(i).join("\n"); - } - - function make_message(function_name, description, error, substitutions) - { - for (var p in substitutions) { - if (substitutions.hasOwnProperty(p)) { - substitutions[p] = format_value(substitutions[p]); - } - } - var node_form = substitute(["{text}", "${function_name}: ${description}" + error], - merge({function_name:function_name, - description:(description?description + " ":"")}, - substitutions)); - return node_form.slice(1).join(""); - } - - function filter(array, callable, thisObj) { - var rv = []; - for (var i = 0; i < array.length; i++) { - if (array.hasOwnProperty(i)) { - var pass = callable.call(thisObj, array[i], i, array); - if (pass) { - rv.push(array[i]); - } - } - } - return rv; - } - - function map(array, callable, thisObj) - { - var rv = []; - rv.length = array.length; - for (var i = 0; i < array.length; i++) { - if (array.hasOwnProperty(i)) { - rv[i] = callable.call(thisObj, array[i], i, array); - } - } - return rv; - } - - function extend(array, items) - { - Array.prototype.push.apply(array, items); - } - - function forEach(array, callback, thisObj) - { - for (var i = 0; i < array.length; i++) { - if (array.hasOwnProperty(i)) { - callback.call(thisObj, array[i], i, array); - } - } - } - - function merge(a,b) - { - var rv = {}; - var p; - for (p in a) { - rv[p] = a[p]; - } - for (p in b) { - rv[p] = b[p]; - } - return rv; - } - - function expose(object, name) - { - var components = name.split("."); - var target = test_environment.global_scope(); - for (var i = 0; i < components.length - 1; i++) { - if (!(components[i] in target)) { - target[components[i]] = {}; - } - target = target[components[i]]; - } - target[components[components.length - 1]] = object; - } - - function is_same_origin(w) { - try { - 'random_prop' in w; - return true; - } catch (e) { - return false; - } - } - - /** Returns the 'src' URL of the first <script> tag in the page to include the file 'testharness.js'. */ - function get_script_url() - { - if (!('document' in self)) { - return undefined; - } - - var scripts = document.getElementsByTagName("script"); - for (var i = 0; i < scripts.length; i++) { - var src; - if (scripts[i].src) { - src = scripts[i].src; - } else if (scripts[i].href) { - //SVG case - src = scripts[i].href.baseVal; - } - - var matches = src && src.match(/^(.*\/|)testharness\.js$/); - if (matches) { - return src; - } - } - return undefined; - } - - /** Returns the URL path at which the files for testharness.js are assumed to reside (e.g., '/resources/'). - The path is derived from inspecting the 'src' of the <script> tag that included 'testharness.js'. */ - function get_harness_url() - { - var script_url = get_script_url(); - - // Exclude the 'testharness.js' file from the returned path, but '+ 1' to include the trailing slash. - return script_url ? script_url.slice(0, script_url.lastIndexOf('/') + 1) : undefined; - } - - function supports_post_message(w) - { - var supports; - var type; - // Given IE implements postMessage across nested iframes but not across - // windows or tabs, you can't infer cross-origin communication from the presence - // of postMessage on the current window object only. - // - // Touching the postMessage prop on a window can throw if the window is - // not from the same origin AND post message is not supported in that - // browser. So just doing an existence test here won't do, you also need - // to wrap it in a try..cacth block. - try { - type = typeof w.postMessage; - if (type === "function") { - supports = true; - } - - // IE8 supports postMessage, but implements it as a host object which - // returns "object" as its `typeof`. - else if (type === "object") { - supports = true; - } - - // This is the case where postMessage isn't supported AND accessing a - // window property across origins does NOT throw (e.g. old Safari browser). - else { - supports = false; - } - } catch (e) { - // This is the case where postMessage isn't supported AND accessing a - // window property across origins throws (e.g. old Firefox browser). - supports = false; - } - return supports; - } - - /** - * Setup globals - */ - - var tests = new Tests(); - - addEventListener("error", function(e) { - if (tests.file_is_test) { - var test = tests.tests[0]; - if (test.phase >= test.phases.HAS_RESULT) { - return; - } - test.set_status(test.FAIL, e.message, e.stack); - test.phase = test.phases.HAS_RESULT; - test.done(); - done(); - } else if (!tests.allow_uncaught_exception) { - tests.status.status = tests.status.ERROR; - tests.status.message = e.message; - tests.status.stack = e.stack; - } - }); - - test_environment.on_tests_ready(); - -})(); -// vim: set expandtab shiftwidth=4 tabstop=4:
diff --git a/third_party/WebKit/LayoutTests/http/tests/w3c/resources/testharnessreport.js b/third_party/WebKit/LayoutTests/http/tests/w3c/resources/testharnessreport.js deleted file mode 100644 index 56dcac54..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/w3c/resources/testharnessreport.js +++ /dev/null
@@ -1,142 +0,0 @@ -/* - * THIS FILE INTENTIONALLY LEFT BLANK - * - * More specifically, this file is intended for vendors to implement - * code needed to integrate testharness.js tests with their own test systems. - * - * Typically such integration will attach callbacks when each test is - * has run, using add_result_callback(callback(test)), or when the whole test file has - * completed, using add_completion_callback(callback(tests, harness_status)). - * - * For more documentation about the callback functions and the - * parameters they are called with see testharness.js - */ - -(function() { - - // Setup for WebKit JavaScript tests - if (self.testRunner) { - testRunner.dumpAsText(); - testRunner.waitUntilDone(); - testRunner.setCanOpenWindows(); - testRunner.setCloseRemainingWindowsWhenComplete(true); - } - - // Disable the default output of testharness.js. The default output formats - // test results into an HTML table. When that table is dumped as text, no - // spacing between cells is preserved, and it is therefore not readable. By - // setting output to false, the HTML table will not be created. - setup({"output":false}); - - // Function used to convert the test status code into the corresponding - // string - function convertResult(resultStatus) { - switch (resultStatus) { - case 0: - return "PASS"; - case 1: - return "FAIL"; - case 2: - return "TIMEOUT"; - default: - return "NOTRUN"; - } - } - - // Sanitizes the given text for display in test results. - function sanitize(text) { - if (!text) { - return ""; - } - // Escape null characters, otherwise diff will think the file is binary. - text = text.replace(/\0/g, "\\0"); - // Escape carriage returns as they break rietveld's difftools. - return text.replace(/\r/g, "\\r"); - } - - // If the test has a meta tag named flags and the content contains "dom", - // then it's a CSSWG test. - function isCSSWGTest() { - var flags = document.querySelector('meta[name=flags]'), - content = flags ? flags.getAttribute('content') : null; - return content && content.match(/\bdom\b/); - } - - function isJSTest() { - return !!document.querySelector('script[src*="/resources/testharness"]'); - } - - var didDispatchLoadEvent = false; - var handleLoad = function() { - didDispatchLoadEvent = true; - window.removeEventListener('load', handleLoad); - }; - window.addEventListener('load', handleLoad, false); - - // Using a callback function, test results will be added to the page in a - // manner that allows dumpAsText to produce readable test results. - add_completion_callback(function (tests, harness_status) { - - // Create element to hold results. - var results = document.createElement("pre"); - - // Declare result string. - var resultStr = "This is a testharness.js-based test.\n"; - - // Check harness_status. If it is not 0, tests did not execute - // correctly, output the error code and message. - if (harness_status.status != 0) { - resultStr += "Harness Error. harness_status.status = " + - harness_status.status + - " , harness_status.message = " + - harness_status.message + - "\n"; - } else { - // Iterate through tests array and build string that contains - // results for all tests. - for (var i = 0; i < tests.length; ++i) { - resultStr += convertResult(tests[i].status) + " " + - sanitize(tests[i].name) + " " + - sanitize(tests[i].message) + "\n"; - } - } - resultStr += "Harness: the test ran to completion.\n"; - - // Set results element's textContent to the results string. - results.textContent = resultStr; - - function done() { - if (self.testRunner) { - var logDiv = document.getElementById('log'); - if ((isCSSWGTest() || isJSTest()) && logDiv) { - // Assume it's a CSSWG style test, and anything other than - // the log div isn't material to the testrunner output, so - // should be hidden from the text dump. - document.body.textContent = ''; - } - } - - // Add results element to document. - if (!document.body) { - if (!document.documentElement) - document.appendChild(document.createElement('html')); - document.documentElement.appendChild(document.createElement("body")); - } - document.body.appendChild(results); - - if (self.testRunner) - testRunner.notifyDone(); - } - - if (didDispatchLoadEvent || document.readyState != 'loading') { - // This function might not be the last 'completion callback', and - // another completion callback might generate more results. So, we - // don't dump the results immediately. - setTimeout(done, 0); - } else { - // Parsing the test HTML isn't finished yet. - window.addEventListener('load', done); - } - }); - -})();
diff --git a/third_party/WebKit/LayoutTests/inspector/console/console-xpath.html b/third_party/WebKit/LayoutTests/inspector/console/console-xpath.html index 3575cf75..8ec0d77 100644 --- a/third_party/WebKit/LayoutTests/inspector/console/console-xpath.html +++ b/third_party/WebKit/LayoutTests/inspector/console/console-xpath.html
@@ -6,7 +6,8 @@ function test() { - InspectorTest.addConsoleViewSniffer(addMessageSniffer, true); + InspectorTest.addSniffer(WebInspector.ConsoleViewMessage.prototype, "_formattedParameterAsNodeForTest", formattedParameter); + InspectorTest.addConsoleViewSniffer(messageSniffer, true); InspectorTest.evaluateInConsole("$x('42')"); // number InspectorTest.evaluateInConsole("$x('name(/html)')"); // string @@ -15,22 +16,28 @@ InspectorTest.evaluateInConsole("$x('//a/@href')[0]"); // href, should not throw InspectorTest.evaluateInPage("console.log('complete')"); // node iterator - function addMessageSniffer(uiMessage) + var completeMessageReceived = false; + function messageSniffer(uiMessage) { if (uiMessage.toString().indexOf("complete") !== -1) { - InspectorTest.expandConsoleMessages(waitForObjects); + completeMessageReceived = true; + maybeCompleteTest(); } } - function waitForObjects() + var parameterFormatted = false; + function formattedParameter() { - InspectorTest.waitForRemoteObjectsConsoleMessages(dumpConsoleMessages); + parameterFormatted = true; + maybeCompleteTest(); } - function dumpConsoleMessages() + function maybeCompleteTest() { - InspectorTest.dumpConsoleMessages(); - InspectorTest.completeTest(); + if (parameterFormatted && completeMessageReceived) { + InspectorTest.dumpConsoleMessages(); + InspectorTest.completeTest(); + } } }
diff --git a/third_party/WebKit/LayoutTests/platform/mac/fast/forms/range/range-appearance-basic-expected.png b/third_party/WebKit/LayoutTests/platform/mac/fast/forms/range/range-appearance-basic-expected.png index d3153fd..2649684 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/fast/forms/range/range-appearance-basic-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/fast/forms/range/range-appearance-basic-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/fast/text/midword-break-after-breakable-char-expected.png b/third_party/WebKit/LayoutTests/platform/win/fast/text/midword-break-after-breakable-char-expected.png index c7c7082..a159aba 100644 --- a/third_party/WebKit/LayoutTests/platform/win/fast/text/midword-break-after-breakable-char-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/fast/text/midword-break-after-breakable-char-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/fast/text/midword-break-after-breakable-char-expected.txt b/third_party/WebKit/LayoutTests/platform/win/fast/text/midword-break-after-breakable-char-expected.txt index 69642e5..92b59e0 100644 --- a/third_party/WebKit/LayoutTests/platform/win/fast/text/midword-break-after-breakable-char-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/fast/text/midword-break-after-breakable-char-expected.txt
@@ -24,14 +24,14 @@ LayoutText {#text} at (0,0) size 266x17 text run at (0,0) width 266: "The following blocks should be identical." LayoutBlockFlow (floating) {DIV} at (4,142) size 300x162 [bgcolor=#FFFFE0] - LayoutText {#text} at (0,0) size 296x161 + LayoutText {#text} at (0,0) size 297x161 text run at (0,0) width 191: "Curabiturpretium,quamquiss?" text run at (0,18) width 295: "empermalesuada,estliberofeugiatlibero,velfrin" text run at (0,36) width 147: "gillaorcinibhsedneque-" text run at (0,54) width 295: "Quisqueeunullanonnisimolestieaccumsan.Etia" text run at (0,72) width 209: "mtellusurna,laoreetac,laoreetnon" - text run at (0,90) width 291: "suscipitsed,sapien.Phasellusvehicula,sematpo" - text run at (0,108) width 242: "suerevehicula,auguenibhmolestienisl\x{AD}" + hyphen string "-" + text run at (0,90) width 297: "suscipitsed,sapien.Phasellusvehicula,sematpos" + text run at (0,108) width 236: "uerevehicula,auguenibhmolestienisl\x{AD}" + hyphen string "-" text run at (0,126) width 296: "necullamcorperlacusantevulputatepede.Nascet" text run at (0,144) width 100: "urridiculusmus." LayoutBlockFlow (floating) {DIV} at (312,142) size 300x234 [bgcolor=#FFFFE0]
diff --git a/third_party/WebKit/LayoutTests/virtual/stable/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt b/third_party/WebKit/LayoutTests/virtual/stable/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt index a7e370f..11a2bde 100644 --- a/third_party/WebKit/LayoutTests/virtual/stable/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/stable/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt
@@ -318,6 +318,7 @@ getter upper getter upperOpen method constructor + method includes interface IDBObjectStore getter autoIncrement getter indexNames @@ -724,6 +725,7 @@ getter upper getter upperOpen method constructor + method includes interface webkitIDBObjectStore getter autoIncrement getter indexNames
diff --git a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-dedicated-worker-expected.txt b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-dedicated-worker-expected.txt index a4cd2ab..2bebec03 100644 --- a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-dedicated-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-dedicated-worker-expected.txt
@@ -338,6 +338,7 @@ [Worker] getter upper [Worker] getter upperOpen [Worker] method constructor +[Worker] method includes [Worker] interface IDBObjectStore [Worker] attribute @@toStringTag [Worker] getter autoIncrement @@ -794,6 +795,7 @@ [Worker] getter upper [Worker] getter upperOpen [Worker] method constructor +[Worker] method includes [Worker] interface webkitIDBObjectStore [Worker] attribute @@toStringTag [Worker] getter autoIncrement
diff --git a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-expected.txt index 691aa46..37314012 100644 --- a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-expected.txt
@@ -2876,6 +2876,7 @@ getter upper getter upperOpen method constructor + method includes interface IDBObjectStore attribute @@toStringTag getter autoIncrement @@ -6213,6 +6214,7 @@ getter upper getter upperOpen method constructor + method includes interface webkitIDBObjectStore attribute @@toStringTag getter autoIncrement
diff --git a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-shared-worker-expected.txt b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-shared-worker-expected.txt index 9263c035..740d2b0 100644 --- a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-shared-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/global-interface-listing-shared-worker-expected.txt
@@ -325,6 +325,7 @@ [Worker] getter upper [Worker] getter upperOpen [Worker] method constructor +[Worker] method includes [Worker] interface IDBObjectStore [Worker] attribute @@toStringTag [Worker] getter autoIncrement @@ -786,6 +787,7 @@ [Worker] getter upper [Worker] getter upperOpen [Worker] method constructor +[Worker] method includes [Worker] interface webkitIDBObjectStore [Worker] attribute @@toStringTag [Worker] getter autoIncrement
diff --git a/third_party/WebKit/LayoutTests/webaudio/audiochannelmerger-basic-expected.txt b/third_party/WebKit/LayoutTests/webaudio/audiochannelmerger-basic-expected.txt index 73511104..522c338 100644 --- a/third_party/WebKit/LayoutTests/webaudio/audiochannelmerger-basic-expected.txt +++ b/third_party/WebKit/LayoutTests/webaudio/audiochannelmerger-basic-expected.txt
@@ -9,7 +9,7 @@ PASS context.createChannelMerger(33) threw IndexSizeError: Failed to execute 'createChannelMerger' on 'AudioContext': The number of inputs provided (33) is outside the range [1, 32].. PASS merger.channelCount is equal to 1. PASS merger.channelCount = 3 threw InvalidStateError: Failed to set the 'channelCount' property on 'AudioNode': ChannelMerger: channelCount cannot be changed from 1. -PASS merger.channelCountMode is equal to explicit. +PASS merger.channelCountMode is equal to "explicit". PASS merger.channelCountMode = "max" threw InvalidStateError: Failed to set the 'channelCountMode' property on 'AudioNode': ChannelMerger: channelCountMode cannot be changed from 'explicit'. PASS successfullyParsed is true
diff --git a/third_party/WebKit/LayoutTests/webaudio/iirfilter-basic-expected.txt b/third_party/WebKit/LayoutTests/webaudio/iirfilter-basic-expected.txt index f41fb8c..8580a3f 100644 --- a/third_party/WebKit/LayoutTests/webaudio/iirfilter-basic-expected.txt +++ b/third_party/WebKit/LayoutTests/webaudio/iirfilter-basic-expected.txt
@@ -6,8 +6,8 @@ PASS context.createIIRFilter is defined. PASS numberOfInputs is equal to 1. PASS numberOfOutputs is equal to 1. -PASS channelCountMode is equal to max. -PASS channelInterpretation is equal to speakers. +PASS channelCountMode is equal to "max". +PASS channelInterpretation is equal to "speakers". PASS All basic IIRFilter parameters are correct. PASS createIIRFilter() threw TypeError: Failed to execute 'createIIRFilter' on 'AudioContext': 2 arguments required, but only 0 present..
diff --git a/third_party/WebKit/LayoutTests/webaudio/offlineaudiocontext-suspend-resume-eventhandler-expected.txt b/third_party/WebKit/LayoutTests/webaudio/offlineaudiocontext-suspend-resume-eventhandler-expected.txt index e4b6237..ce3b80d 100644 --- a/third_party/WebKit/LayoutTests/webaudio/offlineaudiocontext-suspend-resume-eventhandler-expected.txt +++ b/third_party/WebKit/LayoutTests/webaudio/offlineaudiocontext-suspend-resume-eventhandler-expected.txt
@@ -20,7 +20,7 @@ PASS A new suspend has been scheduled at 1.75 second(s). PASS onstatechange event handler: context is suspended at 1.75 second(s). PASS Scheduling at 2 seconds rejected correctly (with InvalidStateError: cannot schedule a suspend at frame 25600 (2 seconds) because it is greater than or equal to the total render duration of 25600 frames). -PASS oncomplete event handler: context.state is equal to closed. +PASS oncomplete event handler: context.state is equal to "closed". PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/webaudio/offlineaudiocontext-suspend-resume-promise-expected.txt b/third_party/WebKit/LayoutTests/webaudio/offlineaudiocontext-suspend-resume-promise-expected.txt index a4ce359f..f5299d5 100644 --- a/third_party/WebKit/LayoutTests/webaudio/offlineaudiocontext-suspend-resume-promise-expected.txt +++ b/third_party/WebKit/LayoutTests/webaudio/offlineaudiocontext-suspend-resume-promise-expected.txt
@@ -20,7 +20,7 @@ PASS A new suspend has been scheduled at 1.75 second(s). PASS suspend promise resolved: context is suspended at 1.75 second(s). PASS Scheduling at 2 seconds rejected correctly (with InvalidStateError: cannot schedule a suspend at frame 25600 (2 seconds) because it is greater than or equal to the total render duration of 25600 frames). -PASS Promise context.state is equal to closed. +PASS Promise context.state is equal to "closed". PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/webaudio/oscillator-basic-expected.txt b/third_party/WebKit/LayoutTests/webaudio/oscillator-basic-expected.txt index 6592180..83ba5a5 100644 --- a/third_party/WebKit/LayoutTests/webaudio/oscillator-basic-expected.txt +++ b/third_party/WebKit/LayoutTests/webaudio/oscillator-basic-expected.txt
@@ -3,15 +3,15 @@ On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". -PASS osc.type = 'sine' is equal to sine. -PASS osc.type = 'square' is equal to square. -PASS osc.type = 'sawtooth' is equal to sawtooth. -PASS osc.type = 'triangle' is equal to triangle. +PASS osc.type = 'sine' is equal to "sine". +PASS osc.type = 'square' is equal to "square". +PASS osc.type = 'sawtooth' is equal to "sawtooth". +PASS osc.type = 'triangle' is equal to "triangle". PASS osc.type = 'custom' threw InvalidStateError: Failed to set the 'type' property on 'OscillatorNode': 'type' cannot be set directly to 'custom'. Use setPeriodicWave() to create a custom Oscillator type.. PASS osc.setPeriodicWave(wave) did not throw an exception. -PASS osc.type is equal to custom. +PASS osc.type is equal to "custom". PASS osc.type = 0 is not equal to 0. -PASS osc.type is equal to custom. +PASS osc.type is equal to "custom". PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/webaudio/resources/audio-testing.js b/third_party/WebKit/LayoutTests/webaudio/resources/audio-testing.js index ba04d973..608d16a 100644 --- a/third_party/WebKit/LayoutTests/webaudio/resources/audio-testing.js +++ b/third_party/WebKit/LayoutTests/webaudio/resources/audio-testing.js
@@ -509,10 +509,18 @@ this._checkNaN(value, 'EXPECTED'); - if (this.target === value) - this._testPassed('is equal to ' + value); - else - this._testFailed('was ' + this.target + ' instead of ' + value); + var outputValue = value; + if (type === 'string') + outputValue = '"' + outputValue + '"'; + if (this.target === value) { + var outputValue = (type === 'string') ? '"' + value + '"' : value; + this._testPassed('is equal to ' + outputValue); + } else { + var targetValue = this.target; + if (typeof this.target === 'string') + targetValue = '"' + targetValue + '"'; + this._testFailed('was ' + targetValue + ' instead of ' + outputValue); + } return this._success; };
diff --git a/third_party/WebKit/Source/config.gni b/third_party/WebKit/Source/config.gni index a0bed4e..b593dc1 100644 --- a/third_party/WebKit/Source/config.gni +++ b/third_party/WebKit/Source/config.gni
@@ -17,10 +17,6 @@ # garbage-collection infrastructure during compilation. blink_gc_plugin = true - # If true, force blink asserts to be off in a release build. When false, - # blink asserts in release build may be controlled by DCHECK_ALWAYS_ON. - blink_asserts_off_in_release = false - # If true, doesn't compile debug symbols into webcore reducing the # size of the binary and increasing the speed of gdb. remove_webcore_debug_symbols = false @@ -91,9 +87,6 @@ if (use_default_render_theme) { feature_defines_list += [ "WTF_USE_DEFAULT_RENDER_THEME=1" ] } -if (blink_asserts_off_in_release && !is_debug) { - feature_defines_list += [ "ENABLE_ASSERT=0" ] -} if (blink_logging_always_on) { feature_defines_list += [ "LOG_DISABLED=0" ] }
diff --git a/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.cpp b/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.cpp index 2eb90c9..3d30b47 100644 --- a/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.cpp +++ b/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.cpp
@@ -74,12 +74,14 @@ CSSDefaultStyleSheets::CSSDefaultStyleSheets() : m_defaultStyle(nullptr) , m_defaultMobileViewportStyle(nullptr) + , m_defaultTelevisionViewportStyle(nullptr) , m_defaultQuirksStyle(nullptr) , m_defaultPrintStyle(nullptr) , m_defaultViewSourceStyle(nullptr) , m_defaultXHTMLMobileProfileStyle(nullptr) , m_defaultStyleSheet(nullptr) , m_mobileViewportStyleSheet(nullptr) + , m_televisionViewportStyleSheet(nullptr) , m_quirksStyleSheet(nullptr) , m_svgStyleSheet(nullptr) , m_mathmlStyleSheet(nullptr) @@ -134,6 +136,16 @@ return m_defaultMobileViewportStyle.get(); } +RuleSet* CSSDefaultStyleSheets::defaultTelevisionViewportStyle() +{ + if (!m_defaultTelevisionViewportStyle) { + m_defaultTelevisionViewportStyle = RuleSet::create(); + m_televisionViewportStyleSheet = parseUASheet(loadResourceAsASCIIString("viewportTelevision.css")); + m_defaultTelevisionViewportStyle->addRulesFromSheet(m_televisionViewportStyleSheet.get(), screenEval()); + } + return m_defaultTelevisionViewportStyle.get(); +} + void CSSDefaultStyleSheets::ensureDefaultStyleSheetsForElement(const Element& element, bool& changedDefaultStyle) { // FIXME: We should assert that the sheet only styles SVG elements. @@ -184,12 +196,14 @@ { visitor->trace(m_defaultStyle); visitor->trace(m_defaultMobileViewportStyle); + visitor->trace(m_defaultTelevisionViewportStyle); visitor->trace(m_defaultQuirksStyle); visitor->trace(m_defaultPrintStyle); visitor->trace(m_defaultViewSourceStyle); visitor->trace(m_defaultXHTMLMobileProfileStyle); visitor->trace(m_defaultStyleSheet); visitor->trace(m_mobileViewportStyleSheet); + visitor->trace(m_televisionViewportStyleSheet); visitor->trace(m_quirksStyleSheet); visitor->trace(m_svgStyleSheet); visitor->trace(m_mathmlStyleSheet);
diff --git a/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.h b/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.h index 0b696ccc..8c4e183 100644 --- a/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.h +++ b/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.h
@@ -45,6 +45,7 @@ RuleSet* defaultPrintStyle() { return m_defaultPrintStyle.get(); } RuleSet* defaultViewSourceStyle(); RuleSet* defaultMobileViewportStyle(); + RuleSet* defaultTelevisionViewportStyle(); // FIXME: Remove WAP support. RuleSet* defaultXHTMLMobileProfileStyle(); @@ -63,6 +64,7 @@ Member<RuleSet> m_defaultStyle; Member<RuleSet> m_defaultMobileViewportStyle; + Member<RuleSet> m_defaultTelevisionViewportStyle; Member<RuleSet> m_defaultQuirksStyle; Member<RuleSet> m_defaultPrintStyle; Member<RuleSet> m_defaultViewSourceStyle; @@ -70,6 +72,7 @@ Member<StyleSheetContents> m_defaultStyleSheet; Member<StyleSheetContents> m_mobileViewportStyleSheet; + Member<StyleSheetContents> m_televisionViewportStyleSheet; Member<StyleSheetContents> m_quirksStyleSheet; Member<StyleSheetContents> m_svgStyleSheet; Member<StyleSheetContents> m_mathmlStyleSheet;
diff --git a/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp b/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp index 8cc01eb..1e40fcd 100644 --- a/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp +++ b/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp
@@ -55,8 +55,20 @@ CSSDefaultStyleSheets& defaultStyleSheets = CSSDefaultStyleSheets::instance(); collectViewportRules(defaultStyleSheets.defaultStyle(), UserAgentOrigin); - if (m_document->settings() && m_document->settings()->useMobileViewportStyle()) - collectViewportRules(defaultStyleSheets.defaultMobileViewportStyle(), UserAgentOrigin); + WebViewportStyle viewportStyle = m_document->settings() ? m_document->settings()->viewportStyle() : WebViewportStyle::Default; + RuleSet* viewportRules = nullptr; + switch (viewportStyle) { + case WebViewportStyle::Default: + break; + case WebViewportStyle::Mobile: + viewportRules = defaultStyleSheets.defaultMobileViewportStyle(); + break; + case WebViewportStyle::Television: + viewportRules = defaultStyleSheets.defaultTelevisionViewportStyle(); + break; + } + if (viewportRules) + collectViewportRules(viewportRules, UserAgentOrigin); if (m_document->isMobileDocument()) collectViewportRules(defaultStyleSheets.defaultXHTMLMobileProfileStyle(), UserAgentOrigin);
diff --git a/third_party/WebKit/Source/core/css/viewportTelevision.css b/third_party/WebKit/Source/core/css/viewportTelevision.css new file mode 100644 index 0000000..3e92b09 --- /dev/null +++ b/third_party/WebKit/Source/core/css/viewportTelevision.css
@@ -0,0 +1,9 @@ +/* + * Copyright 2016 The Chromium Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. +*/ + +@viewport { + min-width: 1280px; +}
diff --git a/third_party/WebKit/Source/core/frame/FrameView.cpp b/third_party/WebKit/Source/core/frame/FrameView.cpp index 7c82141..4db3dbc 100644 --- a/third_party/WebKit/Source/core/frame/FrameView.cpp +++ b/third_party/WebKit/Source/core/frame/FrameView.cpp
@@ -232,7 +232,7 @@ // Call function for each non-throttled frame view in pre tree order. // Note it needs a null check of the frame's layoutView to access it in case of detached frames. template <typename Function> -void FrameView::forAllNonThrottledFrameViews(Function function) +void FrameView::forAllNonThrottledFrameViews(const Function& function) { if (shouldThrottleRendering()) return;
diff --git a/third_party/WebKit/Source/core/frame/FrameView.h b/third_party/WebKit/Source/core/frame/FrameView.h index 8ed74dc..676fcc8 100644 --- a/third_party/WebKit/Source/core/frame/FrameView.h +++ b/third_party/WebKit/Source/core/frame/FrameView.h
@@ -752,7 +752,7 @@ void collectFrameTimingRequests(GraphicsLayerFrameTimingRequests&); void collectFrameTimingRequestsRecursive(GraphicsLayerFrameTimingRequests&); - template <typename Function> void forAllNonThrottledFrameViews(Function); + template <typename Function> void forAllNonThrottledFrameViews(const Function&); void setNeedsUpdateViewportIntersection(); void updateViewportIntersectionsForSubtree(LifeCycleUpdateOption);
diff --git a/third_party/WebKit/Source/core/frame/Settings.h b/third_party/WebKit/Source/core/frame/Settings.h index ddb2151..86fb063ee 100644 --- a/third_party/WebKit/Source/core/frame/Settings.h +++ b/third_party/WebKit/Source/core/frame/Settings.h
@@ -41,6 +41,7 @@ #include "platform/weborigin/KURL.h" #include "public/platform/PointerProperties.h" #include "public/platform/WebDisplayMode.h" +#include "public/platform/WebViewportStyle.h" namespace blink {
diff --git a/third_party/WebKit/Source/core/frame/Settings.in b/third_party/WebKit/Source/core/frame/Settings.in index 37d265d..e90d06c 100644 --- a/third_party/WebKit/Source/core/frame/Settings.in +++ b/third_party/WebKit/Source/core/frame/Settings.in
@@ -340,9 +340,10 @@ logDnsPrefetchAndPreconnect initial=false logPreload initial=false -# If true, the UA styles will include viewportAndroid.css. It is used for -# Android, and dynamically set by the inspector for mobile emulation. -useMobileViewportStyle initial=false, invalidate=ViewportRule +# These values specify the UA intial viewport style. +# It is dynamically set by the inspector for mobile emulation and can be +# used by content embedders to specify custom style on certain platforms. +viewportStyle type=WebViewportStyle, initial=WebViewportStyle::Default, invalidate=ViewportRule # Automatic track selection is performed based on user preference for track kind specified # by this setting.
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp index 43257c2..38cfacd 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp
@@ -554,7 +554,6 @@ return allowConnectToSource(url, redirectStatus, reportingStatus); case WebURLRequest::RequestContextEmbed: case WebURLRequest::RequestContextObject: - case WebURLRequest::RequestContextPlugin: return allowObjectFromSource(url, redirectStatus, reportingStatus); case WebURLRequest::RequestContextFavicon: case WebURLRequest::RequestContextImage: @@ -585,6 +584,7 @@ case WebURLRequest::RequestContextInternal: case WebURLRequest::RequestContextLocation: case WebURLRequest::RequestContextPing: + case WebURLRequest::RequestContextPlugin: case WebURLRequest::RequestContextPrefetch: case WebURLRequest::RequestContextSubresource: case WebURLRequest::RequestContextUnspecified:
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp index 61c2c19..360a0351 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp
@@ -197,4 +197,17 @@ EXPECT_FALSE(directiveList->reportEndpoints().isEmpty()); } +// Tests that object-src directives are applied to a request to load a +// plugin, but not to subresource requests that the plugin itself +// makes. https://crbug.com/603952 +TEST_F(ContentSecurityPolicyTest, ObjectSrc) +{ + KURL url(KURL(), "https://example.test"); + csp->bindToExecutionContext(document.get()); + csp->didReceiveHeader("object-src 'none';", ContentSecurityPolicyHeaderTypeEnforce, ContentSecurityPolicyHeaderSourceMeta); + EXPECT_FALSE(csp->allowRequest(WebURLRequest::RequestContextObject, url, ContentSecurityPolicy::DidNotRedirect, ContentSecurityPolicy::SuppressReport)); + EXPECT_FALSE(csp->allowRequest(WebURLRequest::RequestContextEmbed, url, ContentSecurityPolicy::DidNotRedirect, ContentSecurityPolicy::SuppressReport)); + EXPECT_TRUE(csp->allowRequest(WebURLRequest::RequestContextPlugin, url, ContentSecurityPolicy::DidNotRedirect, ContentSecurityPolicy::SuppressReport)); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp b/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp index f3c41f36..47c40e1 100644 --- a/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp
@@ -1118,4 +1118,11 @@ return std::make_pair(nullptr, String()); } +String HTMLCanvasElement::getIdFromControl(const Element* element) +{ + if (m_context) + return m_context->getIdFromControl(element); + return String(); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/html/HTMLCanvasElement.h b/third_party/WebKit/Source/core/html/HTMLCanvasElement.h index d7785bf4..500efd6e 100644 --- a/third_party/WebKit/Source/core/html/HTMLCanvasElement.h +++ b/third_party/WebKit/Source/core/html/HTMLCanvasElement.h
@@ -186,8 +186,10 @@ void notifyListenersCanvasChanged(); + // For Canvas HitRegions bool isSupportedInteractiveCanvasFallback(const Element&); std::pair<Element*, String> getControlAndIdIfHitRegionExists(const LayoutPoint&); + String getIdFromControl(const Element*); protected: void didMoveToNewDocument(Document& oldDocument) override;
diff --git a/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.h b/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.h index bed999c..de45e8b 100644 --- a/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.h +++ b/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.h
@@ -103,6 +103,7 @@ virtual void setFont(const String&) { } virtual void styleDidChange(const ComputedStyle* oldStyle, const ComputedStyle& newStyle) { } virtual std::pair<Element*, String> getControlAndIdIfHitRegionExists(const LayoutPoint& location) { ASSERT_NOT_REACHED(); return std::make_pair(nullptr, String()); } + virtual String getIdFromControl(const Element* element) { return String(); } // WebGL-specific interface virtual bool is3d() const { return false; }
diff --git a/third_party/WebKit/Source/core/input/EventHandler.cpp b/third_party/WebKit/Source/core/input/EventHandler.cpp index 4a88d459..ee7ebc7f7 100644 --- a/third_party/WebKit/Source/core/input/EventHandler.cpp +++ b/third_party/WebKit/Source/core/input/EventHandler.cpp
@@ -762,9 +762,12 @@ if (!node) node = m_mousePressNode.get(); - if (!node || !node->layoutObject()) + if ((!node || !node->layoutObject()) && m_frame->view() && m_frame->view()->layoutView()) node = m_frame->view()->layoutView()->node(); + if (!node) + return false; + m_frame->document()->updateLayoutIgnorePendingStylesheets(); LayoutBox* curBox = node->layoutObject()->enclosingBox();
diff --git a/third_party/WebKit/Source/core/input/PointerEventManager.cpp b/third_party/WebKit/Source/core/input/PointerEventManager.cpp index 6bade51..07dbc48 100644 --- a/third_party/WebKit/Source/core/input/PointerEventManager.cpp +++ b/third_party/WebKit/Source/core/input/PointerEventManager.cpp
@@ -4,8 +4,10 @@ #include "core/input/PointerEventManager.h" +#include "core/dom/ElementTraversal.h" #include "core/dom/shadow/FlatTreeTraversal.h" #include "core/events/MouseEvent.h" +#include "core/html/HTMLCanvasElement.h" #include "core/input/EventHandler.h" namespace blink { @@ -58,6 +60,25 @@ return WebInputEventResult::NotHandled; } +PlatformMouseEvent mouseEventWithRegion(Node* node, const PlatformMouseEvent& mouseEvent) +{ + if (!node->isElementNode()) + return mouseEvent; + + Element* element = toElement(node); + if (!element->isInCanvasSubtree()) + return mouseEvent; + + HTMLCanvasElement* canvas = Traversal<HTMLCanvasElement>::firstAncestorOrSelf(*element); + // In this case, the event target is canvas and mouse rerouting doesn't happen. + if (canvas == element) + return mouseEvent; + String region = canvas->getIdFromControl(element); + PlatformMouseEvent newMouseEvent = mouseEvent; + newMouseEvent.setRegion(region); + return newMouseEvent; +} + } // namespace WebInputEventResult PointerEventManager::dispatchPointerEvent( @@ -152,7 +173,9 @@ pointerEvent, EventTypeNames::pointerout, enteredTarget)); } else { dispatchMouseEvent(exitedTarget, - EventTypeNames::mouseout, mouseEvent, enteredTarget); + EventTypeNames::mouseout, + mouseEventWithRegion(exitedTarget->toNode(), mouseEvent), + enteredTarget); } } @@ -221,8 +244,9 @@ !exitedNodeHasCapturingAncestor); } else { dispatchMouseEvent(exitedAncestors[j].get(), - EventTypeNames::mouseleave, mouseEvent, enteredTarget, - 0, !exitedNodeHasCapturingAncestor); + EventTypeNames::mouseleave, + mouseEventWithRegion(exitedTarget->toNode(), mouseEvent), + enteredTarget, 0, !exitedNodeHasCapturingAncestor); } }
diff --git a/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.cpp b/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.cpp index 2c65b2c3..7194e6e 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.cpp
@@ -168,70 +168,24 @@ instrumentingAgentsSet().remove(instrumentingAgents); } -InstrumentingAgents* instrumentingAgentsFor(LocalFrame* frame) -{ - return frame ? frame->instrumentingAgents() : nullptr; -} - -InstrumentingAgents* instrumentingAgentsFor(EventTarget* eventTarget) -{ - if (!eventTarget) - return 0; - return instrumentingAgentsFor(eventTarget->getExecutionContext()); -} - -InstrumentingAgents* instrumentingAgentsFor(LayoutObject* layoutObject) -{ - return instrumentingAgentsFor(layoutObject->frame()); -} - InstrumentingAgents* instrumentingAgentsFor(WorkerGlobalScope* workerGlobalScope) { if (!workerGlobalScope) - return 0; - return instrumentationForWorkerGlobalScope(workerGlobalScope); + return nullptr; + if (WorkerInspectorController* controller = workerGlobalScope->workerInspectorController()) + return controller->instrumentingAgents(); + return nullptr; } InstrumentingAgents* instrumentingAgentsForNonDocumentContext(ExecutionContext* context) { if (context->isWorkerGlobalScope()) - return instrumentationForWorkerGlobalScope(toWorkerGlobalScope(context)); - - if (context->isWorkletGlobalScope()) { - LocalFrame* frame = toMainThreadWorkletGlobalScope(context)->frame(); - if (frame) - return instrumentingAgentsFor(frame); - } - - return 0; + return instrumentingAgentsFor(toWorkerGlobalScope(context)); + if (context->isWorkletGlobalScope()) + return instrumentingAgentsFor(toMainThreadWorkletGlobalScope(context)->frame()); + return nullptr; } } // namespace InspectorInstrumentation -namespace InstrumentationEvents { -const char PaintSetup[] = "PaintSetup"; -const char Paint[] = "Paint"; -const char Layer[] = "Layer"; -const char RequestMainThreadFrame[] = "RequestMainThreadFrame"; -const char BeginFrame[] = "BeginFrame"; -const char ActivateLayerTree[] = "ActivateLayerTree"; -const char DrawFrame[] = "DrawFrame"; -const char EmbedderCallback[] = "EmbedderCallback"; -}; - -namespace InstrumentationEventArguments { -const char FrameId[] = "frameId"; -const char LayerId[] = "layerId"; -const char LayerTreeId[] = "layerTreeId"; -const char PageId[] = "pageId"; -const char CallbackName[] = "callbackName"; -}; - -InstrumentingAgents* instrumentationForWorkerGlobalScope(WorkerGlobalScope* workerGlobalScope) -{ - if (WorkerInspectorController* controller = workerGlobalScope->workerInspectorController()) - return controller->m_instrumentingAgents.get(); - return 0; -} - } // namespace blink
diff --git a/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.h b/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.h index 2a548f1..a0a4d31d 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.h +++ b/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.h
@@ -31,36 +31,15 @@ #ifndef InspectorInstrumentation_h #define InspectorInstrumentation_h -#include "bindings/core/v8/ScriptString.h" #include "core/CoreExport.h" -#include "core/animation/Animation.h" -#include "core/css/CSSSelector.h" -#include "core/css/CSSStyleDeclaration.h" -#include "core/css/CSSStyleSheet.h" -#include "core/dom/CharacterData.h" -#include "core/dom/Element.h" -#include "core/dom/ExecutionContext.h" -#include "core/events/NodeEventContext.h" +#include "core/dom/Document.h" +#include "core/dom/Node.h" #include "core/frame/LocalFrame.h" -#include "core/inspector/ConsoleAPITypes.h" -#include "core/layout/HitTestResult.h" -#include "core/layout/LayoutImage.h" -#include "core/page/ChromeClient.h" -#include "platform/network/EncodedFormData.h" -#include "platform/network/ResourceRequest.h" -#include "platform/network/WebSocketHandshakeRequest.h" -#include "platform/network/WebSocketHandshakeResponse.h" -#include "wtf/RefPtr.h" namespace blink { -class Document; -class EventTarget; -class ExecutionContext; class InstrumentingAgents; -class ThreadableLoaderClient; class WorkerGlobalScope; -class WorkerInspectorProxy; #define FAST_RETURN_IF_NO_FRONTENDS(value) if (!hasFrontends()) return value; @@ -110,49 +89,15 @@ CORE_EXPORT void registerInstrumentingAgents(InstrumentingAgents*); CORE_EXPORT void unregisterInstrumentingAgents(InstrumentingAgents*); -// Called from generated instrumentation code. -CORE_EXPORT InstrumentingAgents* instrumentingAgentsFor(LocalFrame*); -InstrumentingAgents* instrumentingAgentsFor(EventTarget*); -InstrumentingAgents* instrumentingAgentsFor(ExecutionContext*); -InstrumentingAgents* instrumentingAgentsFor(Document&); -InstrumentingAgents* instrumentingAgentsFor(Document*); -InstrumentingAgents* instrumentingAgentsFor(LayoutObject*); -InstrumentingAgents* instrumentingAgentsFor(Node*); -InstrumentingAgents* instrumentingAgentsFor(WorkerGlobalScope*); - -// Helper for the one above. -CORE_EXPORT InstrumentingAgents* instrumentingAgentsForNonDocumentContext(ExecutionContext*); - CORE_EXPORT extern const char kInspectorEmulateNetworkConditionsClientId[]; -} // namespace InspectorInstrumentation +// Called from generated instrumentation code. +CORE_EXPORT InstrumentingAgents* instrumentingAgentsFor(WorkerGlobalScope*); +CORE_EXPORT InstrumentingAgents* instrumentingAgentsForNonDocumentContext(ExecutionContext*); -namespace InstrumentationEvents { -extern const char PaintSetup[]; -extern const char Paint[]; -extern const char Layer[]; -extern const char RequestMainThreadFrame[]; -extern const char BeginFrame[]; -extern const char DrawFrame[]; -extern const char ActivateLayerTree[]; -extern const char EmbedderCallback[]; -}; - -namespace InstrumentationEventArguments { -extern const char FrameId[]; -extern const char LayerId[]; -extern const char LayerTreeId[]; -extern const char PageId[]; -extern const char CallbackName[]; -}; - -namespace InspectorInstrumentation { - -inline InstrumentingAgents* instrumentingAgentsFor(ExecutionContext* context) +inline InstrumentingAgents* instrumentingAgentsFor(LocalFrame* frame) { - if (!context) - return 0; - return context->isDocument() ? instrumentingAgentsFor(*toDocument(context)) : instrumentingAgentsForNonDocumentContext(context); + return frame ? frame->instrumentingAgents() : nullptr; } inline InstrumentingAgents* instrumentingAgentsFor(Document& document) @@ -165,28 +110,27 @@ inline InstrumentingAgents* instrumentingAgentsFor(Document* document) { - return document ? instrumentingAgentsFor(*document) : 0; + return document ? instrumentingAgentsFor(*document) : nullptr; } -inline InstrumentingAgents* instrumentingAgentsFor(CSSStyleSheet* styleSheet) +inline InstrumentingAgents* instrumentingAgentsFor(ExecutionContext* context) { - return styleSheet ? instrumentingAgentsFor(styleSheet->ownerDocument()) : 0; + if (!context) + return nullptr; + return context->isDocument() ? instrumentingAgentsFor(*toDocument(context)) : instrumentingAgentsForNonDocumentContext(context); } inline InstrumentingAgents* instrumentingAgentsFor(Node* node) { - return node ? instrumentingAgentsFor(node->document()) : 0; + return node ? instrumentingAgentsFor(node->document()) : nullptr; } -inline InstrumentingAgents* instrumentingAgentsFor(CSSStyleDeclaration* declaration) +inline InstrumentingAgents* instrumentingAgentsFor(EventTarget* eventTarget) { - return declaration ? instrumentingAgentsFor(declaration->parentStyleSheet()) : 0; + return eventTarget ? instrumentingAgentsFor(eventTarget->getExecutionContext()) : nullptr; } } // namespace InspectorInstrumentation - -InstrumentingAgents* instrumentationForWorkerGlobalScope(WorkerGlobalScope*); - } // namespace blink #include "core/InspectorInstrumentationInl.h"
diff --git a/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl b/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl index 0171d65..d7824ce 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl +++ b/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl
@@ -65,7 +65,16 @@ interface InspectorInstrumentation { +#include "core/animation/Animation.h" +#include "core/dom/CharacterData.h" #include "core/dom/PseudoElement.h" +#include "core/page/ChromeClient.h" + +class ThreadableLoaderClient; +class WebSocketHandshakeRequest; +class WebSocketHandshakeResponse; +class WorkerInspectorProxy; +class XMLHttpRequest; // We should call PageDebuggerAgent method first otherwise this method resets script cache and removes scripts executed by other agents. [PageRuntime, Page, Animation] @@ -144,7 +153,7 @@ void didResizeMainFrame(LocalFrame*); [LayerTree, Inline=FastReturn] - void didPaint([Keep] LayoutObject*, const GraphicsLayer*, GraphicsContext&, const LayoutRect&); + void didPaint(LocalFrame*, const GraphicsLayer*, GraphicsContext&, const LayoutRect&); [Resource, Inline=FastReturn] InspectorInstrumentationCookie willRecalculateStyle([Keep] Document*);
diff --git a/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp index c3d62c6..ee5d5e31 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp
@@ -190,7 +190,7 @@ frontend()->layerTreeDidChange(buildLayerTree()); } -void InspectorLayerTreeAgent::didPaint(LayoutObject*, const GraphicsLayer* graphicsLayer, GraphicsContext&, const LayoutRect& rect) +void InspectorLayerTreeAgent::didPaint(const GraphicsLayer* graphicsLayer, GraphicsContext&, const LayoutRect& rect) { // Should only happen for FrameView paints when compositing is off. Consider different instrumentation method for that. if (!graphicsLayer)
diff --git a/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.h b/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.h index c3dc533..00ea532 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.h +++ b/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.h
@@ -68,7 +68,7 @@ // Called from InspectorInstrumentation void layerTreeDidChange(); - void didPaint(LayoutObject*, const GraphicsLayer*, GraphicsContext&, const LayoutRect&); + void didPaint(const GraphicsLayer*, GraphicsContext&, const LayoutRect&); // Called from the front-end. void enable(ErrorString*) override;
diff --git a/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h b/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h index 9d1e9ab..6f6325a 100644 --- a/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h +++ b/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h
@@ -63,6 +63,8 @@ ~WorkerInspectorController(); DECLARE_TRACE(); + InstrumentingAgents* instrumentingAgents() const { return m_instrumentingAgents.get(); } + void connectFrontend(); void disconnectFrontend(); void dispatchMessageFromFrontend(const String&); @@ -70,7 +72,6 @@ private: WorkerInspectorController(WorkerGlobalScope*, PassOwnPtr<V8InspectorSession>); - friend InstrumentingAgents* instrumentationForWorkerGlobalScope(WorkerGlobalScope*); // InspectorRuntimeAgent::Client implementation. void resumeStartup() override;
diff --git a/third_party/WebKit/Source/core/layout/ColumnBalancer.cpp b/third_party/WebKit/Source/core/layout/ColumnBalancer.cpp index 45607bd..1ba0719 100644 --- a/third_party/WebKit/Source/core/layout/ColumnBalancer.cpp +++ b/third_party/WebKit/Source/core/layout/ColumnBalancer.cpp
@@ -10,15 +10,17 @@ namespace blink { -ColumnBalancer::ColumnBalancer(const MultiColumnFragmentainerGroup& group) - : m_group(group) +ColumnBalancer::ColumnBalancer(const LayoutMultiColumnSet& columnSet, LayoutUnit logicalTopInFlowThread, LayoutUnit logicalBottomInFlowThread) + : m_columnSet(columnSet) + , m_logicalTopInFlowThread(logicalTopInFlowThread) + , m_logicalBottomInFlowThread(logicalBottomInFlowThread) , m_previousBreakAfterValue(BreakAuto) { } void ColumnBalancer::traverse() { - traverseSubtree(*m_group.columnSet().flowThread()); + traverseSubtree(*columnSet().flowThread()); ASSERT(!flowThreadOffset()); } @@ -28,15 +30,15 @@ // Look for breaks between lines. for (const RootInlineBox* line = toLayoutBlockFlow(box).firstRootBox(); line; line = line->nextRootBox()) { LayoutUnit lineTopInFlowThread = m_flowThreadOffset + line->lineTopWithLeading(); - if (lineTopInFlowThread < group().logicalTopInFlowThread()) + if (lineTopInFlowThread < logicalTopInFlowThread()) continue; - if (lineTopInFlowThread >= group().logicalBottomInFlowThread()) + if (lineTopInFlowThread >= logicalBottomInFlowThread()) break; examineLine(*line); } } - const LayoutFlowThread* flowThread = group().columnSet().flowThread(); + const LayoutFlowThread* flowThread = columnSet().flowThread(); bool isHorizontalWritingMode = flowThread->isHorizontalWritingMode(); // Look for breaks between and inside block-level children. Even if this is a block flow with @@ -47,13 +49,13 @@ const LayoutBox& childBox = toLayoutBox(*child); LayoutRect overflowRect = childBox.layoutOverflowRect(); LayoutUnit childLogicalBottomWithOverflow = childBox.logicalTop() + (isHorizontalWritingMode ? overflowRect.maxY() : overflowRect.maxX()); - if (m_flowThreadOffset + childLogicalBottomWithOverflow <= group().logicalTopInFlowThread()) { - // This child is fully above the fragmentainer group we're examining. + if (m_flowThreadOffset + childLogicalBottomWithOverflow <= logicalTopInFlowThread()) { + // This child is fully above the flow thread portion we're examining. continue; } LayoutUnit childLogicalTopWithOverflow = childBox.logicalTop() + (isHorizontalWritingMode ? overflowRect.y() : overflowRect.x()); - if (m_flowThreadOffset + childLogicalTopWithOverflow >= group().logicalBottomInFlowThread()) { - // This child is fully below the fragmentainer group we're examining. We cannot just + if (m_flowThreadOffset + childLogicalTopWithOverflow >= logicalBottomInFlowThread()) { + // This child is fully below the flow thread portion we're examining. We cannot just // stop here, though, thanks to negative margins. So keep looking. continue; } @@ -77,10 +79,10 @@ } } -InitialColumnHeightFinder::InitialColumnHeightFinder(const MultiColumnFragmentainerGroup& group) - : ColumnBalancer(group) +InitialColumnHeightFinder::InitialColumnHeightFinder(const LayoutMultiColumnSet& columnSet, LayoutUnit logicalTopInFlowThread, LayoutUnit logicalBottomInFlowThread) + : ColumnBalancer(columnSet, logicalTopInFlowThread, logicalBottomInFlowThread) { - m_shortestStruts.resize(group.columnSet().usedColumnCount()); + m_shortestStruts.resize(columnSet.usedColumnCount()); for (auto& strut : m_shortestStruts) strut = LayoutUnit::max(); traverse(); @@ -93,7 +95,7 @@ LayoutUnit InitialColumnHeightFinder::initialMinimalBalancedHeight() const { unsigned index = contentRunIndexWithTallestColumns(); - LayoutUnit startOffset = index > 0 ? m_contentRuns[index - 1].breakOffset() : group().logicalTopInFlowThread(); + LayoutUnit startOffset = index > 0 ? m_contentRuns[index - 1].breakOffset() : logicalTopInFlowThread(); return m_contentRuns[index].columnLogicalHeight(startOffset); } @@ -157,11 +159,10 @@ void InitialColumnHeightFinder::recordStrutBeforeOffset(LayoutUnit offsetInFlowThread, LayoutUnit strut) { - const LayoutMultiColumnSet& columnSet = group().columnSet(); - ASSERT(columnSet.usedColumnCount() >= 1); - unsigned columnCount = columnSet.usedColumnCount(); + ASSERT(columnSet().usedColumnCount() >= 1); + unsigned columnCount = columnSet().usedColumnCount(); ASSERT(m_shortestStruts.size() == columnCount); - unsigned index = group().columnIndexAtOffset(offsetInFlowThread - strut, MultiColumnFragmentainerGroup::AssumeNewColumns); + unsigned index = groupAtOffset(offsetInFlowThread).columnIndexAtOffset(offsetInFlowThread - strut, MultiColumnFragmentainerGroup::AssumeNewColumns); if (index >= columnCount) return; m_shortestStruts[index] = std::min(m_shortestStruts[index], strut); @@ -169,8 +170,8 @@ LayoutUnit InitialColumnHeightFinder::spaceUsedByStrutsAt(LayoutUnit offsetInFlowThread) const { - unsigned stopBeforeColumn = group().columnIndexAtOffset(offsetInFlowThread, MultiColumnFragmentainerGroup::AssumeNewColumns) + 1; - stopBeforeColumn = std::min(stopBeforeColumn, group().columnSet().usedColumnCount()); + unsigned stopBeforeColumn = groupAtOffset(offsetInFlowThread).columnIndexAtOffset(offsetInFlowThread, MultiColumnFragmentainerGroup::AssumeNewColumns) + 1; + stopBeforeColumn = std::min(stopBeforeColumn, columnSet().usedColumnCount()); ASSERT(stopBeforeColumn <= m_shortestStruts.size()); LayoutUnit totalStrutSpace; for (unsigned i = 0; i < stopBeforeColumn; i++) { @@ -187,7 +188,7 @@ return; // Append another item as long as we haven't exceeded used column count. What ends up in the // overflow area shouldn't affect column balancing. - if (m_contentRuns.size() < group().columnSet().usedColumnCount()) + if (m_contentRuns.size() < columnSet().usedColumnCount()) m_contentRuns.append(ContentRun(endOffsetInFlowThread)); } @@ -195,7 +196,7 @@ { unsigned indexWithLargestHeight = 0; LayoutUnit largestHeight; - LayoutUnit previousOffset = group().logicalTopInFlowThread(); + LayoutUnit previousOffset = logicalTopInFlowThread(); size_t runCount = m_contentRuns.size(); ASSERT(runCount); for (size_t i = 0; i < runCount; i++) { @@ -212,9 +213,9 @@ void InitialColumnHeightFinder::distributeImplicitBreaks() { - // Insert a final content run to encompass all content. This will include overflow if this is - // the last group in the multicol container. - addContentRun(group().logicalBottomInFlowThread()); + // Insert a final content run to encompass all content. This will include overflow if we're at + // the end of the multicol container. + addContentRun(logicalBottomInFlowThread()); unsigned columnCount = m_contentRuns.size(); // If there is room for more breaks (to reach the used value of column-count), imagine that we @@ -223,15 +224,15 @@ // column count by one and shrink its columns' height. Repeat until we have the desired total // number of breaks. The largest column height among the runs will then be the initial column // height for the balancer to use. - while (columnCount < group().columnSet().usedColumnCount()) { + while (columnCount < columnSet().usedColumnCount()) { unsigned index = contentRunIndexWithTallestColumns(); m_contentRuns[index].assumeAnotherImplicitBreak(); columnCount++; } } -MinimumSpaceShortageFinder::MinimumSpaceShortageFinder(const MultiColumnFragmentainerGroup& group) - : ColumnBalancer(group) +MinimumSpaceShortageFinder::MinimumSpaceShortageFinder(const LayoutMultiColumnSet& columnSet, LayoutUnit logicalTopInFlowThread, LayoutUnit logicalBottomInFlowThread) + : ColumnBalancer(columnSet, logicalTopInFlowThread, logicalBottomInFlowThread) , m_minimumSpaceShortage(LayoutUnit::max()) , m_pendingStrut(LayoutUnit::min()) , m_forcedBreaksCount(0) @@ -269,14 +270,15 @@ if (breakability != LayoutBox::ForbidBreaks) { // See if this breakable box crosses column boundaries. LayoutUnit bottomInFlowThread = flowThreadOffset() + box.logicalHeight(); + const MultiColumnFragmentainerGroup& group = groupAtOffset(flowThreadOffset()); if (isFirstAfterBreak(flowThreadOffset()) - || group().columnLogicalTopForOffset(flowThreadOffset()) != group().columnLogicalTopForOffset(bottomInFlowThread)) { + || group.columnLogicalTopForOffset(flowThreadOffset()) != group.columnLogicalTopForOffset(bottomInFlowThread)) { // If the child crosses a column boundary, record space shortage, in case nothing // inside it has already done so. The column balancer needs to know by how much it // has to stretch the columns to make more content fit. If no breaks are reported // (but do occur), the balancer will have no clue. Only measure the space after the // last column boundary, in case it crosses more than one. - LayoutUnit spaceUsedInLastColumn = bottomInFlowThread - group().columnLogicalTopForOffset(bottomInFlowThread); + LayoutUnit spaceUsedInLastColumn = bottomInFlowThread - group.columnLogicalTopForOffset(bottomInFlowThread); recordSpaceShortage(spaceUsedInLastColumn); } } @@ -288,10 +290,12 @@ if (!flowThread || flowThread->isLayoutPagedFlowThread()) return; for (const LayoutMultiColumnSet* columnSet = flowThread->firstMultiColumnSet(); columnSet; columnSet = columnSet->nextSiblingMultiColumnSet()) { - for (const MultiColumnFragmentainerGroup& row : columnSet->fragmentainerGroups()) { - MinimumSpaceShortageFinder innerFinder(row); - recordSpaceShortage(innerFinder.minimumSpaceShortage()); - } + // Establish an inner shortage finder for this column set in the inner multicol + // container. We need to let it walk through all fragmentainer groups in one go, or we'd + // miss the column boundaries between each fragmentainer group. We need to record space + // shortage there too. + MinimumSpaceShortageFinder innerFinder(*columnSet, columnSet->logicalTopInFlowThread(), columnSet->logicalBottomInFlowThread()); + recordSpaceShortage(innerFinder.minimumSpaceShortage()); } } @@ -303,7 +307,7 @@ // The previous break was before a breakable block. Here's the first piece of unbreakable // content after / inside that block. We want to record the distance from the top of the column // to the bottom of this box as space shortage. - LayoutUnit logicalOffsetFromCurrentColumn = flowThreadOffset() - group().columnLogicalTopForOffset(flowThreadOffset()); + LayoutUnit logicalOffsetFromCurrentColumn = offsetFromColumnLogicalTop(flowThreadOffset()); recordSpaceShortage(logicalOffsetFromCurrentColumn + box.logicalHeight() - m_pendingStrut); m_pendingStrut = LayoutUnit::min(); } @@ -317,7 +321,7 @@ // The previous break was before a breakable block. Here's the first line after / inside // that block. We want to record the distance from the top of the column to the bottom of // this box as space shortage. - LayoutUnit logicalOffsetFromCurrentColumn = lineTopInFlowThread - group().columnLogicalTopForOffset(lineTopInFlowThread); + LayoutUnit logicalOffsetFromCurrentColumn = offsetFromColumnLogicalTop(lineTopInFlowThread); recordSpaceShortage(logicalOffsetFromCurrentColumn + lineHeight - m_pendingStrut); m_pendingStrut = LayoutUnit::min(); return; @@ -329,9 +333,10 @@ // Even if the line box itself fits fine inside a column, some content may overflow the line // box bottom (due to restrictive line-height, for instance). We should check if some portion // of said overflow ends up in the next column. That counts as space shortage. + const MultiColumnFragmentainerGroup& group = groupAtOffset(lineTopInFlowThread); LayoutUnit lineBottomWithOverflow = lineTopInFlowThread + line.lineBottom() - lineTop; - if (group().columnLogicalTopForOffset(lineTopInFlowThread) != group().columnLogicalTopForOffset(lineBottomWithOverflow)) { - LayoutUnit shortage = lineBottomWithOverflow - group().columnLogicalTopForOffset(lineBottomWithOverflow); + if (group.columnLogicalTopForOffset(lineTopInFlowThread) != group.columnLogicalTopForOffset(lineBottomWithOverflow)) { + LayoutUnit shortage = lineBottomWithOverflow - group.columnLogicalTopForOffset(lineBottomWithOverflow); recordSpaceShortage(shortage); } }
diff --git a/third_party/WebKit/Source/core/layout/ColumnBalancer.h b/third_party/WebKit/Source/core/layout/ColumnBalancer.h index 2a4976e..4afa578 100644 --- a/third_party/WebKit/Source/core/layout/ColumnBalancer.h +++ b/third_party/WebKit/Source/core/layout/ColumnBalancer.h
@@ -2,18 +2,34 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "core/layout/MultiColumnFragmentainerGroup.h" +#include "core/layout/LayoutMultiColumnSet.h" namespace blink { -// A column balancer traverses the portion of the subtree of a flow thread that belongs to a given -// fragmentainer group, in order to collect certain data to be used for column balancing. This is an -// abstract class that just walks the subtree and leaves it to subclasses to actualy collect data. +// A column balancer traverses a portion of the subtree of a flow thread that belongs to one or +// more fragmentainer groups within one column set, in order to collect certain data to be used for +// column balancing. This is an abstract class that just walks the subtree and leaves it to +// subclasses to actually collect data. class ColumnBalancer { protected: - ColumnBalancer(const MultiColumnFragmentainerGroup&); + ColumnBalancer(const LayoutMultiColumnSet&, LayoutUnit logicalTopInFlowThread, LayoutUnit logicalBottomInFlowThread); - const MultiColumnFragmentainerGroup& group() const { return m_group; } + const LayoutMultiColumnSet& columnSet() const { return m_columnSet; } + + // The flow thread portion we're examining. It may be that of the entire column set, or just of + // a fragmentainer group. + const LayoutUnit logicalTopInFlowThread() const { return m_logicalTopInFlowThread; } + const LayoutUnit logicalBottomInFlowThread() const { return m_logicalBottomInFlowThread; } + + const MultiColumnFragmentainerGroup& groupAtOffset(LayoutUnit offsetInFlowThread) const + { + return m_columnSet.fragmentainerGroupAtFlowThreadOffset(offsetInFlowThread); + } + + LayoutUnit offsetFromColumnLogicalTop(LayoutUnit offsetInFlowThread) const + { + return offsetInFlowThread - groupAtOffset(offsetInFlowThread).columnLogicalTopForOffset(offsetInFlowThread); + } // Flow thread offset for the layout object that we're currently examining. LayoutUnit flowThreadOffset() const { return m_flowThreadOffset; } @@ -21,41 +37,42 @@ EBreak previousBreakAfterValue() const { return m_previousBreakAfterValue; } // Return true if the specified offset is at the top of a column, as long as it's not the first - // column in the fragmentainer group. + // column in the flow thread portion. bool isFirstAfterBreak(LayoutUnit flowThreadOffset) const { - if (flowThreadOffset != m_group.columnLogicalTopForOffset(flowThreadOffset)) - return false; // Not at the top of a column. - // The first column in the fragmentainer group is either not after any break at all, or - // after a break that belongs to the previous fragmentainer group. - return flowThreadOffset > m_group.logicalTopInFlowThread(); + if (flowThreadOffset <= m_logicalTopInFlowThread) { + // The first column is either not after any break at all, or after a break in a + // previous fragmentainer group. + return false; + } + return flowThreadOffset == groupAtOffset(flowThreadOffset).columnLogicalTopForOffset(flowThreadOffset); } bool isLogicalTopWithinBounds(LayoutUnit logicalTopInFlowThread) const { - return logicalTopInFlowThread >= m_group.logicalTopInFlowThread() - && logicalTopInFlowThread < m_group.logicalBottomInFlowThread(); + return logicalTopInFlowThread >= m_logicalTopInFlowThread + && logicalTopInFlowThread < m_logicalBottomInFlowThread; } bool isLogicalBottomWithinBounds(LayoutUnit logicalBottomInFlowThread) const { - return logicalBottomInFlowThread > m_group.logicalTopInFlowThread() - && logicalBottomInFlowThread <= m_group.logicalBottomInFlowThread(); + return logicalBottomInFlowThread > m_logicalTopInFlowThread + && logicalBottomInFlowThread <= m_logicalBottomInFlowThread; } // Examine and collect column balancing data from a layout box that has been found to intersect - // with this fragmentainer group. Does not recurse into children. flowThreadOffset() will - // return the offset from |box| to the flow thread. Two hooks are provided here. The first one - // is called right after entering and before traversing the subtree of the box, and the second - // one right after having traversed the subtree. + // with the flow thread portion we're examining. Does not recurse into + // children. flowThreadOffset() will return the offset from |box| to the flow thread. Two hooks + // are provided here. The first one is called right after entering and before traversing the + // subtree of the box, and the second one right after having traversed the subtree. virtual void examineBoxAfterEntering(const LayoutBox&) = 0; virtual void examineBoxBeforeLeaving(const LayoutBox&) = 0; // Examine and collect column balancing data from a line that has been found to intersect with - // this fragmentainer group. Does not recurse into layout objects on that line. + // the flow thread portion. Does not recurse into layout objects on that line. virtual void examineLine(const RootInlineBox&) = 0; - // Examine and collect column balancing data for everything in the fragmentainer group. Will + // Examine and collect column balancing data for everything in the flow thread portion. Will // trigger calls to examineBoxAfterEntering(), examineBoxBeforeLeaving() and examineLine() for // interesting boxes and lines. void traverse(); @@ -63,7 +80,10 @@ private: void traverseSubtree(const LayoutBox&); - const MultiColumnFragmentainerGroup& m_group; + const LayoutMultiColumnSet& m_columnSet; + const LayoutUnit m_logicalTopInFlowThread; + const LayoutUnit m_logicalBottomInFlowThread; + LayoutUnit m_flowThreadOffset; // The break-after value from the previous in-flow block-level object to be joined with the @@ -81,7 +101,7 @@ // of this class, named MinimumSpaceShortageFinder. class InitialColumnHeightFinder final : public ColumnBalancer { public: - InitialColumnHeightFinder(const MultiColumnFragmentainerGroup&); + InitialColumnHeightFinder(const LayoutMultiColumnSet&, LayoutUnit logicalTopInFlowThread, LayoutUnit logicalBottomInFlowThread); LayoutUnit initialMinimalBalancedHeight() const; @@ -171,7 +191,7 @@ // space shortage after having laid out with the current column height. class MinimumSpaceShortageFinder final : public ColumnBalancer { public: - MinimumSpaceShortageFinder(const MultiColumnFragmentainerGroup&); + MinimumSpaceShortageFinder(const LayoutMultiColumnSet&, LayoutUnit logicalTopInFlowThread, LayoutUnit logicalBottomInFlowThread); LayoutUnit minimumSpaceShortage() const { return m_minimumSpaceShortage; } unsigned forcedBreaksCount() const { return m_forcedBreaksCount; }
diff --git a/third_party/WebKit/Source/core/layout/LayoutBlock.cpp b/third_party/WebKit/Source/core/layout/LayoutBlock.cpp index 5b1bf91d..b1cd8da 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBlock.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBlock.cpp
@@ -1629,14 +1629,13 @@ // TODO(pdr): We should also check for css clip in the !isSelfPaintingLayer // case, similar to overflow clip below. if (hasOverflowClip() && !hasSelfPaintingLayer()) { + if (!locationInContainer.intersects(overflowClipRect(accumulatedOffset, IncludeOverlayScrollbarSize))) + return false; if (style()->hasBorderRadius()) { LayoutRect borderRect = borderBoxRect(); borderRect.moveBy(accumulatedOffset); if (!locationInContainer.intersects(style()->getRoundedInnerBorderFor(borderRect))) return false; - } else { - if (!locationInContainer.intersects(overflowClipRect(accumulatedOffset, IncludeOverlayScrollbarSize))) - return false; } }
diff --git a/third_party/WebKit/Source/core/layout/LayoutBox.cpp b/third_party/WebKit/Source/core/layout/LayoutBox.cpp index 1731bfdc..007c6f9 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBox.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBox.cpp
@@ -4174,7 +4174,7 @@ static bool logicalWidthIsResolvable(const LayoutBox& layoutBox) { const LayoutBox* box = &layoutBox; - while (!box->isLayoutView() && !box->isOutOfFlowPositioned() + while (!box->isLayoutView() && !box->isFloatingOrOutOfFlowPositioned() && (box->style()->logicalWidth().isAuto() || box->isAnonymousBlock()) && !box->hasOverrideContainingBlockLogicalWidth()) box = box->containingBlock();
diff --git a/third_party/WebKit/Source/core/layout/LayoutGrid.cpp b/third_party/WebKit/Source/core/layout/LayoutGrid.cpp index cfde1c7..d21c92d 100644 --- a/third_party/WebKit/Source/core/layout/LayoutGrid.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutGrid.cpp
@@ -1969,17 +1969,15 @@ case GridAxisCenter: { size_t childEndLine = rowsSpan.endLine(); LayoutUnit endOfRow = m_rowPositions[childEndLine]; - // m_rowPositions include gutters so we need to subtract them to get the actual end position for a given - // row (this does not have to be done for the last track as there are no more m_rowPositions after it) + // m_rowPositions include distribution offset (because of content alignment) and gutters + // so we need to subtract them to get the actual end position for a given row + // (this does not have to be done for the last track as there are no more m_columnPositions after it). LayoutUnit trackGap = guttersSize(ForRows, 2); - if (childEndLine < m_rowPositions.size() - 1) + if (childEndLine < m_rowPositions.size() - 1) { endOfRow -= trackGap; - LayoutUnit childBreadth = child.logicalHeight() + child.marginLogicalHeight(); - // The track's start and end lines may be not adjacent because of content alignment, so we assume the stored - // lines are all start plus a content-alignment distribution offset. - // We must subtract last line's offset because is not part of the track the items belongs to. - if (childEndLine - childStartLine > 1 && childEndLine < m_rowPositions.size() - 1) endOfRow -= m_offsetBetweenRows; + } + LayoutUnit childBreadth = child.logicalHeight() + child.marginLogicalHeight(); OverflowAlignment overflow = child.styleRef().resolvedAlignment(styleRef(), ItemPositionStretch).overflow(); LayoutUnit offsetFromStartPosition = computeOverflowAlignmentOffset(overflow, endOfRow - startOfRow, childBreadth); return startPosition + (axisPosition == GridAxisEnd ? offsetFromStartPosition : offsetFromStartPosition / 2); @@ -2006,17 +2004,15 @@ case GridAxisCenter: { size_t childEndLine = columnsSpan.endLine(); LayoutUnit endOfColumn = m_columnPositions[childEndLine]; - // m_columnPositions include gutters so we need to subtract them to get the actual end position for a given - // column (this does not have to be done for the last track as there are no more m_columnPositions after it) + // m_columnPositions include distribution offset (because of content alignment) and gutters + // so we need to subtract them to get the actual end position for a given column + // (this does not have to be done for the last track as there are no more m_columnPositions after it). LayoutUnit trackGap = guttersSize(ForColumns, 2); - if (childEndLine < m_columnPositions.size() - 1) + if (childEndLine < m_columnPositions.size() - 1) { endOfColumn -= trackGap; - LayoutUnit childBreadth = child.logicalWidth() + child.marginLogicalWidth(); - // The track's start and end lines may be not adjacent because of content alignment, so we assume the stored - // lines are all start plus a content-alignment distribution offset. - // We must subtract last line's offset because is not part of the track the items belongs to. - if (childEndLine - childStartLine > 1 && childEndLine < m_columnPositions.size() - 1) endOfColumn -= m_offsetBetweenColumns; + } + LayoutUnit childBreadth = child.logicalWidth() + child.marginLogicalWidth(); LayoutUnit offsetFromStartPosition = computeOverflowAlignmentOffset(child.styleRef().justifySelfOverflowAlignment(), endOfColumn - startOfColumn, childBreadth); return startPosition + (axisPosition == GridAxisEnd ? offsetFromStartPosition : offsetFromStartPosition / 2); }
diff --git a/third_party/WebKit/Source/core/layout/LayoutMultiColumnFlowThread.cpp b/third_party/WebKit/Source/core/layout/LayoutMultiColumnFlowThread.cpp index d79383a9..1e84338 100644 --- a/third_party/WebKit/Source/core/layout/LayoutMultiColumnFlowThread.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutMultiColumnFlowThread.cpp
@@ -510,7 +510,21 @@ // We have run out of columns here, so we need to add at least one more row to hold more // columns. + LayoutMultiColumnFlowThread* enclosingFlowThread = enclosingFragmentationContext->associatedFlowThread(); do { + if (enclosingFlowThread) { + // When we add a new row here, it implicitly means that we're inserting another + // column in our enclosing multicol container. That in turn may mean that we've run + // out of columns there too. Need to insert additional rows in ancestral multicol + // containers before doing it in the descendants, in order to get the height + // constraints right down there. + const MultiColumnFragmentainerGroup& lastRow = columnSet->lastFragmentainerGroup(); + // The top offset where where the new fragmentainer group will start in this column + // set, converted to the coordinate space of the enclosing multicol container. + LayoutUnit logicalOffsetInOuter = lastRow.blockOffsetInEnclosingFragmentationContext() + lastRow.logicalHeight(); + enclosingFlowThread->appendNewFragmentainerGroupIfNeeded(logicalOffsetInOuter, AssociateWithLatterPage); + } + const MultiColumnFragmentainerGroup& newRow = columnSet->appendNewFragmentainerGroup(); // Zero-height rows should really not occur here, but if it does anyway, break, so that // we don't get stuck in an infinite loop. @@ -518,14 +532,6 @@ if (newRow.logicalHeight() <= 0) break; } while (!columnSet->hasFragmentainerGroupForColumnAt(offsetInFlowThread, pageBoundaryRule)); - - if (LayoutMultiColumnFlowThread* enclosingFlowThread = enclosingFragmentationContext->associatedFlowThread()) { - // When we add a new row here, it implicitly means that we're inserting another column - // in our enclosing multicol container. That in turn may mean that we've run out of - // columns there too. - const MultiColumnFragmentainerGroup& lastRow = columnSet->lastFragmentainerGroup(); - enclosingFlowThread->appendNewFragmentainerGroupIfNeeded(lastRow.blockOffsetInEnclosingFragmentationContext(), AssociateWithLatterPage); - } } }
diff --git a/third_party/WebKit/Source/core/layout/LayoutTheme.cpp b/third_party/WebKit/Source/core/layout/LayoutTheme.cpp index 80427ac..e5320a0 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTheme.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTheme.cpp
@@ -406,10 +406,6 @@ case TextFieldPart: return style.hasAuthorBackground() || style.hasAuthorBorder() || style.boxShadow(); - case SliderHorizontalPart: - case SliderVerticalPart: - return style.boxShadow(); - default: return false; }
diff --git a/third_party/WebKit/Source/core/layout/MultiColumnFragmentainerGroup.cpp b/third_party/WebKit/Source/core/layout/MultiColumnFragmentainerGroup.cpp index d743aac8..e2fae00 100644 --- a/third_party/WebKit/Source/core/layout/MultiColumnFragmentainerGroup.cpp +++ b/third_party/WebKit/Source/core/layout/MultiColumnFragmentainerGroup.cpp
@@ -75,7 +75,7 @@ // containing column set, in case there is an outer multicol container that also needs // to balance. After having calculated the initial column height, the multicol container // needs another layout pass with the column height that we just calculated. - InitialColumnHeightFinder initialHeightFinder(*this); + InitialColumnHeightFinder initialHeightFinder(columnSet(), logicalTopInFlowThread(), logicalBottomInFlowThread()); LayoutUnit tallestUnbreakableLogicalHeight = initialHeightFinder.tallestUnbreakableLogicalHeight(); m_columnSet.propagateTallestUnbreakableLogicalHeight(tallestUnbreakableLogicalHeight); newColumnHeight = std::max(initialHeightFinder.initialMinimalBalancedHeight(), tallestUnbreakableLogicalHeight); @@ -336,7 +336,7 @@ return m_columnHeight; } - MinimumSpaceShortageFinder shortageFinder(*this); + MinimumSpaceShortageFinder shortageFinder(columnSet(), logicalTopInFlowThread(), logicalBottomInFlowThread()); if (shortageFinder.forcedBreaksCount() + 1 >= m_columnSet.usedColumnCount()) { // Too many forced breaks to allow any implicit breaks. Initial balancing should already
diff --git a/third_party/WebKit/Source/core/layout/compositing/CompositedLayerMapping.cpp b/third_party/WebKit/Source/core/layout/compositing/CompositedLayerMapping.cpp index f15c88f..9b875d2 100644 --- a/third_party/WebKit/Source/core/layout/compositing/CompositedLayerMapping.cpp +++ b/third_party/WebKit/Source/core/layout/compositing/CompositedLayerMapping.cpp
@@ -1142,6 +1142,12 @@ paintPhase |= GraphicsLayerPaintForeground; m_scrollingContentsLayer->setPaintingPhase(paintPhase); } + if (m_foregroundLayer) { + GraphicsLayerPaintingPhase paintPhase = GraphicsLayerPaintForeground; + if (m_scrollingContentsLayer) + paintPhase |= GraphicsLayerPaintOverflowContents; + m_foregroundLayer->setPaintingPhase(paintPhase); + } } void CompositedLayerMapping::updateContentsRect() @@ -1523,7 +1529,6 @@ if (needsForegroundLayer) { if (!m_foregroundLayer) { m_foregroundLayer = createGraphicsLayer(CompositingReasonLayerForForeground); - m_foregroundLayer->setPaintingPhase(GraphicsLayerPaintForeground); layerChanged = true; } } else if (m_foregroundLayer) { @@ -2358,7 +2363,7 @@ } else if (isScrollableAreaLayer(graphicsLayer)) { paintScrollableArea(graphicsLayer, context, interestRect); } - InspectorInstrumentation::didPaint(m_owningLayer.layoutObject(), graphicsLayer, context, LayoutRect(interestRect)); + InspectorInstrumentation::didPaint(m_owningLayer.layoutObject()->frame(), graphicsLayer, context, LayoutRect(interestRect)); #if ENABLE(ASSERT) if (Page* page = layoutObject()->frame()->page()) page->setIsPainting(false);
diff --git a/third_party/WebKit/Source/core/layout/compositing/CompositedLayerMappingTest.cpp b/third_party/WebKit/Source/core/layout/compositing/CompositedLayerMappingTest.cpp index 61a061aa..9c66cce 100644 --- a/third_party/WebKit/Source/core/layout/compositing/CompositedLayerMappingTest.cpp +++ b/third_party/WebKit/Source/core/layout/compositing/CompositedLayerMappingTest.cpp
@@ -601,4 +601,29 @@ EXPECT_RECT_EQ(IntRect(0, 0, 500, 7500), recomputeInterestRect(frameDocument.view()->layoutView()->enclosingLayer()->graphicsLayerBacking())); } +TEST_F(CompositedLayerMappingTest, ScrollingContentsAndForegroundLayerPaintingPhase) +{ + document().frame()->settings()->setPreferCompositingToLCDTextEnabled(true); + setBodyInnerHTML( + "<div id='container' style='position: relative; z-index: 1; overflow: scroll; width: 300px; height: 300px'>" + " <div id='negative-composited-child' style='background-color: red; width: 1px; height: 1px; position: absolute; backface-visibility: hidden; z-index: -1'></div>" + " <div style='background-color: blue; width: 2000px; height: 2000px; position: relative; top: 10px'></div>" + "</div>"); + + CompositedLayerMapping* mapping = toLayoutBlock(getLayoutObjectByElementId("container"))->layer()->compositedLayerMapping(); + ASSERT_TRUE(mapping->scrollingContentsLayer()); + EXPECT_EQ(static_cast<GraphicsLayerPaintingPhase>(GraphicsLayerPaintOverflowContents | GraphicsLayerPaintCompositedScroll), mapping->scrollingContentsLayer()->paintingPhase()); + ASSERT_TRUE(mapping->foregroundLayer()); + EXPECT_EQ(static_cast<GraphicsLayerPaintingPhase>(GraphicsLayerPaintForeground | GraphicsLayerPaintOverflowContents), mapping->foregroundLayer()->paintingPhase()); + + Element* negativeCompositedChild = document().getElementById("negative-composited-child"); + negativeCompositedChild->parentNode()->removeChild(negativeCompositedChild); + document().view()->updateAllLifecyclePhases(); + + mapping = toLayoutBlock(getLayoutObjectByElementId("container"))->layer()->compositedLayerMapping(); + ASSERT_TRUE(mapping->scrollingContentsLayer()); + EXPECT_EQ(static_cast<GraphicsLayerPaintingPhase>(GraphicsLayerPaintOverflowContents | GraphicsLayerPaintCompositedScroll | GraphicsLayerPaintForeground), mapping->scrollingContentsLayer()->paintingPhase()); + EXPECT_FALSE(mapping->foregroundLayer()); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/layout/line/BreakingContextInlineHeaders.h b/third_party/WebKit/Source/core/layout/line/BreakingContextInlineHeaders.h index b8f2a40..81a80cb5 100644 --- a/third_party/WebKit/Source/core/layout/line/BreakingContextInlineHeaders.h +++ b/third_party/WebKit/Source/core/layout/line/BreakingContextInlineHeaders.h
@@ -660,10 +660,12 @@ float lastSpaceWordSpacing = 0; float wordSpacingForWordMeasurement = 0; + float widthFromLastBreakingOpportunity = m_width.uncommittedWidth(); float charWidth = 0; // Auto-wrapping text should wrap in the middle of a word only if it could not wrap before the word, // which is only possible if the word is the first thing on the line, that is, if |w| is zero. bool breakWords = m_currentStyle->breakWords() && ((m_autoWrap && !m_width.committedWidth()) || m_currWS == PRE); + bool midWordBreak = false; bool breakAll = m_currentStyle->wordBreak() == BreakAllWordBreak && m_autoWrap; bool keepAll = m_currentStyle->wordBreak() == KeepAllWordBreak && m_autoWrap; bool prohibitBreakInside = m_currentStyle->hasTextCombine() && layoutText.isCombineText() && LineLayoutTextCombine(layoutText).isCombined(); @@ -726,13 +728,25 @@ bool applyWordSpacing = false; + // Determine if we should try breaking in the middle of a word. + if (breakWords && !midWordBreak && !U16_IS_TRAIL(c)) { + widthFromLastBreakingOpportunity += charWidth; + bool midWordBreakIsBeforeSurrogatePair = U16_IS_LEAD(c) && m_current.offset() + 1 < layoutText.textLength() && U16_IS_TRAIL(layoutText.uncheckedCharacterAt(m_current.offset() + 1)); + charWidth = textWidth(layoutText, m_current.offset(), midWordBreakIsBeforeSurrogatePair ? 2 : 1, font, m_width.committedWidth() + widthFromLastBreakingOpportunity, m_collapseWhiteSpace); + // Measure up to 2em overflow since ligatures/kerning can shorten + // the width as we add more characters. rewindToMidWordBreak() can + // measure the accurate mid-word break point then. + midWordBreak = m_width.committedWidth() + widthFromLastBreakingOpportunity + charWidth > m_width.availableWidth() + + 2 * font.getFontDescription().computedSize(); + } + // Determine if we are in the whitespace between words. int nextBreakablePosition = m_current.nextBreakablePosition(); bool betweenWords = c == newlineCharacter || (m_currWS != PRE && !m_atStart && m_layoutTextInfo.m_lineBreakIterator.isBreakable(m_current.offset(), nextBreakablePosition, lineBreakType)); m_current.setNextBreakablePosition(nextBreakablePosition); // If we're in the middle of a word or at the start of a new one and can't break there, then continue to the next character. - if (!betweenWords) { + if (!betweenWords && !midWordBreak) { if (m_ignoringSpaces) { // Stop ignoring spaces and begin at this // new point. @@ -771,7 +785,7 @@ WordMeasurement& wordMeasurement = calculateWordWidth(wordMeasurements, layoutText, lastSpace, lastWidthMeasurement, wordSpacingForWordMeasurement, font, wordTrailingSpaceWidth, c); lastWidthMeasurement += lastSpaceWordSpacing; - bool midWordBreak = false; + midWordBreak = false; if (canBreakMidWord && !m_width.fitsOnLine(lastWidthMeasurement) && rewindToMidWordBreak(layoutText, style, font, breakAll, wordMeasurement)) { lastWidthMeasurement = wordMeasurement.width; @@ -816,6 +830,7 @@ // opportunity to break after a word. if (m_autoWrap && betweenWords) { m_width.commit(); + widthFromLastBreakingOpportunity = 0; m_lineBreak.moveTo(m_current.getLineLayoutItem(), m_current.offset(), m_current.nextBreakablePosition()); breakWords = false; canBreakMidWord = breakAll; @@ -856,7 +871,7 @@ float lastWidthMeasurement = 0; wordMeasurement.startOffset = lastSpace; wordMeasurement.endOffset = m_current.offset(); - bool midWordBreak = false; + midWordBreak = false; if (!m_ignoringSpaces) { lastWidthMeasurement = textWidth(layoutText, lastSpace, m_current.offset() - lastSpace, font, m_width.currentWidth(), m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, &wordMeasurement.glyphBounds); wordMeasurement.width = lastWidthMeasurement + wordSpacingForWordMeasurement;
diff --git a/third_party/WebKit/Source/core/paint/FilterEffectBuilder.cpp b/third_party/WebKit/Source/core/paint/FilterEffectBuilder.cpp index 8d231ac..462d852 100644 --- a/third_party/WebKit/Source/core/paint/FilterEffectBuilder.cpp +++ b/third_party/WebKit/Source/core/paint/FilterEffectBuilder.cpp
@@ -231,7 +231,7 @@ } case FilterOperation::BOX_REFLECT: { BoxReflectFilterOperation* boxReflectOperation = toBoxReflectFilterOperation(filterOperation); - effect = FEBoxReflect::create(parentFilter, boxReflectOperation->direction(), boxReflectOperation->offset()); + effect = FEBoxReflect::create(parentFilter, boxReflectOperation->reflection()); break; } default:
diff --git a/third_party/WebKit/Source/core/paint/FilterPainter.cpp b/third_party/WebKit/Source/core/paint/FilterPainter.cpp index 7665a1ff..9e399bb7 100644 --- a/third_party/WebKit/Source/core/paint/FilterPainter.cpp +++ b/third_party/WebKit/Source/core/paint/FilterPainter.cpp
@@ -38,7 +38,7 @@ SkiaImageFilterBuilder builder; lastEffect->determineFilterPrimitiveSubregion(MapRectForward); - RefPtr<SkImageFilter> imageFilter = builder.build(lastEffect, ColorSpaceDeviceRGB); + sk_sp<SkImageFilter> imageFilter = builder.build(lastEffect, ColorSpaceDeviceRGB); if (!imageFilter) return; @@ -76,7 +76,7 @@ visualBounds.moveBy(-offsetFromRoot); layer.convertFromFlowThreadToVisualBoundingBoxInAncestor(paintingInfo.rootLayer, visualBounds); } - context.getPaintController().createAndAppend<BeginFilterDisplayItem>(*m_layoutObject, imageFilter, FloatRect(visualBounds), compositorFilterOperations.release()); + context.getPaintController().createAndAppend<BeginFilterDisplayItem>(*m_layoutObject, std::move(imageFilter), FloatRect(visualBounds), compositorFilterOperations.release()); } m_filterInProgress = true;
diff --git a/third_party/WebKit/Source/core/paint/FramePainter.cpp b/third_party/WebKit/Source/core/paint/FramePainter.cpp index 3671bf71..849cd78 100644 --- a/third_party/WebKit/Source/core/paint/FramePainter.cpp +++ b/third_party/WebKit/Source/core/paint/FramePainter.cpp
@@ -167,7 +167,7 @@ s_inPaintContents = false; } - InspectorInstrumentation::didPaint(layoutView, 0, context, LayoutRect(rect)); + InspectorInstrumentation::didPaint(layoutView->frame(), 0, context, LayoutRect(rect)); } void FramePainter::paintScrollbars(GraphicsContext& context, const IntRect& rect)
diff --git a/third_party/WebKit/Source/core/paint/PaintLayer.cpp b/third_party/WebKit/Source/core/paint/PaintLayer.cpp index 9b9a868..8f60634 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayer.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayer.cpp
@@ -2647,23 +2647,23 @@ // TODO(jbroman): Incorporate the mask image. const auto* reflectStyle = style.boxReflect(); FloatRect frameRect(toLayoutBox(layoutObject())->frameRect()); - ReflectionDirection direction = VerticalReflection; + BoxReflection::ReflectionDirection direction = BoxReflection::VerticalReflection; float offset = 0; switch (reflectStyle->direction()) { case ReflectionAbove: - direction = VerticalReflection; + direction = BoxReflection::VerticalReflection; offset = -floatValueForLength(reflectStyle->offset(), frameRect.height()); break; case ReflectionBelow: - direction = VerticalReflection; + direction = BoxReflection::VerticalReflection; offset = 2 * frameRect.height() + floatValueForLength(reflectStyle->offset(), frameRect.height()); break; case ReflectionLeft: - direction = HorizontalReflection; + direction = BoxReflection::HorizontalReflection; offset = -floatValueForLength(reflectStyle->offset(), frameRect.width()); break; case ReflectionRight: - direction = HorizontalReflection; + direction = BoxReflection::HorizontalReflection; offset = 2 * frameRect.width() + floatValueForLength(reflectStyle->offset(), frameRect.width()); break; } @@ -2674,9 +2674,10 @@ // SkLocalMatrixImageFilter, but simpler). // The rect used here should match the one used in FilterPainter. LayoutRect filterInputBounds = physicalBoundingBoxIncludingReflectionAndStackingChildren(LayoutPoint()); - offset -= 2 * (direction == VerticalReflection ? filterInputBounds.y() : filterInputBounds.x()).toFloat(); + offset -= 2 * (direction == BoxReflection::VerticalReflection ? filterInputBounds.y() : filterInputBounds.x()).toFloat(); - filterOperations.operations().append(BoxReflectFilterOperation::create(direction, offset)); + BoxReflection reflection(direction, offset); + filterOperations.operations().append(BoxReflectFilterOperation::create(reflection)); } return computeFilterOperationsHandleReferenceFilters(filterOperations, style.effectiveZoom(), enclosingNode()); }
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp b/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp index cc6d5fd..b044498 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerPainter.cpp
@@ -727,8 +727,9 @@ } else { if (m_paintLayer.needsPaintPhaseDescendantBlockBackgrounds()) paintForegroundForFragmentsWithPhase(PaintPhaseDescendantBlockBackgroundsOnly, layerFragments, context, localPaintingInfo, paintFlags, clipState); - if (m_paintLayer.needsPaintPhaseFloat()) - paintForegroundForFragmentsWithPhase(PaintPhaseFloat, layerFragments, context, localPaintingInfo, paintFlags, clipState); + // TODO(wangxianzhu): Enable float empty-phase optimization after fixing crbug.com/603910. + // if (m_paintLayer.needsPaintPhaseFloat()) + paintForegroundForFragmentsWithPhase(PaintPhaseFloat, layerFragments, context, localPaintingInfo, paintFlags, clipState); paintForegroundForFragmentsWithPhase(PaintPhaseForeground, layerFragments, context, localPaintingInfo, paintFlags, clipState); if (m_paintLayer.needsPaintPhaseDescendantOutlines()) paintForegroundForFragmentsWithPhase(PaintPhaseDescendantOutlinesOnly, layerFragments, context, localPaintingInfo, paintFlags, clipState);
diff --git a/third_party/WebKit/Source/core/paint/SVGFilterPainter.cpp b/third_party/WebKit/Source/core/paint/SVGFilterPainter.cpp index 9472e62..69fb472 100644 --- a/third_party/WebKit/Source/core/paint/SVGFilterPainter.cpp +++ b/third_party/WebKit/Source/core/paint/SVGFilterPainter.cpp
@@ -50,7 +50,7 @@ m_paintController->commitNewDisplayItems(); m_paintController->paintArtifact().replay(*context); - sourceGraphic->setPicture(context->endRecording()); + sourceGraphic->setPicture(toSkSp(context->endRecording())); // Content is cached by the source graphic so temporaries can be freed. m_paintController = nullptr; @@ -67,7 +67,7 @@ filterData->m_state = FilterData::PaintingFilter; SkiaImageFilterBuilder builder; - RefPtr<SkImageFilter> imageFilter = builder.build(filterData->filter->lastEffect(), ColorSpaceDeviceRGB); + sk_sp<SkImageFilter> imageFilter = builder.build(filterData->filter->lastEffect(), ColorSpaceDeviceRGB); FloatRect boundaries = filterData->filter->filterRegion(); context.save(); @@ -90,11 +90,11 @@ AffineTransform shearAndRotate = scaleAndTranslate.inverse(); shearAndRotate.multiply(ctm); context.concatCTM(shearAndRotate.inverse()); - imageFilter = builder.buildTransform(shearAndRotate, imageFilter.get()); + imageFilter = builder.buildTransform(shearAndRotate, std::move(imageFilter)); } #endif - context.beginLayer(1, SkXfermode::kSrcOver_Mode, &boundaries, ColorFilterNone, imageFilter.get()); + context.beginLayer(1, SkXfermode::kSrcOver_Mode, &boundaries, ColorFilterNone, std::move(imageFilter)); context.endLayer(); context.restore();
diff --git a/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.cpp b/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.cpp index 58931dd..eba6e2b 100644 --- a/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.cpp +++ b/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.cpp
@@ -153,7 +153,7 @@ return ts; } -PassRefPtr<SkImageFilter> FEImage::createImageFilterForLayoutObject(const LayoutObject& layoutObject) +sk_sp<SkImageFilter> FEImage::createImageFilterForLayoutObject(const LayoutObject& layoutObject) { FloatRect dstRect = filterPrimitiveSubregion(); @@ -177,18 +177,16 @@ TransformRecorder transformRecorder(filterPicture.context(), layoutObject, transform); SVGPaintContext::paintSubtree(filterPicture.context(), &layoutObject); } - RefPtr<const SkPicture> recording = filterPicture.endRecording(); - RefPtr<SkImageFilter> result = adoptRef(SkPictureImageFilter::Create(recording.get(), dstRect)); - return result.release(); + return SkPictureImageFilter::Make(toSkSp(filterPicture.endRecording()), dstRect); } -PassRefPtr<SkImageFilter> FEImage::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FEImage::createImageFilter(SkiaImageFilterBuilder& builder) { if (auto* layoutObject = referencedLayoutObject()) return createImageFilterForLayoutObject(*layoutObject); - RefPtr<SkImage> image = m_image ? m_image->imageForCurrentFrame() : nullptr; + sk_sp<SkImage> image = m_image ? toSkSp(m_image->imageForCurrentFrame()) : nullptr; if (!image) { // "A href reference that is an empty image (zero width or zero height), that fails // to download, is non-existent, or that cannot be displayed (e.g. because it is @@ -202,7 +200,7 @@ m_preserveAspectRatio->transformRect(dstRect, srcRect); - return adoptRef(SkImageSource::Create(image.get(), srcRect, dstRect, kHigh_SkFilterQuality)); + return SkImageSource::Make(std::move(image), srcRect, dstRect, kHigh_SkFilterQuality); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.h b/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.h index b242bb97..3b81d1d 100644 --- a/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.h +++ b/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.h
@@ -47,7 +47,7 @@ void setOperatingColorSpace(ColorSpace) override { } TextStream& externalRepresentation(TextStream&, int indention) const override; - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; DECLARE_VIRTUAL_TRACE(); @@ -57,7 +57,7 @@ FEImage(Filter*, TreeScope&, const String&, SVGPreserveAspectRatio*); LayoutObject* referencedLayoutObject() const; - PassRefPtr<SkImageFilter> createImageFilterForLayoutObject(const LayoutObject&); + sk_sp<SkImageFilter> createImageFilterForLayoutObject(const LayoutObject&); RefPtr<Image> m_image;
diff --git a/third_party/WebKit/Source/core/testing/InternalSettings.cpp b/third_party/WebKit/Source/core/testing/InternalSettings.cpp index b002f41..b579924 100644 --- a/third_party/WebKit/Source/core/testing/InternalSettings.cpp +++ b/third_party/WebKit/Source/core/testing/InternalSettings.cpp
@@ -182,6 +182,19 @@ settings()->setViewportMetaEnabled(enabled); } +void InternalSettings::setViewportStyle(const String& style, ExceptionState& exceptionState) +{ + InternalSettingsGuardForSettings(); + if (equalIgnoringCase(style, "default")) + settings()->setViewportStyle(WebViewportStyle::Default); + else if (equalIgnoringCase(style, "mobile")) + settings()->setViewportStyle(WebViewportStyle::Mobile); + else if (equalIgnoringCase(style, "television")) + settings()->setViewportStyle(WebViewportStyle::Television); + else + exceptionState.throwDOMException(SyntaxError, "The viewport style type provided ('" + style + "') is invalid."); +} + void InternalSettings::setStandardFontFamily(const AtomicString& family, const String& script, ExceptionState& exceptionState) { InternalSettingsGuardForSettings();
diff --git a/third_party/WebKit/Source/core/testing/InternalSettings.h b/third_party/WebKit/Source/core/testing/InternalSettings.h index 89c18f2..7245d6c 100644 --- a/third_party/WebKit/Source/core/testing/InternalSettings.h +++ b/third_party/WebKit/Source/core/testing/InternalSettings.h
@@ -106,6 +106,7 @@ void setTextAutosizingWindowSizeOverride(int width, int height, ExceptionState&); void setViewportEnabled(bool, ExceptionState&); void setViewportMetaEnabled(bool, ExceptionState&); + void setViewportStyle(const String& preference, ExceptionState&); void setCompositorWorkerEnabled(bool, ExceptionState&); // FIXME: The following are RuntimeEnabledFeatures and likely
diff --git a/third_party/WebKit/Source/core/testing/InternalSettings.idl b/third_party/WebKit/Source/core/testing/InternalSettings.idl index 62df88c2..05a8d10 100644 --- a/third_party/WebKit/Source/core/testing/InternalSettings.idl +++ b/third_party/WebKit/Source/core/testing/InternalSettings.idl
@@ -47,6 +47,7 @@ [RaisesException] void setDefaultVideoPosterURL(DOMString poster); [RaisesException] void setViewportEnabled(boolean enabled); [RaisesException] void setViewportMetaEnabled(boolean enabled); + [RaisesException] void setViewportStyle(DOMString style); [RaisesException] void setAvailablePointerTypes(DOMString pointers); [RaisesException] void setPrimaryPointerType(DOMString pointer); [RaisesException] void setAvailableHoverTypes(DOMString types);
diff --git a/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewMessage.js b/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewMessage.js index e1e23a3..b558a60 100644 --- a/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewMessage.js +++ b/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewMessage.js
@@ -488,13 +488,15 @@ */ _formatParameterAsNode: function(object, elem) { - WebInspector.Renderer.renderPromise(object).then(appendRenderer, failedToRender.bind(this)); + WebInspector.Renderer.renderPromise(object).then(appendRenderer.bind(this), failedToRender.bind(this)); /** * @param {!Element} rendererElement + * @this {WebInspector.ConsoleViewMessage} */ function appendRenderer(rendererElement) { elem.appendChild(rendererElement); + this._formattedParameterAsNodeForTest(); } /** @@ -506,6 +508,10 @@ } }, + _formattedParameterAsNodeForTest: function() + { + }, + /** * @param {!WebInspector.RemoteObject} array * @return {boolean}
diff --git a/third_party/WebKit/Source/devtools/front_end/main/Main.js b/third_party/WebKit/Source/devtools/front_end/main/Main.js index 7261054c..6d6e53e 100644 --- a/third_party/WebKit/Source/devtools/front_end/main/Main.js +++ b/third_party/WebKit/Source/devtools/front_end/main/Main.js
@@ -113,7 +113,6 @@ Runtime.experiments.register("inspectTooltip", "Dark inspect element tooltip"); Runtime.experiments.register("liveSASS", "Live SASS", true); Runtime.experiments.register("multipleTimelineViews", "Multiple main views on Timeline", true); - Runtime.experiments.register("networkRequestHeadersFilterInDetailsView", "Network request headers filter in details view", true); Runtime.experiments.register("networkRequestsOnTimeline", "Network requests on Timeline", true); Runtime.experiments.register("privateScriptInspection", "Private script inspection"); Runtime.experiments.register("reducedIndentation", "Reduced indentation in Elements DOM tree");
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkDataGridNode.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkDataGridNode.js index 5c4f0e4..816b6c27 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkDataGridNode.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkDataGridNode.js
@@ -708,18 +708,60 @@ /** * @param {string} propertyName - * @param {boolean} revert * @param {!WebInspector.NetworkDataGridNode} a * @param {!WebInspector.NetworkDataGridNode} b * @return {number} */ -WebInspector.NetworkDataGridNode.RequestPropertyComparator = function(propertyName, revert, a, b) +WebInspector.NetworkDataGridNode.RequestPropertyComparator = function(propertyName, a, b) { var aValue = a._request[propertyName]; var bValue = b._request[propertyName]; - if (aValue > bValue) - return revert ? -1 : 1; - if (bValue > aValue) - return revert ? 1 : -1; - return a._request.indentityCompare(b._request); + if (aValue == bValue) + return a._request.indentityCompare(b._request); + return aValue > bValue ? 1 : -1; +} + +/** + * @param {string} propertyName + * @param {!WebInspector.NetworkDataGridNode} a + * @param {!WebInspector.NetworkDataGridNode} b + * @return {number} + */ +WebInspector.NetworkDataGridNode.ResponseHeaderStringComparator = function(propertyName, a, b) +{ + var aValue = String(a._request.responseHeaderValue(propertyName) || ""); + var bValue = String(b._request.responseHeaderValue(propertyName) || ""); + return aValue.localeCompare(bValue) || a._request.indentityCompare(b._request); +} + +/** + * @param {string} propertyName + * @param {!WebInspector.NetworkDataGridNode} a + * @param {!WebInspector.NetworkDataGridNode} b + * @return {number} + */ +WebInspector.NetworkDataGridNode.ResponseHeaderNumberComparator = function(propertyName, a, b) +{ + var aValue = (a._request.responseHeaderValue(propertyName) !== undefined) ? parseFloat(a._request.responseHeaderValue(propertyName)) : -Infinity; + var bValue = (b._request.responseHeaderValue(propertyName) !== undefined) ? parseFloat(b._request.responseHeaderValue(propertyName)) : -Infinity; + if (aValue == bValue) + return a._request.indentityCompare(b._request); + return aValue > bValue ? 1 : -1; +} + +/** + * @param {string} propertyName + * @param {!WebInspector.NetworkDataGridNode} a + * @param {!WebInspector.NetworkDataGridNode} b + * @return {number} + */ +WebInspector.NetworkDataGridNode.ResponseHeaderDateComparator = function(propertyName, a, b) +{ + var aHeader = a._request.responseHeaderValue(propertyName); + var bHeader = b._request.responseHeaderValue(propertyName); + var aValue = aHeader ? new Date(aHeader).getTime() : -Infinity; + var bValue = bHeader ? new Date(bHeader).getTime() : -Infinity; + if (aValue == bValue) + return a._request.indentityCompare(b._request); + return aValue > bValue ? 1 : -1; }
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkLogView.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkLogView.js index 0bae0c8..f83ad7b 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkLogView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkLogView.js
@@ -622,26 +622,36 @@ { this._sortingFunctions = {}; this._sortingFunctions.name = WebInspector.NetworkDataGridNode.NameComparator; - this._sortingFunctions.method = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "requestMethod", false); - this._sortingFunctions.status = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "statusCode", false); - this._sortingFunctions.protocol = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "protocol", false); - this._sortingFunctions.scheme = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "scheme", false); - this._sortingFunctions.domain = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "domain", false); + this._sortingFunctions.method = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "requestMethod"); + this._sortingFunctions.status = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "statusCode"); + this._sortingFunctions.protocol = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "protocol"); + this._sortingFunctions.scheme = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "scheme"); + this._sortingFunctions.domain = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "domain"); this._sortingFunctions.remoteAddress = WebInspector.NetworkDataGridNode.RemoteAddressComparator; this._sortingFunctions.type = WebInspector.NetworkDataGridNode.TypeComparator; this._sortingFunctions.initiator = WebInspector.NetworkDataGridNode.InitiatorComparator; this._sortingFunctions.cookies = WebInspector.NetworkDataGridNode.RequestCookiesCountComparator; this._sortingFunctions.setCookies = WebInspector.NetworkDataGridNode.ResponseCookiesCountComparator; this._sortingFunctions.size = WebInspector.NetworkDataGridNode.SizeComparator; - this._sortingFunctions.time = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "duration", false); - this._sortingFunctions.connectionId = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "connectionId", false); + this._sortingFunctions.time = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "duration"); + this._sortingFunctions.connectionId = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "connectionId"); this._sortingFunctions.priority = WebInspector.NetworkDataGridNode.InitialPriorityComparator; - this._sortingFunctions.timeline = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "startTime", false); - this._sortingFunctions.startTime = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "startTime", false); - this._sortingFunctions.endTime = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "endTime", false); - this._sortingFunctions.responseTime = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "responseReceivedTime", false); - this._sortingFunctions.duration = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "duration", true); - this._sortingFunctions.latency = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "latency", true); + this._sortingFunctions.timeline = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "startTime"); + this._sortingFunctions.startTime = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "startTime"); + this._sortingFunctions.endTime = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "endTime"); + this._sortingFunctions.responseTime = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "responseReceivedTime"); + this._sortingFunctions.duration = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "duration"); + this._sortingFunctions.latency = WebInspector.NetworkDataGridNode.RequestPropertyComparator.bind(null, "latency"); + + this._sortingFunctions["Cache-Control"] = WebInspector.NetworkDataGridNode.ResponseHeaderStringComparator.bind(null, "Cache-Control"); + this._sortingFunctions["Connection"] = WebInspector.NetworkDataGridNode.ResponseHeaderStringComparator.bind(null, "Connection"); + this._sortingFunctions["Content-Encoding"] = WebInspector.NetworkDataGridNode.ResponseHeaderStringComparator.bind(null, "Content-Encoding"); + this._sortingFunctions["Content-Length"] = WebInspector.NetworkDataGridNode.ResponseHeaderNumberComparator.bind(null, "Content-Length"); + this._sortingFunctions["ETag"] = WebInspector.NetworkDataGridNode.ResponseHeaderStringComparator.bind(null, "ETag"); + this._sortingFunctions["Keep-Alive"] = WebInspector.NetworkDataGridNode.ResponseHeaderStringComparator.bind(null, "Keep-Alive"); + this._sortingFunctions["Last-Modified"] = WebInspector.NetworkDataGridNode.ResponseHeaderDateComparator.bind(null, "Last-Modified"); + this._sortingFunctions["Server"] = WebInspector.NetworkDataGridNode.ResponseHeaderStringComparator.bind(null, "Server"); + this._sortingFunctions["Vary"] = WebInspector.NetworkDataGridNode.ResponseHeaderStringComparator.bind(null, "Vary"); }, _createCalculators: function()
diff --git a/third_party/WebKit/Source/devtools/front_end/network/RequestHeadersView.js b/third_party/WebKit/Source/devtools/front_end/network/RequestHeadersView.js index 69e80ec6..7891d105 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/RequestHeadersView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/RequestHeadersView.js
@@ -44,19 +44,6 @@ this._showRequestHeadersText = false; this._showResponseHeadersText = false; - this._requestHeaderFilterSetting = WebInspector.settings.createSetting("requestHeaderFilterSetting", ""); - - /** @type {?RegExp} */ - this._filterRegex = null; - if (Runtime.experiments.isEnabled("networkRequestHeadersFilterInDetailsView")) { - this._filterInput = this.element.createChild("input", "filter-input"); - this._filterInput.type = "text"; - this._filterInput.placeholder = WebInspector.UIString("Filter headers"); - this._filterInput.addEventListener("input", this._updateFilter.bind(this), false); - this._filterInput.addEventListener("keydown", this._onFilterKeyDown.bind(this), false); - this._filterInput.value = this._requestHeaderFilterSetting.get() || ""; - } - var root = new TreeOutline(true); root.element.classList.add("outline-disclosure"); root.expandTreeElementsWhenArrowing = true; @@ -75,43 +62,9 @@ this._queryStringCategory = new WebInspector.RequestHeadersView.Category(root, "queryString", ""); this._formDataCategory = new WebInspector.RequestHeadersView.Category(root, "formData", ""); this._requestPayloadCategory = new WebInspector.RequestHeadersView.Category(root, "requestPayload", WebInspector.UIString("Request Payload")); - - - if (Runtime.experiments.isEnabled("networkRequestHeadersFilterInDetailsView")) { - this._updateFilter(); - } } WebInspector.RequestHeadersView.prototype = { - _updateFilter: function() - { - var text = this._filterInput.value; - this._requestHeaderFilterSetting.set(text); - this._filterRegex = text ? new RegExp(text.escapeForRegExp(), "i") : null; - this._updateHeaders(); - }, - - /** - * @param {!Event} event - */ - _onFilterKeyDown: function(event) - { - var text = this._filterInput.value; - if (!text) - return; - if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code || event.keyIdentifier === "U+001B") { - event.consume(true); - this._filterInput.value = ""; - this._updateFilter(); - } - }, - - _updateHeaders: function() - { - this._refreshRequestHeaders(); - this._refreshResponseHeaders(); - }, - wasShown: function() { this._request.addEventListener(WebInspector.NetworkRequest.Events.RemoteAddressChanged, this._refreshRemoteAddress, this); @@ -121,7 +74,8 @@ this._refreshURL(); this._refreshQueryString(); - this._updateHeaders(); + this._refreshRequestHeaders(); + this._refreshResponseHeaders(); this._refreshHTTPInformation(); this._refreshRemoteAddress(); }, @@ -345,11 +299,7 @@ _refreshRequestHeaders: function() { var treeElement = this._requestHeadersCategory; - var headers = this._request.requestHeaders().slice(); - var filterRegex = this._filterRegex; - if (filterRegex) - headers = headers.filter(function(header) { return filterRegex.test(header.name) || filterRegex.test(header.value);}); headers.sort(function(a, b) { return a.name.toLowerCase().compareTo(b.name.toLowerCase()); }); var headersText = this._request.requestHeadersText(); @@ -371,9 +321,6 @@ { var treeElement = this._responseHeadersCategory; var headers = this._request.sortedResponseHeaders.slice(); - var filterRegex = this._filterRegex; - if (filterRegex) - headers = headers.filter(function(header) { return filterRegex.test(header.name) || filterRegex.test(header.value);}); var headersText = this._request.responseHeadersText; if (this._showResponseHeadersText)
diff --git a/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.cpp b/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.cpp index e355052..9f4185d 100644 --- a/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.cpp +++ b/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.cpp
@@ -383,6 +383,7 @@ modifiableState().setUnparsedFilter(filterString); modifiableState().setFilter(filterValue); + snapshotStateForFilter(); } SVGMatrixTearOff* BaseRenderingContext2D::currentTransform() const
diff --git a/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.h b/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.h index 7d5b6111..41fb0302 100644 --- a/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.h +++ b/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.h
@@ -148,6 +148,7 @@ virtual bool stateHasFilter() = 0; virtual SkImageFilter* stateGetFilter() = 0; + virtual void snapshotStateForFilter() = 0; virtual void validateStateStack() = 0;
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp index 9780f2b..7614344 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.cpp
@@ -372,12 +372,17 @@ bool CanvasRenderingContext2D::stateHasFilter() { - return state().hasFilter(canvas(), accessFont(), canvas()->size(), this); + return state().hasFilter(canvas(), canvas()->size(), this); } SkImageFilter* CanvasRenderingContext2D::stateGetFilter() { - return state().getFilter(canvas(), accessFont(), canvas()->size(), this); + return state().getFilter(canvas(), canvas()->size(), this); +} + +void CanvasRenderingContext2D::snapshotStateForFilter() +{ + modifiableState().setFontForFilter(accessFont()); } SkCanvas* CanvasRenderingContext2D::drawingCanvas() const @@ -599,6 +604,16 @@ return std::make_pair(nullptr, String()); } +String CanvasRenderingContext2D::getIdFromControl(const Element* element) +{ + if (hitRegionsCount() <= 0) + return String(); + + if (HitRegion* hitRegion = m_hitRegionManager->getHitRegionByControl(element)) + return hitRegion->id(); + return String(); +} + String CanvasRenderingContext2D::textAlign() const { return textAlignName(state().getTextAlign());
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.h b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.h index da8a9f415..46245ca 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.h +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2D.h
@@ -136,6 +136,7 @@ void styleDidChange(const ComputedStyle* oldStyle, const ComputedStyle& newStyle) override; std::pair<Element*, String> getControlAndIdIfHitRegionExists(const LayoutPoint& location) override; + String getIdFromControl(const Element*) override; // SVGResourceClient implementation void filterNeedsInvalidation() override; @@ -162,6 +163,7 @@ bool stateHasFilter() final; SkImageFilter* stateGetFilter() final; + void snapshotStateForFilter() final; void validateStateStack() final;
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.cpp b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.cpp index fe74815..d7956f30 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.cpp +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.cpp
@@ -87,6 +87,7 @@ , m_lineDashOffset(other.m_lineDashOffset) , m_unparsedFont(other.m_unparsedFont) , m_font(other.m_font) + , m_fontForFilter(other.m_fontForFilter) , m_unparsedFilter(other.m_unparsedFilter) , m_filterValue(other.m_filterValue) , m_resolvedFilter(other.m_resolvedFilter) @@ -122,7 +123,7 @@ m_font.update(fontSelector); // FIXME: We only really need to invalidate the resolved filter if the font // update above changed anything and the filter uses font-dependent units. - m_resolvedFilter.clear(); + m_resolvedFilter.reset(); } DEFINE_TRACE(CanvasRenderingContext2DState) @@ -261,9 +262,6 @@ m_font.update(selector); m_realizedFont = true; selector->registerForInvalidationCallbacks(this); - // FIXME: We only really need to invalidate the resolved filter if it - // uses font-relative units. - m_resolvedFilter.clear(); } const Font& CanvasRenderingContext2DState::font() const @@ -290,7 +288,7 @@ context->addFilterReferences(filters, canvasElement->document()); } -SkImageFilter* CanvasRenderingContext2DState::getFilter(Element* styleResolutionHost, const Font& font, IntSize canvasSize, CanvasRenderingContext2D* context) const +SkImageFilter* CanvasRenderingContext2DState::getFilter(Element* styleResolutionHost, IntSize canvasSize, CanvasRenderingContext2D* context) const { if (!m_filterValue) return nullptr; @@ -298,7 +296,7 @@ if (!m_resolvedFilter) { RefPtr<ComputedStyle> filterStyle = ComputedStyle::create(); // Must set font in case the filter uses any font-relative units (em, ex) - filterStyle->setFont(font); + filterStyle->setFont(m_fontForFilter); StyleResolverState resolverState(styleResolutionHost->document(), styleResolutionHost, filterStyle.get()); resolverState.setStyle(filterStyle); @@ -335,16 +333,16 @@ return m_resolvedFilter.get(); } -bool CanvasRenderingContext2DState::hasFilter(Element* styleResolutionHost, const Font& font, IntSize canvasSize, CanvasRenderingContext2D* context) const +bool CanvasRenderingContext2DState::hasFilter(Element* styleResolutionHost, IntSize canvasSize, CanvasRenderingContext2D* context) const { // Checking for a non-null m_filterValue isn't sufficient, since this value // might refer to a non-existent filter. - return !!getFilter(styleResolutionHost, font, canvasSize, context); + return !!getFilter(styleResolutionHost, canvasSize, context); } void CanvasRenderingContext2DState::clearResolvedFilter() const { - m_resolvedFilter.clear(); + m_resolvedFilter.reset(); } SkDrawLooper* CanvasRenderingContext2DState::emptyDrawLooper() const @@ -381,7 +379,7 @@ { if (!m_shadowOnlyImageFilter) { double sigma = skBlurRadiusToSigma(m_shadowBlur); - m_shadowOnlyImageFilter = adoptRef(SkDropShadowImageFilter::Create(m_shadowOffset.width(), m_shadowOffset.height(), sigma, sigma, m_shadowColor, SkDropShadowImageFilter::kDrawShadowOnly_ShadowMode)); + m_shadowOnlyImageFilter = SkDropShadowImageFilter::Make(m_shadowOffset.width(), m_shadowOffset.height(), sigma, sigma, m_shadowColor, SkDropShadowImageFilter::kDrawShadowOnly_ShadowMode, nullptr); } return m_shadowOnlyImageFilter.get(); } @@ -390,7 +388,7 @@ { if (!m_shadowAndForegroundImageFilter) { double sigma = skBlurRadiusToSigma(m_shadowBlur); - m_shadowAndForegroundImageFilter = adoptRef(SkDropShadowImageFilter::Create(m_shadowOffset.width(), m_shadowOffset.height(), sigma, sigma, m_shadowColor, SkDropShadowImageFilter::kDrawShadowAndForeground_ShadowMode)); + m_shadowAndForegroundImageFilter = SkDropShadowImageFilter::Make(m_shadowOffset.width(), m_shadowOffset.height(), sigma, sigma, m_shadowColor, SkDropShadowImageFilter::kDrawShadowAndForeground_ShadowMode, nullptr); } return m_shadowAndForegroundImageFilter.get(); } @@ -399,8 +397,8 @@ { m_shadowOnlyDrawLooper.clear(); m_shadowAndForegroundDrawLooper.clear(); - m_shadowOnlyImageFilter.clear(); - m_shadowAndForegroundImageFilter.clear(); + m_shadowOnlyImageFilter.reset(); + m_shadowAndForegroundImageFilter.reset(); } void CanvasRenderingContext2DState::setShadowOffsetX(double x) @@ -430,7 +428,7 @@ void CanvasRenderingContext2DState::setFilter(CSSValue* filterValue) { m_filterValue = filterValue; - m_resolvedFilter.clear(); + m_resolvedFilter.reset(); } void CanvasRenderingContext2DState::setGlobalComposite(SkXfermode::Mode mode)
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.h b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.h index f2f684f..fbb05bc 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.h +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.h
@@ -82,11 +82,13 @@ void setUnparsedFont(const String& font) { m_unparsedFont = font; } const String& unparsedFont() const { return m_unparsedFont; } + void setFontForFilter(const Font& font) { m_fontForFilter = font; } + void setFilter(CSSValue*); void setUnparsedFilter(const String& filterString) { m_unparsedFilter = filterString; } const String& unparsedFilter() const { return m_unparsedFilter; } - SkImageFilter* getFilter(Element*, const Font&, IntSize canvasSize, CanvasRenderingContext2D*) const; - bool hasFilter(Element*, const Font&, IntSize canvasSize, CanvasRenderingContext2D*) const; + SkImageFilter* getFilter(Element*, IntSize canvasSize, CanvasRenderingContext2D*) const; + bool hasFilter(Element*, IntSize canvasSize, CanvasRenderingContext2D*) const; void clearResolvedFilter() const; void setStrokeStyle(CanvasStyle*); @@ -195,8 +197,8 @@ mutable RefPtr<SkDrawLooper> m_emptyDrawLooper; mutable RefPtr<SkDrawLooper> m_shadowOnlyDrawLooper; mutable RefPtr<SkDrawLooper> m_shadowAndForegroundDrawLooper; - mutable RefPtr<SkImageFilter> m_shadowOnlyImageFilter; - mutable RefPtr<SkImageFilter> m_shadowAndForegroundImageFilter; + mutable sk_sp<SkImageFilter> m_shadowOnlyImageFilter; + mutable sk_sp<SkImageFilter> m_shadowAndForegroundImageFilter; double m_globalAlpha; AffineTransform m_transform; @@ -205,10 +207,11 @@ String m_unparsedFont; Font m_font; + Font m_fontForFilter; String m_unparsedFilter; Member<CSSValue> m_filterValue; - mutable RefPtr<SkImageFilter> m_resolvedFilter; + mutable sk_sp<SkImageFilter> m_resolvedFilter; // Text state. TextAlign m_textAlign;
diff --git a/third_party/WebKit/Source/modules/canvas2d/HitRegion.cpp b/third_party/WebKit/Source/modules/canvas2d/HitRegion.cpp index 3934ca7..55300b0 100644 --- a/third_party/WebKit/Source/modules/canvas2d/HitRegion.cpp +++ b/third_party/WebKit/Source/modules/canvas2d/HitRegion.cpp
@@ -66,7 +66,7 @@ removeHitRegion(getHitRegionById(id)); } -void HitRegionManager::removeHitRegionByControl(Element* control) +void HitRegionManager::removeHitRegionByControl(const Element* control) { removeHitRegion(getHitRegionByControl(control)); } @@ -104,7 +104,7 @@ return m_hitRegionIdMap.get(id); } -HitRegion* HitRegionManager::getHitRegionByControl(Element* control) const +HitRegion* HitRegionManager::getHitRegionByControl(const Element* control) const { if (control) return m_hitRegionControlMap.get(control);
diff --git a/third_party/WebKit/Source/modules/canvas2d/HitRegion.h b/third_party/WebKit/Source/modules/canvas2d/HitRegion.h index 8a03e27..a2b689b4 100644 --- a/third_party/WebKit/Source/modules/canvas2d/HitRegion.h +++ b/third_party/WebKit/Source/modules/canvas2d/HitRegion.h
@@ -55,12 +55,12 @@ void removeHitRegion(HitRegion*); void removeHitRegionById(const String& id); - void removeHitRegionByControl(Element*); + void removeHitRegionByControl(const Element*); void removeHitRegionsInRect(const FloatRect&, const AffineTransform&); void removeAllHitRegions(); HitRegion* getHitRegionById(const String& id) const; - HitRegion* getHitRegionByControl(Element*) const; + HitRegion* getHitRegionByControl(const Element*) const; HitRegion* getHitRegionAtPoint(const FloatPoint&) const; unsigned getHitRegionsCount() const; @@ -73,7 +73,7 @@ typedef HeapListHashSet<Member<HitRegion>> HitRegionList; typedef HitRegionList::const_reverse_iterator HitRegionIterator; typedef HeapHashMap<String, Member<HitRegion>> HitRegionIdMap; - typedef HeapHashMap<Member<Element>, Member<HitRegion>> HitRegionControlMap; + typedef HeapHashMap<Member<const Element>, Member<HitRegion>> HitRegionControlMap; HitRegionList m_hitRegionList; HitRegionIdMap m_hitRegionIdMap;
diff --git a/third_party/WebKit/Source/modules/csspaint/PaintRenderingContext2D.h b/third_party/WebKit/Source/modules/csspaint/PaintRenderingContext2D.h index 3c0d925..3fdd6f4 100644 --- a/third_party/WebKit/Source/modules/csspaint/PaintRenderingContext2D.h +++ b/third_party/WebKit/Source/modules/csspaint/PaintRenderingContext2D.h
@@ -56,6 +56,7 @@ // that we don't have a filter set. bool stateHasFilter() final { return false; } SkImageFilter* stateGetFilter() final { return nullptr; } + void snapshotStateForFilter() final { } void validateStateStack() final;
diff --git a/third_party/WebKit/Source/modules/indexeddb/DOMWindowIndexedDatabase.cpp b/third_party/WebKit/Source/modules/indexeddb/DOMWindowIndexedDatabase.cpp deleted file mode 100644 index 40888f6..0000000 --- a/third_party/WebKit/Source/modules/indexeddb/DOMWindowIndexedDatabase.cpp +++ /dev/null
@@ -1,99 +0,0 @@ -/* - * Copyright (C) 2011, Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH - * DAMAGE. - */ - -#include "modules/indexeddb/DOMWindowIndexedDatabase.h" - -#include "core/dom/Document.h" -#include "core/frame/LocalDOMWindow.h" -#include "core/page/Page.h" -#include "modules/indexeddb/IDBFactory.h" - -namespace blink { - -DOMWindowIndexedDatabase::DOMWindowIndexedDatabase(LocalDOMWindow& window) - : DOMWindowProperty(window.frame()) - , m_window(&window) -{ -} - -DEFINE_TRACE(DOMWindowIndexedDatabase) -{ - visitor->trace(m_window); - visitor->trace(m_idbFactory); - Supplement<LocalDOMWindow>::trace(visitor); - DOMWindowProperty::trace(visitor); -} - -const char* DOMWindowIndexedDatabase::supplementName() -{ - return "DOMWindowIndexedDatabase"; -} - -DOMWindowIndexedDatabase& DOMWindowIndexedDatabase::from(LocalDOMWindow& window) -{ - DOMWindowIndexedDatabase* supplement = static_cast<DOMWindowIndexedDatabase*>(Supplement<LocalDOMWindow>::from(window, supplementName())); - if (!supplement) { - supplement = new DOMWindowIndexedDatabase(window); - provideTo(window, supplementName(), supplement); - } - return *supplement; -} - -void DOMWindowIndexedDatabase::willDestroyGlobalObjectInFrame() -{ - m_idbFactory = nullptr; - DOMWindowProperty::willDestroyGlobalObjectInFrame(); -} - -void DOMWindowIndexedDatabase::willDetachGlobalObjectFromFrame() -{ - m_idbFactory = nullptr; - DOMWindowProperty::willDetachGlobalObjectFromFrame(); -} - -IDBFactory* DOMWindowIndexedDatabase::indexedDB(DOMWindow& window) -{ - return from(toLocalDOMWindow(window)).indexedDB(); -} - -IDBFactory* DOMWindowIndexedDatabase::indexedDB() -{ - Document* document = m_window->document(); - if (!document) - return nullptr; - - Page* page = document->page(); - if (!page) - return nullptr; - - if (!m_window->isCurrentlyDisplayedInFrame()) - return nullptr; - - if (!m_idbFactory) - m_idbFactory = IDBFactory::create(); - return m_idbFactory.get(); -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/modules/indexeddb/DOMWindowIndexedDatabase.h b/third_party/WebKit/Source/modules/indexeddb/DOMWindowIndexedDatabase.h deleted file mode 100644 index ec6398bb..0000000 --- a/third_party/WebKit/Source/modules/indexeddb/DOMWindowIndexedDatabase.h +++ /dev/null
@@ -1,62 +0,0 @@ -/* - * Copyright (C) 2011, Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH - * DAMAGE. - */ - -#ifndef DOMWindowIndexedDatabase_h -#define DOMWindowIndexedDatabase_h - -#include "core/frame/DOMWindowProperty.h" -#include "modules/indexeddb/IndexedDBClient.h" -#include "platform/Supplementable.h" - -namespace blink { - -class IDBFactory; -class DOMWindow; - -class DOMWindowIndexedDatabase final : public GarbageCollected<DOMWindowIndexedDatabase>, public Supplement<LocalDOMWindow>, public DOMWindowProperty { - USING_GARBAGE_COLLECTED_MIXIN(DOMWindowIndexedDatabase); -public: - static DOMWindowIndexedDatabase& from(LocalDOMWindow&); - - static IDBFactory* indexedDB(DOMWindow&); - - void willDestroyGlobalObjectInFrame() override; - void willDetachGlobalObjectFromFrame() override; - - DECLARE_TRACE(); - -private: - explicit DOMWindowIndexedDatabase(LocalDOMWindow&); - - IDBFactory* indexedDB(); - static const char* supplementName(); - - Member<LocalDOMWindow> m_window; - Member<IDBFactory> m_idbFactory; -}; - -} // namespace blink - -#endif // DOMWindowIndexedDatabase_h
diff --git a/third_party/WebKit/Source/modules/indexeddb/GlobalIndexedDB.cpp b/third_party/WebKit/Source/modules/indexeddb/GlobalIndexedDB.cpp new file mode 100644 index 0000000..db5e2fa3 --- /dev/null +++ b/third_party/WebKit/Source/modules/indexeddb/GlobalIndexedDB.cpp
@@ -0,0 +1,66 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "modules/indexeddb/GlobalIndexedDB.h" + +#include "core/frame/LocalDOMWindow.h" +#include "core/workers/WorkerGlobalScope.h" +#include "modules/indexeddb/IDBFactory.h" +#include "platform/Supplementable.h" +#include "platform/heap/Handle.h" + +namespace blink { + +namespace { + +template <typename T> +class GlobalIndexedDBImpl final : public GarbageCollectedFinalized<GlobalIndexedDBImpl<T>>, public Supplement<T> { + USING_GARBAGE_COLLECTED_MIXIN(GlobalIndexedDBImpl); +public: + static GlobalIndexedDBImpl& from(T& supplementable) + { + GlobalIndexedDBImpl* supplement = static_cast<GlobalIndexedDBImpl*>(Supplement<T>::from(supplementable, name())); + if (!supplement) { + supplement = new GlobalIndexedDBImpl; + Supplement<T>::provideTo(supplementable, name(), supplement); + } + return *supplement; + } + + IDBFactory* idbFactory(T& fetchingScope) + { + if (!m_idbFactory) + m_idbFactory = IDBFactory::create(); + return m_idbFactory; + } + + DEFINE_INLINE_VIRTUAL_TRACE() + { + visitor->trace(m_idbFactory); + Supplement<T>::trace(visitor); + } + +private: + GlobalIndexedDBImpl() + { + } + + static const char* name() { return "IndexedDB"; } + + Member<IDBFactory> m_idbFactory; +}; + +} // namespace + +IDBFactory* GlobalIndexedDB::indexedDB(DOMWindow& window) +{ + return GlobalIndexedDBImpl<LocalDOMWindow>::from(toLocalDOMWindow(window)).idbFactory(toLocalDOMWindow(window)); +} + +IDBFactory* GlobalIndexedDB::indexedDB(WorkerGlobalScope& worker) +{ + return GlobalIndexedDBImpl<WorkerGlobalScope>::from(worker).idbFactory(worker); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/modules/indexeddb/GlobalIndexedDB.h b/third_party/WebKit/Source/modules/indexeddb/GlobalIndexedDB.h new file mode 100644 index 0000000..de74356 --- /dev/null +++ b/third_party/WebKit/Source/modules/indexeddb/GlobalIndexedDB.h
@@ -0,0 +1,25 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef GlobalIndexedDB_h +#define GlobalIndexedDB_h + +#include "wtf/Allocator.h" + +namespace blink { + +class IDBFactory; +class DOMWindow; +class WorkerGlobalScope; + +class GlobalIndexedDB { + STATIC_ONLY(GlobalIndexedDB); +public: + static IDBFactory* indexedDB(DOMWindow&); + static IDBFactory* indexedDB(WorkerGlobalScope&); +}; + +} // namespace blink + +#endif // GlobalIndexedDB_h
diff --git a/third_party/WebKit/Source/modules/indexeddb/IDBKeyRange.idl b/third_party/WebKit/Source/modules/indexeddb/IDBKeyRange.idl index fe9c55a..0fbc7e14 100644 --- a/third_party/WebKit/Source/modules/indexeddb/IDBKeyRange.idl +++ b/third_party/WebKit/Source/modules/indexeddb/IDBKeyRange.idl
@@ -38,5 +38,5 @@ [CallWith=ExecutionContext, RaisesException] static IDBKeyRange upperBound(any bound, optional boolean open = false); [CallWith=ExecutionContext, RaisesException] static IDBKeyRange bound(any lower, any upper, optional boolean lowerOpen = false, optional boolean upperOpen = false); - [CallWith=ExecutionContext, RaisesException, RuntimeEnabled=IndexedDBExperimental] boolean includes(any key); + [CallWith=ExecutionContext, RaisesException] boolean includes(any key); };
diff --git a/third_party/WebKit/Source/modules/indexeddb/InspectorIndexedDBAgent.cpp b/third_party/WebKit/Source/modules/indexeddb/InspectorIndexedDBAgent.cpp index 790ff2f..e080fb3 100644 --- a/third_party/WebKit/Source/modules/indexeddb/InspectorIndexedDBAgent.cpp +++ b/third_party/WebKit/Source/modules/indexeddb/InspectorIndexedDBAgent.cpp
@@ -41,7 +41,7 @@ #include "core/frame/LocalFrame.h" #include "core/inspector/InspectedFrames.h" #include "modules/IndexedDBNames.h" -#include "modules/indexeddb/DOMWindowIndexedDatabase.h" +#include "modules/indexeddb/GlobalIndexedDB.h" #include "modules/indexeddb/IDBCursor.h" #include "modules/indexeddb/IDBCursorWithValue.h" #include "modules/indexeddb/IDBDatabase.h" @@ -621,7 +621,7 @@ *errorString = "No IndexedDB factory for given frame found"; return nullptr; } - IDBFactory* idbFactory = DOMWindowIndexedDatabase::indexedDB(*domWindow); + IDBFactory* idbFactory = GlobalIndexedDB::indexedDB(*domWindow); if (!idbFactory) *errorString = "No IndexedDB factory for given frame found";
diff --git a/third_party/WebKit/Source/modules/indexeddb/WindowIndexedDatabase.idl b/third_party/WebKit/Source/modules/indexeddb/WindowIndexedDatabase.idl index eb08dd14..d551fe5 100644 --- a/third_party/WebKit/Source/modules/indexeddb/WindowIndexedDatabase.idl +++ b/third_party/WebKit/Source/modules/indexeddb/WindowIndexedDatabase.idl
@@ -25,7 +25,7 @@ */ [ - ImplementedAs=DOMWindowIndexedDatabase, + ImplementedAs=GlobalIndexedDB ] partial interface Window { [ImplementedAs=indexedDB, DeprecateAs=PrefixedIndexedDB] readonly attribute IDBFactory webkitIndexedDB;
diff --git a/third_party/WebKit/Source/modules/indexeddb/WorkerGlobalScopeIndexedDatabase.cpp b/third_party/WebKit/Source/modules/indexeddb/WorkerGlobalScopeIndexedDatabase.cpp deleted file mode 100644 index b083c8f..0000000 --- a/third_party/WebKit/Source/modules/indexeddb/WorkerGlobalScopeIndexedDatabase.cpp +++ /dev/null
@@ -1,76 +0,0 @@ -/* - * Copyright (C) 2008 Apple Inc. All Rights Reserved. - * Copyright (C) 2009, 2011 Google Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#include "modules/indexeddb/WorkerGlobalScopeIndexedDatabase.h" - -#include "core/dom/ExecutionContext.h" -#include "modules/indexeddb/IDBFactory.h" - -namespace blink { - -WorkerGlobalScopeIndexedDatabase::WorkerGlobalScopeIndexedDatabase() -{ -} - -WorkerGlobalScopeIndexedDatabase::~WorkerGlobalScopeIndexedDatabase() -{ -} - -const char* WorkerGlobalScopeIndexedDatabase::supplementName() -{ - return "WorkerGlobalScopeIndexedDatabase"; -} - -WorkerGlobalScopeIndexedDatabase& WorkerGlobalScopeIndexedDatabase::from(Supplementable<WorkerGlobalScope>& context) -{ - WorkerGlobalScopeIndexedDatabase* supplement = static_cast<WorkerGlobalScopeIndexedDatabase*>(Supplement<WorkerGlobalScope>::from(context, supplementName())); - if (!supplement) { - supplement = new WorkerGlobalScopeIndexedDatabase; - provideTo(context, supplementName(), supplement); - } - return *supplement; -} - -IDBFactory* WorkerGlobalScopeIndexedDatabase::indexedDB(Supplementable<WorkerGlobalScope>& context) -{ - return from(context).indexedDB(); -} - -IDBFactory* WorkerGlobalScopeIndexedDatabase::indexedDB() -{ - if (!m_idbFactory) - m_idbFactory = IDBFactory::create(); - return m_idbFactory.get(); -} - -DEFINE_TRACE(WorkerGlobalScopeIndexedDatabase) -{ - visitor->trace(m_idbFactory); - Supplement<WorkerGlobalScope>::trace(visitor); -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/modules/indexeddb/WorkerGlobalScopeIndexedDatabase.h b/third_party/WebKit/Source/modules/indexeddb/WorkerGlobalScopeIndexedDatabase.h deleted file mode 100644 index 8e300c2..0000000 --- a/third_party/WebKit/Source/modules/indexeddb/WorkerGlobalScopeIndexedDatabase.h +++ /dev/null
@@ -1,60 +0,0 @@ -/* - * Copyright (C) 2008, 2009 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#ifndef WorkerGlobalScopeIndexedDatabase_h -#define WorkerGlobalScopeIndexedDatabase_h - -#include "core/workers/WorkerGlobalScope.h" -#include "platform/Supplementable.h" -#include "wtf/Noncopyable.h" - -namespace blink { - -class IDBFactory; -class WorkerGlobalScope; - -class WorkerGlobalScopeIndexedDatabase final : public GarbageCollectedFinalized<WorkerGlobalScopeIndexedDatabase>, public Supplement<WorkerGlobalScope> { - USING_GARBAGE_COLLECTED_MIXIN(WorkerGlobalScopeIndexedDatabase); -public: - virtual ~WorkerGlobalScopeIndexedDatabase(); - static WorkerGlobalScopeIndexedDatabase& from(Supplementable<WorkerGlobalScope>&); - - static IDBFactory* indexedDB(Supplementable<WorkerGlobalScope>&); - - DECLARE_VIRTUAL_TRACE(); - -private: - WorkerGlobalScopeIndexedDatabase(); - - IDBFactory* indexedDB(); - static const char* supplementName(); - - Member<IDBFactory> m_idbFactory; -}; - -} // namespace blink - -#endif // WorkerGlobalScopeIndexedDatabase_h
diff --git a/third_party/WebKit/Source/modules/indexeddb/WorkerGlobalScopeIndexedDatabase.idl b/third_party/WebKit/Source/modules/indexeddb/WorkerGlobalScopeIndexedDatabase.idl index 796cd5d..dbebde3b 100644 --- a/third_party/WebKit/Source/modules/indexeddb/WorkerGlobalScopeIndexedDatabase.idl +++ b/third_party/WebKit/Source/modules/indexeddb/WorkerGlobalScopeIndexedDatabase.idl
@@ -24,7 +24,9 @@ * */ -partial interface WorkerGlobalScope { +[ + ImplementedAs=GlobalIndexedDB +] partial interface WorkerGlobalScope { [ImplementedAs=indexedDB, DeprecateAs=PrefixedIndexedDB] readonly attribute IDBFactory webkitIndexedDB; [DeprecateAs=PrefixedIDBCursorConstructor] attribute IDBCursorConstructor webkitIDBCursor;
diff --git a/third_party/WebKit/Source/modules/modules.gypi b/third_party/WebKit/Source/modules/modules.gypi index faaf3a7..77879ff 100644 --- a/third_party/WebKit/Source/modules/modules.gypi +++ b/third_party/WebKit/Source/modules/modules.gypi
@@ -1133,8 +1133,8 @@ 'geolocation/NavigatorGeolocation.h', 'imagebitmap/ImageBitmapRenderingContext.cpp', 'imagebitmap/ImageBitmapRenderingContext.h', - 'indexeddb/DOMWindowIndexedDatabase.cpp', - 'indexeddb/DOMWindowIndexedDatabase.h', + 'indexeddb/GlobalIndexedDB.cpp', + 'indexeddb/GlobalIndexedDB.h', 'indexeddb/IDBAny.cpp', 'indexeddb/IDBAny.h', 'indexeddb/IDBCursor.cpp', @@ -1182,8 +1182,6 @@ 'indexeddb/WebIDBCallbacksImpl.h', 'indexeddb/WebIDBDatabaseCallbacksImpl.cpp', 'indexeddb/WebIDBDatabaseCallbacksImpl.h', - 'indexeddb/WorkerGlobalScopeIndexedDatabase.cpp', - 'indexeddb/WorkerGlobalScopeIndexedDatabase.h', 'installedapp/InstalledAppController.cpp', 'installedapp/InstalledAppController.h', 'installedapp/NavigatorInstalledApp.cpp',
diff --git a/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.h b/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.h index 1a010d15..d3c80b8c 100644 --- a/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.h +++ b/third_party/WebKit/Source/modules/offscreencanvas2d/OffscreenCanvasRenderingContext2D.h
@@ -61,6 +61,7 @@ bool stateHasFilter() final; SkImageFilter* stateGetFilter() final; + void snapshotStateForFilter() final { } void validateStateStack() final;
diff --git a/third_party/WebKit/Source/modules/webaudio/AbstractAudioContext.cpp b/third_party/WebKit/Source/modules/webaudio/AbstractAudioContext.cpp index 853d94d..c06e0f3 100644 --- a/third_party/WebKit/Source/modules/webaudio/AbstractAudioContext.cpp +++ b/third_party/WebKit/Source/modules/webaudio/AbstractAudioContext.cpp
@@ -189,6 +189,14 @@ return !m_isCleared; } +AudioDestinationNode* AbstractAudioContext::destination() const +{ + // Cannot be called from the audio thread because this method touches objects managed by Oilpan, + // and the audio thread is not managed by Oilpan. + ASSERT(!isAudioThread()); + return m_destinationNode.get(); +} + void AbstractAudioContext::throwExceptionForClosedState(ExceptionState& exceptionState) { exceptionState.throwDOMException(InvalidStateError, "AudioContext has been closed.");
diff --git a/third_party/WebKit/Source/modules/webaudio/AbstractAudioContext.h b/third_party/WebKit/Source/modules/webaudio/AbstractAudioContext.h index 3d847d9..42e175a2 100644 --- a/third_party/WebKit/Source/modules/webaudio/AbstractAudioContext.h +++ b/third_party/WebKit/Source/modules/webaudio/AbstractAudioContext.h
@@ -113,7 +113,8 @@ void stop() final; bool hasPendingActivity() const final; - AudioDestinationNode* destination() const { return m_destinationNode.get(); } + // Cannnot be called from the audio thread. + AudioDestinationNode* destination() const; size_t currentSampleFrame() const {
diff --git a/third_party/WebKit/Source/platform/Prerender.h b/third_party/WebKit/Source/platform/Prerender.h index e942e0e..aff87ae 100644 --- a/third_party/WebKit/Source/platform/Prerender.h +++ b/third_party/WebKit/Source/platform/Prerender.h
@@ -83,7 +83,11 @@ private: Prerender(PrerenderClient*, const KURL&, unsigned relTypes, const Referrer&); - Member<PrerenderClient> m_client; + // The embedder's prerendering support holds on to pending Prerender objects; + // those references should not keep the PrerenderClient alive -- if the client + // becomes otherwise unreachable it should be GCed (at which point it will + // abandon this Prerender object.) + WeakMember<PrerenderClient> m_client; const KURL m_url; const unsigned m_relTypes;
diff --git a/third_party/WebKit/Source/platform/blink_platform.gypi b/third_party/WebKit/Source/platform/blink_platform.gypi index 2069e46e..ffc7b1e1d 100644 --- a/third_party/WebKit/Source/platform/blink_platform.gypi +++ b/third_party/WebKit/Source/platform/blink_platform.gypi
@@ -550,6 +550,8 @@ 'graphics/BitmapImage.h', 'graphics/BitmapImageMetrics.cpp', 'graphics/BitmapImageMetrics.h', + 'graphics/BoxReflection.cpp', + 'graphics/BoxReflection.h', 'graphics/Canvas2DImageBufferSurface.h', 'graphics/Canvas2DLayerBridge.cpp', 'graphics/Canvas2DLayerBridge.h',
diff --git a/third_party/WebKit/Source/platform/graphics/BoxReflection.cpp b/third_party/WebKit/Source/platform/graphics/BoxReflection.cpp new file mode 100644 index 0000000..64e36f4e --- /dev/null +++ b/third_party/WebKit/Source/platform/graphics/BoxReflection.cpp
@@ -0,0 +1,51 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "platform/graphics/BoxReflection.h" + +#include "platform/geometry/FloatRect.h" +#include "platform/graphics/skia/SkiaUtils.h" +#include "third_party/skia/include/core/SkImageFilter.h" +#include "third_party/skia/include/core/SkMatrix.h" +#include "third_party/skia/include/core/SkPicture.h" +#include "third_party/skia/include/core/SkRefCnt.h" +#include "third_party/skia/include/core/SkXfermode.h" +#include "third_party/skia/include/effects/SkPictureImageFilter.h" +#include "third_party/skia/include/effects/SkXfermodeImageFilter.h" + +#include <utility> + +namespace blink { + +SkMatrix BoxReflection::reflectionMatrix() const +{ + SkMatrix flipMatrix; + switch (m_direction) { + case VerticalReflection: + flipMatrix.setScale(1, -1); + flipMatrix.postTranslate(0, m_offset); + break; + case HorizontalReflection: + flipMatrix.setScale(-1, 1); + flipMatrix.postTranslate(m_offset, 0); + break; + default: + // MSVC requires that SkMatrix be initialized in this unreachable case. + NOTREACHED(); + flipMatrix.reset(); + break; + } + return flipMatrix; +} + +FloatRect BoxReflection::mapRect(const FloatRect& rect) const +{ + SkRect reflection(rect); + reflectionMatrix().mapRect(&reflection); + FloatRect result = rect; + result.unite(reflection); + return result; +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/BoxReflection.h b/third_party/WebKit/Source/platform/graphics/BoxReflection.h new file mode 100644 index 0000000..f22482f --- /dev/null +++ b/third_party/WebKit/Source/platform/graphics/BoxReflection.h
@@ -0,0 +1,74 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BoxReflection_h +#define BoxReflection_h + +#include "platform/PlatformExport.h" +#include "third_party/skia/include/core/SkPicture.h" +#include "wtf/PassRefPtr.h" +#include "wtf/RefPtr.h" + +class SkImageFilter; +class SkMatrix; +class SkPicture; + +namespace blink { + +class FloatRect; + +// A reflection, as created by -webkit-box-reflect. Consists of: +// * a direction (either vertical or horizontal) +// * an offset to be applied to the reflection after flipping about the +// x- or y-axis, according to the direction +// * a mask image, which will be applied to the reflection before the +// reflection matrix is applied +class PLATFORM_EXPORT BoxReflection { +public: + enum ReflectionDirection { + // Vertically flipped (to appear above or below). + VerticalReflection, + // Horizontally flipped (to appear to the left or right). + HorizontalReflection, + }; + + BoxReflection(ReflectionDirection direction, float offset, PassRefPtr<SkPicture> mask = nullptr) + : m_direction(direction), m_offset(offset), m_mask(mask) {} + + ReflectionDirection direction() const { return m_direction; } + float offset() const { return m_offset; } + SkPicture* mask() const { return m_mask.get(); } + + // Returns a matrix which maps points between the original content and its + // reflection. Reflections are self-inverse, so this matrix can be used to + // map in either direction. + SkMatrix reflectionMatrix() const; + + // Maps a source rectangle to the destination rectangle it can affect, + // including this reflection. Due to the symmetry of reflections, this can + // also be used to map from a destination rectangle to the source rectangle + // which contributes to it. + FloatRect mapRect(const FloatRect&) const; + +private: + ReflectionDirection m_direction; + float m_offset; + RefPtr<SkPicture> m_mask; +}; + +inline bool operator==(const BoxReflection& a, const BoxReflection& b) +{ + return a.direction() == b.direction() + && a.offset() == b.offset() + && a.mask() == b.mask(); +} + +inline bool operator!=(const BoxReflection& a, const BoxReflection& b) +{ + return !(a == b); +} + +} // namespace blink + +#endif // BoxReflection_h
diff --git a/third_party/WebKit/Source/platform/graphics/CompositorFilterOperations.cpp b/third_party/WebKit/Source/platform/graphics/CompositorFilterOperations.cpp index 0c5de98..8e6ace28 100644 --- a/third_party/WebKit/Source/platform/graphics/CompositorFilterOperations.cpp +++ b/third_party/WebKit/Source/platform/graphics/CompositorFilterOperations.cpp
@@ -88,10 +88,10 @@ cc::FilterOperation::CreateSaturatingBrightnessFilter(amount)); } -void CompositorFilterOperations::appendReferenceFilter(SkImageFilter* imageFilter) +void CompositorFilterOperations::appendReferenceFilter(sk_sp<SkImageFilter> imageFilter) { m_filterOperations.Append( - cc::FilterOperation::CreateReferenceFilter(skia::SharePtr(imageFilter))); + cc::FilterOperation::CreateReferenceFilter(skia::SharePtr(std::move(imageFilter)))); } void CompositorFilterOperations::clear()
diff --git a/third_party/WebKit/Source/platform/graphics/CompositorFilterOperations.h b/third_party/WebKit/Source/platform/graphics/CompositorFilterOperations.h index c5c0f2ec..a2d030f 100644 --- a/third_party/WebKit/Source/platform/graphics/CompositorFilterOperations.h +++ b/third_party/WebKit/Source/platform/graphics/CompositorFilterOperations.h
@@ -38,8 +38,7 @@ void appendZoomFilter(float amount, int inset); void appendSaturatingBrightnessFilter(float amount); - // This grabs a ref on the passed-in filter. - void appendReferenceFilter(SkImageFilter*); + void appendReferenceFilter(sk_sp<SkImageFilter>); void clear(); bool isEmpty() const;
diff --git a/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.cpp b/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.cpp index 2d2dc26..8ccf343 100644 --- a/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.cpp +++ b/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.cpp
@@ -49,7 +49,7 @@ { } -SkData* DecodingImageGenerator::onRefEncodedData() +SkData* DecodingImageGenerator::onRefEncodedData(GrContext* ctx) { TRACE_EVENT0("blink", "DecodingImageGenerator::refEncodedData");
diff --git a/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.h b/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.h index a77fdb2..74ba6cab 100644 --- a/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.h +++ b/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.h
@@ -56,7 +56,7 @@ void setCanYUVDecode(bool yes) { m_canYUVDecode = yes; } protected: - SkData* onRefEncodedData() override; + SkData* onRefEncodedData(GrContext* ctx) override; bool onGetPixels(const SkImageInfo&, void* pixels, size_t rowBytes, SkPMColor table[], int* tableCount) override;
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsContext.cpp b/third_party/WebKit/Source/platform/graphics/GraphicsContext.cpp index 32829b5..dd3cfa5 100644 --- a/third_party/WebKit/Source/platform/graphics/GraphicsContext.cpp +++ b/third_party/WebKit/Source/platform/graphics/GraphicsContext.cpp
@@ -253,7 +253,7 @@ m_canvas->concat(matrix); } -void GraphicsContext::beginLayer(float opacity, SkXfermode::Mode xfermode, const FloatRect* bounds, ColorFilter colorFilter, SkImageFilter* imageFilter) +void GraphicsContext::beginLayer(float opacity, SkXfermode::Mode xfermode, const FloatRect* bounds, ColorFilter colorFilter, sk_sp<SkImageFilter> imageFilter) { if (contextDisabled()) return; @@ -262,7 +262,7 @@ layerPaint.setAlpha(static_cast<unsigned char>(opacity * 255)); layerPaint.setXfermodeMode(xfermode); layerPaint.setColorFilter(toSkSp(WebCoreColorFilterToSkiaColorFilter(colorFilter))); - layerPaint.setImageFilter(imageFilter); + layerPaint.setImageFilter(std::move(imageFilter)); if (bounds) { SkRect skBounds = *bounds; @@ -331,7 +331,7 @@ m_canvas->drawPicture(picture); } -void GraphicsContext::compositePicture(SkPicture* picture, const FloatRect& dest, const FloatRect& src, SkXfermode::Mode op) +void GraphicsContext::compositePicture(PassRefPtr<SkPicture> picture, const FloatRect& dest, const FloatRect& src, SkXfermode::Mode op) { if (contextDisabled() || !picture) return; @@ -345,8 +345,7 @@ SkMatrix pictureTransform; pictureTransform.setRectToRect(sourceBounds, skBounds, SkMatrix::kFill_ScaleToFit); m_canvas->concat(pictureTransform); - RefPtr<SkImageFilter> pictureFilter = adoptRef(SkPictureImageFilter::CreateForLocalSpace(picture, sourceBounds, static_cast<SkFilterQuality>(imageInterpolationQuality()))); - picturePaint.setImageFilter(pictureFilter.get()); + picturePaint.setImageFilter(SkPictureImageFilter::MakeForLocalSpace(toSkSp(picture), sourceBounds, static_cast<SkFilterQuality>(imageInterpolationQuality()))); m_canvas->saveLayer(&sourceBounds, &picturePaint); m_canvas->restore(); m_canvas->restore();
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsContext.h b/third_party/WebKit/Source/platform/graphics/GraphicsContext.h index 207164b..ad88e7a 100644 --- a/third_party/WebKit/Source/platform/graphics/GraphicsContext.h +++ b/third_party/WebKit/Source/platform/graphics/GraphicsContext.h
@@ -158,7 +158,7 @@ void strokeRect(const FloatRect&, float lineWidth); void drawPicture(const SkPicture*); - void compositePicture(SkPicture*, const FloatRect& dest, const FloatRect& src, SkXfermode::Mode); + void compositePicture(PassRefPtr<SkPicture>, const FloatRect& dest, const FloatRect& src, SkXfermode::Mode); void drawImage(Image*, const IntRect&, SkXfermode::Mode = SkXfermode::kSrcOver_Mode, RespectImageOrientationEnum = DoNotRespectImageOrientation); void drawImage(Image*, const FloatRect& destRect, const FloatRect& srcRect, SkXfermode::Mode = SkXfermode::kSrcOver_Mode, RespectImageOrientationEnum = DoNotRespectImageOrientation); @@ -204,7 +204,7 @@ // beginLayer()/endLayer() behaves like save()/restore() for CTM and clip states. // Apply SkXfermode::Mode when the layer is composited on the backdrop (i.e. endLayer()). void beginLayer(float opacity = 1.0f, SkXfermode::Mode = SkXfermode::kSrcOver_Mode, - const FloatRect* = 0, ColorFilter = ColorFilterNone, SkImageFilter* = 0); + const FloatRect* = 0, ColorFilter = ColorFilterNone, sk_sp<SkImageFilter> = nullptr); void endLayer(); // Instead of being dispatched to the active canvas, draw commands following beginRecording()
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsLayer.h b/third_party/WebKit/Source/platform/graphics/GraphicsLayer.h index c3d1f3a..1e71246 100644 --- a/third_party/WebKit/Source/platform/graphics/GraphicsLayer.h +++ b/third_party/WebKit/Source/platform/graphics/GraphicsLayer.h
@@ -177,6 +177,7 @@ void setFilterQuality(SkFilterQuality); // Some GraphicsLayers paint only the foreground or the background content + GraphicsLayerPaintingPhase paintingPhase() const { return m_paintingPhase; } void setPaintingPhase(GraphicsLayerPaintingPhase); void setNeedsDisplay();
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsLayerDebugInfo.cpp b/third_party/WebKit/Source/platform/graphics/GraphicsLayerDebugInfo.cpp index 2abc2db4..417aac8 100644 --- a/third_party/WebKit/Source/platform/graphics/GraphicsLayerDebugInfo.cpp +++ b/third_party/WebKit/Source/platform/graphics/GraphicsLayerDebugInfo.cpp
@@ -76,7 +76,7 @@ { tracedValue->BeginArray("squashing_disallowed_reasons"); for (size_t i = 0; i < kNumberOfSquashingDisallowedReasons; ++i) { - if (!(m_compositingReasons & kSquashingDisallowedReasonStringMap[i].reason)) + if (!(m_squashingDisallowedReasons & kSquashingDisallowedReasonStringMap[i].reason)) continue; tracedValue->AppendString(kSquashingDisallowedReasonStringMap[i].description); }
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsTypes.h b/third_party/WebKit/Source/platform/graphics/GraphicsTypes.h index a8cb842e..610906b 100644 --- a/third_party/WebKit/Source/platform/graphics/GraphicsTypes.h +++ b/third_party/WebKit/Source/platform/graphics/GraphicsTypes.h
@@ -173,13 +173,6 @@ RULE_EVENODD = SkPath::kEvenOdd_FillType }; -enum ReflectionDirection { - // Vertically flipped (to appear above or below). - VerticalReflection, - // Horizontally flipped (to appear to the left or right). - HorizontalReflection, -}; - PLATFORM_EXPORT String compositeOperatorName(CompositeOperator, WebBlendMode); PLATFORM_EXPORT bool parseCompositeAndBlendOperator(const String&, CompositeOperator&, WebBlendMode&);
diff --git a/third_party/WebKit/Source/platform/graphics/RecordingImageBufferSurface.cpp b/third_party/WebKit/Source/platform/graphics/RecordingImageBufferSurface.cpp index 669767a..08caf761 100644 --- a/third_party/WebKit/Source/platform/graphics/RecordingImageBufferSurface.cpp +++ b/third_party/WebKit/Source/platform/graphics/RecordingImageBufferSurface.cpp
@@ -70,6 +70,8 @@ void RecordingImageBufferSurface::fallBackToRasterCanvas(FallbackReason reason) { + ASSERT(m_fallbackFactory); + if (m_fallbackSurface) { ASSERT(!m_currentFrame); return; @@ -178,6 +180,8 @@ bool canUsePicture = finalizeFrameInternal(&fallbackReason); m_imageBuffer->didFinalizeFrame(); + ASSERT(canUsePicture || m_fallbackFactory); + if (canUsePicture) { return m_previousFrame; } @@ -262,7 +266,7 @@ return false; } - if (m_currentFrame->getRecordingCanvas()->getSaveCount() > ExpensiveCanvasHeuristicParameters::ExpensiveRecordingStackDepth) { + if (m_fallbackFactory && m_currentFrame->getRecordingCanvas()->getSaveCount() > ExpensiveCanvasHeuristicParameters::ExpensiveRecordingStackDepth) { *fallbackReason = FallbackReasonRunawayStateStack; return false; }
diff --git a/third_party/WebKit/Source/platform/graphics/RecordingImageBufferSurface.h b/third_party/WebKit/Source/platform/graphics/RecordingImageBufferSurface.h index f7d37ae3..7f87b6b 100644 --- a/third_party/WebKit/Source/platform/graphics/RecordingImageBufferSurface.h +++ b/third_party/WebKit/Source/platform/graphics/RecordingImageBufferSurface.h
@@ -35,7 +35,11 @@ class PLATFORM_EXPORT RecordingImageBufferSurface : public ImageBufferSurface { WTF_MAKE_NONCOPYABLE(RecordingImageBufferSurface); USING_FAST_MALLOC(RecordingImageBufferSurface); public: - RecordingImageBufferSurface(const IntSize&, PassOwnPtr<RecordingImageBufferFallbackSurfaceFactory> fallbackFactory, OpacityMode = NonOpaque); + // If the fallbackFactory is null the buffer surface should only be used + // for one frame and should not be used for any operations which need a + // raster surface, (i.e. writePixels). + // Only #getPicture should be used to access the resulting frame. + RecordingImageBufferSurface(const IntSize&, PassOwnPtr<RecordingImageBufferFallbackSurfaceFactory> fallbackFactory = nullptr, OpacityMode = NonOpaque); ~RecordingImageBufferSurface() override; // Implementation of ImageBufferSurface interfaces
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEBlend.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEBlend.cpp index 7561b29..db6ffe23 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEBlend.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEBlend.cpp
@@ -55,13 +55,13 @@ return true; } -PassRefPtr<SkImageFilter> FEBlend::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FEBlend::createImageFilter(SkiaImageFilterBuilder& builder) { - RefPtr<SkImageFilter> foreground(builder.build(inputEffect(0), operatingColorSpace())); - RefPtr<SkImageFilter> background(builder.build(inputEffect(1), operatingColorSpace())); + sk_sp<SkImageFilter> foreground(builder.build(inputEffect(0), operatingColorSpace())); + sk_sp<SkImageFilter> background(builder.build(inputEffect(1), operatingColorSpace())); sk_sp<SkXfermode> mode(SkXfermode::Make(WebCoreCompositeToSkiaComposite(CompositeSourceOver, m_mode))); SkImageFilter::CropRect cropRect = getCropRect(); - return fromSkSp(SkXfermodeImageFilter::Make(std::move(mode), background.get(), foreground.get(), &cropRect)); + return SkXfermodeImageFilter::Make(std::move(mode), std::move(background), std::move(foreground), &cropRect); } TextStream& FEBlend::externalRepresentation(TextStream& ts, int indent) const
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEBlend.h b/third_party/WebKit/Source/platform/graphics/filters/FEBlend.h index 0ac88ab8..3cf9bdb32 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEBlend.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FEBlend.h
@@ -40,7 +40,7 @@ private: FEBlend(Filter*, WebBlendMode); - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; WebBlendMode m_mode; };
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEBoxReflect.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEBoxReflect.cpp index bd73ca8750..fcba0d7 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEBoxReflect.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEBoxReflect.cpp
@@ -10,15 +10,9 @@ namespace blink { -FEBoxReflect* FEBoxReflect::create(Filter* filter, ReflectionDirection direction, float offset) -{ - return new FEBoxReflect(filter, direction, offset); -} - -FEBoxReflect::FEBoxReflect(Filter* filter, ReflectionDirection direction, float offset) +FEBoxReflect::FEBoxReflect(Filter* filter, const BoxReflection& reflection) : FilterEffect(filter) - , m_reflectionDirection(direction) - , m_offset(offset) + , m_reflection(reflection) { } @@ -28,17 +22,9 @@ FloatRect FEBoxReflect::mapRect(const FloatRect& rect, bool forward) const { - // Reflection about any line is self-inverse, so this matrix works for both - // forward and reverse mapping. - SkMatrix flipMatrix = SkiaImageFilterBuilder().matrixForBoxReflectFilter( - m_reflectionDirection, m_offset); - - SkRect reflection(rect); - flipMatrix.mapRect(&reflection); - - FloatRect result = rect; - result.unite(reflection); - return result; + // Reflection about any line is self-inverse, so this for both forward and + // reverse mapping. + return m_reflection.mapRect(rect); } TextStream& FEBoxReflect::externalRepresentation(TextStream& ts, int indent) const @@ -48,10 +34,9 @@ return ts; } -PassRefPtr<SkImageFilter> FEBoxReflect::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FEBoxReflect::createImageFilter(SkiaImageFilterBuilder& builder) { - RefPtr<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); - return builder.buildBoxReflectFilter(m_reflectionDirection, m_offset, nullptr, input.get()); + return SkiaImageFilterBuilder().buildBoxReflectFilter(m_reflection, builder.build(inputEffect(0), operatingColorSpace())); } } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEBoxReflect.h b/third_party/WebKit/Source/platform/graphics/filters/FEBoxReflect.h index 1b136d1..75d92ee 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEBoxReflect.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FEBoxReflect.h
@@ -6,7 +6,7 @@ #define FEBoxReflect_h #include "platform/PlatformExport.h" -#include "platform/graphics/GraphicsTypes.h" +#include "platform/graphics/BoxReflection.h" #include "platform/graphics/filters/FilterEffect.h" namespace blink { @@ -14,19 +14,21 @@ // Used to implement the -webkit-box-reflect property as a filter. class PLATFORM_EXPORT FEBoxReflect final : public FilterEffect { public: - static FEBoxReflect* create(Filter*, ReflectionDirection, float offset); + static FEBoxReflect* create(Filter* filter, const BoxReflection& reflection) + { + return new FEBoxReflect(filter, reflection); + } // FilterEffect implementation FloatRect mapRect(const FloatRect&, bool forward = true) const final; TextStream& externalRepresentation(TextStream&, int indentation) const final; - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) final; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) final; private: - FEBoxReflect(Filter*, ReflectionDirection, float offset); + FEBoxReflect(Filter*, const BoxReflection&); ~FEBoxReflect() final; - ReflectionDirection m_reflectionDirection; - float m_offset; + BoxReflection m_reflection; }; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEColorMatrix.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEColorMatrix.cpp index 39d5df9..1d8da7f3 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEColorMatrix.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEColorMatrix.cpp
@@ -160,12 +160,12 @@ return m_type == FECOLORMATRIX_TYPE_MATRIX && m_values.size() >= kColorMatrixSize && m_values[19] > 0; } -PassRefPtr<SkImageFilter> FEColorMatrix::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FEColorMatrix::createImageFilter(SkiaImageFilterBuilder& builder) { - RefPtr<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); + sk_sp<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); sk_sp<SkColorFilter> filter = createColorFilter(m_type, m_values); SkImageFilter::CropRect rect = getCropRect(); - return adoptRef(SkColorFilterImageFilter::Create(filter.get(), input.get(), &rect)); + return SkColorFilterImageFilter::Make(std::move(filter), std::move(input), &rect); } static TextStream& operator<<(TextStream& ts, const ColorMatrixType& type)
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEColorMatrix.h b/third_party/WebKit/Source/platform/graphics/filters/FEColorMatrix.h index 3e3d123..942db9f 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEColorMatrix.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FEColorMatrix.h
@@ -54,7 +54,7 @@ private: FEColorMatrix(Filter*, ColorMatrixType, const Vector<float>&); - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; bool affectsTransparentPixels() override;
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEComponentTransfer.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEComponentTransfer.cpp index a086b117..9fc272f 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEComponentTransfer.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEComponentTransfer.cpp
@@ -128,16 +128,16 @@ return 255 * intercept >= 1; } -PassRefPtr<SkImageFilter> FEComponentTransfer::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FEComponentTransfer::createImageFilter(SkiaImageFilterBuilder& builder) { - RefPtr<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); + sk_sp<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); unsigned char rValues[256], gValues[256], bValues[256], aValues[256]; getValues(rValues, gValues, bValues, aValues); SkImageFilter::CropRect cropRect = getCropRect(); sk_sp<SkColorFilter> colorFilter = SkTableColorFilter::MakeARGB(aValues, rValues, gValues, bValues); - return adoptRef(SkColorFilterImageFilter::Create(colorFilter.get(), input.get(), &cropRect)); + return SkColorFilterImageFilter::Make(std::move(colorFilter), std::move(input), &cropRect); } void FEComponentTransfer::getValues(unsigned char rValues[256], unsigned char gValues[256], unsigned char bValues[256], unsigned char aValues[256])
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEComponentTransfer.h b/third_party/WebKit/Source/platform/graphics/filters/FEComponentTransfer.h index 8dcd95c..0706fad5 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEComponentTransfer.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FEComponentTransfer.h
@@ -71,7 +71,7 @@ FEComponentTransfer(Filter*, const ComponentTransferFunction& redFunc, const ComponentTransferFunction& greenFunc, const ComponentTransferFunction& blueFunc, const ComponentTransferFunction& alphaFunc); - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; bool affectsTransparentPixels() override;
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEComposite.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEComposite.cpp index 67026eb..4101427 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEComposite.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEComposite.cpp
@@ -191,27 +191,27 @@ } } -PassRefPtr<SkImageFilter> FEComposite::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FEComposite::createImageFilter(SkiaImageFilterBuilder& builder) { return createImageFilterInternal(builder, true); } -PassRefPtr<SkImageFilter> FEComposite::createImageFilterWithoutValidation(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FEComposite::createImageFilterWithoutValidation(SkiaImageFilterBuilder& builder) { return createImageFilterInternal(builder, false); } -PassRefPtr<SkImageFilter> FEComposite::createImageFilterInternal(SkiaImageFilterBuilder& builder, bool requiresPMColorValidation) +sk_sp<SkImageFilter> FEComposite::createImageFilterInternal(SkiaImageFilterBuilder& builder, bool requiresPMColorValidation) { - RefPtr<SkImageFilter> foreground(builder.build(inputEffect(0), operatingColorSpace(), !mayProduceInvalidPreMultipliedPixels())); - RefPtr<SkImageFilter> background(builder.build(inputEffect(1), operatingColorSpace(), !mayProduceInvalidPreMultipliedPixels())); + sk_sp<SkImageFilter> foreground(builder.build(inputEffect(0), operatingColorSpace(), !mayProduceInvalidPreMultipliedPixels())); + sk_sp<SkImageFilter> background(builder.build(inputEffect(1), operatingColorSpace(), !mayProduceInvalidPreMultipliedPixels())); SkImageFilter::CropRect cropRect = getCropRect(); sk_sp<SkXfermode> mode; if (m_type == FECOMPOSITE_OPERATOR_ARITHMETIC) mode = SkArithmeticMode::Make(SkFloatToScalar(m_k1), SkFloatToScalar(m_k2), SkFloatToScalar(m_k3), SkFloatToScalar(m_k4), requiresPMColorValidation); else mode = SkXfermode::Make(toXfermode(m_type)); - return fromSkSp(SkXfermodeImageFilter::Make(std::move(mode), background.get(), foreground.get(), &cropRect)); + return SkXfermodeImageFilter::Make(std::move(mode), std::move(background), std::move(foreground), &cropRect); } static TextStream& operator<<(TextStream& ts, const CompositeOperationType& type)
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEComposite.h b/third_party/WebKit/Source/platform/graphics/filters/FEComposite.h index 085e252..8ea1e33 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEComposite.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FEComposite.h
@@ -68,9 +68,9 @@ private: FEComposite(Filter*, const CompositeOperationType&, float, float, float, float); - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; - PassRefPtr<SkImageFilter> createImageFilterWithoutValidation(SkiaImageFilterBuilder&) override; - PassRefPtr<SkImageFilter> createImageFilterInternal(SkiaImageFilterBuilder&, bool requiresPMColorValidation); + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilterWithoutValidation(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilterInternal(SkiaImageFilterBuilder&, bool requiresPMColorValidation); CompositeOperationType m_type; float m_k1;
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEConvolveMatrix.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEConvolveMatrix.cpp index b19909e3..fd9b8c6 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEConvolveMatrix.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEConvolveMatrix.cpp
@@ -136,12 +136,12 @@ return true; } -PassRefPtr<SkImageFilter> FEConvolveMatrix::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FEConvolveMatrix::createImageFilter(SkiaImageFilterBuilder& builder) { if (!parametersValid()) return createTransparentBlack(builder); - RefPtr<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); + sk_sp<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); SkISize kernelSize(SkISize::Make(m_kernelSize.width(), m_kernelSize.height())); // parametersValid() above checks that the kernel area fits in int. int numElements = safeCast<int>(m_kernelSize.area()); @@ -154,7 +154,7 @@ for (int i = 0; i < numElements; ++i) kernel[i] = SkFloatToScalar(m_kernelMatrix[numElements - 1 - i]); SkImageFilter::CropRect cropRect = getCropRect(); - return adoptRef(SkMatrixConvolutionImageFilter::Create(kernelSize, kernel.get(), gain, bias, target, tileMode, convolveAlpha, input.get(), &cropRect)); + return SkMatrixConvolutionImageFilter::Make(kernelSize, kernel.get(), gain, bias, target, tileMode, convolveAlpha, std::move(input), &cropRect); } static TextStream& operator<<(TextStream& ts, const EdgeModeType& type)
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEConvolveMatrix.h b/third_party/WebKit/Source/platform/graphics/filters/FEConvolveMatrix.h index 0e42081..fe20ebc 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEConvolveMatrix.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FEConvolveMatrix.h
@@ -58,7 +58,7 @@ FEConvolveMatrix(Filter*, const IntSize&, float, float, const IntPoint&, EdgeModeType, bool, const Vector<float>&); - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; bool parametersValid() const;
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEDisplacementMap.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEDisplacementMap.cpp index cc9ddb5..ba6ca9b0 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEDisplacementMap.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEDisplacementMap.cpp
@@ -109,16 +109,16 @@ } } -PassRefPtr<SkImageFilter> FEDisplacementMap::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FEDisplacementMap::createImageFilter(SkiaImageFilterBuilder& builder) { - RefPtr<SkImageFilter> color = builder.build(inputEffect(0), operatingColorSpace()); - RefPtr<SkImageFilter> displ = builder.build(inputEffect(1), operatingColorSpace()); + sk_sp<SkImageFilter> color = builder.build(inputEffect(0), operatingColorSpace()); + sk_sp<SkImageFilter> displ = builder.build(inputEffect(1), operatingColorSpace()); SkDisplacementMapEffect::ChannelSelectorType typeX = toSkiaMode(m_xChannelSelector); SkDisplacementMapEffect::ChannelSelectorType typeY = toSkiaMode(m_yChannelSelector); SkImageFilter::CropRect cropRect = getCropRect(); // FIXME : Only applyHorizontalScale is used and applyVerticalScale is ignored // This can be fixed by adding a 2nd scale parameter to SkDisplacementMapEffect - return adoptRef(SkDisplacementMapEffect::Create(typeX, typeY, SkFloatToScalar(getFilter()->applyHorizontalScale(m_scale)), displ.get(), color.get(), &cropRect)); + return SkDisplacementMapEffect::Make(typeX, typeY, SkFloatToScalar(getFilter()->applyHorizontalScale(m_scale)), std::move(displ), std::move(color), &cropRect); } static TextStream& operator<<(TextStream& ts, const ChannelSelectorType& type)
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEDisplacementMap.h b/third_party/WebKit/Source/platform/graphics/filters/FEDisplacementMap.h index 50ae7a1f..0e76ef24 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEDisplacementMap.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FEDisplacementMap.h
@@ -57,7 +57,7 @@ private: FEDisplacementMap(Filter*, ChannelSelectorType xChannelSelector, ChannelSelectorType yChannelSelector, float); - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; ChannelSelectorType m_xChannelSelector; ChannelSelectorType m_yChannelSelector;
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEDropShadow.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEDropShadow.cpp index 5bf275a..60b44e08 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEDropShadow.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEDropShadow.cpp
@@ -65,16 +65,16 @@ return result; } -PassRefPtr<SkImageFilter> FEDropShadow::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FEDropShadow::createImageFilter(SkiaImageFilterBuilder& builder) { - RefPtr<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); + sk_sp<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); float dx = getFilter()->applyHorizontalScale(m_dx); float dy = getFilter()->applyVerticalScale(m_dy); float stdX = getFilter()->applyHorizontalScale(m_stdX); float stdY = getFilter()->applyVerticalScale(m_stdY); Color color = adaptColorToOperatingColorSpace(m_shadowColor.combineWithAlpha(m_shadowOpacity)); SkImageFilter::CropRect cropRect = getCropRect(); - return adoptRef(SkDropShadowImageFilter::Create(SkFloatToScalar(dx), SkFloatToScalar(dy), SkFloatToScalar(stdX), SkFloatToScalar(stdY), color.rgb(), SkDropShadowImageFilter::kDrawShadowAndForeground_ShadowMode, input.get(), &cropRect)); + return SkDropShadowImageFilter::Make(SkFloatToScalar(dx), SkFloatToScalar(dy), SkFloatToScalar(stdX), SkFloatToScalar(stdY), color.rgb(), SkDropShadowImageFilter::kDrawShadowAndForeground_ShadowMode, std::move(input), &cropRect); }
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEDropShadow.h b/third_party/WebKit/Source/platform/graphics/filters/FEDropShadow.h index 7305c486..d4c4913c 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEDropShadow.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FEDropShadow.h
@@ -33,7 +33,7 @@ FloatRect mapRect(const FloatRect&, bool forward = true) const final; TextStream& externalRepresentation(TextStream&, int indention) const override; - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; private: FEDropShadow(Filter*, float, float, float, float, const Color&, float);
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEFlood.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEFlood.cpp index 5f6519b8..dd3af72 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEFlood.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEFlood.cpp
@@ -69,13 +69,12 @@ return true; } -PassRefPtr<SkImageFilter> FEFlood::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FEFlood::createImageFilter(SkiaImageFilterBuilder& builder) { Color color = floodColor().combineWithAlpha(floodOpacity()); SkImageFilter::CropRect rect = getCropRect(); - sk_sp<SkColorFilter> colorFilter = SkColorFilter::MakeModeFilter(color.rgb(), SkXfermode::kSrc_Mode); - return adoptRef(SkColorFilterImageFilter::Create(colorFilter.get(), 0, &rect)); + return SkColorFilterImageFilter::Make(SkColorFilter::MakeModeFilter(color.rgb(), SkXfermode::kSrc_Mode), 0, &rect); } TextStream& FEFlood::externalRepresentation(TextStream& ts, int indent) const
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEFlood.h b/third_party/WebKit/Source/platform/graphics/filters/FEFlood.h index ffd81e9..5eb969d9 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEFlood.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FEFlood.h
@@ -47,7 +47,7 @@ private: FEFlood(Filter*, const Color&, float); - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; Color m_floodColor; float m_floodOpacity;
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEGaussianBlur.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEGaussianBlur.cpp index bf3fd068..87f6518 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEGaussianBlur.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEGaussianBlur.cpp
@@ -107,13 +107,13 @@ return outputRect; } -PassRefPtr<SkImageFilter> FEGaussianBlur::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FEGaussianBlur::createImageFilter(SkiaImageFilterBuilder& builder) { - RefPtr<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); + sk_sp<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); float stdX = getFilter()->applyHorizontalScale(m_stdX); float stdY = getFilter()->applyVerticalScale(m_stdY); SkImageFilter::CropRect rect = getCropRect(); - return adoptRef(SkBlurImageFilter::Create(SkFloatToScalar(stdX), SkFloatToScalar(stdY), input.get(), &rect)); + return SkBlurImageFilter::Make(SkFloatToScalar(stdX), SkFloatToScalar(stdY), std::move(input), &rect); } TextStream& FEGaussianBlur::externalRepresentation(TextStream& ts, int indent) const
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEGaussianBlur.h b/third_party/WebKit/Source/platform/graphics/filters/FEGaussianBlur.h index 45b78f7e..f026ce2 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEGaussianBlur.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FEGaussianBlur.h
@@ -41,7 +41,7 @@ private: FEGaussianBlur(Filter*, float, float); - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; float m_stdX; float m_stdY;
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FELighting.cpp b/third_party/WebKit/Source/platform/graphics/filters/FELighting.cpp index 5d4f21572..dc925dc7 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FELighting.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FELighting.cpp
@@ -58,14 +58,14 @@ return result; } -PassRefPtr<SkImageFilter> FELighting::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FELighting::createImageFilter(SkiaImageFilterBuilder& builder) { if (!m_lightSource) return createTransparentBlack(builder); SkImageFilter::CropRect rect = getCropRect(); Color lightColor = adaptColorToOperatingColorSpace(m_lightingColor); - RefPtr<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); + sk_sp<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); switch (m_lightSource->type()) { case LS_DISTANT: { DistantLightSource* distantLightSource = static_cast<DistantLightSource*>(m_lightSource.get()); @@ -73,16 +73,16 @@ float elevationRad = deg2rad(distantLightSource->elevation()); const SkPoint3 direction = SkPoint3::Make(cosf(azimuthRad) * cosf(elevationRad), sinf(azimuthRad) * cosf(elevationRad), sinf(elevationRad)); if (m_specularConstant > 0) - return adoptRef(SkLightingImageFilter::CreateDistantLitSpecular(direction, lightColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input.get(), &rect)); - return adoptRef(SkLightingImageFilter::CreateDistantLitDiffuse(direction, lightColor.rgb(), m_surfaceScale, m_diffuseConstant, input.get(), &rect)); + return SkLightingImageFilter::MakeDistantLitSpecular(direction, lightColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, std::move(input), &rect); + return SkLightingImageFilter::MakeDistantLitDiffuse(direction, lightColor.rgb(), m_surfaceScale, m_diffuseConstant, std::move(input), &rect); } case LS_POINT: { PointLightSource* pointLightSource = static_cast<PointLightSource*>(m_lightSource.get()); const FloatPoint3D position = pointLightSource->position(); const SkPoint3 skPosition = SkPoint3::Make(position.x(), position.y(), position.z()); if (m_specularConstant > 0) - return adoptRef(SkLightingImageFilter::CreatePointLitSpecular(skPosition, lightColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input.get(), &rect)); - return adoptRef(SkLightingImageFilter::CreatePointLitDiffuse(skPosition, lightColor.rgb(), m_surfaceScale, m_diffuseConstant, input.get(), &rect)); + return SkLightingImageFilter::MakePointLitSpecular(skPosition, lightColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, std::move(input), &rect); + return SkLightingImageFilter::MakePointLitDiffuse(skPosition, lightColor.rgb(), m_surfaceScale, m_diffuseConstant, std::move(input), &rect); } case LS_SPOT: { SpotLightSource* spotLightSource = static_cast<SpotLightSource*>(m_lightSource.get()); @@ -93,8 +93,8 @@ if (!limitingConeAngle || limitingConeAngle > 90 || limitingConeAngle < -90) limitingConeAngle = 90; if (m_specularConstant > 0) - return adoptRef(SkLightingImageFilter::CreateSpotLitSpecular(location, target, specularExponent, limitingConeAngle, lightColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input.get(), &rect)); - return adoptRef(SkLightingImageFilter::CreateSpotLitDiffuse(location, target, specularExponent, limitingConeAngle, lightColor.rgb(), m_surfaceScale, m_diffuseConstant, input.get(), &rect)); + return SkLightingImageFilter::MakeSpotLitSpecular(location, target, specularExponent, limitingConeAngle, lightColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, std::move(input), &rect); + return SkLightingImageFilter::MakeSpotLitDiffuse(location, target, specularExponent, limitingConeAngle, lightColor.rgb(), m_surfaceScale, m_diffuseConstant, std::move(input), &rect); } default: ASSERT_NOT_REACHED();
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FELighting.h b/third_party/WebKit/Source/platform/graphics/filters/FELighting.h index b97914c..649116c 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FELighting.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FELighting.h
@@ -44,7 +44,7 @@ SpecularLighting }; - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; FloatRect mapPaintRect(const FloatRect&, bool forward = true) const final; bool affectsTransparentPixels() override { return true; }
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEMerge.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEMerge.cpp index addd37e..e9381a8 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEMerge.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEMerge.cpp
@@ -39,18 +39,15 @@ return new FEMerge(filter); } -PassRefPtr<SkImageFilter> FEMerge::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FEMerge::createImageFilter(SkiaImageFilterBuilder& builder) { unsigned size = numberOfEffectInputs(); - OwnPtr<RefPtr<SkImageFilter>[]> inputRefs = adoptArrayPtr(new RefPtr<SkImageFilter>[size]); - OwnPtr<SkImageFilter*[]> inputs = adoptArrayPtr(new SkImageFilter*[size]); - for (unsigned i = 0; i < size; ++i) { + OwnPtr<sk_sp<SkImageFilter>[]> inputRefs = adoptArrayPtr(new sk_sp<SkImageFilter>[size]); + for (unsigned i = 0; i < size; ++i) inputRefs[i] = builder.build(inputEffect(i), operatingColorSpace()); - inputs[i] = inputRefs[i].get(); - } SkImageFilter::CropRect rect = getCropRect(); - return adoptRef(SkMergeImageFilter::Create(inputs.get(), size, 0, &rect)); + return SkMergeImageFilter::Make(inputRefs.get(), size, 0, &rect); } TextStream& FEMerge::externalRepresentation(TextStream& ts, int indent) const
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEMerge.h b/third_party/WebKit/Source/platform/graphics/filters/FEMerge.h index 9986c5d3..4b88677b 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEMerge.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FEMerge.h
@@ -36,7 +36,7 @@ private: explicit FEMerge(Filter*); - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; }; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEMorphology.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEMorphology.cpp index 2f3bfcd..3e13fe84 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEMorphology.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEMorphology.cpp
@@ -93,15 +93,15 @@ return result; } -PassRefPtr<SkImageFilter> FEMorphology::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FEMorphology::createImageFilter(SkiaImageFilterBuilder& builder) { - RefPtr<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); + sk_sp<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); SkScalar radiusX = SkFloatToScalar(getFilter()->applyHorizontalScale(m_radiusX)); SkScalar radiusY = SkFloatToScalar(getFilter()->applyVerticalScale(m_radiusY)); SkImageFilter::CropRect rect = getCropRect(); if (m_type == FEMORPHOLOGY_OPERATOR_DILATE) - return adoptRef(SkDilateImageFilter::Create(radiusX, radiusY, input.get(), &rect)); - return adoptRef(SkErodeImageFilter::Create(radiusX, radiusY, input.get(), &rect)); + return SkDilateImageFilter::Make(radiusX, radiusY, std::move(input), &rect); + return SkErodeImageFilter::Make(radiusX, radiusY, std::move(input), &rect); } static TextStream& operator<<(TextStream& ts, const MorphologyOperatorType& type)
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEMorphology.h b/third_party/WebKit/Source/platform/graphics/filters/FEMorphology.h index 17fd1b2..8cb82be 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEMorphology.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FEMorphology.h
@@ -52,7 +52,7 @@ private: FEMorphology(Filter*, MorphologyOperatorType, float radiusX, float radiusY); - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; MorphologyOperatorType m_type; float m_radiusX;
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEOffset.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEOffset.cpp index a9ceb34..e5ccfd7 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEOffset.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEOffset.cpp
@@ -73,12 +73,11 @@ return result; } -PassRefPtr<SkImageFilter> FEOffset::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FEOffset::createImageFilter(SkiaImageFilterBuilder& builder) { - RefPtr<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); Filter* filter = this->getFilter(); SkImageFilter::CropRect cropRect = getCropRect(); - return adoptRef(SkOffsetImageFilter::Create(SkFloatToScalar(filter->applyHorizontalScale(m_dx)), SkFloatToScalar(filter->applyVerticalScale(m_dy)), input.get(), &cropRect)); + return SkOffsetImageFilter::Make(SkFloatToScalar(filter->applyHorizontalScale(m_dx)), SkFloatToScalar(filter->applyVerticalScale(m_dy)), builder.build(inputEffect(0), operatingColorSpace()), &cropRect); } TextStream& FEOffset::externalRepresentation(TextStream& ts, int indent) const
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEOffset.h b/third_party/WebKit/Source/platform/graphics/filters/FEOffset.h index 41797a2..9b8adcf 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEOffset.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FEOffset.h
@@ -44,7 +44,7 @@ private: FEOffset(Filter*, float dx, float dy); - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; float m_dx; float m_dy;
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FETile.cpp b/third_party/WebKit/Source/platform/graphics/filters/FETile.cpp index df734c2..9136fd45 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FETile.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FETile.cpp
@@ -43,12 +43,12 @@ return forward ? maxEffectRect() : inputEffect(0)->maxEffectRect(); } -PassRefPtr<SkImageFilter> FETile::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FETile::createImageFilter(SkiaImageFilterBuilder& builder) { - RefPtr<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); + sk_sp<SkImageFilter> input(builder.build(inputEffect(0), operatingColorSpace())); FloatRect srcRect = inputEffect(0)->filterPrimitiveSubregion(); FloatRect dstRect = applyEffectBoundaries(getFilter()->filterRegion()); - return adoptRef(SkTileImageFilter::Create(srcRect, dstRect, input.get())); + return SkTileImageFilter::Make(srcRect, dstRect, std::move(input)); } TextStream& FETile::externalRepresentation(TextStream& ts, int indent) const
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FETile.h b/third_party/WebKit/Source/platform/graphics/filters/FETile.h index d44a161..99acef0 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FETile.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FETile.h
@@ -40,7 +40,7 @@ private: FETile(Filter*); - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; }; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FETurbulence.cpp b/third_party/WebKit/Source/platform/graphics/filters/FETurbulence.cpp index c391bb10..f307f51 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FETurbulence.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FETurbulence.cpp
@@ -146,7 +146,7 @@ stitchTiles() ? &size : 0); } -PassRefPtr<SkImageFilter> FETurbulence::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FETurbulence::createImageFilter(SkiaImageFilterBuilder& builder) { if (m_baseFrequencyX < 0 || m_baseFrequencyY < 0) return createTransparentBlack(builder); @@ -154,7 +154,7 @@ SkPaint paint; paint.setShader(createShader()); SkImageFilter::CropRect rect = getCropRect(); - return adoptRef(SkPaintImageFilter::Create(paint, &rect)); + return SkPaintImageFilter::Make(paint, &rect); } static TextStream& operator<<(TextStream& ts, const TurbulenceType& type)
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FETurbulence.h b/third_party/WebKit/Source/platform/graphics/filters/FETurbulence.h index d67bedd..7a06648 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FETurbulence.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FETurbulence.h
@@ -64,7 +64,7 @@ private: FETurbulence(Filter*, TurbulenceType, float, float, int, float, bool); - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; sk_sp<SkShader> createShader() const; TurbulenceType m_type;
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FilterEffect.cpp b/third_party/WebKit/Source/platform/graphics/filters/FilterEffect.cpp index 06ffe78..c92c651c 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FilterEffect.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FilterEffect.cpp
@@ -189,12 +189,12 @@ return subregion; } -PassRefPtr<SkImageFilter> FilterEffect::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FilterEffect::createImageFilter(SkiaImageFilterBuilder&) { return nullptr; } -PassRefPtr<SkImageFilter> FilterEffect::createImageFilterWithoutValidation(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> FilterEffect::createImageFilterWithoutValidation(SkiaImageFilterBuilder& builder) { return createImageFilter(builder); } @@ -208,11 +208,11 @@ return false; } -PassRefPtr<SkImageFilter> FilterEffect::createTransparentBlack(SkiaImageFilterBuilder& builder) const +sk_sp<SkImageFilter> FilterEffect::createTransparentBlack(SkiaImageFilterBuilder& builder) const { SkImageFilter::CropRect rect = getCropRect(); sk_sp<SkColorFilter> colorFilter = SkColorFilter::MakeModeFilter(0, SkXfermode::kClear_Mode); - return adoptRef(SkColorFilterImageFilter::Create(colorFilter.get(), nullptr, &rect)); + return SkColorFilterImageFilter::Make(std::move(colorFilter), nullptr, &rect); } SkImageFilter::CropRect FilterEffect::getCropRect() const @@ -242,10 +242,10 @@ return m_imageFilters[index].get(); } -void FilterEffect::setImageFilter(ColorSpace colorSpace, bool requiresPMColorValidation, PassRefPtr<SkImageFilter> imageFilter) +void FilterEffect::setImageFilter(ColorSpace colorSpace, bool requiresPMColorValidation, sk_sp<SkImageFilter> imageFilter) { int index = getImageFilterIndex(colorSpace, requiresPMColorValidation); - m_imageFilters[index] = imageFilter; + m_imageFilters[index] = std::move(imageFilter); } } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FilterEffect.h b/third_party/WebKit/Source/platform/graphics/filters/FilterEffect.h index 4e00f582..0c9f24c3 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FilterEffect.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FilterEffect.h
@@ -82,8 +82,8 @@ FloatRect maxEffectRect() const { return m_maxEffectRect; } void setMaxEffectRect(const FloatRect& maxEffectRect) { m_maxEffectRect = maxEffectRect; } - virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&); - virtual PassRefPtr<SkImageFilter> createImageFilterWithoutValidation(SkiaImageFilterBuilder&); + virtual sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&); + virtual sk_sp<SkImageFilter> createImageFilterWithoutValidation(SkiaImageFilterBuilder&); // Mapping a rect forwards determines which which destination pixels a // given source rect would affect. Mapping a rect backwards determines @@ -146,7 +146,7 @@ virtual bool mayProduceInvalidPreMultipliedPixels() { return false; } SkImageFilter* getImageFilter(ColorSpace, bool requiresPMColorValidation) const; - void setImageFilter(ColorSpace, bool requiresPMColorValidation, PassRefPtr<SkImageFilter>); + void setImageFilter(ColorSpace, bool requiresPMColorValidation, sk_sp<SkImageFilter>); bool originTainted() const { return m_originTainted; } void setOriginTainted() { m_originTainted = true; } @@ -156,7 +156,7 @@ protected: FilterEffect(Filter*); - PassRefPtr<SkImageFilter> createTransparentBlack(SkiaImageFilterBuilder&) const; + sk_sp<SkImageFilter> createTransparentBlack(SkiaImageFilterBuilder&) const; Color adaptColorToOperatingColorSpace(const Color& deviceColor); @@ -196,7 +196,7 @@ ColorSpace m_operatingColorSpace; - RefPtr<SkImageFilter> m_imageFilters[4]; + sk_sp<SkImageFilter> m_imageFilters[4]; }; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FilterOperation.cpp b/third_party/WebKit/Source/platform/graphics/filters/FilterOperation.cpp index 46baef0..4616533 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FilterOperation.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FilterOperation.cpp
@@ -192,17 +192,7 @@ FloatRect BoxReflectFilterOperation::mapRect(const FloatRect& rect) const { - // Reflection about any line is self-inverse, so this matrix works for both - // forward and reverse mapping. - SkMatrix flipMatrix = SkiaImageFilterBuilder().matrixForBoxReflectFilter( - m_direction, m_offset); - - SkRect reflection(rect); - flipMatrix.mapRect(&reflection); - - FloatRect result = rect; - result.unite(reflection); - return result; + return m_reflection.mapRect(rect); } FilterOperation* BoxReflectFilterOperation::blend(const FilterOperation* from, double progress) const @@ -216,7 +206,7 @@ if (!isSameType(o)) return false; const auto& other = static_cast<const BoxReflectFilterOperation&>(o); - return m_direction == other.m_direction && m_offset == other.m_offset; + return m_reflection == other.m_reflection; } } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FilterOperation.h b/third_party/WebKit/Source/platform/graphics/filters/FilterOperation.h index e9bd90d..2d33ec1 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FilterOperation.h +++ b/third_party/WebKit/Source/platform/graphics/filters/FilterOperation.h
@@ -28,8 +28,8 @@ #include "platform/Length.h" #include "platform/PlatformExport.h" +#include "platform/graphics/BoxReflection.h" #include "platform/graphics/Color.h" -#include "platform/graphics/GraphicsTypes.h" #include "platform/graphics/filters/Filter.h" #include "platform/heap/Handle.h" #include "wtf/Noncopyable.h" @@ -322,13 +322,12 @@ class PLATFORM_EXPORT BoxReflectFilterOperation : public FilterOperation { public: - static BoxReflectFilterOperation* create(ReflectionDirection direction, float offset) + static BoxReflectFilterOperation* create(const BoxReflection& reflection) { - return new BoxReflectFilterOperation(direction, offset); + return new BoxReflectFilterOperation(reflection); } - ReflectionDirection direction() const { return m_direction; } - float offset() const { return m_offset; } + const BoxReflection& reflection() const { return m_reflection; } bool affectsOpacity() const override { return true; } bool movesPixels() const override { return true; } @@ -338,15 +337,13 @@ FilterOperation* blend(const FilterOperation* from, double progress) const override; bool operator==(const FilterOperation&) const override; - BoxReflectFilterOperation(ReflectionDirection direction, float offset) + BoxReflectFilterOperation(const BoxReflection& reflection) : FilterOperation(BOX_REFLECT) - , m_direction(direction) - , m_offset(offset) + , m_reflection(reflection) { } - ReflectionDirection m_direction; - float m_offset; + BoxReflection m_reflection; }; DEFINE_FILTER_OPERATION_TYPE_CASTS(BoxReflectFilterOperation, BOX_REFLECT);
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FilterOperationsTest.cpp b/third_party/WebKit/Source/platform/graphics/filters/FilterOperationsTest.cpp index a51acd7..ecb4268 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FilterOperationsTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FilterOperationsTest.cpp
@@ -57,7 +57,8 @@ TEST(FilterOperationsTest, mapRectBoxReflect) { FilterOperations ops; - ops.operations().append(BoxReflectFilterOperation::create(VerticalReflection, 100)); + ops.operations().append(BoxReflectFilterOperation::create( + BoxReflection(BoxReflection::VerticalReflection, 100))); EXPECT_TRUE(ops.hasFilterThatMovesPixels()); // original IntRect(0, 0, 10, 10) + reflection IntRect(90, 90, 10, 10) @@ -70,7 +71,8 @@ // important that the bounds be filtered in the correct order. FilterOperations ops; ops.operations().append(DropShadowFilterOperation::create(IntPoint(100, 200), 0, Color::black)); - ops.operations().append(BoxReflectFilterOperation::create(VerticalReflection, 50)); + ops.operations().append(BoxReflectFilterOperation::create( + BoxReflection(BoxReflection::VerticalReflection, 50))); EXPECT_TRUE(ops.hasFilterThatMovesPixels()); EXPECT_EQ(FloatRect(0, -160, 110, 370), ops.mapRect(FloatRect(0, 0, 10, 10)));
diff --git a/third_party/WebKit/Source/platform/graphics/filters/ImageFilterBuilderTest.cpp b/third_party/WebKit/Source/platform/graphics/filters/ImageFilterBuilderTest.cpp index 50c25a5d..8700e1e5 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/ImageFilterBuilderTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/ImageFilterBuilderTest.cpp
@@ -72,7 +72,7 @@ // Get SkImageFilter resulting tree SkiaImageFilterBuilder builder; - RefPtr<SkImageFilter> filter = builder.build(referenceFilter->lastEffect(), ColorSpaceDeviceRGB); + sk_sp<SkImageFilter> filter = builder.build(referenceFilter->lastEffect(), ColorSpaceDeviceRGB); // Let's check that the resulting tree looks like this : // ColorSpace (Linear->Device) : CS (L->D)
diff --git a/third_party/WebKit/Source/platform/graphics/filters/PaintFilterEffect.cpp b/third_party/WebKit/Source/platform/graphics/filters/PaintFilterEffect.cpp index a86950b..4a8997a 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/PaintFilterEffect.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/PaintFilterEffect.cpp
@@ -26,9 +26,9 @@ return new PaintFilterEffect(filter, paint); } -PassRefPtr<SkImageFilter> PaintFilterEffect::createImageFilter(SkiaImageFilterBuilder&) +sk_sp<SkImageFilter> PaintFilterEffect::createImageFilter(SkiaImageFilterBuilder&) { - return adoptRef(SkPaintImageFilter::Create(m_paint, nullptr)); + return SkPaintImageFilter::Make(m_paint, nullptr); } TextStream& PaintFilterEffect::externalRepresentation(TextStream& ts, int indent) const
diff --git a/third_party/WebKit/Source/platform/graphics/filters/PaintFilterEffect.h b/third_party/WebKit/Source/platform/graphics/filters/PaintFilterEffect.h index edd3b6e..fdee14dc4 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/PaintFilterEffect.h +++ b/third_party/WebKit/Source/platform/graphics/filters/PaintFilterEffect.h
@@ -18,7 +18,7 @@ FilterEffectType getFilterEffectType() const override { return FilterEffectTypeSourceInput; } TextStream& externalRepresentation(TextStream&, int indention) const override; - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; private: PaintFilterEffect(Filter*, const SkPaint&);
diff --git a/third_party/WebKit/Source/platform/graphics/filters/SkiaImageFilterBuilder.cpp b/third_party/WebKit/Source/platform/graphics/filters/SkiaImageFilterBuilder.cpp index 1442d438..8c6bde0 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/SkiaImageFilterBuilder.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/SkiaImageFilterBuilder.cpp
@@ -30,6 +30,7 @@ #include "SkColorMatrixFilter.h" #include "SkTableColorFilter.h" #include "platform/geometry/IntPoint.h" +#include "platform/graphics/BoxReflection.h" #include "platform/graphics/filters/FilterEffect.h" #include "platform/graphics/filters/FilterOperations.h" #include "platform/graphics/filters/SourceGraphic.h" @@ -43,7 +44,7 @@ { } -PassRefPtr<SkImageFilter> SkiaImageFilterBuilder::build(FilterEffect* effect, ColorSpace colorSpace, bool destinationRequiresValidPreMultipliedPixels) +sk_sp<SkImageFilter> SkiaImageFilterBuilder::build(FilterEffect* effect, ColorSpace colorSpace, bool destinationRequiresValidPreMultipliedPixels) { if (!effect) return nullptr; @@ -51,37 +52,35 @@ bool requiresPMColorValidation = effect->mayProduceInvalidPreMultipliedPixels() && destinationRequiresValidPreMultipliedPixels; if (SkImageFilter* filter = effect->getImageFilter(colorSpace, requiresPMColorValidation)) - return filter; + return sk_ref_sp(filter); // Note that we may still need the color transform even if the filter is null - RefPtr<SkImageFilter> origFilter = requiresPMColorValidation ? effect->createImageFilter(*this) : effect->createImageFilterWithoutValidation(*this); - RefPtr<SkImageFilter> filter = transformColorSpace(origFilter.get(), effect->operatingColorSpace(), colorSpace); - effect->setImageFilter(colorSpace, requiresPMColorValidation, filter.get()); + sk_sp<SkImageFilter> origFilter = requiresPMColorValidation ? effect->createImageFilter(*this) : effect->createImageFilterWithoutValidation(*this); + sk_sp<SkImageFilter> filter = transformColorSpace(origFilter, effect->operatingColorSpace(), colorSpace); + effect->setImageFilter(colorSpace, requiresPMColorValidation, filter); if (filter.get() != origFilter.get()) - effect->setImageFilter(effect->operatingColorSpace(), requiresPMColorValidation, origFilter.get()); - return filter.release(); + effect->setImageFilter(effect->operatingColorSpace(), requiresPMColorValidation, std::move(origFilter)); + return filter; } -PassRefPtr<SkImageFilter> SkiaImageFilterBuilder::transformColorSpace( - SkImageFilter* input, ColorSpace srcColorSpace, ColorSpace dstColorSpace) { +sk_sp<SkImageFilter> SkiaImageFilterBuilder::transformColorSpace( + sk_sp<SkImageFilter> input, ColorSpace srcColorSpace, ColorSpace dstColorSpace) { - RefPtr<SkColorFilter> colorFilter = ColorSpaceUtilities::createColorSpaceFilter(srcColorSpace, dstColorSpace); + sk_sp<SkColorFilter> colorFilter = toSkSp(ColorSpaceUtilities::createColorSpaceFilter(srcColorSpace, dstColorSpace)); if (!colorFilter) return input; - return adoptRef(SkColorFilterImageFilter::Create(colorFilter.get(), input)); + return SkColorFilterImageFilter::Make(std::move(colorFilter), std::move(input)); } void SkiaImageFilterBuilder::buildFilterOperations(const FilterOperations& operations, CompositorFilterOperations* filters) { ColorSpace currentColorSpace = ColorSpaceDeviceRGB; - SkImageFilter* const nullFilter = 0; for (size_t i = 0; i < operations.size(); ++i) { const FilterOperation& op = *operations.at(i); switch (op.type()) { case FilterOperation::REFERENCE: { - RefPtr<SkImageFilter> filter; Filter* referenceFilter = toReferenceFilterOperation(op).getFilter(); if (referenceFilter && referenceFilter->lastEffect()) { FilterEffect* filterEffect = referenceFilter->lastEffect(); @@ -91,18 +90,17 @@ // initialize SourceGraphic with both options. // Since we know SourceGraphic is always PM-valid, we also use // these for the PM-validated options. - RefPtr<SkImageFilter> deviceFilter = transformColorSpace(nullFilter, currentColorSpace, ColorSpaceDeviceRGB); - RefPtr<SkImageFilter> linearFilter = transformColorSpace(nullFilter, currentColorSpace, ColorSpaceLinearRGB); + sk_sp<SkImageFilter> deviceFilter = transformColorSpace(nullptr, currentColorSpace, ColorSpaceDeviceRGB); + sk_sp<SkImageFilter> linearFilter = transformColorSpace(nullptr, currentColorSpace, ColorSpaceLinearRGB); FilterEffect* sourceGraphic = referenceFilter->getSourceGraphic(); - sourceGraphic->setImageFilter(ColorSpaceDeviceRGB, false, deviceFilter.get()); - sourceGraphic->setImageFilter(ColorSpaceLinearRGB, false, linearFilter.get()); - sourceGraphic->setImageFilter(ColorSpaceDeviceRGB, true, deviceFilter.get()); - sourceGraphic->setImageFilter(ColorSpaceLinearRGB, true, linearFilter.get()); + sourceGraphic->setImageFilter(ColorSpaceDeviceRGB, false, deviceFilter); + sourceGraphic->setImageFilter(ColorSpaceLinearRGB, false, linearFilter); + sourceGraphic->setImageFilter(ColorSpaceDeviceRGB, true, deviceFilter); + sourceGraphic->setImageFilter(ColorSpaceLinearRGB, true, linearFilter); currentColorSpace = filterEffect->operatingColorSpace(); filterEffect->determineFilterPrimitiveSubregion(MapRectForward); - filter = SkiaImageFilterBuilder::build(filterEffect, currentColorSpace); - filters->appendReferenceFilter(filter.get()); + filters->appendReferenceFilter(SkiaImageFilterBuilder::build(filterEffect, currentColorSpace)); } break; } @@ -165,10 +163,8 @@ case FilterOperation::BOX_REFLECT: { // TODO(jbroman): Consider explaining box reflect to the compositor, // instead of calling this a "reference filter". - const auto& reflectOperation = toBoxReflectFilterOperation(op); - RefPtr<SkImageFilter> imageFilter = buildBoxReflectFilter( - reflectOperation.direction(), reflectOperation.offset(), nullptr, nullFilter); - filters->appendReferenceFilter(imageFilter.get()); + const auto& reflection = toBoxReflectFilterOperation(op).reflection(); + filters->appendReferenceFilter(buildBoxReflectFilter(reflection, nullptr)); break; } case FilterOperation::NONE: @@ -177,47 +173,24 @@ } if (currentColorSpace != ColorSpaceDeviceRGB) { // Transform to device color space at the end of processing, if required - RefPtr<SkImageFilter> filter = transformColorSpace(nullFilter, currentColorSpace, ColorSpaceDeviceRGB); - filters->appendReferenceFilter(filter.get()); + sk_sp<SkImageFilter> filter = transformColorSpace(nullptr, currentColorSpace, ColorSpaceDeviceRGB); + filters->appendReferenceFilter(std::move(filter)); } } -PassRefPtr<SkImageFilter> SkiaImageFilterBuilder::buildTransform(const AffineTransform& transform, SkImageFilter* input) +sk_sp<SkImageFilter> SkiaImageFilterBuilder::buildTransform(const AffineTransform& transform, sk_sp<SkImageFilter> input) { - return adoptRef(SkImageFilter::CreateMatrixFilter(affineTransformToSkMatrix(transform), kHigh_SkFilterQuality, input)); + return SkImageFilter::MakeMatrixFilter(affineTransformToSkMatrix(transform), kHigh_SkFilterQuality, std::move(input)); } -SkMatrix SkiaImageFilterBuilder::matrixForBoxReflectFilter(ReflectionDirection direction, float offset) +sk_sp<SkImageFilter> SkiaImageFilterBuilder::buildBoxReflectFilter(const BoxReflection& reflection, sk_sp<SkImageFilter> input) { - SkMatrix flipMatrix; - switch (direction) { - case VerticalReflection: - flipMatrix.setScale(1, -1); - flipMatrix.postTranslate(0, offset); - break; - case HorizontalReflection: - flipMatrix.setScale(-1, 1); - flipMatrix.postTranslate(offset, 0); - break; - default: - // MSVC requires that SkMatrix be initialized in this unreachable case. - NOTREACHED(); - flipMatrix.reset(); - break; - } - return flipMatrix; -} - -PassRefPtr<SkImageFilter> SkiaImageFilterBuilder::buildBoxReflectFilter(ReflectionDirection direction, float offset, Image* maskImage, SkImageFilter* input) -{ - RefPtr<SkImageFilter> maskedInput = input; + sk_sp<SkImageFilter> maskedInput = input; // TODO(jbroman): If a mask image is provided, mask! - SkMatrix flipMatrix = matrixForBoxReflectFilter(direction, offset); - RefPtr<SkImageFilter> flipImageFilter = adoptRef(SkImageFilter::CreateMatrixFilter( - flipMatrix, kLow_SkFilterQuality, maskedInput.get())); - - return fromSkSp(SkXfermodeImageFilter::Make(nullptr, flipImageFilter.get(), input, nullptr)); + sk_sp<SkImageFilter> flipImageFilter = SkImageFilter::MakeMatrixFilter( + reflection.reflectionMatrix(), kLow_SkFilterQuality, std::move(maskedInput)); + return SkXfermodeImageFilter::Make(nullptr, std::move(flipImageFilter), std::move(input), nullptr); } } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/filters/SkiaImageFilterBuilder.h b/third_party/WebKit/Source/platform/graphics/filters/SkiaImageFilterBuilder.h index efbcdf5..f8e15440 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/SkiaImageFilterBuilder.h +++ b/third_party/WebKit/Source/platform/graphics/filters/SkiaImageFilterBuilder.h
@@ -34,11 +34,11 @@ #include "platform/heap/Handle.h" class SkImageFilter; -class SkMatrix; namespace blink { class AffineTransform; +class BoxReflection; class FilterEffect; class FilterOperations; class Image; @@ -48,16 +48,14 @@ public: ~SkiaImageFilterBuilder(); - PassRefPtr<SkImageFilter> build(FilterEffect*, ColorSpace, bool requiresPMColorValidation = true); + sk_sp<SkImageFilter> build(FilterEffect*, ColorSpace, bool requiresPMColorValidation = true); void buildFilterOperations(const FilterOperations&, CompositorFilterOperations*); - PassRefPtr<SkImageFilter> buildTransform(const AffineTransform&, SkImageFilter* input); + sk_sp<SkImageFilter> buildTransform(const AffineTransform&, sk_sp<SkImageFilter> input); - PassRefPtr<SkImageFilter> transformColorSpace( - SkImageFilter* input, ColorSpace srcColorSpace, ColorSpace dstColorSpace); + sk_sp<SkImageFilter> transformColorSpace( + sk_sp<SkImageFilter> input, ColorSpace srcColorSpace, ColorSpace dstColorSpace); - SkMatrix matrixForBoxReflectFilter(ReflectionDirection, float offset); - PassRefPtr<SkImageFilter> buildBoxReflectFilter( - ReflectionDirection, float offset, Image* maskImage, SkImageFilter* input); + sk_sp<SkImageFilter> buildBoxReflectFilter(const BoxReflection&, sk_sp<SkImageFilter> input); }; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/filters/SourceAlpha.cpp b/third_party/WebKit/Source/platform/graphics/filters/SourceAlpha.cpp index f20f989..9d84f3b9 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/SourceAlpha.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/SourceAlpha.cpp
@@ -46,9 +46,9 @@ return inputEffect(0)->determineAbsolutePaintRect(requestedRect); } -PassRefPtr<SkImageFilter> SourceAlpha::createImageFilter(SkiaImageFilterBuilder& builder) +sk_sp<SkImageFilter> SourceAlpha::createImageFilter(SkiaImageFilterBuilder& builder) { - RefPtr<SkImageFilter> sourceGraphic(builder.build(inputEffect(0), operatingColorSpace())); + sk_sp<SkImageFilter> sourceGraphic(builder.build(inputEffect(0), operatingColorSpace())); SkScalar matrix[20] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -56,7 +56,7 @@ 0, 0, 0, SK_Scalar1, 0 }; sk_sp<SkColorFilter> colorFilter = SkColorFilter::MakeMatrixFilterRowMajor255(matrix); - return adoptRef(SkColorFilterImageFilter::Create(colorFilter.get(), sourceGraphic.get())); + return SkColorFilterImageFilter::Make(std::move(colorFilter), std::move(sourceGraphic)); } TextStream& SourceAlpha::externalRepresentation(TextStream& ts, int indent) const
diff --git a/third_party/WebKit/Source/platform/graphics/filters/SourceAlpha.h b/third_party/WebKit/Source/platform/graphics/filters/SourceAlpha.h index 5e37e7c..47e4c57 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/SourceAlpha.h +++ b/third_party/WebKit/Source/platform/graphics/filters/SourceAlpha.h
@@ -34,7 +34,7 @@ FilterEffectType getFilterEffectType() const override { return FilterEffectTypeSourceInput; } TextStream& externalRepresentation(TextStream&, int indention) const override; - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; private: explicit SourceAlpha(FilterEffect*);
diff --git a/third_party/WebKit/Source/platform/graphics/filters/SourceGraphic.cpp b/third_party/WebKit/Source/platform/graphics/filters/SourceGraphic.cpp index 150badb..8725011 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/SourceGraphic.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/SourceGraphic.cpp
@@ -49,9 +49,9 @@ return srcRect; } -void SourceGraphic::setPicture(PassRefPtr<const SkPicture> picture) +void SourceGraphic::setPicture(sk_sp<SkPicture> picture) { - m_picture = picture; + m_picture = std::move(picture); } void SourceGraphic::setSourceRect(const IntRect& sourceRect) @@ -59,12 +59,12 @@ m_sourceRect = sourceRect; } -PassRefPtr<SkImageFilter> SourceGraphic::createImageFilter(SkiaImageFilterBuilder&) +sk_sp<SkImageFilter> SourceGraphic::createImageFilter(SkiaImageFilterBuilder&) { if (!m_picture) return nullptr; - return adoptRef(SkPictureImageFilter::Create(m_picture.get(), m_picture->cullRect())); + return SkPictureImageFilter::Make(m_picture, m_picture->cullRect()); } TextStream& SourceGraphic::externalRepresentation(TextStream& ts, int indent) const
diff --git a/third_party/WebKit/Source/platform/graphics/filters/SourceGraphic.h b/third_party/WebKit/Source/platform/graphics/filters/SourceGraphic.h index 9c9d2ca..3aec12e 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/SourceGraphic.h +++ b/third_party/WebKit/Source/platform/graphics/filters/SourceGraphic.h
@@ -39,15 +39,15 @@ FilterEffectType getFilterEffectType() const override { return FilterEffectTypeSourceInput; } TextStream& externalRepresentation(TextStream&, int indention) const override; - PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; + sk_sp<SkImageFilter> createImageFilter(SkiaImageFilterBuilder&) override; - void setPicture(PassRefPtr<const SkPicture>); + void setPicture(sk_sp<SkPicture>); void setSourceRect(const IntRect&); private: explicit SourceGraphic(Filter*); - RefPtr<const SkPicture> m_picture; + sk_sp<SkPicture> m_picture; IntRect m_sourceRect; };
diff --git a/third_party/WebKit/Source/platform/graphics/paint/FilterDisplayItem.cpp b/third_party/WebKit/Source/platform/graphics/paint/FilterDisplayItem.cpp index 4df3f6b..5ab5dcf 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/FilterDisplayItem.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/FilterDisplayItem.cpp
@@ -14,7 +14,7 @@ FloatRect imageFilterBounds(FloatPoint(), m_bounds.size()); context.save(); context.translate(m_bounds.x(), m_bounds.y()); - context.beginLayer(1, SkXfermode::kSrcOver_Mode, &imageFilterBounds, ColorFilterNone, m_imageFilter.get()); + context.beginLayer(1, SkXfermode::kSrcOver_Mode, &imageFilterBounds, ColorFilterNone, m_imageFilter); context.translate(-m_bounds.x(), -m_bounds.y()); }
diff --git a/third_party/WebKit/Source/platform/graphics/paint/FilterDisplayItem.h b/third_party/WebKit/Source/platform/graphics/paint/FilterDisplayItem.h index 1e7b71b..0c67a4a 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/FilterDisplayItem.h +++ b/third_party/WebKit/Source/platform/graphics/paint/FilterDisplayItem.h
@@ -18,9 +18,9 @@ class PLATFORM_EXPORT BeginFilterDisplayItem final : public PairedBeginDisplayItem { public: - BeginFilterDisplayItem(const DisplayItemClient& client, PassRefPtr<SkImageFilter> imageFilter, const FloatRect& bounds, PassOwnPtr<CompositorFilterOperations> filterOperations = nullptr) + BeginFilterDisplayItem(const DisplayItemClient& client, sk_sp<SkImageFilter> imageFilter, const FloatRect& bounds, PassOwnPtr<CompositorFilterOperations> filterOperations = nullptr) : PairedBeginDisplayItem(client, BeginFilter, sizeof(*this)) - , m_imageFilter(imageFilter) + , m_imageFilter(std::move(imageFilter)) , m_webFilterOperations(std::move(filterOperations)) , m_bounds(bounds) { } @@ -42,7 +42,7 @@ #endif // FIXME: m_imageFilter should be replaced with m_webFilterOperations when copying data to the compositor. - RefPtr<SkImageFilter> m_imageFilter; + sk_sp<SkImageFilter> m_imageFilter; OwnPtr<CompositorFilterOperations> m_webFilterOperations; const FloatRect m_bounds; };
diff --git a/third_party/WebKit/Source/web/DevToolsEmulator.cpp b/third_party/WebKit/Source/web/DevToolsEmulator.cpp index fde42d1..9b1e490 100644 --- a/third_party/WebKit/Source/web/DevToolsEmulator.cpp +++ b/third_party/WebKit/Source/web/DevToolsEmulator.cpp
@@ -59,7 +59,7 @@ , m_embedderTextAutosizingEnabled(webViewImpl->page()->settings().textAutosizingEnabled()) , m_embedderDeviceScaleAdjustment(webViewImpl->page()->settings().deviceScaleAdjustment()) , m_embedderPreferCompositingToLCDTextEnabled(webViewImpl->page()->settings().preferCompositingToLCDTextEnabled()) - , m_embedderUseMobileViewport(webViewImpl->page()->settings().useMobileViewportStyle()) + , m_embedderViewportStyle(webViewImpl->page()->settings().viewportStyle()) , m_embedderPluginsEnabled(webViewImpl->page()->settings().pluginsEnabled()) , m_embedderAvailablePointerTypes(webViewImpl->page()->settings().availablePointerTypes()) , m_embedderPrimaryPointerType(webViewImpl->page()->settings().primaryPointerType()) @@ -114,12 +114,12 @@ m_webViewImpl->page()->settings().setPreferCompositingToLCDTextEnabled(enabled); } -void DevToolsEmulator::setUseMobileViewportStyle(bool enabled) +void DevToolsEmulator::setViewportStyle(WebViewportStyle style) { - m_embedderUseMobileViewport = enabled; + m_embedderViewportStyle = style; bool emulateMobileEnabled = m_deviceMetricsEnabled && m_emulateMobileEnabled; if (!emulateMobileEnabled) - m_webViewImpl->page()->settings().setUseMobileViewportStyle(enabled); + m_webViewImpl->page()->settings().setViewportStyle(style); } void DevToolsEmulator::setPluginsEnabled(bool enabled) @@ -264,7 +264,7 @@ m_isMobileLayoutThemeEnabled = RuntimeEnabledFeatures::mobileLayoutThemeEnabled(); RuntimeEnabledFeatures::setMobileLayoutThemeEnabled(true); ComputedStyle::invalidateInitialStyle(); - m_webViewImpl->page()->settings().setUseMobileViewportStyle(true); + m_webViewImpl->page()->settings().setViewportStyle(WebViewportStyle::Mobile); m_webViewImpl->page()->settings().setViewportEnabled(true); m_webViewImpl->page()->settings().setViewportMetaEnabled(true); m_webViewImpl->page()->frameHost().visualViewport().initializeScrollbars(); @@ -302,7 +302,7 @@ m_webViewImpl->settings()->setShrinksViewportContentToFit(false); m_webViewImpl->page()->settings().setTextAutosizingEnabled(m_embedderTextAutosizingEnabled); m_webViewImpl->page()->settings().setPreferCompositingToLCDTextEnabled(m_embedderPreferCompositingToLCDTextEnabled); - m_webViewImpl->page()->settings().setUseMobileViewportStyle(m_embedderUseMobileViewport); + m_webViewImpl->page()->settings().setViewportStyle(m_embedderViewportStyle); m_webViewImpl->page()->settings().setPluginsEnabled(m_embedderPluginsEnabled); m_webViewImpl->page()->settings().setAvailablePointerTypes(m_embedderAvailablePointerTypes); m_webViewImpl->page()->settings().setPrimaryPointerType(m_embedderPrimaryPointerType);
diff --git a/third_party/WebKit/Source/web/DevToolsEmulator.h b/third_party/WebKit/Source/web/DevToolsEmulator.h index de03c91..f5da9d568 100644 --- a/third_party/WebKit/Source/web/DevToolsEmulator.h +++ b/third_party/WebKit/Source/web/DevToolsEmulator.h
@@ -7,6 +7,7 @@ #include "platform/heap/Handle.h" #include "public/platform/PointerProperties.h" +#include "public/platform/WebViewportStyle.h" #include "public/web/WebDeviceEmulationParams.h" #include "wtf/Forward.h" #include "wtf/OwnPtr.h" @@ -28,7 +29,7 @@ void setTextAutosizingEnabled(bool); void setDeviceScaleAdjustment(float); void setPreferCompositingToLCDTextEnabled(bool); - void setUseMobileViewportStyle(bool); + void setViewportStyle(WebViewportStyle); void setPluginsEnabled(bool); void setScriptEnabled(bool); void setDoubleTapToZoomEnabled(bool); @@ -69,7 +70,7 @@ bool m_embedderTextAutosizingEnabled; float m_embedderDeviceScaleAdjustment; bool m_embedderPreferCompositingToLCDTextEnabled; - bool m_embedderUseMobileViewport; + WebViewportStyle m_embedderViewportStyle; bool m_embedderPluginsEnabled; int m_embedderAvailablePointerTypes; PointerType m_embedderPrimaryPointerType;
diff --git a/third_party/WebKit/Source/web/WebSettingsImpl.cpp b/third_party/WebKit/Source/web/WebSettingsImpl.cpp index d8dbe90..14d019be 100644 --- a/third_party/WebKit/Source/web/WebSettingsImpl.cpp +++ b/third_party/WebKit/Source/web/WebSettingsImpl.cpp
@@ -798,9 +798,9 @@ m_settings->setV8CacheOptions(static_cast<blink::V8CacheOptions>(options)); } -void WebSettingsImpl::setUseMobileViewportStyle(bool enabled) +void WebSettingsImpl::setViewportStyle(WebViewportStyle style) { - m_devToolsEmulator->setUseMobileViewportStyle(enabled); + m_devToolsEmulator->setViewportStyle(style); } } // namespace blink
diff --git a/third_party/WebKit/Source/web/WebSettingsImpl.h b/third_party/WebKit/Source/web/WebSettingsImpl.h index 36d9a6e..7f5ea5fe 100644 --- a/third_party/WebKit/Source/web/WebSettingsImpl.h +++ b/third_party/WebKit/Source/web/WebSettingsImpl.h
@@ -177,7 +177,7 @@ void setUnifiedTextCheckerEnabled(bool) override; void setUsesEncodingDetector(bool) override; void setUseLegacyBackgroundSizeShorthandBehavior(bool) override; - void setUseMobileViewportStyle(bool) override; + void setViewportStyle(WebViewportStyle) override; void setUseSolidColorScrollbars(bool) override; void setUseWideViewport(bool) override; void setV8CacheOptions(V8CacheOptions) override;
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/servers/apache_http.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/servers/apache_http.py index 134880b..59b676cd4 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/servers/apache_http.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/servers/apache_http.py
@@ -60,6 +60,7 @@ document_root = self._filesystem.join(test_dir, "http", "tests") js_test_resources_dir = self._filesystem.join(test_dir, "resources") forms_test_resources_dir = self._filesystem.join(test_dir, "fast", "forms", "resources") + imported_resources_dir = self._filesystem.join(test_dir, "imported", "web-platform-tests", "resources") media_resources_dir = self._filesystem.join(test_dir, "media") mime_types_path = self._filesystem.join(test_dir, "http", "conf", "mime.types") cert_file = self._filesystem.join(test_dir, "http", "conf", "webkit-httpd.pem") @@ -76,6 +77,9 @@ '-C', 'ServerRoot "%s"' % server_root, '-C', 'DocumentRoot "%s"' % document_root, '-c', 'Alias /js-test-resources "%s"' % js_test_resources_dir, + '-c', 'AliasMatch ^/resources/testharness([r.].*) "%s/testharness$1"' % imported_resources_dir, + '-c', 'Alias /w3c/resources/WebIDLParser.js "%s/webidl2/lib/webidl2.js"' % imported_resources_dir, + '-c', 'Alias /w3c/resources "%s"' % imported_resources_dir, '-c', 'Alias /forms-test-resources "%s"' % forms_test_resources_dir, '-c', 'Alias /media-resources "%s"' % media_resources_dir, '-c', 'TypesConfig "%s"' % mime_types_path,
diff --git a/third_party/WebKit/public/blink_resources.grd b/third_party/WebKit/public/blink_resources.grd index 342e8be..c627ca6 100644 --- a/third_party/WebKit/public/blink_resources.grd +++ b/third_party/WebKit/public/blink_resources.grd
@@ -32,6 +32,7 @@ <include name="IDR_UASTYLE_FULLSCREEN_CSS" file="../Source/core/css/fullscreen.css" type="BINDATA"/> <include name="IDR_UASTYLE_XHTMLMP_CSS" file="../Source/core/css/xhtmlmp.css" type="BINDATA"/> <include name="IDR_UASTYLE_VIEWPORT_ANDROID_CSS" file="../Source/core/css/viewportAndroid.css" type="BINDATA"/> + <include name="IDR_UASTYLE_VIEWPORT_TELEVISION_CSS" file="../Source/core/css/viewportTelevision.css" type="BINDATA"/> <include name="IDR_INSPECTOR_OVERLAY_PAGE_HTML" file="../Source/core/inspector/InspectorOverlayPage.html" type="BINDATA"/> <include name="IDR_PRIVATE_SCRIPT_DOCUMENTEXECCOMMAND_JS" file="../Source/core/editing/js/DocumentExecCommand.js" type="BINDATA"/>
diff --git a/third_party/WebKit/public/platform/WebViewportStyle.h b/third_party/WebKit/public/platform/WebViewportStyle.h new file mode 100644 index 0000000..0cf1e2f --- /dev/null +++ b/third_party/WebKit/public/platform/WebViewportStyle.h
@@ -0,0 +1,21 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef WebViewportStyle_h +#define WebViewportStyle_h + +namespace blink { + +// UA style if viewport is enabled. +enum class WebViewportStyle { + Default, + // Includes viewportAndroid.css. + Mobile, + // Includes viewportTelevision.css. + Television +}; + +} // namespace blink + +#endif // WebViewportStyle_h
diff --git a/third_party/WebKit/public/web/WebSettings.h b/third_party/WebKit/public/web/WebSettings.h index 17cfafe..0ed0f2c 100644 --- a/third_party/WebKit/public/web/WebSettings.h +++ b/third_party/WebKit/public/web/WebSettings.h
@@ -34,6 +34,7 @@ #include "../platform/PointerProperties.h" #include "../platform/WebCommon.h" #include "../platform/WebSize.h" +#include "../platform/WebViewportStyle.h" #include <unicode/uscript.h> namespace blink { @@ -236,7 +237,7 @@ virtual void setTouchDragDropEnabled(bool) = 0; virtual void setUnifiedTextCheckerEnabled(bool) = 0; virtual void setUseLegacyBackgroundSizeShorthandBehavior(bool) = 0; - virtual void setUseMobileViewportStyle(bool) = 0; + virtual void setViewportStyle(WebViewportStyle) = 0; virtual void setUseSolidColorScrollbars(bool) = 0; virtual void setUseWideViewport(bool) = 0; virtual void setUsesEncodingDetector(bool) = 0;
diff --git a/third_party/android_swipe_refresh/OWNERS b/third_party/android_swipe_refresh/OWNERS index 5e41936..d3930d9 100644 --- a/third_party/android_swipe_refresh/OWNERS +++ b/third_party/android_swipe_refresh/OWNERS
@@ -1,2 +1 @@ -aurimas@chromium.org tedchoc@chromium.org
diff --git a/third_party/ijar/BUILD.gn b/third_party/ijar/BUILD.gn index 7fbb45c9..044edc4 100644 --- a/third_party/ijar/BUILD.gn +++ b/third_party/ijar/BUILD.gn
@@ -10,9 +10,15 @@ "classfile.cc", "common.h", "ijar.cc", + "mapped_file.h", "zip.cc", "zip.h", ] + if (is_win) { + sources += [ "mapped_file_windows.cc" ] + } else { + sources += [ "mapped_file_unix.cc" ] + } # Always build release since this is a build tool. if (is_debug) {
diff --git a/third_party/ijar/README.chromium b/third_party/ijar/README.chromium index 80dc09c..8f6bb02 100644 --- a/third_party/ijar/README.chromium +++ b/third_party/ijar/README.chromium
@@ -1,7 +1,7 @@ Name: ijar URL: https://github.com/google/bazel/tree/master/third_party/ijar Version: 0 -Revision: 3a160e754eaa27be157f463c42ecea045906516f +Revision: 31c8878fa3ed34356d90642c19e46e4a06d84f4a License: Apache 2.0 Security Critical: No @@ -11,3 +11,5 @@ Local Modifications: - Removed test directory - Added BUILD.gn and ijar.gni +- Enabled CRC32 zip entries by passing true to 3rd parameter of FinishFile() + within ijar.cc
diff --git a/third_party/ijar/classfile.cc b/third_party/ijar/classfile.cc index 39d24f9..9d48429 100644 --- a/third_party/ijar/classfile.cc +++ b/third_party/ijar/classfile.cc
@@ -1,6 +1,4 @@ -// Copyright 2001,2007 Alan Donovan. All rights reserved. -// -// Author: Alan Donovan <adonovan@google.com> +// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -34,11 +32,25 @@ #include <stdlib.h> #include <string.h> +#include <set> +#include <sstream> #include <string> #include <vector> #include "third_party/ijar/common.h" +namespace { +// Converts a value to string. +// Workaround for mingw where std::to_string is not implemented. +// See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52015. +template <typename T> +std::string ToString(const T& value) { + std::ostringstream oss; + oss << value; + return oss.str(); +} +} // namespace + namespace devtools_ijar { // See Table 4.3 in JVM Spec. @@ -60,17 +72,19 @@ }; // See Tables 4.1, 4.4, 4.5 in JVM Spec. -enum ACCESS { - ACC_PUBLIC = 0x0001, - ACC_PRIVATE = 0x0002, - ACC_PROTECTED = 0x0004, - ACC_STATIC = 0x0008, - ACC_FINAL = 0x0010, - ACC_SYNCHRONIZED = 0x0020, - ACC_VOLATILE = 0x0040, - ACC_TRANSIENT = 0x0080, - ACC_INTERFACE = 0x0200, - ACC_ABSTRACT = 0x0400 +enum ACCESS { + ACC_PUBLIC = 0x0001, + ACC_PRIVATE = 0x0002, + ACC_PROTECTED = 0x0004, + ACC_STATIC = 0x0008, + ACC_FINAL = 0x0010, + ACC_SYNCHRONIZED = 0x0020, + ACC_BRIDGE = 0x0040, + ACC_VOLATILE = 0x0040, + ACC_TRANSIENT = 0x0080, + ACC_INTERFACE = 0x0200, + ACC_ABSTRACT = 0x0400, + ACC_SYNTHETIC = 0x1000 }; // See Table 4.7.20-A in Java 8 JVM Spec. @@ -99,6 +113,8 @@ // TODO(adonovan) these globals are unfortunate static std::vector<Constant*> const_pool_in; // input constant pool static std::vector<Constant*> const_pool_out; // output constant_pool +static std::set<std::string> used_class_names; +static Constant * class_name; // Returns the Constant object, given an index into the input constant pool. // Note: constant(0) == NULL; this invariant is exploited by the @@ -138,6 +154,10 @@ // calling slot() on them in turn. virtual void Keep() {} + bool Kept() { + return slot_ != 0; + } + // Returns the index of this constant in the output class's constant // pool, assigning a slot if not already done. u2 slot() { @@ -163,6 +183,13 @@ u1 tag_; }; +// Extracts class names from a signature and puts them into the global +// variable used_class_names. +// +// desc: the descriptor class names should be extracted from. +// p: the position where the extraction should tart. +void ExtractClassNames(const std::string& desc, size_t* p); + // See sec.4.4.1 of JVM spec. struct Constant_Class : Constant { @@ -335,7 +362,7 @@ } std::string Display() { - return "Constant_MethodHandle::" + std::to_string(reference_kind_) + "::" + return "Constant_MethodHandle::" + ToString(reference_kind_) + "::" + constant(reference_index_)->Display(); } @@ -378,7 +405,7 @@ std::string Display() { return "Constant_InvokeDynamic::" - + std::to_string(bootstrap_method_attr_index_) + "::" + + ToString(bootstrap_method_attr_index_) + "::" + constant(name_and_type_index_)->Display(); } @@ -397,6 +424,7 @@ virtual ~Attribute() {} virtual void Write(u1 *&p) = 0; + virtual void ExtractClassNames() {} void WriteProlog(u1 *&p, u2 length) { put_u2be(p, attribute_name_->slot()); @@ -464,10 +492,51 @@ } void Write(u1 *&p) { - WriteProlog(p, 2 + entries_.size() * 8); - put_u2be(p, entries_.size()); - for (size_t ii = 0; ii < entries_.size(); ++ii) { - Entry *entry = entries_[ii]; + std::set<int> kept_entries; + // We keep an entry if the constant referring to the inner class is already + // kept. Then we mark its outer class and its class name as kept, too, then + // iterate until a fixed point is reached. + int entry_count; + int iteration = 0; + + do { + entry_count = kept_entries.size(); + for (int i_entry = 0; i_entry < static_cast<int>(entries_.size()); + ++i_entry) { + Entry* entry = entries_[i_entry]; + if (entry->inner_class_info->Kept() || + used_class_names.find(entry->inner_class_info->Display()) != + used_class_names.end() || + entry->outer_class_info == class_name) { + if (entry->inner_name == NULL) { + // JVMS 4.7.6: inner_name_index is zero iff the class is anonymous + continue; + } + + kept_entries.insert(i_entry); + + // JVMS 4.7.6: outer_class_info_index is zero for top-level classes + if (entry->outer_class_info != NULL) { + entry->outer_class_info->slot(); + } + + entry->inner_name->slot(); + } + } + iteration += 1; + } while (entry_count != static_cast<int>(kept_entries.size())); + + if (kept_entries.size() == 0) { + return; + } + + WriteProlog(p, 2 + kept_entries.size() * 8); + put_u2be(p, kept_entries.size()); + + for (std::set<int>::iterator it = kept_entries.begin(); + it != kept_entries.end(); + ++it) { + Entry *entry = entries_[*it]; put_u2be(p, entry->inner_class_info == NULL ? 0 : entry->inner_class_info->slot()); @@ -516,6 +585,7 @@ struct ElementValue { virtual ~ElementValue() {} virtual void Write(u1 *&p) = 0; + virtual void ExtractClassNames() {} static ElementValue* Read(const u1 *&p); u1 tag_; u4 length_; @@ -555,6 +625,12 @@ put_u1(p, tag_); put_u2be(p, class_info_->slot()); } + + virtual void ExtractClassNames() { + size_t idx = 0; + devtools_ijar::ExtractClassNames(class_info_->Display(), &idx); + } + static ClassTypeElementValue *Read(const u1 *&p) { ClassTypeElementValue *value = new ClassTypeElementValue; value->class_info_ = constant(get_u2be(p)); @@ -565,16 +641,22 @@ struct ArrayTypeElementValue : ElementValue { virtual ~ArrayTypeElementValue() { - for (size_t i = 0; i < values_.size(); i++) { - delete values_[i]; + for (const auto *value : values_) { + delete value; + } + } + + virtual void ExtractClassNames() { + for (auto *value : values_) { + value->ExtractClassNames(); } } void Write(u1 *&p) { put_u1(p, tag_); put_u2be(p, values_.size()); - for (size_t ii = 0; ii < values_.size(); ++ii) { - values_[ii]->Write(p); + for (auto *value : values_) { + value->Write(p); } } static ArrayTypeElementValue *Read(const u1 *&p) { @@ -597,6 +679,12 @@ } } + void ExtractClassNames() { + for (size_t i = 0; i < element_value_pairs_.size(); i++) { + element_value_pairs_[i]->element_value_->ExtractClassNames(); + } + } + void Write(u1 *&p) { put_u2be(p, type_->slot()); put_u2be(p, element_value_pairs_.size()); @@ -662,6 +750,10 @@ delete annotation_; } + void ExtractClassNames() { + annotation_->ExtractClassNames(); + } + void Write(u1 *&p) { put_u1(p, target_type_); target_info_->Write(p); @@ -873,6 +965,10 @@ default_value_->Write(p); } + virtual void ExtractClassNames() { + default_value_->ExtractClassNames(); + } + ElementValue *default_value_; }; @@ -913,6 +1009,11 @@ put_u2be(p, signature_->slot()); } + virtual void ExtractClassNames() { + size_t signature_idx = 0; + devtools_ijar::ExtractClassNames(signature_->Display(), &signature_idx); + } + Constant *signature_; }; @@ -954,12 +1055,18 @@ return attr; } + virtual void ExtractClassNames() { + for (auto *annotation : annotations_) { + annotation->ExtractClassNames(); + } + } + void Write(u1 *&p) { WriteProlog(p, -1); u1 *payload_start = p - 4; put_u2be(p, annotations_.size()); - for (size_t ii = 0; ii < annotations_.size(); ++ii) { - annotations_[ii]->Write(p); + for (auto *annotation : annotations_) { + annotation->Write(p); } put_u4be(payload_start, p - 4 - payload_start); // backpatch length } @@ -990,6 +1097,15 @@ return attr; } + virtual void ExtractClassNames() { + for (size_t i = 0; i < parameter_annotations_.size(); i++) { + const std::vector<Annotation*>& annotations = parameter_annotations_[i]; + for (size_t j = 0; j < annotations.size(); j++) { + annotations[j]->ExtractClassNames(); + } + } + } + void Write(u1 *&p) { WriteProlog(p, -1); u1 *payload_start = p - 4; @@ -1022,6 +1138,12 @@ return attr; } + virtual void ExtractClassNames() { + for (auto *type_annotation : type_annotations_) { + type_annotation->ExtractClassNames(); + } + } + void Write(u1 *&p) { WriteProlog(p, -1); u1 *payload_start = p - 4; @@ -1035,6 +1157,41 @@ std::vector<TypeAnnotation*> type_annotations_; }; +// See JVMS §4.7.24 +struct MethodParametersAttribute : Attribute { + static MethodParametersAttribute *Read(const u1 *&p, Constant *attribute_name, + u4 attribute_length) { + auto attr = new MethodParametersAttribute; + attr->attribute_name_ = attribute_name; + u1 parameters_count = get_u1(p); + for (int ii = 0; ii < parameters_count; ++ii) { + MethodParameter* parameter = new MethodParameter; + parameter->name_ = constant(get_u2be(p)); + parameter->access_flags_ = get_u2be(p); + attr->parameters_.push_back(parameter); + } + return attr; + } + + void Write(u1 *&p) { + WriteProlog(p, -1); + u1 *payload_start = p - 4; + put_u1(p, parameters_.size()); + for (MethodParameter* parameter : parameters_) { + put_u2be(p, parameter->name_->slot()); + put_u2be(p, parameter->access_flags_); + } + put_u4be(payload_start, p - 4 - payload_start); // backpatch length + } + + struct MethodParameter { + Constant *name_; + u2 access_flags_; + }; + + std::vector<MethodParameter*> parameters_; +}; + struct GeneralAttribute : Attribute { static GeneralAttribute* Read(const u1 *&p, Constant *attribute_name, u4 attribute_length) { @@ -1068,8 +1225,14 @@ void ReadAttrs(const u1 *&p); virtual ~HasAttrs() { - for (size_t i = 0; i < attributes.size(); i++) { - delete attributes[i]; + for (const auto *attribute : attributes) { + delete attribute; + } + } + + void ExtractClassNames() { + for (auto *attribute : attributes) { + attribute->ExtractClassNames(); } } }; @@ -1132,7 +1295,7 @@ bool ReadConstantPool(const u1 *&p); - void StripIfAnonymous(); + bool IsLocalOrAnonymous(); void WriteHeader(u1 *&p) { put_u4be(p, magic); @@ -1163,6 +1326,23 @@ for (size_t ii = 0; ii < methods.size(); ++ii) { methods[ii]->Write(p); } + + Attribute* inner_classes = NULL; + + // Make the inner classes attribute the last, so that it can know which + // constants were needed + for (size_t ii = 0; ii < attributes.size(); ii++) { + if (attributes[ii]->attribute_name_->Display() == "InnerClasses") { + inner_classes = attributes[ii]; + attributes.erase(attributes.begin() + ii); + break; + } + } + + if (inner_classes != NULL) { + attributes.push_back(inner_classes); + } + WriteAttrs(p); } @@ -1176,12 +1356,14 @@ std::string attr_name = attribute_name->Display(); if (attr_name == "SourceFile" || + attr_name == "StackMapTable" || attr_name == "LineNumberTable" || attr_name == "LocalVariableTable" || attr_name == "LocalVariableTypeTable" || attr_name == "Code" || attr_name == "Synthetic" || - attr_name == "BootstrapMethods") { + attr_name == "BootstrapMethods" || + attr_name == "SourceDebugExtension") { p += attribute_length; // drop these attributes } else if (attr_name == "Exceptions") { attributes.push_back(ExceptionsAttribute::Read(p, attribute_name)); @@ -1214,10 +1396,11 @@ attribute_length)); } else if (attr_name == "RuntimeVisibleTypeAnnotations" || attr_name == "RuntimeInvisibleTypeAnnotations") { - // JSR 308: annotations on types. JDK 7 has no use for these yet, but the - // Checkers Framework relies on them. attributes.push_back(TypeAnnotationsAttribute::Read(p, attribute_name, attribute_length)); + } else if (attr_name == "MethodParameters") { + attributes.push_back( + MethodParametersAttribute::Read(p, attribute_name, attribute_length)); } else { // Skip over unknown attributes with a warning. The JVM spec // says this is ok, so long as we handle the mandatory attributes. @@ -1229,10 +1412,19 @@ } void HasAttrs::WriteAttrs(u1 *&p) { - put_u2be(p, attributes.size()); + u1* p_size = p; + + put_u2be(p, 0); + int n_written_attrs = 0; for (size_t ii = 0; ii < attributes.size(); ii++) { + u1* before = p; attributes[ii]->Write(p); + if (p != before) { + n_written_attrs++; + } } + + put_u2be(p_size, n_written_attrs); } // See sec.4.4 of JVM spec. @@ -1335,53 +1527,15 @@ return true; } -// Anonymous inner classes are stripped to opaque classes that only extend -// Object. None of their methods or fields are accessible anyway. -void ClassFile::StripIfAnonymous() { - int enclosing_index = -1; - int inner_classes_index = -1; - - for (size_t ii = 0; ii < attributes.size(); ++ii) { - if (attributes[ii]->attribute_name_->Display() == "EnclosingMethod") { - enclosing_index = ii; - } else if (attributes[ii]->attribute_name_->Display() == "InnerClasses") { - inner_classes_index = ii; +bool ClassFile::IsLocalOrAnonymous() { + for (const Attribute *attribute : attributes) { + if (attribute->attribute_name_->Display() == "EnclosingMethod") { + // JVMS 4.7.6: a class must has EnclosingMethod attribute iff it + // represents a local class or an anonymous class + return true; } } - - // Presence of an EnclosingMethod attribute indicates a local or anonymous - // class, which can be stripped. - if (enclosing_index > -1) { - // Clear the signature to only extend java.lang.Object. - super_class = NULL; - interfaces.clear(); - - // Clear away all fields (implementation details). - for (size_t ii = 0; ii < fields.size(); ++ii) { - delete fields[ii]; - } - fields.clear(); - - // Clear away all methods (implementation details). - for (size_t ii = 0; ii < methods.size(); ++ii) { - delete methods[ii]; - } - methods.clear(); - - // Only preserve the InnerClasses attribute to comply with the spec. - Attribute *attr = NULL; - for (size_t ii = 0; ii < attributes.size(); ++ii) { - if (static_cast<int>(ii) != inner_classes_index) { - delete attributes[ii]; - } else { - attr = attributes[ii]; - } - } - attributes.clear(); - if (attr != NULL) { - attributes.push_back(attr); - } - } + return false; } static ClassFile *ReadClass(const void *classdata, size_t length) { @@ -1406,6 +1560,8 @@ clazz->access_flags = get_u2be(p); clazz->this_class = constant(get_u2be(p)); + class_name = clazz->this_class; + u2 super_class_id = get_u2be(p); clazz->super_class = super_class_id == 0 ? NULL : constant(super_class_id); @@ -1418,9 +1574,11 @@ for (int ii = 0; ii < fields_count; ++ii) { Member *field = Member::Read(p); - if (!(field->access_flags & ACC_PRIVATE)) { // drop private fields - clazz->fields.push_back(field); + if ((field->access_flags & ACC_PRIVATE) == ACC_PRIVATE) { + // drop private fields + continue; } + clazz->fields.push_back(field); } u2 methods_count = get_u2be(p); @@ -1430,18 +1588,188 @@ // drop class initializers if (method->name->Display() == "<clinit>") continue; - if (!(method->access_flags & ACC_PRIVATE)) { // drop private methods - clazz->methods.push_back(method); + if ((method->access_flags & ACC_PRIVATE) == ACC_PRIVATE) { + // drop private methods + continue; } + if ((method->access_flags & (ACC_SYNTHETIC | ACC_BRIDGE)) == + ACC_SYNTHETIC) { + // drop non-bridge synthetic methods, e.g. package-private synthetic + // constructors used to instantiate private nested classes within their + // declaring compilation unit + continue; + } + clazz->methods.push_back(method); } clazz->ReadAttrs(p); - clazz->StripIfAnonymous(); return clazz; } +// In theory, '/' is also reserved, but it's okay if we just parse package +// identifiers as part of the class name. Note that signatures are UTF-8, but +// this works just as well as in plain ASCII. +static const char *SIGNATURE_NON_IDENTIFIER_CHARS = ".;[<>:"; + +void Expect(const std::string& desc, size_t* p, char expected) { + if (desc[*p] != expected) { + fprintf(stderr, "Expected '%c' in '%s' at %zd in signature\n", + expected, desc.substr(*p).c_str(), *p); + exit(1); + } + + *p += 1; +} + +// These functions form a crude recursive descent parser for descriptors and +// signatures in class files (see JVM spec 4.3). +// +// This parser is a bit more liberal than the spec, but this should be fine, +// because it accepts all valid class files and croaks only on invalid ones. +void ParseFromClassTypeSignature(const std::string& desc, size_t* p); +void ParseSimpleClassTypeSignature(const std::string& desc, size_t* p); +void ParseClassTypeSignatureSuffix(const std::string& desc, size_t* p); +void ParseIdentifier(const std::string& desc, size_t* p); +void ParseTypeArgumentsOpt(const std::string& desc, size_t* p); +void ParseMethodDescriptor(const std::string& desc, size_t* p); + +void ParseClassTypeSignature(const std::string& desc, size_t* p) { + Expect(desc, p, 'L'); + ParseSimpleClassTypeSignature(desc, p); + ParseClassTypeSignatureSuffix(desc, p); + Expect(desc, p, ';'); +} + +void ParseSimpleClassTypeSignature(const std::string& desc, size_t* p) { + ParseIdentifier(desc, p); + ParseTypeArgumentsOpt(desc, p); +} + +void ParseClassTypeSignatureSuffix(const std::string& desc, size_t* p) { + while (desc[*p] == '.') { + *p += 1; + ParseSimpleClassTypeSignature(desc, p); + } +} + +void ParseIdentifier(const std::string& desc, size_t* p) { + size_t next = desc.find_first_of(SIGNATURE_NON_IDENTIFIER_CHARS, *p); + std::string id = desc.substr(*p, next - *p); + used_class_names.insert(id); + *p = next; +} + +void ParseTypeArgumentsOpt(const std::string& desc, size_t* p) { + if (desc[*p] != '<') { + return; + } + + *p += 1; + while (desc[*p] != '>') { + switch (desc[*p]) { + case '*': + *p += 1; + break; + + case '+': + case '-': + *p += 1; + ExtractClassNames(desc, p); + break; + + default: + ExtractClassNames(desc, p); + break; + } + } + + *p += 1; +} + +void ParseMethodDescriptor(const std::string& desc, size_t* p) { + Expect(desc, p, '('); + while (desc[*p] != ')') { + ExtractClassNames(desc, p); + } + + Expect(desc, p, ')'); + ExtractClassNames(desc, p); +} + +void ParseFormalTypeParameters(const std::string& desc, size_t* p) { + Expect(desc, p, '<'); + while (desc[*p] != '>') { + ParseIdentifier(desc, p); + Expect(desc, p, ':'); + if (desc[*p] != ':' && desc[*p] != '>') { + ExtractClassNames(desc, p); + } + + while (desc[*p] == ':') { + Expect(desc, p, ':'); + ExtractClassNames(desc, p); + } + } + + Expect(desc, p, '>'); +} + +void ExtractClassNames(const std::string& desc, size_t* p) { + switch (desc[*p]) { + case '<': + ParseFormalTypeParameters(desc, p); + ExtractClassNames(desc, p); + break; + + case 'L': + ParseClassTypeSignature(desc, p); + break; + + case '[': + *p += 1; + ExtractClassNames(desc, p); + break; + + case 'T': + *p += 1; + ParseIdentifier(desc, p); + Expect(desc, p, ';'); + break; + + case '(': + ParseMethodDescriptor(desc, p); + break; + + case 'B': + case 'C': + case 'D': + case 'F': + case 'I': + case 'J': + case 'S': + case 'Z': + case 'V': + *p += 1; + break; + + default: + fprintf(stderr, "Invalid signature %s\n", desc.substr(*p).c_str()); + } +} + void ClassFile::WriteClass(u1 *&p) { + used_class_names.clear(); + std::vector<Member *> members; + members.insert(members.end(), fields.begin(), fields.end()); + members.insert(members.end(), methods.begin(), methods.end()); + ExtractClassNames(); + for (auto *member : members) { + size_t idx = 0; + devtools_ijar::ExtractClassNames(member->descriptor->Display(), &idx); + member->ExtractClassNames(); + } + // We have to write the body out before the header in order to reference // the essential constants and populate the output constant pool: u1 *body = new u1[length]; @@ -1454,23 +1782,20 @@ delete[] body; } - -void StripClass(u1 *&classdata_out, const u1 *classdata_in, size_t in_length) { +bool StripClass(u1 *&classdata_out, const u1 *classdata_in, size_t in_length) { ClassFile *clazz = ReadClass(classdata_in, in_length); + bool keep = true; if (clazz == NULL) { // Class is invalid. Simply copy it to the output and call it a day. put_n(classdata_out, classdata_in, in_length); + } else if (clazz->IsLocalOrAnonymous()) { + keep = false; } else { // Constant pool item zero is a dummy entry. Setting it marks the // beginning of the output phase; calls to Constant::slot() will // fail if called prior to this. const_pool_out.push_back(NULL); - - // TODO(bazel-team): We should only keep classes in the InnerClass attributes - // if they're used in the output. The entries can then be cleaned out of the - // constant pool in the normal way. - clazz->WriteClass(classdata_out); delete clazz; @@ -1484,6 +1809,7 @@ const_pool_in.clear(); const_pool_out.clear(); + return keep; } } // namespace devtools_ijar
diff --git a/third_party/ijar/common.h b/third_party/ijar/common.h index 118041b8..513e0019a 100644 --- a/third_party/ijar/common.h +++ b/third_party/ijar/common.h
@@ -1,6 +1,4 @@ -// Copyright 2001,2007 Alan Donovan. All rights reserved. -// -// Author: Alan Donovan <adonovan@google.com> +// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -61,6 +59,13 @@ return x; } +inline u8 get_u8le(const u1 *&p) { + u4 lo = get_u4le(p); + u4 hi = get_u4le(p); + u8 x = ((u8)hi << 32) | lo; + return x; +} + inline void put_u1(u1 *&p, u1 x) { *p++ = x; } @@ -89,6 +94,11 @@ *p++ = x >> 24; } +inline void put_u8le(u1 *&p, u8 x) { + put_u4le(p, x & 0xffffffff); + put_u4le(p, (x >> 32) & 0xffffffff); +} + // Copy n bytes from src to p, and advance p. inline void put_n(u1 *&p, const u1 *src, size_t n) { memcpy(p, src, n);
diff --git a/third_party/ijar/ijar.cc b/third_party/ijar/ijar.cc index 860b551..5bbc13cd 100644 --- a/third_party/ijar/ijar.cc +++ b/third_party/ijar/ijar.cc
@@ -1,6 +1,4 @@ -// Copyright 2001,2007 Alan Donovan. All rights reserved. -// -// Author: Alan Donovan <adonovan@google.com> +// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -32,8 +30,8 @@ // Reads a JVM class from classdata_in (of the specified length), and // writes out a simplified class to classdata_out, advancing the -// pointer. -void StripClass(u1 *&classdata_out, const u1 *classdata_in, size_t in_length); +// pointer. Returns true if the class should be kept. +bool StripClass(u1*& classdata_out, const u1* classdata_in, size_t in_length); const char* CLASS_EXTENSION = ".class"; const size_t CLASS_EXTENSION_LENGTH = strlen(CLASS_EXTENSION); @@ -76,11 +74,17 @@ if (verbose) { fprintf(stderr, "INFO: StripClass: %s\n", filename); } - u1 *q = builder->NewFile(filename, 0); - u1 *classdata_out = q; - StripClass(q, data, size); // actually process it - size_t out_length = q - classdata_out; - builder->FinishFile(out_length); + u1* buf = reinterpret_cast<u1*>(malloc(size)); + u1* classdata_out = buf; + if (!StripClass(buf, data, size)) { + free(classdata_out); + return; + } + u1* q = builder->NewFile(filename, 0); + size_t out_length = buf - classdata_out; + memcpy(q, classdata_out, out_length); + builder->FinishFile(out_length, false, true); + free(classdata_out); } // Opens "file_in" (a .jar file) for reading, and writes an interface
diff --git a/third_party/ijar/mapped_file.h b/third_party/ijar/mapped_file.h new file mode 100644 index 0000000..6db0673 --- /dev/null +++ b/third_party/ijar/mapped_file.h
@@ -0,0 +1,82 @@ +// Copyright 2015 The Bazel Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef INCLUDED_THIRD_PARTY_IJAR_MAPPED_FILE_H +#define INCLUDED_THIRD_PARTY_IJAR_MAPPED_FILE_H + +#include "third_party/ijar/common.h" + +namespace devtools_ijar { + +struct MappedInputFileImpl; +struct MappedOutputFileImpl; + +// A memory mapped input file. +class MappedInputFile { + private: + MappedInputFileImpl *impl_; + + protected: + const char* errmsg_; + bool opened_; + u1* buffer_; + size_t length_; + + public: + MappedInputFile(const char* name); + virtual ~MappedInputFile(); + + // If opening the file succeeded or not. + bool Opened() const { return opened_; } + + // Description of the last error that happened. + const char* Error() const { return errmsg_; } + + // The mapped contents of the file. + u1* Buffer() const { return buffer_ ; } + + // The length of the file. + size_t Length() const { return length_; } + + // Unmap a given number of bytes from the beginning of the file. + void Discard(size_t bytes); + int Close(); +}; + +class MappedOutputFile { + private: + MappedOutputFileImpl *impl_; + + protected: + const char* errmsg_; + bool opened_; + u1* buffer_; + + public: + MappedOutputFile(const char* name, u8 estimated_size); + virtual ~MappedOutputFile(); + + // If opening the file succeeded or not. + bool Opened() const { return opened_; } + + // Description of the last error that happened. + const char* Error() const { return errmsg_; } + + // The mapped contents of the file. + u1* Buffer() const { return buffer_; } + int Close(int size); +}; + +} // namespace devtools_ijar +#endif
diff --git a/third_party/ijar/mapped_file_unix.cc b/third_party/ijar/mapped_file_unix.cc new file mode 100644 index 0000000..f7668a51 --- /dev/null +++ b/third_party/ijar/mapped_file_unix.cc
@@ -0,0 +1,147 @@ +// Copyright 2015 The Bazel Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include <errno.h> +#include <fcntl.h> +#include <stdio.h> +#include <unistd.h> +#include <sys/mman.h> + +#include <algorithm> + +#include "third_party/ijar/mapped_file.h" + +#define MAX_ERROR 2048 + +namespace devtools_ijar { + +static char errmsg[MAX_ERROR]; + +struct MappedInputFileImpl { + size_t discarded_; + int fd_; +}; + +MappedInputFile::MappedInputFile(const char* name) { + impl_ = NULL; + opened_ = false; + + int fd = open(name, O_RDONLY); + if (fd < 0) { + snprintf(errmsg, MAX_ERROR, "open(): %s", strerror(errno)); + errmsg_ = errmsg; + return; + } + + off_t length = lseek(fd, 0, SEEK_END); + if (length < 0) { + snprintf(errmsg, MAX_ERROR, "lseek(): %s", strerror(errno)); + errmsg_ = errmsg; + return; + } + + void* buffer = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0); + if (buffer == MAP_FAILED) { + snprintf(errmsg, MAX_ERROR, "mmap(): %s", strerror(errno)); + errmsg_ = errmsg; + return; + } + + impl_ = new MappedInputFileImpl(); + impl_->fd_ = fd; + impl_->discarded_ = 0; + buffer_ = reinterpret_cast<u1*>(buffer); + length_ = length; + opened_ = true; +} + +MappedInputFile::~MappedInputFile() { + delete impl_; +} + +void MappedInputFile::Discard(size_t bytes) { + munmap(buffer_ + impl_->discarded_, bytes); + impl_->discarded_ += bytes; +} + +int MappedInputFile::Close() { + if (close(impl_->fd_) < 0) { + snprintf(errmsg, MAX_ERROR, "close(): %s", strerror(errno)); + errmsg_ = errmsg; + return -1; + } + + return 0; +} + +struct MappedOutputFileImpl { + int fd_; +}; + +MappedOutputFile::MappedOutputFile(const char* name, u8 estimated_size) { + impl_ = NULL; + opened_ = false; + int fd = open(name, O_CREAT|O_RDWR|O_TRUNC, 0644); + if (fd < 0) { + snprintf(errmsg, MAX_ERROR, "open(): %s", strerror(errno)); + errmsg_ = errmsg; + return; + } + + // Create mmap-able sparse file + if (ftruncate(fd, estimated_size) < 0) { + snprintf(errmsg, MAX_ERROR, "ftruncate(): %s", strerror(errno)); + errmsg_ = errmsg; + return; + } + + // Ensure that any buffer overflow in JarStripper will result in + // SIGSEGV or SIGBUS by over-allocating beyond the end of the file. + size_t mmap_length = std::min(estimated_size + sysconf(_SC_PAGESIZE), + (u8) std::numeric_limits<size_t>::max()); + void* mapped = mmap(NULL, mmap_length, PROT_WRITE, MAP_SHARED, fd, 0); + if (mapped == MAP_FAILED) { + snprintf(errmsg, MAX_ERROR, "mmap(): %s", strerror(errno)); + errmsg_ = errmsg; + return; + } + + impl_ = new MappedOutputFileImpl(); + impl_->fd_ = fd; + buffer_ = reinterpret_cast<u1*>(mapped); + opened_ = true; +} + + +MappedOutputFile::~MappedOutputFile() { + delete impl_; +} + +int MappedOutputFile::Close(int size) { + if (ftruncate(impl_->fd_, size) < 0) { + snprintf(errmsg, MAX_ERROR, "ftruncate(): %s", strerror(errno)); + errmsg_ = errmsg; + return -1; + } + + if (close(impl_->fd_) < 0) { + snprintf(errmsg, MAX_ERROR, "close(): %s", strerror(errno)); + errmsg_ = errmsg; + return -1; + } + + return 0; +} + +} // namespace devtools_ijar
diff --git a/third_party/ijar/mapped_file_windows.cc b/third_party/ijar/mapped_file_windows.cc new file mode 100644 index 0000000..3a928c51 --- /dev/null +++ b/third_party/ijar/mapped_file_windows.cc
@@ -0,0 +1,216 @@ +// Copyright 2015 The Bazel Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include <stdio.h> +#include <windows.h> +#include <sys/cygwin.h> + +#include "third_party/ijar/mapped_file.h" + +#define MAX_ERROR 2048 + +namespace devtools_ijar { + +static char errmsg[MAX_ERROR] = ""; + +void PrintLastError(const char* op) { + char *message; + DWORD err = GetLastError(); + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER + | FORMAT_MESSAGE_FROM_SYSTEM + | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + reinterpret_cast<char *>(&message), + 0, NULL); + snprintf(errmsg, MAX_ERROR, "%s: %s", op, message); + LocalFree(message); +} + +char* ToUnicodePath(const char* path) { + // Add \\?\ as prefix to enable unicode path which allows path length longer + // than 260 + int length = strlen(path) + 5; + char* unicode_path = reinterpret_cast<char*>(malloc(length)); + snprintf(unicode_path, length, "\\\\?\\%s", path); + return unicode_path; +} + +struct MappedInputFileImpl { + HANDLE file_; + HANDLE mapping_; + + MappedInputFileImpl(HANDLE file, HANDLE mapping) { + file_ = file; + mapping_ = mapping; + } +}; + +MappedInputFile::MappedInputFile(const char* name) { + impl_ = NULL; + opened_ = false; + errmsg_ = errmsg; + + char* path = reinterpret_cast<char*>( + cygwin_create_path(CCP_POSIX_TO_WIN_A, name)); + char* unicode_path = ToUnicodePath(path); + free(path); + HANDLE file = CreateFile(unicode_path, GENERIC_READ, FILE_SHARE_READ, NULL, + OPEN_EXISTING, 0, NULL); + free(unicode_path); + if (file == INVALID_HANDLE_VALUE) { + PrintLastError("CreateFile()"); + return; + } + + LARGE_INTEGER size; + if (!GetFileSizeEx(file, &size)) { + PrintLastError("GetFileSizeEx()"); + CloseHandle(file); + return; + } + + HANDLE mapping = CreateFileMapping(file, NULL, PAGE_READONLY, + size.HighPart, size.LowPart, NULL); + if (mapping == NULL) { + PrintLastError("CreateFileMapping()"); + CloseHandle(file); + return; + } + + void *view = MapViewOfFileEx(mapping, FILE_MAP_READ, 0, 0, 0, NULL); + if (view == NULL) { + PrintLastError("MapViewOfFileEx()"); + CloseHandle(mapping); + CloseHandle(file); + return; + } + + impl_ = new MappedInputFileImpl(file, mapping); + length_ = size.QuadPart; + buffer_ = reinterpret_cast<u1*>(view); + opened_ = true; +} + +MappedInputFile::~MappedInputFile() { + delete impl_; +} + +void MappedInputFile::Discard(size_t bytes) { + // This is not supported on Windows for now. I'm not sure if we can unmap + // parts of an existing view and that this is necessary for Windows at all. + // At any rate, this only matters for >2GB (or maybe >4GB?) input files. +} + +int MappedInputFile::Close() { + if (!UnmapViewOfFile(buffer_)) { + PrintLastError("UnmapViewOfFile()"); + return -1; + } + + if (!CloseHandle(impl_->mapping_)) { + PrintLastError("CloseHandle(mapping)"); + return -1; + } + + if (!CloseHandle(impl_->file_)) { + PrintLastError("CloseHandle(file)"); + return -1; + } + + return 0; +} + +struct MappedOutputFileImpl { + HANDLE file_; + HANDLE mapping_; + + MappedOutputFileImpl(HANDLE file, HANDLE mapping) { + file_ = file; + mapping_ = mapping; + } +}; + +MappedOutputFile::MappedOutputFile(const char* name, u8 estimated_size) { + impl_ = NULL; + opened_ = false; + errmsg_ = errmsg; + + char* path = reinterpret_cast<char*>( + cygwin_create_path(CCP_POSIX_TO_WIN_A, name)); + char* unicode_path = ToUnicodePath(path); + free(path); + HANDLE file = CreateFile(unicode_path, GENERIC_READ | GENERIC_WRITE, 0, NULL, + CREATE_ALWAYS, 0, NULL); + free(unicode_path); + if (file == INVALID_HANDLE_VALUE) { + PrintLastError("CreateFile()"); + return; + } + + HANDLE mapping = CreateFileMapping(file, NULL, PAGE_READWRITE, + estimated_size >> 32, estimated_size & 0xffffffffUL, NULL); + if (mapping == NULL) { + PrintLastError("CreateFileMapping()"); + CloseHandle(file); + return; + } + + void *view = MapViewOfFileEx(mapping, FILE_MAP_ALL_ACCESS, 0, 0, 0, NULL); + if (view == NULL) { + PrintLastError("MapViewOfFileEx()"); + CloseHandle(mapping); + CloseHandle(file); + return; + } + + impl_ = new MappedOutputFileImpl(file, mapping); + buffer_ = reinterpret_cast<u1*>(view); + opened_ = true; +} + +MappedOutputFile::~MappedOutputFile() { + delete impl_; +} + +int MappedOutputFile::Close(int size) { + if (!UnmapViewOfFile(buffer_)) { + PrintLastError("UnmapViewOfFile()"); + return -1; + } + + if (!CloseHandle(impl_->mapping_)) { + PrintLastError("CloseHandle(mapping)"); + return -1; + } + + if (!SetFilePointer(impl_->file_, size, NULL, FILE_BEGIN)) { + PrintLastError("SetFilePointer()"); + return -1; + } + + if (!SetEndOfFile(impl_->file_)) { + PrintLastError("SetEndOfFile()"); + return -1; + } + + if (!CloseHandle(impl_->file_)) { + PrintLastError("CloseHandle(file)"); + return -1; + } + + return 0; +} + +} // namespace devtools_ijar
diff --git a/third_party/ijar/zip.cc b/third_party/ijar/zip.cc index cb9d1cc..44372f4 100644 --- a/third_party/ijar/zip.cc +++ b/third_party/ijar/zip.cc
@@ -1,6 +1,4 @@ -// Copyright 2007 Alan Donovan. All rights reserved. -// -// Author: Alan Donovan <adonovan@google.com> +// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -38,13 +36,24 @@ #include <limits> #include <vector> +#include "third_party/ijar/mapped_file.h" #include "third_party/ijar/zip.h" #include <zlib.h> -#define LOCAL_FILE_HEADER_SIGNATURE 0x04034b50 -#define CENTRAL_FILE_HEADER_SIGNATURE 0x02014b50 -#define END_OF_CENTRAL_DIR_SIGNATURE 0x06054b50 -#define DATA_DESCRIPTOR_SIGNATURE 0x08074b50 +#define LOCAL_FILE_HEADER_SIGNATURE 0x04034b50 +#define CENTRAL_FILE_HEADER_SIGNATURE 0x02014b50 +#define DIGITAL_SIGNATURE 0x05054b50 +#define ZIP64_EOCD_SIGNATURE 0x06064b50 +#define ZIP64_EOCD_LOCATOR_SIGNATURE 0x07064b50 +#define EOCD_SIGNATURE 0x06054b50 +#define DATA_DESCRIPTOR_SIGNATURE 0x08074b50 + +#define U2_MAX 0xffff +#define U4_MAX 0xffffffffUL + +#define ZIP64_EOCD_LOCATOR_SIZE 20 +// zip64 eocd is fixed size in the absence of a zip64 extensible data sector +#define ZIP64_EOCD_FIXED_SIZE 56 // version to extract: 1.0 - default value from APPNOTE.TXT. // Output JAR files contain no extra ZIP features, so this is enough. @@ -65,22 +74,13 @@ // http://www.info-zip.org/FAQ.html#limits static const u8 kMaximumOutputSize = std::numeric_limits<uint32_t>::max(); -static bool ProcessCentralDirEntry(const u1 *&p, - size_t *compressed_size, - size_t *uncompressed_size, - char *filename, - size_t filename_size, - u4 *attr, - u4 *offset); - // // A class representing a ZipFile for reading. Its public API is exposed // using the ZipExtractor abstract class. // class InputZipFile : public ZipExtractor { public: - InputZipFile(ZipExtractorProcessor *processor, int fd, off_t in_length, - off_t in_offset, const u1* zipdata_in, const u1* central_dir); + InputZipFile(ZipExtractorProcessor *processor, const char* filename); virtual ~InputZipFile(); virtual const char* GetError() { @@ -90,27 +90,32 @@ return errmsg; } + bool Open(); virtual bool ProcessNext(); virtual void Reset(); virtual size_t GetSize() { - return in_length_; + return input_file_->Length(); } virtual u8 CalculateOutputLength(); + virtual bool ProcessCentralDirEntry(const u1 *&p, size_t *compressed_size, + size_t *uncompressed_size, char *filename, + size_t filename_size, u4 *attr, + u4 *offset); + private: ZipExtractorProcessor *processor; - - int fd_in; // Input file descripor + const char* filename_; + MappedInputFile *input_file_; // InputZipFile is responsible for maintaining the following // pointers. They are allocated by the Create() method before // the object is actually created using mmap. - const u1 * const zipdata_in_; // start of input file mmap - const u1 * zipdata_in_mapped_; // start of still mapped region - const u1 * const central_dir_; // central directory in input file + const u1 * zipdata_in_; // start of input file mmap + size_t bytes_unmapped_; // bytes that have already been unmapped + const u1 * central_dir_; // central directory in input file - size_t in_length_; // size of the input file size_t in_offset_; // offset the input file const u1 *p; // input cursor @@ -122,10 +127,10 @@ // not enough, we bail out. We only decompress class files, so they should // be smaller than 64K anyway, but we give a little leeway. // MAX_BUFFER_SIZE must be bigger than the size of the biggest file in the - // ZIP. It is set to 128M here so we can uncompress the Bazel server with - // this library. + // ZIP. It is set to 2GB here because no one has audited the code for 64-bit + // cleanliness. static const size_t INITIAL_BUFFER_SIZE = 256 * 1024; // 256K - static const size_t MAX_BUFFER_SIZE = 128 * 1024 * 1024; + static const size_t MAX_BUFFER_SIZE = std::numeric_limits<int32_t>::max(); static const size_t MAX_MAPPED_REGION = 32 * 1024 * 1024; // These metadata fields are the fields of the ZIP header of the file being @@ -168,7 +173,7 @@ // we're about to read, for diagnostics. int EnsureRemaining(size_t n, const char *state) { size_t in_offset = p - zipdata_in_; - size_t remaining = in_length_ - in_offset; + size_t remaining = input_file_->Length() - in_offset; if (n > remaining) { return error("Premature end of file (at offset %zd, state=%s); " "expected %zd more bytes but found %zd.\n", @@ -197,10 +202,11 @@ // class OutputZipFile : public ZipBuilder { public: - OutputZipFile(int fd, u1 * const zipdata_out) : - fd_out(fd), - zipdata_out_(zipdata_out), - q(zipdata_out) { + OutputZipFile(const char* filename, u8 estimated_size) : + output_file_(NULL), + filename_(filename), + estimated_size_(estimated_size), + finished_(false) { errmsg[0] = 0; } @@ -213,7 +219,8 @@ virtual ~OutputZipFile() { Finish(); } virtual u1* NewFile(const char* filename, const u4 attr); - virtual int FinishFile(size_t filelength, bool compress = false); + virtual int FinishFile(size_t filelength, bool compress = false, + bool compute_crc = false); virtual int WriteEmptyFile(const char *filename); virtual size_t GetSize() { return Offset(q); @@ -222,6 +229,7 @@ return entries_.size(); } virtual int Finish(); + bool Open(); private: struct LocalFileEntry { @@ -235,6 +243,9 @@ // Compression method u2 compression_method; + // CRC32 + u4 crc32; + // external attributes field u4 external_attr; @@ -247,12 +258,15 @@ u2 extra_field_length; }; - int fd_out; // file descriptor for the output file + MappedOutputFile* output_file_; + const char* filename_; + u8 estimated_size_; + bool finished_; // OutputZipFile is responsible for maintaining the following // pointers. They are allocated by the Create() method before // the object is actually created using mmap. - u1 * const zipdata_out_; // start of output file mmap + u1 *zipdata_out_; // start of output file mmap u1 *q; // output cursor u1 *header_ptr; // Current pointer to "compression method" entry. @@ -289,8 +303,10 @@ // Fill in the "compressed size" and "uncompressed size" fields in a local // file header previously written by WriteLocalFileHeader(). - size_t WriteFileSizeInLocalFileHeader(u1 *header_ptr, size_t out_length, - bool compress = false); + size_t WriteFileSizeInLocalFileHeader(u1 *header_ptr, + size_t out_length, + bool compress = false, + const u4 crc = 0); }; // @@ -413,9 +429,10 @@ } } - if (p > zipdata_in_mapped_ + MAX_MAPPED_REGION) { - munmap(const_cast<u1 *>(zipdata_in_mapped_), MAX_MAPPED_REGION); - zipdata_in_mapped_ += MAX_MAPPED_REGION; + size_t bytes_processed = p - zipdata_in_; + if (bytes_processed > bytes_unmapped_ + MAX_MAPPED_REGION) { + input_file_->Discard(MAX_MAPPED_REGION); + bytes_unmapped_ += MAX_MAPPED_REGION; } return 0; @@ -440,7 +457,7 @@ u1* InputZipFile::UncompressFile() { size_t in_offset = p - zipdata_in_; - size_t remaining = in_length_ - in_offset; + size_t remaining = input_file_->Length() - in_offset; z_stream stream; stream.zalloc = Z_NULL; @@ -547,11 +564,17 @@ // Of course, in the latter case, the size output variables are not changed. // Note that the central directory is always followed by another data structure // that has a signature, so parsing it this way is safe. -static bool ProcessCentralDirEntry( - const u1 *&p, size_t *compressed_size, size_t *uncompressed_size, - char *filename, size_t filename_size, u4 *attr, u4 *offset) { +bool InputZipFile::ProcessCentralDirEntry(const u1 *&p, size_t *compressed_size, + size_t *uncompressed_size, + char *filename, size_t filename_size, + u4 *attr, u4 *offset) { u4 signature = get_u4le(p); + if (signature != CENTRAL_FILE_HEADER_SIGNATURE) { + if (signature != DIGITAL_SIGNATURE && signature != EOCD_SIGNATURE && + signature != ZIP64_EOCD_SIGNATURE) { + error("invalid central file header signature: 0x%x\n", signature); + } return false; } @@ -609,14 +632,132 @@ // The worst case is when the output is simply the input uncompressed. The // metadata in the zip file will stay the same, so the file will grow by the // difference between the compressed and uncompressed sizes. - return (u8) in_length_ - skipped_compressed_size + return (u8) input_file_->Length() - skipped_compressed_size + (uncompressed_size - compressed_size); } +// An end of central directory record, sized for optional zip64 contents. +struct EndOfCentralDirectoryRecord { + u4 number_of_this_disk; + u4 disk_with_central_dir; + u8 central_dir_entries_on_this_disk; + u8 central_dir_entries; + u8 central_dir_size; + u8 central_dir_offset; +}; + +// Checks for a zip64 end of central directory record. If a valid zip64 EOCD is +// found, updates the original EOCD record and returns true. +bool MaybeReadZip64CentralDirectory(const u1 *bytes, size_t in_length, + const u1 *current, + const u1 **end_of_central_dir, + EndOfCentralDirectoryRecord *cd) { + if (current < bytes) { + return false; + } + const u1 *candidate = current; + u4 zip64_directory_signature = get_u4le(current); + if (zip64_directory_signature != ZIP64_EOCD_SIGNATURE) { + return false; + } + + // size of zip64 end of central directory record + // (fixed size unless there's a zip64 extensible data sector, which + // we don't need to read) + get_u8le(current); + get_u2be(current); // version made by + get_u2be(current); // version needed to extract + + u4 number_of_this_disk = get_u4be(current); + u4 disk_with_central_dir = get_u4le(current); + u8 central_dir_entries_on_this_disk = get_u8le(current); + u8 central_dir_entries = get_u8le(current); + u8 central_dir_size = get_u8le(current); + u8 central_dir_offset = get_u8le(current); + + // check for a zip64 EOCD that matches the regular EOCD + if (number_of_this_disk != cd->number_of_this_disk && + cd->number_of_this_disk != U2_MAX) { + return false; + } + if (disk_with_central_dir != cd->disk_with_central_dir && + cd->disk_with_central_dir != U2_MAX) { + return false; + } + if (central_dir_entries_on_this_disk != + cd->central_dir_entries_on_this_disk && + cd->central_dir_entries_on_this_disk != U2_MAX) { + return false; + } + if (central_dir_entries != cd->central_dir_entries && + cd->central_dir_entries != U2_MAX) { + return false; + } + if (central_dir_size != cd->central_dir_size && + cd->central_dir_size != U4_MAX) { + return false; + } + if (central_dir_offset != cd->central_dir_offset && + cd->central_dir_offset != U4_MAX) { + return false; + } + + *end_of_central_dir = candidate; + cd->number_of_this_disk = number_of_this_disk; + cd->disk_with_central_dir = disk_with_central_dir; + cd->central_dir_entries_on_this_disk = central_dir_entries_on_this_disk; + cd->central_dir_entries = central_dir_entries; + cd->central_dir_size = central_dir_size; + cd->central_dir_offset = central_dir_offset; + return true; +} + +// Starting from the end of central directory record, attempts to locate a zip64 +// end of central directory record. If found, updates the given record and +// offset with the zip64 data. Returns false on error. +bool FindZip64CentralDirectory(const u1 *bytes, size_t in_length, + const u1 **end_of_central_dir, + EndOfCentralDirectoryRecord *cd) { + // In the absence of a zip64 extensible data sector, the zip64 EOCD is at a + // fixed offset from the regular central directory. + if (MaybeReadZip64CentralDirectory( + bytes, in_length, + *end_of_central_dir - ZIP64_EOCD_LOCATOR_SIZE - ZIP64_EOCD_FIXED_SIZE, + end_of_central_dir, cd)) { + return true; + } + + // If we couldn't find a zip64 EOCD at a fixed offset, either it doesn't exist + // or there was a zip64 extensible data sector, so try going through the + // locator. This approach doesn't work if data was prepended to the archive + // without updating the offset in the locator. + const u1 *zip64_locator = *end_of_central_dir - ZIP64_EOCD_LOCATOR_SIZE; + if (zip64_locator - ZIP64_EOCD_FIXED_SIZE < bytes) { + return true; + } + u4 zip64_locator_signature = get_u4le(zip64_locator); + if (zip64_locator_signature != ZIP64_EOCD_LOCATOR_SIGNATURE) { + return true; + } + u4 disk_with_zip64_central_directory = get_u4le(zip64_locator); + u8 zip64_end_of_central_dir_offset = get_u8le(zip64_locator); + u4 zip64_total_disks = get_u4le(zip64_locator); + if (MaybeReadZip64CentralDirectory(bytes, in_length, + bytes + zip64_end_of_central_dir_offset, + end_of_central_dir, cd)) { + if (disk_with_zip64_central_directory != 0 || zip64_total_disks != 1) { + fprintf(stderr, "multi-disk JAR files are not supported\n"); + return false; + } + return true; + } + return true; +} + // Given the data in the zip file, returns the offset of the central directory // and the number of files contained in it. -bool FindZipCentralDirectory(const u1* bytes, size_t in_length, - u4* offset, const u1** central_dir) { +bool FindZipCentralDirectory(const u1 *bytes, size_t in_length, u4 *offset, + const u1 **central_dir) { static const int MAX_COMMENT_LENGTH = 0xffff; static const int CENTRAL_DIR_LOCATOR_SIZE = 22; // Maximum distance of start of central dir locator from end of file @@ -631,7 +772,7 @@ current >= last_pos_to_check; current-- ) { const u1* p = current; - if (get_u4le(p) != END_OF_CENTRAL_DIR_SIGNATURE) { + if (get_u4le(p) != EOCD_SIGNATURE) { continue; } @@ -655,36 +796,40 @@ return false; } + EndOfCentralDirectoryRecord cd; const u1* end_of_central_dir = current; get_u4le(current); // central directory locator signature, already checked - u2 number_of_this_disk = get_u2le(current); - u2 disk_with_central_dir = get_u2le(current); - u2 central_dir_entries_on_this_disk = get_u2le(current); - u2 central_dir_entries = get_u2le(current); - u4 central_dir_size = get_u4le(current); - u4 central_dir_offset = get_u4le(current); + cd.number_of_this_disk = get_u2le(current); + cd.disk_with_central_dir = get_u2le(current); + cd.central_dir_entries_on_this_disk = get_u2le(current); + cd.central_dir_entries = get_u2le(current); + cd.central_dir_size = get_u4le(current); + cd.central_dir_offset = get_u4le(current); u2 file_comment_length = get_u2le(current); current += file_comment_length; // set current to the end of the central dir - if (number_of_this_disk != 0 - || disk_with_central_dir != 0 - || central_dir_entries_on_this_disk != central_dir_entries) { + if (!FindZip64CentralDirectory(bytes, in_length, &end_of_central_dir, &cd)) { + return false; + } + + if (cd.number_of_this_disk != 0 || cd.disk_with_central_dir != 0 || + cd.central_dir_entries_on_this_disk != cd.central_dir_entries) { fprintf(stderr, "multi-disk JAR files are not supported\n"); return false; } // Do not change output values before determining that they are OK. - *offset = central_dir_offset; + *offset = cd.central_dir_offset; // Central directory start can then be used to determine the actual // starts of the zip file (which can be different in case of a non-zip // header like for auto-extractable binaries). - *central_dir = end_of_central_dir - central_dir_size; + *central_dir = end_of_central_dir - cd.central_dir_size; return true; } void InputZipFile::Reset() { central_dir_current_ = central_dir_; - zipdata_in_mapped_ = zipdata_in_; + bytes_unmapped_ = 0; p = zipdata_in_ + in_offset_; } @@ -698,55 +843,68 @@ ZipExtractor* ZipExtractor::Create(const char* filename, ZipExtractorProcessor *processor) { - int fd_in = open(filename, O_RDONLY); - if (fd_in < 0) { + InputZipFile* result = new InputZipFile(processor, filename); + if (!result->Open()) { + fprintf(stderr, "%s\n", result->GetError()); + delete result; return NULL; } - off_t length = lseek(fd_in, 0, SEEK_END); - if (length < 0) { - return NULL; + return result; +} + +// zipdata_in_, in_offset_, p, central_dir_current_ + +InputZipFile::InputZipFile(ZipExtractorProcessor *processor, + const char* filename) + : processor(processor), filename_(filename), input_file_(NULL), + bytes_unmapped_(0) { + uncompressed_data_allocated_ = INITIAL_BUFFER_SIZE; + uncompressed_data_ = + reinterpret_cast<u1*>(malloc(uncompressed_data_allocated_)); + errmsg[0] = 0; +} + +bool InputZipFile::Open() { + MappedInputFile* input_file = new MappedInputFile(filename_); + if (!input_file->Opened()) { + snprintf(errmsg, sizeof(errmsg), "%s", input_file->Error()); + delete input_file; + return false; } - void *zipdata_in = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd_in, 0); - if (zipdata_in == MAP_FAILED) { - return NULL; - } - + void *zipdata_in = input_file->Buffer(); u4 central_dir_offset; const u1 *central_dir = NULL; if (!devtools_ijar::FindZipCentralDirectory( - static_cast<const u1*>(zipdata_in), length, + static_cast<const u1*>(zipdata_in), input_file->Length(), ¢ral_dir_offset, ¢ral_dir)) { errno = EIO; // we don't really have a good error number - return NULL; + error("Cannot find central directory"); + delete input_file; + return false; } const u1 *zipdata_start = static_cast<const u1*>(zipdata_in); - off_t offset = - static_cast<off_t>(zipdata_start - + central_dir_offset - - central_dir); + in_offset_ = - static_cast<off_t>(zipdata_start + + central_dir_offset + - central_dir); - return new InputZipFile(processor, fd_in, length, offset, - zipdata_start, central_dir); -} - -InputZipFile::InputZipFile(ZipExtractorProcessor *processor, int fd, - off_t in_length, off_t in_offset, - const u1* zipdata_in, const u1* central_dir) - : processor(processor), fd_in(fd), - zipdata_in_(zipdata_in), zipdata_in_mapped_(zipdata_in), - central_dir_(central_dir), in_length_(in_length), in_offset_(in_offset), - p(zipdata_in + in_offset), central_dir_current_(central_dir) { - uncompressed_data_allocated_ = INITIAL_BUFFER_SIZE; - uncompressed_data_ = - reinterpret_cast<u1*>(malloc(uncompressed_data_allocated_)); + input_file_ = input_file; + zipdata_in_ = zipdata_start; + central_dir_ = central_dir; + central_dir_current_ = central_dir; + p = zipdata_in_ + in_offset_; errmsg[0] = 0; + return true; } InputZipFile::~InputZipFile() { free(uncompressed_data_); - close(fd_in); + if (input_file_ != NULL) { + input_file_->Close(); + delete input_file_; + } } @@ -760,6 +918,7 @@ LocalFileEntry *entry = new LocalFileEntry; entry->local_header_offset = Offset(q); entry->external_attr = 0; + entry->crc32 = 0; // Output the ZIP local_file_header: put_u4le(q, LOCAL_FILE_HEADER_SIGNATURE); @@ -768,7 +927,7 @@ put_u2le(q, 0); // compression_method put_u2le(q, 0); // last_mod_file_time put_u2le(q, 0); // last_mod_file_date - put_u4le(q, 0); // crc32 + put_u4le(q, entry->crc32); // crc32 put_u4le(q, 0); // compressed_size put_u4le(q, 0); // uncompressed_size put_u2le(q, file_name_length); @@ -800,7 +959,7 @@ put_u2le(q, entry->compression_method); // compression method: put_u2le(q, 0); // last_mod_file_time put_u2le(q, 0); // last_mod_file_date - put_u4le(q, 0); // crc32 (jar/javac tools don't care) + put_u4le(q, entry->crc32); // crc32 put_u4le(q, entry->compressed_length); // compressed_size put_u4le(q, entry->uncompressed_length); // uncompressed_size put_u2le(q, entry->file_name_length); @@ -816,17 +975,60 @@ put_n(q, entry->file_name, entry->file_name_length); put_n(q, entry->extra_field, entry->extra_field_length); } - u4 central_directory_size = q - central_directory_start; + u8 central_directory_size = q - central_directory_start; - put_u4le(q, END_OF_CENTRAL_DIR_SIGNATURE); - put_u2le(q, 0); // number of this disk - put_u2le(q, 0); // number of the disk with the start of the central directory - put_u2le(q, entries_.size()); // # central dir entries on this disk - put_u2le(q, entries_.size()); // total # entries in the central directory - put_u4le(q, central_directory_size); // size of the central directory - put_u4le(q, Offset(central_directory_start)); // offset of start of central - // directory wrt starting disk - put_u2le(q, 0); // .ZIP file comment length + if (entries_.size() > U2_MAX || central_directory_size > U4_MAX || + Offset(central_directory_start) > U4_MAX) { + u1 *zip64_end_of_central_directory_start = q; + + put_u4le(q, ZIP64_EOCD_SIGNATURE); + // signature and size field doesn't count towards size + put_u8le(q, ZIP64_EOCD_FIXED_SIZE - 12); + put_u2le(q, 0); // version made by + put_u2le(q, 0); // version needed to extract + put_u4le(q, 0); // number of this disk + put_u4le(q, 0); // # of the disk with the start of the central directory + put_u8le(q, entries_.size()); // # central dir entries on this disk + put_u8le(q, entries_.size()); // total # entries in the central directory + put_u8le(q, central_directory_size); // size of the central directory + // offset of start of central directory wrt starting disk + put_u8le(q, Offset(central_directory_start)); + + put_u4le(q, ZIP64_EOCD_LOCATOR_SIGNATURE); + // number of the disk with the start of the zip64 end of central directory + put_u4le(q, 0); + // relative offset of the zip64 end of central directory record + put_u8le(q, Offset(zip64_end_of_central_directory_start)); + // total number of disks + put_u4le(q, 1); + + put_u4le(q, EOCD_SIGNATURE); + put_u2le(q, 0); // number of this disk + put_u2le(q, 0); // # of disk with the start of the central directory + // # central dir entries on this disk + put_u2le(q, entries_.size() > 0xffff ? 0xffff : entries_.size()); + // total # entries in the central directory + put_u2le(q, entries_.size() > 0xffff ? 0xffff : entries_.size()); + // size of the central directory + put_u4le(q, + central_directory_size > U4_MAX ? U4_MAX : central_directory_size); + // offset of start of central + put_u4le(q, Offset(central_directory_start) > U4_MAX + ? U4_MAX + : Offset(central_directory_start)); + put_u2le(q, 0); // .ZIP file comment length + + } else { + put_u4le(q, EOCD_SIGNATURE); + put_u2le(q, 0); // number of this disk + put_u2le(q, 0); // # of the disk with the start of the central directory + put_u2le(q, entries_.size()); // # central dir entries on this disk + put_u2le(q, entries_.size()); // total # entries in the central directory + put_u4le(q, central_directory_size); // size of the central directory + // offset of start of central directory wrt starting disk + put_u4le(q, Offset(central_directory_start)); + put_u2le(q, 0); // .ZIP file comment length + } } u1* OutputZipFile::WriteLocalFileHeader(const char* filename, const u4 attr) { @@ -848,7 +1050,7 @@ put_u2le(q, COMPRESSION_METHOD_STORED); // compression method = placeholder put_u2le(q, 0); // last_mod_file_time put_u2le(q, 0); // last_mod_file_date - put_u4le(q, 0); // crc32 (jar/javac tools don't care) + put_u4le(q, entry->crc32); // crc32 put_u4le(q, 0); // compressed_size = placeholder put_u4le(q, 0); // uncompressed_size = placeholder put_u2le(q, entry->file_name_length); @@ -880,7 +1082,9 @@ stream.next_in = buf; stream.next_out = outbuf; - if (deflateInit(&stream, Z_DEFAULT_COMPRESSION) != Z_OK) { + // deflateInit2 negative windows size prevent the zlib wrapper to be used. + if (deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, + -MAX_WBITS, 8, Z_DEFAULT_STRATEGY) != Z_OK) { // Failure to compress => return the buffer uncompressed free(outbuf); return length; @@ -901,7 +1105,8 @@ size_t OutputZipFile::WriteFileSizeInLocalFileHeader(u1 *header_ptr, size_t out_length, - bool compress) { + bool compress, + const u4 crc) { size_t compressed_size = out_length; if (compress) { compressed_size = TryDeflate(q, out_length); @@ -912,23 +1117,25 @@ } else { put_u2le(header_ptr, COMPRESSION_METHOD_STORED); } - header_ptr += 8; + header_ptr += 4; + put_u4le(header_ptr, crc); // crc32 put_u4le(header_ptr, compressed_size); // compressed_size put_u4le(header_ptr, out_length); // uncompressed_size return compressed_size; } int OutputZipFile::Finish() { - if (fd_out > 0) { - WriteCentralDirectory(); - if (ftruncate(fd_out, GetSize()) < 0) { - return error("ftruncate(fd_out, GetSize()): %s", strerror(errno)); - } - if (close(fd_out) < 0) { - return error("close(fd_out): %s", strerror(errno)); - } - fd_out = -1; + if (finished_) { + return 0; } + + finished_ = true; + WriteCentralDirectory(); + if (output_file_->Close(GetSize()) < 0) { + return error("%s", output_file_->Error()); + } + delete output_file_; + output_file_ = NULL; return 0; } @@ -937,9 +1144,15 @@ return q; } -int OutputZipFile::FinishFile(size_t filelength, bool compress) { +int OutputZipFile::FinishFile(size_t filelength, bool compress, + bool compute_crc) { + u4 crc = 0; + if (compute_crc) { + crc = crc32(crc, q, filelength); + } size_t compressed_size = - WriteFileSizeInLocalFileHeader(header_ptr, filelength, compress); + WriteFileSizeInLocalFileHeader(header_ptr, filelength, compress, crc); + entries_.back()->crc32 = crc; entries_.back()->compressed_length = compressed_size; entries_.back()->uncompressed_length = filelength; if (compressed_size < filelength) { @@ -951,39 +1164,39 @@ return 0; } -ZipBuilder* ZipBuilder::Create(const char* zip_file, u8 estimated_size) { - if (estimated_size > kMaximumOutputSize) { +bool OutputZipFile::Open() { + if (estimated_size_ > kMaximumOutputSize) { fprintf(stderr, "Uncompressed input jar has size %llu, " "which exceeds the maximum supported output size %llu.\n" "Assuming that ijar will be smaller and hoping for the best.\n", - estimated_size, kMaximumOutputSize); - estimated_size = kMaximumOutputSize; + estimated_size_, kMaximumOutputSize); + estimated_size_ = kMaximumOutputSize; } - int fd_out = open(zip_file, O_CREAT|O_RDWR|O_TRUNC, 0644); - if (fd_out < 0) { + MappedOutputFile* output_file = new MappedOutputFile( + filename_, estimated_size_); + if (!output_file->Opened()) { + snprintf(errmsg, sizeof(errmsg), "%s", output_file->Error()); + delete output_file; + return false; + } + + output_file_ = output_file; + q = output_file->Buffer(); + zipdata_out_ = output_file->Buffer(); + return true; +} + +ZipBuilder* ZipBuilder::Create(const char* zip_file, u8 estimated_size) { + OutputZipFile* result = new OutputZipFile(zip_file, estimated_size); + if (!result->Open()) { + fprintf(stderr, "%s\n", result->GetError()); + delete result; return NULL; } - // Create mmap-able sparse file - if (ftruncate(fd_out, estimated_size) < 0) { - return NULL; - } - - // Ensure that any buffer overflow in JarStripper will result in - // SIGSEGV or SIGBUS by over-allocating beyond the end of the file. - size_t mmap_length = std::min(estimated_size + sysconf(_SC_PAGESIZE), - (u8) std::numeric_limits<size_t>::max()); - - void *zipdata_out = mmap(NULL, mmap_length, PROT_WRITE, - MAP_SHARED, fd_out, 0); - if (zipdata_out == MAP_FAILED) { - fprintf(stderr, "output_length=%llu\n", estimated_size); - return NULL; - } - - return new OutputZipFile(fd_out, (u1*) zipdata_out); + return result; } u8 ZipBuilder::EstimateSize(char **files) {
diff --git a/third_party/ijar/zip.h b/third_party/ijar/zip.h index c548cb3..aa17a47 100644 --- a/third_party/ijar/zip.h +++ b/third_party/ijar/zip.h
@@ -1,4 +1,4 @@ -// Copyright 2015 Google Inc. All rights reserved. +// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -63,8 +63,12 @@ // Finish writing a file and specify its length. After calling this method // one should not reuse the pointer given by NewFile. The file can be // compressed using the deflate algorithm by setting `compress` to true. + // By default, CRC32 are not computed as java tooling doesn't care, but + // computing it can be activated by setting `compute_crc` to true. // On failure, returns -1 and GetError() will return an non-empty message. - virtual int FinishFile(size_t filelength, bool compress = false) = 0; + virtual int FinishFile(size_t filelength, + bool compress = false, + bool compute_crc = false) = 0; // Write an empty file, it is equivalent to: // NewFile(filename, 0);
diff --git a/third_party/ijar/zip_main.cc b/third_party/ijar/zip_main.cc index 6c2a974..1c55ee9 100644 --- a/third_party/ijar/zip_main.cc +++ b/third_party/ijar/zip_main.cc
@@ -1,6 +1,4 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Author: Alan Donovan <adonovan@google.com> +// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,14 +20,14 @@ // CRC-32 of all files in the zip file will be set to 0. // -#include <stdio.h> -#include <string.h> -#include <stdlib.h> -#include <limits.h> -#include <fcntl.h> -#include <unistd.h> -#include <sys/mman.h> #include <errno.h> +#include <fcntl.h> +#include <limits.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> #include <memory> #include "third_party/ijar/zip.h" @@ -72,8 +70,8 @@ void concat_path(char* out, const size_t size, const char *path1, const char *path2) { int len1 = strlen(path1); - int l = len1; - strncpy(out, path1, size-1); + size_t l = len1; + strncpy(out, path1, size - 1); out[size-1] = 0; if (l < size - 1 && path1[len1] != '/' && path2[0] != '/') { out[l] = '/'; @@ -154,11 +152,30 @@ output[output_size-1] = 0; } +// copy size bytes from file descriptor fd into buffer. +int copy_file_to_buffer(int fd, size_t size, void *buffer) { + size_t nb_read = 0; + while (nb_read < size) { + size_t to_read = size - nb_read; + if (to_read > 16384 /* 16K */) { + to_read = 16384; + } + ssize_t r = read(fd, static_cast<uint8_t *>(buffer) + nb_read, to_read); + if (r < 0) { + return -1; + } + nb_read += r; + } + return 0; +} // Execute the extraction (or just listing if just v is provided) int extract(char *zipfile, bool verbose, bool extract) { char output_root[PATH_MAX]; - getcwd(output_root, PATH_MAX); + if (getcwd(output_root, PATH_MAX) == NULL) { + fprintf(stderr, "getcwd() failed: %s.\n", strerror(errno)); + return -1; + } UnzipProcessor processor(output_root, verbose, extract); std::unique_ptr<ZipExtractor> extractor(ZipExtractor::Create(zipfile, @@ -176,10 +193,122 @@ return 0; } +// add a file to the zip +int add_file(std::unique_ptr<ZipBuilder> const &builder, char *file, + bool flatten, bool verbose, bool compress) { + struct stat statst; + if (stat(file, &statst) < 0) { + fprintf(stderr, "Cannot stat file %s: %s.\n", file, strerror(errno)); + return -1; + } + bool isdir = (statst.st_mode & S_IFDIR) != 0; + + if (flatten && isdir) { + return 0; + } + + // Compute the path, flattening it if requested + char path[PATH_MAX]; + size_t len = strlen(file); + if (len > PATH_MAX) { + fprintf(stderr, "Path too long: %s.\n", file); + return -1; + } + if (flatten) { + basename(file, path, PATH_MAX); + } else { + strncpy(path, file, PATH_MAX); + path[PATH_MAX - 1] = 0; + if (isdir && len < PATH_MAX - 1) { + // Add the trailing slash for folders + path[len] = '/'; + path[len + 1] = 0; + } + } + + if (verbose) { + mode_t perm = statst.st_mode & 0777; + printf("%c %o %s\n", isdir ? 'd' : 'f', perm, path); + } + + u1 *buffer = builder->NewFile(path, mode_to_zipattr(statst.st_mode)); + if (isdir || statst.st_size == 0) { + builder->FinishFile(0); + } else { + // read the input file + int fd = open(file, O_RDONLY); + if (fd < 0) { + fprintf(stderr, "Can't open file %s for reading: %s.\n", file, + strerror(errno)); + return -1; + } + if (copy_file_to_buffer(fd, statst.st_size, buffer) < 0) { + fprintf(stderr, "Can't read file %s: %s.\n", file, strerror(errno)); + close(fd); + return -1; + } + close(fd); + builder->FinishFile(statst.st_size, compress, true); + } + return 0; +} + +// Read a list of files separated by newlines. The resulting array can be +// freed using the free method. +char **read_filelist(char *filename) { + struct stat statst; + int fd = open(filename, O_RDONLY); + if (fd < 0) { + fprintf(stderr, "Can't open file %s for reading: %s.\n", filename, + strerror(errno)); + return NULL; + } + if (fstat(fd, &statst) < 0) { + fprintf(stderr, "Cannot stat file %s: %s.\n", filename, strerror(errno)); + return NULL; + } + + char *data = static_cast<char *>(malloc(statst.st_size)); + if (copy_file_to_buffer(fd, statst.st_size, data) < 0) { + fprintf(stderr, "Can't read file %s: %s.\n", filename, strerror(errno)); + close(fd); + return NULL; + } + close(fd); + + int nb_entries = 1; + for (int i = 0; i < statst.st_size; i++) { + if (data[i] == '\n') { + nb_entries++; + } + } + + size_t sizeof_array = sizeof(char *) * (nb_entries + 1); + void *result = malloc(sizeof_array + statst.st_size); + // copy the content + char **filelist = static_cast<char **>(result); + char *content = static_cast<char *>(result) + sizeof_array; + memcpy(content, data, statst.st_size); + free(data); + // Create the corresponding array + int j = 1; + filelist[0] = content; + for (int i = 0; i < statst.st_size; i++) { + if (content[i] == '\n') { + content[i] = 0; + if (i + 1 < statst.st_size) { + filelist[j] = content + i + 1; + j++; + } + } + } + filelist[j] = NULL; + return filelist; +} + // Execute the create operation int create(char *zipfile, char **files, bool flatten, bool verbose, bool compress) { - struct stat statst; u8 size = ZipBuilder::EstimateSize(files); if (size == 0) { return -1; @@ -191,53 +320,8 @@ return -1; } for (int i = 0; files[i] != NULL; i++) { - stat(files[i], &statst); - char path[PATH_MAX]; - bool isdir = (statst.st_mode & S_IFDIR) != 0; - - if (flatten && isdir) { - continue; - } - - // Compute the path, flattening it if requested - if (flatten) { - basename(files[i], path, PATH_MAX); - } else { - strncpy(path, files[i], PATH_MAX); - path[PATH_MAX-1] = 0; - size_t len = strlen(path); - if (isdir && len < PATH_MAX - 1) { - // Add the trailing slash for folders - path[len] = '/'; - path[len+1] = 0; - } - } - - if (verbose) { - mode_t perm = statst.st_mode & 0777; - printf("%c %o %s\n", isdir ? 'd' : 'f', perm, path); - } - - u1 *buffer = builder->NewFile(path, mode_to_zipattr(statst.st_mode)); - if (isdir || statst.st_size == 0) { - builder->FinishFile(0); - } else { - // mmap the input file and memcpy - int fd = open(files[i], O_RDONLY); - if (fd < 0) { - fprintf(stderr, "Can't open file %s for reading: %s.\n", - files[i], strerror(errno)); - return -1; - } - void *data = mmap(NULL, statst.st_size, PROT_READ, MAP_PRIVATE, fd, 0); - if (data == MAP_FAILED) { - fprintf(stderr, "Can't mmap file %s for reading: %s.\n", - files[i], strerror(errno)); - return -1; - } - memcpy(buffer, data, statst.st_size); - munmap(data, statst.st_size); - builder->FinishFile(statst.st_size, compress); + if (add_file(builder, files[i], flatten, verbose, compress) < 0) { + return -1; } } if (builder->Finish() < 0) { @@ -301,7 +385,16 @@ usage(argv[0]); } // Create a zip - return devtools_ijar::create(argv[2], argv + 3, flatten, verbose, compress); + char **filelist = argv + 3; + if (argc == 4 && argv[3][0] == '@') { + // We never free that list because it needs to be allocated during the + // whole execution, the system will reclaim memory. + filelist = devtools_ijar::read_filelist(argv[3] + 1); + if (filelist == NULL) { + return -1; + } + } + return devtools_ijar::create(argv[2], filelist, flatten, verbose, compress); } else { if (flatten) { usage(argv[0]);
diff --git a/third_party/zlib/google/zip_reader.cc b/third_party/zlib/google/zip_reader.cc index 91d2ec3..6be6dc1 100644 --- a/third_party/zlib/google/zip_reader.cc +++ b/third_party/zlib/google/zip_reader.cc
@@ -517,7 +517,7 @@ } FileWriterDelegate::~FileWriterDelegate() { -#if !defined(NDEBUG) +#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON) const bool success = #endif file_->SetLength(file_length_);
diff --git a/tools/android/loading/devtools_monitor.py b/tools/android/loading/devtools_monitor.py index aade097..bfbf00f 100644 --- a/tools/android/loading/devtools_monitor.py +++ b/tools/android/loading/devtools_monitor.py
@@ -22,7 +22,9 @@ import common_util -DEFAULT_TIMEOUT_SECONDS = 10 # seconds +DEFAULT_TIMEOUT_SECONDS = 10 + +_WEBSOCKET_TIMEOUT_SECONDS = 10 class DevToolsConnectionException(Exception): @@ -177,7 +179,7 @@ request = {'method': method} if params: request['params'] = params - return self._ws.SyncRequest(request) + return self._ws.SyncRequest(request, timeout=_WEBSOCKET_TIMEOUT_SECONDS) def SendAndIgnoreResponse(self, method, params=None): """Issues a request to the DevTools server, do not wait for the response. @@ -370,7 +372,8 @@ break assert self._target_descriptor['url'] == 'about:blank' self._ws = inspector_websocket.InspectorWebsocket() - self._ws.Connect(self._target_descriptor['webSocketDebuggerUrl']) + self._ws.Connect(self._target_descriptor['webSocketDebuggerUrl'], + timeout=_WEBSOCKET_TIMEOUT_SECONDS) class Listener(object):
diff --git a/tools/android/loading/loading_graph_view_visualization.py b/tools/android/loading/loading_graph_view_visualization.py index d083575..7a89f6bf 100644 --- a/tools/android/loading/loading_graph_view_visualization.py +++ b/tools/android/loading/loading_graph_view_visualization.py
@@ -2,8 +2,12 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -"""Visualize a loading_graph_view.LoadingGraphView.""" +"""Visualize a loading_graph_view.LoadingGraphView. +When executed as a script, takes a loading trace and generates a png of the +loading graph.""" + +import activity_lens import request_track @@ -167,3 +171,28 @@ from_request_id = edge.from_node.request.request_id to_request_id = edge.to_node.request.request_id return '"%s" -> "%s" %s;\n' % (from_request_id, to_request_id, arrow) + +def main(trace_file): + import subprocess + + import loading_graph_view + import loading_trace + import request_dependencies_lens + + trace = loading_trace.LoadingTrace.FromJsonFile(trace_file) + dependencies_lens = request_dependencies_lens.RequestDependencyLens(trace) + activity = activity_lens.ActivityLens(trace) + graph_view = loading_graph_view.LoadingGraphView(trace, dependencies_lens, + activity=activity) + visualization = LoadingGraphViewVisualization(graph_view) + + dotfile = trace_file + '.dot' + pngfile = trace_file + '.png' + with file(dotfile, 'w') as output: + visualization.OutputDot(output) + subprocess.check_call(['dot', '-Tpng', dotfile, '-o', pngfile]) + + +if __name__ == '__main__': + import sys + main(sys.argv[1])
diff --git a/tools/bisect-builds.py b/tools/bisect-builds.py index e2c577d..57f0ca8 100755 --- a/tools/bisect-builds.py +++ b/tools/bisect-builds.py
@@ -21,7 +21,7 @@ '/chromium-browser-asan') # GS bucket name. -GS_BUCKET_NAME = 'chrome-unsigned/desktop-W15K3Y' +GS_BUCKET_NAME = 'chrome-unsigned/desktop-5c0tCh' # Base URL for downloading official builds. GOOGLE_APIS_URL = 'commondatastorage.googleapis.com'
diff --git a/tools/chrome_proxy/common/inspector_network.py b/tools/chrome_proxy/common/inspector_network.py index 051a8fb9..dee22d37 100644 --- a/tools/chrome_proxy/common/inspector_network.py +++ b/tools/chrome_proxy/common/inspector_network.py
@@ -158,7 +158,7 @@ 'method': 'Network.clearBrowserCache' }, timeout) - def StartMonitoringNetwork(self): + def StartMonitoringNetwork(self, timeout=60): """Starts monitoring network notifications and recording HTTP responses.""" self.ClearResponseData() self._inspector_websocket.RegisterDomain( @@ -167,14 +167,14 @@ request = { 'method': 'Network.enable' } - self._inspector_websocket.SyncRequest(request) + self._inspector_websocket.SyncRequest(request, timeout) - def StopMonitoringNetwork(self): + def StopMonitoringNetwork(self, timeout=60): """Stops monitoring network notifications and recording HTTP responses.""" request = { 'method': 'Network.disable' } - self._inspector_websocket.SyncRequest(request) + self._inspector_websocket.SyncRequest(request, timeout) # There may be queued messages that don't appear until the SyncRequest # happens. Wait to unregister until after sending the disable command. self._inspector_websocket.UnregisterDomain('Network')
diff --git a/tools/clang/scripts/package.py b/tools/clang/scripts/package.py index 61f4594..cc4415b 100755 --- a/tools/clang/scripts/package.py +++ b/tools/clang/scripts/package.py
@@ -210,12 +210,11 @@ 'lib/libBlinkGCPlugin.' + so_ext, ]) if sys.platform == 'darwin': - want.extend([# Copy only the OSX and iossim (ASan and profile) runtime - # libraries: + want.extend([# Copy only the OSX (ASan and profile) and iossim (ASan) + # runtime libraries: 'lib/clang/*/lib/darwin/*asan_osx*', 'lib/clang/*/lib/darwin/*asan_iossim*', 'lib/clang/*/lib/darwin/*profile_osx*', - 'lib/clang/*/lib/darwin/*profile_iossim*', ]) elif sys.platform.startswith('linux'): # Copy the libstdc++.so.6 we linked Clang against so it can run.
diff --git a/tools/clang/scripts/update.py b/tools/clang/scripts/update.py index d541393..4b2d8c3b 100755 --- a/tools/clang/scripts/update.py +++ b/tools/clang/scripts/update.py
@@ -657,8 +657,6 @@ compiler_rt_args = base_cmake_args + [ '-DCMAKE_C_FLAGS=' + ' '.join(cflags), '-DCMAKE_CXX_FLAGS=' + ' '.join(cxxflags)] - if sys.platform == 'darwin': - compiler_rt_args += ['-DCOMPILER_RT_ENABLE_IOS=ON'] if sys.platform != 'win32': compiler_rt_args += ['-DLLVM_CONFIG_PATH=' + os.path.join(LLVM_BUILD_DIR, 'bin', 'llvm-config'),
diff --git a/tools/gn/command_format.cc b/tools/gn/command_format.cc index a054b21b..7b8f2f3 100644 --- a/tools/gn/command_format.cc +++ b/tools/gn/command_format.cc
@@ -181,7 +181,7 @@ // bracket. template <class PARSENODE> // Just for const covariance. void Sequence(SequenceStyle style, - const std::vector<PARSENODE*>& list, + const std::vector<std::unique_ptr<PARSENODE>>& list, const ParseNode* end, bool force_multiline); @@ -194,7 +194,7 @@ void InitializeSub(Printer* sub); template <class PARSENODE> - bool ListWillBeMultiline(const std::vector<PARSENODE*>& list, + bool ListWillBeMultiline(const std::vector<std::unique_ptr<PARSENODE>>& list, const ParseNode* end); std::string output_; // Output buffer. @@ -385,7 +385,7 @@ size_t i = 0; for (const auto& stmt : block->statements()) { - Expr(stmt, kPrecedenceLowest, std::string()); + Expr(stmt.get(), kPrecedenceLowest, std::string()); Newline(); if (stmt->comments()) { // Why are before() not printed here too? before() are handled inside @@ -399,8 +399,8 @@ } } if (i < block->statements().size() - 1 && - (ShouldAddBlankLineInBetween(block->statements()[i], - block->statements()[i + 1]))) { + (ShouldAddBlankLineInBetween(block->statements()[i].get(), + block->statements()[i + 1].get()))) { Newline(); } ++i; @@ -648,7 +648,7 @@ template <class PARSENODE> void Printer::Sequence(SequenceStyle style, - const std::vector<PARSENODE*>& list, + const std::vector<std::unique_ptr<PARSENODE>>& list, const ParseNode* end, bool force_multiline) { if (style == kSequenceStyleList) @@ -665,7 +665,7 @@ // No elements, and not forcing newlines, print nothing. } else if (list.size() == 1 && !force_multiline) { Print(" "); - Expr(list[0], kPrecedenceLowest, std::string()); + Expr(list[0].get(), kPrecedenceLowest, std::string()); CHECK(!list[0]->comments() || list[0]->comments()->after().empty()); Print(" "); } else { @@ -687,11 +687,11 @@ bool body_of_list = i < list.size() - 1 || style == kSequenceStyleList; bool want_comma = body_of_list && (style == kSequenceStyleList && !x->AsBlockComment()); - Expr(x, kPrecedenceLowest, want_comma ? "," : std::string()); + Expr(x.get(), kPrecedenceLowest, want_comma ? "," : std::string()); CHECK(!x->comments() || x->comments()->after().empty()); if (body_of_list) { if (i < list.size() - 1 && - ShouldAddBlankLineInBetween(list[i], list[i + 1])) + ShouldAddBlankLineInBetween(list[i].get(), list[i + 1].get())) Newline(); } ++i; @@ -734,7 +734,7 @@ bool have_block = func_call->block() != nullptr; bool force_multiline = false; - const std::vector<const ParseNode*>& list = func_call->args()->contents(); + const auto& list = func_call->args()->contents(); const ParseNode* end = func_call->args()->End(); if (end && end->comments() && !end->comments()->before().empty()) @@ -767,7 +767,7 @@ IndentState(CurrentColumn(), continuation_requires_indent, false)); int penalty_one_line = 0; for (size_t i = 0; i < list.size(); ++i) { - penalty_one_line += sub1.Expr(list[i], kPrecedenceLowest, + penalty_one_line += sub1.Expr(list[i].get(), kPrecedenceLowest, i < list.size() - 1 ? ", " : std::string()); } sub1.Print(terminator); @@ -785,8 +785,9 @@ IndentState(CurrentColumn(), continuation_requires_indent, false)); int penalty_multiline_start_same_line = 0; for (size_t i = 0; i < list.size(); ++i) { - penalty_multiline_start_same_line += sub2.Expr( - list[i], kPrecedenceLowest, i < list.size() - 1 ? "," : std::string()); + penalty_multiline_start_same_line += + sub2.Expr(list[i].get(), kPrecedenceLowest, + i < list.size() - 1 ? "," : std::string()); if (i < list.size() - 1) { sub2.Newline(); } @@ -807,8 +808,9 @@ std::abs(sub3.CurrentColumn() - start_column) * kPenaltyHorizontalSeparation; } - penalty_multiline_start_next_line += sub3.Expr( - list[i], kPrecedenceLowest, i < list.size() - 1 ? "," : std::string()); + penalty_multiline_start_next_line += + sub3.Expr(list[i].get(), kPrecedenceLowest, + i < list.size() - 1 ? "," : std::string()); if (i < list.size() - 1) { sub3.Newline(); } @@ -852,7 +854,7 @@ Newline(); } bool want_comma = i < list.size() - 1 && !x->AsBlockComment(); - Expr(x, kPrecedenceLowest, want_comma ? "," : std::string()); + Expr(x.get(), kPrecedenceLowest, want_comma ? "," : std::string()); CHECK(!x->comments() || x->comments()->after().empty()); if (i < list.size() - 1) { if (!want_comma) @@ -900,8 +902,9 @@ } template <class PARSENODE> -bool Printer::ListWillBeMultiline(const std::vector<PARSENODE*>& list, - const ParseNode* end) { +bool Printer::ListWillBeMultiline( + const std::vector<std::unique_ptr<PARSENODE>>& list, + const ParseNode* end) { if (list.size() > 1) return true;
diff --git a/tools/gn/function_foreach.cc b/tools/gn/function_foreach.cc index 549ebe4..b74fc18 100644 --- a/tools/gn/function_foreach.cc +++ b/tools/gn/function_foreach.cc
@@ -47,7 +47,7 @@ const FunctionCallNode* function, const ListNode* args_list, Err* err) { - const std::vector<const ParseNode*>& args_vector = args_list->contents(); + const auto& args_vector = args_list->contents(); if (args_vector.size() != 2) { *err = Err(function, "Wrong number of arguments to foreach().", "Expecting exactly two."); @@ -57,7 +57,8 @@ // Extract the loop variable. const IdentifierNode* identifier = args_vector[0]->AsIdentifier(); if (!identifier) { - *err = Err(args_vector[0], "Expected an identifier for the loop var."); + *err = + Err(args_vector[0].get(), "Expected an identifier for the loop var."); return Value(); } base::StringPiece loop_var(identifier->value().value()); @@ -69,7 +70,7 @@ if (list_identifier) { list_value = scope->GetValue(list_identifier->value().value(), true); if (!list_value) { - *err = Err(args_vector[1], "Undefined identifier."); + *err = Err(args_vector[1].get(), "Undefined identifier."); return Value(); } } else {
diff --git a/tools/gn/function_forward_variables_from.cc b/tools/gn/function_forward_variables_from.cc index ee14128..dd3629b 100644 --- a/tools/gn/function_forward_variables_from.cc +++ b/tools/gn/function_forward_variables_from.cc
@@ -153,7 +153,7 @@ const FunctionCallNode* function, const ListNode* args_list, Err* err) { - const std::vector<const ParseNode*>& args_vector = args_list->contents(); + const auto& args_vector = args_list->contents(); if (args_vector.size() != 2 && args_vector.size() != 3) { *err = Err(function, "Wrong number of arguments.", "Expecting two or three arguments."); @@ -166,7 +166,7 @@ // to execute the ParseNode and get the value out if it's not an identifer. const IdentifierNode* identifier = args_vector[0]->AsIdentifier(); if (!identifier) { - *err = Err(args_vector[0], "Expected an identifier for the scope."); + *err = Err(args_vector[0].get(), "Expected an identifier for the scope."); return Value(); }
diff --git a/tools/gn/functions.cc b/tools/gn/functions.cc index f6d405d..af413d6 100644 --- a/tools/gn/functions.cc +++ b/tools/gn/functions.cc
@@ -464,7 +464,7 @@ const FunctionCallNode* function, const ListNode* args_list, Err* err) { - const std::vector<const ParseNode*>& args_vector = args_list->contents(); + const auto& args_vector = args_list->contents(); if (args_vector.size() != 1) { *err = Err(function, "Wrong number of arguments to defined().", "Expecting exactly one.");
diff --git a/tools/gn/import_manager.cc b/tools/gn/import_manager.cc index 83cc090..8c57008 100644 --- a/tools/gn/import_manager.cc +++ b/tools/gn/import_manager.cc
@@ -4,9 +4,6 @@ #include "tools/gn/import_manager.h" -#include <memory> - -#include "base/stl_util.h" #include "tools/gn/parse_tree.h" #include "tools/gn/scheduler.h" #include "tools/gn/scope_per_file_provider.h" @@ -14,10 +11,10 @@ namespace { // Returns a newly-allocated scope on success, null on failure. -Scope* UncachedImport(const Settings* settings, - const SourceFile& file, - const ParseNode* node_for_err, - Err* err) { +std::unique_ptr<Scope> UncachedImport(const Settings* settings, + const SourceFile& file, + const ParseNode* node_for_err, + Err* err) { const ParseNode* node = g_scheduler->input_file_manager()->SyncLoadFile( node_for_err->GetRange(), settings->build_settings(), file, err); if (!node) @@ -37,7 +34,7 @@ return nullptr; scope->ClearProcessingImport(); - return scope.release(); + return scope; } } // namesapce @@ -46,7 +43,6 @@ } ImportManager::~ImportManager() { - STLDeleteContainerPairSecondPointers(imports_.begin(), imports_.end()); } bool ImportManager::DoImport(const SourceFile& file, @@ -60,14 +56,14 @@ base::AutoLock lock(lock_); ImportMap::const_iterator found = imports_.find(file); if (found != imports_.end()) - imported_scope = found->second; + imported_scope = found->second.get(); } if (!imported_scope) { // Do a new import of the file. - imported_scope = UncachedImport(scope->settings(), file, - node_for_err, err); - if (!imported_scope) + std::unique_ptr<Scope> new_imported_scope = + UncachedImport(scope->settings(), file, node_for_err, err); + if (!new_imported_scope) return false; // We loaded the file outside the lock. This means that there could be a @@ -77,10 +73,10 @@ base::AutoLock lock(lock_); ImportMap::const_iterator found = imports_.find(file); if (found != imports_.end()) { - delete imported_scope; - imported_scope = found->second; + imported_scope = found->second.get(); } else { - imports_[file] = imported_scope; + imported_scope = new_imported_scope.get(); + imports_[file] = std::move(new_imported_scope); } } }
diff --git a/tools/gn/import_manager.h b/tools/gn/import_manager.h index 70aeee7..bd47a2ad 100644 --- a/tools/gn/import_manager.h +++ b/tools/gn/import_manager.h
@@ -6,6 +6,7 @@ #define TOOLS_GN_IMPORT_MANAGER_H_ #include <map> +#include <memory> #include "base/macros.h" #include "base/synchronization/lock.h" @@ -33,7 +34,7 @@ base::Lock lock_; // Owning pointers to the scopes. - typedef std::map<SourceFile, const Scope*> ImportMap; + typedef std::map<SourceFile, std::unique_ptr<const Scope>> ImportMap; ImportMap imports_; DISALLOW_COPY_AND_ASSIGN(ImportManager);
diff --git a/tools/gn/input_file_manager.cc b/tools/gn/input_file_manager.cc index a3e64606..36c0bf3 100644 --- a/tools/gn/input_file_manager.cc +++ b/tools/gn/input_file_manager.cc
@@ -94,9 +94,6 @@ InputFileManager::~InputFileManager() { // Should be single-threaded by now. - STLDeleteContainerPairSecondPointers(input_files_.begin(), - input_files_.end()); - STLDeleteContainerPointers(dynamic_inputs_.begin(), dynamic_inputs_.end()); } bool InputFileManager::AsyncLoadFile(const LocationRange& origin, @@ -114,18 +111,18 @@ InputFileMap::const_iterator found = input_files_.find(file_name); if (found == input_files_.end()) { // New file, schedule load. - InputFileData* data = new InputFileData(file_name); + std::unique_ptr<InputFileData> data(new InputFileData(file_name)); data->scheduled_callbacks.push_back(callback); - input_files_[file_name] = data; - schedule_this = base::Bind(&InputFileManager::BackgroundLoadFile, this, origin, build_settings, file_name, &data->file); + input_files_[file_name] = std::move(data); + } else { - InputFileData* data = found->second; + InputFileData* data = found->second.get(); // Prevent mixing async and sync loads. See SyncLoadFile for discussion. if (data->sync_invocation) { @@ -167,16 +164,17 @@ InputFileMap::iterator found = input_files_.find(file_name); if (found == input_files_.end()) { // Haven't seen this file yet, start loading right now. - data = new InputFileData(file_name); + std::unique_ptr<InputFileData> new_data(new InputFileData(file_name)); + data = new_data.get(); data->sync_invocation = true; - input_files_[file_name] = data; + input_files_[file_name] = std::move(new_data); base::AutoUnlock unlock(lock_); if (!LoadFile(origin, build_settings, file_name, &data->file, err)) return nullptr; } else { // This file has either been loaded or is pending loading. - data = found->second; + data = found->second.get(); if (!data->sync_invocation) { // Don't allow mixing of sync and async loads. If an async load is @@ -231,14 +229,14 @@ InputFile** file, std::vector<Token>** tokens, std::unique_ptr<ParseNode>** parse_root) { - InputFileData* data = new InputFileData(name); - { - base::AutoLock lock(lock_); - dynamic_inputs_.push_back(data); - } + std::unique_ptr<InputFileData> data(new InputFileData(name)); *file = &data->file; *tokens = &data->tokens; *parse_root = &data->parsed_root; + { + base::AutoLock lock(lock_); + dynamic_inputs_.push_back(std::move(data)); + } } int InputFileManager::GetInputFileCount() const { @@ -286,7 +284,7 @@ base::AutoLock lock(lock_); DCHECK(input_files_.find(name) != input_files_.end()); - InputFileData* data = input_files_[name]; + InputFileData* data = input_files_[name].get(); data->loaded = true; if (success) { data->tokens.swap(tokens);
diff --git a/tools/gn/input_file_manager.h b/tools/gn/input_file_manager.h index ba055e2..dd16604 100644 --- a/tools/gn/input_file_manager.h +++ b/tools/gn/input_file_manager.h
@@ -137,7 +137,8 @@ mutable base::Lock lock_; // Maps repo-relative filenames to the corresponding owned pointer. - typedef base::hash_map<SourceFile, InputFileData*> InputFileMap; + typedef base::hash_map<SourceFile, std::unique_ptr<InputFileData>> + InputFileMap; InputFileMap input_files_; // Tracks all dynamic inputs. The data are holders for memory management @@ -146,9 +147,7 @@ // charge of the threadsafety requirements. // // See AddDynamicInput(). - // - // Owning pointers. - std::vector<InputFileData*> dynamic_inputs_; + std::vector<std::unique_ptr<InputFileData>> dynamic_inputs_; DISALLOW_COPY_AND_ASSIGN(InputFileManager); };
diff --git a/tools/gn/loader.cc b/tools/gn/loader.cc index 9061be82..3ac868c 100644 --- a/tools/gn/loader.cc +++ b/tools/gn/loader.cc
@@ -7,7 +7,6 @@ #include "base/bind.h" #include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" -#include "base/stl_util.h" #include "tools/gn/build_settings.h" #include "tools/gn/err.h" #include "tools/gn/filesystem_utils.h" @@ -106,8 +105,6 @@ } LoaderImpl::~LoaderImpl() { - STLDeleteContainerPairSecondPointers(toolchain_records_.begin(), - toolchain_records_.end()); } void LoaderImpl::Load(const SourceFile& file, @@ -120,13 +117,14 @@ return; // Already in set, so this file was already loaded or schedulerd. if (toolchain_records_.empty()) { - // Nothing loaded, need to load the default build config. The intial load + // Nothing loaded, need to load the default build config. The initial load // should not specify a toolchain. DCHECK(toolchain_name.is_null()); - ToolchainRecord* record = - new ToolchainRecord(build_settings_, Label(), Label()); - toolchain_records_[Label()] = record; + std::unique_ptr<ToolchainRecord> new_record( + new ToolchainRecord(build_settings_, Label(), Label())); + ToolchainRecord* record = new_record.get(); + toolchain_records_[Label()] = std::move(new_record); // The default build config is no dependent on the toolchain definition, // since we need to load the build config before we know what the default @@ -135,22 +133,24 @@ record->waiting_on_me.push_back(SourceFileAndOrigin(file, origin)); ScheduleLoadBuildConfig(&record->settings, Scope::KeyValueMap()); + return; } ToolchainRecord* record; if (toolchain_name.is_null()) - record = toolchain_records_[default_toolchain_label_]; + record = toolchain_records_[default_toolchain_label_].get(); else - record = toolchain_records_[toolchain_name]; + record = toolchain_records_[toolchain_name].get(); if (!record) { DCHECK(!default_toolchain_label_.is_null()); // No reference to this toolchain found yet, make one. - record = new ToolchainRecord(build_settings_, toolchain_name, - default_toolchain_label_); - toolchain_records_[toolchain_name] = record; + std::unique_ptr<ToolchainRecord> new_record(new ToolchainRecord( + build_settings_, toolchain_name, default_toolchain_label_)); + record = new_record.get(); + toolchain_records_[toolchain_name] = std::move(new_record); // Schedule a load of the toolchain using the default one. Load(BuildFileForLabel(toolchain_name), origin, default_toolchain_label_); @@ -163,12 +163,13 @@ } void LoaderImpl::ToolchainLoaded(const Toolchain* toolchain) { - ToolchainRecord* record = toolchain_records_[toolchain->label()]; + ToolchainRecord* record = toolchain_records_[toolchain->label()].get(); if (!record) { DCHECK(!default_toolchain_label_.is_null()); - record = new ToolchainRecord(build_settings_, toolchain->label(), - default_toolchain_label_); - toolchain_records_[toolchain->label()] = record; + std::unique_ptr<ToolchainRecord> new_record(new ToolchainRecord( + build_settings_, toolchain->label(), default_toolchain_label_)); + record = new_record.get(); + toolchain_records_[toolchain->label()] = std::move(new_record); } record->is_toolchain_loaded = true; @@ -356,8 +357,10 @@ CHECK(empty_label != toolchain_records_.end()); // Fix up the toolchain record. - record = empty_label->second; - toolchain_records_[label] = record; + std::unique_ptr<ToolchainRecord> moved_record = + std::move(empty_label->second); + record = moved_record.get(); + toolchain_records_[label] = std::move(moved_record); toolchain_records_.erase(empty_label); // Save the default toolchain label. @@ -383,7 +386,7 @@ } } } else { - record = found_toolchain->second; + record = found_toolchain->second.get(); } DCHECK(!record->is_config_loaded);
diff --git a/tools/gn/loader.h b/tools/gn/loader.h index 3d61fe4b..37f7085 100644 --- a/tools/gn/loader.h +++ b/tools/gn/loader.h
@@ -6,6 +6,7 @@ #define TOOLS_GN_LOADER_H_ #include <map> +#include <memory> #include <set> #include "base/callback.h" @@ -173,8 +174,7 @@ Label default_toolchain_label_; // Records for the build config file loads. - // Owning pointers. - typedef std::map<Label, ToolchainRecord*> ToolchainRecordMap; + typedef std::map<Label, std::unique_ptr<ToolchainRecord>> ToolchainRecordMap; ToolchainRecordMap toolchain_records_; };
diff --git a/tools/gn/ninja_binary_target_writer.cc b/tools/gn/ninja_binary_target_writer.cc index a62f8725..4a923c3 100644 --- a/tools/gn/ninja_binary_target_writer.cc +++ b/tools/gn/ninja_binary_target_writer.cc
@@ -103,14 +103,15 @@ } } -std::string GetWindowsPCHObjectExtension(Toolchain::ToolType tool_type) { +std::string GetWindowsPCHObjectExtension(Toolchain::ToolType tool_type, + const std::string& obj_extension) { const char* lang_suffix = GetPCHLangSuffixForToolType(tool_type); std::string result = "."; // For MSVC, annotate the obj files with the language type. For example: - // obj/foo/target_name.precompile.o -> - // obj/foo/target_name.precompile.cc.o + // obj/foo/target_name.precompile.obj -> + // obj/foo/target_name.precompile.cc.obj result += lang_suffix; - result += ".o"; + result += obj_extension; return result; } @@ -182,7 +183,8 @@ Tool::PrecompiledHeaderType header_type = tool->precompiled_header_type(); switch (header_type) { case Tool::PCH_MSVC: - output_extension = GetWindowsPCHObjectExtension(tool_type); + output_extension = GetWindowsPCHObjectExtension( + tool_type, output_value.substr(extension_offset - 1)); break; case Tool::PCH_GCC: output_extension = GetGCCPCHOutputExtension(tool_type); @@ -621,7 +623,7 @@ if (tool_type != Toolchain::TYPE_NONE) { // Only include PCH deps that correspond to the tool type, for instance, - // do not specify target_name.precompile.cc.o (a CXX PCH file) as a dep + // do not specify target_name.precompile.cc.obj (a CXX PCH file) as a dep // for the output of a C tool type. // // This makes the assumption that pch_deps only contains pch output files @@ -631,9 +633,13 @@ if (tool->precompiled_header_type() != Tool::PCH_NONE) { for (const auto& dep : pch_deps) { const std::string& output_value = dep.value(); + size_t extension_offset = FindExtensionOffset(output_value); + if (extension_offset == std::string::npos) + continue; std::string output_extension; if (tool->precompiled_header_type() == Tool::PCH_MSVC) { - output_extension = GetWindowsPCHObjectExtension(tool_type); + output_extension = GetWindowsPCHObjectExtension( + tool_type, output_value.substr(extension_offset - 1)); } else if (tool->precompiled_header_type() == Tool::PCH_GCC) { output_extension = GetGCCPCHOutputExtension(tool_type); }
diff --git a/tools/gn/parse_tree.cc b/tools/gn/parse_tree.cc index 167531c..dc80514 100644 --- a/tools/gn/parse_tree.cc +++ b/tools/gn/parse_tree.cc
@@ -297,7 +297,6 @@ } BlockNode::~BlockNode() { - STLDeleteContainerPointers(statements_.begin(), statements_.end()); } const BlockNode* BlockNode::AsBlock() const { @@ -307,7 +306,7 @@ Value BlockNode::Execute(Scope* scope, Err* err) const { for (size_t i = 0; i < statements_.size() && !err->has_error(); i++) { // Check for trying to execute things with no side effects in a block. - const ParseNode* cur = statements_[i]; + const ParseNode* cur = statements_[i].get(); if (cur->AsList() || cur->AsLiteral() || cur->AsUnaryOp() || cur->AsIdentifier()) { *err = cur->MakeErrorDescribing( @@ -492,7 +491,6 @@ } ListNode::~ListNode() { - STLDeleteContainerPointers(contents_.begin(), contents_.end()); } const ListNode* ListNode::AsList() const { @@ -547,7 +545,7 @@ bool skip = false; for (size_t i = sr.begin; i != sr.end; ++i) { // Bails out if any of the nodes are unsupported. - const ParseNode* node = contents_[i]; + const ParseNode* node = contents_[i].get(); if (!node->AsLiteral() && !node->AsIdentifier() && !node->AsAccessor()) { skip = true; continue; @@ -561,15 +559,19 @@ // to determine whether two nodes were initially separated by a blank line // or not. int start_line = contents_[sr.begin]->GetRange().begin().line_number(); - const ParseNode* original_first = contents_[sr.begin]; + const ParseNode* original_first = contents_[sr.begin].get(); std::sort(contents_.begin() + sr.begin, contents_.begin() + sr.end, - comparator); + [&comparator](const std::unique_ptr<const ParseNode>& a, + const std::unique_ptr<const ParseNode>& b) { + return comparator(a.get(), b.get()); + }); // If the beginning of the range had before comments, and the first node // moved during the sort, then move its comments to the new head of the // range. - if (original_first->comments() && contents_[sr.begin] != original_first) { + if (original_first->comments() && + contents_[sr.begin].get() != original_first) { for (const auto& hc : original_first->comments()->before()) { - const_cast<ParseNode*>(contents_[sr.begin]) + const_cast<ParseNode*>(contents_[sr.begin].get()) ->comments_mutable() ->append_before(hc); } @@ -579,7 +581,7 @@ } const ParseNode* prev = nullptr; for (size_t i = sr.begin; i != sr.end; ++i) { - const ParseNode* node = contents_[i]; + const ParseNode* node = contents_[i].get(); DCHECK(node->AsLiteral() || node->AsIdentifier() || node->AsAccessor()); int line_number = prev ? prev->GetRange().end().line_number() + 1 : start_line; @@ -627,8 +629,8 @@ std::vector<SortRange> ranges; const ParseNode* prev = nullptr; size_t begin = 0; - for (size_t i = begin; i < contents_.size(); prev = contents_[i++]) { - if (IsSortRangeSeparator(contents_[i], prev)) { + for (size_t i = begin; i < contents_.size(); prev = contents_[i++].get()) { + if (IsSortRangeSeparator(contents_[i].get(), prev)) { if (i > begin) { ranges.push_back(SortRange(begin, i)); // If |i| is an item with an attached comment, then we start the next
diff --git a/tools/gn/parse_tree.h b/tools/gn/parse_tree.h index 2853799..48313bea 100644 --- a/tools/gn/parse_tree.h +++ b/tools/gn/parse_tree.h
@@ -227,9 +227,11 @@ void set_end(std::unique_ptr<EndNode> e) { end_ = std::move(e); } const EndNode* End() const { return end_.get(); } - const std::vector<ParseNode*>& statements() const { return statements_; } + const std::vector<std::unique_ptr<ParseNode>>& statements() const { + return statements_; + } void append_statement(std::unique_ptr<ParseNode> s) { - statements_.push_back(s.release()); + statements_.push_back(std::move(s)); } private: @@ -238,8 +240,7 @@ Token begin_token_; std::unique_ptr<EndNode> end_; - // Owning pointers, use unique_ptr when we can use C++11. - std::vector<ParseNode*> statements_; + std::vector<std::unique_ptr<ParseNode>> statements_; DISALLOW_COPY_AND_ASSIGN(BlockNode); }; @@ -364,9 +365,11 @@ const EndNode* End() const { return end_.get(); } void append_item(std::unique_ptr<ParseNode> s) { - contents_.push_back(s.release()); + contents_.push_back(std::move(s)); } - const std::vector<const ParseNode*>& contents() const { return contents_; } + const std::vector<std::unique_ptr<const ParseNode>>& contents() const { + return contents_; + } void SortAsStringsList(); void SortAsDepsList(); @@ -397,8 +400,7 @@ std::unique_ptr<EndNode> end_; bool prefer_multiline_; - // Owning pointers, use unique_ptr when we can use C++11. - std::vector<const ParseNode*> contents_; + std::vector<std::unique_ptr<const ParseNode>> contents_; DISALLOW_COPY_AND_ASSIGN(ListNode); };
diff --git a/tools/gn/parser.cc b/tools/gn/parser.cc index 33abfd0b..977ddad 100644 --- a/tools/gn/parser.cc +++ b/tools/gn/parser.cc
@@ -671,7 +671,7 @@ TraverseOrder(binop->right(), pre, post); } else if (const BlockNode* block = root->AsBlock()) { for (const auto& statement : block->statements()) - TraverseOrder(statement, pre, post); + TraverseOrder(statement.get(), pre, post); TraverseOrder(block->End(), pre, post); } else if (const ConditionNode* condition = root->AsConditionNode()) { TraverseOrder(condition->condition(), pre, post); @@ -684,7 +684,7 @@ // Nothing. } else if (const ListNode* list = root->AsList()) { for (const auto& node : list->contents()) - TraverseOrder(node, pre, post); + TraverseOrder(node.get(), pre, post); TraverseOrder(list->End(), pre, post); } else if (root->AsLiteral()) { // Nothing.
diff --git a/tools/gn/scope.cc b/tools/gn/scope.cc index d3d29d44..93ce966 100644 --- a/tools/gn/scope.cc +++ b/tools/gn/scope.cc
@@ -5,7 +5,7 @@ #include "tools/gn/scope.h" #include "base/logging.h" -#include "base/stl_util.h" +#include "base/memory/ptr_util.h" #include "tools/gn/parse_tree.h" #include "tools/gn/template.h" @@ -64,8 +64,6 @@ } Scope::~Scope() { - STLDeleteContainerPairSecondPointers(target_defaults_.begin(), - target_defaults_.end()); } const Value* Scope::GetValue(const base::StringPiece& ident, @@ -315,12 +313,9 @@ } } - // Be careful to delete any pointer we're about to clobber. - Scope** dest_scope = &dest->target_defaults_[current_name]; - if (*dest_scope) - delete *dest_scope; - *dest_scope = new Scope(settings_); - pair.second->NonRecursiveMergeTo(*dest_scope, options, node_for_err, + std::unique_ptr<Scope>& dest_scope = dest->target_defaults_[current_name]; + dest_scope = base::WrapUnique(new Scope(settings_)); + pair.second->NonRecursiveMergeTo(dest_scope.get(), options, node_for_err, "<SHOULDN'T HAPPEN>", err); } @@ -412,19 +407,19 @@ if (GetTargetDefaults(target_type)) return nullptr; - Scope** dest = &target_defaults_[target_type]; - if (*dest) { + std::unique_ptr<Scope>& dest = target_defaults_[target_type]; + if (dest) { NOTREACHED(); // Already set. - return *dest; + return dest.get(); } - *dest = new Scope(settings_); - return *dest; + dest = base::WrapUnique(new Scope(settings_)); + return dest.get(); } const Scope* Scope::GetTargetDefaults(const std::string& target_type) const { NamedScopeMap::const_iterator found = target_defaults_.find(target_type); if (found != target_defaults_.end()) - return found->second; + return found->second.get(); if (containing()) return containing()->GetTargetDefaults(target_type); return nullptr;
diff --git a/tools/gn/scope.h b/tools/gn/scope.h index 72aa0c3..e9bd139 100644 --- a/tools/gn/scope.h +++ b/tools/gn/scope.h
@@ -333,10 +333,9 @@ RecordMap; RecordMap values_; - // Owning pointers. Note that this can't use string pieces since the names - // are constructed from Values which might be deallocated before this goes - // out of scope. - typedef base::hash_map<std::string, Scope*> NamedScopeMap; + // Note that this can't use string pieces since the names are constructed from + // Values which might be deallocated before this goes out of scope. + typedef base::hash_map<std::string, std::unique_ptr<Scope>> NamedScopeMap; NamedScopeMap target_defaults_; // Null indicates not set and that we should fallback to the containing
diff --git a/tools/gn/visual_studio_writer.cc b/tools/gn/visual_studio_writer.cc index e0483465..4f92344 100644 --- a/tools/gn/visual_studio_writer.cc +++ b/tools/gn/visual_studio_writer.cc
@@ -5,6 +5,7 @@ #include "tools/gn/visual_studio_writer.h" #include <algorithm> +#include <iterator> #include <map> #include <memory> #include <set> @@ -211,8 +212,6 @@ } VisualStudioWriter::~VisualStudioWriter() { - STLDeleteContainerPointers(projects_.begin(), projects_.end()); - STLDeleteContainerPointers(folders_.begin(), folders_.end()); } // static @@ -281,7 +280,8 @@ // Sort projects so they appear always in the same order in solution file. // Otherwise solution file is rewritten and reloaded by Visual Studio. std::sort(writer.projects_.begin(), writer.projects_.end(), - [](const SolutionEntry* a, const SolutionEntry* b) { + [](const std::unique_ptr<SolutionProject>& a, + const std::unique_ptr<SolutionProject>& b) { return a->path < b->path; }); @@ -310,7 +310,7 @@ base::FilePath vcxproj_path = build_settings_->GetFullPath(target_file); std::string vcxproj_path_str = FilePathToUTF8(vcxproj_path); - projects_.push_back(new SolutionProject( + projects_.emplace_back(new SolutionProject( project_name, vcxproj_path_str, MakeGuid(vcxproj_path_str, kGuidSeedProject), FilePathToUTF8(build_settings_->GetFullPath(target->label().dir())), @@ -648,14 +648,14 @@ out << "# " << version_string_ << std::endl; SourceDir solution_dir(FilePathToUTF8(solution_dir_path)); - for (const SolutionEntry* folder : folders_) { + for (const std::unique_ptr<SolutionEntry>& folder : folders_) { out << "Project(\"" << kGuidTypeFolder << "\") = \"(" << folder->name << ")\", \"" << RebasePath(folder->path, solution_dir) << "\", \"" << folder->guid << "\"" << std::endl; out << "EndProject" << std::endl; } - for (const SolutionEntry* project : projects_) { + for (const std::unique_ptr<SolutionProject>& project : projects_) { out << "Project(\"" << kGuidTypeProject << "\") = \"" << project->name << "\", \"" << RebasePath(project->path, solution_dir) << "\", \"" << project->guid << "\"" << std::endl; @@ -673,7 +673,7 @@ out << "\tGlobalSection(ProjectConfigurationPlatforms) = postSolution" << std::endl; - for (const SolutionProject* project : projects_) { + for (const std::unique_ptr<SolutionProject>& project : projects_) { const std::string project_config_mode = config_mode_prefix + project->config_platform; out << "\t\t" << project->guid << '.' << config_mode @@ -688,13 +688,13 @@ out << "\tEndGlobalSection" << std::endl; out << "\tGlobalSection(NestedProjects) = preSolution" << std::endl; - for (const SolutionEntry* folder : folders_) { + for (const std::unique_ptr<SolutionEntry>& folder : folders_) { if (folder->parent_folder) { out << "\t\t" << folder->guid << " = " << folder->parent_folder->guid << std::endl; } } - for (const SolutionEntry* project : projects_) { + for (const std::unique_ptr<SolutionProject>& project : projects_) { out << "\t\t" << project->guid << " = " << project->parent_folder->guid << std::endl; } @@ -708,7 +708,7 @@ // Get all project directories. Create solution folder for each directory. std::map<base::StringPiece, SolutionEntry*> processed_paths; - for (SolutionProject* project : projects_) { + for (const std::unique_ptr<SolutionProject>& project : projects_) { base::StringPiece folder_path = project->label_dir_path; if (IsSlash(folder_path[folder_path.size() - 1])) folder_path = folder_path.substr(0, folder_path.size() - 1); @@ -717,12 +717,12 @@ project->parent_folder = it->second; } else { std::string folder_path_str = folder_path.as_string(); - SolutionEntry* folder = new SolutionEntry( + std::unique_ptr<SolutionEntry> folder(new SolutionEntry( FindLastDirComponent(SourceDir(folder_path)).as_string(), - folder_path_str, MakeGuid(folder_path_str, kGuidSeedFolder)); - folders_.push_back(folder); - project->parent_folder = folder; - processed_paths[folder_path] = folder; + folder_path_str, MakeGuid(folder_path_str, kGuidSeedFolder))); + project->parent_folder = folder.get(); + processed_paths[folder_path] = folder.get(); + folders_.push_back(std::move(folder)); if (root_folder_path_.empty()) { root_folder_path_ = folder_path_str; @@ -751,38 +751,42 @@ // Create also all parent folders up to |root_folder_path_|. SolutionFolders additional_folders; - for (SolutionEntry* folder : folders_) { - if (folder->path == root_folder_path_) + for (const std::unique_ptr<SolutionEntry>& solution_folder : folders_) { + if (solution_folder->path == root_folder_path_) continue; + SolutionEntry* folder = solution_folder.get(); base::StringPiece parent_path; while ((parent_path = FindParentDir(&folder->path)) != root_folder_path_) { auto it = processed_paths.find(parent_path); if (it != processed_paths.end()) { folder = it->second; } else { - folder = new SolutionEntry( + std::unique_ptr<SolutionEntry> new_folder(new SolutionEntry( FindLastDirComponent(SourceDir(parent_path)).as_string(), parent_path.as_string(), - MakeGuid(parent_path.as_string(), kGuidSeedFolder)); - additional_folders.push_back(folder); - processed_paths[parent_path] = folder; + MakeGuid(parent_path.as_string(), kGuidSeedFolder))); + processed_paths[parent_path] = new_folder.get(); + folder = new_folder.get(); + additional_folders.push_back(std::move(new_folder)); } } } - folders_.insert(folders_.end(), additional_folders.begin(), - additional_folders.end()); + folders_.insert(folders_.end(), + std::make_move_iterator(additional_folders.begin()), + std::make_move_iterator(additional_folders.end())); // Sort folders by path. std::sort(folders_.begin(), folders_.end(), - [](const SolutionEntry* a, const SolutionEntry* b) { + [](const std::unique_ptr<SolutionEntry>& a, + const std::unique_ptr<SolutionEntry>& b) { return a->path < b->path; }); // Match subfolders with their parents. Since |folders_| are sorted by path we // know that parent folder always precedes its children in vector. - SolutionFolders parents; - for (SolutionEntry* folder : folders_) { + std::vector<SolutionEntry*> parents; + for (const std::unique_ptr<SolutionEntry>& folder : folders_) { while (!parents.empty()) { if (base::StartsWith(folder->path, parents.back()->path, base::CompareCase::SENSITIVE)) { @@ -792,7 +796,7 @@ parents.pop_back(); } } - parents.push_back(folder); + parents.push_back(folder.get()); } }
diff --git a/tools/gn/visual_studio_writer.h b/tools/gn/visual_studio_writer.h index 5b578ed..2971896 100644 --- a/tools/gn/visual_studio_writer.h +++ b/tools/gn/visual_studio_writer.h
@@ -6,6 +6,7 @@ #define TOOLS_GN_VISUAL_STUDIO_WRITER_H_ #include <iosfwd> +#include <memory> #include <string> #include <vector> @@ -77,8 +78,8 @@ std::string config_platform; }; - using SolutionProjects = std::vector<SolutionProject*>; - using SolutionFolders = std::vector<SolutionEntry*>; + using SolutionProjects = std::vector<std::unique_ptr<SolutionProject>>; + using SolutionFolders = std::vector<std::unique_ptr<SolutionEntry>>; VisualStudioWriter(const BuildSettings* build_settings, const char* config_platform,
diff --git a/tools/gn/visual_studio_writer_unittest.cc b/tools/gn/visual_studio_writer_unittest.cc index d70117f..16e327b 100644 --- a/tools/gn/visual_studio_writer_unittest.cc +++ b/tools/gn/visual_studio_writer_unittest.cc
@@ -31,22 +31,22 @@ std::string path = MakeTestPath("/foo/chromium/src/out/Debug/obj/base/base.vcxproj"); - writer.projects_.push_back(new VisualStudioWriter::SolutionProject( + writer.projects_.emplace_back(new VisualStudioWriter::SolutionProject( "base", path, MakeGuid(path, "project"), MakeTestPath("/foo/chromium/src/base"), "Win32")); path = MakeTestPath("/foo/chromium/src/out/Debug/obj/tools/gn/gn.vcxproj"); - writer.projects_.push_back(new VisualStudioWriter::SolutionProject( + writer.projects_.emplace_back(new VisualStudioWriter::SolutionProject( "gn", path, MakeGuid(path, "project"), MakeTestPath("/foo/chromium/src/tools/gn"), "Win32")); path = MakeTestPath("/foo/chromium/src/out/Debug/obj/chrome/chrome.vcxproj"); - writer.projects_.push_back(new VisualStudioWriter::SolutionProject( + writer.projects_.emplace_back(new VisualStudioWriter::SolutionProject( "chrome", path, MakeGuid(path, "project"), MakeTestPath("/foo/chromium/src/chrome"), "Win32")); path = MakeTestPath("/foo/chromium/src/out/Debug/obj/base/bar.vcxproj"); - writer.projects_.push_back(new VisualStudioWriter::SolutionProject( + writer.projects_.emplace_back(new VisualStudioWriter::SolutionProject( "bar", path, MakeGuid(path, "project"), MakeTestPath("/foo/chromium/src/base"), "Win32")); @@ -71,12 +71,12 @@ ASSERT_EQ("gn", writer.folders_[3]->name); ASSERT_EQ(MakeTestPath("/foo/chromium/src/tools/gn"), writer.folders_[3]->path); - ASSERT_EQ(writer.folders_[2], writer.folders_[3]->parent_folder); + ASSERT_EQ(writer.folders_[2].get(), writer.folders_[3]->parent_folder); - ASSERT_EQ(writer.folders_[0], writer.projects_[0]->parent_folder); - ASSERT_EQ(writer.folders_[3], writer.projects_[1]->parent_folder); - ASSERT_EQ(writer.folders_[1], writer.projects_[2]->parent_folder); - ASSERT_EQ(writer.folders_[0], writer.projects_[3]->parent_folder); + ASSERT_EQ(writer.folders_[0].get(), writer.projects_[0]->parent_folder); + ASSERT_EQ(writer.folders_[3].get(), writer.projects_[1]->parent_folder); + ASSERT_EQ(writer.folders_[1].get(), writer.projects_[2]->parent_folder); + ASSERT_EQ(writer.folders_[0].get(), writer.projects_[3]->parent_folder); } TEST_F(VisualStudioWriterTest, ResolveSolutionFolders_AbsPath) { @@ -85,24 +85,24 @@ std::string path = MakeTestPath("/foo/chromium/src/out/Debug/obj/base/base.vcxproj"); - writer.projects_.push_back(new VisualStudioWriter::SolutionProject( + writer.projects_.emplace_back(new VisualStudioWriter::SolutionProject( "base", path, MakeGuid(path, "project"), MakeTestPath("/foo/chromium/src/base"), "Win32")); path = MakeTestPath("/foo/chromium/src/out/Debug/obj/tools/gn/gn.vcxproj"); - writer.projects_.push_back(new VisualStudioWriter::SolutionProject( + writer.projects_.emplace_back(new VisualStudioWriter::SolutionProject( "gn", path, MakeGuid(path, "project"), MakeTestPath("/foo/chromium/src/tools/gn"), "Win32")); path = MakeTestPath( "/foo/chromium/src/out/Debug/obj/ABS_PATH/C/foo/bar/bar.vcxproj"); - writer.projects_.push_back(new VisualStudioWriter::SolutionProject( + writer.projects_.emplace_back(new VisualStudioWriter::SolutionProject( "bar", path, MakeGuid(path, "project"), MakeTestPath("/foo/bar"), "Win32")); path = MakeTestPath( "/foo/chromium/src/out/Debug/obj/ABS_PATH/C/foo/bar/baz/baz.vcxproj"); - writer.projects_.push_back(new VisualStudioWriter::SolutionProject( + writer.projects_.emplace_back(new VisualStudioWriter::SolutionProject( "baz", path, MakeGuid(path, "project"), MakeTestPath("/foo/bar/baz"), "Win32")); @@ -118,7 +118,7 @@ ASSERT_EQ("baz", writer.folders_[1]->name); ASSERT_EQ(MakeTestPath("/foo/bar/baz"), writer.folders_[1]->path); - ASSERT_EQ(writer.folders_[0], writer.folders_[1]->parent_folder); + ASSERT_EQ(writer.folders_[0].get(), writer.folders_[1]->parent_folder); ASSERT_EQ("chromium", writer.folders_[2]->name); ASSERT_EQ(MakeTestPath("/foo/chromium"), writer.folders_[2]->path); @@ -126,23 +126,23 @@ ASSERT_EQ("src", writer.folders_[3]->name); ASSERT_EQ(MakeTestPath("/foo/chromium/src"), writer.folders_[3]->path); - ASSERT_EQ(writer.folders_[2], writer.folders_[3]->parent_folder); + ASSERT_EQ(writer.folders_[2].get(), writer.folders_[3]->parent_folder); ASSERT_EQ("base", writer.folders_[4]->name); ASSERT_EQ(MakeTestPath("/foo/chromium/src/base"), writer.folders_[4]->path); - ASSERT_EQ(writer.folders_[3], writer.folders_[4]->parent_folder); + ASSERT_EQ(writer.folders_[3].get(), writer.folders_[4]->parent_folder); ASSERT_EQ("tools", writer.folders_[5]->name); ASSERT_EQ(MakeTestPath("/foo/chromium/src/tools"), writer.folders_[5]->path); - ASSERT_EQ(writer.folders_[3], writer.folders_[5]->parent_folder); + ASSERT_EQ(writer.folders_[3].get(), writer.folders_[5]->parent_folder); ASSERT_EQ("gn", writer.folders_[6]->name); ASSERT_EQ(MakeTestPath("/foo/chromium/src/tools/gn"), writer.folders_[6]->path); - ASSERT_EQ(writer.folders_[5], writer.folders_[6]->parent_folder); + ASSERT_EQ(writer.folders_[5].get(), writer.folders_[6]->parent_folder); - ASSERT_EQ(writer.folders_[4], writer.projects_[0]->parent_folder); - ASSERT_EQ(writer.folders_[6], writer.projects_[1]->parent_folder); - ASSERT_EQ(writer.folders_[0], writer.projects_[2]->parent_folder); - ASSERT_EQ(writer.folders_[1], writer.projects_[3]->parent_folder); + ASSERT_EQ(writer.folders_[4].get(), writer.projects_[0]->parent_folder); + ASSERT_EQ(writer.folders_[6].get(), writer.projects_[1]->parent_folder); + ASSERT_EQ(writer.folders_[0].get(), writer.projects_[2]->parent_folder); + ASSERT_EQ(writer.folders_[1].get(), writer.projects_[3]->parent_folder); }
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index 166cc9c..7fc178d0 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -314,6 +314,42 @@ 'Linux Tests': 'none', }, + 'chromium.lkgr': { + 'ASAN Debug': 'gyp_asan_lsan_edge_fuzzer_debug_bot', + 'ASAN Release (symbolized)': + 'gyp_asan_lsan_edge_fuzzer_v8_heap_symbolized_release_bot', + 'ASAN Release Media': + 'gyp_asan_lsan_edge_fuzzer_v8_heap_chromeos_codecs_release_bot', + 'ASAN Release': 'gyp_asan_lsan_edge_fuzzer_v8_heap_release_bot', + 'ASan Debug (32-bit x86 with V8-ARM)': + 'gyp_asan_edge_fuzzer_v8_heap_debug_bot_hybrid', + 'ASan Release (32-bit x86 with V8-ARM)': + 'gyp_asan_edge_fuzzer_v8_heap_release_bot_hybrid', + 'ASan Release (32-bit x86 with V8-ARM, symbolized)': + 'gyp_asan_edge_fuzzer_v8_heap_symbolized_release_bot_hybrid', + 'ASan Release Media (32-bit x86 with V8-ARM)': + 'gyp_asan_edge_fuzzer_v8_heap_chromeos_codecs_release_bot_hybrid', + 'ChromiumOS ASAN Release': + 'gyp_chromeos_asan_lsan_edge_fuzzer_v8_heap_release_bot', + 'MSAN Release (chained origins)': 'gyp_msan_edge_release_bot', + 'MSAN Release (no origins)': 'gyp_msan_no_origins_edge_release_bot', + 'Mac ASAN Debug': 'gyp_asan_fuzzer_v8_heap_debug_symbols_static_bot', + 'Mac ASAN Release Media': + 'gyp_asan_fuzzer_v8_heap_chrome_with_codecs_release_bot', + 'Mac ASAN Release': 'gyp_asan_fuzzer_v8_heap_release_bot', + 'TSAN Debug': 'gyp_tsan_disable_nacl_line_tables_debug_bot', + 'TSAN Release': 'gyp_tsan_disable_nacl_line_tables_release_bot', + 'Telemetry Harness Upload': 'none', + 'UBSan Release': 'gyp_ubsan_release_bot', + 'UBSan vptr Release': 'gyp_ubsan_vptr_edge_release_bot', + 'Win ASan Release Coverage': + 'gyp_asan_edge_fuzzer_v8_heap_release_static_x86', + 'Win ASan Release Media': + 'gyp_asan_fuzzer_v8_heap_chrome_with_codecs_release_static_x86', + 'Win ASan Release': 'gyp_asan_fuzzer_v8_heap_release_static_x86', + 'Win SyzyASAN LKGR': 'gyp_syzyasan_no_pch_win_z7_x86', + }, + 'chromium.mac': { 'Mac Builder': 'swarming_gpu_tests_gyp_release_bot', 'Mac Builder (dbg)': 'swarming_gyp_debug_bot', @@ -557,8 +593,8 @@ # Windows bots take too long to link w/ full symbols and time out. 'Win Builder': 'swarming_gyp_release_bot_minimal_symbols_x86', 'Win Builder (dbg)': 'swarming_gyp_debug_bot_minimal_symbols_x86', - 'Win x64 Builder': 'swarming_gyp_release_bot_minimal_symbols_x64', - 'Win x64 Builder (dbg)': 'swarming_gyp_debug_bot_minimal_symbols_x64', + 'Win x64 Builder': 'swarming_gn_release_bot_minimal_symbols_x64', + 'Win x64 Builder (dbg)': 'swarming_gn_debug_bot_minimal_symbols_x64', 'Win x64 GN (dbg)': 'gn_debug_bot_minimal_symbols', 'Win x64 GN': 'gn_release_bot_minimal_symbols', 'Win 7 Tests x64 (1)': 'none', @@ -621,11 +657,9 @@ }, 'tryserver.chromium.android': { - 'android_amp': 'tbd', - 'android_archive_rel_ng': 'tbd', - 'android_coverage': 'tbd', - 'android_swarming_rel': 'tbd', - + 'android_archive_rel_ng': 'android_gn_release_trybot', + 'android_coverage': 'android_gn_debug_trybot_java_coverage', + 'android_swarming_rel': 'swarming_android_gn_release_trybot', 'android_arm64_dbg_recipe': 'swarming_android_gyp_debug_trybot_arm64', 'android_blink_rel': 'swarming_android_gyp_release_trybot', 'android_chromium_gn_compile_dbg': 'android_gn_debug_trybot', @@ -813,7 +847,7 @@ 'tryserver.chromium.win': { 'win10_chromium_x64_rel_ng': - 'swarming_gyp_release_trybot_minimal_symbols_x64', + 'swarming_gn_release_trybot_minimal_symbols_x64', 'win8_chromium_gn_dbg': 'gn_debug_bot_minimal_symbols_x86', 'win8_chromium_gn_upload': 'gn_release_bot_minimal_symbols_x86', 'win8_chromium_ng': 'gn_release_trybot_x86', @@ -838,7 +872,7 @@ 'win_chromium_variable_webkit_win7_builder': 'findit', 'win_chromium_variable_webkit_win7_builder_x64': 'findit', 'win_chromium_x64_rel_ng': - 'swarming_gyp_release_trybot_minimal_symbols_x64', + 'swarming_gn_release_trybot_minimal_symbols_x64', 'win_clang': 'win_clang_debug_bot', 'win_clang_dbg': 'swarming_gyp_clang_debug_bot_minimal_symbols_x86', 'win_clang_rel': @@ -991,6 +1025,10 @@ 'android', 'gn', 'debug_static_bot', 'arm64', ], + 'android_gn_debug_trybot_java_coverage': [ + 'android', 'gn', 'debug_trybot', 'java_coverage', + ], + 'android_without_codecs_gyp_release_bot_minimal_symbols': [ 'android_without_codecs', 'gyp', 'release_bot_minimal_symbols', ], @@ -1098,6 +1136,99 @@ 'gn', 'release_trybot', 'x86', ], + 'gyp_asan_lsan_edge_fuzzer_debug_bot': [ + 'gyp', 'asan', 'lsan', 'edge', 'fuzzer', 'debug_bot', + ], + + 'gyp_asan_lsan_edge_fuzzer_v8_heap_symbolized_release_bot': [ + 'gyp', 'asan', 'lsan', 'edge', 'v8_heap', 'symbolized', 'release_bot', + ], + + 'gyp_asan_lsan_edge_fuzzer_v8_heap_chromeos_codecs_release_bot': [ + 'gyp', 'asan', 'lsan', 'edge', 'v8_heap', 'chromeos_codecs', + 'release_bot', + ], + + 'gyp_asan_lsan_edge_fuzzer_v8_heap_release_bot': [ + 'gyp', 'asan', 'lsan', 'edge', 'fuzzer', 'v8_heap', 'release_bot', + ], + + 'gyp_asan_edge_fuzzer_v8_heap_debug_bot_hybrid': [ + 'gyp', 'asan', 'edge', 'fuzzer', 'v8_heap', 'debug_bot', 'hybrid', + ], + + 'gyp_asan_edge_fuzzer_v8_heap_release_bot_hybrid': [ + 'gyp', 'asan', 'edge', 'fuzzer', 'v8_heap', 'release_bot', 'hybrid', + ], + + 'gyp_asan_edge_fuzzer_v8_heap_symbolized_release_bot_hybrid': [ + 'gyp', 'asan', 'edge', 'fuzzer', 'v8_heap', 'symbolized', + 'release_bot', 'hybrid', + ], + + 'gyp_asan_edge_fuzzer_v8_heap_chromeos_codecs_release_bot_hybrid': [ + 'gyp', 'asan', 'edge', 'fuzzer', 'v8_heap', 'chromeos_codecs', + 'release_bot', 'hybrid', + ], + + 'gyp_chromeos_asan_lsan_edge_fuzzer_v8_heap_release_bot': [ + 'gyp', 'chromeos', 'asan', 'lsan', 'edge', 'fuzzer', 'v8_heap', + 'release_bot', + ], + + 'gyp_msan_edge_release_bot': [ + 'gyp', 'msan', 'edge', 'release_bot', + ], + + 'gyp_msan_no_origins_edge_release_bot': [ + 'gyp', 'msan_no_origins', 'edge', 'release_bot', + ], + + 'gyp_asan_fuzzer_v8_heap_debug_symbols_static_bot': [ + 'gyp', 'asan', 'fuzzer', 'v8_heap', 'debug_symbols_static_bot', + ], + + 'gyp_asan_fuzzer_v8_heap_chrome_with_codecs_release_bot': [ + 'gyp', 'asan', 'fuzzer', 'v8_heap', 'chrome_with_codecs', 'release_bot', + ], + + 'gyp_asan_fuzzer_v8_heap_release_bot': [ + 'gyp', 'asan', 'fuzzer', 'v8_heap', 'release_bot', + ], + + 'gyp_tsan_disable_nacl_line_tables_debug_bot': [ + 'gyp', 'tsan', 'disable_nacl', 'line_tables', 'debug_bot', + ], + + 'gyp_tsan_disable_nacl_line_tables_release_bot': [ + 'gyp', 'tsan', 'disable_nacl', 'line_tables', 'release_bot', + ], + + 'gyp_ubsan_release_bot': [ + 'gyp', 'ubsan', 'release_bot', + ], + + 'gyp_ubsan_vptr_edge_release_bot': [ + 'gyp', 'ubsan_vptr', 'edge', 'release_bot', + ], + + 'gyp_asan_edge_fuzzer_v8_heap_release_static_x86': [ + 'gyp', 'asan', 'edge', 'fuzzer', 'v8_heap', 'release', 'static', 'x86', + ], + + 'gyp_asan_fuzzer_v8_heap_chrome_with_codecs_release_static_x86': [ + 'gyp', 'asan', 'fuzzer', 'v8_heap', 'chrome_with_codecs', + 'release', 'static', 'x86', + ], + + 'gyp_asan_fuzzer_v8_heap_release_static_x86': [ + 'gyp', 'asan', 'fuzzer', 'v8_heap', 'release', 'static', 'x86', + ], + + 'gyp_syzyasan_no_pch_win_z7_x86': [ + 'gyp', 'syzyasan', 'no_pch', 'win_z7', 'x86', + ], + 'gyp_official': [ 'gyp', 'official', ], @@ -1245,6 +1376,10 @@ 'swarming', 'android', 'gyp', 'debug_trybot', 'arm64', ], + 'swarming_android_gn_release_trybot': [ + 'swarming', 'android', 'gn', 'release_trybot', + ], + 'swarming_android_gyp_release_bot_minimal_symbols': [ 'swarming', 'android', 'gyp', 'release_bot_minimal_symbols', ], @@ -1419,6 +1554,10 @@ 'swarming', 'gn', 'release_bot', ], + 'swarming_gn_release_bot_minimal_symbols_x64': [ + 'swarming', 'gn', 'release_bot_minimal_symbols', 'x64', + ], + 'swarming_gn_release_bot_x64': [ 'swarming', 'gn', 'release_bot', 'x64', ], @@ -1628,8 +1767,12 @@ 'gyp_defines': 'chromeos=1', }, + 'chromeos_codecs': { + 'mixins': ['ffmpeg_branding_chromeos', 'proprietary_codecs'], + }, + 'chromeos_with_codecs': { - 'mixins': ['ffmpeg_branding_chromeos', 'chromeos', 'proprietary_codecs'], + 'mixins': ['chromeos', 'chromeos_codecs'], }, 'clang_no_chrome_plugins': { @@ -1682,6 +1825,10 @@ 'mixins': ['debug_bot', 'minimal_symbols'], }, + 'debug_symbols_static_bot': { + 'mixins': ['debug', 'static', 'goma'], + }, + 'debug_static_bot': { 'mixins': ['debug', 'static', 'minimal_symbols', 'goma'], }, @@ -1700,6 +1847,11 @@ 'gyp_defines': 'chromium_win_pch=0', }, + 'edge': { + 'gn_args': 'sanitizer_coverage_flags="edge"', + 'gyp_defines': 'sanitizer_coverage=edge', + }, + 'embedded': { 'gn_args': 'error', 'gyp_defines': 'embedded=1', @@ -1714,11 +1866,21 @@ 'gyp_defines': 'target_arch=unknown', }, + 'ffmpeg_branding_chromeos': { + 'gn_args': 'ffmpeg_branding="ChromeOS"', + 'gyp_defines': 'ffmpeg_branding=ChromeOS', + }, + 'findbugs': { 'gn_args': 'run_findbugs=true', 'gyp_defines': 'run_findbugs=1', }, + 'fuzzer': { + 'gn_args': 'error', # TODO(GYP): implement enable_ipc_fuzzer=true + 'gyp_defines': 'enable_ipc_fuzzer=1', + }, + 'gn_linux_upload': { 'type': 'gn', @@ -1744,13 +1906,28 @@ 'gyp': {'type': 'gyp'}, + 'hybrid': { + 'gn_args': 'error', # TODO(GYP): figure out the equivalent for this + 'gyp_defines': 'v8_target_arch=arm target_arch=ia32, host_arch=x86_64', + 'mixins': ['disable_nacl'], + }, + 'internal_gles2_conform_tests': { 'gn_args': 'internal_gles2_conform_tests=true', 'gyp_defines': 'internal_gles2_conform_tests=1', }, + 'java_coverage': { + 'gn_args': 'emma_coverage=true emma_filter="org.chromium.*"', + }, + 'libfuzzer': { 'gn_args': 'use_libfuzzer=true' }, + 'line_tables': { + 'gn_args': '', # TODO(GYP): check that this is not needed + 'gyp_defines': 'debug_extra_cflags="-gline-tables-only"', + }, + 'ubsan_security': { 'gn_args': 'is_ubsan_security=true' }, 'lsan': { @@ -1785,6 +1962,18 @@ 'use_prebuilt_instrumented_libraries=1'), }, + 'msan_no_origins': { + 'gn_args': ('is_msan=true msan_track_origins=0 ' + 'use_prebuilt_instrumented_libraries=true'), + 'gyp_defines': ('msan=1 msan_track_origins=0 ' + 'use_prebuilt_instrumented_libraries=1'), + }, + + 'no_pch': { + 'gn_args': 'disable_precompiled_headers=true', + 'gyp_defines': 'chromium_win_pch=0', + }, + 'no_symbols': { 'gn_args': 'symbol_level=0', 'gyp_defines': 'fastbuild=2', @@ -1852,6 +2041,12 @@ 'gyp_defines': 'test_isolation_mode=prepare', }, + 'symbolized': { + 'gn_args': 'error', # TODO(GYP): add an equivalent flag for this + 'gyp_defines': + 'release_extra_cflags="-O1 -fno-inline-functions -fno-inline"', + }, + 'syzyasan': { 'gn_args': 'is_syzyasan=true', 'gyp_defines': 'syzyasan=1' @@ -1862,11 +2057,31 @@ 'gyp_defines': 'tsan=1', }, + 'ubsan': { + 'gn_args': 'is_ubsan=true', + 'gyp_defines': 'ubsan=1', + }, + + 'ubsan_vptr': { + 'gn_args': 'is_ubsan_vptr=true', + 'gyp_defines': 'ubsan_vptr=1', + }, + + 'v8_heap': { + 'gn_args': 'error', # TODO(GYP): implement v8_enable_verify_heap=true + 'gyp_defines': 'v8_enable_verify_heap=1', + }, + 'win_analyze': { 'gn_args': 'use_vs_code_analysis=true', 'gyp_defines': 'win_analyze=1', }, + 'win_z7': { + 'gn_args': 'error', # TODO(GYP): implement win_z7=true + 'gyp_defines': 'win_z7=1', + }, + 'x64': { 'gn_args': 'target_cpu="x64"', 'gyp_defines': 'target_arch=x64', @@ -1885,7 +2100,7 @@ }, 'valgrind': { - # TODO: add gn_args for 'build_for_tool=memcheck' + 'gn_args': 'error', # TODO(GYP): implement build_for_tool=memcheck 'gyp_defines': 'build_for_tool=memcheck', } },
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 5d280b6..8c2e443 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -378,6 +378,14 @@ </summary> </histogram> +<histogram name="Android.MultiWindowMode.Active" enum="BooleanEnabled"> + <owner>twellington@chromium.org</owner> + <summary> + Records on every metrics upload whether the activity is running in Android N + multi-window mode or not. + </summary> +</histogram> + <histogram name="Android.NTP.Impression" enum="NTPImpressionType"> <owner>finkm@chromium.org</owner> <summary> @@ -23600,6 +23608,24 @@ </summary> </histogram> +<histogram name="Navigation.SchemePerUniqueOrigin" enum="NavigationScheme"> + <owner>palmer@chromium.org</owner> + <owner>felt@chromium.org</owner> + <summary> + The scheme of the URL for the first main-frame navigation per origin per + non-OffTheRecord session. + </summary> +</histogram> + +<histogram name="Navigation.SchemePerUniqueOriginOTR" enum="NavigationScheme"> + <owner>palmer@chromium.org</owner> + <owner>felt@chromium.org</owner> + <summary> + The scheme of the URL for the first main-frame navigation per origin per + OffTheRecord session. + </summary> +</histogram> + <histogram name="Navigation.Start.RendererBrowserDifference.Negative" units="ms"> <owner>csharrison@chromium.org</owner> @@ -47362,6 +47388,32 @@ </summary> </histogram> +<histogram name="ServiceWorker.StartWorker.AfterFailureStreak" + enum="ServiceWorkerStatusCode"> + <owner>falken@chromium.org</owner> + <summary> + The result of trying to start a service worker after it has failed + consecutively. Recorded only for installed workers. + </summary> +</histogram> + +<histogram name="ServiceWorker.StartWorker.FailureStreak" units="count"> + <owner>falken@chromium.org</owner> + <summary> + The number of consecutive startup failures of a service worker. Recorded + each time the service worker failed (so there is double counting: failing + twice results in 1 and 2 being logged). Only for installed workers. + </summary> +</histogram> + +<histogram name="ServiceWorker.StartWorker.FailureStreakEnded" units="count"> + <owner>falken@chromium.org</owner> + <summary> + When a worker startup succeeded after failing, the number of times the + worker had consecutively failed. Recorded only for installed workers. + </summary> +</histogram> + <histogram name="ServiceWorker.StartWorker.Purpose" enum="ServiceWorkerMetrics.EventType"> <owner>falken@chromium.org</owner> @@ -65922,6 +65974,21 @@ <int value="244" label="zip"/> <int value="245" label="zipx"/> <int value="246" label="zpaq"/> + <int value="247" label="cdr"/> + <int value="248" label="dart"/> + <int value="249" label="dc42"/> + <int value="250" label="diskcopy42"/> + <int value="251" label="dmg"/> + <int value="252" label="dmgpart"/> + <int value="253" label="dvdr"/> + <int value="254" label="img"/> + <int value="255" label="imgpart"/> + <int value="256" label="ndif"/> + <int value="257" label="smi"/> + <int value="258" label="sparsebundle"/> + <int value="259" label="sparseimage"/> + <int value="260" label="toast"/> + <int value="261" label="udif"/> </enum> <enum name="DownloadItem.DangerType" type="int"> @@ -82697,6 +82764,18 @@ <int value="246" label="SEARCH_MS"/> <int value="247" label="IMG"/> <int value="248" label="SMI"/> + <int value="249" label="SPARSEBUNDLE"/> + <int value="250" label="SPARSEIMAGE"/> + <int value="251" label="CDR"/> + <int value="252" label="DMGPART"/> + <int value="253" label="DVDR"/> + <int value="254" label="DART"/> + <int value="255" label="DC42"/> + <int value="256" label="DISKCOPY42"/> + <int value="257" label="IMGPART"/> + <int value="258" label="NDIF"/> + <int value="259" label="UDIF"/> + <int value="260" label="TOAST"/> </enum> <enum name="SBClientDownloadIsSignedBinary" type="int"> @@ -92550,6 +92629,13 @@ <affected-histogram name="interstitial.interaction"/> </histogram_suffixes> +<histogram_suffixes name="ServiceWorker.FailureStreak"> + <affected-histogram name="ServiceWorker.StartWorker.AfterFailureStreak"/> + <suffix name="1" label="Failed one time."/> + <suffix name="2" label="Failed two times."/> + <suffix name="3" label="Failed three times."/> +</histogram_suffixes> + <histogram_suffixes name="ServiceWorker.StartSituation"> <affected-histogram name="EmbeddedWorkerInstance.Start.TimeToEvaluateScript"/> <affected-histogram name="EmbeddedWorkerInstance.Start.TimeToLoad.HttpCache"/>
diff --git a/tools/perf/benchmarks/speedometer.py b/tools/perf/benchmarks/speedometer.py index 157d024..e70d169 100644 --- a/tools/perf/benchmarks/speedometer.py +++ b/tools/perf/benchmarks/speedometer.py
@@ -20,6 +20,9 @@ from core import perf_benchmark +from benchmarks import v8_helper + +from telemetry import benchmark from telemetry import page as page_module from telemetry.page import page_test from telemetry import story @@ -100,3 +103,14 @@ 'http://browserbench.org/Speedometer/', ps, ps.base_dir, make_javascript_deterministic=False)) return ps + + +@benchmark.Disabled('reference') # crbug.com/579546 +class SpeedometerIgnition(Speedometer): + def SetExtraBrowserOptions(self, options): + super(SpeedometerIgnition, self).SetExtraBrowserOptions(options) + v8_helper.EnableIgnition(options) + + @classmethod + def Name(cls): + return 'speedometer-ignition'
diff --git a/tools/perf/benchmarks/v8.py b/tools/perf/benchmarks/v8.py index fcd997c..d5e857cb5 100644 --- a/tools/perf/benchmarks/v8.py +++ b/tools/perf/benchmarks/v8.py
@@ -8,6 +8,8 @@ from core import perf_benchmark from page_sets import google_pages +from benchmarks import v8_helper + from measurements import v8_detached_context_age_in_gc from measurements import v8_gc_times import page_sets @@ -21,16 +23,13 @@ from telemetry.web_perf.metrics import memory_timeline -def EnableIgnition(options): - existing_js_flags = [] - for extra_arg in options.extra_browser_args: - if extra_arg.startswith('--js-flags='): - existing_js_flags.extend(shlex.split(extra_arg[len('--js-flags='):])) - options.AppendExtraBrowserArgs([ - # This overrides any existing --js-flags, hence we have to include the - # previous flags as well. - '--js-flags=--ignition %s' % (' '.join(existing_js_flags)) - ]) +def CreateV8TimelineBasedMeasurementOptions(): + category_filter = tracing_category_filter.CreateMinimalOverheadFilter() + category_filter.AddIncludedCategory('v8') + category_filter.AddIncludedCategory('blink.console') + options = timeline_based_measurement.Options(category_filter) + options.SetTimelineBasedMetric('executionMetric') + return options @benchmark.Disabled('win') # crbug.com/416502 @@ -143,12 +142,7 @@ page_set = page_sets.TodoMVCPageSet def CreateTimelineBasedMeasurementOptions(self): - category_filter = tracing_category_filter.CreateMinimalOverheadFilter() - category_filter.AddIncludedCategory('v8') - category_filter.AddIncludedCategory('blink.console') - options = timeline_based_measurement.Options(category_filter) - options.SetTimelineBasedMetric('executionMetric') - return options + return CreateV8TimelineBasedMeasurementOptions() @classmethod def Name(cls): @@ -159,47 +153,21 @@ return True -@benchmark.Disabled('reference') # https://crbug.com/598096 -class V8TodoMVCIgnition(perf_benchmark.PerfBenchmark): +# Disabled on reference builds because they don't support the new +# Tracing.requestMemoryDump DevTools API. See http://crbug.com/540022. +@benchmark.Disabled('reference') +class V8TodoMVCIgnition(V8TodoMVC): """Measures V8 Execution metrics on the TodoMVC examples using ignition.""" page_set = page_sets.TodoMVCPageSet def SetExtraBrowserOptions(self, options): - EnableIgnition(options) - - def CreateTimelineBasedMeasurementOptions(self): - category_filter = tracing_category_filter.CreateMinimalOverheadFilter() - category_filter.AddIncludedCategory('v8') - category_filter.AddIncludedCategory('blink.console') - options = timeline_based_measurement.Options(category_filter) - options.SetTimelineBasedMetric('executionMetric') - return options + super(V8TodoMVCIgnition, self).SetExtraBrowserOptions(options) + v8_helper.EnableIgnition(options) @classmethod def Name(cls): return 'v8.todomvc-ignition' - @classmethod - def ShouldTearDownStateAfterEachStoryRun(cls): - return True - - -# Disabled on reference builds because they don't support the new -# Tracing.requestMemoryDump DevTools API. See http://crbug.com/540022. -@benchmark.Disabled('reference') # crbug.com/579546 -class V8InfiniteScrollIgnition(_InfiniteScrollBenchmark): - """Measures V8 GC metrics using Ignition.""" - - page_set = page_sets.InfiniteScrollPageSet - - def SetExtraBrowserOptions(self, options): - _InfiniteScrollBenchmark.SetExtraBrowserOptions(self,options) - EnableIgnition(options) - - @classmethod - def Name(cls): - return 'v8.infinite_scroll-ignition' - # Disabled on reference builds because they don't support the new # Tracing.requestMemoryDump DevTools API. See http://crbug.com/540022. @@ -215,6 +183,21 @@ return 'v8.infinite_scroll' +# Disabled on reference builds because they don't support the new +# Tracing.requestMemoryDump DevTools API. See http://crbug.com/540022. +@benchmark.Disabled('reference') # crbug.com/579546 +class V8InfiniteScrollIgnition(V8InfiniteScroll): + """Measures V8 GC metrics using Ignition.""" + + def SetExtraBrowserOptions(self, options): + super(V8InfiniteScrollIgnition, self).SetExtraBrowserOptions(options) + v8_helper.EnableIgnition(options) + + @classmethod + def Name(cls): + return 'v8.infinite_scroll-ignition' + + @benchmark.Enabled('android') class V8MobileInfiniteScroll(_InfiniteScrollBenchmark): """Measures V8 GC metrics and memory usage while scrolling the top mobile @@ -237,13 +220,7 @@ """Measures V8 Execution metrics on the Adword page.""" def CreateTimelineBasedMeasurementOptions(self): - - category_filter = tracing_category_filter.CreateMinimalOverheadFilter() - category_filter.AddIncludedCategory('v8') - category_filter.AddIncludedCategory('blink.console') - options = timeline_based_measurement.Options(category_filter) - options.SetTimelineBasedMetric('executionMetric') - return options + return CreateV8TimelineBasedMeasurementOptions() def CreateStorySet(self, options): """Creates the instance of StorySet used to run the benchmark.
diff --git a/tools/perf/benchmarks/v8_helper.py b/tools/perf/benchmarks/v8_helper.py new file mode 100644 index 0000000..27df3d42 --- /dev/null +++ b/tools/perf/benchmarks/v8_helper.py
@@ -0,0 +1,17 @@ +# Copyright 2016 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import shlex + + +def EnableIgnition(options): + existing_js_flags = [] + for extra_arg in options.extra_browser_args: + if extra_arg.startswith('--js-flags='): + existing_js_flags.extend(shlex.split(extra_arg[len('--js-flags='):])) + options.AppendExtraBrowserArgs([ + # This overrides any existing --js-flags, hence we have to include the + # previous flags as well. + '--js-flags=--ignition %s' % (' '.join(existing_js_flags)) + ])
diff --git a/tools/perf/chrome_telemetry_build/BUILD.gn b/tools/perf/chrome_telemetry_build/BUILD.gn index 6883c55..9bc2764 100644 --- a/tools/perf/chrome_telemetry_build/BUILD.gn +++ b/tools/perf/chrome_telemetry_build/BUILD.gn
@@ -64,6 +64,8 @@ "$root_out_dir/blink_web.dll.pdb", "$root_out_dir/content.dll.pdb", ] + } else { + data += [ "$root_out_dir/chrome_child.dll.pdb" ] } } }
diff --git a/tools/perf/chrome_telemetry_build/binary_dependencies.json b/tools/perf/chrome_telemetry_build/binary_dependencies.json index e6f6d866..43ab52c5 100644 --- a/tools/perf/chrome_telemetry_build/binary_dependencies.json +++ b/tools/perf/chrome_telemetry_build/binary_dependencies.json
@@ -11,6 +11,8 @@ }, "win_AMD64": { "local_paths": [ + "../../../out/Debug_x64/crashpad_database_util.exe", + "../../../out/Release_x64/crashpad_database_util.exe", "../../../out/Debug/crashpad_database_util.exe", "../../../out/Release/crashpad_database_util.exe" ] @@ -49,11 +51,6 @@ }, "generate_breakpad_symbols": { "file_info": { - "win_AMD64": { - "local_paths": [ - "../../../components/crash/content/tools/generate_breakpad_symbols.py" - ] - }, "mac_x86_64": { "local_paths": [ "../../../components/crash/content/tools/generate_breakpad_symbols.py"
diff --git a/tools/perf/core/stacktrace_unittest.py b/tools/perf/core/stacktrace_unittest.py index 856e954..51b1e8a 100644 --- a/tools/perf/core/stacktrace_unittest.py +++ b/tools/perf/core/stacktrace_unittest.py
@@ -15,15 +15,13 @@ # Stack traces do not currently work on 10.6, but they are also being # disabled shortly so just disable it for now. # All platforms except chromeos should at least have a valid minidump. - # TODO(dyen): Investigate why crashpad_database_util is not being included. - @decorators.Disabled('snowleopard', 'chromeos', 'win') + @decorators.Disabled('snowleopard', 'chromeos') def testValidDump(self): with self.assertRaises(exceptions.DevtoolsTargetCrashException) as c: self._tab.Navigate('chrome://crash', timeout=5) self.assertTrue(c.exception.is_valid_dump) # Stack traces aren't working on Android yet. - # TODO(dyen): Investigate why windows is crashing in mojo. @decorators.Enabled('mac', 'linux') @decorators.Disabled('snowleopard') def testCrashSymbols(self): @@ -31,6 +29,15 @@ self._tab.Navigate('chrome://crash', timeout=5) self.assertIn('CrashIntentionally', '\n'.join(c.exception.stack_trace)) + # Some platforms do not support full stack traces, this test requires only + # minimal symbols to be available. + @decorators.Enabled('mac', 'linux', 'win') + @decorators.Disabled('snowleopard') + def testCrashMinimalSymbols(self): + with self.assertRaises(exceptions.DevtoolsTargetCrashException) as c: + self._tab.Navigate('chrome://crash', timeout=5) + self.assertIn('OnNavigate', '\n'.join(c.exception.stack_trace)) + # The breakpad file specific test only apply to platforms which use the # breakpad symbol format. This also must be tested in isolation because it can # potentially interfere with other tests symbol parsing.
diff --git a/tools/roll_webrtc.py b/tools/roll_webrtc.py index 94f421c..5fb661c 100755 --- a/tools/roll_webrtc.py +++ b/tools/roll_webrtc.py
@@ -39,7 +39,7 @@ LIBJINGLE_PATH = os.path.join('third_party', 'libjingle', 'source', 'talk') LIBJINGLE_README = os.path.join('third_party', 'libjingle', 'README.chromium') # Run these CQ trybots in addition to the default ones in infra/config/cq.cfg. -EXTRA_TRYBOTS = ('tryserver.chromium.linux:linux_chromium_archive_rel_ng,' +EXTRA_TRYBOTS = ('tryserver.chromium.linux:linux_chromium_archive_rel_ng;' 'tryserver.chromium.mac:mac_chromium_archive_rel_ng') # Result codes from build/third_party/buildbot_8_4p1/buildbot/status/results.py
diff --git a/tools/valgrind/gtest_exclude/content_unittests.gtest-drmemory_win32.txt b/tools/valgrind/gtest_exclude/content_unittests.gtest-drmemory_win32.txt index 01d1997..f12d3ce 100644 --- a/tools/valgrind/gtest_exclude/content_unittests.gtest-drmemory_win32.txt +++ b/tools/valgrind/gtest_exclude/content_unittests.gtest-drmemory_win32.txt
@@ -13,4 +13,4 @@ WebContentsVideoCaptureDeviceTest.VariableResolution_FixedAspectRatio # https://crbug.com/604056 -CodecProfiles/RTCVideoDecoderTest.GetVDAErrorCounterForTesting/0 +CodecProfiles/RTCVideoDecoderTest.GetVDAErrorCounterForTesting*
diff --git a/ui/android/java/src/org/chromium/ui/autofill/OWNERS b/ui/android/java/src/org/chromium/ui/autofill/OWNERS deleted file mode 100644 index 812e8d9..0000000 --- a/ui/android/java/src/org/chromium/ui/autofill/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -aurimas@chromium.org
diff --git a/ui/android/java/src/org/chromium/ui/picker/OWNERS b/ui/android/java/src/org/chromium/ui/picker/OWNERS index a4238ac..86dc4380 100644 --- a/ui/android/java/src/org/chromium/ui/picker/OWNERS +++ b/ui/android/java/src/org/chromium/ui/picker/OWNERS
@@ -1,2 +1 @@ -aurimas@chromium.org miguelg@chromium.org
diff --git a/ui/compositor/compositor.cc b/ui/compositor/compositor.cc index 7bb1f09..fda1f49 100644 --- a/ui/compositor/compositor.cc +++ b/ui/compositor/compositor.cc
@@ -397,24 +397,6 @@ return animation_observer_list_.HasObserver(observer); } -void Compositor::AddBeginFrameObserver(CompositorBeginFrameObserver* observer) { - if (!begin_frame_observer_list_.might_have_observers()) - host_->SetChildrenNeedBeginFrames(true); - - begin_frame_observer_list_.AddObserver(observer); - - if (missed_begin_frame_args_.IsValid()) - observer->OnSendBeginFrame(missed_begin_frame_args_); -} - -void Compositor::RemoveBeginFrameObserver( - CompositorBeginFrameObserver* observer) { - begin_frame_observer_list_.RemoveObserver(observer); - - // As this call may take place while iterating over observers, unsubscription - // from |host_| is performed after iteration in |SendBeginFramesToChildren()|. -} - void Compositor::BeginMainFrame(const cc::BeginFrameArgs& args) { FOR_EACH_OBSERVER(CompositorAnimationObserver, animation_observer_list_, @@ -486,24 +468,6 @@ host_->SetNeedsRedraw(); } -void Compositor::SendBeginFramesToChildren(const cc::BeginFrameArgs& args) { - FOR_EACH_OBSERVER(CompositorBeginFrameObserver, begin_frame_observer_list_, - OnSendBeginFrame(args)); - - // Unsubscription is performed here, after iteration, to handle the case where - // the last BeginFrame observer is removed while iterating over the observers. - if (!begin_frame_observer_list_.might_have_observers()) { - host_->SetChildrenNeedBeginFrames(false); - // Unsubscription should reset |missed_begin_frame_args_|, avoiding stale - // BeginFrame dispatch when the next BeginFrame observer is added. - missed_begin_frame_args_ = cc::BeginFrameArgs(); - return; - } - - missed_begin_frame_args_ = args; - missed_begin_frame_args_.type = cc::BeginFrameArgs::MISSED; -} - const cc::LayerTreeDebugState& Compositor::GetLayerTreeDebugState() const { return host_->debug_state(); }
diff --git a/ui/compositor/compositor.h b/ui/compositor/compositor.h index f6290b9..778fbdae 100644 --- a/ui/compositor/compositor.h +++ b/ui/compositor/compositor.h
@@ -147,13 +147,6 @@ DISALLOW_COPY_AND_ASSIGN(CompositorLock); }; -// This class observes BeginFrame notification from LayerTreeHost. -class COMPOSITOR_EXPORT CompositorBeginFrameObserver { - public: - virtual ~CompositorBeginFrameObserver() {} - virtual void OnSendBeginFrame(const cc::BeginFrameArgs& args) = 0; -}; - // Compositor object to take care of GPU painting. // A Browser compositor object is responsible for generating the final // displayable form of pixels comprising a single widget's contents. It draws an @@ -263,9 +256,6 @@ void RemoveAnimationObserver(CompositorAnimationObserver* observer); bool HasAnimationObserver(const CompositorAnimationObserver* observer) const; - void AddBeginFrameObserver(CompositorBeginFrameObserver* observer); - void RemoveBeginFrameObserver(CompositorBeginFrameObserver* observer); - // Change the timeout behavior for all future locks that are created. Locks // should time out if there is an expectation that the compositor will be // responsive. @@ -308,7 +298,6 @@ void DidCommitAndDrawFrame() override; void DidCompleteSwapBuffers() override; void DidCompletePageScaleAnimation() override {} - void SendBeginFramesToChildren(const cc::BeginFrameArgs& args) override; void RecordFrameTimingEvents( std::unique_ptr<cc::FrameTimingTracker::CompositeTimingSet> composite_events, @@ -354,8 +343,6 @@ base::ObserverList<CompositorObserver, true> observer_list_; base::ObserverList<CompositorAnimationObserver> animation_observer_list_; - base::ObserverList<CompositorBeginFrameObserver, true> - begin_frame_observer_list_; gfx::AcceleratedWidget widget_; bool widget_valid_; @@ -381,9 +368,6 @@ LayerAnimatorCollection layer_animator_collection_; scoped_refptr<cc::AnimationTimeline> animation_timeline_; - // Used to send to any new CompositorBeginFrameObserver immediately. - cc::BeginFrameArgs missed_begin_frame_args_; - base::WeakPtrFactory<Compositor> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(Compositor);
diff --git a/ui/compositor/compositor_unittest.cc b/ui/compositor/compositor_unittest.cc index 1682482..1cf3ae2 100644 --- a/ui/compositor/compositor_unittest.cc +++ b/ui/compositor/compositor_unittest.cc
@@ -24,11 +24,6 @@ compositor->RemoveBeginFrameObserver(observer); } -class MockCompositorBeginFrameObserver : public CompositorBeginFrameObserver { - public: - MOCK_METHOD1(OnSendBeginFrame, void(const cc::BeginFrameArgs&)); -}; - // Test fixture for tests that require a ui::Compositor with a real task // runner. class CompositorTest : public testing::Test { @@ -91,109 +86,6 @@ } } -TEST_F(CompositorTest, AddAndRemoveBeginFrameObserver) { - cc::BeginFrameArgs args = - cc::CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE, - base::TimeTicks::FromInternalValue(33)); - - MockCompositorBeginFrameObserver test_observer; - MockCompositorBeginFrameObserver test_observer2; - - // Add a single observer. - compositor()->AddBeginFrameObserver(&test_observer); - Mock::VerifyAndClearExpectations(&test_observer); - - // When |missed_begin_frame_args_| is sent, its type is set to MISSED. - cc::BeginFrameArgs expected_args(args); - cc::BeginFrameArgs expected_missed_args(args); - expected_missed_args.type = cc::BeginFrameArgs::MISSED; - - // Simulate to trigger new BeginFrame by using |args|. - EXPECT_CALL(test_observer, OnSendBeginFrame(expected_args)); - compositor()->SendBeginFramesToChildren(args); - Mock::VerifyAndClearExpectations(&test_observer); - - // When new observer is added, Compositor immediately calls OnSendBeginFrame - // with |missed_begin_frame_args_|. - EXPECT_CALL(test_observer2, OnSendBeginFrame(expected_missed_args)); - compositor()->AddBeginFrameObserver(&test_observer2); - Mock::VerifyAndClearExpectations(&test_observer); - Mock::VerifyAndClearExpectations(&test_observer2); - - // When |test_observer2| is removed and added again, it will be called again. - EXPECT_CALL(test_observer2, OnSendBeginFrame(expected_missed_args)); - compositor()->RemoveBeginFrameObserver(&test_observer2); - compositor()->AddBeginFrameObserver(&test_observer2); - Mock::VerifyAndClearExpectations(&test_observer2); - - // When all observer is removed, |missed_begin_frame_args_| is invalidated. - // So, it is not used for newly added observer. - EXPECT_CALL(test_observer2, OnSendBeginFrame(_)).Times(0); - compositor()->RemoveBeginFrameObserver(&test_observer); - compositor()->RemoveBeginFrameObserver(&test_observer2); - compositor()->SendBeginFramesToChildren(args); - compositor()->AddBeginFrameObserver(&test_observer2); - Mock::VerifyAndClearExpectations(&test_observer2); - - compositor()->RemoveBeginFrameObserver(&test_observer2); -} - -TEST_F(CompositorTest, RemoveBeginFrameObserverWhileSendingBeginFrame) { - cc::BeginFrameArgs args = cc::CreateBeginFrameArgsForTesting( - BEGINFRAME_FROM_HERE, base::TimeTicks::FromInternalValue(33)); - - cc::BeginFrameArgs expected_args(args); - cc::BeginFrameArgs expected_missed_args(args); - expected_missed_args.type = cc::BeginFrameArgs::MISSED; - - // Add both observers, and simulate removal of |test_observer2| during - // BeginFrame dispatch (implicitly triggered when the observer is added). - MockCompositorBeginFrameObserver test_observer; - MockCompositorBeginFrameObserver test_observer2; - EXPECT_CALL(test_observer, OnSendBeginFrame(expected_args)); - EXPECT_CALL(test_observer2, OnSendBeginFrame(expected_missed_args)) - .WillOnce(RemoveObserver(compositor(), &test_observer2)); - - // When a new observer is added, Compositor immediately calls OnSendBeginFrame - // with |missed_begin_frame_args_|. - compositor()->AddBeginFrameObserver(&test_observer); - compositor()->SendBeginFramesToChildren(args); - compositor()->AddBeginFrameObserver(&test_observer2); - Mock::VerifyAndClearExpectations(&test_observer); - Mock::VerifyAndClearExpectations(&test_observer2); - - // |test_observer2| was removed during the previous implicit BeginFrame - // dispatch, and should not get the new frame. - expected_args.type = cc::BeginFrameArgs::NORMAL; - EXPECT_CALL(test_observer, OnSendBeginFrame(expected_args)); - EXPECT_CALL(test_observer2, OnSendBeginFrame(_)).Times(0); - compositor()->SendBeginFramesToChildren(args); - Mock::VerifyAndClearExpectations(&test_observer); - Mock::VerifyAndClearExpectations(&test_observer2); - - // Now remove |test_observer| during explicit BeginFrame dispatch. - EXPECT_CALL(test_observer, OnSendBeginFrame(expected_args)) - .WillOnce(RemoveObserver(compositor(), &test_observer)); - EXPECT_CALL(test_observer2, OnSendBeginFrame(_)).Times(0); - compositor()->SendBeginFramesToChildren(args); - Mock::VerifyAndClearExpectations(&test_observer); - Mock::VerifyAndClearExpectations(&test_observer2); - - // No observers should get the new frame. - EXPECT_CALL(test_observer, OnSendBeginFrame(_)).Times(0); - EXPECT_CALL(test_observer2, OnSendBeginFrame(_)).Times(0); - compositor()->SendBeginFramesToChildren(args); - Mock::VerifyAndClearExpectations(&test_observer); - Mock::VerifyAndClearExpectations(&test_observer2); - - // Adding a new observer should not trigger a missed frame, as the - // previous frame had no observers. - EXPECT_CALL(test_observer, OnSendBeginFrame(_)).Times(0); - compositor()->AddBeginFrameObserver(&test_observer); - compositor()->RemoveBeginFrameObserver(&test_observer); - Mock::VerifyAndClearExpectations(&test_observer); -} - TEST_F(CompositorTest, ReleaseWidgetWithOutputSurfaceNeverCreated) { compositor()->SetVisible(false); EXPECT_EQ(gfx::kNullAcceleratedWidget,
diff --git a/ui/compositor/debug_utils.cc b/ui/compositor/debug_utils.cc index 3d0d42dd..0fa6da7 100644 --- a/ui/compositor/debug_utils.cc +++ b/ui/compositor/debug_utils.cc
@@ -14,15 +14,12 @@ #include <string> #include "base/logging.h" -#include "base/strings/utf_string_conversions.h" #include "ui/compositor/layer.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/point_conversions.h" #include "ui/gfx/interpolated_transform.h" #include "ui/gfx/transform.h" -using base::UTF8ToWide; - namespace ui { namespace { @@ -30,79 +27,79 @@ void PrintLayerHierarchyImp(const Layer* layer, int indent, gfx::Point mouse_location, - std::wostringstream* out) { + std::ostringstream* out) { std::string indent_str(indent, ' '); layer->transform().TransformPointReverse(&mouse_location); bool mouse_inside_layer_bounds = layer->bounds().Contains(mouse_location); mouse_location.Offset(-layer->bounds().x(), -layer->bounds().y()); - *out << UTF8ToWide(indent_str); + *out << indent_str; if (mouse_inside_layer_bounds) - *out << L'*'; + *out << '*'; else - *out << L' '; + *out << ' '; - *out << UTF8ToWide(layer->name()) << L' ' << layer; + *out << layer->name() << ' ' << layer; switch (layer->type()) { case ui::LAYER_NOT_DRAWN: - *out << L" not_drawn"; + *out << " not_drawn"; break; case ui::LAYER_TEXTURED: - *out << L" textured"; + *out << " textured"; if (layer->fills_bounds_opaquely()) - *out << L" opaque"; + *out << " opaque"; break; case ui::LAYER_SOLID_COLOR: - *out << L" solid"; + *out << " solid"; break; case ui::LAYER_NINE_PATCH: - *out << L" nine_patch"; + *out << " nine_patch"; break; } if (!layer->visible()) - *out << L" !visible"; + *out << " !visible"; std::string property_indent_str(indent+3, ' '); - *out << L'\n' << UTF8ToWide(property_indent_str); - *out << L"bounds: " << layer->bounds().x() << L',' << layer->bounds().y(); - *out << L' ' << layer->bounds().width() << L'x' << layer->bounds().height(); + *out << '\n' << property_indent_str; + *out << "bounds: " << layer->bounds().x() << ',' << layer->bounds().y(); + *out << ' ' << layer->bounds().width() << 'x' << layer->bounds().height(); if (!layer->subpixel_position_offset().IsZero()) - *out << " " << UTF8ToWide(layer->subpixel_position_offset().ToString()); + *out << " " << layer->subpixel_position_offset().ToString(); const ui::Layer* mask = const_cast<ui::Layer*>(layer)->layer_mask_layer(); if (mask) { - *out << L'\n' << UTF8ToWide(property_indent_str); - *out << L"mask layer: " << std::setprecision(2) - << UTF8ToWide(mask->bounds().ToString()) - << UTF8ToWide(mask->subpixel_position_offset().ToString()); + *out << '\n' << property_indent_str; + *out << "mask layer: " << std::setprecision(2) + << mask->bounds().ToString() + << mask->subpixel_position_offset().ToString(); } if (layer->opacity() != 1.0f) { - *out << L'\n' << UTF8ToWide(property_indent_str); - *out << L"opacity: " << std::setprecision(2) << layer->opacity(); + *out << '\n' << property_indent_str; + *out << "opacity: " << std::setprecision(2) << layer->opacity(); } gfx::DecomposedTransform decomp; if (!layer->transform().IsIdentity() && gfx::DecomposeTransform(&decomp, layer->transform())) { - *out << L'\n' << UTF8ToWide(property_indent_str); - *out << L"translation: " << std::fixed << decomp.translate[0]; - *out << L", " << decomp.translate[1]; + *out << '\n' << property_indent_str; + *out << "translation: " << std::fixed << decomp.translate[0]; + *out << ", " << decomp.translate[1]; - *out << L'\n' << UTF8ToWide(property_indent_str); - *out << L"rotation: "; + *out << '\n' << property_indent_str; + *out << "rotation: "; *out << std::acos(decomp.quaternion[3]) * 360.0 / M_PI; - *out << L'\n' << UTF8ToWide(property_indent_str); - *out << L"scale: " << decomp.scale[0]; - *out << L", " << decomp.scale[1]; + *out << '\n' << property_indent_str; + *out << "scale: " << decomp.scale[0]; + *out << ", " << decomp.scale[1]; } - *out << L'\n'; + *out << '\n'; for (size_t i = 0, count = layer->children().size(); i < count; ++i) { PrintLayerHierarchyImp( @@ -113,8 +110,8 @@ } // namespace void PrintLayerHierarchy(const Layer* layer, gfx::Point mouse_location) { - std::wostringstream out; - out << L"Layer hierarchy:\n"; + std::ostringstream out; + out << "Layer hierarchy:\n"; PrintLayerHierarchyImp(layer, 0, mouse_location, &out); // Error so logs can be collected from end-users. LOG(ERROR) << out.str();
diff --git a/ui/compositor/layer_animation_sequence.cc b/ui/compositor/layer_animation_sequence.cc index f71728d..041bdbe 100644 --- a/ui/compositor/layer_animation_sequence.cc +++ b/ui/compositor/layer_animation_sequence.cc
@@ -212,17 +212,19 @@ } void LayerAnimationSequence::OnThreadedAnimationStarted( - const cc::AnimationEvent& event) { - if (elements_.empty() || event.group_id != animation_group_id_) + base::TimeTicks monotonic_time, + cc::TargetProperty::Type target_property, + int group_id) { + if (elements_.empty() || group_id != animation_group_id_) return; size_t current_index = last_element_ % elements_.size(); LayerAnimationElement::AnimatableProperties element_properties = elements_[current_index]->properties(); LayerAnimationElement::AnimatableProperty event_property = - LayerAnimationElement::ToAnimatableProperty(event.target_property); + LayerAnimationElement::ToAnimatableProperty(target_property); DCHECK(element_properties & event_property); - elements_[current_index]->set_effective_start_time(event.monotonic_time); + elements_[current_index]->set_effective_start_time(monotonic_time); } void LayerAnimationSequence::OnScheduled() {
diff --git a/ui/compositor/layer_animation_sequence.h b/ui/compositor/layer_animation_sequence.h index 1cd1a9f..e050439 100644 --- a/ui/compositor/layer_animation_sequence.h +++ b/ui/compositor/layer_animation_sequence.h
@@ -18,10 +18,6 @@ #include "ui/compositor/compositor_export.h" #include "ui/compositor/layer_animation_element.h" -namespace cc { -struct AnimationEvent; -} - namespace ui { class LayerAnimationDelegate; @@ -120,7 +116,9 @@ void RemoveObserver(LayerAnimationObserver* observer); // Called when a threaded animation is actually started. - void OnThreadedAnimationStarted(const cc::AnimationEvent& event); + void OnThreadedAnimationStarted(base::TimeTicks monotonic_time, + cc::TargetProperty::Type target_property, + int group_id); // Called when the animator schedules this sequence. void OnScheduled();
diff --git a/ui/compositor/layer_animation_sequence_unittest.cc b/ui/compositor/layer_animation_sequence_unittest.cc index b4ec02b..9222046f 100644 --- a/ui/compositor/layer_animation_sequence_unittest.cc +++ b/ui/compositor/layer_animation_sequence_unittest.cc
@@ -8,7 +8,6 @@ #include "base/compiler_specific.h" #include "base/time/time.h" -#include "cc/animation/animation_events.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/compositor/layer_animation_delegate.h" #include "ui/compositor/layer_animation_element.h" @@ -93,9 +92,9 @@ sequence.Progress(start_time, &delegate); EXPECT_FLOAT_EQ(start, sequence.last_progressed_fraction()); effective_start = start_time + delta; - sequence.OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::STARTED, 0, sequence.animation_group_id(), - cc::TargetProperty::OPACITY, effective_start)); + sequence.OnThreadedAnimationStarted(effective_start, + cc::TargetProperty::OPACITY, + sequence.animation_group_id()); sequence.Progress(effective_start + delta/2, &delegate); EXPECT_FLOAT_EQ(middle, sequence.last_progressed_fraction()); EXPECT_TRUE(sequence.IsFinished(effective_start + delta)); @@ -147,9 +146,9 @@ EXPECT_FLOAT_EQ(0.0, sequence.last_progressed_fraction()); opacity_effective_start = start_time + delta; EXPECT_EQ(starting_group_id, sequence.animation_group_id()); - sequence.OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::STARTED, 0, sequence.animation_group_id(), - cc::TargetProperty::OPACITY, opacity_effective_start)); + sequence.OnThreadedAnimationStarted(opacity_effective_start, + cc::TargetProperty::OPACITY, + sequence.animation_group_id()); sequence.Progress(opacity_effective_start + delta/2, &delegate); EXPECT_FLOAT_EQ(0.5, sequence.last_progressed_fraction()); sequence.Progress(opacity_effective_start + delta, &delegate); @@ -175,9 +174,9 @@ EXPECT_FLOAT_EQ(0.0, sequence.last_progressed_fraction()); transform_effective_start = opacity_effective_start + 3 * delta; EXPECT_NE(starting_group_id, sequence.animation_group_id()); - sequence.OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::STARTED, 0, sequence.animation_group_id(), - cc::TargetProperty::TRANSFORM, transform_effective_start)); + sequence.OnThreadedAnimationStarted(transform_effective_start, + cc::TargetProperty::TRANSFORM, + sequence.animation_group_id()); sequence.Progress(transform_effective_start + delta/2, &delegate); EXPECT_FLOAT_EQ(0.5, sequence.last_progressed_fraction()); EXPECT_TRUE(sequence.IsFinished(transform_effective_start + delta));
diff --git a/ui/compositor/layer_animator.cc b/ui/compositor/layer_animator.cc index 787b121..d7c36da 100644 --- a/ui/compositor/layer_animator.cc +++ b/ui/compositor/layer_animator.cc
@@ -10,7 +10,6 @@ #include "base/logging.h" #include "base/trace_event/trace_event.h" -#include "cc/animation/animation_events.h" #include "cc/animation/animation_host.h" #include "cc/animation/animation_id_provider.h" #include "cc/animation/animation_player.h" @@ -196,17 +195,11 @@ else DCHECK_EQ(animation_player_->layer_id(), layer_id); - if (animation_player_->element_animations()) { - animation_player_->element_animations() - ->AddEventObserver(this); - } + animation_player_->set_layer_animation_delegate(this); } void LayerAnimator::DetachLayerFromAnimationPlayer() { - if (animation_player_->element_animations()) { - animation_player_->element_animations() - ->RemoveEventObserver(this); - } + animation_player_->set_layer_animation_delegate(nullptr); if (animation_player_->layer_id()) animation_player_->DetachLayer(); @@ -409,23 +402,26 @@ } void LayerAnimator::OnThreadedAnimationStarted( - const cc::AnimationEvent& event) { + base::TimeTicks monotonic_time, + cc::TargetProperty::Type target_property, + int group_id) { LayerAnimationElement::AnimatableProperty property = - LayerAnimationElement::ToAnimatableProperty(event.target_property); + LayerAnimationElement::ToAnimatableProperty(target_property); RunningAnimation* running = GetRunningAnimation(property); if (!running) return; DCHECK(running->is_sequence_alive()); - if (running->sequence()->animation_group_id() != event.group_id) + if (running->sequence()->animation_group_id() != group_id) return; - running->sequence()->OnThreadedAnimationStarted(event); + running->sequence()->OnThreadedAnimationStarted(monotonic_time, + target_property, group_id); if (!running->sequence()->waiting_for_group_start()) return; - base::TimeTicks start_time = event.monotonic_time; + base::TimeTicks start_time = monotonic_time; running->sequence()->set_waiting_for_group_start(false); @@ -436,7 +432,7 @@ iter != running_animations_.end(); ++iter) { // Ensure that each sequence is only Started once, regardless of the // number of sequences in the group that have threaded first elements. - if (((*iter).sequence()->animation_group_id() == event.group_id) && + if (((*iter).sequence()->animation_group_id() == group_id) && !(*iter).sequence()->IsFirstElementThreaded() && (*iter).sequence()->waiting_for_group_start()) { (*iter).sequence()->set_start_time(start_time); @@ -956,8 +952,11 @@ return delegate_ ? delegate_->GetLayerAnimatorCollection() : NULL; } -void LayerAnimator::OnAnimationStarted(const cc::AnimationEvent& event) { - OnThreadedAnimationStarted(event); +void LayerAnimator::NotifyAnimationStarted( + base::TimeTicks monotonic_time, + cc::TargetProperty::Type target_property, + int group) { + OnThreadedAnimationStarted(monotonic_time, target_property, group); } LayerAnimator::RunningAnimation::RunningAnimation(
diff --git a/ui/compositor/layer_animator.h b/ui/compositor/layer_animator.h index c9dedd027..9bd9f05 100644 --- a/ui/compositor/layer_animator.h +++ b/ui/compositor/layer_animator.h
@@ -15,7 +15,8 @@ #include "base/memory/ref_counted.h" #include "base/observer_list.h" #include "base/time/time.h" -#include "cc/animation/layer_animation_event_observer.h" +#include "cc/animation/animation_delegate.h" +#include "cc/animation/target_property.h" #include "ui/compositor/compositor_export.h" #include "ui/compositor/layer_animation_element.h" #include "ui/compositor/layer_threaded_animation_delegate.h" @@ -56,7 +57,7 @@ class COMPOSITOR_EXPORT LayerAnimator : public base::RefCounted<LayerAnimator>, public LayerThreadedAnimationDelegate, - NON_EXPORTED_BASE(public cc::LayerAnimationEventObserver) { + NON_EXPORTED_BASE(public cc::AnimationDelegate) { public: enum PreemptionStrategy { IMMEDIATELY_SET_NEW_TARGET, @@ -196,7 +197,9 @@ void RemoveObserver(LayerAnimationObserver* observer); // Called when a threaded animation is actually started. - void OnThreadedAnimationStarted(const cc::AnimationEvent& event); + void OnThreadedAnimationStarted(base::TimeTicks monotonic_time, + cc::TargetProperty::Type target_property, + int group_id); // This determines how implicit animations will be tweened. This has no // effect on animations that are explicitly started or scheduled. The default @@ -339,8 +342,21 @@ LayerAnimatorCollection* GetLayerAnimatorCollection(); - // LayerAnimationEventObserver - void OnAnimationStarted(const cc::AnimationEvent& event) override; + // cc::AnimationDelegate implementation. + void NotifyAnimationStarted(base::TimeTicks monotonic_time, + cc::TargetProperty::Type target_property, + int group_id) override; + void NotifyAnimationFinished(base::TimeTicks monotonic_time, + cc::TargetProperty::Type target_property, + int group_id) override {} + void NotifyAnimationAborted(base::TimeTicks monotonic_time, + cc::TargetProperty::Type target_property, + int group_id) override {} + void NotifyAnimationTakeover( + base::TimeTicks monotonic_time, + cc::TargetProperty::Type target_property, + double animation_start_time, + std::unique_ptr<cc::AnimationCurve> curve) override {} // Implementation of LayerThreadedAnimationDelegate. void AddThreadedAnimation(std::unique_ptr<cc::Animation> animation) override;
diff --git a/ui/compositor/layer_animator_unittest.cc b/ui/compositor/layer_animator_unittest.cc index 89bb496..6367b58 100644 --- a/ui/compositor/layer_animator_unittest.cc +++ b/ui/compositor/layer_animator_unittest.cc
@@ -10,7 +10,6 @@ #include "base/macros.h" #include "base/strings/stringprintf.h" #include "base/time/time.h" -#include "cc/animation/animation_events.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_animation_delegate.h" @@ -372,11 +371,10 @@ base::TimeTicks start_time = test_controller.animator()->last_step_time(); base::TimeTicks effective_start = start_time + delta; - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::STARTED, 0, + test_controller.animator()->OnThreadedAnimationStarted( + effective_start, cc::TargetProperty::OPACITY, test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::TargetProperty::OPACITY, effective_start)); + ->animation_group_id()); animator->Step(effective_start + delta / 2); @@ -481,11 +479,10 @@ base::TimeTicks start_time = test_controller.animator()->last_step_time(); base::TimeTicks effective_start = start_time + delta; - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::STARTED, 0, + test_controller.animator()->OnThreadedAnimationStarted( + effective_start, cc::TargetProperty::OPACITY, test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::TargetProperty::OPACITY, effective_start)); + ->animation_group_id()); animator->Step(effective_start + delta / 2); @@ -742,11 +739,10 @@ base::TimeTicks start_time = test_controller.animator()->last_step_time(); base::TimeTicks effective_start = start_time + delta; - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::STARTED, 0, + test_controller.animator()->OnThreadedAnimationStarted( + effective_start, cc::TargetProperty::OPACITY, test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::TargetProperty::OPACITY, effective_start)); + ->animation_group_id()); animator->Step(effective_start + delta / 2); @@ -866,11 +862,10 @@ base::TimeTicks start_time = test_controller.animator()->last_step_time(); base::TimeTicks effective_start = start_time + delta; - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::STARTED, 0, + test_controller.animator()->OnThreadedAnimationStarted( + effective_start, cc::TargetProperty::OPACITY, test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::TargetProperty::OPACITY, effective_start)); + ->animation_group_id()); animator->Step(effective_start + delta / 2); @@ -889,11 +884,10 @@ base::TimeTicks second_effective_start = effective_start + delta; - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::STARTED, 0, + test_controller.animator()->OnThreadedAnimationStarted( + second_effective_start, cc::TargetProperty::OPACITY, test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::TargetProperty::OPACITY, second_effective_start)); + ->animation_group_id()); animator->Step(second_effective_start + delta / 2); @@ -1189,11 +1183,10 @@ base::TimeTicks start_time = test_controller.animator()->last_step_time(); base::TimeTicks effective_start = start_time + delta; - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::STARTED, 0, + test_controller.animator()->OnThreadedAnimationStarted( + effective_start, cc::TargetProperty::OPACITY, test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::TargetProperty::OPACITY, effective_start)); + ->animation_group_id()); animator->Step(effective_start + delta / 2); @@ -1217,11 +1210,10 @@ base::TimeTicks second_effective_start = effective_start + delta; - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::STARTED, 0, + test_controller.animator()->OnThreadedAnimationStarted( + second_effective_start, cc::TargetProperty::OPACITY, test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::TargetProperty::OPACITY, second_effective_start)); + ->animation_group_id()); animator->Step(second_effective_start + delta / 2); @@ -1459,22 +1451,20 @@ base::TimeTicks start_time = test_controller.animator()->last_step_time(); base::TimeTicks effective_start = start_time + delta; - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::STARTED, 0, + test_controller.animator()->OnThreadedAnimationStarted( + effective_start, cc::TargetProperty::OPACITY, test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::TargetProperty::OPACITY, effective_start)); + ->animation_group_id()); animator->Step(effective_start + delta); EXPECT_TRUE(test_controller.animator()->is_animating()); EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), target_opacity); base::TimeTicks second_effective_start = effective_start + 2 * delta; - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::STARTED, 0, + test_controller.animator()->OnThreadedAnimationStarted( + second_effective_start, cc::TargetProperty::OPACITY, test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::TargetProperty::OPACITY, second_effective_start)); + ->animation_group_id()); animator->Step(second_effective_start + delta); @@ -1482,22 +1472,20 @@ EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), start_opacity); base::TimeTicks third_effective_start = second_effective_start + 2 * delta; - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::STARTED, 0, + test_controller.animator()->OnThreadedAnimationStarted( + third_effective_start, cc::TargetProperty::OPACITY, test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::TargetProperty::OPACITY, third_effective_start)); + ->animation_group_id()); animator->Step(third_effective_start + delta); EXPECT_TRUE(test_controller.animator()->is_animating()); EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), target_opacity); base::TimeTicks fourth_effective_start = third_effective_start + 2 * delta; - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::STARTED, 0, + test_controller.animator()->OnThreadedAnimationStarted( + fourth_effective_start, cc::TargetProperty::OPACITY, test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::TargetProperty::OPACITY, fourth_effective_start)); + ->animation_group_id()); // Skip ahead by a lot. animator->Step(fourth_effective_start + 1000 * delta); @@ -1506,11 +1494,10 @@ EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), target_opacity); base::TimeTicks fifth_effective_start = fourth_effective_start + 1001 * delta; - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::STARTED, 0, + test_controller.animator()->OnThreadedAnimationStarted( + fifth_effective_start, cc::TargetProperty::OPACITY, test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::TargetProperty::OPACITY, fifth_effective_start)); + ->animation_group_id()); // Skip ahead by a lot. animator->Step(fifth_effective_start + 999 * delta);
diff --git a/ui/compositor/test/layer_animator_test_controller.cc b/ui/compositor/test/layer_animator_test_controller.cc index 497cb92..611b2de 100644 --- a/ui/compositor/test/layer_animator_test_controller.cc +++ b/ui/compositor/test/layer_animator_test_controller.cc
@@ -50,9 +50,9 @@ element->effective_start_time() != base::TimeTicks()) continue; - animator_->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::STARTED, 0, element->animation_group_id(), - threaded_properties[i], base::TimeTicks::Now())); + animator_->OnThreadedAnimationStarted(base::TimeTicks::Now(), + threaded_properties[i], + element->animation_group_id()); } }
diff --git a/ui/gl/BUILD.gn b/ui/gl/BUILD.gn index 34cecb7..ea3d06a 100644 --- a/ui/gl/BUILD.gn +++ b/ui/gl/BUILD.gn
@@ -230,6 +230,8 @@ "gl_image_io_surface.mm", "scoped_cgl.cc", "scoped_cgl.h", + "yuv_to_rgb_converter.cc", + "yuv_to_rgb_converter.h", ] libs = [
diff --git a/ui/gl/gl.gyp b/ui/gl/gl.gyp index 66420ce..a1fce09 100644 --- a/ui/gl/gl.gyp +++ b/ui/gl/gl.gyp
@@ -243,6 +243,8 @@ 'gl_image_io_surface.h', 'scoped_cgl.cc', 'scoped_cgl.h', + 'yuv_to_rgb_converter.cc', + 'yuv_to_rgb_converter.h', ], 'link_settings': { 'libraries': [
diff --git a/ui/gl/gl_context.cc b/ui/gl/gl_context.cc index 70cc8523..63b711a 100644 --- a/ui/gl/gl_context.cc +++ b/ui/gl/gl_context.cc
@@ -92,6 +92,10 @@ return std::string(renderer ? renderer : ""); } +gl::YUVToRGBConverter* GLContext::GetYUVToRGBConverter() { + return nullptr; +} + bool GLContext::HasExtension(const char* name) { std::string extensions = GetExtensions(); extensions += " ";
diff --git a/ui/gl/gl_context.h b/ui/gl/gl_context.h index 1b4c040..6d1420ded4 100644 --- a/ui/gl/gl_context.h +++ b/ui/gl/gl_context.h
@@ -17,6 +17,10 @@ #include "ui/gl/gl_state_restorer.h" #include "ui/gl/gpu_preference.h" +namespace gl { +class YUVToRGBConverter; +} // namespace gl + namespace gpu { class GLContextVirtual; } // namespace gpu @@ -29,7 +33,6 @@ class VirtualGLApi; struct GLVersionInfo; - // Encapsulates an OpenGL context, hiding platform specific management. class GL_EXPORT GLContext : public base::RefCounted<GLContext> { public: @@ -127,6 +130,9 @@ // Returns the GL renderer string. The context must be current. virtual std::string GetGLRenderer(); + // Returns a helper structure to convert YUV textures to RGB textures. + virtual gl::YUVToRGBConverter* GetYUVToRGBConverter(); + protected: virtual ~GLContext();
diff --git a/ui/gl/gl_context_cgl.cc b/ui/gl/gl_context_cgl.cc index 374b38e..333f2f1 100644 --- a/ui/gl/gl_context_cgl.cc +++ b/ui/gl/gl_context_cgl.cc
@@ -16,6 +16,8 @@ #include "ui/gl/gl_implementation.h" #include "ui/gl/gl_surface.h" #include "ui/gl/gpu_switching_manager.h" +#include "ui/gl/scoped_cgl.h" +#include "ui/gl/yuv_to_rgb_converter.h" namespace gfx { @@ -136,6 +138,10 @@ } void GLContextCGL::Destroy() { + if (yuv_to_rgb_converter_) { + gfx::ScopedCGLSetCurrentContext(static_cast<CGLContextObj>(context_)); + yuv_to_rgb_converter_.reset(); + } if (discrete_pixelformat_) { if (base::MessageLoop::current() != nullptr) { // Delay releasing the pixel format for 10 seconds to reduce the number of @@ -195,6 +201,12 @@ return true; } +gl::YUVToRGBConverter* GLContextCGL::GetYUVToRGBConverter() { + if (!yuv_to_rgb_converter_) + yuv_to_rgb_converter_.reset(new gl::YUVToRGBConverter); + return yuv_to_rgb_converter_.get(); +} + bool GLContextCGL::MakeCurrent(GLSurface* surface) { DCHECK(context_);
diff --git a/ui/gl/gl_context_cgl.h b/ui/gl/gl_context_cgl.h index bb7a241..1a10162 100644 --- a/ui/gl/gl_context_cgl.h +++ b/ui/gl/gl_context_cgl.h
@@ -8,6 +8,7 @@ #include <OpenGL/CGLTypes.h> #include "base/macros.h" +#include "base/memory/scoped_ptr.h" #include "ui/gl/gl_context.h" namespace gfx { @@ -29,6 +30,7 @@ void OnSetSwapInterval(int interval) override; void SetSafeToForceGpuSwitch() override; bool ForceGpuSwitchIfNeeded() override; + gl::YUVToRGBConverter* GetYUVToRGBConverter() override; protected: ~GLContextCGL() override; @@ -39,6 +41,7 @@ void* context_; GpuPreference gpu_preference_; + scoped_ptr<gl::YUVToRGBConverter> yuv_to_rgb_converter_; CGLPixelFormatObj discrete_pixelformat_;
diff --git a/ui/gl/gl_image_io_surface.h b/ui/gl/gl_image_io_surface.h index a7d71be..f62d4a21 100644 --- a/ui/gl/gl_image_io_surface.h +++ b/ui/gl/gl_image_io_surface.h
@@ -87,10 +87,6 @@ gfx::GenericSharedMemoryId io_surface_id_; base::ThreadChecker thread_checker_; - // GL state to support 420v IOSurface conversion to RGB. This is retained - // to avoid re-creating the necessary GL programs every frame. - scoped_refptr<RGBConverter> rgb_converter_; - DISALLOW_COPY_AND_ASSIGN(GLImageIOSurface); };
diff --git a/ui/gl/gl_image_io_surface.mm b/ui/gl/gl_image_io_surface.mm index 1ae69b6..68bf3c0d 100644 --- a/ui/gl/gl_image_io_surface.mm +++ b/ui/gl/gl_image_io_surface.mm
@@ -7,21 +7,16 @@ #include <map> #include "base/callback_helpers.h" -#include "base/lazy_instance.h" #include "base/mac/bind_objc_block.h" #include "base/mac/foundation_util.h" -#include "base/strings/stringize_macros.h" -#include "base/strings/stringprintf.h" #include "base/trace_event/memory_allocator_dump.h" #include "base/trace_event/memory_dump_manager.h" #include "base/trace_event/process_memory_dump.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_context.h" -#include "ui/gl/gl_helper.h" -#include "ui/gl/gl_implementation.h" #include "ui/gl/scoped_api.h" #include "ui/gl/scoped_binders.h" -#include "ui/gl/scoped_cgl.h" +#include "ui/gl/yuv_to_rgb_converter.h" // Note that this must be included after gl_bindings.h to avoid conflicts. #include <OpenGL/CGLIOSurface.h> @@ -33,60 +28,6 @@ namespace gl { namespace { -const char kVertexHeaderCompatiblityProfile[] = - "#version 110\n" - "#define ATTRIBUTE attribute\n" - "#define VARYING varying\n"; - -const char kVertexHeaderCoreProfile[] = - "#version 150\n" - "#define ATTRIBUTE in\n" - "#define VARYING out\n"; - -const char kFragmentHeaderCompatiblityProfile[] = - "#version 110\n" - "#extension GL_ARB_texture_rectangle : require\n" - "#define VARYING varying\n" - "#define FRAGCOLOR gl_FragColor\n" - "#define TEX texture2DRect\n"; - -const char kFragmentHeaderCoreProfile[] = - "#version 150\n" - "#define VARYING in\n" - "#define TEX texture\n" - "#define FRAGCOLOR frag_color\n" - "out vec4 FRAGCOLOR;\n"; - -// clang-format off -const char kVertexShader[] = -STRINGIZE( - ATTRIBUTE vec2 a_position; - uniform vec2 a_texScale; - VARYING vec2 v_texCoord; - void main() { - gl_Position = vec4(a_position.x, a_position.y, 0.0, 1.0); - v_texCoord = (a_position + vec2(1.0, 1.0)) * 0.5 * a_texScale; - } -); - -const char kFragmentShader[] = -STRINGIZE( - uniform sampler2DRect a_y_texture; - uniform sampler2DRect a_uv_texture; - VARYING vec2 v_texCoord; - void main() { - vec3 yuv_adj = vec3(-0.0625, -0.5, -0.5); - mat3 yuv_matrix = mat3(vec3(1.164, 1.164, 1.164), - vec3(0.0, -.391, 2.018), - vec3(1.596, -.813, 0.0)); - vec3 yuv = vec3( - TEX(a_y_texture, v_texCoord).r, - TEX(a_uv_texture, v_texCoord * 0.5).rg); - FRAGCOLOR = vec4(yuv_matrix * (yuv + yuv_adj), 1.0); - } -); -// clang-format on - bool ValidInternalFormat(unsigned internalformat) { switch (internalformat) { case GL_RED: @@ -219,176 +160,6 @@ } // namespace -class GLImageIOSurface::RGBConverter - : public base::RefCounted<GLImageIOSurface::RGBConverter> { - public: - static scoped_refptr<RGBConverter> GetForCurrentContext(); - bool CopyTexImage(IOSurfaceRef io_surface, const gfx::Size& size); - - private: - friend class base::RefCounted<RGBConverter>; - RGBConverter(CGLContextObj cgl_context); - ~RGBConverter(); - - unsigned framebuffer_ = 0; - unsigned vertex_shader_ = 0; - unsigned fragment_shader_ = 0; - unsigned program_ = 0; - int size_location_ = -1; - unsigned vertex_buffer_ = 0; - base::ScopedTypeRef<CGLContextObj> cgl_context_; - - static base::LazyInstance< - std::map<CGLContextObj, GLImageIOSurface::RGBConverter*>> - g_rgb_converters; - static base::LazyInstance<base::ThreadChecker> - g_rgb_converters_thread_checker; -}; - -base::LazyInstance<std::map<CGLContextObj, GLImageIOSurface::RGBConverter*>> - GLImageIOSurface::RGBConverter::g_rgb_converters; - -base::LazyInstance<base::ThreadChecker> - GLImageIOSurface::RGBConverter::g_rgb_converters_thread_checker; - -scoped_refptr<GLImageIOSurface::RGBConverter> -GLImageIOSurface::RGBConverter::GetForCurrentContext() { - CGLContextObj current_context = CGLGetCurrentContext(); - DCHECK(current_context); - DCHECK(g_rgb_converters_thread_checker.Get().CalledOnValidThread()); - auto found = g_rgb_converters.Get().find(current_context); - if (found != g_rgb_converters.Get().end()) - return make_scoped_refptr(found->second); - return make_scoped_refptr(new RGBConverter(current_context)); -} - -GLImageIOSurface::RGBConverter::RGBConverter(CGLContextObj cgl_context) - : cgl_context_(cgl_context, base::scoped_policy::RETAIN) { - bool use_core_profile = - gfx::GetGLImplementation() == gfx::kGLImplementationDesktopGLCoreProfile; - gfx::ScopedSetGLToRealGLApi scoped_set_gl_api; - glGenFramebuffersEXT(1, &framebuffer_); - vertex_buffer_ = gfx::GLHelper::SetupQuadVertexBuffer(); - vertex_shader_ = gfx::GLHelper::LoadShader( - GL_VERTEX_SHADER, - base::StringPrintf("%s\n%s", - use_core_profile ? kVertexHeaderCoreProfile - : kVertexHeaderCompatiblityProfile, - kVertexShader).c_str()); - fragment_shader_ = gfx::GLHelper::LoadShader( - GL_FRAGMENT_SHADER, - base::StringPrintf("%s\n%s", - use_core_profile ? kFragmentHeaderCoreProfile - : kFragmentHeaderCompatiblityProfile, - kFragmentShader).c_str()); - program_ = gfx::GLHelper::SetupProgram(vertex_shader_, fragment_shader_); - - gfx::ScopedUseProgram use_program(program_); - size_location_ = glGetUniformLocation(program_, "a_texScale"); - DCHECK_NE(-1, size_location_); - int y_sampler_location = glGetUniformLocation(program_, "a_y_texture"); - DCHECK_NE(-1, y_sampler_location); - int uv_sampler_location = glGetUniformLocation(program_, "a_uv_texture"); - DCHECK_NE(-1, uv_sampler_location); - - glUniform1i(y_sampler_location, 0); - glUniform1i(uv_sampler_location, 1); - - DCHECK(g_rgb_converters_thread_checker.Get().CalledOnValidThread()); - DCHECK(g_rgb_converters.Get().find(cgl_context) == - g_rgb_converters.Get().end()); - g_rgb_converters.Get()[cgl_context] = this; -} - -GLImageIOSurface::RGBConverter::~RGBConverter() { - DCHECK(g_rgb_converters_thread_checker.Get().CalledOnValidThread()); - DCHECK(g_rgb_converters.Get()[cgl_context_] == this); - g_rgb_converters.Get().erase(cgl_context_.get()); - { - gfx::ScopedCGLSetCurrentContext(cgl_context_.get()); - gfx::ScopedSetGLToRealGLApi scoped_set_gl_api; - glDeleteProgram(program_); - glDeleteShader(vertex_shader_); - glDeleteShader(fragment_shader_); - glDeleteBuffersARB(1, &vertex_buffer_); - glDeleteFramebuffersEXT(1, &framebuffer_); - } - cgl_context_.reset(); -} - -bool GLImageIOSurface::RGBConverter::CopyTexImage(IOSurfaceRef io_surface, - const gfx::Size& size) { - gfx::ScopedSetGLToRealGLApi scoped_set_gl_api; - DCHECK_EQ(CGLGetCurrentContext(), cgl_context_.get()); - glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, size.width(), size.height(), - 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr); - GLint target_texture = 0; - glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &target_texture); - DCHECK(target_texture); - - // Note that state restoration is done explicitly in the ScopedClosureRunner - // instead of scoped binders to avoid https://crbug.com/601729. - GLint old_active_texture = -1; - glGetIntegerv(GL_ACTIVE_TEXTURE, &old_active_texture); - GLint old_texture0_binding = -1; - glActiveTexture(GL_TEXTURE0); - glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_texture0_binding); - GLint old_texture1_binding = -1; - glActiveTexture(GL_TEXTURE1); - glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_texture1_binding); - - unsigned y_texture = 0; - glGenTextures(1, &y_texture); - unsigned uv_texture = 0; - glGenTextures(1, &uv_texture); - - base::ScopedClosureRunner destroy_resources_runner(base::BindBlock(^{ - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_RECTANGLE_ARB, old_texture0_binding); - glActiveTexture(GL_TEXTURE1); - glBindTexture(GL_TEXTURE_RECTANGLE_ARB, old_texture1_binding); - glActiveTexture(old_active_texture); - - glDeleteTextures(1, &y_texture); - glDeleteTextures(1, &uv_texture); - })); - - CGLError cgl_error = kCGLNoError; - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_RECTANGLE_ARB, y_texture); - cgl_error = CGLTexImageIOSurface2D(cgl_context_, GL_TEXTURE_RECTANGLE_ARB, - GL_RED, size.width(), size.height(), - GL_RED, GL_UNSIGNED_BYTE, io_surface, 0); - if (cgl_error != kCGLNoError) { - LOG(ERROR) << "Error in CGLTexImageIOSurface2D for the Y plane. " - << cgl_error; - return false; - } - glActiveTexture(GL_TEXTURE1); - glBindTexture(GL_TEXTURE_RECTANGLE_ARB, uv_texture); - cgl_error = CGLTexImageIOSurface2D(cgl_context_, GL_TEXTURE_RECTANGLE_ARB, - GL_RG, size.width() / 2, size.height() / 2, - GL_RG, GL_UNSIGNED_BYTE, io_surface, 1); - if (cgl_error != kCGLNoError) { - LOG(ERROR) << "Error in CGLTexImageIOSurface2D for the UV plane. " - << cgl_error; - return false; - } - - gfx::ScopedFrameBufferBinder framebuffer_binder(framebuffer_); - gfx::ScopedViewport viewport(0, 0, size.width(), size.height()); - glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, - GL_TEXTURE_RECTANGLE_ARB, target_texture, 0); - DCHECK_EQ(static_cast<GLenum>(GL_FRAMEBUFFER_COMPLETE), - glCheckFramebufferStatusEXT(GL_FRAMEBUFFER)); - gfx::ScopedUseProgram use_program(program_); - glUniform2f(size_location_, size.width(), size.height()); - gfx::GLHelper::DrawQuad(vertex_buffer_); - glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, - GL_TEXTURE_RECTANGLE_ARB, 0, 0); - return true; -} - GLImageIOSurface::GLImageIOSurface(const gfx::Size& size, unsigned internalformat) : size_(size), @@ -492,13 +263,62 @@ if (format_ != BufferFormat::YUV_420_BIPLANAR) return false; + if (target != GL_TEXTURE_RECTANGLE_ARB) { LOG(ERROR) << "YUV_420_BIPLANAR requires GL_TEXTURE_RECTANGLE_ARB target"; return false; } - rgb_converter_ = RGBConverter::GetForCurrentContext(); - return rgb_converter_->CopyTexImage(io_surface_.get(), size_); + gfx::GLContext* gl_context = gfx::GLContext::GetCurrent(); + DCHECK(gl_context); + + gl::YUVToRGBConverter* yuv_to_rgb_converter = + gl_context->GetYUVToRGBConverter(); + DCHECK(yuv_to_rgb_converter); + + gfx::ScopedSetGLToRealGLApi scoped_set_gl_api; + + // Note that state restoration is done explicitly instead of scoped binders to + // avoid https://crbug.com/601729. + GLint rgb_texture = 0; + GLuint y_texture = 0; + GLuint uv_texture = 0; + glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &rgb_texture); + glGenTextures(1, &y_texture); + glGenTextures(1, &uv_texture); + base::ScopedClosureRunner destroy_resources_runner(base::BindBlock(^{ + glDeleteTextures(1, &y_texture); + glDeleteTextures(1, &uv_texture); + glBindTexture(GL_TEXTURE_RECTANGLE_ARB, rgb_texture); + })); + + CGLContextObj cgl_context = CGLGetCurrentContext(); + { + glBindTexture(GL_TEXTURE_RECTANGLE_ARB, y_texture); + CGLError cgl_error = CGLTexImageIOSurface2D( + cgl_context, GL_TEXTURE_RECTANGLE_ARB, GL_RED, size_.width(), + size_.height(), GL_RED, GL_UNSIGNED_BYTE, io_surface_, 0); + if (cgl_error != kCGLNoError) { + LOG(ERROR) << "Error in CGLTexImageIOSurface2D for the Y plane. " + << cgl_error; + return false; + } + } + { + glBindTexture(GL_TEXTURE_RECTANGLE_ARB, uv_texture); + CGLError cgl_error = CGLTexImageIOSurface2D( + cgl_context, GL_TEXTURE_RECTANGLE_ARB, GL_RG, size_.width() / 2, + size_.height() / 2, GL_RG, GL_UNSIGNED_BYTE, io_surface_, 1); + if (cgl_error != kCGLNoError) { + LOG(ERROR) << "Error in CGLTexImageIOSurface2D for the UV plane. " + << cgl_error; + return false; + } + } + + yuv_to_rgb_converter->CopyYUV420ToRGB( + GL_TEXTURE_RECTANGLE_ARB, y_texture, uv_texture, size_, rgb_texture); + return true; } bool GLImageIOSurface::CopyTexSubImage(unsigned target,
diff --git a/ui/gl/yuv_to_rgb_converter.cc b/ui/gl/yuv_to_rgb_converter.cc new file mode 100644 index 0000000..4c19b36 --- /dev/null +++ b/ui/gl/yuv_to_rgb_converter.cc
@@ -0,0 +1,166 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/gl/yuv_to_rgb_converter.h" + +#include "base/strings/stringize_macros.h" +#include "base/strings/stringprintf.h" +#include "ui/gl/gl_helper.h" +#include "ui/gl/gl_implementation.h" +#include "ui/gl/scoped_api.h" +#include "ui/gl/scoped_binders.h" + +namespace gl { +namespace { + +const char kVertexHeaderCompatiblityProfile[] = + "#version 110\n" + "#define ATTRIBUTE attribute\n" + "#define VARYING varying\n"; + +const char kVertexHeaderCoreProfile[] = + "#version 150\n" + "#define ATTRIBUTE in\n" + "#define VARYING out\n"; + +const char kFragmentHeaderCompatiblityProfile[] = + "#version 110\n" + "#extension GL_ARB_texture_rectangle : require\n" + "#define VARYING varying\n" + "#define FRAGCOLOR gl_FragColor\n" + "#define TEX texture2DRect\n"; + +const char kFragmentHeaderCoreProfile[] = + "#version 150\n" + "#define VARYING in\n" + "#define TEX texture\n" + "#define FRAGCOLOR frag_color\n" + "out vec4 FRAGCOLOR;\n"; + +// clang-format off +const char kVertexShader[] = +STRINGIZE( + ATTRIBUTE vec2 a_position; + uniform vec2 a_texScale; + VARYING vec2 v_texCoord; + void main() { + gl_Position = vec4(a_position.x, a_position.y, 0.0, 1.0); + v_texCoord = (a_position + vec2(1.0, 1.0)) * 0.5 * a_texScale; + } +); + +const char kFragmentShader[] = +STRINGIZE( + uniform sampler2DRect a_y_texture; + uniform sampler2DRect a_uv_texture; + VARYING vec2 v_texCoord; + void main() { + vec3 yuv_adj = vec3(-0.0625, -0.5, -0.5); + mat3 yuv_matrix = mat3(vec3(1.164, 1.164, 1.164), + vec3(0.0, -.391, 2.018), + vec3(1.596, -.813, 0.0)); + vec3 yuv = vec3( + TEX(a_y_texture, v_texCoord).r, + TEX(a_uv_texture, v_texCoord * 0.5).rg); + FRAGCOLOR = vec4(yuv_matrix * (yuv + yuv_adj), 1.0); + } +); +// clang-format on + +} // namespace + +YUVToRGBConverter::YUVToRGBConverter() { + bool use_core_profile = + gfx::GetGLImplementation() == gfx::kGLImplementationDesktopGLCoreProfile; + gfx::ScopedSetGLToRealGLApi scoped_set_gl_api; + glGenFramebuffersEXT(1, &framebuffer_); + vertex_buffer_ = gfx::GLHelper::SetupQuadVertexBuffer(); + vertex_shader_ = gfx::GLHelper::LoadShader( + GL_VERTEX_SHADER, + base::StringPrintf("%s\n%s", + use_core_profile ? kVertexHeaderCoreProfile + : kVertexHeaderCompatiblityProfile, + kVertexShader) + .c_str()); + fragment_shader_ = gfx::GLHelper::LoadShader( + GL_FRAGMENT_SHADER, + base::StringPrintf("%s\n%s", + use_core_profile ? kFragmentHeaderCoreProfile + : kFragmentHeaderCompatiblityProfile, + kFragmentShader) + .c_str()); + program_ = gfx::GLHelper::SetupProgram(vertex_shader_, fragment_shader_); + + gfx::ScopedUseProgram use_program(program_); + size_location_ = glGetUniformLocation(program_, "a_texScale"); + DCHECK_NE(-1, size_location_); + int y_sampler_location = glGetUniformLocation(program_, "a_y_texture"); + DCHECK_NE(-1, y_sampler_location); + int uv_sampler_location = glGetUniformLocation(program_, "a_uv_texture"); + DCHECK_NE(-1, uv_sampler_location); + + glUniform1i(y_sampler_location, 0); + glUniform1i(uv_sampler_location, 1); +} + +YUVToRGBConverter::~YUVToRGBConverter() { + gfx::ScopedSetGLToRealGLApi scoped_set_gl_api; + glDeleteProgram(program_); + glDeleteShader(vertex_shader_); + glDeleteShader(fragment_shader_); + glDeleteBuffersARB(1, &vertex_buffer_); + glDeleteFramebuffersEXT(1, &framebuffer_); +} + +void YUVToRGBConverter::CopyYUV420ToRGB(unsigned target, + unsigned y_texture, + unsigned uv_texture, + const gfx::Size& size, + unsigned rgb_texture) { + // Only support for rectangle targets exists so far. + DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_RECTANGLE_ARB), target); + gfx::ScopedSetGLToRealGLApi scoped_set_gl_api; + + // Note that state restoration is done explicitly instead of scoped binders to + // avoid https://crbug.com/601729. + GLint old_active_texture = -1; + glGetIntegerv(GL_ACTIVE_TEXTURE, &old_active_texture); + GLint old_texture0_binding = -1; + glActiveTexture(GL_TEXTURE0); + glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_texture0_binding); + GLint old_texture1_binding = -1; + glActiveTexture(GL_TEXTURE1); + glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_texture1_binding); + + // Allocate the rgb texture. + glBindTexture(GL_TEXTURE_RECTANGLE_ARB, rgb_texture); + glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, size.width(), size.height(), + 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr); + + // Set up and issue the draw call. + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_RECTANGLE_ARB, y_texture); + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_RECTANGLE_ARB, uv_texture); + gfx::ScopedFrameBufferBinder framebuffer_binder(framebuffer_); + gfx::ScopedViewport viewport(0, 0, size.width(), size.height()); + glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + GL_TEXTURE_RECTANGLE_ARB, rgb_texture, 0); + DCHECK_EQ(static_cast<GLenum>(GL_FRAMEBUFFER_COMPLETE), + glCheckFramebufferStatusEXT(GL_FRAMEBUFFER)); + gfx::ScopedUseProgram use_program(program_); + glUniform2f(size_location_, size.width(), size.height()); + gfx::GLHelper::DrawQuad(vertex_buffer_); + + // Restore previous state. + glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + GL_TEXTURE_RECTANGLE_ARB, 0, 0); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_RECTANGLE_ARB, old_texture0_binding); + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_RECTANGLE_ARB, old_texture1_binding); + glActiveTexture(old_active_texture); +} + +} // namespace gl
diff --git a/ui/gl/yuv_to_rgb_converter.h b/ui/gl/yuv_to_rgb_converter.h new file mode 100644 index 0000000..794b615 --- /dev/null +++ b/ui/gl/yuv_to_rgb_converter.h
@@ -0,0 +1,33 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef UI_GL_YUV420_RGB_CONVERTER_H_ +#define UI_GL_YUV420_RGB_CONVERTER_H_ + +#include "ui/gfx/geometry/size.h" + +namespace gl { + +class YUVToRGBConverter { + public: + YUVToRGBConverter(); + ~YUVToRGBConverter(); + void CopyYUV420ToRGB(unsigned target, + unsigned y_texture, + unsigned uv_texture, + const gfx::Size& size, + unsigned rgb_texture); + + private: + unsigned framebuffer_ = 0; + unsigned vertex_shader_ = 0; + unsigned fragment_shader_ = 0; + unsigned program_ = 0; + int size_location_ = -1; + unsigned vertex_buffer_ = 0; +}; + +} // namespace gl + +#endif // UI_GL_YUV420_RGB_CONVERTER_H_
diff --git a/ui/shell_dialogs/OWNERS b/ui/shell_dialogs/OWNERS index afcba9f..68dadb1 100644 --- a/ui/shell_dialogs/OWNERS +++ b/ui/shell_dialogs/OWNERS
@@ -1,3 +1,2 @@ -per-file *android*=aurimas@chromium.org per-file *android*=miguelg@chromium.org per-file *android*=qinmin@chromium.org
diff --git a/ui/shell_dialogs/android/OWNERS b/ui/shell_dialogs/android/OWNERS index 824dee7..a936f654 100644 --- a/ui/shell_dialogs/android/OWNERS +++ b/ui/shell_dialogs/android/OWNERS
@@ -1,3 +1,2 @@ -aurimas@chromium.org miguelg@chromium.org qinmin@chromium.org
diff --git a/ui/views/cocoa/native_widget_mac_nswindow.mm b/ui/views/cocoa/native_widget_mac_nswindow.mm index 4acbd94..b93ee6f3 100644 --- a/ui/views/cocoa/native_widget_mac_nswindow.mm +++ b/ui/views/cocoa/native_widget_mac_nswindow.mm
@@ -199,9 +199,13 @@ // command handler, defer to AppController. if ([item action] == @selector(commandDispatch:) || [item action] == @selector(commandDispatchUsingKeyModifiers:)) { - return commandHandler_ - ? [commandHandler_ validateUserInterfaceItem:item window:self] - : [[NSApp delegate] validateUserInterfaceItem:item]; + if (commandHandler_) + return [commandHandler_ validateUserInterfaceItem:item window:self]; + + id appController = [NSApp delegate]; + DCHECK([appController + conformsToProtocol:@protocol(NSUserInterfaceValidations)]); + return [appController validateUserInterfaceItem:item]; } return [super validateUserInterfaceItem:item];
diff --git a/ui/views/controls/textfield/textfield.cc b/ui/views/controls/textfield/textfield.cc index 2d16153..26e1678b 100644 --- a/ui/views/controls/textfield/textfield.cc +++ b/ui/views/controls/textfield/textfield.cc
@@ -40,6 +40,7 @@ #include "ui/views/metrics.h" #include "ui/views/native_cursor.h" #include "ui/views/painter.h" +#include "ui/views/style/platform_style.h" #include "ui/views/views_delegate.h" #include "ui/views/widget/widget.h" @@ -1746,7 +1747,18 @@ void Textfield::SelectThroughLastDragLocation() { OnBeforeUserAction(); - model_->MoveCursorTo(last_drag_location_, true); + + const bool drags_to_end = PlatformStyle::kTextfieldDragVerticallyDragsToEnd; + if (drags_to_end && last_drag_location_.y() < 0) { + model_->MoveCursor(gfx::BreakType::LINE_BREAK, + gfx::VisualCursorDirection::CURSOR_LEFT, true); + } else if (drags_to_end && last_drag_location_.y() > height()) { + model_->MoveCursor(gfx::BreakType::LINE_BREAK, + gfx::VisualCursorDirection::CURSOR_RIGHT, true); + } else { + model_->MoveCursorTo(last_drag_location_, true); + } + if (aggregated_clicks_ == 1) { model_->SelectWord(); // Expand the selection so the initially selected word remains selected.
diff --git a/ui/views/controls/textfield/textfield_unittest.cc b/ui/views/controls/textfield/textfield_unittest.cc index 97320101..8e14fa0 100644 --- a/ui/views/controls/textfield/textfield_unittest.cc +++ b/ui/views/controls/textfield/textfield_unittest.cc
@@ -39,6 +39,7 @@ #include "ui/views/controls/textfield/textfield_model.h" #include "ui/views/controls/textfield/textfield_test_api.h" #include "ui/views/focus/focus_manager.h" +#include "ui/views/style/platform_style.h" #include "ui/views/test/test_views_delegate.h" #include "ui/views/test/views_test_base.h" #include "ui/views/test/widget_test.h" @@ -634,6 +635,44 @@ EXPECT_TRUE(menu->IsEnabledAt(7 /* SELECT ALL */)); } + void PressLeftMouseButton(int extra_flags) { + ui::MouseEvent click(ui::ET_MOUSE_PRESSED, mouse_position_, mouse_position_, + ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, + ui::EF_LEFT_MOUSE_BUTTON | extra_flags); + textfield_->OnMousePressed(click); + } + + void PressLeftMouseButton() { + PressLeftMouseButton(0); + } + + void ReleaseLeftMouseButton() { + ui::MouseEvent release(ui::ET_MOUSE_RELEASED, mouse_position_, + mouse_position_, ui::EventTimeForNow(), + ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); + textfield_->OnMouseReleased(release); + } + + void ClickLeftMouseButton(int extra_flags) { + PressLeftMouseButton(extra_flags); + ReleaseLeftMouseButton(); + } + + void ClickLeftMouseButton() { + ClickLeftMouseButton(0); + } + + void DragMouseTo(const gfx::Point& where) { + mouse_position_ = where; + ui::MouseEvent drag(ui::ET_MOUSE_DRAGGED, where, where, + ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0); + textfield_->OnMouseDragged(drag); + } + + // Textfield does not listen to OnMouseMoved, so this function does not send + // an event when it updates the cursor position. + void MoveMouseTo(const gfx::Point& where) { mouse_position_ = where; } + // We need widget to populate wrapper class. Widget* widget_; @@ -654,6 +693,8 @@ int on_after_user_action_; private: + // Position of the mouse for synthetic mouse events. + gfx::Point mouse_position_; ui::ClipboardType copied_to_clipboard_; std::unique_ptr<ui::test::EventGenerator> event_generator_; DISALLOW_COPY_AND_ASSIGN(TextfieldTest); @@ -1073,10 +1114,8 @@ // Test if clicking on textfield view sets the focus. widget_->GetFocusManager()->AdvanceFocus(true); EXPECT_EQ(3, GetFocusedView()->id()); - ui::MouseEvent click(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(click); + MoveMouseTo(gfx::Point()); + ClickLeftMouseButton(); EXPECT_EQ(1, GetFocusedView()->id()); // Tab/Shift+Tab should also cycle focus, not insert a tab character. @@ -1125,33 +1164,20 @@ TEST_F(TextfieldTest, DoubleAndTripleClickTest) { InitTextfield(); textfield_->SetText(ASCIIToUTF16("hello world")); - ui::MouseEvent click(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - ui::MouseEvent release(ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - ui::MouseEvent double_click(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), - ui::EventTimeForNow(), - ui::EF_LEFT_MOUSE_BUTTON | ui::EF_IS_DOUBLE_CLICK, - ui::EF_LEFT_MOUSE_BUTTON); // Test for double click. - textfield_->OnMousePressed(click); - textfield_->OnMouseReleased(release); + MoveMouseTo(gfx::Point()); + ClickLeftMouseButton(); EXPECT_TRUE(textfield_->GetSelectedText().empty()); - textfield_->OnMousePressed(double_click); - textfield_->OnMouseReleased(release); + ClickLeftMouseButton(ui::EF_IS_DOUBLE_CLICK); EXPECT_STR_EQ("hello", textfield_->GetSelectedText()); // Test for triple click. - textfield_->OnMousePressed(click); - textfield_->OnMouseReleased(release); + ClickLeftMouseButton(); EXPECT_STR_EQ("hello world", textfield_->GetSelectedText()); // Another click should reset back to double click. - textfield_->OnMousePressed(click); - textfield_->OnMouseReleased(release); + ClickLeftMouseButton(); EXPECT_STR_EQ("hello", textfield_->GetSelectedText()); } @@ -1162,39 +1188,70 @@ const int kEnd = 500; gfx::Point start_point(kStart, 0); gfx::Point end_point(kEnd, 0); - ui::MouseEvent click_a(ui::ET_MOUSE_PRESSED, start_point, start_point, - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - ui::MouseEvent click_b(ui::ET_MOUSE_PRESSED, end_point, end_point, - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - ui::MouseEvent drag_left(ui::ET_MOUSE_DRAGGED, gfx::Point(), gfx::Point(), - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0); - ui::MouseEvent drag_right(ui::ET_MOUSE_DRAGGED, end_point, end_point, - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0); - ui::MouseEvent release(ui::ET_MOUSE_RELEASED, end_point, end_point, - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(click_a); + + MoveMouseTo(start_point); + PressLeftMouseButton(); EXPECT_TRUE(textfield_->GetSelectedText().empty()); + // Check that dragging left selects the beginning of the string. - textfield_->OnMouseDragged(drag_left); + DragMouseTo(gfx::Point()); base::string16 text_left = textfield_->GetSelectedText(); EXPECT_STR_EQ("hello", text_left); + // Check that dragging right selects the rest of the string. - textfield_->OnMouseDragged(drag_right); + DragMouseTo(end_point); base::string16 text_right = textfield_->GetSelectedText(); EXPECT_STR_EQ(" world", text_right); + // Check that releasing in the same location does not alter the selection. - textfield_->OnMouseReleased(release); + ReleaseLeftMouseButton(); EXPECT_EQ(text_right, textfield_->GetSelectedText()); + // Check that dragging from beyond the text length works too. - textfield_->OnMousePressed(click_b); - textfield_->OnMouseDragged(drag_left); - textfield_->OnMouseReleased(release); + MoveMouseTo(end_point); + PressLeftMouseButton(); + DragMouseTo(gfx::Point()); + ReleaseLeftMouseButton(); EXPECT_EQ(textfield_->text(), textfield_->GetSelectedText()); } +// This test checks that dragging above the textfield selects to the beginning +// and dragging below the textfield selects to the end, but only on platforms +// where that is the expected behavior. +TEST_F(TextfieldTest, DragUpOrDownSelectsToEnd) { + InitTextfield(); + textfield_->SetText(ASCIIToUTF16("hello world")); + const base::string16 expected_up = base::ASCIIToUTF16( + PlatformStyle::kTextfieldDragVerticallyDragsToEnd ? "hello" : "lo"); + const base::string16 expected_down = base::ASCIIToUTF16( + PlatformStyle::kTextfieldDragVerticallyDragsToEnd ? " world" : " w"); + const int kStartX = GetCursorPositionX(5); + const int kDownX = GetCursorPositionX(7); + const int kUpX = GetCursorPositionX(3); + gfx::Point start_point(kStartX, 0); + gfx::Point down_point(kDownX, 500); + gfx::Point up_point(kUpX, -500); + + MoveMouseTo(start_point); + PressLeftMouseButton(); + DragMouseTo(up_point); + ReleaseLeftMouseButton(); + EXPECT_EQ(textfield_->GetSelectedText(), expected_up); + + // Click at |up_point|. This is important because drags do not count as clicks + // for the purpose of double-click detection, so if this test doesn't click + // somewhere other than |start_point| before the code below runs, the second + // click at |start_point| will be interpreted as a double-click instead of the + // start of a drag. + ClickLeftMouseButton(); + + MoveMouseTo(start_point); + PressLeftMouseButton(); + DragMouseTo(down_point); + ReleaseLeftMouseButton(); + EXPECT_EQ(textfield_->GetSelectedText(), expected_down); +} + #if defined(OS_WIN) TEST_F(TextfieldTest, DragAndDrop_AcceptDrop) { InitTextfield(); @@ -1277,11 +1334,9 @@ EXPECT_EQ(ui::DragDropTypes::DRAG_NONE, textfield_->GetDragOperationsForView(NULL, kStringPoint)); textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_TEXT); + MoveMouseTo(kStringPoint); + PressLeftMouseButton(); // Ensure that textfields only initiate drag operations inside the selection. - ui::MouseEvent press_event(ui::ET_MOUSE_PRESSED, kStringPoint, kStringPoint, - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(press_event); EXPECT_EQ(ui::DragDropTypes::DRAG_NONE, textfield_->GetDragOperationsForView(NULL, gfx::Point())); EXPECT_FALSE(textfield_->CanStartDragForView(NULL, gfx::Point(), @@ -1308,17 +1363,13 @@ // Start dragging "ello". textfield_->SelectRange(gfx::Range(1, 5)); gfx::Point point(GetCursorPositionX(3), 0); - ui::MouseEvent click_a(ui::ET_MOUSE_PRESSED, point, point, - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(click_a); - EXPECT_TRUE(textfield_->CanStartDragForView(textfield_, click_a.location(), - gfx::Point())); - operations = textfield_->GetDragOperationsForView(textfield_, - click_a.location()); + MoveMouseTo(point); + PressLeftMouseButton(); + EXPECT_TRUE(textfield_->CanStartDragForView(textfield_, point, point)); + operations = textfield_->GetDragOperationsForView(textfield_, point); EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE | ui::DragDropTypes::DRAG_COPY, operations); - textfield_->WriteDragDataForView(NULL, click_a.location(), &data); + textfield_->WriteDragDataForView(nullptr, point, &data); EXPECT_TRUE(data.GetString(&string)); EXPECT_EQ(textfield_->GetSelectedText(), string); EXPECT_TRUE(textfield_->GetDropFormats(&formats, &format_types)); @@ -1362,17 +1413,13 @@ // Start dragging " worl". textfield_->SelectRange(gfx::Range(5, 10)); gfx::Point point(GetCursorPositionX(7), 0); - ui::MouseEvent click_a(ui::ET_MOUSE_PRESSED, point, point, - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(click_a); - EXPECT_TRUE(textfield_->CanStartDragForView(textfield_, click_a.location(), - gfx::Point())); - operations = textfield_->GetDragOperationsForView(textfield_, - click_a.location()); + MoveMouseTo(point); + PressLeftMouseButton(); + EXPECT_TRUE(textfield_->CanStartDragForView(textfield_, point, gfx::Point())); + operations = textfield_->GetDragOperationsForView(textfield_, point); EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE | ui::DragDropTypes::DRAG_COPY, operations); - textfield_->WriteDragDataForView(NULL, click_a.location(), &data); + textfield_->WriteDragDataForView(nullptr, point, &data); EXPECT_TRUE(data.GetString(&string)); EXPECT_EQ(textfield_->GetSelectedText(), string); EXPECT_TRUE(textfield_->GetDropFormats(&formats, &format_types)); @@ -1410,12 +1457,10 @@ // Start dragging "worl". textfield_->SelectRange(gfx::Range(6, 10)); gfx::Point point(GetCursorPositionX(8), 0); - ui::MouseEvent click(ui::ET_MOUSE_PRESSED, point, point, - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(click); + MoveMouseTo(point); + PressLeftMouseButton(); ui::OSExchangeData data; - textfield_->WriteDragDataForView(NULL, click.location(), &data); + textfield_->WriteDragDataForView(nullptr, point, &data); EXPECT_TRUE(textfield_->CanDrop(data)); // Drag the text over somewhere valid, outside the current selection. gfx::Point drop_point(GetCursorPositionX(2), 0); @@ -1424,14 +1469,8 @@ EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE, textfield_->OnDragUpdated(drop)); // "Cancel" the drag, via move and release over the selection, and OnDragDone. gfx::Point drag_point(GetCursorPositionX(9), 0); - ui::MouseEvent drag(ui::ET_MOUSE_DRAGGED, drag_point, drag_point, - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0); - ui::MouseEvent release(ui::ET_MOUSE_RELEASED, drag_point, drag_point, - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMouseDragged(drag); - textfield_->OnMouseReleased(release); - textfield_->OnDragDone(); + DragMouseTo(drag_point); + ReleaseLeftMouseButton(); EXPECT_EQ(ASCIIToUTF16("hello world"), textfield_->text()); } @@ -2205,16 +2244,12 @@ MouseClick(middle_cursor, 0); const gfx::Point middle(middle_cursor.x(), middle_cursor.y() + middle_cursor.height() / 2); - ui::MouseEvent press_event(ui::ET_MOUSE_PRESSED, middle, middle, - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(press_event); + MoveMouseTo(middle); + PressLeftMouseButton(); EXPECT_EQ(gfx::Range(4, 7), textfield_->GetSelectedRange()); // Drag the mouse to the beginning of the textfield. - ui::MouseEvent drag_event(ui::ET_MOUSE_DRAGGED, beginning, beginning, - ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, 0); - textfield_->OnMouseDragged(drag_event); + DragMouseTo(beginning); EXPECT_EQ(gfx::Range(7, 0), textfield_->GetSelectedRange()); }
diff --git a/ui/views/debug_utils.cc b/ui/views/debug_utils.cc index 12b4759..b451c2d 100644 --- a/ui/views/debug_utils.cc +++ b/ui/views/debug_utils.cc
@@ -7,26 +7,25 @@ #include <ostream> #include "base/logging.h" -#include "base/strings/utf_string_conversions.h" #include "ui/views/view.h" namespace views { namespace { void PrintViewHierarchyImp(const View* view, int indent, - std::wostringstream* out) { + std::ostringstream* out) { int ind = indent; while (ind-- > 0) - *out << L' '; - *out << base::UTF8ToWide(view->GetClassName()); - *out << L' '; + *out << ' '; + *out << view->GetClassName(); + *out << ' '; *out << view->id(); - *out << L' '; - *out << view->x() << L"," << view->y() << L","; - *out << view->bounds().right() << L"," << view->bounds().bottom(); - *out << L' '; + *out << ' '; + *out << view->x() << "," << view->y() << ","; + *out << view->bounds().right() << "," << view->bounds().bottom(); + *out << ' '; *out << view; - *out << L'\n'; + *out << '\n'; for (int i = 0, count = view->child_count(); i < count; ++i) PrintViewHierarchyImp(view->child_at(i), indent + 2, out); @@ -34,18 +33,18 @@ void PrintFocusHierarchyImp(const View* view, int indent, - std::wostringstream* out) { + std::ostringstream* out) { int ind = indent; while (ind-- > 0) - *out << L' '; - *out << base::UTF8ToWide(view->GetClassName()); - *out << L' '; - *out << view->id(); - *out << L' '; + *out << ' '; *out << view->GetClassName(); - *out << L' '; + *out << ' '; + *out << view->id(); + *out << ' '; + *out << view->GetClassName(); + *out << ' '; *out << view; - *out << L'\n'; + *out << '\n'; if (view->child_count() > 0) PrintFocusHierarchyImp(view->child_at(0), indent + 2, out); @@ -57,16 +56,16 @@ } // namespace void PrintViewHierarchy(const View* view) { - std::wostringstream out; - out << L"View hierarchy:\n"; + std::ostringstream out; + out << "View hierarchy:\n"; PrintViewHierarchyImp(view, 0, &out); // Error so users in the field can generate and upload logs. LOG(ERROR) << out.str(); } void PrintFocusHierarchy(const View* view) { - std::wostringstream out; - out << L"Focus hierarchy:\n"; + std::ostringstream out; + out << "Focus hierarchy:\n"; PrintFocusHierarchyImp(view, 0, &out); // Error so users in the field can generate and upload logs. LOG(ERROR) << out.str();
diff --git a/ui/views/examples/examples_window.cc b/ui/views/examples/examples_window.cc index 08526a1..57be047 100644 --- a/ui/views/examples/examples_window.cc +++ b/ui/views/examples/examples_window.cc
@@ -186,7 +186,7 @@ void WindowClosing() override { instance_ = NULL; if (operation_ == QUIT_ON_CLOSE) - base::MessageLoopForUI::current()->QuitWhenIdle(); + base::MessageLoop::current()->QuitWhenIdle(); } gfx::Size GetPreferredSize() const override { return gfx::Size(800, 300); }
diff --git a/ui/views/style/platform_style.cc b/ui/views/style/platform_style.cc index 9027c663..a303d84 100644 --- a/ui/views/style/platform_style.cc +++ b/ui/views/style/platform_style.cc
@@ -37,6 +37,7 @@ const int PlatformStyle::kMinLabelButtonWidth = 70; const int PlatformStyle::kMinLabelButtonHeight = 33; const bool PlatformStyle::kDefaultLabelButtonHasBoldFont = true; +const bool PlatformStyle::kTextfieldDragVerticallyDragsToEnd = false; // static gfx::ImageSkia PlatformStyle::CreateComboboxArrow(bool is_enabled,
diff --git a/ui/views/style/platform_style.h b/ui/views/style/platform_style.h index e6916176..97f697e 100644 --- a/ui/views/style/platform_style.h +++ b/ui/views/style/platform_style.h
@@ -34,6 +34,10 @@ // Whether dialog-default buttons are given a bold font style. static const bool kDefaultLabelButtonHasBoldFont; + // Whether dragging vertically above or below a textfield's bounds selects to + // the left or right end of the text from the cursor, respectively. + static const bool kTextfieldDragVerticallyDragsToEnd; + // Creates an ImageSkia containing the image to use for the combobox arrow. // The |is_enabled| argument is true if the control the arrow is for is // enabled, and false if the control is disabled. The |style| argument is the
diff --git a/ui/views/style/platform_style_mac.mm b/ui/views/style/platform_style_mac.mm index 550d9b2..a789644 100644 --- a/ui/views/style/platform_style_mac.mm +++ b/ui/views/style/platform_style_mac.mm
@@ -21,6 +21,7 @@ const int PlatformStyle::kMinLabelButtonWidth = 32; const int PlatformStyle::kMinLabelButtonHeight = 30; const bool PlatformStyle::kDefaultLabelButtonHasBoldFont = false; +const bool PlatformStyle::kTextfieldDragVerticallyDragsToEnd = true; // static gfx::ImageSkia PlatformStyle::CreateComboboxArrow(bool is_enabled,
diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.cc b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.cc index 7889e47..32092cf 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.cc +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.cc
@@ -1653,7 +1653,6 @@ 1); } - x_map_window_was_called_ = true; XMapWindow(xdisplay_, xwindow_); // We now block until our window is mapped. Some X11 APIs will crash and @@ -1661,17 +1660,6 @@ // asynchronous. if (ui::X11EventSource::GetInstance()) ui::X11EventSource::GetInstance()->BlockUntilWindowMapped(xwindow_); - window_mapped_ = true; - x_map_window_was_called_ = false; - - UpdateMinAndMaxSize(); - - // Some WMs only respect maximize hints after the window has been mapped. - // Check whether we need to re-do a maximization. - if (should_maximize_after_map_) { - Maximize(); - should_maximize_after_map_ = false; - } } void DesktopWindowTreeHostX11::SetWindowTransparency() { @@ -1885,13 +1873,21 @@ break; } case MapNotify: { - CHECK(x_map_window_was_called_) - << "Received MapNotify event despite never calling XMapWindow(). " - << "(This is debugging state for crbug.com/381732.)"; + window_mapped_ = true; FOR_EACH_OBSERVER(DesktopWindowTreeHostObserverX11, observer_list_, OnWindowMapped(xwindow_)); + + UpdateMinAndMaxSize(); + + // Some WMs only respect maximize hints after the window has been mapped. + // Check whether we need to re-do a maximization. + if (should_maximize_after_map_) { + Maximize(); + should_maximize_after_map_ = false; + } + break; } case UnmapNotify: {
diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.h b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.h index c174531..1d3cbd7 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.h +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11.h
@@ -259,10 +259,6 @@ // Is the window mapped to the screen? bool window_mapped_; - // Keeps track of whether we have ever mapped/withdrawn this - // window. Debugging information in trying to track down crbug.com/381732. - bool x_map_window_was_called_ = false; - // The bounds of |xwindow_|. gfx::Rect bounds_in_pixels_;
diff --git a/ui/webui/resources/js/promise_resolver.js b/ui/webui/resources/js/promise_resolver.js index ba84ada0..58236360 100644 --- a/ui/webui/resources/js/promise_resolver.js +++ b/ui/webui/resources/js/promise_resolver.js
@@ -21,7 +21,7 @@ * @template T */ function PromiseResolver() { - /** @private {function(T): void} */ + /** @private {function(T=): void} */ this.resolve_; /** @private {function(*=): void} */ @@ -39,7 +39,7 @@ get promise() { return this.promise_; }, set promise(p) { assertNotReached(); }, - /** @return {function(T): void} */ + /** @return {function(T=): void} */ get resolve() { return this.resolve_; }, set resolve(r) { assertNotReached(); },