diff --git a/DEPS b/DEPS index 25124403..85229df 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': 'f9634b95eccd58acf5b20d98c5d2ee5af353d3d2', + 'skia_revision': 'a821af83890d3b365c7b871f939737d47c48139c', # 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': 'cf55e9aee1a3c17c803ccf33f165973d5b820227', + 'v8_revision': '798d1933a7bbaa1890e0d7beb1e506bfa886e689', # 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. @@ -100,7 +100,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': '263d9a1192b33379be00ab2a93531aa679bae5f1', + 'catapult_revision': '91c0bacc9a93e51e5fb31c0743487c21d6664a45', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -220,7 +220,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' + '@' + '957712a5a83de8f328feba86cc0310cf5606dc9f', # commit position 12356 + Var('chromium_git') + '/external/webrtc/trunk/webrtc.git' + '@' + '590e847a1bcf77039ac2760e0e308bd12b46cf09', # commit position 12359 'src/third_party/openmax_dl': Var('chromium_git') + '/external/webrtc/deps/third_party/openmax.git' + '@' + Var('openmax_dl_revision'),
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 8f25c5d..4769a4e 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
@@ -235,12 +235,15 @@ mAppTargetSdkVersion < Build.VERSION_CODES.JELLY_BEAN; final boolean areLegacyQuirksEnabled = mAppTargetSdkVersion < Build.VERSION_CODES.KITKAT; final boolean allowEmptyDocumentPersistence = mAppTargetSdkVersion <= Build.VERSION_CODES.M; + final boolean allowGeolocationOnInsecureOrigins = + mAppTargetSdkVersion <= Build.VERSION_CODES.M; mContentsClientAdapter = new WebViewContentsClientAdapter(mWebView, mContext, mFactory.getWebViewDelegate()); mWebSettings = new ContentSettingsAdapter( new AwSettings(mContext, isAccessFromFileURLsGrantedByDefault, - areLegacyQuirksEnabled, allowEmptyDocumentPersistence)); + areLegacyQuirksEnabled, allowEmptyDocumentPersistence, + allowGeolocationOnInsecureOrigins)); if (mAppTargetSdkVersion < Build.VERSION_CODES.LOLLIPOP) { // Prior to Lollipop we always allowed third party cookies and mixed content.
diff --git a/android_webview/java/src/org/chromium/android_webview/AwSettings.java b/android_webview/java/src/org/chromium/android_webview/AwSettings.java index a7f1afd..07eaaea 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwSettings.java +++ b/android_webview/java/src/org/chromium/android_webview/AwSettings.java
@@ -97,6 +97,7 @@ private final boolean mSupportLegacyQuirks; private final boolean mAllowEmptyDocumentPersistence; + private final boolean mAllowGeolocationOnInsecureOrigins; private final boolean mPasswordEchoEnabled; @@ -210,7 +211,8 @@ public AwSettings(Context context, boolean isAccessFromFileURLsGrantedByDefault, boolean supportsLegacyQuirks, - boolean allowEmptyDocumentPersistence) { + boolean allowEmptyDocumentPersistence, + boolean allowGeolocationOnInsecureOrigins) { boolean hasInternetPermission = context.checkPermission( android.Manifest.permission.INTERNET, Process.myPid(), @@ -240,6 +242,7 @@ mSupportLegacyQuirks = supportsLegacyQuirks; mAllowEmptyDocumentPersistence = allowEmptyDocumentPersistence; + mAllowGeolocationOnInsecureOrigins = allowGeolocationOnInsecureOrigins; } // Defer initializing the native side until a native WebContents instance is set. } @@ -1255,6 +1258,12 @@ return mAllowEmptyDocumentPersistence; } + @CalledByNative + private boolean getAllowGeolocationOnInsecureOrigins() { + assert Thread.holdsLock(mAwSettingsLock); + return mAllowGeolocationOnInsecureOrigins; + } + /** * See {@link android.webkit.WebSettings#setUseWideViewPort}. */
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/AwSettingsTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/AwSettingsTest.java index fa5c110..fc05a0f9 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/AwSettingsTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/AwSettingsTest.java
@@ -2901,7 +2901,7 @@ @Override public AwSettings createAwSettings(Context context, boolean supportsLegacyQuirks) { return new AwSettings(context, false /* isAccessFromFileURLsGrantedByDefault */, - supportsLegacyQuirks, mAllow); + supportsLegacyQuirks, mAllow, true /* allowGeolocationOnInsecureOrigins */); } }
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/AwTestBase.java b/android_webview/javatests/src/org/chromium/android_webview/test/AwTestBase.java index d432226..f28d180 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/AwTestBase.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/AwTestBase.java
@@ -382,7 +382,8 @@ } public AwSettings createAwSettings(Context context, boolean supportsLegacyQuirks) { return new AwSettings(context, false /* isAccessFromFileURLsGrantedByDefault */, - supportsLegacyQuirks, false /* allowEmptyDocumentPersistence */); + supportsLegacyQuirks, false /* allowEmptyDocumentPersistence */, + true /* allowGeolocationOnInsecureOrigins */); } }
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/GeolocationTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/GeolocationTest.java index 54e07e3..0ed9bdc 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/GeolocationTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/GeolocationTest.java
@@ -4,11 +4,13 @@ package org.chromium.android_webview.test; +import android.content.Context; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; import android.webkit.GeolocationPermissions; import org.chromium.android_webview.AwContents; +import org.chromium.android_webview.AwSettings; import org.chromium.base.annotations.SuppressFBWarnings; import org.chromium.base.test.util.Feature; import org.chromium.content.browser.LocationProviderFactory; @@ -25,6 +27,7 @@ private TestAwContentsClient mContentsClient; private AwContents mAwContents; private MockLocationProvider mMockLocationProvider; + private TestDependencyFactory mOverridenFactory; private static final String RAW_HTML = "<!DOCTYPE html>\n" @@ -92,9 +95,15 @@ @Override public void tearDown() throws Exception { mMockLocationProvider.stopUpdates(); + mOverridenFactory = null; super.tearDown(); } + @Override + protected TestDependencyFactory createTestDependencyFactory() { + return mOverridenFactory == null ? new TestDependencyFactory() : mOverridenFactory; + } + private int getPositionCountFromJS() { int result = -1; try { @@ -115,6 +124,19 @@ }); } + private static class GeolocationOnInsecureOriginsTestDependencyFactory + extends TestDependencyFactory { + private boolean mAllow; + public GeolocationOnInsecureOriginsTestDependencyFactory(boolean allow) { + mAllow = allow; + } + + @Override + public AwSettings createAwSettings(Context context, boolean supportLegacyQuirks) { + return new AwSettings(context, false /* isAccessFromFileURLsGrantedByDefault */, + supportLegacyQuirks, false /* allowEmptyDocumentPersistence */, mAllow); + } + } /** * Ensure that a call to navigator.getCurrentPosition works in WebView. @@ -297,4 +319,41 @@ }); } + @Feature({"AndroidWebView"}) + @SmallTest + public void testDenyOnInsecureOrigins() throws Throwable { + mOverridenFactory = new GeolocationOnInsecureOriginsTestDependencyFactory(false); + initAwContents(new GrantPermisionAwContentClient()); + loadDataWithBaseUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), RAW_HTML, + "text/html", false, "http://google.com/", "about:blank"); + + mAwContents.evaluateJavaScriptForTests("initiate_getCurrentPosition();", null); + + pollInstrumentationThread(new Callable<Boolean>() { + @SuppressFBWarnings("DM_GC") + @Override + public Boolean call() throws Exception { + Runtime.getRuntime().gc(); + return "deny".equals(getTitleOnUiThread(mAwContents)); + } + }); + } + + @Feature({"AndroidWebView"}) + @SmallTest + public void testAllowOnInsecureOriginsByDefault() throws Throwable { + initAwContents(new GrantPermisionAwContentClient()); + loadDataWithBaseUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), RAW_HTML, + "text/html", false, "http://google.com/", "about:blank"); + + mAwContents.evaluateJavaScriptForTests("initiate_getCurrentPosition();", null); + + pollInstrumentationThread(new Callable<Boolean>() { + @Override + public Boolean call() throws Exception { + return getPositionCountFromJS() > 0; + } + }); + } + }
diff --git a/android_webview/native/aw_settings.cc b/android_webview/native/aw_settings.cc index aee8af6..85b61aa 100644 --- a/android_webview/native/aw_settings.cc +++ b/android_webview/native/aw_settings.cc
@@ -440,7 +440,8 @@ // TODO(jww): This should be removed once sufficient warning has been given of // possible API breakage because of disabling insecure use of geolocation. - web_prefs->allow_geolocation_on_insecure_origins = true; + web_prefs->allow_geolocation_on_insecure_origins = + Java_AwSettings_getAllowGeolocationOnInsecureOrigins(env, obj); } static jlong Init(JNIEnv* env,
diff --git a/android_webview/test/shell/src/org/chromium/android_webview/shell/AwShellActivity.java b/android_webview/test/shell/src/org/chromium/android_webview/shell/AwShellActivity.java index e3ddc60..2459198 100644 --- a/android_webview/test/shell/src/org/chromium/android_webview/shell/AwShellActivity.java +++ b/android_webview/test/shell/src/org/chromium/android_webview/shell/AwShellActivity.java
@@ -185,7 +185,8 @@ } final AwSettings awSettings = new AwSettings(this /* context */, false /* isAccessFromFileURLsGrantedByDefault */, false /* supportsLegacyQuirks */, - false /* allowEmptyDocumentPersistence */); + false /* allowEmptyDocumentPersistence */, + true /* allowGeolocationOnInsecureOrigins */); // Required for WebGL conformance tests. awSettings.setMediaPlaybackRequiresUserGesture(false); // Allow zoom and fit contents to screen
diff --git a/base/threading/platform_thread_internal_posix.cc b/base/threading/platform_thread_internal_posix.cc index 9af02044..378a24d 100644 --- a/base/threading/platform_thread_internal_posix.cc +++ b/base/threading/platform_thread_internal_posix.cc
@@ -4,6 +4,7 @@ #include "base/threading/platform_thread_internal_posix.h" +#include "base/containers/adapters.h" #include "base/logging.h" namespace base { @@ -11,8 +12,7 @@ namespace internal { int ThreadPriorityToNiceValue(ThreadPriority priority) { - for (const ThreadPriorityToNiceValuePair& pair : - kThreadPriorityToNiceValueMap) { + for (const auto& pair : kThreadPriorityToNiceValueMap) { if (pair.priority == priority) return pair.nice_value; } @@ -21,13 +21,17 @@ } ThreadPriority NiceValueToThreadPriority(int nice_value) { - for (const ThreadPriorityToNiceValuePair& pair : - kThreadPriorityToNiceValueMap) { - if (pair.nice_value == nice_value) + // Try to find a priority that best describes |nice_value|. If there isn't + // an exact match, this method returns the closest priority whose nice value + // is higher (lower priority) than |nice_value|. + for (const auto& pair : Reversed(kThreadPriorityToNiceValueMap)) { + if (pair.nice_value >= nice_value) return pair.priority; } - NOTREACHED() << "Unknown nice value"; - return ThreadPriority::NORMAL; + + // Reaching here means |nice_value| is more than any of the defined + // priorities. The lowest priority is suitable in this case. + return ThreadPriority::BACKGROUND; } } // namespace internal
diff --git a/base/threading/platform_thread_internal_posix.h b/base/threading/platform_thread_internal_posix.h index 05a8d1e..5f4a21596 100644 --- a/base/threading/platform_thread_internal_posix.h +++ b/base/threading/platform_thread_internal_posix.h
@@ -5,6 +5,7 @@ #ifndef BASE_THREADING_PLATFORM_THREAD_INTERNAL_POSIX_H_ #define BASE_THREADING_PLATFORM_THREAD_INTERNAL_POSIX_H_ +#include "base/base_export.h" #include "base/threading/platform_thread.h" namespace base { @@ -15,7 +16,11 @@ ThreadPriority priority; int nice_value; }; -extern const ThreadPriorityToNiceValuePair kThreadPriorityToNiceValueMap[4]; +// The elements must be listed in the order of increasing priority (lowest +// priority first), that is, in the order of decreasing nice values (highest +// nice value first). +BASE_EXPORT extern +const ThreadPriorityToNiceValuePair kThreadPriorityToNiceValueMap[4]; // Returns the nice value matching |priority| based on the platform-specific // implementation of kThreadPriorityToNiceValueMap. @@ -23,7 +28,7 @@ // Returns the ThreadPrioirty matching |nice_value| based on the platform- // specific implementation of kThreadPriorityToNiceValueMap. -ThreadPriority NiceValueToThreadPriority(int nice_value); +BASE_EXPORT ThreadPriority NiceValueToThreadPriority(int nice_value); // Allows platform specific tweaks to the generic POSIX solution for // SetCurrentThreadPriority. Returns true if the platform-specific
diff --git a/base/threading/platform_thread_unittest.cc b/base/threading/platform_thread_unittest.cc index 6738775..82221e1 100644 --- a/base/threading/platform_thread_unittest.cc +++ b/base/threading/platform_thread_unittest.cc
@@ -14,6 +14,7 @@ #if defined(OS_POSIX) #include <sys/types.h> #include <unistd.h> +#include "base/threading/platform_thread_internal_posix.h" #elif defined(OS_WIN) #include <windows.h> #endif @@ -271,4 +272,64 @@ } } +// Test for a function defined in platform_thread_internal_posix.cc. On OSX and +// iOS, platform_thread_internal_posix.cc is not compiled, so these platforms +// are excluded here, too. +#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS) +TEST(PlatformThreadTest, GetNiceValueToThreadPriority) { + using internal::NiceValueToThreadPriority; + using internal::kThreadPriorityToNiceValueMap; + + EXPECT_EQ(ThreadPriority::BACKGROUND, + kThreadPriorityToNiceValueMap[0].priority); + EXPECT_EQ(ThreadPriority::NORMAL, + kThreadPriorityToNiceValueMap[1].priority); + EXPECT_EQ(ThreadPriority::DISPLAY, + kThreadPriorityToNiceValueMap[2].priority); + EXPECT_EQ(ThreadPriority::REALTIME_AUDIO, + kThreadPriorityToNiceValueMap[3].priority); + + static const int kBackgroundNiceValue = + kThreadPriorityToNiceValueMap[0].nice_value; + static const int kNormalNiceValue = + kThreadPriorityToNiceValueMap[1].nice_value; + static const int kDisplayNiceValue = + kThreadPriorityToNiceValueMap[2].nice_value; + static const int kRealtimeAudioNiceValue = + kThreadPriorityToNiceValueMap[3].nice_value; + + // The tests below assume the nice values specified in the map are within + // the range below (both ends exclusive). + static const int kHighestNiceValue = 19; + static const int kLowestNiceValue = -20; + + EXPECT_GT(kHighestNiceValue, kBackgroundNiceValue); + EXPECT_GT(kBackgroundNiceValue, kNormalNiceValue); + EXPECT_GT(kNormalNiceValue, kDisplayNiceValue); + EXPECT_GT(kDisplayNiceValue, kRealtimeAudioNiceValue); + EXPECT_GT(kRealtimeAudioNiceValue, kLowestNiceValue); + + EXPECT_EQ(ThreadPriority::BACKGROUND, + NiceValueToThreadPriority(kHighestNiceValue)); + EXPECT_EQ(ThreadPriority::BACKGROUND, + NiceValueToThreadPriority(kBackgroundNiceValue + 1)); + EXPECT_EQ(ThreadPriority::BACKGROUND, + NiceValueToThreadPriority(kBackgroundNiceValue)); + EXPECT_EQ(ThreadPriority::BACKGROUND, + NiceValueToThreadPriority(kNormalNiceValue + 1)); + EXPECT_EQ(ThreadPriority::NORMAL, + NiceValueToThreadPriority(kNormalNiceValue)); + EXPECT_EQ(ThreadPriority::NORMAL, + NiceValueToThreadPriority(kDisplayNiceValue + 1)); + EXPECT_EQ(ThreadPriority::DISPLAY, + NiceValueToThreadPriority(kDisplayNiceValue)); + EXPECT_EQ(ThreadPriority::DISPLAY, + NiceValueToThreadPriority(kRealtimeAudioNiceValue + 1)); + EXPECT_EQ(ThreadPriority::REALTIME_AUDIO, + NiceValueToThreadPriority(kRealtimeAudioNiceValue)); + EXPECT_EQ(ThreadPriority::REALTIME_AUDIO, + NiceValueToThreadPriority(kLowestNiceValue)); +} +#endif + } // namespace base
diff --git a/base/trace_event/memory_dump_manager.cc b/base/trace_event/memory_dump_manager.cc index 35b27d9..53532b2 100644 --- a/base/trace_event/memory_dump_manager.cc +++ b/base/trace_event/memory_dump_manager.cc
@@ -407,8 +407,14 @@ // (for discounting trace memory overhead) while holding the |lock_|. TraceLog::GetInstance()->InitializeThreadLocalEventBufferIfSupported(); - // If this was the last hop, create a trace event, add it to the trace and - // finalize process dump (invoke callback). + // |dump_thread_| might be destroyed before getting this point. + // It means that tracing was disabled right before starting this dump. + // Anyway either tracing is stopped or this was the last hop, create a trace + // event, add it to the trace and finalize process dump invoking the callback. + if (!pmd_async_state->dump_thread_task_runner.get()) { + pmd_async_state->dump_successful = false; + pmd_async_state->pending_dump_providers.clear(); + } if (pmd_async_state->pending_dump_providers.empty()) return FinalizeDumpAndAddToTrace(std::move(pmd_async_state)); @@ -418,20 +424,12 @@ pmd_async_state->pending_dump_providers.back().get(); // If the dump provider did not specify a task runner affinity, dump on - // |dump_thread_|. Note that |dump_thread_| might have been destroyed - // meanwhile. + // |dump_thread_| which is already checked above for presence. SequencedTaskRunner* task_runner = mdpinfo->task_runner.get(); if (!task_runner) { DCHECK(mdpinfo->options.dumps_on_single_thread_task_runner); task_runner = pmd_async_state->dump_thread_task_runner.get(); - if (!task_runner) { - // If tracing was disabled before reaching CreateProcessDump() the - // dump_thread_ would have been already torn down. Nack current dump and - // continue. - pmd_async_state->dump_successful = false; - pmd_async_state->pending_dump_providers.pop_back(); - return SetupNextMemoryDump(std::move(pmd_async_state)); - } + DCHECK(task_runner); } if (mdpinfo->options.dumps_on_single_thread_task_runner &&
diff --git a/base/trace_event/memory_dump_manager_unittest.cc b/base/trace_event/memory_dump_manager_unittest.cc index 2461e61..0de5a48a 100644 --- a/base/trace_event/memory_dump_manager_unittest.cc +++ b/base/trace_event/memory_dump_manager_unittest.cc
@@ -117,7 +117,17 @@ MOCK_METHOD2(OnMemoryDump, bool(const MemoryDumpArgs& args, ProcessMemoryDump* pmd)); - MockMemoryDumpProvider() : enable_mock_destructor(false) {} + MockMemoryDumpProvider() : enable_mock_destructor(false) { + ON_CALL(*this, OnMemoryDump(_, _)) + .WillByDefault(Invoke([](const MemoryDumpArgs&, + ProcessMemoryDump* pmd) -> bool { + // |session_state| should not be null under any circumstances when + // invoking a memory dump. The problem might arise in race conditions + // like crbug.com/600570 . + EXPECT_TRUE(pmd->session_state().get() != nullptr); + return true; + })); + } ~MockMemoryDumpProvider() override { if (enable_mock_destructor) Destructor(); @@ -938,8 +948,14 @@ base::WaitableEvent tracing_disabled_event(false, false); InitializeMemoryDumpManager(false /* is_coordinator */); - MockMemoryDumpProvider mdp; - RegisterDumpProvider(&mdp); + std::unique_ptr<Thread> mdp_thread(new Thread("test thread")); + mdp_thread->Start(); + + // Create both same-thread MDP and another MDP with dedicated thread + MockMemoryDumpProvider mdp1; + RegisterDumpProvider(&mdp1); + MockMemoryDumpProvider mdp2; + RegisterDumpProvider(&mdp2, mdp_thread->task_runner(), kDefaultOptions); EnableTracingWithLegacyCategories(MemoryDumpManager::kTraceCategory); EXPECT_CALL(*delegate_, RequestGlobalMemoryDump(_, _)) @@ -949,6 +965,11 @@ delegate_->CreateProcessDump(args, callback); })); + // If tracing is disabled for current session CreateProcessDump() should NOT + // request dumps from providers. Real-world regression: crbug.com/600570 . + EXPECT_CALL(mdp1, OnMemoryDump(_, _)).Times(0); + EXPECT_CALL(mdp2, OnMemoryDump(_, _)).Times(0); + last_callback_success_ = true; RequestGlobalDumpAndWait(MemoryDumpType::EXPLICITLY_TRIGGERED, MemoryDumpLevelOfDetail::DETAILED);
diff --git a/build/isolate.gypi b/build/isolate.gypi index fc82a15c..ea3a91b 100644 --- a/build/isolate.gypi +++ b/build/isolate.gypi
@@ -37,9 +37,6 @@ # for more information. { - 'includes': [ - '../build/util/version.gypi', - ], 'rules': [ { 'rule_name': 'isolate', @@ -67,10 +64,6 @@ '--path-variable', 'DEPTH', '<(DEPTH)', '--path-variable', 'PRODUCT_DIR', '<(PRODUCT_DIR) ', - # Extra variables are replaced on the 'command' entry and on paths in - # the .isolate file but are not considered relative paths. - '--extra-variable', 'version_full=<(version_full)', - # Note: This list must match DefaultConfigVariables() # in build/android/pylib/utils/isolator.py '--config-variable', 'CONFIGURATION_NAME=<(CONFIGURATION_NAME)', @@ -104,6 +97,8 @@ ], 'conditions': [ # Note: When gyp merges lists, it appends them to the old value. + # Extra variables are replaced on the 'command' entry and on paths in + # the .isolate file but are not considered relative paths. ['OS=="mac"', { 'action': [ '--extra-variable', 'mac_product_name=<(mac_product_name)', @@ -119,7 +114,9 @@ ], }], ['OS=="win"', { + 'includes': ['../build/util/version.gypi'], 'action': [ + '--extra-variable', 'version_full=<(version_full)', '--config-variable', 'msvs_version=<(MSVS_VERSION)', ], }, {
diff --git a/cc/proto/property_tree.proto b/cc/proto/property_tree.proto index 2924233..4bb2e08 100644 --- a/cc/proto/property_tree.proto +++ b/cc/proto/property_tree.proto
@@ -84,17 +84,15 @@ } // Proto for struct EffectNodeData. -// NEXT ID: 17 +// NEXT ID: 15 message EffectNodeData { optional float opacity = 1; optional float screen_space_opacity = 2; optional bool has_render_surface = 3; optional bool has_copy_request = 4; optional bool has_background_filters = 5; - optional bool node_or_ancestor_has_background_filters = 13; - optional bool to_screen_opacity_is_animated = 14; - optional bool hidden_by_backface_visibility = 15; - optional bool double_sided = 16; + optional bool hidden_by_backface_visibility = 14; + optional bool double_sided = 13; optional bool is_drawn = 6; optional bool has_animated_opacity = 7; optional bool effect_changed = 11;
diff --git a/cc/trees/draw_property_utils.cc b/cc/trees/draw_property_utils.cc index 27ef7425..f86b301 100644 --- a/cc/trees/draw_property_utils.cc +++ b/cc/trees/draw_property_utils.cc
@@ -378,88 +378,42 @@ } // namespace -static inline bool LayerShouldBeSkipped(Layer* layer, - bool layer_is_drawn, - const TransformTree& transform_tree, - const EffectTree& effect_tree) { +template <typename LayerType> +static inline bool LayerShouldBeSkippedInternal( + LayerType* layer, + bool layer_is_drawn, + const TransformTree& transform_tree, + const EffectTree& effect_tree) { const TransformNode* transform_node = transform_tree.Node(layer->transform_tree_index()); const EffectNode* effect_node = effect_tree.Node(layer->effect_tree_index()); - // If the layer transform is not invertible, it should not be drawn. - if (!transform_node->data.node_and_ancestors_are_animated_or_invertible) - return true; - - // When we need to do a readback/copy of a layer's output, we can not skip - // it or any of its ancestors. - if (effect_node->data.num_copy_requests_in_subtree > 0) + if (effect_node->data.has_render_surface && + effect_node->data.num_copy_requests_in_subtree > 0) return false; - - // If the layer is not drawn, then skip it and its subtree. - if (!effect_node->data.is_drawn) - return true; - - if (!transform_node->data.to_screen_is_potentially_animated && - effect_node->data.hidden_by_backface_visibility) - return true; - - // If layer has a background filter, don't skip the layer, even it the - // opacity is 0. - if (effect_node->data.node_or_ancestor_has_background_filters) - return false; - - // If the opacity is being animated then the opacity on the main thread is - // unreliable (since the impl thread may be using a different opacity), so it - // should not be trusted. - // In particular, it should not cause the subtree to be skipped. - // Similarly, for layers that might animate opacity using an impl-only - // animation, their subtree should also not be skipped. - return !effect_node->data.screen_space_opacity && - !effect_node->data.to_screen_opacity_is_animated; + // If the layer transform is not invertible, it should be skipped. + // TODO(ajuma): Correctly process subtrees with singular transform for the + // case where we may animate to a non-singular transform and wish to + // pre-raster. + return !transform_node->data.node_and_ancestors_are_animated_or_invertible || + effect_node->data.hidden_by_backface_visibility || + !effect_node->data.is_drawn; } bool LayerShouldBeSkipped(LayerImpl* layer, bool layer_is_drawn, const TransformTree& transform_tree, const EffectTree& effect_tree) { - const TransformNode* transform_node = - transform_tree.Node(layer->transform_tree_index()); - const EffectNode* effect_node = effect_tree.Node(layer->effect_tree_index()); - // If the layer transform is not invertible, it should not be drawn. - // TODO(ajuma): Correctly process subtrees with singular transform for the - // case where we may animate to a non-singular transform and wish to - // pre-raster. - if (!transform_node->data.node_and_ancestors_are_animated_or_invertible) - return true; + return LayerShouldBeSkippedInternal(layer, layer_is_drawn, transform_tree, + effect_tree); +} - // When we need to do a readback/copy of a layer's output, we can not skip - // it or any of its ancestors. - if (effect_node->data.num_copy_requests_in_subtree > 0) - return false; - - // If the layer is not drawn, then skip it and its subtree. - if (!effect_node->data.is_drawn) - return true; - - if (effect_node->data.hidden_by_backface_visibility) - return true; - - // If layer is on the pending tree and opacity is being animated then - // this subtree can't be skipped as we need to create, prioritize and - // include tiles for this layer when deciding if tree can be activated. - if (!transform_tree.property_trees()->is_active && - effect_node->data.to_screen_opacity_is_animated) - return false; - - // If layer has a background filter, don't skip the layer, even it the - // opacity is 0. - if (effect_node->data.node_or_ancestor_has_background_filters) - return false; - - // The opacity of a layer always applies to its children (either implicitly - // via a render surface or explicitly if the parent preserves 3D), so the - // entire subtree can be skipped if this layer is fully transparent. - return !effect_node->data.screen_space_opacity; +bool LayerShouldBeSkipped(Layer* layer, + bool layer_is_drawn, + const TransformTree& transform_tree, + const EffectTree& effect_tree) { + return LayerShouldBeSkippedInternal(layer, layer_is_drawn, transform_tree, + effect_tree); } void FindLayersThatNeedUpdates(LayerTreeHost* layer_tree_host,
diff --git a/cc/trees/layer_tree_host_common.cc b/cc/trees/layer_tree_host_common.cc index c16382e..9fec1ab 100644 --- a/cc/trees/layer_tree_host_common.cc +++ b/cc/trees/layer_tree_host_common.cc
@@ -646,8 +646,6 @@ descendants = &(layer->render_surface()->layer_list()); } - size_t descendants_size = descendants->size(); - bool layer_should_be_skipped = !draw_property_utils::LayerNeedsUpdate( layer, layer_is_drawn, property_trees->transform_tree); if (!layer_should_be_skipped) { @@ -731,13 +729,6 @@ if (render_to_separate_surface && !IsRootLayer(layer) && layer->render_surface()->DrawableContentRect().IsEmpty()) { RemoveSurfaceForEarlyExit(layer, render_surface_layer_list); - return; - } - - // If neither this layer nor any of its children were added, early out. - if (descendants_size == descendants->size()) { - DCHECK(!render_to_separate_surface || IsRootLayer(layer)); - return; } }
diff --git a/cc/trees/layer_tree_host_common_unittest.cc b/cc/trees/layer_tree_host_common_unittest.cc index 128de8e..bb3b18d 100644 --- a/cc/trees/layer_tree_host_common_unittest.cc +++ b/cc/trees/layer_tree_host_common_unittest.cc
@@ -1344,6 +1344,7 @@ // When parent is transparent, the layer should not be drawn. parent->OnOpacityAnimated(0.f); render_surface1->OnOpacityAnimated(1.f); + render_surface1->set_visible_layer_rect(gfx::Rect()); { LayerImplList render_surface_layer_list; parent->layer_tree_impl()->IncrementRenderSurfaceListIdForTesting(); @@ -1356,6 +1357,7 @@ node = effect_tree.Node(render_surface1->effect_tree_index()); EXPECT_FALSE(node->data.is_drawn); + EXPECT_EQ(gfx::Rect(), render_surface1->visible_layer_rect()); } TEST_F(LayerTreeHostCommonTest, RenderSurfaceListForFilter) { @@ -5187,7 +5189,7 @@ LayerTreeHostCommon::CalculateDrawProperties(&inputs2); LayerImpl* child_ptr = root_layer->layer_tree_impl()->LayerById(2); - EffectTree tree = + EffectTree& tree = root_layer->layer_tree_impl()->property_trees()->effect_tree; EffectNode* node = tree.Node(child_ptr->effect_tree_index()); EXPECT_FALSE(node->data.is_drawn); @@ -5210,6 +5212,23 @@ node = tree.Node(child_ptr->effect_tree_index()); EXPECT_TRUE(node->data.is_drawn); EXPECT_TRUE(tree.ContributesToDrawnSurface(child_ptr->effect_tree_index())); + + // But if the opacity of the layer remains 0 after activation, it should not + // be drawn. + host_impl.ActivateSyncTree(); + LayerImpl* active_root = host_impl.active_tree()->root_layer(); + LayerImpl* active_child = host_impl.active_tree()->LayerById(child_ptr->id()); + + EffectTree& active_effect_tree = + host_impl.active_tree()->property_trees()->effect_tree; + EXPECT_TRUE(active_effect_tree.needs_update()); + + ExecuteCalculateDrawProperties(active_root); + + node = active_effect_tree.Node(active_child->effect_tree_index()); + EXPECT_FALSE(node->data.is_drawn); + EXPECT_FALSE(active_effect_tree.ContributesToDrawnSurface( + active_child->effect_tree_index())); } using LCDTextTestParam = std::tr1::tuple<bool, bool, bool>; @@ -5681,7 +5700,7 @@ // appear in its list, since it needs to be drawn for the copy request. ASSERT_EQ(1u, copy_parent_layer->render_surface()->layer_list().size()); EXPECT_EQ(copy_layer->id(), - copy_layer->render_surface()->layer_list().at(0)->id()); + copy_parent_layer->render_surface()->layer_list().at(0)->id()); // The copy_layer's render surface should have two contributing layers. ASSERT_EQ(2u, copy_layer->render_surface()->layer_list().size());
diff --git a/cc/trees/layer_tree_impl.h b/cc/trees/layer_tree_impl.h index 63ac715..5e061e5d3 100644 --- a/cc/trees/layer_tree_impl.h +++ b/cc/trees/layer_tree_impl.h
@@ -142,6 +142,11 @@ property_trees_.is_main_thread = false; property_trees_.is_active = IsActiveTree(); property_trees_.transform_tree.set_source_to_parent_updates_allowed(false); + // The value of some effect node properties (like is_drawn) depends on + // whether we are on the active tree or not. So, we need to update the + // effect tree. + if (IsActiveTree()) + property_trees_.effect_tree.set_needs_update(true); } PropertyTrees* property_trees() { return &property_trees_; }
diff --git a/cc/trees/property_tree.cc b/cc/trees/property_tree.cc index 54f4ec47..91dd5c7 100644 --- a/cc/trees/property_tree.cc +++ b/cc/trees/property_tree.cc
@@ -450,8 +450,6 @@ render_surface(nullptr), has_copy_request(false), has_background_filters(false), - node_or_ancestor_has_background_filters(false), - to_screen_opacity_is_animated(false), hidden_by_backface_visibility(false), double_sided(false), is_drawn(true), @@ -470,9 +468,6 @@ has_render_surface == other.has_render_surface && has_copy_request == other.has_copy_request && has_background_filters == other.has_background_filters && - node_or_ancestor_has_background_filters == - other.node_or_ancestor_has_background_filters && - to_screen_opacity_is_animated == other.to_screen_opacity_is_animated && hidden_by_backface_visibility == other.hidden_by_backface_visibility && double_sided == other.double_sided && is_drawn == other.is_drawn && has_animated_opacity == other.has_animated_opacity && @@ -490,9 +485,6 @@ data->set_has_render_surface(has_render_surface); data->set_has_copy_request(has_copy_request); data->set_has_background_filters(has_background_filters); - data->set_node_or_ancestor_has_background_filters( - node_or_ancestor_has_background_filters); - data->set_to_screen_opacity_is_animated(to_screen_opacity_is_animated); data->set_hidden_by_backface_visibility(hidden_by_backface_visibility); data->set_double_sided(double_sided); data->set_is_drawn(is_drawn); @@ -513,9 +505,6 @@ has_render_surface = data.has_render_surface(); has_copy_request = data.has_copy_request(); has_background_filters = data.has_background_filters(); - node_or_ancestor_has_background_filters = - data.node_or_ancestor_has_background_filters(); - to_screen_opacity_is_animated = data.to_screen_opacity_is_animated(); hidden_by_backface_visibility = data.hidden_by_backface_visibility(); double_sided = data.double_sided(); is_drawn = data.is_drawn(); @@ -1244,11 +1233,12 @@ // 1) Nodes that contribute to copy requests, whether hidden or not, must be // drawn. // 2) Nodes that have a background filter. - // 3) Nodes with animating screen space opacity are drawn if their parent is - // drawn irrespective of their opacity. + // 3) Nodes with animating screen space opacity on main thread or pending tree + // are drawn if their parent is drawn irrespective of their opacity. if (node->data.has_copy_request) node->data.is_drawn = true; - else if (node->data.opacity == 0.f && !node->data.has_animated_opacity && + else if (node->data.opacity == 0.f && + (!node->data.has_animated_opacity || property_trees()->is_active) && !node->data.has_background_filters) node->data.is_drawn = false; else if (parent_node) @@ -1328,13 +1318,7 @@ // copy requests. EffectNode* node = Node(id); EffectNode* parent_node = parent(node); - bool contributes_to_drawn_surface = - node->data.is_drawn && - (node->data.opacity != 0.f || node->data.has_animated_opacity || - node->data.has_background_filters); - if (parent_node && !parent_node->data.is_drawn) - contributes_to_drawn_surface = false; - return contributes_to_drawn_surface; + return node->data.is_drawn && (!parent_node || parent_node->data.is_drawn); } void EffectTree::ResetChangeTracking() {
diff --git a/cc/trees/property_tree.h b/cc/trees/property_tree.h index e105072..eff9594 100644 --- a/cc/trees/property_tree.h +++ b/cc/trees/property_tree.h
@@ -267,8 +267,6 @@ RenderSurfaceImpl* render_surface; bool has_copy_request; bool has_background_filters; - bool node_or_ancestor_has_background_filters; - bool to_screen_opacity_is_animated; bool hidden_by_backface_visibility; bool double_sided; bool is_drawn;
diff --git a/cc/trees/property_tree_builder.cc b/cc/trees/property_tree_builder.cc index 5e050a3..a9eff8c 100644 --- a/cc/trees/property_tree_builder.cc +++ b/cc/trees/property_tree_builder.cc
@@ -626,12 +626,6 @@ data_from_ancestor.transform_tree->next_available_id(); } node.data.clip_id = data_from_ancestor.clip_tree_parent; - EffectNode* parent_node = data_for_children->effect_tree->Node(parent_id); - node.data.node_or_ancestor_has_background_filters = - parent_node->data.node_or_ancestor_has_background_filters || - node.data.has_background_filters; - node.data.to_screen_opacity_is_animated = - parent_node->data.to_screen_opacity_is_animated || has_animated_opacity; } else { // Root render surface acts the unbounded and untransformed to draw content // into. Transform node created from root layer (includes device scale @@ -639,9 +633,6 @@ // to root render surface's content, but not root render surface itself. node.data.transform_id = kRootPropertyTreeNodeId; node.data.clip_id = kRootPropertyTreeNodeId; - node.data.node_or_ancestor_has_background_filters = - node.data.has_background_filters; - node.data.to_screen_opacity_is_animated = has_animated_opacity; } data_for_children->effect_tree_parent = data_for_children->effect_tree->Insert(node, parent_id);
diff --git a/chrome/android/java/AndroidManifest.xml b/chrome/android/java/AndroidManifest.xml index 6539c203..c3820ddb 100644 --- a/chrome/android/java/AndroidManifest.xml +++ b/chrome/android/java/AndroidManifest.xml
@@ -307,10 +307,12 @@ android:label="@string/fre_label" android:launchMode="singleTop" android:windowSoftInputMode="stateHidden|adjustPan" + android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|mcc|mnc|screenLayout|smallestScreenSize"> </activity> <activity android:name="org.chromium.chrome.browser.signin.AccountSigninActivity" android:theme="@style/MainTheme" + android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|mcc|mnc|screenLayout|smallestScreenSize"> </activity> <activity android:name="org.chromium.chrome.browser.preferences.Preferences" @@ -359,6 +361,7 @@ </activity> <activity android:name="org.chromium.chrome.browser.bookmarks.BookmarkSigninActivity" android:theme="@style/BookmarkDialogWhite" + android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|mcc|mnc|screenLayout|smallestScreenSize"> </activity>
diff --git a/chrome/android/java/proguard.flags b/chrome/android/java/proguard.flags index 7112ad7..4998d3f4 100644 --- a/chrome/android/java/proguard.flags +++ b/chrome/android/java/proguard.flags
@@ -112,7 +112,7 @@ *; } --keep class android.support.v4.app.NotificationCompat** { +-keep class android.support.v7.app.NotificationCompat** { *; }
diff --git a/chrome/android/java/res/drawable-hdpi/chrome_sync_logo.png b/chrome/android/java/res/drawable-hdpi/chrome_sync_logo.png new file mode 100644 index 0000000..ed53451 --- /dev/null +++ b/chrome/android/java/res/drawable-hdpi/chrome_sync_logo.png Binary files differ
diff --git a/chrome/android/java/res/drawable-mdpi/chrome_sync_logo.png b/chrome/android/java/res/drawable-mdpi/chrome_sync_logo.png new file mode 100644 index 0000000..122de7b --- /dev/null +++ b/chrome/android/java/res/drawable-mdpi/chrome_sync_logo.png Binary files differ
diff --git a/chrome/android/java/res/drawable-xhdpi/chrome_sync_logo.png b/chrome/android/java/res/drawable-xhdpi/chrome_sync_logo.png new file mode 100644 index 0000000..d4af888 --- /dev/null +++ b/chrome/android/java/res/drawable-xhdpi/chrome_sync_logo.png Binary files differ
diff --git a/chrome/android/java/res/drawable-xxhdpi/chrome_sync_logo.png b/chrome/android/java/res/drawable-xxhdpi/chrome_sync_logo.png new file mode 100644 index 0000000..b7e7cbf7 --- /dev/null +++ b/chrome/android/java/res/drawable-xxhdpi/chrome_sync_logo.png Binary files differ
diff --git a/chrome/android/java/res/drawable-xxxhdpi/chrome_sync_logo.png b/chrome/android/java/res/drawable-xxxhdpi/chrome_sync_logo.png new file mode 100644 index 0000000..01760ec --- /dev/null +++ b/chrome/android/java/res/drawable-xxxhdpi/chrome_sync_logo.png Binary files differ
diff --git a/chrome/android/java/res/layout/account_signin_account_view.xml b/chrome/android/java/res/layout/account_signin_account_view.xml new file mode 100644 index 0000000..9729f27 --- /dev/null +++ b/chrome/android/java/res/layout/account_signin_account_view.xml
@@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- 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. +--> +<LinearLayout + xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:gravity="center_vertical" + android:paddingStart="16dp" + android:paddingEnd="16dp" + android:orientation="horizontal"> + + <ImageView + android:id="@+id/account_image" + android:layout_width="40dp" + android:layout_height="40dp" + android:layout_marginEnd="16dp" + android:contentDescription="@null"/> + + <TextView + android:id="@+id/account_name" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:minHeight="56dp" + android:gravity="center_vertical" + android:textColor="@color/default_text_color" + android:textSize="@dimen/fre_normal_text_size"/> + + <ImageView + android:id="@+id/account_selection_mark" + android:layout_width="24dp" + android:layout_height="24dp" + android:layout_marginStart="16dp" + android:src="@drawable/bookmark_check_blue" + android:contentDescription="@null" + android:visibility="gone"/> +</LinearLayout>
diff --git a/chrome/android/java/res/layout/account_signin_choice_description_view.xml b/chrome/android/java/res/layout/account_signin_choice_description_view.xml new file mode 100644 index 0000000..5a10a94 --- /dev/null +++ b/chrome/android/java/res/layout/account_signin_choice_description_view.xml
@@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- 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. --> + +<TextView xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/signin_choice_description" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:padding="16dp" + android:lineSpacingMultiplier="1.4" + android:text="@string/signin_account_choice_description" + android:textColor="@color/default_text_color" + android:textSize="@dimen/fre_normal_text_size"/> \ No newline at end of file
diff --git a/chrome/android/java/res/layout/account_signin_view.xml b/chrome/android/java/res/layout/account_signin_view.xml index 5e31977..b1467f7 100644 --- a/chrome/android/java/res/layout/account_signin_view.xml +++ b/chrome/android/java/res/layout/account_signin_view.xml
@@ -8,99 +8,207 @@ xmlns:android="http://schemas.android.com/apk/res/android" xmlns:chrome="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" - android:layout_height="match_parent"> + android:layout_height="match_parent" + android:background="@color/signin_body_background"> - <ScrollView + <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" - android:layout_marginBottom="72dp" - android:fillViewport="true"> + android:layout_marginBottom="52dp"> + <!-- The view that allows the user to choose the sign in account --> <LinearLayout - android:id="@+id/fre_main_layout" + android:id="@+id/signin_choose_account_view" android:layout_width="match_parent" - android:layout_height="wrap_content" - android:orientation="vertical" - android:gravity="center_horizontal"> + android:layout_height="match_parent" + android:orientation="vertical"> + <!-- The layout_width/layout_height is set to 16/9 dynamically in Java --> <TextView - android:id="@+id/title" - android:text="@string/signin_set_up_chrome" - style="@style/FreTitle"/> - - <!-- The orientation of this view is changed dynamically to give a nicer layout when in - landscape mode on devices with small screens. --> - <LinearLayout - android:id="@+id/fre_image_and_content" + android:id="@+id/signin_title" android:layout_width="match_parent" android:layout_height="wrap_content" - android:orientation="vertical" - android:gravity="center_horizontal" - android:layout_marginTop="@dimen/fre_vertical_spacing"> + android:gravity="bottom" + android:paddingStart="16dp" + android:paddingEnd="16dp" + android:paddingBottom="16dp" + android:background="@color/signin_head_background" + android:textColor="@color/default_text_color" + android:textSize="@dimen/fre_title_text_size" + android:text="@string/sign_in_to_chrome"/> - <org.chromium.chrome.browser.firstrun.ImageCarousel - android:id="@+id/image" - android:layout_width="@dimen/signin_image_carousel_width" - android:layout_height="@dimen/fre_image_height" /> + <View + android:layout_width="match_parent" + android:layout_height="1dp" + android:background="@color/signin_border_line_color" + android:alpha="0.08"/> + <org.chromium.chrome.browser.signin.AccountListView + android:id="@+id/signin_account_list" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:divider="@null" + android:dividerHeight="0dp" + android:scrollbars="none" + android:requiresFadingEdge="vertical" + android:fadingEdgeLength="48dp"/> + </LinearLayout> + + <!-- The view that allows the user to confirm signed in account, sync and service personalization --> + <org.chromium.chrome.browser.signin.AccountSigninConfirmationView + android:id="@+id/signin_confirmation_view" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:scrollbars="none" + android:requiresFadingEdge="vertical" + android:fadingEdgeLength="48dp" + android:visibility="gone"> + + <RelativeLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <!-- The layout_width/layout_height is set to 16/9 dynamically in Java --> <LinearLayout - android:id="@+id/fre_content_wrapper" - android:layout_width="0dp" - android:layout_height="0dp" - android:layout_weight="1" - android:layout_marginTop="@dimen/fre_vertical_spacing" - android:layout_marginEnd="@dimen/fre_content_margin" - android:layout_marginStart="@dimen/fre_content_margin" - android:orientation="vertical" > + android:id="@+id/signin_confirmation_head" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:gravity="bottom" + android:paddingStart="16dp" + android:paddingEnd="16dp" + android:background="@color/signin_head_background" + android:orientation="vertical"> - <Spinner - style="@style/Widget.AppCompat.Spinner.Underlined" - android:id="@+id/google_accounts_spinner" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_marginBottom="@dimen/fre_vertical_spacing" - android:layout_gravity="center_horizontal" - android:popupBackground="#ffffff" - android:paddingStart="0dp" - android:paddingEnd="0dp" - android:textColor="@color/fre_text_color" /> + <ImageView + android:id="@+id/signin_account_image" + android:layout_width="64dp" + android:layout_height="64dp" + android:layout_marginBottom="24dp" + android:scaleType="fitCenter" + android:contentDescription="@null"/> <TextView - android:id="@+id/confirm_account_email" - android:layout_width="wrap_content" + android:id="@+id/signin_account_name" + android:layout_width="match_parent" android:layout_height="wrap_content" - android:layout_gravity="center" + android:layout_marginBottom="8dp" + android:textColor="@color/default_text_color" + android:textSize="@dimen/fre_title_text_size" + android:ellipsize="end" + android:maxLines="1"/> + + <TextView + android:id="@+id/signin_account_email" + android:layout_width="match_parent" + android:layout_height="wrap_content" android:layout_marginBottom="16dp" - android:paddingTop="12dp" - android:paddingBottom="8dp" - android:textColor="@color/fre_text_color" - android:visibility="gone" /> + android:textColor="@color/descriptive_text_color" + android:textSize="@dimen/fre_normal_text_size" + android:ellipsize="end" + android:maxLines="1"/> + </LinearLayout> - <org.chromium.ui.widget.TextViewWithClickableSpans - android:id="@+id/description" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:gravity="center" - android:lineSpacingMultiplier="1.4" - android:text="@string/signin_account_choice_description" - android:textColor="@color/signin_light_text_color" - android:textSize="@dimen/fre_normal_text_size" /> - </LinearLayout> - - </LinearLayout> - </LinearLayout> - </ScrollView> + <View + android:id="@+id/signin_confirmation_head_body_border" + android:layout_width="match_parent" + android:layout_height="1dp" + android:layout_below="@id/signin_confirmation_head" + android:background="@color/signin_border_line_color" + android:alpha="0.08"/> - <!-- layout_height = 72dp = fre_button_bar_height + paddingTop --> + <TextView + android:id="@+id/signin_chrome_sync_title" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="16dp" + android:layout_marginBottom="8dp" + android:layout_below="@id/signin_confirmation_head_body_border" + android:paddingStart="16dp" + android:paddingEnd="16dp" + android:text="@string/sync_confirmation_chrome_sync_title" + android:textColor="@color/default_text_color" + android:textSize="@dimen/fre_normal_text_size" + android:fontFamily="sans-serif-medium" + android:drawableStart="@drawable/chrome_sync_logo" + android:drawablePadding="16dp"/> + + <TextView + android:id="@+id/signin_chrome_sync_description" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginBottom="16dp" + android:layout_below="@id/signin_chrome_sync_title" + android:paddingStart="56dp" + android:paddingEnd="16dp" + android:lineSpacingMultiplier="1.4" + android:text="@string/sync_confirmation_chrome_sync_message" + android:textColor="@color/descriptive_text_color" + android:textSize="@dimen/fre_normal_text_size" /> + + <View + android:id="@+id/signin_confirmation_body_rule_line" + android:layout_width="match_parent" + android:layout_height="1dp" + android:layout_marginStart="56dp" + android:layout_marginEnd="16dp" + android:layout_below="@id/signin_chrome_sync_description" + android:background="@color/signin_border_line_color" + android:alpha="0.08"/> + + <TextView + android:id="@+id/signin_personalize_service_title" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="16dp" + android:layout_marginBottom="8dp" + android:layout_below="@id/signin_confirmation_body_rule_line" + android:paddingStart="16dp" + android:paddingEnd="16dp" + android:text="@string/sync_confirmation_personalize_services_title" + android:textColor="@color/default_text_color" + android:textSize="@dimen/fre_normal_text_size" + android:fontFamily="sans-serif-medium" + android:drawableStart="@drawable/googleg" + android:drawablePadding="16dp"/> + + <TextView + android:id="@+id/signin_personalize_service_description" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginBottom="32dp" + android:layout_below="@id/signin_personalize_service_title" + android:paddingStart="56dp" + android:paddingEnd="16dp" + android:lineSpacingMultiplier="1.4" + android:text="@string/sync_confirmation_personalize_services_body" + android:textColor="@color/descriptive_text_color" + android:textSize="@dimen/fre_normal_text_size"/> + + <org.chromium.ui.widget.TextViewWithClickableSpans + android:id="@+id/signin_settings_control" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_below="@id/signin_personalize_service_description" + android:paddingStart="16dp" + android:paddingEnd="16dp" + android:paddingBottom="36dp" + android:lineSpacingMultiplier="1.4" + android:text="@string/signin_signed_in_settings_description" + android:textColor="@color/descriptive_text_color" + android:textSize="@dimen/fre_normal_text_size" /> + </RelativeLayout> + </org.chromium.chrome.browser.signin.AccountSigninConfirmationView> + </FrameLayout> + <LinearLayout android:id="@+id/button_bar" android:layout_width="match_parent" - android:layout_height="72dp" + android:layout_height="52dp" android:layout_gravity="bottom" - android:orientation="horizontal" - android:paddingTop="16dp" android:paddingStart="16dp" - android:paddingEnd="16dp" > + android:paddingEnd="16dp" + android:orientation="horizontal" > <!--suppress ButtonStyle --> <Button @@ -111,8 +219,7 @@ android:text="@string/fre_skip_text" android:textAllCaps="true" android:textColor="@color/light_active_color" - android:textSize="14sp" - android:layout_marginBottom="24dp" /> + android:textSize="14sp"/> <View android:layout_width="0dp" @@ -129,8 +236,7 @@ android:textAllCaps="true" android:textColor="@android:color/white" android:textSize="14sp" - chrome:buttonColor="@color/light_active_color" - android:layout_marginBottom="24dp" /> + chrome:buttonColor="@color/light_active_color"/> <View android:id="@+id/positive_button_end_padding"
diff --git a/chrome/android/java/res/layout/fre_spinner_dropdown.xml b/chrome/android/java/res/layout/fre_spinner_dropdown.xml deleted file mode 100644 index 8c039c9..0000000 --- a/chrome/android/java/res/layout/fre_spinner_dropdown.xml +++ /dev/null
@@ -1,20 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- 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. ---> - -<TextView xmlns:android="http://schemas.android.com/apk/res/android" - style="?android:attr/spinnerDropDownItemStyle" - android:singleLine="true" - android:ellipsize="end" - android:maxWidth="300dp" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:textColor="@color/fre_text_color" - android:textSize="@dimen/fre_normal_text_size" - android:paddingTop="12dp" - android:paddingBottom="12dp" - android:paddingEnd="14dp" - android:paddingStart="18dp" /> \ No newline at end of file
diff --git a/chrome/android/java/res/layout/fre_spinner_text.xml b/chrome/android/java/res/layout/fre_spinner_text.xml deleted file mode 100644 index 1176fb0..0000000 --- a/chrome/android/java/res/layout/fre_spinner_text.xml +++ /dev/null
@@ -1,21 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- 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. ---> -<TextView xmlns:android="http://schemas.android.com/apk/res/android" - android:id="@+id/fre_spinner_text" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:maxWidth="300dp" - android:layoutDirection="locale" - android:paddingTop="8dp" - android:paddingBottom="8dp" - android:paddingEnd="16dp" - android:paddingStart="4dp" - android:textAlignment="viewStart" - android:ellipsize="end" - android:singleLine="true" - android:textColor="@color/fre_text_color" - android:textSize="@dimen/fre_normal_text_size" />
diff --git a/chrome/android/java/res/values/colors.xml b/chrome/android/java/res/values/colors.xml index 67bf25f0..83a0f15e 100644 --- a/chrome/android/java/res/values/colors.xml +++ b/chrome/android/java/res/values/colors.xml
@@ -82,7 +82,10 @@ <!-- Account Signin Colors --> <!-- As in dimens.xml, signin uses values from the First Run Experience --> - <color name="signin_light_text_color">#494949</color> + <color name="signin_head_background">#fff</color> + <color name="signin_body_background">#fafafa</color> + <color name="signin_border_line_color">#000</color> + <color name="signin_button_disabled_color">#4f4f4f</color> <!-- Sad Tab colors --> <color name="sad_tab_header_text_color">#333333</color> @@ -104,9 +107,6 @@ <color name="snippets_list_header_text_color">#646464</color> <color name="snippets_headline_text_color">#333333</color> - <!-- Signin promo screen colors --> - <color name="illustration_background_color">#4FC3F7</color> - <!-- Contextual Search colors --> <color name="contextual_search_promo_text_color">#333333</color> <color name="contextual_search_promo_background_color">#EEEEEE</color>
diff --git a/chrome/android/java/res/values/dimens.xml b/chrome/android/java/res/values/dimens.xml index 44d0c2f..b00dba8 100644 --- a/chrome/android/java/res/values/dimens.xml +++ b/chrome/android/java/res/values/dimens.xml
@@ -178,11 +178,7 @@ <!-- The Account Signin page appears in the First Run Experience (amongst other places), so uses a lot of the fre_* dimensions for consistency. --> <dimen name="signin_image_carousel_width">240dp</dimen> - <dimen name="signin_checkmark_size">38dp</dimen> - - <!-- Sign-in promo dimensions --> - <dimen name="sign_in_promo_padding_bottom">16dp</dimen> - + <!-- Autofill card unmasking prompt dimensions --> <dimen name="autofill_card_unmask_tooltip_horizontal_padding">16dp</dimen> <dimen name="autofill_card_unmask_tooltip_vertical_padding">4dp</dimen>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java index aa82e01..e9255fb6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java
@@ -32,6 +32,7 @@ public static final String NTP_SNIPPETS = "NTPSnippets"; public static final String NTP_TOOLBAR = "NTPToolbar"; public static final String NTP_FAKE_OMNIBOX_TEXT = "NTPFakeOmniboxText"; + public static final String MEDIA_STYLE_NOTIFICATION = "MediaStyleNotification"; private static native boolean nativeIsEnabled(String featureName); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/AccountFirstRunFragment.java b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/AccountFirstRunFragment.java index e6f60edf..50c8673a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/AccountFirstRunFragment.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/AccountFirstRunFragment.java
@@ -81,7 +81,6 @@ @Override public void onStart() { super.onStart(); - mView.setProfileDataCache(getPageDelegate().getProfileDataCache()); getPageDelegate().onSigninDialogShown(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/ImageCarousel.java b/chrome/android/java/src/org/chromium/chrome/browser/firstrun/ImageCarousel.java deleted file mode 100644 index c4d17b25..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/firstrun/ImageCarousel.java +++ /dev/null
@@ -1,437 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.firstrun; - -import android.animation.Animator; -import android.animation.AnimatorSet; -import android.animation.ObjectAnimator; -import android.content.Context; -import android.graphics.Bitmap; -import android.util.AttributeSet; -import android.util.Property; -import android.view.GestureDetector; -import android.view.Gravity; -import android.view.MotionEvent; -import android.view.View; -import android.view.animation.DecelerateInterpolator; -import android.widget.FrameLayout; -import android.widget.ImageView; - -import org.chromium.chrome.R; - -import java.util.Arrays; - -/** - * Account chooser that displays profile images in a carousel and allows users to rotate it to - * select an account. - * - * Internally it is implemented using four ImageViews that get translated along the X axis based - * on the current carousel position. - * - * |'''''| |'''''| |'''''| |'''''| |'''''| - * |'''| |'''| |'''| |'''| |'''| |'''| |'''| |'''| |'''| |'''| - * |IM3| IM0 |IM1| -> |IM0| IM1 |IM2| -> |IM1| IM2 |IM3| -> |IM2| IM3 |IM0| -> |IM3| IM0 |IM1| - * |,,,| |,,,| |,,,| |,,,| |,,,| |,,,| |,,,| |,,,| |,,,| |,,,| - * |,,,,,| |,,,,,| |,,,,,| |,,,,,| |,,,,,| - * - * mPosition=0 mPosition=1 mPosition=2 mPosition=3 mPosition=4 - * - * IM0 is mViews[0] - * IM1 is mViews[1] - * IM2 is mViews[2] - * IM3 is mViews[3] - * - * Each ImageView is displaying a profile image if there is one, however it is not necessarily true - * that IM0 is showing mImages[0] and IM1 is showing mImages[1], and so on. This changes when there - * are more than 4 accounts and ImageViews get reused for new accounts. - */ -public class ImageCarousel extends FrameLayout implements GestureDetector.OnGestureListener { - - /** - * Constant used together image width to calculate how far should should each image move in - * x axis. This value was tweaked until images did not overlap with each other when scrolling. - */ - private static final float TRANSLATION_FACTOR = 0.64f; - - /** - * Constant used together with carousel width to calculate how should fling velocity in x axis - * be scaled when changing ImageCarousel position. It was tweaked for flings to look natural. - */ - private static final float FLING_FACTOR = 20f * 0.92f / 2f; - - /** - * Constant used together with carousel width to calculate how should scroll distance in x axis - * be scaled when changing ImageCarousel position. It was tweaked for image to follow user's - * finger when scrolling. - */ - private static final float SCROLL_FACTOR = 0.92f / 2f; - - /** - * Listener to ImageCarousel center position changes. - */ - public interface ImageCarouselPositionChangeListener { - /** - * @param position The new center position of the ImageCarousel. It is a number in - * range [0, mImages.length). - */ - void onPositionChanged(int position); - } - - private static final int SCROLL_ANIMATION_DURATION_MS = 200; - private static final int ACCOUNT_SIGNED_IN_ANIMATION_DURATION_MS = 200; - - private static final float MINIMUM_POSITION_TWO_IMAGES = -0.1f; - private static final float MAXIMUM_POSITION_TWO_IMAGES = 1.1f; - - /** - * Number of ImageViews used in ImageCarousel. - */ - private static final int VIEW_COUNT = 4; - - private static final int[] ORDER_OFFSETS = {2, 1, 3, 0}; - - private static final int[] POSITION_OFFSETS = {0, -1, 2, 1}; - - private static final int[] BITMAP_OFFSETS = {2, 1, -1, 0}; - - /** - * Property used to animate scrolling of the ImageCarousel. - */ - private static final Property<ImageCarousel, Float> POSITION_PROPERTY = - new Property<ImageCarousel, Float>(Float.class, "") { - @Override - public Float get(ImageCarousel object) { - return object.mPosition; - } - - @Override - public void set(ImageCarousel object, Float value) { - object.setPosition(value); - } - }; - - /** - * Property used to animate the alpha value of the images that are currently on the left and - * the right of the center image. - */ - private static final Property<ImageCarousel, Float> BACKGROUND_IMAGE_ALPHA = - new Property<ImageCarousel, Float>(Float.class, "") { - @Override - public Float get(ImageCarousel object) { - return object.mViews[object.getChildDrawingOrder(VIEW_COUNT, 1)].getAlpha(); - } - - @Override - public void set(ImageCarousel object, Float value) { - object.mViews[object.getChildDrawingOrder(VIEW_COUNT, 1)].setAlpha(value); - object.mViews[object.getChildDrawingOrder(VIEW_COUNT, 2)].setAlpha(value); - } - }; - - /** - * Gesture detector used to capture scrolls, flings and taps on the image carousel. - */ - private GestureDetector mGestureDetector; - - /** - * Array that holds four ImageViews that are used to display images in the carousel. - */ - private ImageView[] mViews = new ImageView[VIEW_COUNT]; - - /** - * Images that shown in the image carousel. - */ - private Bitmap[] mImages; - - private Animator mScrollAnimator; - private Animator mFadeInOutAnimator; - - private float mPosition = 0f; - - private ImageCarouselPositionChangeListener mListener; - private ImageView mCheckmark; - private int mLastPosition = 0; - private boolean mNeedsPositionUpdates = true; - - private int mCarouselWidth; - private int mImageWidth; - private float mScrollScalingFactor; - private float mFlingScalingFactor; - private float mTranslationFactor; - - private boolean mScrollingDisabled; - private boolean mAccountSelected; - - public ImageCarousel(Context context, AttributeSet attrs) { - super(context, attrs); - mGestureDetector = new GestureDetector(getContext(), this); - } - - /** - * Scrolls ImageCarousel to the closest whole position for the desired position. - * @param position Desired ImageCarousel position. - * @param decelerate Whether animation should be decelerating. - * @param needsPositionUpdates Whether this scroll should trigger position update calls to - * mListener. - */ - public void scrollTo(float position, boolean decelerate, boolean needsPositionUpdates) { - mNeedsPositionUpdates = needsPositionUpdates; - if (mScrollAnimator != null) mScrollAnimator.cancel(); - - position = Math.round(position); - if (mImages != null && mImages.length == 2) { - if (position < 0) position = 0; - if (position > 1) position = 1; - } - mScrollAnimator = ObjectAnimator.ofFloat(this, POSITION_PROPERTY, mPosition, position); - mScrollAnimator.setDuration(SCROLL_ANIMATION_DURATION_MS); - if (decelerate) mScrollAnimator.setInterpolator(new DecelerateInterpolator()); - mScrollAnimator.start(); - } - - /** - * @param listener Listener that should be notified on ImageCarousel center position changes. - */ - public void setListener(ImageCarouselPositionChangeListener listener) { - mListener = listener; - } - - /** - * @param images Images that should be displayed in the ImageCarousel. - */ - public void setImages(Bitmap[] images) { - switch (images.length) { - case 0: - mImages = null; - mScrollingDisabled = true; - break; - case 1: - mScrollingDisabled = true; - mImages = Arrays.copyOf(images, images.length); - break; - default: - // Enable scrolling only if no account has already been selected. - mScrollingDisabled = mAccountSelected; - mImages = Arrays.copyOf(images, images.length); - break; - } - - updateImageViews(); - } - - /** - * Sets whether the ImageCarousel is in signed in mode. This mode disables scrolling, animates - * away the background images, and displays a checkmark next to the chosen account image. - * @param isSignedIn Whether the ImageCarousel should in signed in mode or not. - */ - public void setSignedInMode(boolean isSignedIn) { - if (isSignedIn == mAccountSelected) return; - - mScrollingDisabled = isSignedIn; - mAccountSelected = isSignedIn; - setPosition(getCenterPosition()); - - if (mCheckmark == null) { - mCheckmark = new ImageView(getContext()); - mCheckmark.setImageResource(R.drawable.verify_checkmark); - setLayoutParamsForCheckmark(mCheckmark); - addView(mCheckmark); - } - - if (mFadeInOutAnimator != null) mFadeInOutAnimator.cancel(); - AnimatorSet animatorSet = new AnimatorSet(); - if (isSignedIn) { - animatorSet.playTogether(ObjectAnimator.ofFloat(this, BACKGROUND_IMAGE_ALPHA, 0), - ObjectAnimator.ofFloat(mCheckmark, View.ALPHA, 0.0f, 1.0f)); - } else { - animatorSet.playTogether(ObjectAnimator.ofFloat(this, BACKGROUND_IMAGE_ALPHA, 1), - ObjectAnimator.ofFloat(mCheckmark, View.ALPHA, 1.0f, 0.0f)); - } - mFadeInOutAnimator = animatorSet; - mFadeInOutAnimator.setDuration(ACCOUNT_SIGNED_IN_ANIMATION_DURATION_MS); - mFadeInOutAnimator.start(); - } - - @Override - public void onFinishInflate() { - super.onFinishInflate(); - - mImageWidth = getResources().getDimensionPixelSize(R.dimen.fre_image_height); - for (int i = 0; i < VIEW_COUNT; ++i) { - ImageView view = new ImageView(getContext()); - FrameLayout.LayoutParams params = - new FrameLayout.LayoutParams(mImageWidth, mImageWidth); - params.gravity = Gravity.CENTER; - view.setLayoutParams(params); - mViews[i] = view; - addView(view); - } - - mCarouselWidth = getResources().getDimensionPixelSize(R.dimen.signin_image_carousel_width); - mScrollScalingFactor = SCROLL_FACTOR * mCarouselWidth; - mFlingScalingFactor = FLING_FACTOR * mCarouselWidth; - mTranslationFactor = TRANSLATION_FACTOR * mImageWidth; - - setChildrenDrawingOrderEnabled(true); - setPosition(0f); - } - - /** - * @return The index of the view that should be drawn on the given iteration. - */ - @Override - protected int getChildDrawingOrder(int childCount, int iteration) { - // Draw the views that are not our 4 ImagesViews in their normal order. - if (iteration >= VIEW_COUNT) return iteration; - - // Draw image views in the correct z order based on the current position. - return (Math.round(mPosition) + ORDER_OFFSETS[iteration]) % VIEW_COUNT; - } - - @Override - public boolean onTouchEvent(MotionEvent event) { - if (mScrollingDisabled) return false; - if (mGestureDetector.onTouchEvent(event)) return true; - - if (event.getAction() == MotionEvent.ACTION_UP - || event.getAction() == MotionEvent.ACTION_CANCEL) { - scrollTo(mPosition, false, true); - } - - return false; - } - - // Implementation of GestureDetector.OnGestureListener - - @Override - public boolean onDown(MotionEvent motionEvent) { - return true; - } - - @Override - public void onShowPress(MotionEvent motionEvent) {} - - @Override - public boolean onSingleTapUp(MotionEvent motionEvent) { - mNeedsPositionUpdates = true; - if (motionEvent.getX() < (mCarouselWidth - mImageWidth) / 2f) { - scrollTo(mPosition - 1, false, true); - return true; - } else if (motionEvent.getX() > (mCarouselWidth + mImageWidth) / 2f) { - scrollTo(mPosition + 1, false, true); - return true; - } - return false; - } - - @Override - public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { - // Once the user has started scrolling, prevent the parent view from handling touch events. - // This allows the ImageCarousel to be behave reasonably when nested inside a ScrollView. - getParent().requestDisallowInterceptTouchEvent(true); - - mNeedsPositionUpdates = true; - setPosition(mPosition + distanceX / mScrollScalingFactor); - return true; - } - - @Override - public void onLongPress(MotionEvent motionEvent) {} - - @Override - public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { - mNeedsPositionUpdates = true; - scrollTo(mPosition - velocityX / mFlingScalingFactor, true, true); - return true; - } - - // Internal methods - - /** - * Updates the position, scale, alpha and image shown for all four ImageViews used by - * the ImageCarousel. - */ - private void updateImageViews() { - if (mImages == null) return; - - for (int i = 0; i < VIEW_COUNT; i++) { - if (mAccountSelected && i != getCenterPosition()) continue; - - ImageView image = mViews[i]; - - updateBitmap(i); - - final float position = mPosition + POSITION_OFFSETS[i]; - - // X translation is a sin function with a period of 4 and with range - // [-mTranslationFactor, mTranslationFactor] - image.setTranslationX( - -mTranslationFactor * ((float) Math.sin(position * Math.PI / 2f))); - - // scale is a cos function with a period of 4 and range [1/3, 1] - // scale is 1 when the image is in the front and 1/3 when the image is behind other - // images. - final float scale = (float) Math.cos(position * Math.PI / 2f) / 3f + 2f / 3f; - image.setScaleY(scale); - image.setScaleX(scale); - - // alpha is a cos^2 function with a period of 2 and range [0, 1] - // alpha is 1 when the image is in the center in the front and 0 when it is in the back. - final float alpha = (float) Math.pow(Math.cos(position * Math.PI / 4f), 2); - image.setAlpha(alpha); - } - } - - private void updateBitmap(int i) { - int drawingOrder = getChildDrawingOrder(VIEW_COUNT, i); - // Only draw one top bitmap for one image case. - if (mImages.length == 1 && drawingOrder > 0) return; - // Only draw two top bitmaps for two images case. - if (mImages.length == 2 && drawingOrder > 1) return; - ImageView image = mViews[drawingOrder]; - image.setImageBitmap(mImages[ - (mImages.length + Math.round(mPosition) + BITMAP_OFFSETS[i]) % mImages.length]); - } - - private void setPosition(float position) { - if (mImages != null) { - if (mImages.length == 2) { - position = Math.max(MINIMUM_POSITION_TWO_IMAGES, position); - position = Math.min(MAXIMUM_POSITION_TWO_IMAGES, position); - mPosition = position; - } else { - mPosition = ((position % mImages.length) + mImages.length) % mImages.length; - } - } - - int adjustedPosition = getCenterPosition(); - if (adjustedPosition != mLastPosition) { - mLastPosition = adjustedPosition; - if (mListener != null && mNeedsPositionUpdates) { - mListener.onPositionChanged(adjustedPosition); - } - } - - // Need to call invalidate() for getChildDrawingOrder() to be called since the image - // order has changed. - updateImageViews(); - invalidate(); - } - - private int getCenterPosition() { - if (mImages == null) return 0; - return Math.round(mPosition) % mImages.length; - } - - private void setLayoutParamsForCheckmark(View view) { - int size = getResources().getDimensionPixelSize(R.dimen.signin_checkmark_size); - FrameLayout.LayoutParams params = - new FrameLayout.LayoutParams(size, size); - params.gravity = Gravity.CENTER; - view.setLayoutParams(params); - view.setTranslationX((mImageWidth - size) / 2f); - view.setTranslationY((mImageWidth - size) / 2f); - } -} \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/remote/CastNotificationControl.java b/chrome/android/java/src/org/chromium/chrome/browser/media/remote/CastNotificationControl.java index 35b9fb0..f98442b9 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/remote/CastNotificationControl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/remote/CastNotificationControl.java
@@ -82,7 +82,7 @@ } mPosterBitmap = posterBitmap; if (mNotificationBuilder == null || mMediaRouteController == null) return; - mNotificationBuilder.setImage(mMediaRouteController.getPoster()); + mNotificationBuilder.setLargeIcon(mMediaRouteController.getPoster()); updateNotification(); } @@ -105,7 +105,7 @@ .setPrivate(false) .setIcon(R.drawable.ic_notification_media_route) .setContentIntent(contentIntent) - .setImage(mMediaRouteController.getPoster()) + .setLargeIcon(mMediaRouteController.getPoster()) .setId(R.id.remote_notification) .setListener(this); mState = initialState; @@ -136,7 +136,7 @@ // poster changes. public void onPosterBitmapChanged() { if (mNotificationBuilder == null || mMediaRouteController == null) return; - mNotificationBuilder.setImage(mMediaRouteController.getPoster()); + mNotificationBuilder.setLargeIcon(mMediaRouteController.getPoster()); updateNotification(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/ui/MediaNotificationInfo.java b/chrome/android/java/src/org/chromium/chrome/browser/media/ui/MediaNotificationInfo.java index 750cd59..32cc7bd 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/ui/MediaNotificationInfo.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/ui/MediaNotificationInfo.java
@@ -49,10 +49,10 @@ private int mTabId = Tab.INVALID_TAB_ID; private boolean mIsPrivate = true; private int mIcon = -1; + private Bitmap mLargeIcon = null; private int mActions = ACTION_PLAY_PAUSE | ACTION_SWIPEAWAY; private int mId = INVALID_ID; private Intent mContentIntent = null; - private Bitmap mImage = null; private MediaNotificationListener mListener = null; /** @@ -73,9 +73,9 @@ mTabId, mIsPrivate, mIcon, + mLargeIcon, mActions, mId, - mImage, mContentIntent, mListener); } @@ -110,6 +110,11 @@ return this; } + public Builder setLargeIcon(Bitmap icon) { + mLargeIcon = icon; + return this; + } + public Builder setActions(int actions) { mActions = actions; return this; @@ -120,11 +125,6 @@ return this; } - public Builder setImage(Bitmap image) { - mImage = image; - return this; - } - public Builder setContentIntent(Intent intent) { mContentIntent = intent; return this; @@ -172,16 +172,16 @@ public final int icon; /** + * The Bitmap resource used for a large icon. + */ + public final Bitmap largeIcon; + + /** * The id to use for the notification itself. */ public final int id; /** - * The bitmap of the image, if any. - */ - public final Bitmap image; - - /** * The intent to send when the notification is selected. */ public final Intent contentIntent; @@ -219,7 +219,6 @@ * @param origin The origin of the tab containing the media. * @param tabId The id of the tab containing the media. * @param isPrivate Whether the media notification should be considered as private. - * @param image An image associated with the media, displayed in icons etc.. * @param contentIntent the intent to send when the notification is selected. * @param listener The listener for the control events. */ @@ -230,9 +229,9 @@ int tabId, boolean isPrivate, int icon, + Bitmap largeIcon, int actions, int id, - Bitmap image, Intent contentIntent, MediaNotificationListener listener) { this.metadata = metadata; @@ -241,10 +240,10 @@ this.tabId = tabId; this.isPrivate = isPrivate; this.icon = icon; + this.largeIcon = largeIcon; this.mActions = actions; this.id = id; this.contentIntent = contentIntent; - this.image = image; this.listener = listener; } @@ -258,12 +257,13 @@ && isPrivate == other.isPrivate && tabId == other.tabId && icon == other.icon + && (largeIcon == other.largeIcon + || (largeIcon != null && largeIcon.sameAs(other.largeIcon))) && mActions == other.mActions && id == other.id && (metadata == other.metadata || (metadata != null && metadata.equals(other.metadata))) && TextUtils.equals(origin, other.origin) - && (image == other.image || (image != null && image.sameAs(other.image))) && (contentIntent == other.contentIntent || (contentIntent != null && contentIntent.equals(other.contentIntent))) && (listener == other.listener @@ -276,10 +276,10 @@ result = 31 * result + (isPrivate ? 1 : 0); result = 31 * result + (metadata == null ? 0 : metadata.hashCode()); result = 31 * result + (origin == null ? 0 : origin.hashCode()); - result = 31 * result + (image == null ? 0 : image.hashCode()); result = 31 * result + (contentIntent == null ? 0 : contentIntent.hashCode()); result = 31 * result + tabId; result = 31 * result + icon; + result = 31 * result + (largeIcon == null ? 0 : largeIcon.hashCode()); result = 31 * result + mActions; result = 31 * result + id; result = 31 * result + listener.hashCode();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/ui/MediaNotificationManager.java b/chrome/android/java/src/org/chromium/chrome/browser/media/ui/MediaNotificationManager.java index b36cc9f..643cc79 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/ui/MediaNotificationManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/ui/MediaNotificationManager.java
@@ -18,11 +18,11 @@ import android.media.AudioManager; import android.os.Build; import android.os.IBinder; -import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaSessionCompat; import android.support.v4.media.session.PlaybackStateCompat; +import android.support.v7.app.NotificationCompat; import android.support.v7.media.MediaRouter; import android.text.TextUtils; import android.util.SparseArray; @@ -33,6 +33,7 @@ import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.VisibleForTesting; import org.chromium.chrome.R; +import org.chromium.chrome.browser.ChromeFeatureList; import javax.annotation.Nullable; @@ -43,9 +44,13 @@ * There's one service started for a distinct notification id. */ public class MediaNotificationManager { - private static final String TAG = "MediaNotification"; + // The background notification size on Android Wear. See: + // http://developer.android.com/training/wearables/notifications/creating.html + private static final int WEARABLE_NOTIFICATION_BACKGROUND_WIDTH = 400; + private static final int WEARABLE_NOTIFICATION_BACKGROUND_HEIGHT = 400; + // We're always used on the UI thread but the LOCK is required by lint when creating the // singleton. private static final Object LOCK = new Object(); @@ -482,61 +487,13 @@ clearNotification(); } - private RemoteViews createContentView() { - RemoteViews contentView = - new RemoteViews(mContext.getPackageName(), R.layout.playback_notification_bar); - - // By default, play/pause button is the only one. - int playPauseButtonId = R.id.button1; - // On Android pre-L, dismissing the notification when the service is no longer in foreground - // doesn't work. Instead, a STOP button is shown. - if (mMediaNotificationInfo.supportsSwipeAway() - && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP - || mMediaNotificationInfo.supportsStop()) { - contentView.setOnClickPendingIntent(R.id.button1, - createPendingIntent(ListenerService.ACTION_STOP)); - contentView.setContentDescription(R.id.button1, mStopDescription); - - // If the play/pause needs to be shown, it moves over to the second button from the end. - playPauseButtonId = R.id.button2; - } - - contentView.setTextViewText(R.id.title, mMediaNotificationInfo.metadata.getTitle()); - contentView.setTextViewText(R.id.status, mMediaNotificationInfo.origin); - if (mNotificationIcon != null) { - contentView.setImageViewBitmap(R.id.icon, mNotificationIcon); - } else { - contentView.setImageViewResource(R.id.icon, mMediaNotificationInfo.icon); - } - - if (mMediaNotificationInfo.supportsPlayPause()) { - if (mMediaNotificationInfo.isPaused) { - contentView.setImageViewResource(playPauseButtonId, R.drawable.ic_vidcontrol_play); - contentView.setContentDescription(playPauseButtonId, mPlayDescription); - contentView.setOnClickPendingIntent(playPauseButtonId, - createPendingIntent(ListenerService.ACTION_PLAY)); - } else { - // If we're here, the notification supports play/pause button and is playing. - contentView.setImageViewResource(playPauseButtonId, R.drawable.ic_vidcontrol_pause); - contentView.setContentDescription(playPauseButtonId, mPauseDescription); - contentView.setOnClickPendingIntent(playPauseButtonId, - createPendingIntent(ListenerService.ACTION_PAUSE)); - } - - contentView.setViewVisibility(playPauseButtonId, View.VISIBLE); - } else { - contentView.setViewVisibility(playPauseButtonId, View.GONE); - } - - return contentView; - } - private MediaMetadataCompat createMetadata() { MediaMetadataCompat.Builder metadataBuilder = new MediaMetadataCompat.Builder(); // Choose the image to use as the icon. - Bitmap mediaSessionImage = mMediaNotificationInfo.image == null ? mDefaultMediaSessionImage - : mMediaNotificationInfo.image; + Bitmap mediaSessionImage = mMediaNotificationInfo.largeIcon == null + ? mDefaultMediaSessionImage + : mMediaNotificationInfo.largeIcon; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { metadataBuilder.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, @@ -544,12 +501,12 @@ metadataBuilder.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE, mMediaNotificationInfo.origin); metadataBuilder.putBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON, - mediaSessionImage); + scaleBitmapForWearable(mediaSessionImage)); // METADATA_KEY_ART is optional and should only be used if we can provide something // better than the default image. - if (mMediaNotificationInfo.image != null) { - metadataBuilder.putBitmap(MediaMetadataCompat.METADATA_KEY_ART, - mMediaNotificationInfo.image); + if (mMediaNotificationInfo.largeIcon != null) { + metadataBuilder.putBitmap( + MediaMetadataCompat.METADATA_KEY_ART, mMediaNotificationInfo.largeIcon); } } else { metadataBuilder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, @@ -576,21 +533,17 @@ if (mMediaNotificationInfo == null) return; - // Android doesn't badge the icons for RemoteViews automatically when - // running the app under the Work profile. - if (mNotificationIcon == null) { - Drawable notificationIconDrawable = ApiCompatibilityUtils.getUserBadgedIcon( - mContext, mMediaNotificationInfo.icon); - mNotificationIcon = drawableToBitmap(notificationIconDrawable); - } + updateMediaSession(); - if (mNotificationBuilder == null) { - mNotificationBuilder = new NotificationCompat.Builder(mContext) - .setSmallIcon(mMediaNotificationInfo.icon) - .setAutoCancel(false) - .setLocalOnly(true) - .setDeleteIntent(createPendingIntent(ListenerService.ACTION_STOP)); + mNotificationBuilder = new NotificationCompat.Builder(mContext); + if (ChromeFeatureList.isEnabled(ChromeFeatureList.MEDIA_STYLE_NOTIFICATION)) { + setMediaStyleLayoutForNotificationBuilder(mNotificationBuilder); + } else { + setCustomLayoutForNotificationBuilder(mNotificationBuilder); } + mNotificationBuilder.setSmallIcon(mMediaNotificationInfo.icon); + mNotificationBuilder.setAutoCancel(false); + mNotificationBuilder.setLocalOnly(true); if (mMediaNotificationInfo.supportsSwipeAway()) { mNotificationBuilder.setOngoing(!mMediaNotificationInfo.isPaused); @@ -604,39 +557,10 @@ mMediaNotificationInfo.contentIntent, 0)); } - mNotificationBuilder.setContent(createContentView()); mNotificationBuilder.setVisibility( mMediaNotificationInfo.isPrivate ? NotificationCompat.VISIBILITY_PRIVATE : NotificationCompat.VISIBILITY_PUBLIC); - - if (mMediaNotificationInfo.supportsPlayPause()) { - - if (mMediaSession == null) mMediaSession = createMediaSession(); - try { - // Tell the MediaRouter about the session, so that Chrome can control the volume - // on the remote cast device (if any). - // Pre-MR1 versions of JB do not have the complete MediaRouter APIs, - // so getting the MediaRouter instance will throw an exception. - MediaRouter.getInstance(mContext).setMediaSessionCompat(mMediaSession); - } catch (NoSuchMethodError e) { - // Do nothing. Chrome can't be casting without a MediaRouter, so there is nothing - // to do here. - } - mMediaSession.setMetadata(createMetadata()); - - PlaybackStateCompat.Builder playbackStateBuilder = new PlaybackStateCompat.Builder() - .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE); - if (mMediaNotificationInfo.isPaused) { - playbackStateBuilder.setState(PlaybackStateCompat.STATE_PAUSED, - PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1.0f); - } else { - playbackStateBuilder.setState(PlaybackStateCompat.STATE_PLAYING, - PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1.0f); - } - mMediaSession.setPlaybackState(playbackStateBuilder.build()); - } - Notification notification = mNotificationBuilder.build(); // We keep the service as a foreground service while the media is playing. When it is not, @@ -653,6 +577,38 @@ } } + private void updateMediaSession() { + if (!mMediaNotificationInfo.supportsPlayPause()) return; + + if (mMediaSession == null) mMediaSession = createMediaSession(); + + try { + // Tell the MediaRouter about the session, so that Chrome can control the volume + // on the remote cast device (if any). + // Pre-MR1 versions of JB do not have the complete MediaRouter APIs, + // so getting the MediaRouter instance will throw an exception. + MediaRouter.getInstance(mContext).setMediaSessionCompat(mMediaSession); + } catch (NoSuchMethodError e) { + // Do nothing. Chrome can't be casting without a MediaRouter, so there is nothing + // to do here. + } + + mMediaSession.setMetadata(createMetadata()); + + PlaybackStateCompat.Builder playbackStateBuilder = + new PlaybackStateCompat.Builder().setActions( + PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE); + if (mMediaNotificationInfo.isPaused) { + playbackStateBuilder.setState(PlaybackStateCompat.STATE_PAUSED, + PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1.0f); + } else { + // If notification only supports stop, still pretend + playbackStateBuilder.setState(PlaybackStateCompat.STATE_PLAYING, + PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1.0f); + } + mMediaSession.setPlaybackState(playbackStateBuilder.build()); + } + private MediaSessionCompat createMediaSession() { MediaSessionCompat mediaSession = new MediaSessionCompat( mContext, @@ -680,6 +636,124 @@ return mediaSession; } + private void setMediaStyleLayoutForNotificationBuilder(NotificationCompat.Builder builder) { + // TODO(zqzhang): After we ship the new style, we should see how to present the + // metadata.artist and metadata.album. See http://crbug.com/599937 + builder.setContentTitle(mMediaNotificationInfo.metadata.getTitle()); + builder.setContentText(mMediaNotificationInfo.origin); + // TODO(zqzhang): Update the default icon when a new one in provided. + // See http://crbug.com/600396. + if (mMediaNotificationInfo.largeIcon != null) { + builder.setLargeIcon(mMediaNotificationInfo.largeIcon); + } else { + builder.setLargeIcon(mDefaultMediaSessionImage); + } + // TODO(zqzhang): It's weird that setShowWhen() don't work on K. Calling setWhen() to force + // removing the time. + builder.setShowWhen(false).setWhen(0); + + // Only apply MediaStyle when NotificationInfo supports play/pause. + if (mMediaNotificationInfo.supportsPlayPause()) { + NotificationCompat.MediaStyle style = new NotificationCompat.MediaStyle(); + style.setMediaSession(mMediaSession.getSessionToken()); + + if (mMediaNotificationInfo.isPaused) { + builder.addAction(R.drawable.ic_vidcontrol_play, mPlayDescription, + createPendingIntent(ListenerService.ACTION_PLAY)); + } else { + // If we're here, the notification supports play/pause button and is playing. + builder.addAction(R.drawable.ic_vidcontrol_pause, mPauseDescription, + createPendingIntent(ListenerService.ACTION_PAUSE)); + } + style.setShowActionsInCompactView(0); + style.setCancelButtonIntent(createPendingIntent(ListenerService.ACTION_STOP)); + style.setShowCancelButton(true); + builder.setStyle(style); + } + + if (mMediaNotificationInfo.supportsStop()) { + builder.addAction(R.drawable.ic_vidcontrol_stop, mStopDescription, + createPendingIntent(ListenerService.ACTION_STOP)); + } + } + + private void setCustomLayoutForNotificationBuilder(NotificationCompat.Builder builder) { + builder.setContent(createContentView()); + } + + private RemoteViews createContentView() { + RemoteViews contentView = + new RemoteViews(mContext.getPackageName(), R.layout.playback_notification_bar); + + // By default, play/pause button is the only one. + int playPauseButtonId = R.id.button1; + // On Android pre-L, dismissing the notification when the service is no longer in foreground + // doesn't work. Instead, a STOP button is shown. + if (mMediaNotificationInfo.supportsSwipeAway() + && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP + || mMediaNotificationInfo.supportsStop()) { + contentView.setOnClickPendingIntent( + R.id.button1, createPendingIntent(ListenerService.ACTION_STOP)); + contentView.setContentDescription(R.id.button1, mStopDescription); + + // If the play/pause needs to be shown, it moves over to the second button from the end. + playPauseButtonId = R.id.button2; + } + + contentView.setTextViewText(R.id.title, mMediaNotificationInfo.metadata.getTitle()); + contentView.setTextViewText(R.id.status, mMediaNotificationInfo.origin); + + // Android doesn't badge the icons for RemoteViews automatically when + // running the app under the Work profile. + if (mNotificationIcon == null) { + Drawable notificationIconDrawable = + ApiCompatibilityUtils.getUserBadgedIcon(mContext, mMediaNotificationInfo.icon); + mNotificationIcon = drawableToBitmap(notificationIconDrawable); + } + + if (mNotificationIcon != null) { + contentView.setImageViewBitmap(R.id.icon, mNotificationIcon); + } else { + contentView.setImageViewResource(R.id.icon, mMediaNotificationInfo.icon); + } + + if (mMediaNotificationInfo.supportsPlayPause()) { + if (mMediaNotificationInfo.isPaused) { + contentView.setImageViewResource(playPauseButtonId, R.drawable.ic_vidcontrol_play); + contentView.setContentDescription(playPauseButtonId, mPlayDescription); + contentView.setOnClickPendingIntent( + playPauseButtonId, createPendingIntent(ListenerService.ACTION_PLAY)); + } else { + // If we're here, the notification supports play/pause button and is playing. + contentView.setImageViewResource(playPauseButtonId, R.drawable.ic_vidcontrol_pause); + contentView.setContentDescription(playPauseButtonId, mPauseDescription); + contentView.setOnClickPendingIntent( + playPauseButtonId, createPendingIntent(ListenerService.ACTION_PAUSE)); + } + + contentView.setViewVisibility(playPauseButtonId, View.VISIBLE); + } else { + contentView.setViewVisibility(playPauseButtonId, View.GONE); + } + + return contentView; + } + + /** + * Scales the Bitmap to make the notification background on Wearable devices look better. + * The returned Bitmap size will be exactly 400x400. + * According to http://developer.android.com/training/wearables/notifications/creating.html, + * the background image of Android Wear notifications should be of size 400x400 or 640x400. + * Otherwise, it will be scaled to fit the desired size. However for some reason (maybe battery + * concern), the smoothing filter is not applied when scaling the image, so we need to manually + * scale the image with filter applied before sending to Android Wear. + */ + private Bitmap scaleBitmapForWearable(Bitmap original) { + Bitmap result = Bitmap.createScaledBitmap(original, WEARABLE_NOTIFICATION_BACKGROUND_WIDTH, + WEARABLE_NOTIFICATION_BACKGROUND_HEIGHT, true); + return result; + } + private Bitmap drawableToBitmap(Drawable drawable) { if (!(drawable instanceof BitmapDrawable)) return null;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/ui/MediaSessionTabHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/media/ui/MediaSessionTabHelper.java index 56e26b285..04d3061d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/ui/MediaSessionTabHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/ui/MediaSessionTabHelper.java
@@ -5,12 +5,15 @@ package org.chromium.chrome.browser.media.ui; import android.app.Activity; +import android.graphics.Bitmap; import android.media.AudioManager; +import android.os.Build; import android.text.TextUtils; import org.chromium.base.ApplicationStatus; import org.chromium.base.Log; import org.chromium.chrome.R; +import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.metrics.MediaSessionUMA; import org.chromium.chrome.browser.tab.EmptyTabObserver; import org.chromium.chrome.browser.tab.Tab; @@ -34,6 +37,8 @@ private static final String UNICODE_PLAY_CHARACTER = "\u25B6"; private Tab mTab; + private Bitmap mFavicon = null; + private String mOrigin = null; private WebContents mWebContents; private WebContentsObserver mWebContentsObserver; private int mPreviousVolumeControlStream = AudioManager.USE_DEFAULT_STREAM_TYPE; @@ -93,13 +98,6 @@ hideNotification(); return; } - String origin = mTab.getUrl(); - try { - origin = UrlUtilities.formatUrlForSecurityDisplay(new URI(origin), true); - } catch (URISyntaxException e) { - Log.e(TAG, "Unable to parse the origin from the URL. " - + "Showing the full URL instead."); - } mFallbackMetadata = null; @@ -113,18 +111,20 @@ metadata = mFallbackMetadata; } - mNotificationInfoBuilder = new MediaNotificationInfo.Builder() - .setMetadata(metadata) - .setPaused(isPaused) - .setOrigin(origin) - .setTabId(mTab.getId()) - .setPrivate(mTab.isIncognito()) - .setIcon(R.drawable.audio_playing) - .setActions(MediaNotificationInfo.ACTION_PLAY_PAUSE - | MediaNotificationInfo.ACTION_SWIPEAWAY) - .setContentIntent(Tab.createBringTabToFrontIntent(mTab.getId())) - .setId(R.id.media_playback_notification) - .setListener(mControlsListener); + mNotificationInfoBuilder = + new MediaNotificationInfo.Builder() + .setMetadata(metadata) + .setPaused(isPaused) + .setOrigin(mOrigin) + .setTabId(mTab.getId()) + .setPrivate(mTab.isIncognito()) + .setIcon(R.drawable.audio_playing) + .setLargeIcon(mFavicon) + .setActions(MediaNotificationInfo.ACTION_PLAY_PAUSE + | MediaNotificationInfo.ACTION_SWIPEAWAY) + .setContentIntent(Tab.createBringTabToFrontIntent(mTab.getId())) + .setId(R.id.media_playback_notification) + .setListener(mControlsListener); MediaNotificationManager.show(ApplicationStatus.getApplicationContext(), mNotificationInfoBuilder.build()); @@ -159,6 +159,46 @@ } @Override + public void onFaviconUpdated(Tab tab, Bitmap icon) { + assert tab == mTab; + // Don't update the large icon if using customized notification. Otherwise, the + // lockscreen art will be the favicon. + if (!ChromeFeatureList.isEnabled(ChromeFeatureList.MEDIA_STYLE_NOTIFICATION)) return; + + if (!updateFavicon(icon)) return; + + if (mNotificationInfoBuilder == null) return; + + mNotificationInfoBuilder.setLargeIcon(mFavicon); + MediaNotificationManager.show( + ApplicationStatus.getApplicationContext(), mNotificationInfoBuilder.build()); + } + + @Override + public void onUrlUpdated(Tab tab) { + assert tab == mTab; + + String origin = mTab.getUrl(); + try { + origin = UrlUtilities.formatUrlForSecurityDisplay(new URI(origin), true); + } catch (URISyntaxException e) { + Log.e(TAG, "Unable to parse the origin from the URL. " + + "Using the full URL instead."); + } + + if (mOrigin != null && mOrigin.equals(origin)) return; + mOrigin = origin; + mFavicon = null; + + if (mNotificationInfoBuilder == null) return; + + mNotificationInfoBuilder.setOrigin(mOrigin); + mNotificationInfoBuilder.setLargeIcon(mFavicon); + MediaNotificationManager.show( + ApplicationStatus.getApplicationContext(), mNotificationInfoBuilder.build()); + } + + @Override public void onTitleUpdated(Tab tab) { assert tab == mTab; if (mNotificationInfoBuilder == null || mFallbackMetadata == null) return; @@ -240,4 +280,31 @@ return windowAndroid.getActivity().get(); } + + /** + * Updates the best favicon if the given icon is better. + * @return whether the best favicon is updated. + */ + private boolean updateFavicon(Bitmap icon) { + if (icon == null) return false; + + int largeIconSizeInDp = 0; + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) { + largeIconSizeInDp = 128; + } else { + // TODO(zqzhang): Get this value via Resource.getDimension() if N has a resource id. + largeIconSizeInDp = 96; + } + int minimalIconSizeInPx = Math.round(largeIconSizeInDp * 0.75f); + + if (icon.getWidth() < minimalIconSizeInPx || icon.getHeight() < minimalIconSizeInPx) { + return false; + } + if (mFavicon != null && (icon.getWidth() < mFavicon.getWidth() + || icon.getHeight() < mFavicon.getHeight())) { + return false; + } + mFavicon = icon; + return true; + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountListAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountListAdapter.java new file mode 100644 index 0000000..bf8e5893 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountListAdapter.java
@@ -0,0 +1,73 @@ +// 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.chrome.browser.signin; + +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ArrayAdapter; +import android.widget.ImageView; +import android.widget.TextView; + +import org.chromium.chrome.R; +import org.chromium.chrome.browser.firstrun.ProfileDataCache; + +/** +* Adapter for AccountListView. It associates an array of account names on the device and +* provides account views of these accounts. +*/ +public class AccountListAdapter extends ArrayAdapter<String> { + private final LayoutInflater mInflater; + private final ProfileDataCache mProfileData; + private int mSelectedAccountPosition = 0; + + public AccountListAdapter(Context context, ProfileDataCache profileData) { + super(context, 0); + mInflater = LayoutInflater.from(context); + mProfileData = profileData; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + View view = convertView; + if (view == null) { + view = mInflater.inflate(R.layout.account_signin_account_view, parent, false); + } + + // Sets account profile image, name and selection status. + String accountName = getItem(position); + ImageView accountImage = (ImageView) view.findViewById(R.id.account_image); + // The view at the last position is the "Add account" view. + if (position == getCount() - 1) { + accountImage.setImageResource(R.drawable.add_circle_blue); + } else { + accountImage.setImageBitmap(mProfileData.getImage(accountName)); + } + ((TextView) view.findViewById(R.id.account_name)).setText(accountName); + if (position == mSelectedAccountPosition) { + view.findViewById(R.id.account_selection_mark).setVisibility(View.VISIBLE); + } else { + view.findViewById(R.id.account_selection_mark).setVisibility(View.GONE); + } + + return view; + } + + /** + * Sets selected account position. + * @param position Position in the collection of the associated items. + */ + public void setSelectedAccountPosition(int position) { + mSelectedAccountPosition = position; + } + + /** + * Gets selected account position. + */ + public int getSelectedAccountPosition() { + return mSelectedAccountPosition; + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountListView.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountListView.java new file mode 100644 index 0000000..1740da5c --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountListView.java
@@ -0,0 +1,24 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.signin; + +import android.content.Context; +import android.util.AttributeSet; +import android.widget.ListView; + +/** +* ListView to list accounts on device. +*/ +public class AccountListView extends ListView { + public AccountListView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + @Override + protected float getTopFadingEdgeStrength() { + // Disable fading out effect at the top of this ListView. + return 0; + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninActivity.java index 1350d02..d753142 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninActivity.java
@@ -57,7 +57,6 @@ mView = (AccountSigninView) LayoutInflater.from(this).inflate( R.layout.account_signin_view, null); mView.init(new ProfileDataCache(this, Profile.getLastUsedProfile())); - mView.configureForSettingsPage(); mView.setListener(this); mView.setDelegate(this);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninConfirmationView.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninConfirmationView.java new file mode 100644 index 0000000..8ad1a51 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninConfirmationView.java
@@ -0,0 +1,100 @@ +// 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.chrome.browser.signin; + +import android.content.Context; +import android.util.AttributeSet; +import android.widget.LinearLayout; +import android.widget.RelativeLayout; +import android.widget.ScrollView; + +import org.chromium.chrome.R; + +/** +* This view allows the user to confirm signed in account, sync, and service personalization. +*/ +public class AccountSigninConfirmationView extends ScrollView { + private Observer mObserver; + private boolean mScrolledToBottom = false; + + /** + * Scrolled to bottom observer. + */ + public interface Observer { + /** + * On scrolled to bottom. This is called only once when showing the view. + */ + void onScrolledToBottom(); + } + + public AccountSigninConfirmationView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + // This assumes that view's layout_width and layout_height are set to match_parent. + assert MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY; + assert MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; + + int width = MeasureSpec.getSize(widthMeasureSpec); + int height = MeasureSpec.getSize(heightMeasureSpec); + + // Sets aspect ratio of the head to 16:9. + if (height > width) { + LinearLayout layout = (LinearLayout) findViewById(R.id.signin_confirmation_head); + RelativeLayout.LayoutParams params = + (RelativeLayout.LayoutParams) layout.getLayoutParams(); + params.height = width * 9 / 16; + params.width = LayoutParams.MATCH_PARENT; + layout.setLayoutParams(params); + } + + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + } + + @Override + protected float getTopFadingEdgeStrength() { + // Disable fading out effect at the top of this ScrollView. + return 0; + } + + @Override + protected void onLayout(boolean changed, int left, int top, int right, int bottom) { + super.onLayout(changed, left, top, right, bottom); + + notifyIfScrolledToBottom(true); + } + + @Override + protected void onScrollChanged(int l, int t, int oldl, int oldt) { + super.onScrollChanged(l, t, oldl, oldt); + + notifyIfScrolledToBottom(false); + } + + /** + * Sets scrolled to bottom observer. See {@link Observer} + * + * @param observer The observer. + */ + public void setScrolledToBottomObserver(Observer observer) { + mObserver = observer; + } + + private void notifyIfScrolledToBottom(boolean forceNotify) { + if (mObserver == null) return; + + if (!forceNotify && mScrolledToBottom) return; + + int distance = (getChildAt(getChildCount() - 1).getBottom() - (getHeight() + getScrollY())); + if (distance <= findViewById(R.id.signin_settings_control).getPaddingBottom()) { + mObserver.onScrolledToBottom(); + mScrolledToBottom = true; + } else { + mScrolledToBottom = false; + } + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java index a3b8e69d..d8f70472 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/AccountSigninView.java
@@ -7,26 +7,22 @@ import android.app.FragmentManager; import android.content.Context; import android.graphics.Bitmap; -import android.graphics.drawable.Drawable; -import android.os.Bundle; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.util.AttributeSet; +import android.view.LayoutInflater; +import android.view.MotionEvent; import android.view.View; import android.widget.AdapterView; -import android.widget.ArrayAdapter; import android.widget.Button; +import android.widget.FrameLayout; import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.Spinner; +import android.widget.ListView; import android.widget.TextView; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; -import org.chromium.chrome.browser.firstrun.FirstRunView; -import org.chromium.chrome.browser.firstrun.ImageCarousel; -import org.chromium.chrome.browser.firstrun.ImageCarousel.ImageCarouselPositionChangeListener; import org.chromium.chrome.browser.firstrun.ProfileDataCache; import org.chromium.chrome.browser.preferences.PrefServiceBridge; import org.chromium.chrome.browser.profiles.ProfileDownloader; @@ -39,9 +35,13 @@ import org.chromium.ui.text.NoUnderlineClickableSpan; import org.chromium.ui.text.SpanApplier; import org.chromium.ui.text.SpanApplier.SpanInfo; +import org.chromium.ui.widget.ButtonCompat; import java.util.List; +// TODO(gogerald): add landscape mode (http://crbug.com/599139). +// TODO(gogerald): refactor common part into one place after redesign all sign in screens. + /** * This view allows the user to select an account to log in to, add an account, * cancel account selection, etc. Users of this class should @@ -49,9 +49,8 @@ * {@link AccountSigninView#setDelegate(Delegate)} after the view has been inflated. */ -public class AccountSigninView extends FirstRunView - implements ImageCarouselPositionChangeListener, ProfileDownloader.Observer { - +public class AccountSigninView + extends FrameLayout implements AdapterView.OnItemClickListener, ProfileDownloader.Observer { /** * Callbacks for various account selection events. */ @@ -93,66 +92,34 @@ public FragmentManager getFragmentManager(); } - private class SpinnerOnItemSelectedListener implements AdapterView.OnItemSelectedListener { - @Override - public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { - String accountName = parent.getItemAtPosition(pos).toString(); - if (accountName.equals(mAddAnotherAccount)) { - // Don't allow "add account" to remain selected. http://crbug.com/421052 - int oldPosition = mArrayAdapter.getPosition(mAccountName); - if (oldPosition == -1) oldPosition = 0; - mSpinner.setSelection(oldPosition, false); - - mListener.onNewAccount(); - RecordUserAction.record("Signin_AddAccountToDevice"); - } else { - mAccountName = accountName; - if (!mPositionSetProgrammatically) mImageCarousel.scrollTo(pos, false, false); - mPositionSetProgrammatically = false; - } - } - @Override - public void onNothingSelected(AdapterView<?> parent) { - mAccountName = parent.getItemAtPosition(0).toString(); - } - } - - private static final String TAG = "AccountFirstRunView"; - - private static final int EXPERIMENT_TITLE_VARIANT_MASK = 1; - private static final int EXPERIMENT_SUMMARY_VARIANT_MASK = 2; - private static final int EXPERIMENT_LAYOUT_VARIANT_MASK = 4; - private static final int EXPERIMENT_MAX_VALUE = 7; + private static final String TAG = "AccountSigninView"; private static final String SETTINGS_LINK_OPEN = "<LINK1>"; private static final String SETTINGS_LINK_CLOSE = "</LINK1>"; private AccountManagerHelper mAccountManagerHelper; private List<String> mAccountNames; - private ArrayAdapter<CharSequence> mArrayAdapter; - private ImageCarousel mImageCarousel; - private Button mPositiveButton; + private View mSigninView; + private AccountListAdapter mAccountListAdapter; + private ListView mAccountListView; + private ButtonCompat mPositiveButton; private Button mNegativeButton; private TextView mTitle; - private TextView mDescriptionText; private Listener mListener; private Delegate mDelegate; - private Spinner mSpinner; - private TextView mConfirmAccountEmail; - private Drawable mSpinnerBackground; private String mForcedAccountName; - private String mAccountName; - private String mAddAnotherAccount; private ProfileDataCache mProfileData; private boolean mSignedIn; - private boolean mPositionSetProgrammatically; - private int mDescriptionTextId; private int mCancelButtonTextId; private boolean mIsChildAccount; - private boolean mHorizontalModeEnabled = true; - private boolean mDynamicPaddingEnabled = true; private boolean mShowSettingsSpan = true; + private AccountSigninConfirmationView mSigninConfirmationView; + private ImageView mSigninAccountImage; + private TextView mSigninAccountName; + private TextView mSigninAccountEmail; + private TextView mSigninSettingsControl; + public AccountSigninView(Context context, AttributeSet attrs) { super(context, attrs); mAccountManagerHelper = AccountManagerHelper.get(getContext().getApplicationContext()); @@ -163,27 +130,58 @@ * @param profileData ProfileDataCache that will be used to call to retrieve user account info. */ public void init(ProfileDataCache profileData) { - setProfileDataCache(profileData); - } - - /** - * Sets the profile data cache. - * @param profileData ProfileDataCache that will be used to call to retrieve user account info. - */ - public void setProfileDataCache(ProfileDataCache profileData) { mProfileData = profileData; mProfileData.setObserver(this); - updateProfileImages(); + mAccountListAdapter = new AccountListAdapter(getContext(), profileData); + mAccountListView.setAdapter(mAccountListAdapter); + showSigninPage(); } @Override protected void onFinishInflate() { super.onFinishInflate(); - mImageCarousel = (ImageCarousel) findViewById(R.id.image); - mImageCarousel.setListener(this); + mSigninView = findViewById(R.id.signin_choose_account_view); - mPositiveButton = (Button) findViewById(R.id.positive_button); + mTitle = (TextView) findViewById(R.id.signin_title); + + mAccountListView = (ListView) findViewById(R.id.signin_account_list); + mAccountListView.setOnItemClickListener(this); + View signinChoiceDescription = + LayoutInflater.from(getContext()) + .inflate(R.layout.account_signin_choice_description_view, null, false); + signinChoiceDescription.setOnClickListener(null); + mAccountListView.addHeaderView(signinChoiceDescription); + + // Once the user has touched this ListView, prevent the parent view from handling touch + // events. This allows the ListView to behave reasonably when nested inside a ListView. + // TODO(gogerald): Remove this listener after https://crbug.com/583774 has been fixed. + mAccountListView.setOnTouchListener(new ListView.OnTouchListener() { + @Override + public boolean onTouch(View view, MotionEvent event) { + int action = event.getAction(); + switch (action) { + case MotionEvent.ACTION_DOWN: + view.getParent().requestDisallowInterceptTouchEvent(true); + break; + + case MotionEvent.ACTION_UP: + view.performClick(); + view.getParent().requestDisallowInterceptTouchEvent(false); + break; + default: + // Ignore. + break; + } + + view.onTouchEvent(event); + return true; + } + }); + + mPositiveButton = (ButtonCompat) findViewById(R.id.positive_button); + // Remove drop shadow effect. + mPositiveButton.setRaised(false); mNegativeButton = (Button) findViewById(R.id.negative_button); // A workaround for Android support library ignoring padding set in XML. b/20307607 @@ -191,46 +189,41 @@ ApiCompatibilityUtils.setPaddingRelative(mPositiveButton, padding, 0, padding, 0); ApiCompatibilityUtils.setPaddingRelative(mNegativeButton, padding, 0, padding, 0); - mTitle = (TextView) findViewById(R.id.title); - mDescriptionText = (TextView) findViewById(R.id.description); - // For the spans to be clickable. - mDescriptionText.setMovementMethod(LinkMovementMethod.getInstance()); - mDescriptionTextId = R.string.signin_account_choice_description; - // TODO(peconn): Ensure this is changed to R.string.cancel when used in Settings > Sign In. mCancelButtonTextId = R.string.no_thanks; - mAddAnotherAccount = getResources().getString(R.string.signin_add_account); + mSigninConfirmationView = + (AccountSigninConfirmationView) findViewById(R.id.signin_confirmation_view); + mSigninConfirmationView.setScrolledToBottomObserver( + new AccountSigninConfirmationView.Observer() { + @Override + public void onScrolledToBottom() { + setPositiveButtonEnabled(); + } + }); + mSigninAccountImage = (ImageView) findViewById(R.id.signin_account_image); + mSigninAccountName = (TextView) findViewById(R.id.signin_account_name); + mSigninAccountEmail = (TextView) findViewById(R.id.signin_account_email); + mSigninSettingsControl = (TextView) findViewById(R.id.signin_settings_control); + // For the spans to be clickable. + mSigninSettingsControl.setMovementMethod(LinkMovementMethod.getInstance()); + } - mConfirmAccountEmail = (TextView) findViewById(R.id.confirm_account_email); - mSpinner = (Spinner) findViewById(R.id.google_accounts_spinner); + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + // This assumes that view's layout_width and layout_height are set to match_parent. + assert MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY; + assert MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; - mSpinnerBackground = mSpinner.getBackground(); - mArrayAdapter = new ArrayAdapter<CharSequence>(getContext().getApplicationContext(), - R.layout.fre_spinner_text); + int width = MeasureSpec.getSize(widthMeasureSpec); + int height = MeasureSpec.getSize(heightMeasureSpec); - mArrayAdapter.setDropDownViewResource(R.layout.fre_spinner_dropdown); - mSpinner.setAdapter(mArrayAdapter); - mSpinner.setOnItemSelectedListener(new SpinnerOnItemSelectedListener()); + // Sets title aspect ratio to be 16:9. + if (height > width) { + mTitle.setHeight(width * 9 / 16); + } - // Only set the spinner's content description right before the accessibility action is going - // to be performed. Otherwise, the the content description is read when the - // AccountFirstRunView is created because setting the spinner's adapter causes a - // TYPE_VIEW_SELECTED event. ViewPager loads the next and previous pages according to - // it's off-screen page limit, which is one by default, so without this the content - // description ends up being read when the card before this one shown. - mSpinner.setAccessibilityDelegate(new AccessibilityDelegate() { - @Override - public boolean performAccessibilityAction(View host, int action, Bundle args) { - if (mSpinner.getContentDescription() == null) { - mSpinner.setContentDescription(getResources().getString( - R.string.accessibility_signin_account_spinner)); - } - return super.performAccessibilityAction(host, action, args); - } - }); - - showSigninPage(); + super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override @@ -252,70 +245,17 @@ } } - @Override - protected boolean isHorizontalModeEnabled() { - return mHorizontalModeEnabled; - } - - @Override - protected boolean isDynamicPaddingEnabled() { - return mDynamicPaddingEnabled; - } - /** * Changes the visuals slightly for when this view appears in the recent tabs page instead of - * in first run. For example, the title text is changed as well as the button style. + * in first run. * This is currently used in the Recent Tabs Promo and the bookmarks page. */ public void configureForRecentTabsOrBookmarksPage() { - mHorizontalModeEnabled = false; - mDynamicPaddingEnabled = false; mShowSettingsSpan = false; setBackgroundResource(R.color.ntp_bg); - mTitle.setText(R.string.sign_in_to_chrome); - mCancelButtonTextId = R.string.cancel; setUpCancelButton(); - - setPadding(0, 0, 0, - getResources().getDimensionPixelOffset(R.dimen.sign_in_promo_padding_bottom)); - } - - /** - * Changes the visuals slightly for when this view appears in the settings menu. - */ - public void configureForSettingsPage() { - mHorizontalModeEnabled = false; - } - - /** - * Changes the visuals slightly for when this view is shown in a subsequent run after user adds - * a Google account to the device. - */ - public void configureForAddAccountPromo() { - int experimentGroup = SigninManager.getAndroidSigninPromoExperimentGroup(); - assert experimentGroup >= 0 && experimentGroup <= EXPERIMENT_MAX_VALUE; - - if ((experimentGroup & EXPERIMENT_TITLE_VARIANT_MASK) != 0) { - mTitle.setText(R.string.make_chrome_yours); - } - - mDescriptionTextId = (experimentGroup & EXPERIMENT_SUMMARY_VARIANT_MASK) != 0 - ? R.string.signin_sign_in_to_chrome_summary_variant - : R.string.sign_in_to_chrome_summary; - - if ((experimentGroup & EXPERIMENT_LAYOUT_VARIANT_MASK) != 0) { - mImageCarousel.setVisibility(GONE); - - ImageView illustrationView = new ImageView(getContext()); - illustrationView.setImageResource(R.drawable.signin_promo_illustration); - illustrationView.setBackgroundColor(ApiCompatibilityUtils.getColor(getResources(), - R.color.illustration_background_color)); - - LinearLayout linearLayout = (LinearLayout) findViewById(R.id.fre_main_layout); - linearLayout.addView(illustrationView, 0); - } } /** @@ -351,7 +291,7 @@ * selected). */ private boolean updateAccounts() { - if (mSignedIn) return false; + if (mSignedIn || mProfileData == null) return false; List<String> oldAccountNames = mAccountNames; mAccountNames = mAccountManagerHelper.getGoogleAccountNames(); @@ -363,32 +303,24 @@ return false; } } else { - accountToSelect = getIndexOfNewElement( - oldAccountNames, mAccountNames, mSpinner.getSelectedItemPosition()); + accountToSelect = getIndexOfNewElement(oldAccountNames, mAccountNames, + mAccountListAdapter.getSelectedAccountPosition()); } - mArrayAdapter.clear(); + mAccountListAdapter.clear(); if (!mAccountNames.isEmpty()) { - mSpinner.setVisibility(View.VISIBLE); - mArrayAdapter.addAll(mAccountNames); - mArrayAdapter.add(mAddAnotherAccount); + mAccountListAdapter.addAll(mAccountNames); + mAccountListAdapter.add(getResources().getString(R.string.signin_add_account)); setUpSigninButton(true); - mDescriptionText.setText(mDescriptionTextId); - } else { - mSpinner.setVisibility(View.GONE); - mArrayAdapter.add(mAddAnotherAccount); setUpSigninButton(false); - mDescriptionText.setText(R.string.signin_no_account_choice_description); } - if (mProfileData != null) mProfileData.update(); + mProfileData.update(); updateProfileImages(); - mSpinner.setSelection(accountToSelect); - mAccountName = mArrayAdapter.getItem(accountToSelect).toString(); - mImageCarousel.scrollTo(accountToSelect, false, false); + selectAccount(accountToSelect); return oldAccountNames != null && !(oldAccountNames.size() == mAccountNames.size() @@ -426,34 +358,21 @@ private void updateProfileImages() { if (mProfileData == null) return; - int count = mAccountNames.size(); + mAccountListAdapter.notifyDataSetChanged(); - Bitmap[] images; - if (count == 0) { - images = new Bitmap[1]; - images[0] = mProfileData.getImage(null); - } else { - images = new Bitmap[count]; - for (int i = 0; i < count; ++i) { - images[i] = mProfileData.getImage(mAccountNames.get(i)); - } - } - - mImageCarousel.setImages(images); - updateProfileName(); + if (mSignedIn) updateSignedInAccountInfo(); } - private void updateProfileName() { - if (!mSignedIn) return; - + private void updateSignedInAccountInfo() { + String selectedAccountEmail = getSelectedAccountName(); + mSigninAccountImage.setImageBitmap(mProfileData.getImage(selectedAccountEmail)); String name = null; - if (mProfileData != null) { - if (mIsChildAccount) name = mProfileData.getGivenName(mAccountName); - if (name == null) name = mProfileData.getFullName(mAccountName); - } - if (name == null) name = mAccountName; + if (mIsChildAccount) name = mProfileData.getGivenName(selectedAccountEmail); + if (name == null) name = mProfileData.getFullName(selectedAccountEmail); + if (name == null) name = selectedAccountEmail; String text = String.format(getResources().getString(R.string.signin_hi_name), name); - mTitle.setText(text); + mSigninAccountName.setText(text); + mSigninAccountEmail.setText(selectedAccountEmail); } /** @@ -466,53 +385,45 @@ showConfirmSigninPage(); } - private void configureSpinner(boolean signinPage) { - mSpinner.setEnabled(signinPage); - mSpinner.setVisibility(signinPage ? View.VISIBLE : View.GONE); - mConfirmAccountEmail.setVisibility(signinPage ? View.GONE : View.VISIBLE); - mConfirmAccountEmail.setText(mAccountName); - } - private void showSigninPage() { mSignedIn = false; - mTitle.setText(R.string.sign_in_to_chrome); - configureSpinner(true); - mImageCarousel.setVisibility(VISIBLE); + mSigninConfirmationView.setVisibility(View.GONE); + mSigninView.setVisibility(View.VISIBLE); setUpCancelButton(); updateAccounts(); - - mImageCarousel.setSignedInMode(false); } private void showConfirmSigninPage() { mSignedIn = true; - updateProfileName(); - configureSpinner(false); + updateSignedInAccountInfo(); + + mSigninView.setVisibility(View.GONE); + mSigninConfirmationView.setVisibility(View.VISIBLE); + setButtonsEnabled(true); setUpConfirmButton(); + setPositiveButtonDisabled(); setUpUndoButton(); if (mShowSettingsSpan) { NoUnderlineClickableSpan settingsSpan = new NoUnderlineClickableSpan() { @Override public void onClick(View widget) { - mListener.onAccountSelected(mAccountName, true); + mListener.onAccountSelected(getSelectedAccountName(), true); } }; - mDescriptionText.setText(SpanApplier.applySpans(getSignedInDescription(mIsChildAccount), - new SpanInfo(SETTINGS_LINK_OPEN, SETTINGS_LINK_CLOSE, settingsSpan))); + mSigninSettingsControl.setText( + SpanApplier.applySpans(getSettingsControlDescription(mIsChildAccount), + new SpanInfo(SETTINGS_LINK_OPEN, SETTINGS_LINK_CLOSE, settingsSpan))); } else { // If we aren't showing the span, get rid of the LINK1 annotations. - mDescriptionText.setText(getSignedInDescription(mIsChildAccount) - .replace(SETTINGS_LINK_OPEN, "") - .replace(SETTINGS_LINK_CLOSE, "")); + mSigninSettingsControl.setText(getSettingsControlDescription(mIsChildAccount) + .replace(SETTINGS_LINK_OPEN, "") + .replace(SETTINGS_LINK_CLOSE, "")); } - - mImageCarousel.setVisibility(VISIBLE); - mImageCarousel.setSignedInMode(true); } private void showConfirmSigninPageAccountTrackerServiceCheck() { @@ -540,14 +451,11 @@ } private void showConfirmSigninPagePreviousAccountCheck() { - if (SigninInvestigator.investigate(mAccountName) - == InvestigatedScenario.DIFFERENT_ACCOUNT) { - + String accountName = getSelectedAccountName(); + if (SigninInvestigator.investigate(accountName) == InvestigatedScenario.DIFFERENT_ACCOUNT) { ConfirmImportSyncDataDialog.showNewInstance( - PrefServiceBridge.getInstance().getSyncLastAccountName(), - mAccountName, - ImportSyncType.PREVIOUS_DATA_FOUND, - mDelegate.getFragmentManager(), + PrefServiceBridge.getInstance().getSyncLastAccountName(), accountName, + ImportSyncType.PREVIOUS_DATA_FOUND, mDelegate.getFragmentManager(), new ConfirmImportSyncDataDialog.Listener() { @Override public void onConfirm(boolean wipeData) { @@ -587,8 +495,8 @@ } private void setUpSigninButton(boolean hasAccounts) { - mPositiveButton.setText(R.string.choose_account_sign_in); if (hasAccounts) { + mPositiveButton.setText(R.string.continue_sign_in); mPositiveButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { @@ -596,6 +504,7 @@ } }); } else { + mPositiveButton.setText(R.string.choose_account_sign_in); mPositiveButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { @@ -604,6 +513,7 @@ } }); } + setPositiveButtonEnabled(); } private void setUpUndoButton() { @@ -625,7 +535,7 @@ mPositiveButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { - mListener.onAccountSelected(mAccountName, false); + mListener.onAccountSelected(getSelectedAccountName(), false); } }); } @@ -640,12 +550,12 @@ } } - private String getSignedInDescription(boolean childAccount) { + private String getSettingsControlDescription(boolean childAccount) { if (childAccount) { - return getResources().getString(R.string.signin_signed_in_description) + '\n' + return getResources().getString(R.string.signin_signed_in_settings_description) + '\n' + getResources().getString(R.string.signin_signed_in_description_uca_addendum); } else { - return getResources().getString(R.string.signin_signed_in_description); + return getResources().getString(R.string.signin_signed_in_settings_description); } } @@ -663,9 +573,9 @@ public void switchToForcedAccountMode(String forcedAccountName) { mForcedAccountName = forcedAccountName; updateAccounts(); - assert TextUtils.equals(mAccountName, mForcedAccountName); + assert TextUtils.equals(getSelectedAccountName(), mForcedAccountName); switchToSignedMode(); - assert TextUtils.equals(mAccountName, mForcedAccountName); + assert TextUtils.equals(getSelectedAccountName(), mForcedAccountName); } /** @@ -682,9 +592,42 @@ return mForcedAccountName != null; } + // Overrides AdapterView.OnItemClickListener. @Override - public void onPositionChanged(int i) { - mPositionSetProgrammatically = true; - mSpinner.setSelection(i); + public void onItemClick(AdapterView<?> adapter, View view, int position, long id) { + int positionInAccountListAdapter = position - mAccountListView.getHeaderViewsCount(); + if (positionInAccountListAdapter == mAccountListAdapter.getCount() - 1) { + mListener.onNewAccount(); + RecordUserAction.record("Signin_AddAccountToDevice"); + } else { + selectAccount(positionInAccountListAdapter); + } + } + + private void selectAccount(int position) { + mAccountListAdapter.setSelectedAccountPosition(position); + mAccountListAdapter.notifyDataSetChanged(); + } + + private void setPositiveButtonEnabled() { + mPositiveButton.setButtonColor( + ApiCompatibilityUtils.getColor(getResources(), R.color.light_active_color)); + mPositiveButton.setTextColor( + ApiCompatibilityUtils.getColor(getResources(), R.color.signin_head_background)); + mPositiveButton.setAlpha(1f); + mPositiveButton.setEnabled(true); + } + + private void setPositiveButtonDisabled() { + mPositiveButton.setButtonColor(ApiCompatibilityUtils.getColor( + getResources(), R.color.signin_button_disabled_color)); + mPositiveButton.setTextColor( + ApiCompatibilityUtils.getColor(getResources(), R.color.fre_text_color)); + mPositiveButton.setAlpha(0.26f); + mPositiveButton.setEnabled(false); + } + + private String getSelectedAccountName() { + return mAccountNames.get(mAccountListAdapter.getSelectedAccountPosition()); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninPromoScreen.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninPromoScreen.java index b19a8ff..4350f046 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninPromoScreen.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninPromoScreen.java
@@ -77,7 +77,6 @@ inflater.inflate(R.layout.account_signin_view, null); mProfileDataCache = new ProfileDataCache(activity, Profile.getLastUsedProfile()); mAccountFirstRunView.init(mProfileDataCache); - mAccountFirstRunView.configureForAddAccountPromo(); mAccountFirstRunView.setListener(this); mAccountFirstRunView.setDelegate(this);
diff --git a/chrome/android/java/strings/android_chrome_strings.grd b/chrome/android/java/strings/android_chrome_strings.grd index 4fd2286..f693d11f 100644 --- a/chrome/android/java/strings/android_chrome_strings.grd +++ b/chrome/android/java/strings/android_chrome_strings.grd
@@ -1675,6 +1675,9 @@ <message name="IDS_CHOOSE_ACCOUNT_SIGN_IN" desc="Sign in button for choose google account dialog [CHAR-LIMIT=20]"> Sign in </message> + <message name="IDS_CONTINUE_SIGN_IN" desc="Sign in button for proceed sign in with selected account [CHAR-LIMIT=20]"> + Continue + </message> <message name="IDS_SIGNIN_ACCOUNT_CHOICE_DESCRIPTION" desc="Text for account chooser page"> Sign in to get your bookmarks, history, passwords, and other settings on all your devices. </message> @@ -1687,23 +1690,14 @@ <message name="IDS_MAKE_CHROME_YOURS" desc="Title for the signin promo that prompts the user to sign in to Chrome to have a personalized experirence. [CHAR-LIMIT=24]"> Make Chrome yours </message> - <message name="IDS_SIGNIN_NO_ACCOUNT_CHOICE_DESCRIPTION" desc="Text for account chooser page when there are no accounts on the device."> - Add an account to get your bookmarks, history, passwords, and other settings on all your devices. - </message> - <message name="IDS_SIGNIN_SIGN_IN_TO_CHROME_SUMMARY_VARIANT" desc="A variant of summary for the signin promo; lists reasons to sign in to Chrome."> - Sign in to access all your web stuff from any device - </message> <message name="IDS_SIGNIN_HI_NAME" desc="Title welcoming the user by their name after they have signed in."> Hi, <ph name="FULL_NAME">%1$s<ex>John Smith</ex></ph> </message> - <message name="IDS_SIGNIN_SIGNED_IN_DESCRIPTION" desc="Explanation of what gets synced after the user signed in"> - Your bookmarks, history, passwords, and other settings will be synced to your Google Account so you can use them on all your devices. You can choose what to sync in <ph name="BEGIN_LINK1"><LINK1></ph>Settings<ph name="END_LINK1"></LINK1></ph>. - </message> <message name="IDS_SIGNIN_SIGNED_IN_DESCRIPTION_UCA_ADDENDUM" desc="Additional explanation for child accounts that synced settings are managed by parents."> Your parents help manage these settings. </message> - <message name="IDS_ACCESSIBILITY_SIGNIN_ACCOUNT_SPINNER" desc="Content description for the first run account drop down spinner."> - Choose account + <message name="IDS_SIGNIN_SIGNED_IN_SETTINGS_DESCRIPTION" desc="Label of the section containing the link to go to the settings page."> + Control how this works in <ph name="BEGIN_LINK1"><LINK1></ph>Settings<ph name="END_LINK1"></LINK1></ph> </message> <!-- External Navigation Strings -->
diff --git a/chrome/android/java_sources.gni b/chrome/android/java_sources.gni index 9fa4ffe..037dc67a 100644 --- a/chrome/android/java_sources.gni +++ b/chrome/android/java_sources.gni
@@ -335,7 +335,6 @@ "java/src/org/chromium/chrome/browser/firstrun/FirstRunStatus.java", "java/src/org/chromium/chrome/browser/firstrun/FirstRunView.java", "java/src/org/chromium/chrome/browser/firstrun/ForcedSigninProcessor.java", - "java/src/org/chromium/chrome/browser/firstrun/ImageCarousel.java", "java/src/org/chromium/chrome/browser/firstrun/ProfileDataCache.java", "java/src/org/chromium/chrome/browser/firstrun/ToSAckedReceiver.java", "java/src/org/chromium/chrome/browser/firstrun/ToSAndUMAFirstRunFragment.java", @@ -722,7 +721,10 @@ "java/src/org/chromium/chrome/browser/signin/AccountIdProvider.java", "java/src/org/chromium/chrome/browser/signin/AccountManagementFragment.java", "java/src/org/chromium/chrome/browser/signin/AccountManagementScreenHelper.java", + "java/src/org/chromium/chrome/browser/signin/AccountListAdapter.java", + "java/src/org/chromium/chrome/browser/signin/AccountListView.java", "java/src/org/chromium/chrome/browser/signin/AccountSigninActivity.java", + "java/src/org/chromium/chrome/browser/signin/AccountSigninConfirmationView.java", "java/src/org/chromium/chrome/browser/signin/AccountSigninView.java", "java/src/org/chromium/chrome/browser/signin/AccountTrackerService.java", "java/src/org/chromium/chrome/browser/signin/AddGoogleAccountDialogFragment.java",
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/media/ui/NotificationTitleUpdatedTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/media/ui/NotificationTitleUpdatedTest.java index 506a600..c2e0b98e 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/media/ui/NotificationTitleUpdatedTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/media/ui/NotificationTitleUpdatedTest.java
@@ -13,9 +13,11 @@ import org.chromium.base.ObserverList; import org.chromium.base.ThreadUtils; +import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Restriction; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeActivity; +import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.test.ChromeActivityTestCaseBase; import org.chromium.chrome.test.util.ChromeRestriction; @@ -46,38 +48,33 @@ simulateUpdateTitle(mTab, "title1"); } - @SmallTest - public void testSessionStatePlaying() throws InterruptedException { + private void testSessionStatePlayingInternal() throws InterruptedException { simulateMediaSessionStateChanged(mTab, true, false); assertTitleMatches("title1"); simulateUpdateTitle(mTab, "title2"); assertTitleMatches("title2"); } - @SmallTest - public void testSessionStatePaused() throws InterruptedException { + private void testSessionStatePausedInternal() throws InterruptedException { simulateMediaSessionStateChanged(mTab, true, true); assertTitleMatches("title1"); simulateUpdateTitle(mTab, "title2"); assertTitleMatches("title2"); } - @SmallTest - public void testSessionStateUncontrollable() throws InterruptedException { + private void testSessionStateUncontrollableInternal() throws InterruptedException { simulateMediaSessionStateChanged(mTab, true, false); assertTitleMatches("title1"); simulateMediaSessionStateChanged(mTab, false, false); simulateUpdateTitle(mTab, "title2"); } - @SmallTest - public void testMediaMetadaSetsTitle() throws InterruptedException { + private void testMediaMetadataSetsTitleInternal() throws InterruptedException { simulateMediaSessionStateChanged(mTab, true, false, new MediaMetadata("title2", "", "")); assertTitleMatches("title2"); } - @SmallTest - public void testMediaMetadaOverridesTitle() throws InterruptedException { + private void testMediaMetadataOverridesTitleInternal() throws InterruptedException { simulateMediaSessionStateChanged(mTab, true, false, new MediaMetadata("title2", "", "")); assertTitleMatches("title2"); @@ -94,9 +91,7 @@ * 4. change the title of newTab and then mTab to different names, * the notification should have the title of newTab. */ - @SmallTest - @Restriction({ChromeRestriction.RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_NON_LOW_END_DEVICE}) - public void testMultipleTabs() throws Throwable { + private void testMultipleTabsInternal() throws Throwable { simulateMediaSessionStateChanged(mTab, true, false); assertTitleMatches("title1"); simulateMediaSessionStateChanged(mTab, false, false); @@ -110,6 +105,82 @@ assertTitleMatches("title3"); } + @SmallTest + @CommandLineFlags.Add("enable-features=MediaStyleNotification") + public void testSessionStatePlaying_MediaStyleNotification() throws InterruptedException { + testSessionStatePlayingInternal(); + } + + @SmallTest + @CommandLineFlags.Add("enable-features=MediaStyleNotification") + public void testSessionStatePaused_MediaStyleNotification() throws InterruptedException { + testSessionStatePausedInternal(); + } + + @SmallTest + @CommandLineFlags.Add("enable-features=MediaStyleNotification") + public void testSessionStateUncontrollable_MediaStyleNotification() + throws InterruptedException { + testSessionStateUncontrollableInternal(); + } + + @SmallTest + @CommandLineFlags.Add("enable-features=MediaStyleNotification") + public void testMediaMetadataSetsTitle_MediaStyleNotification() throws InterruptedException { + testMediaMetadataSetsTitleInternal(); + } + + @SmallTest + @CommandLineFlags.Add("enable-features=MediaStyleNotification") + public void testMediaMetadataOverridesTitle_MediaStyleNotification() + throws InterruptedException { + testMediaMetadataOverridesTitleInternal(); + } + + @SmallTest + @Restriction({ChromeRestriction.RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_NON_LOW_END_DEVICE}) + @CommandLineFlags.Add("enable-features=MediaStyleNotification") + public void testMultipleTabs_MediaStyleNotification() throws Throwable { + testMultipleTabsInternal(); + } + + @SmallTest + @CommandLineFlags.Add("disable-features=MediaStyleNotification") + public void testSessionStatePlaying_CustomNotification() throws InterruptedException { + testSessionStatePlayingInternal(); + } + + @SmallTest + @CommandLineFlags.Add("disable-features=MediaStyleNotification") + public void testSessionStatePaused_CustomNotification() throws InterruptedException { + testSessionStatePausedInternal(); + } + + @SmallTest + @CommandLineFlags.Add("disable-features=MediaStyleNotification") + public void testSessionStateUncontrollable_CustomNotification() throws InterruptedException { + testSessionStateUncontrollableInternal(); + } + + @SmallTest + @CommandLineFlags.Add("disable-features=MediaStyleNotification") + public void testMediaMetadataSetsTitle_CustomNotification() throws InterruptedException { + testMediaMetadataSetsTitleInternal(); + } + + @SmallTest + @CommandLineFlags.Add("disable-features=MediaStyleNotification") + public void testMediaMetadataOverridesTitle_CustomNotification() throws InterruptedException { + testMediaMetadataOverridesTitleInternal(); + } + + @SmallTest + @Restriction({ChromeRestriction.RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_NON_LOW_END_DEVICE}) + @CommandLineFlags.Add("disable-features=MediaStyleNotification") + public void testMultipleTabs_CustomNotification() throws Throwable { + testMultipleTabsInternal(); + } + @Override public void startMainActivity() throws InterruptedException { startMainActivityOnBlankPage(); @@ -169,8 +240,21 @@ View contentView = notification.contentView.apply( getActivity().getApplicationContext(), null); - TextView titleView = (TextView) contentView.findViewById(R.id.title); - assertEquals(title, titleView.getText()); + String observedText = null; + if (ChromeFeatureList.isEnabled(ChromeFeatureList.MEDIA_STYLE_NOTIFICATION)) { + TextView view = (TextView) contentView.findViewById(android.R.id.title); + if (view == null) { + // Case where NotificationCompat does not use the native Notification. + // The TextView id will be in Chrome's namespace. + view = (TextView) contentView.findViewById(R.id.title); + } + observedText = view.getText().toString(); + } else { + observedText = ((TextView) contentView.findViewById(R.id.title)) + .getText() + .toString(); + } + assertEquals(title, observedText); } }); }
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index f89783c5..bfa2d137d 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -5611,6 +5611,14 @@ <message name="IDS_FLAGS_GESTURE_REQUIREMENT_FOR_MEDIA_PLAYBACK_DESCRIPTION" desc="Description for the flag for gesture requiment for media playback"> User gesture requirement for playing media elements. Disabling this will allow autoplay to work. </message> + <if expr="is_android"> + <message name="IDS_FLAGS_MEDIA_STYLE_NOTIFICATION_NAME" desc="Title for the flag for using media style notification"> + Media style notification + </message> + <message name="IDS_FLAGS_MEDIA_STYLE_NOTIFICATION_DESCRIPTION" desc="Description for the flag for using media style notification"> + Use Android MediaStyle notifications for Chrome media notifications. + </message> + </if> <if expr="use_ash"> <message name="IDS_FLAGS_ASH_MAXIMIZE_MODE_WINDOW_BACKDROP_NAME" desc="Title for the flag which can be used for window backdrops in TouchView."> Window backdrops in TouchView @@ -10808,19 +10816,19 @@ <message name="IDS_SYNC_CONFIRMATION_TITLE" desc="Title of the sync confirmation dialog in the tab modal signin flow"> You're now signed in to Chrome </message> - <message name="IDS_SYNC_CONFIRMATION_CHROME_SYNC_TITLE" desc="Title of the chrome sync section of the sync confirmation dialog in the tab modal signin flow"> + <message name="IDS_SYNC_CONFIRMATION_CHROME_SYNC_TITLE" desc="Title of the chrome sync section of the sync confirmation dialog in the tab modal signin flow" formatter_data="android_java"> Chrome Sync </message> <message name="IDS_SYNC_CONFIRMATION_CHROME_SYNC_BODY" desc="Body of the chrome sync section of the sync confirmation dialog in the tab modal signin flow"> Your bookmarks, history, passwords and other settings will be synced to your Google Account so you can use them on all your devices. Control what to sync in <ph name="BEGIN_LINK"><a id="settingsLink" href="#">Settings</a>.</ph> </message> - <message name="IDS_SYNC_CONFIRMATION_CHROME_SYNC_MESSAGE" desc="Body of the chrome sync section of the sync confirmation dialog in the tab modal signin flow"> + <message name="IDS_SYNC_CONFIRMATION_CHROME_SYNC_MESSAGE" desc="Body of the chrome sync section of the sync confirmation dialog in the tab modal signin flow" formatter_data="android_java"> Your bookmarks, history, passwords, and other settings will be synced to your Google Account so you can use them on all your devices </message> - <message name="IDS_SYNC_CONFIRMATION_PERSONALIZE_SERVICES_TITLE" desc="Title of the personalize services section of the sync confirmation dialog in the tab modal signin flow"> + <message name="IDS_SYNC_CONFIRMATION_PERSONALIZE_SERVICES_TITLE" desc="Title of the personalize services section of the sync confirmation dialog in the tab modal signin flow" formatter_data="android_java"> Personalize Google services </message> - <message name="IDS_SYNC_CONFIRMATION_PERSONALIZE_SERVICES_BODY" desc="Body of the personalize services section of the sync confirmation dialog in the tab modal signin flow"> + <message name="IDS_SYNC_CONFIRMATION_PERSONALIZE_SERVICES_BODY" desc="Body of the personalize services section of the sync confirmation dialog in the tab modal signin flow" formatter_data="android_java"> Google may use your browsing history to personalize Search and other Google services </message> <message name="IDS_SYNC_CONFIRMATION_SYNC_SETTINGS_LINK_BODY" desc="Label of the section containing the link to go to the sync setting page."> @@ -11463,7 +11471,7 @@ <!-- Personalize Google Services section of the configure sync dialog --> <message name="IDS_SYNC_PERSONALIZE_GOOGLE_SERVICES_MESSAGE" desc="Text of the section containing a link to the Google Activity Controls."> - Control how Google uses your browsing history to personalize Search and other Google services from <ph name="BEGIN_LINK"><a href="$1" target="_blank"></ph>Google Activity Controls<ph name="END_LINK"></a></ph>. + Control how Google uses your browsing history to personalize Search and other Google services from <ph name="BEGIN_LINK"><a id="activity-controls" href="$1" target="_blank"></ph>Google Activity Controls<ph name="END_LINK"></a></ph>. </message> <!-- Passphrase dialog strings -->
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 688b570..37822da2 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -1822,6 +1822,12 @@ IDS_FLAGS_TAB_DETACHING_IN_FULLSCREEN_DESCRIPTION, kOsMac, SINGLE_VALUE_TYPE(switches::kEnableFullscreenTabDetaching)}, #endif +#if defined(OS_ANDROID) + {"media-style-notification", + IDS_FLAGS_MEDIA_STYLE_NOTIFICATION_NAME, + IDS_FLAGS_MEDIA_STYLE_NOTIFICATION_DESCRIPTION, kOsAndroid, + FEATURE_VALUE_TYPE(chrome::android::kMediaStyleNotification)}, +#endif // NOTE: Adding new command-line switches requires adding corresponding // entries to enum "LoginCustomFlags" in histograms.xml. See note in // histograms.xml and don't forget to run AboutFlagsHistogramTest unit test.
diff --git a/chrome/browser/android/chrome_feature_list.cc b/chrome/browser/android/chrome_feature_list.cc index c949f6d..21a9c7a 100644 --- a/chrome/browser/android/chrome_feature_list.cc +++ b/chrome/browser/android/chrome_feature_list.cc
@@ -26,6 +26,7 @@ // this array may either refer to features defined in this file (above) or in // other locations in the code base (e.g. chrome/, components/, etc). const base::Feature* kFeaturesExposedToJava[] = { + &kMediaStyleNotification, &kNTPOfflinePagesFeature, &kNTPSnippetsFeature, &kNTPToolbarFeature, @@ -37,6 +38,10 @@ } // namespace +const base::Feature kMediaStyleNotification { + "MediaStyleNotification", base::FEATURE_DISABLED_BY_DEFAULT +}; + const base::Feature kNTPOfflinePagesFeature { "NTPOfflinePages", base::FEATURE_DISABLED_BY_DEFAULT };
diff --git a/chrome/browser/android/chrome_feature_list.h b/chrome/browser/android/chrome_feature_list.h index 342ebc8..ecd05c75 100644 --- a/chrome/browser/android/chrome_feature_list.h +++ b/chrome/browser/android/chrome_feature_list.h
@@ -12,6 +12,7 @@ namespace chrome { namespace android { +extern const base::Feature kMediaStyleNotification; extern const base::Feature kNTPOfflinePagesFeature; extern const base::Feature kNTPSnippetsFeature; extern const base::Feature kNTPToolbarFeature;
diff --git a/chrome/browser/apps/guest_view/web_view_interactive_browsertest.cc b/chrome/browser/apps/guest_view/web_view_interactive_browsertest.cc index 34d88650..2d907918 100644 --- a/chrome/browser/apps/guest_view/web_view_interactive_browsertest.cc +++ b/chrome/browser/apps/guest_view/web_view_interactive_browsertest.cc
@@ -1420,14 +1420,12 @@ base::Bind(&TextInputStateHelper::HasGivenValue, "last one")); } -// TODO(ekaramad): Activate this test for OOPIF when input event routing for -// OOPIF-<webview> is fixed. IN_PROC_BROWSER_TEST_P(WebViewTextInputStateInteractiveTest, CrashingWebViewResetsState) { SetupTest("web_view/text_input_state", "/extensions/platform_apps/web_view/text_input_state/guest.html"); - // Press tab key twice to end up in the <input> of the <webview>, + // Press tab key twice to end up in the <input> of the <webview>. ExtensionTestMessageListener listener("GUEST-FOCUSED", false); for (size_t i = 0; i < 2; ++i) SendKeyPressToPlatformApp(ui::VKEY_TAB); @@ -1442,7 +1440,43 @@ // Now crash the <webview>. guest_web_contents()->GetRenderProcessHost()->Shutdown(false, 0); - // State should reset to none. + // Wait for the outer WebContentsImpl |text_input_state_->type| to be reset to + // none. + TextInputStateHelper::WaitForDesiredState( + embedder_web_contents(), + base::Bind(&TextInputStateHelper::IsStateOfGivenType, + ui::TEXT_INPUT_TYPE_NONE)); +} + +// This test creates a <webview> with a text input field inside, gives focus to +// the input field, and then detaches the <webview>. It monitors the embedder +// WebContents text input state to make sure it tracks the state properly. +IN_PROC_BROWSER_TEST_P(WebViewTextInputStateInteractiveTest, + OuterWebContentsResetsStateAfterDetach) { + SetupTest("web_view/text_input_state", + "/extensions/platform_apps/web_view/text_input_state/guest.html"); + + // Press tab key twice to end up in the <input> of the <webview>. + ExtensionTestMessageListener listener("GUEST-FOCUSED", false); + for (size_t i = 0; i < 2; ++i) + SendKeyPressToPlatformApp(ui::VKEY_TAB); + + listener.WaitUntilSatisfied(); + + // Now wait for a text input state change. + TextInputStateHelper::WaitForDesiredState( + embedder_web_contents(), + base::Bind(&TextInputStateHelper::HasGivenValue, "guest")); + + // Now detach the <webview>. + ExtensionTestMessageListener detach_listener("detached", false); + detach_listener.set_failure_message("failed-to-detach"); + EXPECT_TRUE( + content::ExecuteScript(embedder_web_contents(), "detachWebView();")); + detach_listener.WaitUntilSatisfied(); + + // Wait for the outer WebContentsImpl |text_input_state_->type| to be reset to + // none. TextInputStateHelper::WaitForDesiredState( embedder_web_contents(), base::Bind(&TextInputStateHelper::IsStateOfGivenType,
diff --git a/chrome/browser/autofill/autofill_interactive_uitest.cc b/chrome/browser/autofill/autofill_interactive_uitest.cc index 5ec23cd..045f6924 100644 --- a/chrome/browser/autofill/autofill_interactive_uitest.cc +++ b/chrome/browser/autofill/autofill_interactive_uitest.cc
@@ -626,7 +626,14 @@ // Test that a field is still autofillable after the previously autofilled // value is deleted. -IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, OnDeleteValueAfterAutofill) { +// TODO(crbug.com/603488) Test is timing out flakily on CrOS. +#if defined(OS_CHROMEOS) +#define MAYBE_OnDeleteValueAfterAutofill DISABLED_OnDeleteValueAfterAutofill +#else +#define MAYBE_OnDeleteValueAfterAutofill OnDeleteValueAfterAutofill +#endif +IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, + MAYBE_OnDeleteValueAfterAutofill) { CreateTestProfile(); // Load the test page. @@ -1016,9 +1023,17 @@ ExpectFieldValue("state_freeform", std::string()); } +// TODO(crbug.com/603488) Test is timing out flakily on CrOS. +#if defined(OS_CHROMEOS) +#define MAYBE_AutofillFormWithNonAutofillableField \ + DISABLED_AutofillFormWithNonAutofillableField +#else +#define MAYBE_AutofillFormWithNonAutofillableField \ + AutofillFormWithNonAutofillableField +#endif // Test that we properly autofill forms with non-autofillable fields. IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, - AutofillFormWithNonAutofillableField) { + MAYBE_AutofillFormWithNonAutofillableField) { CreateTestProfile(); // Load the test page.
diff --git a/chrome/browser/chromeos/arc/arc_policy_bridge.cc b/chrome/browser/chromeos/arc/arc_policy_bridge.cc index 8807eeff..74e68f9 100644 --- a/chrome/browser/chromeos/arc/arc_policy_bridge.cc +++ b/chrome/browser/chromeos/arc/arc_policy_bridge.cc
@@ -89,6 +89,8 @@ // Keep them sorted by the ARC policy names. AddPolicy("cameraDisabled", policy::key::kVideoCaptureAllowed, policy_map, true, &filtered_policies); + AddPolicy("screenCaptureDisabled", policy::key::kDisableScreenshots, + policy_map, false, &filtered_policies); AddPolicy("unmuteMicrophoneDisabled", policy::key::kAudioCaptureAllowed, policy_map, true, &filtered_policies);
diff --git a/chrome/browser/chromeos/arc/arc_policy_bridge_unittest.cc b/chrome/browser/chromeos/arc/arc_policy_bridge_unittest.cc index ce159b4..f04a340 100644 --- a/chrome/browser/chromeos/arc/arc_policy_bridge_unittest.cc +++ b/chrome/browser/chromeos/arc/arc_policy_bridge_unittest.cc
@@ -77,8 +77,8 @@ TEST_F(ArcPolicyBridgeTest, ArcPolicyTest) { policy_map().Set( - "ArcPolicy", policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, - policy::POLICY_SOURCE_CLOUD, + policy::key::kArcPolicy, policy::POLICY_LEVEL_MANDATORY, + policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, new base::StringValue( "{\"applications\":" "[{\"packageName\":\"com.google.android.apps.youtube.kids\"," @@ -102,22 +102,35 @@ TEST_F(ArcPolicyBridgeTest, HompageLocationTest) { // This policy will not be passed on, result should be empty. - policy_map().Set("HomepageLocation", policy::POLICY_LEVEL_MANDATORY, - policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, - new base::StringValue("http://chromium.org"), nullptr); + policy_map().Set(policy::key::kHomepageLocation, + policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, + policy::POLICY_SOURCE_CLOUD, + new base::StringValue("http://chromium.org"), + nullptr); policy_bridge()->GetPolicies(PolicyStringCallback("{}")); } +TEST_F(ArcPolicyBridgeTest, DisableScreenshotsTest) { + policy_map().Set(policy::key::kDisableScreenshots, + policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, + policy::POLICY_SOURCE_CLOUD, + new base::FundamentalValue(true), nullptr); + policy_bridge()->GetPolicies( + PolicyStringCallback("{\"screenCaptureDisabled\":true}")); +} + TEST_F(ArcPolicyBridgeTest, VideoCaptureAllowedTest) { - policy_map().Set("VideoCaptureAllowed", policy::POLICY_LEVEL_MANDATORY, - policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, + policy_map().Set(policy::key::kVideoCaptureAllowed, + policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, + policy::POLICY_SOURCE_CLOUD, new base::FundamentalValue(false), nullptr); policy_bridge()->GetPolicies( PolicyStringCallback("{\"cameraDisabled\":true}")); } TEST_F(ArcPolicyBridgeTest, AudioCaptureAllowedTest) { - policy_map().Set("AudioCaptureAllowed", policy::POLICY_LEVEL_MANDATORY, + policy_map().Set(policy::key::kAudioCaptureAllowed, + policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, new base::FundamentalValue(false), nullptr); policy_bridge()->GetPolicies( @@ -156,8 +169,8 @@ TEST_F(ArcPolicyBridgeTest, MultiplePoliciesTest) { policy_map().Set( - "ArcPolicy", policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, - policy::POLICY_SOURCE_CLOUD, + policy::key::kArcPolicy, policy::POLICY_LEVEL_MANDATORY, + policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, new base::StringValue("{\"applications\":" "[{\"packageName\":\"com.google.android.apps.youtube.kids\"," "\"installType\":\"REQUIRED\"," @@ -166,10 +179,12 @@ "}]," "\"defaultPermissionPolicy\":\"GRANT\"}"), nullptr); - policy_map().Set("HomepageLocation", policy::POLICY_LEVEL_MANDATORY, + policy_map().Set(policy::key::kHomepageLocation, + policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, new base::StringValue("http://chromium.org"), nullptr); - policy_map().Set("VideoCaptureAllowed", policy::POLICY_LEVEL_MANDATORY, + policy_map().Set(policy::key::kVideoCaptureAllowed, + policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, new base::FundamentalValue(false), nullptr); policy_bridge()->GetPolicies(PolicyStringCallback(
diff --git a/chrome/browser/history/android/android_history_provider_service.cc b/chrome/browser/history/android/android_history_provider_service.cc index 9baba26..c418746 100644 --- a/chrome/browser/history/android/android_history_provider_service.cc +++ b/chrome/browser/history/android/android_history_provider_service.cc
@@ -59,11 +59,11 @@ // Creates an instance of AndroidProviderTask using the two callback and using // type deduction. template <typename ResultType> -scoped_ptr<history::HistoryDBTask> CreateAndroidProviderTask( +std::unique_ptr<history::HistoryDBTask> CreateAndroidProviderTask( const base::Callback<ResultType(history::AndroidProviderBackend*)>& request_cb, const base::Callback<void(ResultType)>& result_cb) { - return scoped_ptr<history::HistoryDBTask>( + return std::unique_ptr<history::HistoryDBTask>( new AndroidProviderTask<ResultType>(request_cb, result_cb)); } @@ -373,7 +373,7 @@ delete statement; return; } - scoped_ptr<CloseStatementTask> task(new CloseStatementTask(statement)); + std::unique_ptr<CloseStatementTask> task(new CloseStatementTask(statement)); base::CancelableTaskTracker* tracker = task->tracker(); hs->ScheduleDBTask(std::move(task), tracker); }
diff --git a/chrome/browser/history/android/android_history_provider_service_unittest.cc b/chrome/browser/history/android/android_history_provider_service_unittest.cc index 836b3e98..c03ec13 100644 --- a/chrome/browser/history/android/android_history_provider_service_unittest.cc +++ b/chrome/browser/history/android/android_history_provider_service_unittest.cc
@@ -74,7 +74,7 @@ base::MessageLoop message_loop_; content::TestBrowserThread ui_thread_; content::TestBrowserThread file_thread_; - scoped_ptr<AndroidHistoryProviderService> service_; + std::unique_ptr<AndroidHistoryProviderService> service_; base::CancelableTaskTracker cancelable_tracker_; TestingProfile* testing_profile_;
diff --git a/chrome/browser/history/android/android_provider_backend.cc b/chrome/browser/history/android/android_provider_backend.cc index 96f42e0..67861c8 100644 --- a/chrome/browser/history/android/android_provider_backend.cc +++ b/chrome/browser/history/android/android_provider_backend.cc
@@ -115,17 +115,17 @@ } void RunNotifyFaviconChanged(HistoryBackendNotifier* notifier, - scoped_ptr<std::set<GURL>> urls) { + std::unique_ptr<std::set<GURL>> urls) { notifier->NotifyFaviconsChanged(*(urls.get()), GURL()); } void RunNotifyURLsModified(HistoryBackendNotifier* notifier, - scoped_ptr<URLRows> rows) { + std::unique_ptr<URLRows> rows) { notifier->NotifyURLsModified(*(rows.get())); } void RunNotifyURLsDeleted(HistoryBackendNotifier* notifier, - scoped_ptr<URLRows> rows) { + std::unique_ptr<URLRows> rows) { notifier->NotifyURLsDeleted(false /* all_history */, false /* expired */, *(rows.get()), @@ -360,8 +360,8 @@ } *updated_count = ids_set.size(); - scoped_ptr<URLRows> changed_urls; - scoped_ptr<std::set<GURL>> favicon; + std::unique_ptr<URLRows> changed_urls; + std::unique_ptr<std::set<GURL>> favicon; for (const auto& id : ids_set) { if (row.is_value_set_explicitly(HistoryAndBookmarkRow::TITLE) || @@ -424,10 +424,10 @@ if (!history_db_->GetURLRow(row.url_id(), &url_row)) return false; - scoped_ptr<URLRows> changed_urls(new URLRows); + std::unique_ptr<URLRows> changed_urls(new URLRows); changed_urls->push_back(url_row); - scoped_ptr<std::set<GURL>> favicon; + std::unique_ptr<std::set<GURL>> favicon; // No favicon should be changed if the thumbnail_db_ is not available. if (row.is_value_set_explicitly(HistoryAndBookmarkRow::FAVICON) && row.favicon_valid() && thumbnail_db_) { @@ -558,8 +558,8 @@ sql.append(sort_order); } - scoped_ptr<sql::Statement> statement(new sql::Statement( - db_->GetUniqueStatement(sql.c_str()))); + std::unique_ptr<sql::Statement> statement( + new sql::Statement(db_->GetUniqueStatement(sql.c_str()))); int count = 0; BindStatement(selection_args, statement.get(), &count); if (!statement->is_valid()) { @@ -1004,7 +1004,7 @@ std::ostringstream oss; oss << "url_id = " << ids[0].url_id; - scoped_ptr<AndroidStatement> statement; + std::unique_ptr<AndroidStatement> statement; statement.reset(QueryHistoryAndBookmarksInternal(projections, oss.str(), std::vector<base::string16>(), std::string())); if (!statement.get() || !statement->statement()->Step()) @@ -1022,8 +1022,8 @@ if (!history_db_->GetURLRow(ids[0].url_id, &old_url_row)) return false; - scoped_ptr<std::set<GURL>> favicons; - scoped_ptr<URLRows> deleted_rows(new URLRows); + std::unique_ptr<std::set<GURL>> favicons; + std::unique_ptr<URLRows> deleted_rows(new URLRows); deleted_rows->push_back(old_url_row); favicon_base::FaviconID favicon_id = statement->statement()->ColumnInt64(4); @@ -1098,7 +1098,7 @@ if (!history_db_->GetURLRow(new_row.url_id(), &new_url_row)) return false; - scoped_ptr<URLRows> changed_urls(new URLRows); + std::unique_ptr<URLRows> changed_urls(new URLRows); changed_urls->push_back(new_url_row); notifications->push_back( @@ -1142,8 +1142,8 @@ sql.append(sort_order); } - scoped_ptr<sql::Statement> statement(new sql::Statement( - db_->GetUniqueStatement(sql.c_str()))); + std::unique_ptr<sql::Statement> statement( + new sql::Statement(db_->GetUniqueStatement(sql.c_str()))); int count = 0; BindStatement(selection_args, statement.get(), &count); if (!statement->is_valid()) { @@ -1158,8 +1158,8 @@ const TableIDRows& urls, bool delete_bookmarks, HistoryNotifications* notifications) { - scoped_ptr<URLRows> deleted_rows; - scoped_ptr<std::set<GURL>> favicons; + std::unique_ptr<URLRows> deleted_rows; + std::unique_ptr<std::set<GURL>> favicons; for (TableIDRows::const_iterator i = urls.begin(); i != urls.end(); ++i) { URLRow url_row; if (!history_db_->GetURLRow(i->url_id, &url_row))
diff --git a/chrome/browser/history/android/android_provider_backend.h b/chrome/browser/history/android/android_provider_backend.h index 9ddb3368..61b8230 100644 --- a/chrome/browser/history/android/android_provider_backend.h +++ b/chrome/browser/history/android/android_provider_backend.h
@@ -6,6 +6,7 @@ #define CHROME_BROWSER_HISTORY_ANDROID_ANDROID_PROVIDER_BACKEND_H_ #include <list> +#include <memory> #include <set> #include "base/containers/hash_tables.h" @@ -13,7 +14,6 @@ #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/supports_user_data.h" #include "components/history/core/browser/android/android_cache_database.h" #include "components/history/core/browser/android/android_history_types.h" @@ -320,11 +320,11 @@ bool AddSearchTerm(const SearchRow& values); // SQLHandlers for different tables. - scoped_ptr<SQLHandler> urls_handler_; - scoped_ptr<SQLHandler> visit_handler_; - scoped_ptr<SQLHandler> android_urls_handler_; - scoped_ptr<SQLHandler> favicon_handler_; - scoped_ptr<SQLHandler> bookmark_model_handler_; + std::unique_ptr<SQLHandler> urls_handler_; + std::unique_ptr<SQLHandler> visit_handler_; + std::unique_ptr<SQLHandler> android_urls_handler_; + std::unique_ptr<SQLHandler> favicon_handler_; + std::unique_ptr<SQLHandler> bookmark_model_handler_; // The vector of all handlers std::vector<SQLHandler*> sql_handlers_;
diff --git a/chrome/browser/history/android/android_provider_backend_unittest.cc b/chrome/browser/history/android/android_provider_backend_unittest.cc index 5bc86e3..e572ad0 100644 --- a/chrome/browser/history/android/android_provider_backend_unittest.cc +++ b/chrome/browser/history/android/android_provider_backend_unittest.cc
@@ -76,7 +76,7 @@ void NotifyProfileError(sql::InitStatus init_status) override {} void SetInMemoryBackend( - scoped_ptr<InMemoryHistoryBackend> backend) override {} + std::unique_ptr<InMemoryHistoryBackend> backend) override {} void NotifyFaviconsChanged(const std::set<GURL>& page_urls, const GURL& icon_url) override { favicon_changed_.reset( @@ -114,9 +114,9 @@ } private: - scoped_ptr<history::URLRows> deleted_details_; - scoped_ptr<history::URLRows> modified_details_; - scoped_ptr<std::set<GURL>> favicon_changed_; + std::unique_ptr<history::URLRows> deleted_details_; + std::unique_ptr<history::URLRows> modified_details_; + std::unique_ptr<std::set<GURL>> favicon_changed_; DISALLOW_COPY_AND_ASSIGN(AndroidProviderBackendDelegate); }; @@ -158,9 +158,9 @@ } private: - scoped_ptr<history::URLRows> deleted_details_; - scoped_ptr<history::URLRows> modified_details_; - scoped_ptr<std::set<GURL>> favicon_changed_; + std::unique_ptr<history::URLRows> deleted_details_; + std::unique_ptr<history::URLRows> modified_details_; + std::unique_ptr<std::set<GURL>> favicon_changed_; DISALLOW_COPY_AND_ASSIGN(AndroidProviderBackendNotifier); }; @@ -258,8 +258,8 @@ base::MessageLoopForUI message_loop_; content::TestBrowserThread ui_thread_; content::TestBrowserThread file_thread_; - scoped_ptr<history::HistoryClient> history_client_; - scoped_ptr<history::HistoryBackendClient> history_backend_client_; + std::unique_ptr<history::HistoryClient> history_client_; + std::unique_ptr<history::HistoryBackendClient> history_backend_client_; DISALLOW_COPY_AND_ASSIGN(AndroidProviderBackendTest); }; @@ -328,12 +328,9 @@ ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); // Set url1 as bookmark. AddBookmark(url1); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); ASSERT_TRUE(backend->EnsureInitializedAndUpdated()); @@ -469,12 +466,9 @@ // Set url1 as bookmark. AddBookmark(url1); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); std::vector<HistoryAndBookmarkRow::ColumnID> projections; @@ -487,7 +481,7 @@ projections.push_back(HistoryAndBookmarkRow::FAVICON); projections.push_back(HistoryAndBookmarkRow::BOOKMARK); - scoped_ptr<AndroidStatement> statement(backend->QueryHistoryAndBookmarks( + std::unique_ptr<AndroidStatement> statement(backend->QueryHistoryAndBookmarks( projections, std::string(), std::vector<base::string16>(), std::string("url ASC"))); ASSERT_TRUE(statement->statement()->Step()); @@ -558,12 +552,9 @@ ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); ASSERT_TRUE(backend->InsertHistoryAndBookmark(row1)); EXPECT_FALSE(notifier_.deleted_details()); @@ -609,7 +600,7 @@ projections.push_back(HistoryAndBookmarkRow::FAVICON); projections.push_back(HistoryAndBookmarkRow::BOOKMARK); - scoped_ptr<AndroidStatement> statement(backend->QueryHistoryAndBookmarks( + std::unique_ptr<AndroidStatement> statement(backend->QueryHistoryAndBookmarks( projections, std::string(), std::vector<base::string16>(), std::string("url ASC"))); ASSERT_TRUE(statement->statement()->Step()); @@ -670,12 +661,9 @@ ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); ASSERT_TRUE(backend->InsertHistoryAndBookmark(row1)); ASSERT_TRUE(backend->InsertHistoryAndBookmark(row2)); @@ -719,7 +707,7 @@ projections.push_back(HistoryAndBookmarkRow::FAVICON); projections.push_back(HistoryAndBookmarkRow::BOOKMARK); - scoped_ptr<AndroidStatement> statement(backend->QueryHistoryAndBookmarks( + std::unique_ptr<AndroidStatement> statement(backend->QueryHistoryAndBookmarks( projections, std::string(), std::vector<base::string16>(), std::string("url ASC"))); ASSERT_TRUE(statement->statement()->Step()); @@ -760,21 +748,19 @@ notifier_.favicon_changed()->find(row2.url())); ASSERT_EQ(1, deleted_count); - scoped_ptr<AndroidStatement> statement1(backend->QueryHistoryAndBookmarks( - projections, std::string(), std::vector<base::string16>(), - std::string("url ASC"))); + std::unique_ptr<AndroidStatement> statement1( + backend->QueryHistoryAndBookmarks(projections, std::string(), + std::vector<base::string16>(), + std::string("url ASC"))); ASSERT_FALSE(statement1->statement()->Step()); } TEST_F(AndroidProviderBackendTest, IsValidHistoryAndBookmarkRow) { ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); // The created time and last visit time are too close to have required visit // count. @@ -862,12 +848,9 @@ ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); AndroidURLID id1 = backend->InsertHistoryAndBookmark(row1); ASSERT_TRUE(id1); @@ -1044,12 +1027,9 @@ ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); AndroidURLID id1 = backend->InsertHistoryAndBookmark(row1); ASSERT_TRUE(id1); @@ -1127,12 +1107,9 @@ ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); AndroidURLID id1 = backend->InsertHistoryAndBookmark(row1); ASSERT_TRUE(id1); @@ -1191,12 +1168,9 @@ ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); AndroidURLID id1 = backend->InsertHistoryAndBookmark(row1); ASSERT_TRUE(id1); @@ -1259,12 +1233,9 @@ TEST_F(AndroidProviderBackendTest, UpdateSearchTermTable) { ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); // Insert a keyword search item to verify if the update succeeds. HistoryAndBookmarkRow row1; row1.set_raw_url("cnn.com"); @@ -1340,12 +1311,9 @@ TEST_F(AndroidProviderBackendTest, QuerySearchTerms) { ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); // Insert a keyword search item to verify if we can find it. HistoryAndBookmarkRow row1; row1.set_raw_url("cnn.com"); @@ -1362,9 +1330,9 @@ projections.push_back(SearchRow::ID); projections.push_back(SearchRow::SEARCH_TERM); projections.push_back(SearchRow::SEARCH_TIME); - scoped_ptr<AndroidStatement> statement(backend->QuerySearchTerms( - projections, std::string(), std::vector<base::string16>(), - std::string())); + std::unique_ptr<AndroidStatement> statement( + backend->QuerySearchTerms(projections, std::string(), + std::vector<base::string16>(), std::string())); ASSERT_TRUE(statement.get()); ASSERT_TRUE(statement->statement()->Step()); EXPECT_TRUE(statement->statement()->ColumnInt64(0)); @@ -1377,12 +1345,9 @@ TEST_F(AndroidProviderBackendTest, UpdateSearchTerms) { ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); // Insert a keyword. HistoryAndBookmarkRow row1; row1.set_raw_url("cnn.com"); @@ -1402,7 +1367,7 @@ projections.push_back(SearchRow::SEARCH_TERM); std::vector<base::string16> args; args.push_back(term); - scoped_ptr<AndroidStatement> statement(backend->QuerySearchTerms( + std::unique_ptr<AndroidStatement> statement(backend->QuerySearchTerms( projections, "search = ?", args, std::string())); ASSERT_TRUE(statement.get()); ASSERT_TRUE(statement->statement()->Step()); @@ -1484,12 +1449,9 @@ TEST_F(AndroidProviderBackendTest, DeleteSearchTerms) { ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); // Insert a keyword. HistoryAndBookmarkRow row1; row1.set_raw_url("cnn.com"); @@ -1509,7 +1471,7 @@ projections.push_back(SearchRow::SEARCH_TERM); std::vector<base::string16> args; args.push_back(term); - scoped_ptr<AndroidStatement> statement(backend->QuerySearchTerms( + std::unique_ptr<AndroidStatement> statement(backend->QuerySearchTerms( projections, "search = ?", args, std::string())); ASSERT_TRUE(statement.get()); ASSERT_TRUE(statement->statement()->Step()); @@ -1593,12 +1555,9 @@ TEST_F(AndroidProviderBackendTest, InsertSearchTerm) { ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); SearchRow search_row; search_row.set_search_term(UTF8ToUTF16("google")); search_row.set_url(GURL("http://google.com")); @@ -1616,8 +1575,8 @@ std::ostringstream oss; oss << id; args.push_back(UTF8ToUTF16(oss.str())); - scoped_ptr<AndroidStatement> statement(backend->QuerySearchTerms( - projections, "_id = ?", args, std::string())); + std::unique_ptr<AndroidStatement> statement( + backend->QuerySearchTerms(projections, "_id = ?", args, std::string())); ASSERT_TRUE(statement.get()); ASSERT_TRUE(statement->statement()->Step()); EXPECT_EQ(id, statement->statement()->ColumnInt64(0)); @@ -1650,12 +1609,9 @@ ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); AndroidURLID id1 = backend->InsertHistoryAndBookmark(row1); ASSERT_TRUE(id1); @@ -1706,12 +1662,9 @@ TEST_F(AndroidProviderBackendTest, TestMultipleNestingTransaction) { ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); // Create the nested transactions. history_db_.BeginTransaction(); @@ -1759,12 +1712,9 @@ // count is 0. ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); URLRow url_row(GURL("http://www.google.com")); url_row.set_last_visit(Time::Now()); url_row.set_visit_count(0); @@ -1781,7 +1731,7 @@ projections.push_back(HistoryAndBookmarkRow::FAVICON); projections.push_back(HistoryAndBookmarkRow::BOOKMARK); - scoped_ptr<AndroidStatement> statement(backend->QueryHistoryAndBookmarks( + std::unique_ptr<AndroidStatement> statement(backend->QueryHistoryAndBookmarks( projections, std::string(), std::vector<base::string16>(), std::string("url ASC"))); @@ -1799,12 +1749,9 @@ // is 1. ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db_.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - &thumbnail_db_, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db_, &thumbnail_db_, + history_backend_client_.get(), ¬ifier_)); HistoryAndBookmarkRow row1; row1.set_raw_url("cnn.com"); row1.set_url(GURL("http://cnn.com")); @@ -1835,7 +1782,7 @@ projections.push_back(HistoryAndBookmarkRow::URL); - scoped_ptr<AndroidStatement> statement(backend->QueryHistoryAndBookmarks( + std::unique_ptr<AndroidStatement> statement(backend->QueryHistoryAndBookmarks( projections, std::string("folder=0"), std::vector<base::string16>(), std::string("url ASC"))); ASSERT_TRUE(statement->statement()->Step()); @@ -1909,12 +1856,9 @@ // Set url1 as bookmark. AddBookmark(url1); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - NULL, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend( + new AndroidProviderBackend(android_cache_db_name_, &history_db_, NULL, + history_backend_client_.get(), ¬ifier_)); std::vector<HistoryAndBookmarkRow::ColumnID> projections; @@ -1927,7 +1871,7 @@ projections.push_back(HistoryAndBookmarkRow::FAVICON); projections.push_back(HistoryAndBookmarkRow::BOOKMARK); - scoped_ptr<AndroidStatement> statement(backend->QueryHistoryAndBookmarks( + std::unique_ptr<AndroidStatement> statement(backend->QueryHistoryAndBookmarks( projections, std::string(), std::vector<base::string16>(), std::string("url ASC"))); ASSERT_TRUE(statement->statement()->Step()); @@ -1982,12 +1926,9 @@ row2.set_favicon(base::RefCountedBytes::TakeVector(&data)); ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - NULL, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend( + new AndroidProviderBackend(android_cache_db_name_, &history_db_, NULL, + history_backend_client_.get(), ¬ifier_)); ASSERT_TRUE(backend->InsertHistoryAndBookmark(row1)); EXPECT_FALSE(notifier_.deleted_details()); @@ -2049,12 +1990,9 @@ ASSERT_EQ(sql::INIT_OK, history_db.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db, - &thumbnail_db, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db, &thumbnail_db, + history_backend_client_.get(), ¬ifier_)); ASSERT_TRUE(backend->InsertHistoryAndBookmark(row1)); ASSERT_TRUE(backend->InsertHistoryAndBookmark(row2)); @@ -2067,12 +2005,9 @@ EXPECT_EQ(row1.url(), child->url()); } ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - NULL, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend( + new AndroidProviderBackend(android_cache_db_name_, &history_db_, NULL, + history_backend_client_.get(), ¬ifier_)); // Delete all rows. std::vector<base::string16> args; @@ -2104,9 +2039,10 @@ projections.push_back(HistoryAndBookmarkRow::FAVICON); projections.push_back(HistoryAndBookmarkRow::BOOKMARK); - scoped_ptr<AndroidStatement> statement1(backend->QueryHistoryAndBookmarks( - projections, std::string(), std::vector<base::string16>(), - std::string("url ASC"))); + std::unique_ptr<AndroidStatement> statement1( + backend->QueryHistoryAndBookmarks(projections, std::string(), + std::vector<base::string16>(), + std::string("url ASC"))); ASSERT_FALSE(statement1->statement()->Step()); } @@ -2125,24 +2061,18 @@ ThumbnailDatabase thumbnail_db(NULL); ASSERT_EQ(sql::INIT_OK, history_db.Init(history_db_name_)); ASSERT_EQ(sql::INIT_OK, thumbnail_db.Init(thumbnail_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db, - &thumbnail_db, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend(new AndroidProviderBackend( + android_cache_db_name_, &history_db, &thumbnail_db, + history_backend_client_.get(), ¬ifier_)); AndroidURLID id1 = backend->InsertHistoryAndBookmark(row1); ASSERT_TRUE(id1); } ASSERT_EQ(sql::INIT_OK, history_db_.Init(history_db_name_)); - scoped_ptr<AndroidProviderBackend> backend( - new AndroidProviderBackend(android_cache_db_name_, - &history_db_, - NULL, - history_backend_client_.get(), - ¬ifier_)); + std::unique_ptr<AndroidProviderBackend> backend( + new AndroidProviderBackend(android_cache_db_name_, &history_db_, NULL, + history_backend_client_.get(), ¬ifier_)); int update_count; std::vector<base::string16> update_args;
diff --git a/chrome/browser/history/android/android_urls_database_unittest.cc b/chrome/browser/history/android/android_urls_database_unittest.cc index dc1b65a..f59d983e 100644 --- a/chrome/browser/history/android/android_urls_database_unittest.cc +++ b/chrome/browser/history/android/android_urls_database_unittest.cc
@@ -39,7 +39,7 @@ protected: base::FilePath history_db_name_; - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<TestingProfile> profile_; }; // Disabled as this does not correctly set up all the tables so that migration
diff --git a/chrome/browser/history/android/sqlite_cursor.h b/chrome/browser/history/android/sqlite_cursor.h index 08d17b48..bdc60926 100644 --- a/chrome/browser/history/android/sqlite_cursor.h +++ b/chrome/browser/history/android/sqlite_cursor.h
@@ -6,12 +6,13 @@ #define CHROME_BROWSER_HISTORY_ANDROID_SQLITE_CURSOR_H_ #include <jni.h> + +#include <memory> #include <vector> #include "base/android/scoped_java_ref.h" #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "base/synchronization/waitable_event.h" #include "base/task/cancelable_task_tracker.h" @@ -189,7 +190,7 @@ AndroidHistoryProviderService* service_; // Live on UI thread. - scoped_ptr<base::CancelableTaskTracker> tracker_; + std::unique_ptr<base::CancelableTaskTracker> tracker_; // The count of result rows. int count_;
diff --git a/chrome/browser/history/android/sqlite_cursor_unittest.cc b/chrome/browser/history/android/sqlite_cursor_unittest.cc index af9e8ba7..fbcb8d9 100644 --- a/chrome/browser/history/android/sqlite_cursor_unittest.cc +++ b/chrome/browser/history/android/sqlite_cursor_unittest.cc
@@ -97,7 +97,7 @@ base::MessageLoop message_loop_; content::TestBrowserThread ui_thread_; content::TestBrowserThread file_thread_; - scoped_ptr<AndroidHistoryProviderService> service_; + std::unique_ptr<AndroidHistoryProviderService> service_; base::CancelableTaskTracker cancelable_tracker_; TestingProfile* testing_profile_; history::HistoryService* hs_;
diff --git a/chrome/browser/history/chrome_history_client.cc b/chrome/browser/history/chrome_history_client.cc index 9e1148ca..32cafc19 100644 --- a/chrome/browser/history/chrome_history_client.cc +++ b/chrome/browser/history/chrome_history_client.cc
@@ -7,6 +7,7 @@ #include "base/bind.h" #include "base/callback.h" #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/history/chrome_history_backend_client.h" #include "chrome/browser/history/history_utils.h" #include "chrome/browser/ui/profile_error_dialog.h" @@ -69,9 +70,9 @@ IDS_COULDNT_OPEN_PROFILE_ERROR : IDS_PROFILE_TOO_NEW_ERROR); } -scoped_ptr<history::HistoryBackendClient> +std::unique_ptr<history::HistoryBackendClient> ChromeHistoryClient::CreateBackendClient() { - return make_scoped_ptr(new ChromeHistoryBackendClient(bookmark_model_)); + return base::WrapUnique(new ChromeHistoryBackendClient(bookmark_model_)); } void ChromeHistoryClient::BookmarkModelChanged() {
diff --git a/chrome/browser/history/chrome_history_client.h b/chrome/browser/history/chrome_history_client.h index e939fb0a..66c0da33 100644 --- a/chrome/browser/history/chrome_history_client.h +++ b/chrome/browser/history/chrome_history_client.h
@@ -5,12 +5,12 @@ #ifndef CHROME_BROWSER_HISTORY_CHROME_HISTORY_CLIENT_H_ #define CHROME_BROWSER_HISTORY_CHROME_HISTORY_CLIENT_H_ +#include <memory> #include <set> #include "base/callback_forward.h" #include "base/callback_list.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "components/bookmarks/browser/base_bookmark_model_observer.h" #include "components/history/core/browser/history_client.h" @@ -35,7 +35,7 @@ void Shutdown() override; bool CanAddURL(const GURL& url) override; void NotifyProfileError(sql::InitStatus init_status) override; - scoped_ptr<history::HistoryBackendClient> CreateBackendClient() override; + std::unique_ptr<history::HistoryBackendClient> CreateBackendClient() override; private: // bookmarks::BaseBookmarkModelObserver implementation. @@ -59,8 +59,8 @@ base::Callback<void(const std::set<GURL>&)> on_bookmarks_removed_; // Subscription for notifications of changes to favicons. - scoped_ptr<base::CallbackList<void(const std::set<GURL>&, - const GURL&)>::Subscription> + std::unique_ptr<base::CallbackList<void(const std::set<GURL>&, + const GURL&)>::Subscription> favicons_changed_subscription_; DISALLOW_COPY_AND_ASSIGN(ChromeHistoryClient);
diff --git a/chrome/browser/history/history_browsertest.cc b/chrome/browser/history/history_browsertest.cc index 633c635..d244750 100644 --- a/chrome/browser/history/history_browsertest.cc +++ b/chrome/browser/history/history_browsertest.cc
@@ -100,7 +100,7 @@ void WaitForHistoryBackendToRun() { base::CancelableTaskTracker task_tracker; - scoped_ptr<history::HistoryDBTask> task(new WaitForHistoryTask()); + std::unique_ptr<history::HistoryDBTask> task(new WaitForHistoryTask()); history::HistoryService* history = HistoryServiceFactory::GetForProfile( GetProfile(), ServiceAccessType::EXPLICIT_ACCESS); history->ScheduleDBTask(std::move(task), &task_tracker);
diff --git a/chrome/browser/history/history_service_factory.cc b/chrome/browser/history/history_service_factory.cc index b3855219..30f9f3e 100644 --- a/chrome/browser/history/history_service_factory.cc +++ b/chrome/browser/history/history_service_factory.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/history/history_service_factory.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/history/chrome_history_client.h" #include "chrome/browser/profiles/incognito_helpers.h" @@ -77,11 +78,11 @@ KeyedService* HistoryServiceFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); - scoped_ptr<history::HistoryService> history_service( + std::unique_ptr<history::HistoryService> history_service( new history::HistoryService( - make_scoped_ptr(new ChromeHistoryClient( + base::WrapUnique(new ChromeHistoryClient( BookmarkModelFactory::GetForProfile(profile))), - make_scoped_ptr(new history::ContentVisitDelegate(profile)))); + base::WrapUnique(new history::ContentVisitDelegate(profile)))); if (!history_service->Init( history::HistoryDatabaseParamsForPath(profile->GetPath()))) { return nullptr;
diff --git a/chrome/browser/history/redirect_browsertest.cc b/chrome/browser/history/redirect_browsertest.cc index 56fb331..9db250f 100644 --- a/chrome/browser/history/redirect_browsertest.cc +++ b/chrome/browser/history/redirect_browsertest.cc
@@ -7,11 +7,12 @@ // here might indicate that WebKit changed the calls our glue layer gets in // the case of redirects. It may also mean problems with the history system. +#include <memory> + #include "base/bind.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/single_thread_task_runner.h" #include "base/strings/string16.h" #include "base/strings/string_util.h"
diff --git a/chrome/browser/metrics/chrome_browser_main_extra_parts_metrics.h b/chrome/browser/metrics/chrome_browser_main_extra_parts_metrics.h index d646d3b..f8c4bf7a 100644 --- a/chrome/browser/metrics/chrome_browser_main_extra_parts_metrics.h +++ b/chrome/browser/metrics/chrome_browser_main_extra_parts_metrics.h
@@ -7,9 +7,10 @@ #include <stdint.h> +#include <memory> + #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "build/build_config.h" #include "chrome/browser/chrome_browser_main_extra_parts.h" #include "ui/gfx/display_observer.h" @@ -59,7 +60,7 @@ bool is_screen_observer_; #if defined(USE_OZONE) || defined(USE_X11) - scoped_ptr<ui::InputDeviceEventObserver> input_device_event_observer_; + std::unique_ptr<ui::InputDeviceEventObserver> input_device_event_observer_; #endif // defined(USE_OZONE) || defined(USE_X11) DISALLOW_COPY_AND_ASSIGN(ChromeBrowserMainExtraPartsMetrics);
diff --git a/chrome/browser/metrics/chrome_browser_main_extra_parts_metrics_unittest.cc b/chrome/browser/metrics/chrome_browser_main_extra_parts_metrics_unittest.cc index d6cbf6d..27ba4bb 100644 --- a/chrome/browser/metrics/chrome_browser_main_extra_parts_metrics_unittest.cc +++ b/chrome/browser/metrics/chrome_browser_main_extra_parts_metrics_unittest.cc
@@ -4,8 +4,9 @@ #include "chrome/browser/metrics/chrome_browser_main_extra_parts_metrics.h" +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/test/histogram_tester.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/metrics/chrome_metrics_service_client.cc b/chrome/browser/metrics/chrome_metrics_service_client.cc index 9ccb73b0..b5af63a 100644 --- a/chrome/browser/metrics/chrome_metrics_service_client.cc +++ b/chrome/browser/metrics/chrome_metrics_service_client.cc
@@ -13,6 +13,7 @@ #include "base/command_line.h" #include "base/files/file_path.h" #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "base/metrics/histogram.h" #include "base/path_service.h" #include "base/rand_util.h" @@ -146,12 +147,12 @@ void RegisterInstallerFileMetricsProvider( metrics::MetricsService* metrics_service) { #if defined(OS_WIN) - scoped_ptr<metrics::FileMetricsProvider> file_metrics( - new metrics::FileMetricsProvider( - content::BrowserThread::GetBlockingPool() - ->GetTaskRunnerWithShutdownBehavior( - base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN), - g_browser_process->local_state())); + std::unique_ptr<metrics::FileMetricsProvider> file_metrics( + new metrics::FileMetricsProvider( + content::BrowserThread::GetBlockingPool() + ->GetTaskRunnerWithShutdownBehavior( + base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN), + g_browser_process->local_state())); base::FilePath program_dir; base::PathService::Get(base::DIR_EXE, &program_dir); file_metrics->RegisterFile( @@ -195,12 +196,12 @@ } // static -scoped_ptr<ChromeMetricsServiceClient> ChromeMetricsServiceClient::Create( +std::unique_ptr<ChromeMetricsServiceClient> ChromeMetricsServiceClient::Create( metrics::MetricsStateManager* state_manager, PrefService* local_state) { // Perform two-phase initialization so that |client->metrics_service_| only // receives pointers to fully constructed objects. - scoped_ptr<ChromeMetricsServiceClient> client( + std::unique_ptr<ChromeMetricsServiceClient> client( new ChromeMetricsServiceClient(state_manager)); client->Initialize(); @@ -299,14 +300,13 @@ } } -scoped_ptr<metrics::MetricsLogUploader> +std::unique_ptr<metrics::MetricsLogUploader> ChromeMetricsServiceClient::CreateUploader( const base::Callback<void(int)>& on_upload_complete) { - return scoped_ptr<metrics::MetricsLogUploader>( + return std::unique_ptr<metrics::MetricsLogUploader>( new metrics::NetMetricsLogUploader( g_browser_process->system_request_context(), - metrics::kDefaultMetricsServerUrl, - metrics::kDefaultMetricsMimeType, + metrics::kDefaultMetricsServerUrl, metrics::kDefaultMetricsMimeType, on_upload_complete)); } @@ -360,31 +360,35 @@ // Gets access to persistent metrics shared by sub-processes. metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>(new SubprocessMetricsProvider())); + std::unique_ptr<metrics::MetricsProvider>( + new SubprocessMetricsProvider())); // Register metrics providers. #if defined(ENABLE_EXTENSIONS) metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>( + std::unique_ptr<metrics::MetricsProvider>( new ExtensionsMetricsProvider(metrics_state_manager_))); #endif metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>(new metrics::NetworkMetricsProvider( - content::BrowserThread::GetBlockingPool()))); + std::unique_ptr<metrics::MetricsProvider>( + new metrics::NetworkMetricsProvider( + content::BrowserThread::GetBlockingPool()))); // Currently, we configure OmniboxMetricsProvider to not log events to UMA // if there is a single incognito session visible. In the future, it may // be worth revisiting this to still log events from non-incognito sessions. metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>(new OmniboxMetricsProvider( + std::unique_ptr<metrics::MetricsProvider>(new OmniboxMetricsProvider( base::Bind(&chrome::IsOffTheRecordSessionActive)))); metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>(new ChromeStabilityMetricsProvider( - g_browser_process->local_state()))); + std::unique_ptr<metrics::MetricsProvider>( + new ChromeStabilityMetricsProvider( + g_browser_process->local_state()))); metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>(new metrics::GPUMetricsProvider)); + std::unique_ptr<metrics::MetricsProvider>( + new metrics::GPUMetricsProvider)); metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>( + std::unique_ptr<metrics::MetricsProvider>( new metrics::ScreenInfoMetricsProvider)); RegisterInstallerFileMetricsProvider(metrics_service_.get()); @@ -394,30 +398,31 @@ content::BrowserThread::FILE), chrome::FILE_LOCAL_STATE); metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>(drive_metrics_provider_)); + std::unique_ptr<metrics::MetricsProvider>(drive_metrics_provider_)); profiler_metrics_provider_ = new metrics::ProfilerMetricsProvider(base::Bind(&IsCellularLogicEnabled)); metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>(profiler_metrics_provider_)); + std::unique_ptr<metrics::MetricsProvider>(profiler_metrics_provider_)); metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>( + std::unique_ptr<metrics::MetricsProvider>( new metrics::CallStackProfileMetricsProvider)); #if BUILDFLAG(ANDROID_JAVA_UI) metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>( + std::unique_ptr<metrics::MetricsProvider>( new AndroidMetricsProvider(g_browser_process->local_state()))); #endif // BUILDFLAG(ANDROID_JAVA_UI) #if defined(OS_WIN) google_update_metrics_provider_ = new GoogleUpdateMetricsProviderWin; metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>(google_update_metrics_provider_)); + std::unique_ptr<metrics::MetricsProvider>( + google_update_metrics_provider_)); metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>( + std::unique_ptr<metrics::MetricsProvider>( new browser_watcher::WatcherMetricsProviderWin( chrome::kBrowserExitCodesRegistryPath, content::BrowserThread::GetBlockingPool()))); @@ -427,7 +432,7 @@ plugin_metrics_provider_ = new PluginMetricsProvider(g_browser_process->local_state()); metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>(plugin_metrics_provider_)); + std::unique_ptr<metrics::MetricsProvider>(plugin_metrics_provider_)); #endif // defined(ENABLE_PLUGINS) #if defined(OS_CHROMEOS) @@ -435,23 +440,23 @@ new ChromeOSMetricsProvider; chromeos_metrics_provider_ = chromeos_metrics_provider; metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>(chromeos_metrics_provider)); + std::unique_ptr<metrics::MetricsProvider>(chromeos_metrics_provider)); SigninStatusMetricsProviderChromeOS* signin_metrics_provider_cros = new SigninStatusMetricsProviderChromeOS; metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>(signin_metrics_provider_cros)); + std::unique_ptr<metrics::MetricsProvider>(signin_metrics_provider_cros)); #endif // defined(OS_CHROMEOS) #if !defined(OS_CHROMEOS) metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>( - SigninStatusMetricsProvider::CreateInstance( - make_scoped_ptr(new ChromeSigninStatusMetricsProviderDelegate)))); + std::unique_ptr<metrics::MetricsProvider>( + SigninStatusMetricsProvider::CreateInstance(base::WrapUnique( + new ChromeSigninStatusMetricsProviderDelegate)))); #endif // !defined(OS_CHROMEOS) metrics_service_->RegisterMetricsProvider( - scoped_ptr<metrics::MetricsProvider>( + std::unique_ptr<metrics::MetricsProvider>( new sync_driver::DeviceCountMetricsProvider(base::Bind( &browser_sync::ChromeSyncClient::GetDeviceInfoTrackers))));
diff --git a/chrome/browser/metrics/chrome_metrics_service_client.h b/chrome/browser/metrics/chrome_metrics_service_client.h index 8c91871c..133b4921 100644 --- a/chrome/browser/metrics/chrome_metrics_service_client.h +++ b/chrome/browser/metrics/chrome_metrics_service_client.h
@@ -7,11 +7,11 @@ #include <stdint.h> +#include <memory> #include <string> #include "base/callback.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" #include "build/build_config.h" @@ -49,7 +49,7 @@ ~ChromeMetricsServiceClient() override; // Factory function. - static scoped_ptr<ChromeMetricsServiceClient> Create( + static std::unique_ptr<ChromeMetricsServiceClient> Create( metrics::MetricsStateManager* state_manager, PrefService* local_state); @@ -70,7 +70,7 @@ void InitializeSystemProfileMetrics( const base::Closure& done_callback) override; void CollectFinalMetricsForLog(const base::Closure& done_callback) override; - scoped_ptr<metrics::MetricsLogUploader> CreateUploader( + std::unique_ptr<metrics::MetricsLogUploader> CreateUploader( const base::Callback<void(int)>& on_upload_complete) override; base::TimeDelta GetStandardUploadInterval() override; base::string16 GetRegistryBackupKey() override; @@ -151,7 +151,7 @@ metrics::MetricsStateManager* metrics_state_manager_; // The MetricsService that |this| is a client of. - scoped_ptr<metrics::MetricsService> metrics_service_; + std::unique_ptr<metrics::MetricsService> metrics_service_; content::NotificationRegistrar registrar_; @@ -206,7 +206,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_; // Whether this client has already uploaded profiler data during this session.
diff --git a/chrome/browser/metrics/chrome_metrics_services_manager_client.cc b/chrome/browser/metrics/chrome_metrics_services_manager_client.cc index 5e6b5a306..64cb51cc 100644 --- a/chrome/browser/metrics/chrome_metrics_services_manager_client.cc +++ b/chrome/browser/metrics/chrome_metrics_services_manager_client.cc
@@ -6,6 +6,7 @@ #include "base/command_line.h" #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/metrics/chrome_metrics_service_accessor.h" #include "chrome/browser/metrics/chrome_metrics_service_client.h" @@ -42,23 +43,23 @@ ChromeMetricsServicesManagerClient::~ChromeMetricsServicesManagerClient() {} -scoped_ptr<rappor::RapporService> +std::unique_ptr<rappor::RapporService> ChromeMetricsServicesManagerClient::CreateRapporService() { DCHECK(thread_checker_.CalledOnValidThread()); - return make_scoped_ptr(new rappor::RapporService( + return base::WrapUnique(new rappor::RapporService( local_state_, base::Bind(&chrome::IsOffTheRecordSessionActive))); } -scoped_ptr<variations::VariationsService> +std::unique_ptr<variations::VariationsService> ChromeMetricsServicesManagerClient::CreateVariationsService() { DCHECK(thread_checker_.CalledOnValidThread()); return variations::VariationsService::Create( - make_scoped_ptr(new ChromeVariationsServiceClient()), local_state_, + base::WrapUnique(new ChromeVariationsServiceClient()), local_state_, GetMetricsStateManager(), switches::kDisableBackgroundNetworking, chrome_variations::CreateUIStringOverrider()); } -scoped_ptr<metrics::MetricsServiceClient> +std::unique_ptr<metrics::MetricsServiceClient> ChromeMetricsServicesManagerClient::CreateMetricsServiceClient() { DCHECK(thread_checker_.CalledOnValidThread()); return ChromeMetricsServiceClient::Create(GetMetricsStateManager(),
diff --git a/chrome/browser/metrics/chrome_metrics_services_manager_client.h b/chrome/browser/metrics/chrome_metrics_services_manager_client.h index 3186606..d2b8eca 100644 --- a/chrome/browser/metrics/chrome_metrics_services_manager_client.h +++ b/chrome/browser/metrics/chrome_metrics_services_manager_client.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_METRICS_CHROME_METRICS_SERVICES_MANAGER_CLIENT_H_ #define CHROME_BROWSER_METRICS_CHROME_METRICS_SERVICES_MANAGER_CLIENT_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/threading/thread_checker.h" #include "chrome/browser/safe_browsing/safe_browsing_service.h" #include "components/metrics_services_manager/metrics_services_manager_client.h" @@ -26,9 +27,10 @@ private: // metrics_services_manager::MetricsServicesManagerClient: - scoped_ptr<rappor::RapporService> CreateRapporService() override; - scoped_ptr<variations::VariationsService> CreateVariationsService() override; - scoped_ptr<metrics::MetricsServiceClient> CreateMetricsServiceClient() + std::unique_ptr<rappor::RapporService> CreateRapporService() override; + std::unique_ptr<variations::VariationsService> CreateVariationsService() + override; + std::unique_ptr<metrics::MetricsServiceClient> CreateMetricsServiceClient() override; net::URLRequestContextGetter* GetURLRequestContext() override; bool IsSafeBrowsingEnabled(const base::Closure& on_update_callback) override; @@ -40,7 +42,7 @@ metrics::MetricsStateManager* GetMetricsStateManager(); // MetricsStateManager which is passed as a parameter to service constructors. - scoped_ptr<metrics::MetricsStateManager> metrics_state_manager_; + std::unique_ptr<metrics::MetricsStateManager> metrics_state_manager_; // Ensures that all functions are called from the same thread. base::ThreadChecker thread_checker_; @@ -49,7 +51,7 @@ PrefService* local_state_; // Subscription to SafeBrowsing service state changes. - scoped_ptr<safe_browsing::SafeBrowsingService::StateSubscription> + std::unique_ptr<safe_browsing::SafeBrowsingService::StateSubscription> sb_state_subscription_; DISALLOW_COPY_AND_ASSIGN(ChromeMetricsServicesManagerClient);
diff --git a/chrome/browser/metrics/chrome_stability_metrics_provider_unittest.cc b/chrome/browser/metrics/chrome_stability_metrics_provider_unittest.cc index fa454c18..a23da90 100644 --- a/chrome/browser/metrics/chrome_stability_metrics_provider_unittest.cc +++ b/chrome/browser/metrics/chrome_stability_metrics_provider_unittest.cc
@@ -39,7 +39,7 @@ TestingPrefServiceSimple* prefs() { return prefs_.get(); } private: - scoped_ptr<TestingPrefServiceSimple> prefs_; + std::unique_ptr<TestingPrefServiceSimple> prefs_; content::TestBrowserThreadBundle thread_bundle_; DISALLOW_COPY_AND_ASSIGN(ChromeStabilityMetricsProviderTest); @@ -69,7 +69,7 @@ TEST_F(ChromeStabilityMetricsProviderTest, NotificationObserver) { ChromeStabilityMetricsProvider provider(prefs()); - scoped_ptr<TestingProfileManager> profile_manager( + std::unique_ptr<TestingProfileManager> profile_manager( new TestingProfileManager(TestingBrowserProcess::GetGlobal())); EXPECT_TRUE(profile_manager->SetUp()); @@ -77,7 +77,7 @@ TestingProfile* profile( profile_manager->CreateTestingProfile("StabilityTestProfile")); - scoped_ptr<content::MockRenderProcessHostFactory> rph_factory( + std::unique_ptr<content::MockRenderProcessHostFactory> rph_factory( new content::MockRenderProcessHostFactory()); scoped_refptr<content::SiteInstance> site_instance( content::SiteInstance::Create(profile));
diff --git a/chrome/browser/metrics/chromeos_metrics_provider.h b/chrome/browser/metrics/chromeos_metrics_provider.h index 55d96c2..c39d2d2e 100644 --- a/chrome/browser/metrics/chromeos_metrics_provider.h +++ b/chrome/browser/metrics/chromeos_metrics_provider.h
@@ -91,7 +91,7 @@ metrics::PerfProvider perf_provider_; // Enables runtime memory leak detection and gets notified of leak reports. - scoped_ptr<metrics::LeakDetectorController> leak_detector_controller_; + std::unique_ptr<metrics::LeakDetectorController> leak_detector_controller_; // Bluetooth Adapter instance for collecting information about paired devices. scoped_refptr<device::BluetoothAdapter> adapter_;
diff --git a/chrome/browser/metrics/chromeos_metrics_provider_unittest.cc b/chrome/browser/metrics/chromeos_metrics_provider_unittest.cc index 087b98e..4094f37 100644 --- a/chrome/browser/metrics/chromeos_metrics_provider_unittest.cc +++ b/chrome/browser/metrics/chromeos_metrics_provider_unittest.cc
@@ -64,33 +64,33 @@ #endif // Set up the fake Bluetooth environment, - scoped_ptr<BluezDBusManagerSetter> bluez_dbus_setter = + std::unique_ptr<BluezDBusManagerSetter> bluez_dbus_setter = BluezDBusManager::GetSetterForTesting(); bluez_dbus_setter->SetBluetoothAdapterClient( - scoped_ptr<BluetoothAdapterClient>(new FakeBluetoothAdapterClient)); + std::unique_ptr<BluetoothAdapterClient>( + new FakeBluetoothAdapterClient)); bluez_dbus_setter->SetBluetoothDeviceClient( - scoped_ptr<BluetoothDeviceClient>(new FakeBluetoothDeviceClient)); + std::unique_ptr<BluetoothDeviceClient>(new FakeBluetoothDeviceClient)); bluez_dbus_setter->SetBluetoothGattCharacteristicClient( - scoped_ptr<BluetoothGattCharacteristicClient>( + std::unique_ptr<BluetoothGattCharacteristicClient>( new FakeBluetoothGattCharacteristicClient)); bluez_dbus_setter->SetBluetoothGattDescriptorClient( - scoped_ptr<BluetoothGattDescriptorClient>( + std::unique_ptr<BluetoothGattDescriptorClient>( new FakeBluetoothGattDescriptorClient)); bluez_dbus_setter->SetBluetoothGattServiceClient( - scoped_ptr<BluetoothGattServiceClient>( + std::unique_ptr<BluetoothGattServiceClient>( new FakeBluetoothGattServiceClient)); bluez_dbus_setter->SetBluetoothInputClient( - scoped_ptr<BluetoothInputClient>(new FakeBluetoothInputClient)); + std::unique_ptr<BluetoothInputClient>(new FakeBluetoothInputClient)); bluez_dbus_setter->SetBluetoothAgentManagerClient( - scoped_ptr<BluetoothAgentManagerClient>( + std::unique_ptr<BluetoothAgentManagerClient>( new FakeBluetoothAgentManagerClient)); // Set up a PowerManagerClient instance for PerfProvider. - scoped_ptr<DBusThreadManagerSetter> dbus_setter = + std::unique_ptr<DBusThreadManagerSetter> dbus_setter = DBusThreadManager::GetSetterForTesting(); - dbus_setter->SetPowerManagerClient( - scoped_ptr<PowerManagerClient>( - PowerManagerClient::Create(STUB_DBUS_CLIENT_IMPLEMENTATION))); + dbus_setter->SetPowerManagerClient(std::unique_ptr<PowerManagerClient>( + PowerManagerClient::Create(STUB_DBUS_CLIENT_IMPLEMENTATION))); // Grab pointers to members of the thread manager for easier testing. fake_bluetooth_adapter_client_ = static_cast<FakeBluetoothAdapterClient*>(
diff --git a/chrome/browser/metrics/extensions_metrics_provider.cc b/chrome/browser/metrics/extensions_metrics_provider.cc index 80c0443..75c3bfb 100644 --- a/chrome/browser/metrics/extensions_metrics_provider.cc +++ b/chrome/browser/metrics/extensions_metrics_provider.cc
@@ -7,11 +7,11 @@ #include <stddef.h> #include <algorithm> +#include <memory> #include <set> #include <vector> #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/stringprintf.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/install_verifier.h" @@ -158,13 +158,13 @@ return cached_profile_; } -scoped_ptr<extensions::ExtensionSet> +std::unique_ptr<extensions::ExtensionSet> ExtensionsMetricsProvider::GetInstalledExtensions(Profile* profile) { if (profile) { return extensions::ExtensionRegistry::Get(profile) ->GenerateInstalledExtensionsSet(); } - return scoped_ptr<extensions::ExtensionSet>(); + return std::unique_ptr<extensions::ExtensionSet>(); } uint64_t ExtensionsMetricsProvider::GetClientID() { @@ -195,7 +195,7 @@ extensions::InstallVerifier* verifier = extensions::InstallVerifier::Get(profiles[i]); - scoped_ptr<extensions::ExtensionSet> extensions( + std::unique_ptr<extensions::ExtensionSet> extensions( GetInstalledExtensions(profiles[i])); if (!extensions) continue; @@ -216,7 +216,7 @@ // profiles. Profile* profile = GetMetricsProfile(); - scoped_ptr<extensions::ExtensionSet> extensions( + std::unique_ptr<extensions::ExtensionSet> extensions( GetInstalledExtensions(profile)); if (!extensions) return;
diff --git a/chrome/browser/metrics/extensions_metrics_provider.h b/chrome/browser/metrics/extensions_metrics_provider.h index 50ef6f2e..8bdb8fb3 100644 --- a/chrome/browser/metrics/extensions_metrics_provider.h +++ b/chrome/browser/metrics/extensions_metrics_provider.h
@@ -7,10 +7,10 @@ #include <stdint.h> +#include <memory> #include <string> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "components/metrics/metrics_provider.h" class Profile; @@ -43,7 +43,7 @@ // Exposed for the sake of mocking in test code. // Retrieves the set of extensions installed in the given |profile|. - virtual scoped_ptr<extensions::ExtensionSet> GetInstalledExtensions( + virtual std::unique_ptr<extensions::ExtensionSet> GetInstalledExtensions( Profile* profile); // Retrieves the client ID.
diff --git a/chrome/browser/metrics/extensions_metrics_provider_unittest.cc b/chrome/browser/metrics/extensions_metrics_provider_unittest.cc index bd6b4472..934e2bf 100644 --- a/chrome/browser/metrics/extensions_metrics_provider_unittest.cc +++ b/chrome/browser/metrics/extensions_metrics_provider_unittest.cc
@@ -6,9 +6,9 @@ #include <stdint.h> +#include <memory> #include <string> -#include "base/memory/scoped_ptr.h" #include "components/metrics/client_info.h" #include "components/metrics/metrics_service.h" #include "components/metrics/metrics_state_manager.h" @@ -28,8 +28,8 @@ void StoreNoClientInfoBackup(const metrics::ClientInfo& /* client_info */) { } -scoped_ptr<metrics::ClientInfo> ReturnNoBackup() { - return scoped_ptr<metrics::ClientInfo>(); +std::unique_ptr<metrics::ClientInfo> ReturnNoBackup() { + return std::unique_ptr<metrics::ClientInfo>(); } class TestExtensionsMetricsProvider : public ExtensionsMetricsProvider { @@ -44,9 +44,9 @@ protected: // Override the GetInstalledExtensions method to return a set of extensions // for tests. - scoped_ptr<extensions::ExtensionSet> GetInstalledExtensions( + std::unique_ptr<extensions::ExtensionSet> GetInstalledExtensions( Profile* profile) override { - scoped_ptr<extensions::ExtensionSet> extensions( + std::unique_ptr<extensions::ExtensionSet> extensions( new extensions::ExtensionSet()); scoped_refptr<const extensions::Extension> extension; extension = extensions::ExtensionBuilder() @@ -109,12 +109,10 @@ metrics::SystemProfileProto system_profile; TestingPrefServiceSimple local_state; metrics::MetricsService::RegisterPrefs(local_state.registry()); - scoped_ptr<metrics::MetricsStateManager> metrics_state_manager( + std::unique_ptr<metrics::MetricsStateManager> metrics_state_manager( metrics::MetricsStateManager::Create( - &local_state, - base::Bind(&IsMetricsReportingEnabled), - base::Bind(&StoreNoClientInfoBackup), - base::Bind(&ReturnNoBackup))); + &local_state, base::Bind(&IsMetricsReportingEnabled), + base::Bind(&StoreNoClientInfoBackup), base::Bind(&ReturnNoBackup))); TestExtensionsMetricsProvider extension_metrics(metrics_state_manager.get()); extension_metrics.ProvideSystemProfileMetrics(&system_profile); ASSERT_EQ(2, system_profile.occupied_extension_bucket_size());
diff --git a/chrome/browser/metrics/first_web_contents_profiler.h b/chrome/browser/metrics/first_web_contents_profiler.h index e6e5dbf4..83beccc 100644 --- a/chrome/browser/metrics/first_web_contents_profiler.h +++ b/chrome/browser/metrics/first_web_contents_profiler.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_METRICS_FIRST_WEB_CONTENTS_PROFILER_H_ #define CHROME_BROWSER_METRICS_FIRST_WEB_CONTENTS_PROFILER_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "content/public/browser/web_contents_observer.h" namespace content {
diff --git a/chrome/browser/metrics/metrics_memory_details_browsertest.cc b/chrome/browser/metrics/metrics_memory_details_browsertest.cc index e06a665..7a2eeaf 100644 --- a/chrome/browser/metrics/metrics_memory_details_browsertest.cc +++ b/chrome/browser/metrics/metrics_memory_details_browsertest.cc
@@ -54,7 +54,7 @@ // Memory.Browser histogram should have a single non-0 sample recorded. histogram_tester.ExpectTotalCount("Memory.Browser", 1); - scoped_ptr<base::HistogramSamples> samples( + std::unique_ptr<base::HistogramSamples> samples( histogram_tester.GetHistogramSamplesSinceCreation("Memory.Browser")); ASSERT_TRUE(samples); EXPECT_NE(0, samples->sum());
diff --git a/chrome/browser/metrics/perf/perf_provider_chromeos.cc b/chrome/browser/metrics/perf/perf_provider_chromeos.cc index cb1769a..443714a6 100644 --- a/chrome/browser/metrics/perf/perf_provider_chromeos.cc +++ b/chrome/browser/metrics/perf/perf_provider_chromeos.cc
@@ -384,8 +384,8 @@ } void PerfProvider::ParseOutputProtoIfValid( - scoped_ptr<WindowedIncognitoObserver> incognito_observer, - scoped_ptr<SampledProfile> sampled_profile, + std::unique_ptr<WindowedIncognitoObserver> incognito_observer, + std::unique_ptr<SampledProfile> sampled_profile, int result, const std::vector<uint8_t>& perf_data, const std::vector<uint8_t>& perf_stat) { @@ -553,7 +553,7 @@ } void PerfProvider::CollectIfNecessary( - scoped_ptr<SampledProfile> sampled_profile) { + std::unique_ptr<SampledProfile> sampled_profile) { DCHECK(CalledOnValidThread()); // Schedule another interval collection. This call makes sense regardless of @@ -580,7 +580,7 @@ return; } - scoped_ptr<WindowedIncognitoObserver> incognito_observer( + std::unique_ptr<WindowedIncognitoObserver> incognito_observer( new WindowedIncognitoObserver); chromeos::DebugDaemonClient* client = @@ -597,7 +597,7 @@ } void PerfProvider::DoPeriodicCollection() { - scoped_ptr<SampledProfile> sampled_profile(new SampledProfile); + std::unique_ptr<SampledProfile> sampled_profile(new SampledProfile); sampled_profile->set_trigger_event(SampledProfile::PERIODIC_COLLECTION); CollectIfNecessary(std::move(sampled_profile)); @@ -607,7 +607,7 @@ const base::TimeDelta& sleep_duration, const base::TimeDelta& time_after_resume) { // Fill out a SampledProfile protobuf that will contain the collected data. - scoped_ptr<SampledProfile> sampled_profile(new SampledProfile); + std::unique_ptr<SampledProfile> sampled_profile(new SampledProfile); sampled_profile->set_trigger_event(SampledProfile::RESUME_FROM_SUSPEND); sampled_profile->set_suspend_duration_ms(sleep_duration.InMilliseconds()); sampled_profile->set_ms_after_resume(time_after_resume.InMilliseconds()); @@ -619,7 +619,7 @@ const base::TimeDelta& time_after_restore, int num_tabs_restored) { // Fill out a SampledProfile protobuf that will contain the collected data. - scoped_ptr<SampledProfile> sampled_profile(new SampledProfile); + std::unique_ptr<SampledProfile> sampled_profile(new SampledProfile); sampled_profile->set_trigger_event(SampledProfile::RESTORE_SESSION); sampled_profile->set_ms_after_restore(time_after_restore.InMilliseconds()); sampled_profile->set_num_tabs_restored(num_tabs_restored);
diff --git a/chrome/browser/metrics/perf/perf_provider_chromeos.h b/chrome/browser/metrics/perf/perf_provider_chromeos.h index 68d1cd7..3693c6db 100644 --- a/chrome/browser/metrics/perf/perf_provider_chromeos.h +++ b/chrome/browser/metrics/perf/perf_provider_chromeos.h
@@ -132,8 +132,8 @@ // |result| is the return value of running perf/quipper. It is 0 if successful // and nonzero if not successful. void ParseOutputProtoIfValid( - scoped_ptr<WindowedIncognitoObserver> incognito_observer, - scoped_ptr<SampledProfile> sampled_profile, + std::unique_ptr<WindowedIncognitoObserver> incognito_observer, + std::unique_ptr<SampledProfile> sampled_profile, int result, const std::vector<uint8_t>& perf_data, const std::vector<uint8_t>& perf_stat); @@ -194,7 +194,7 @@ // Collects perf data for a given |trigger_event|. Calls perf via the ChromeOS // debug daemon's dbus interface. - void CollectIfNecessary(scoped_ptr<SampledProfile> sampled_profile); + void CollectIfNecessary(std::unique_ptr<SampledProfile> sampled_profile); // Collects perf data on a repeating basis by calling CollectIfNecessary() and // reschedules it to be collected again.
diff --git a/chrome/browser/metrics/perf/perf_provider_chromeos_unittest.cc b/chrome/browser/metrics/perf/perf_provider_chromeos_unittest.cc index 3edf1aa..91cb172 100644 --- a/chrome/browser/metrics/perf/perf_provider_chromeos_unittest.cc +++ b/chrome/browser/metrics/perf/perf_provider_chromeos_unittest.cc
@@ -5,12 +5,13 @@ #include "chrome/browser/metrics/perf/perf_provider_chromeos.h" #include <stdint.h> + +#include <memory> #include <string> #include <utility> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/metrics/field_trial.h" #include "base/test/test_simple_task_runner.h" #include "base/thread_task_runner_handle.h" @@ -108,12 +109,12 @@ class TestIncognitoObserver : public WindowedIncognitoObserver { public: // Factory function to create a TestIncognitoObserver object contained in a - // scoped_ptr<WindowedIncognitoObserver> object. |incognito_launched| + // std::unique_ptr<WindowedIncognitoObserver> object. |incognito_launched| // simulates the presence of an open incognito window, or the lack thereof. // Used for passing observers to ParseOutputProtoIfValid(). - static scoped_ptr<WindowedIncognitoObserver> CreateWithIncognitoLaunched( + static std::unique_ptr<WindowedIncognitoObserver> CreateWithIncognitoLaunched( bool incognito_launched) { - scoped_ptr<TestIncognitoObserver> observer(new TestIncognitoObserver); + std::unique_ptr<TestIncognitoObserver> observer(new TestIncognitoObserver); observer->set_incognito_launched(incognito_launched); return std::move(observer); } @@ -173,7 +174,7 @@ } protected: - scoped_ptr<TestPerfProvider> perf_provider_; + std::unique_ptr<TestPerfProvider> perf_provider_; scoped_refptr<base::TestSimpleTaskRunner> task_runner_; base::ThreadTaskRunnerHandle task_runner_handle_; @@ -202,7 +203,7 @@ } TEST_F(PerfProviderTest, NoPerfData) { - scoped_ptr<SampledProfile> sampled_profile(new SampledProfile); + std::unique_ptr<SampledProfile> sampled_profile(new SampledProfile); sampled_profile->set_trigger_event(SampledProfile::PERIODIC_COLLECTION); perf_provider_->ParseOutputProtoIfValid( @@ -215,7 +216,7 @@ } TEST_F(PerfProviderTest, PerfDataProtoOnly) { - scoped_ptr<SampledProfile> sampled_profile(new SampledProfile); + std::unique_ptr<SampledProfile> sampled_profile(new SampledProfile); sampled_profile->set_trigger_event(SampledProfile::PERIODIC_COLLECTION); perf_provider_->ParseOutputProtoIfValid( @@ -238,7 +239,7 @@ } TEST_F(PerfProviderTest, PerfStatProtoOnly) { - scoped_ptr<SampledProfile> sampled_profile(new SampledProfile); + std::unique_ptr<SampledProfile> sampled_profile(new SampledProfile); sampled_profile->set_trigger_event(SampledProfile::PERIODIC_COLLECTION); perf_provider_->ParseOutputProtoIfValid( @@ -261,7 +262,7 @@ } TEST_F(PerfProviderTest, BothPerfDataProtoAndPerfStatProto) { - scoped_ptr<SampledProfile> sampled_profile(new SampledProfile); + std::unique_ptr<SampledProfile> sampled_profile(new SampledProfile); sampled_profile->set_trigger_event(SampledProfile::PERIODIC_COLLECTION); perf_provider_->ParseOutputProtoIfValid( @@ -276,7 +277,7 @@ } TEST_F(PerfProviderTest, InvalidPerfOutputResult) { - scoped_ptr<SampledProfile> sampled_profile(new SampledProfile); + std::unique_ptr<SampledProfile> sampled_profile(new SampledProfile); sampled_profile->set_trigger_event(SampledProfile::PERIODIC_COLLECTION); perf_provider_->ParseOutputProtoIfValid( @@ -292,7 +293,7 @@ // Change |sampled_profile| between calls to ParseOutputProtoIfValid(). TEST_F(PerfProviderTest, MultipleCalls) { - scoped_ptr<SampledProfile> sampled_profile(new SampledProfile); + std::unique_ptr<SampledProfile> sampled_profile(new SampledProfile); sampled_profile->set_trigger_event(SampledProfile::PERIODIC_COLLECTION); perf_provider_->ParseOutputProtoIfValid( @@ -367,7 +368,7 @@ // Simulate opening and closing of incognito window in between calls to // ParseOutputProtoIfValid(). TEST_F(PerfProviderTest, IncognitoWindowOpened) { - scoped_ptr<SampledProfile> sampled_profile(new SampledProfile); + std::unique_ptr<SampledProfile> sampled_profile(new SampledProfile); sampled_profile->set_trigger_event(SampledProfile::PERIODIC_COLLECTION); perf_provider_->ParseOutputProtoIfValid(
diff --git a/chrome/browser/metrics/plugin_metrics_provider_unittest.cc b/chrome/browser/metrics/plugin_metrics_provider_unittest.cc index 442373d..0bc4f23 100644 --- a/chrome/browser/metrics/plugin_metrics_provider_unittest.cc +++ b/chrome/browser/metrics/plugin_metrics_provider_unittest.cc
@@ -48,7 +48,7 @@ } private: - scoped_ptr<TestingPrefServiceSimple> prefs_; + std::unique_ptr<TestingPrefServiceSimple> prefs_; DISALLOW_COPY_AND_ASSIGN(PluginMetricsProviderTest); }; @@ -88,7 +88,7 @@ EXPECT_TRUE(system_profile.plugin(1).is_pepper()); // Now set some plugin stability stats for p2 and verify they're recorded. - scoped_ptr<base::DictionaryValue> plugin_dict(new base::DictionaryValue); + std::unique_ptr<base::DictionaryValue> plugin_dict(new base::DictionaryValue); plugin_dict->SetString(prefs::kStabilityPluginName, "p2"); plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, 1); plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, 2);
diff --git a/chrome/browser/metrics/thread_watcher.h b/chrome/browser/metrics/thread_watcher.h index af5ec1f..6bf8d15c 100644 --- a/chrome/browser/metrics/thread_watcher.h +++ b/chrome/browser/metrics/thread_watcher.h
@@ -553,7 +553,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(ThreadWatcherObserver); @@ -662,7 +662,7 @@ private: // A profiler that periodically samples stack traces. Used to sample jank // behavior. - scoped_ptr<base::StackSamplingProfiler> sampling_profiler_; + std::unique_ptr<base::StackSamplingProfiler> sampling_profiler_; // We use this factory during creation and starting timer. base::WeakPtrFactory<JankTimeBomb> weak_ptr_factory_;
diff --git a/chrome/browser/metrics/thread_watcher_android_unittest.cc b/chrome/browser/metrics/thread_watcher_android_unittest.cc index a80e7ef4..1bcc58bc 100644 --- a/chrome/browser/metrics/thread_watcher_android_unittest.cc +++ b/chrome/browser/metrics/thread_watcher_android_unittest.cc
@@ -45,8 +45,7 @@ base::MessageLoopForUI message_loop_for_ui; content::TestBrowserThread ui_thread(BrowserThread::UI, &message_loop_for_ui); - - scoped_ptr<WatchDogThread> watchdog_thread_(new WatchDogThread()); + std::unique_ptr<WatchDogThread> watchdog_thread_(new WatchDogThread()); watchdog_thread_->StartAndWaitForTesting(); EXPECT_FALSE(ThreadWatcherList::g_thread_watcher_list_);
diff --git a/chrome/browser/metrics/thread_watcher_unittest.cc b/chrome/browser/metrics/thread_watcher_unittest.cc index 972e1e0..fbe49751e 100644 --- a/chrome/browser/metrics/thread_watcher_unittest.cc +++ b/chrome/browser/metrics/thread_watcher_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/metrics/thread_watcher.h" + #include <math.h> #include <stdint.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/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" @@ -23,7 +26,6 @@ #include "base/threading/platform_thread.h" #include "base/time/time.h" #include "build/build_config.h" -#include "chrome/browser/metrics/thread_watcher.h" #include "chrome/common/chrome_switches.h" #include "content/public/test/test_browser_thread.h" #include "testing/gtest/include/gtest/gtest.h" @@ -320,9 +322,9 @@ base::Lock lock_; base::ConditionVariable setup_complete_; bool initialized_; - scoped_ptr<content::TestBrowserThread> db_thread_; - scoped_ptr<content::TestBrowserThread> io_thread_; - scoped_ptr<WatchDogThread> watchdog_thread_; + std::unique_ptr<content::TestBrowserThread> db_thread_; + std::unique_ptr<content::TestBrowserThread> io_thread_; + std::unique_ptr<WatchDogThread> watchdog_thread_; }; // Define static constants. @@ -691,7 +693,7 @@ base::MessageLoopForUI message_loop_for_ui; content::TestBrowserThread ui_thread(BrowserThread::UI, &message_loop_for_ui); - scoped_ptr<WatchDogThread> watchdog_thread_(new WatchDogThread()); + std::unique_ptr<WatchDogThread> watchdog_thread_(new WatchDogThread()); watchdog_thread_->StartAndWaitForTesting(); // See http://crbug.com/347887. @@ -794,7 +796,7 @@ event->Wait(); } - scoped_ptr<WatchDogThread> watchdog_thread_; + std::unique_ptr<WatchDogThread> watchdog_thread_; DISALLOW_COPY_AND_ASSIGN(JankTimeBombTest); };
diff --git a/chrome/browser/policy/chrome_browser_policy_connector.cc b/chrome/browser/policy/chrome_browser_policy_connector.cc index cd5f1dc..888f13a 100644 --- a/chrome/browser/policy/chrome_browser_policy_connector.cc +++ b/chrome/browser/policy/chrome_browser_policy_connector.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/policy/chrome_browser_policy_connector.h" +#include <memory> #include <string> #include <utility> @@ -11,7 +12,7 @@ #include "base/command_line.h" #include "base/files/file_path.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/path_service.h" #include "base/strings/sys_string_conversions.h" #include "build/build_config.h" @@ -68,7 +69,7 @@ : BrowserPolicyConnector(base::Bind(&BuildHandlerList)) { ConfigurationPolicyProvider* platform_provider = CreatePlatformProvider(); if (platform_provider) - SetPlatformPolicyProvider(make_scoped_ptr(platform_provider)); + SetPlatformPolicyProvider(base::WrapUnique(platform_provider)); } ChromeBrowserPolicyConnector::~ChromeBrowserPolicyConnector() {} @@ -80,10 +81,10 @@ // sure that threading is ready at this point. DCHECK(BrowserThread::IsThreadInitialized(BrowserThread::FILE)); - scoped_ptr<DeviceManagementService::Configuration> configuration( + std::unique_ptr<DeviceManagementService::Configuration> configuration( new DeviceManagementServiceConfiguration( BrowserPolicyConnector::GetDeviceManagementUrl())); - scoped_ptr<DeviceManagementService> device_management_service( + std::unique_ptr<DeviceManagementService> device_management_service( new DeviceManagementService(std::move(configuration))); device_management_service->ScheduleInitialization( kServiceInitializationStartupDelay); @@ -94,23 +95,21 @@ ConfigurationPolicyProvider* ChromeBrowserPolicyConnector::CreatePlatformProvider() { #if defined(OS_WIN) - scoped_ptr<AsyncPolicyLoader> loader(PolicyLoaderWin::Create( + std::unique_ptr<AsyncPolicyLoader> loader(PolicyLoaderWin::Create( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE), kRegistryChromePolicyKey)); return new AsyncPolicyProvider(GetSchemaRegistry(), std::move(loader)); #elif defined(OS_MACOSX) - scoped_ptr<AsyncPolicyLoader> loader(new PolicyLoaderMac( + std::unique_ptr<AsyncPolicyLoader> loader(new PolicyLoaderMac( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE), - GetManagedPolicyPath(), - new MacPreferences())); + GetManagedPolicyPath(), new MacPreferences())); return new AsyncPolicyProvider(GetSchemaRegistry(), std::move(loader)); #elif defined(OS_POSIX) && !defined(OS_ANDROID) base::FilePath config_dir_path; if (PathService::Get(chrome::DIR_POLICY_FILES, &config_dir_path)) { - scoped_ptr<AsyncPolicyLoader> loader(new ConfigDirPolicyLoader( + std::unique_ptr<AsyncPolicyLoader> loader(new ConfigDirPolicyLoader( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE), - config_dir_path, - POLICY_SCOPE_MACHINE)); + config_dir_path, POLICY_SCOPE_MACHINE)); return new AsyncPolicyProvider(GetSchemaRegistry(), std::move(loader)); } else { return NULL;
diff --git a/chrome/browser/policy/cloud/cloud_policy_browsertest.cc b/chrome/browser/policy/cloud/cloud_policy_browsertest.cc index b660aa0..d307475 100644 --- a/chrome/browser/policy/cloud/cloud_policy_browsertest.cc +++ b/chrome/browser/policy/cloud/cloud_policy_browsertest.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 <memory> + #include "base/callback.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/stringprintf.h" @@ -81,10 +83,10 @@ namespace { -scoped_ptr<KeyedService> BuildFakeProfileInvalidationProvider( +std::unique_ptr<KeyedService> BuildFakeProfileInvalidationProvider( content::BrowserContext* context) { - return make_scoped_ptr(new invalidation::ProfileInvalidationProvider( - scoped_ptr<invalidation::InvalidationService>( + return base::WrapUnique(new invalidation::ProfileInvalidationProvider( + std::unique_ptr<invalidation::InvalidationService>( new invalidation::FakeInvalidationService))); } @@ -380,7 +382,7 @@ void OnPolicyServiceInitialized(PolicyDomain domain) override {} base::ScopedTempDir temp_dir_; - scoped_ptr<LocalPolicyTestServer> test_server_; + std::unique_ptr<LocalPolicyTestServer> test_server_; base::FilePath user_policy_key_file_; base::Closure on_policy_updated_; };
diff --git a/chrome/browser/policy/cloud/cloud_policy_invalidator.cc b/chrome/browser/policy/cloud/cloud_policy_invalidator.cc index f70e424..02656751 100644 --- a/chrome/browser/policy/cloud/cloud_policy_invalidator.cc +++ b/chrome/browser/policy/cloud/cloud_policy_invalidator.cc
@@ -36,7 +36,7 @@ enterprise_management::DeviceRegisterRequest::Type type, CloudPolicyCore* core, const scoped_refptr<base::SequencedTaskRunner>& task_runner, - scoped_ptr<base::Clock> clock, + std::unique_ptr<base::Clock> clock, int64_t highest_handled_invalidation_version) : state_(UNINITIALIZED), type_(type),
diff --git a/chrome/browser/policy/cloud/cloud_policy_invalidator.h b/chrome/browser/policy/cloud/cloud_policy_invalidator.h index 8932c4e7..0416dcb 100644 --- a/chrome/browser/policy/cloud/cloud_policy_invalidator.h +++ b/chrome/browser/policy/cloud/cloud_policy_invalidator.h
@@ -7,6 +7,7 @@ #include <stdint.h> +#include <memory> #include <string> #include "base/callback.h" @@ -14,7 +15,6 @@ #include "base/logging.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" #include "components/invalidation/public/invalidation.h" @@ -73,7 +73,7 @@ enterprise_management::DeviceRegisterRequest::Type type, CloudPolicyCore* core, const scoped_refptr<base::SequencedTaskRunner>& task_runner, - scoped_ptr<base::Clock> clock, + std::unique_ptr<base::Clock> clock, int64_t highest_handled_invalidation_version); ~CloudPolicyInvalidator() override; @@ -184,7 +184,7 @@ const scoped_refptr<base::SequencedTaskRunner> task_runner_; // The clock. - scoped_ptr<base::Clock> clock_; + std::unique_ptr<base::Clock> clock_; // The invalidation service. invalidation::InvalidationService* invalidation_service_; @@ -225,7 +225,7 @@ int64_t highest_handled_invalidation_version_; // The most up to date invalidation. - scoped_ptr<syncer::Invalidation> invalidation_; + std::unique_ptr<syncer::Invalidation> invalidation_; // The maximum random delay, in ms, between receiving an invalidation and // fetching the new policy.
diff --git a/chrome/browser/policy/cloud/cloud_policy_invalidator_unittest.cc b/chrome/browser/policy/cloud/cloud_policy_invalidator_unittest.cc index 3428d995..ac8c09b 100644 --- a/chrome/browser/policy/cloud/cloud_policy_invalidator_unittest.cc +++ b/chrome/browser/policy/cloud/cloud_policy_invalidator_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/policy/cloud/cloud_policy_invalidator.h" + #include <stdint.h> +#include <memory> #include <string> #include "base/bind.h" #include "base/macros.h" #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/sample_map.h" @@ -20,7 +22,6 @@ #include "base/time/time.h" #include "base/values.h" #include "build/build_config.h" -#include "chrome/browser/policy/cloud/cloud_policy_invalidator.h" #include "chrome/browser/policy/cloud/user_cloud_policy_invalidator.h" #include "components/invalidation/impl/fake_invalidation_service.h" #include "components/invalidation/public/invalidation_util.h" @@ -194,7 +195,7 @@ base::SimpleTestClock* clock_; // The invalidator which will be tested. - scoped_ptr<CloudPolicyInvalidator> invalidator_; + std::unique_ptr<CloudPolicyInvalidator> invalidator_; // Object ids for the test policy objects. invalidation::ObjectId object_id_a_; @@ -236,12 +237,10 @@ bool initialize, bool start_refresh_scheduler, int64_t highest_handled_invalidation_version) { - invalidator_.reset(new CloudPolicyInvalidator( - GetPolicyType(), - &core_, - task_runner_, - scoped_ptr<base::Clock>(clock_), - highest_handled_invalidation_version)); + invalidator_.reset( + new CloudPolicyInvalidator(GetPolicyType(), &core_, task_runner_, + std::unique_ptr<base::Clock>(clock_), + highest_handled_invalidation_version)); if (start_refresh_scheduler) { ConnectCore(); StartRefreshScheduler(); @@ -265,7 +264,7 @@ void CloudPolicyInvalidatorTest::ConnectCore() { client_ = new MockCloudPolicyClient(); client_->SetDMToken("dm"); - core_.Connect(scoped_ptr<CloudPolicyClient>(client_)); + core_.Connect(std::unique_ptr<CloudPolicyClient>(client_)); } void CloudPolicyInvalidatorTest::StartRefreshScheduler() { @@ -865,14 +864,14 @@ em::DeviceRegisterRequest::Type GetPolicyType() const override; // Get histogram samples for the given histogram. - scoped_ptr<base::HistogramSamples> GetHistogramSamples( + std::unique_ptr<base::HistogramSamples> GetHistogramSamples( const std::string& name) const; // Stores starting histogram counts for kMetricPolicyRefresh. - scoped_ptr<base::HistogramSamples> refresh_samples_; + std::unique_ptr<base::HistogramSamples> refresh_samples_; // Stores starting histogram counts for kMetricPolicyInvalidations. - scoped_ptr<base::HistogramSamples> invalidations_samples_; + std::unique_ptr<base::HistogramSamples> invalidations_samples_; DISALLOW_COPY_AND_ASSIGN(CloudPolicyInvalidatorUserTypedTest); }; @@ -915,13 +914,13 @@ return GetParam(); } -scoped_ptr<base::HistogramSamples> +std::unique_ptr<base::HistogramSamples> CloudPolicyInvalidatorUserTypedTest::GetHistogramSamples( const std::string& name) const { base::HistogramBase* histogram = base::StatisticsRecorder::FindHistogram(name); if (!histogram) - return scoped_ptr<base::HistogramSamples>(new base::SampleMap()); + return std::unique_ptr<base::HistogramSamples>(new base::SampleMap()); return histogram->SnapshotSamples(); }
diff --git a/chrome/browser/policy/cloud/cloud_policy_manager_browsertest.cc b/chrome/browser/policy/cloud/cloud_policy_manager_browsertest.cc index afeb37a8..e924d035 100644 --- a/chrome/browser/policy/cloud/cloud_policy_manager_browsertest.cc +++ b/chrome/browser/policy/cloud/cloud_policy_manager_browsertest.cc
@@ -2,8 +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 "base/command_line.h" -#include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" @@ -136,7 +137,7 @@ policy_manager()->core()->client()->RemoveObserver(&observer); } - scoped_ptr<TestRequestInterceptor> interceptor_; + std::unique_ptr<TestRequestInterceptor> interceptor_; }; IN_PROC_BROWSER_TEST_F(CloudPolicyManagerTest, Register) {
diff --git a/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc b/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc index 78dd4de..3b1c37c6 100644 --- a/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc +++ b/chrome/browser/policy/cloud/component_cloud_policy_browsertest.cc
@@ -218,7 +218,7 @@ LocalPolicyTestServer test_server_; scoped_refptr<const extensions::Extension> extension_; - scoped_ptr<ExtensionTestMessageListener> event_listener_; + std::unique_ptr<ExtensionTestMessageListener> event_listener_; }; IN_PROC_BROWSER_TEST_F(ComponentCloudPolicyTest, FetchExtensionPolicy) {
diff --git a/chrome/browser/policy/cloud/device_management_service_browsertest.cc b/chrome/browser/policy/cloud/device_management_service_browsertest.cc index cee468e..b1d7d6d2 100644 --- a/chrome/browser/policy/cloud/device_management_service_browsertest.cc +++ b/chrome/browser/policy/cloud/device_management_service_browsertest.cc
@@ -4,9 +4,10 @@ #include <stdint.h> +#include <memory> + #include "base/bind.h" #include "base/bind_helpers.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/stl_util.h" #include "chrome/browser/browser_process.h" @@ -131,7 +132,7 @@ Invoke(this, &DeviceManagementServiceIntegrationTest::RecordToken), InvokeWithoutArgs(base::MessageLoop::current(), &base::MessageLoop::QuitWhenIdle))); - scoped_ptr<DeviceManagementRequestJob> job( + std::unique_ptr<DeviceManagementRequestJob> job( service_->CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, g_browser_process->system_request_context())); job->SetGaiaToken("gaia_auth_token"); @@ -146,7 +147,7 @@ void SetUpOnMainThread() override { std::string service_url((this->*(GetParam()))()); service_.reset(new DeviceManagementService( - scoped_ptr<DeviceManagementService::Configuration>( + std::unique_ptr<DeviceManagementService::Configuration>( new MockDeviceManagementServiceConfiguration(service_url)))); service_->ScheduleInitialization(0); } @@ -171,9 +172,9 @@ std::string token_; std::string robot_auth_code_; - scoped_ptr<DeviceManagementService> service_; - scoped_ptr<LocalPolicyTestServer> test_server_; - scoped_ptr<TestRequestInterceptor> interceptor_; + std::unique_ptr<DeviceManagementService> service_; + std::unique_ptr<LocalPolicyTestServer> test_server_; + std::unique_ptr<TestRequestInterceptor> interceptor_; }; IN_PROC_BROWSER_TEST_P(DeviceManagementServiceIntegrationTest, Registration) { @@ -191,9 +192,9 @@ Invoke(this, &DeviceManagementServiceIntegrationTest::RecordAuthCode), InvokeWithoutArgs(base::MessageLoop::current(), &base::MessageLoop::QuitWhenIdle))); - scoped_ptr<DeviceManagementRequestJob> job(service_->CreateJob( - DeviceManagementRequestJob::TYPE_API_AUTH_CODE_FETCH, - g_browser_process->system_request_context())); + std::unique_ptr<DeviceManagementRequestJob> job( + service_->CreateJob(DeviceManagementRequestJob::TYPE_API_AUTH_CODE_FETCH, + g_browser_process->system_request_context())); job->SetDMToken(token_); job->SetClientID("testid"); em::DeviceServiceApiAccessRequest* request = @@ -213,7 +214,7 @@ EXPECT_CALL(*this, OnJobDone(DM_STATUS_SUCCESS, _, _)) .WillOnce(InvokeWithoutArgs(base::MessageLoop::current(), &base::MessageLoop::QuitWhenIdle)); - scoped_ptr<DeviceManagementRequestJob> job( + std::unique_ptr<DeviceManagementRequestJob> job( service_->CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, g_browser_process->system_request_context())); job->SetDMToken(token_); @@ -233,7 +234,7 @@ EXPECT_CALL(*this, OnJobDone(DM_STATUS_SUCCESS, _, _)) .WillOnce(InvokeWithoutArgs(base::MessageLoop::current(), &base::MessageLoop::QuitWhenIdle)); - scoped_ptr<DeviceManagementRequestJob> job( + std::unique_ptr<DeviceManagementRequestJob> job( service_->CreateJob(DeviceManagementRequestJob::TYPE_UNREGISTRATION, g_browser_process->system_request_context())); job->SetDMToken(token_); @@ -249,7 +250,7 @@ EXPECT_CALL(*this, OnJobDone(DM_STATUS_SUCCESS, _, _)) .WillOnce(InvokeWithoutArgs(base::MessageLoop::current(), &base::MessageLoop::QuitWhenIdle)); - scoped_ptr<DeviceManagementRequestJob> job( + std::unique_ptr<DeviceManagementRequestJob> job( service_->CreateJob(DeviceManagementRequestJob::TYPE_AUTO_ENROLLMENT, g_browser_process->system_request_context())); job->SetClientID("testid");
diff --git a/chrome/browser/policy/cloud/policy_header_service_factory.cc b/chrome/browser/policy/cloud/policy_header_service_factory.cc index 6fcf3a67..4d6299d7 100644 --- a/chrome/browser/policy/cloud/policy_header_service_factory.cc +++ b/chrome/browser/policy/cloud/policy_header_service_factory.cc
@@ -4,9 +4,10 @@ #include "chrome/browser/policy/cloud/policy_header_service_factory.h" +#include <memory> #include <utility> -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" @@ -33,7 +34,8 @@ class PolicyHeaderServiceWrapper : public KeyedService { public: - explicit PolicyHeaderServiceWrapper(scoped_ptr<PolicyHeaderService> service) + explicit PolicyHeaderServiceWrapper( + std::unique_ptr<PolicyHeaderService> service) : policy_header_service_(std::move(service)) {} PolicyHeaderService* policy_header_service() const { @@ -47,7 +49,7 @@ } private: - scoped_ptr<PolicyHeaderService> policy_header_service_; + std::unique_ptr<PolicyHeaderService> policy_header_service_; }; } // namespace @@ -106,11 +108,10 @@ device_store = connector->GetDeviceCloudPolicyManager()->core()->store(); #endif - scoped_ptr<PolicyHeaderService> service = make_scoped_ptr( - new PolicyHeaderService(device_management_service->GetServerUrl(), - kPolicyVerificationKeyHash, - user_store, - device_store)); + std::unique_ptr<PolicyHeaderService> service = + base::WrapUnique(new PolicyHeaderService( + device_management_service->GetServerUrl(), kPolicyVerificationKeyHash, + user_store, device_store)); return new PolicyHeaderServiceWrapper(std::move(service)); }
diff --git a/chrome/browser/policy/cloud/test_request_interceptor.cc b/chrome/browser/policy/cloud/test_request_interceptor.cc index e1b4752..5bc98e7 100644 --- a/chrome/browser/policy/cloud/test_request_interceptor.cc +++ b/chrome/browser/policy/cloud/test_request_interceptor.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/policy/cloud/test_request_interceptor.h" #include <limits> +#include <memory> #include <queue> #include <utility> #include <vector> @@ -12,7 +13,6 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "base/sequenced_task_runner.h" #include "base/thread_task_runner_handle.h" @@ -85,7 +85,7 @@ const net::UploadDataStream* stream = request->get_upload(); if (!stream) return false; - const std::vector<scoped_ptr<net::UploadElementReader>>* readers = + const std::vector<std::unique_ptr<net::UploadElementReader>>* readers = stream->GetElementReaders(); if (!readers || readers->size() != 1u) return false; @@ -153,7 +153,7 @@ void RegisterHttpInterceptor( const std::string& hostname, - scoped_ptr<net::URLRequestInterceptor> interceptor) { + std::unique_ptr<net::URLRequestInterceptor> interceptor) { net::URLRequestFilter::GetInstance()->AddHostnameInterceptor( "http", hostname, std::move(interceptor)); } @@ -181,7 +181,7 @@ private: static void InvokeRequestServicedCallbacks( - scoped_ptr<std::vector<base::Closure>> callbacks); + std::unique_ptr<std::vector<base::Closure>> callbacks); const std::string hostname_; scoped_refptr<base::SequencedTaskRunner> io_task_runner_; @@ -222,7 +222,7 @@ // Invoke any callbacks that are waiting for the next request to be serviced // after this job is serviced. if (!request_serviced_callbacks_.empty()) { - scoped_ptr<std::vector<base::Closure>> callbacks( + std::unique_ptr<std::vector<base::Closure>> callbacks( new std::vector<base::Closure>); callbacks->swap(request_serviced_callbacks_); io_task_runner_->PostTask( @@ -255,7 +255,7 @@ // static void TestRequestInterceptor::Delegate::InvokeRequestServicedCallbacks( - scoped_ptr<std::vector<base::Closure>> callbacks) { + std::unique_ptr<std::vector<base::Closure>> callbacks) { for (const auto& p : *callbacks) p.Run(); } @@ -265,7 +265,7 @@ : hostname_(hostname), io_task_runner_(io_task_runner) { delegate_ = new Delegate(hostname_, io_task_runner_); - scoped_ptr<net::URLRequestInterceptor> interceptor(delegate_); + std::unique_ptr<net::URLRequestInterceptor> interceptor(delegate_); PostToIOAndWait( base::Bind(&RegisterHttpInterceptor, hostname_, base::Passed(&interceptor)));
diff --git a/chrome/browser/policy/cloud/user_cloud_policy_invalidator.cc b/chrome/browser/policy/cloud/user_cloud_policy_invalidator.cc index 237e7a7..7d88cc4b 100644 --- a/chrome/browser/policy/cloud/user_cloud_policy_invalidator.cc +++ b/chrome/browser/policy/cloud/user_cloud_policy_invalidator.cc
@@ -4,8 +4,9 @@ #include "chrome/browser/policy/cloud/user_cloud_policy_invalidator.h" +#include <memory> + #include "base/bind.h" -#include "base/memory/scoped_ptr.h" #include "base/thread_task_runner_handle.h" #include "base/time/default_clock.h" #include "build/build_config.h" @@ -20,11 +21,12 @@ UserCloudPolicyInvalidator::UserCloudPolicyInvalidator( Profile* profile, CloudPolicyManager* policy_manager) - : CloudPolicyInvalidator(GetPolicyType(), - policy_manager->core(), - base::ThreadTaskRunnerHandle::Get(), - scoped_ptr<base::Clock>(new base::DefaultClock()), - 0 /* highest_handled_invalidation_version */), + : CloudPolicyInvalidator( + GetPolicyType(), + policy_manager->core(), + base::ThreadTaskRunnerHandle::Get(), + std::unique_ptr<base::Clock>(new base::DefaultClock()), + 0 /* highest_handled_invalidation_version */), profile_(profile) { DCHECK(profile);
diff --git a/chrome/browser/policy/cloud/user_cloud_policy_manager_factory.cc b/chrome/browser/policy/cloud/user_cloud_policy_manager_factory.cc index eaf96155..b766ec52 100644 --- a/chrome/browser/policy/cloud/user_cloud_policy_manager_factory.cc +++ b/chrome/browser/policy/cloud/user_cloud_policy_manager_factory.cc
@@ -67,7 +67,7 @@ } // static -scoped_ptr<UserCloudPolicyManager> +std::unique_ptr<UserCloudPolicyManager> UserCloudPolicyManagerFactory::CreateForOriginalBrowserContext( content::BrowserContext* context, bool force_immediate_load, @@ -77,7 +77,7 @@ UserCloudPolicyManagerFactory* factory = GetInstance(); // If there's a testing factory set, don't bother creating a new one. if (factory->testing_factory_ != NULL) - return scoped_ptr<UserCloudPolicyManager>(); + return std::unique_ptr<UserCloudPolicyManager>(); return factory->CreateManagerForOriginalBrowserContext( context, force_immediate_load, @@ -130,7 +130,7 @@ return it != manager_wrappers_.end() ? it->second->manager() : NULL; } -scoped_ptr<UserCloudPolicyManager> +std::unique_ptr<UserCloudPolicyManager> UserCloudPolicyManagerFactory::CreateManagerForOriginalBrowserContext( content::BrowserContext* context, bool force_immediate_load, @@ -143,20 +143,18 @@ // Instead, instances are instantiated via CreateServiceNow(). DCHECK(!testing_factory_); - scoped_ptr<UserCloudPolicyStore> store( - UserCloudPolicyStore::Create(context->GetPath(), - GetPolicyVerificationKey(), - background_task_runner)); + std::unique_ptr<UserCloudPolicyStore> store(UserCloudPolicyStore::Create( + context->GetPath(), GetPolicyVerificationKey(), background_task_runner)); if (force_immediate_load) store->LoadImmediately(); const base::FilePath component_policy_cache_dir = context->GetPath().Append(kPolicy).Append(kComponentsDir); - scoped_ptr<UserCloudPolicyManager> manager; + std::unique_ptr<UserCloudPolicyManager> manager; manager.reset(new UserCloudPolicyManager( std::move(store), component_policy_cache_dir, - scoped_ptr<CloudExternalDataManager>(), + std::unique_ptr<CloudExternalDataManager>(), base::ThreadTaskRunnerHandle::Get(), file_task_runner, io_task_runner)); manager->Init( SchemaRegistryServiceFactory::GetForContext(context)->registry());
diff --git a/chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h b/chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h index c3efa24..49c7126 100644 --- a/chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h +++ b/chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h
@@ -6,10 +6,10 @@ #define CHROME_BROWSER_POLICY_CLOUD_USER_CLOUD_POLICY_MANAGER_FACTORY_H_ #include <map> +#include <memory> #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "components/keyed_service/content/browser_context_keyed_base_factory.h" @@ -62,7 +62,8 @@ // FILE BrowserThread. // |io_task_runner| is used for network IO. Currently this must be the IO // BrowserThread. - static scoped_ptr<UserCloudPolicyManager> CreateForOriginalBrowserContext( + static std::unique_ptr<UserCloudPolicyManager> + CreateForOriginalBrowserContext( content::BrowserContext* context, bool force_immediate_load, const scoped_refptr<base::SequencedTaskRunner>& background_task_runner, @@ -95,7 +96,8 @@ UserCloudPolicyManager* GetManagerForBrowserContext( content::BrowserContext* context); - scoped_ptr<UserCloudPolicyManager> CreateManagerForOriginalBrowserContext( + std::unique_ptr<UserCloudPolicyManager> + CreateManagerForOriginalBrowserContext( content::BrowserContext* context, bool force_immediate_load, const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service.cc b/chrome/browser/policy/cloud/user_policy_signin_service.cc index 0959273..0a5e82188 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service.cc
@@ -78,8 +78,8 @@ DCHECK(!oauth2_refresh_token.empty()); // Create a new CloudPolicyClient for fetching the DMToken. - scoped_ptr<CloudPolicyClient> policy_client = CreateClientForRegistrationOnly( - username); + std::unique_ptr<CloudPolicyClient> policy_client = + CreateClientForRegistrationOnly(username); if (!policy_client) { callback.Run(std::string(), std::string()); return; @@ -102,7 +102,7 @@ } void UserPolicySigninService::CallPolicyRegistrationCallback( - scoped_ptr<CloudPolicyClient> client, + std::unique_ptr<CloudPolicyClient> client, PolicyRegistrationCallback callback) { registration_helper_.reset(); callback.Run(client->dm_token(), client->client_id()); @@ -136,7 +136,7 @@ void UserPolicySigninService::InitializeUserCloudPolicyManager( const std::string& username, - scoped_ptr<CloudPolicyClient> client) { + std::unique_ptr<CloudPolicyClient> client) { UserPolicySigninServiceBase::InitializeUserCloudPolicyManager( username, std::move(client)); ProhibitSignoutIfNeeded();
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service.h b/chrome/browser/policy/cloud/user_policy_signin_service.h index fea47f96..65d94865 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service.h +++ b/chrome/browser/policy/cloud/user_policy_signin_service.h
@@ -5,12 +5,12 @@ #ifndef CHROME_BROWSER_POLICY_CLOUD_USER_POLICY_SIGNIN_SERVICE_H_ #define CHROME_BROWSER_POLICY_CLOUD_USER_POLICY_SIGNIN_SERVICE_H_ +#include <memory> #include <string> #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/policy/cloud/user_policy_signin_service_base.h" #include "google_apis/gaia/oauth2_token_service.h" @@ -64,7 +64,7 @@ // UserPolicySigninServiceBase implementation: void InitializeUserCloudPolicyManager( const std::string& username, - scoped_ptr<CloudPolicyClient> client) override; + std::unique_ptr<CloudPolicyClient> client) override; void PrepareForUserCloudPolicyManagerShutdown() override; void ShutdownUserCloudPolicyManager() override; @@ -84,13 +84,13 @@ void ProhibitSignoutIfNeeded(); // Invoked when a policy registration request is complete. - void CallPolicyRegistrationCallback(scoped_ptr<CloudPolicyClient> client, + void CallPolicyRegistrationCallback(std::unique_ptr<CloudPolicyClient> client, PolicyRegistrationCallback callback); // Parent profile for this service. Profile* profile_; - scoped_ptr<CloudPolicyClientRegistrationHelper> registration_helper_; + std::unique_ptr<CloudPolicyClientRegistrationHelper> registration_helper_; // Weak pointer to the token service we use to authenticate during // CloudPolicyClient registration.
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service_base.cc b/chrome/browser/policy/cloud/user_policy_signin_service_base.cc index 29a300e..a9cb5994 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_base.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service_base.cc
@@ -54,7 +54,7 @@ const std::string& client_id, scoped_refptr<net::URLRequestContextGetter> profile_request_context, const PolicyFetchCallback& callback) { - scoped_ptr<CloudPolicyClient> client = + std::unique_ptr<CloudPolicyClient> client = UserCloudPolicyManager::CreateCloudPolicyClient( device_management_service_, profile_request_context); client->SetupRegistration(dm_token, client_id); @@ -148,7 +148,7 @@ manager->core()->service()->RemoveObserver(this); } -scoped_ptr<CloudPolicyClient> +std::unique_ptr<CloudPolicyClient> UserPolicySigninServiceBase::CreateClientForRegistrationOnly( const std::string& username) { DCHECK(!username.empty()); @@ -158,7 +158,7 @@ // If the user should not get policy, just bail out. if (!policy_manager() || !ShouldLoadPolicyForUser(username)) { DVLOG(1) << "Signed in user is not in the whitelist"; - return scoped_ptr<CloudPolicyClient>(); + return std::unique_ptr<CloudPolicyClient>(); } // If the DeviceManagementService is not yet initialized, start it up now. @@ -231,7 +231,7 @@ void UserPolicySigninServiceBase::InitializeUserCloudPolicyManager( const std::string& username, - scoped_ptr<CloudPolicyClient> client) { + std::unique_ptr<CloudPolicyClient> client) { DCHECK(client); UserCloudPolicyManager* manager = policy_manager(); manager->SetSigninUsername(username);
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service_base.h b/chrome/browser/policy/cloud/user_policy_signin_service_base.h index 9e0cf6c2..68a30cd 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_base.h +++ b/chrome/browser/policy/cloud/user_policy_signin_service_base.h
@@ -5,13 +5,13 @@ #ifndef CHROME_BROWSER_POLICY_CLOUD_USER_POLICY_SIGNIN_SERVICE_BASE_H_ #define CHROME_BROWSER_POLICY_CLOUD_USER_POLICY_SIGNIN_SERVICE_BASE_H_ +#include <memory> #include <string> #include "base/callback.h" #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 "components/keyed_service/core/keyed_service.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" @@ -112,7 +112,7 @@ // Returns a CloudPolicyClient to perform a registration with the DM server, // or NULL if |username| shouldn't register for policy management. - scoped_ptr<CloudPolicyClient> CreateClientForRegistrationOnly( + std::unique_ptr<CloudPolicyClient> CreateClientForRegistrationOnly( const std::string& username); // Returns false if cloud policy is disabled or if the passed |email_address| @@ -141,7 +141,7 @@ // the initial policy fetch after signing in. virtual void InitializeUserCloudPolicyManager( const std::string& username, - scoped_ptr<CloudPolicyClient> client); + std::unique_ptr<CloudPolicyClient> client); // Prepares for the UserCloudPolicyManager to be shutdown due to // user signout or profile destruction.
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service_mobile.cc b/chrome/browser/policy/cloud/user_policy_signin_service_mobile.cc index f927c7d..51eeb48d 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_mobile.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service_mobile.cc
@@ -92,8 +92,8 @@ const std::string& access_token, const PolicyRegistrationCallback& callback) { // Create a new CloudPolicyClient for fetching the DMToken. - scoped_ptr<CloudPolicyClient> policy_client = CreateClientForRegistrationOnly( - username); + std::unique_ptr<CloudPolicyClient> policy_client = + CreateClientForRegistrationOnly(username); if (!policy_client) { callback.Run(std::string(), std::string()); return; @@ -128,7 +128,7 @@ } void UserPolicySigninService::CallPolicyRegistrationCallback( - scoped_ptr<CloudPolicyClient> client, + std::unique_ptr<CloudPolicyClient> client, PolicyRegistrationCallback callback) { registration_helper_.reset(); callback.Run(client->dm_token(), client->client_id());
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service_mobile.h b/chrome/browser/policy/cloud/user_policy_signin_service_mobile.h index 6d003ae..c024376 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_mobile.h +++ b/chrome/browser/policy/cloud/user_policy_signin_service_mobile.h
@@ -5,13 +5,13 @@ #ifndef CHROME_BROWSER_POLICY_CLOUD_USER_POLICY_SIGNIN_SERVICE_MOBILE_H_ #define CHROME_BROWSER_POLICY_CLOUD_USER_POLICY_SIGNIN_SERVICE_MOBILE_H_ +#include <memory> #include <string> #include <vector> #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 "build/build_config.h" #include "chrome/browser/policy/cloud/user_policy_signin_service_base.h" @@ -78,7 +78,7 @@ const std::string& access_token, const PolicyRegistrationCallback& callback); - void CallPolicyRegistrationCallback(scoped_ptr<CloudPolicyClient> client, + void CallPolicyRegistrationCallback(std::unique_ptr<CloudPolicyClient> client, PolicyRegistrationCallback callback); // KeyedService implementation: @@ -95,7 +95,7 @@ void OnRegistrationDone(); - scoped_ptr<CloudPolicyClientRegistrationHelper> registration_helper_; + std::unique_ptr<CloudPolicyClientRegistrationHelper> registration_helper_; // Weak pointer to the token service used to authenticate the // CloudPolicyClient during registration.
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service_unittest.cc b/chrome/browser/policy/cloud/user_policy_signin_service_unittest.cc index b78e64d1..f089b05 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_unittest.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service_unittest.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 <utility> #include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "base/thread_task_runner_handle.h" #include "base/time/time.h" @@ -94,11 +94,9 @@ EXPECT_CALL(*store, Load()).Times(AnyNumber()); return new UserCloudPolicyManager( - scoped_ptr<UserCloudPolicyStore>(store), - base::FilePath(), - scoped_ptr<CloudExternalDataManager>(), - base::ThreadTaskRunnerHandle::Get(), - base::ThreadTaskRunnerHandle::Get(), + std::unique_ptr<UserCloudPolicyStore>(store), base::FilePath(), + std::unique_ptr<CloudExternalDataManager>(), + base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get()); } @@ -157,7 +155,7 @@ // Create a testing profile with cloud-policy-on-signin enabled, and bring // up a UserCloudPolicyManager with a MockUserCloudPolicyStore. - scoped_ptr<syncable_prefs::TestingPrefServiceSyncable> prefs( + std::unique_ptr<syncable_prefs::TestingPrefServiceSyncable> prefs( new syncable_prefs::TestingPrefServiceSyncable()); chrome::RegisterUserProfilePrefs(prefs->registry()); @@ -170,7 +168,7 @@ BuildCloudPolicyManager); TestingProfile::Builder builder; builder.SetPrefService( - scoped_ptr<syncable_prefs::PrefServiceSyncable>(std::move(prefs))); + std::unique_ptr<syncable_prefs::PrefServiceSyncable>(std::move(prefs))); builder.AddTestingFactory(SigninManagerFactory::GetInstance(), BuildFakeSigninManagerBase); builder.AddTestingFactory(ProfileOAuth2TokenServiceFactory::GetInstance(), @@ -347,10 +345,10 @@ Mock::VerifyAndClearExpectations(this); } - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<TestingProfile> profile_; MockUserCloudPolicyStore* mock_store_; // Not owned. SchemaRegistry schema_registry_; - scoped_ptr<UserCloudPolicyManager> manager_; + std::unique_ptr<UserCloudPolicyManager> manager_; // BrowserPolicyConnector and UrlFetcherFactory want to initialize and free // various components asynchronously via tasks, so create fake threads here. @@ -372,7 +370,7 @@ // BrowserPolicyConnector). MockDeviceManagementService device_management_service_; - scoped_ptr<TestingPrefServiceSimple> local_state_; + std::unique_ptr<TestingPrefServiceSimple> local_state_; scoped_refptr<net::URLRequestContextGetter> system_request_context_getter_; };
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index b777319..4483ffe 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -6,10 +6,12 @@ #include <limits.h> #include <stddef.h> + #include <utility> #include "base/bind.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/memory/scoped_vector.h" #include "base/values.h" #include "build/build_config.h" @@ -599,9 +601,8 @@ const extensions::schema_constants::AllowedTypesMapEntry& entry = extensions::schema_constants::kAllowedTypesMap[index]; result->push_back(new StringMappingListPolicyHandler::MappingEntry( - entry.name, - scoped_ptr<base::Value>( - new base::FundamentalValue(entry.manifest_type)))); + entry.name, std::unique_ptr<base::Value>( + new base::FundamentalValue(entry.manifest_type)))); } } #endif @@ -625,83 +626,83 @@ #endif } -scoped_ptr<ConfigurationPolicyHandlerList> BuildHandlerList( +std::unique_ptr<ConfigurationPolicyHandlerList> BuildHandlerList( const Schema& chrome_schema) { - scoped_ptr<ConfigurationPolicyHandlerList> handlers( + std::unique_ptr<ConfigurationPolicyHandlerList> handlers( new ConfigurationPolicyHandlerList( base::Bind(&PopulatePolicyHandlerParameters), base::Bind(&GetChromePolicyDetails))); for (size_t i = 0; i < arraysize(kSimplePolicyMap); ++i) { - handlers->AddHandler(make_scoped_ptr(new SimplePolicyHandler( + handlers->AddHandler(base::WrapUnique(new SimplePolicyHandler( kSimplePolicyMap[i].policy_name, kSimplePolicyMap[i].preference_path, kSimplePolicyMap[i].value_type))); } - handlers->AddHandler(make_scoped_ptr(new AutofillPolicyHandler())); - handlers->AddHandler(make_scoped_ptr(new DefaultSearchPolicyHandler())); - handlers->AddHandler(make_scoped_ptr(new ForceSafeSearchPolicyHandler())); - handlers->AddHandler(make_scoped_ptr(new IncognitoModePolicyHandler())); + handlers->AddHandler(base::WrapUnique(new AutofillPolicyHandler())); + handlers->AddHandler(base::WrapUnique(new DefaultSearchPolicyHandler())); + handlers->AddHandler(base::WrapUnique(new ForceSafeSearchPolicyHandler())); + handlers->AddHandler(base::WrapUnique(new IncognitoModePolicyHandler())); handlers->AddHandler( - make_scoped_ptr(new ManagedBookmarksPolicyHandler(chrome_schema))); - handlers->AddHandler(make_scoped_ptr(new ProxyPolicyHandler())); - handlers->AddHandler(make_scoped_ptr(new URLBlacklistPolicyHandler())); + base::WrapUnique(new ManagedBookmarksPolicyHandler(chrome_schema))); + handlers->AddHandler(base::WrapUnique(new ProxyPolicyHandler())); + handlers->AddHandler(base::WrapUnique(new URLBlacklistPolicyHandler())); #if BUILDFLAG(ANDROID_JAVA_UI) handlers->AddHandler( - make_scoped_ptr(new ContextualSearchPolicyHandlerAndroid())); + base::WrapUnique(new ContextualSearchPolicyHandlerAndroid())); #endif handlers->AddHandler( - make_scoped_ptr(new FileSelectionDialogsPolicyHandler())); - handlers->AddHandler(make_scoped_ptr(new JavascriptPolicyHandler())); - handlers->AddHandler(make_scoped_ptr(new NetworkPredictionPolicyHandler())); - handlers->AddHandler(make_scoped_ptr(new RestoreOnStartupPolicyHandler())); - handlers->AddHandler(make_scoped_ptr(new sync_driver::SyncPolicyHandler())); + base::WrapUnique(new FileSelectionDialogsPolicyHandler())); + handlers->AddHandler(base::WrapUnique(new JavascriptPolicyHandler())); + handlers->AddHandler(base::WrapUnique(new NetworkPredictionPolicyHandler())); + handlers->AddHandler(base::WrapUnique(new RestoreOnStartupPolicyHandler())); + handlers->AddHandler(base::WrapUnique(new sync_driver::SyncPolicyHandler())); - handlers->AddHandler(make_scoped_ptr(new StringMappingListPolicyHandler( + handlers->AddHandler(base::WrapUnique(new StringMappingListPolicyHandler( key::kEnableDeprecatedWebPlatformFeatures, prefs::kEnableDeprecatedWebPlatformFeatures, base::Bind(GetDeprecatedFeaturesMap)))); #if defined(ENABLE_EXTENSIONS) handlers->AddHandler( - make_scoped_ptr(new extensions::ExtensionListPolicyHandler( + base::WrapUnique(new extensions::ExtensionListPolicyHandler( key::kExtensionInstallWhitelist, extensions::pref_names::kInstallAllowList, false))); handlers->AddHandler( - make_scoped_ptr(new extensions::ExtensionListPolicyHandler( + base::WrapUnique(new extensions::ExtensionListPolicyHandler( key::kExtensionInstallBlacklist, extensions::pref_names::kInstallDenyList, true))); - handlers->AddHandler(make_scoped_ptr( + handlers->AddHandler(base::WrapUnique( new extensions::ExtensionInstallForcelistPolicyHandler())); handlers->AddHandler( - make_scoped_ptr(new extensions::ExtensionURLPatternListPolicyHandler( + base::WrapUnique(new extensions::ExtensionURLPatternListPolicyHandler( key::kExtensionInstallSources, extensions::pref_names::kAllowedInstallSites))); - handlers->AddHandler(make_scoped_ptr(new StringMappingListPolicyHandler( + handlers->AddHandler(base::WrapUnique(new StringMappingListPolicyHandler( key::kExtensionAllowedTypes, extensions::pref_names::kAllowedTypes, base::Bind(GetExtensionAllowedTypesMap)))); - handlers->AddHandler(make_scoped_ptr( + handlers->AddHandler(base::WrapUnique( new extensions::ExtensionSettingsPolicyHandler(chrome_schema))); #endif #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) - handlers->AddHandler(make_scoped_ptr(new DiskCacheDirPolicyHandler())); + handlers->AddHandler(base::WrapUnique(new DiskCacheDirPolicyHandler())); handlers->AddHandler( - make_scoped_ptr(new extensions::NativeMessagingHostListPolicyHandler( + base::WrapUnique(new extensions::NativeMessagingHostListPolicyHandler( key::kNativeMessagingWhitelist, extensions::pref_names::kNativeMessagingWhitelist, false))); handlers->AddHandler( - make_scoped_ptr(new extensions::NativeMessagingHostListPolicyHandler( + base::WrapUnique(new extensions::NativeMessagingHostListPolicyHandler( key::kNativeMessagingBlacklist, extensions::pref_names::kNativeMessagingBlacklist, true))); #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID) #if !defined(OS_ANDROID) - handlers->AddHandler(make_scoped_ptr(new DownloadDirPolicyHandler)); + handlers->AddHandler(base::WrapUnique(new DownloadDirPolicyHandler)); - handlers->AddHandler(make_scoped_ptr(new SimpleSchemaValidatingPolicyHandler( + handlers->AddHandler(base::WrapUnique(new SimpleSchemaValidatingPolicyHandler( key::kRegisteredProtocolHandlers, prefs::kPolicyRegisteredProtocolHandlers, chrome_schema, SCHEMA_STRICT, SimpleSchemaValidatingPolicyHandler::RECOMMENDED_ALLOWED, @@ -710,16 +711,16 @@ #if defined(OS_CHROMEOS) handlers->AddHandler( - make_scoped_ptr(new extensions::ExtensionListPolicyHandler( + base::WrapUnique(new extensions::ExtensionListPolicyHandler( key::kAttestationExtensionWhitelist, prefs::kAttestationExtensionWhitelist, false))); - handlers->AddHandler(make_scoped_ptr( + handlers->AddHandler(base::WrapUnique( NetworkConfigurationPolicyHandler::CreateForDevicePolicy())); - handlers->AddHandler(make_scoped_ptr( + handlers->AddHandler(base::WrapUnique( NetworkConfigurationPolicyHandler::CreateForUserPolicy())); - handlers->AddHandler(make_scoped_ptr(new PinnedLauncherAppsPolicyHandler())); - handlers->AddHandler(make_scoped_ptr(new ScreenMagnifierPolicyHandler())); - handlers->AddHandler(make_scoped_ptr( + handlers->AddHandler(base::WrapUnique(new PinnedLauncherAppsPolicyHandler())); + handlers->AddHandler(base::WrapUnique(new ScreenMagnifierPolicyHandler())); + handlers->AddHandler(base::WrapUnique( new LoginScreenPowerManagementPolicyHandler(chrome_schema))); ScopedVector<ConfigurationPolicyHandler> @@ -797,45 +798,45 @@ INT_MAX, true)); - handlers->AddHandler(make_scoped_ptr(new IntRangePolicyHandler( + handlers->AddHandler(base::WrapUnique(new IntRangePolicyHandler( key::kSAMLOfflineSigninTimeLimit, prefs::kSAMLOfflineSigninTimeLimit, -1, INT_MAX, true))); - handlers->AddHandler(make_scoped_ptr(new IntRangePolicyHandler( + handlers->AddHandler(base::WrapUnique(new IntRangePolicyHandler( key::kLidCloseAction, prefs::kPowerLidClosedAction, chromeos::PowerPolicyController::ACTION_SUSPEND, chromeos::PowerPolicyController::ACTION_DO_NOTHING, false))); - handlers->AddHandler(make_scoped_ptr(new IntPercentageToDoublePolicyHandler( + handlers->AddHandler(base::WrapUnique(new IntPercentageToDoublePolicyHandler( key::kPresentationScreenDimDelayScale, prefs::kPowerPresentationScreenDimDelayFactor, 100, INT_MAX, true))); - handlers->AddHandler(make_scoped_ptr(new IntPercentageToDoublePolicyHandler( + handlers->AddHandler(base::WrapUnique(new IntPercentageToDoublePolicyHandler( key::kUserActivityScreenDimDelayScale, prefs::kPowerUserActivityScreenDimDelayFactor, 100, INT_MAX, true))); - handlers->AddHandler(make_scoped_ptr(new IntRangePolicyHandler( + handlers->AddHandler(base::WrapUnique(new IntRangePolicyHandler( key::kUptimeLimit, prefs::kUptimeLimit, 3600, INT_MAX, true))); - handlers->AddHandler(make_scoped_ptr(new IntRangePolicyHandler( + handlers->AddHandler(base::WrapUnique(new IntRangePolicyHandler( key::kDeviceLoginScreenDefaultScreenMagnifierType, NULL, 0, ui::MAGNIFIER_FULL, false))); // TODO(binjin): Remove LegacyPoliciesDeprecatingPolicyHandler for these two // policies once deprecation of legacy power management policies is done. // http://crbug.com/346229 handlers->AddHandler( - make_scoped_ptr(new LegacyPoliciesDeprecatingPolicyHandler( + base::WrapUnique(new LegacyPoliciesDeprecatingPolicyHandler( std::move(power_management_idle_legacy_policies), - make_scoped_ptr( + base::WrapUnique( new PowerManagementIdleSettingsPolicyHandler(chrome_schema))))); handlers->AddHandler( - make_scoped_ptr(new LegacyPoliciesDeprecatingPolicyHandler( + base::WrapUnique(new LegacyPoliciesDeprecatingPolicyHandler( std::move(screen_lock_legacy_policies), - make_scoped_ptr(new ScreenLockDelayPolicyHandler(chrome_schema))))); + base::WrapUnique(new ScreenLockDelayPolicyHandler(chrome_schema))))); handlers->AddHandler( - make_scoped_ptr(new ExternalDataPolicyHandler(key::kUserAvatarImage))); + base::WrapUnique(new ExternalDataPolicyHandler(key::kUserAvatarImage))); handlers->AddHandler( - make_scoped_ptr(new ExternalDataPolicyHandler(key::kWallpaperImage))); - handlers->AddHandler(make_scoped_ptr(new SimpleSchemaValidatingPolicyHandler( + base::WrapUnique(new ExternalDataPolicyHandler(key::kWallpaperImage))); + handlers->AddHandler(base::WrapUnique(new SimpleSchemaValidatingPolicyHandler( key::kSessionLocales, NULL, chrome_schema, SCHEMA_STRICT, SimpleSchemaValidatingPolicyHandler::RECOMMENDED_ALLOWED, SimpleSchemaValidatingPolicyHandler::MANDATORY_PROHIBITED))); - handlers->AddHandler(make_scoped_ptr( + handlers->AddHandler(base::WrapUnique( new chromeos::KeyPermissionsPolicyHandler(chrome_schema))); #endif // defined(OS_CHROMEOS)
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.h b/chrome/browser/policy/configuration_policy_handler_list_factory.h index cf95e1cc..64d36ee 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.h +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.h
@@ -5,7 +5,7 @@ #ifndef CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_HANDLER_LIST_FACTORY_H_ #define CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_HANDLER_LIST_FACTORY_H_ -#include "base/memory/scoped_ptr.h" +#include <memory> namespace policy { @@ -13,7 +13,7 @@ class Schema; // Builds a platform-specific handler list. -scoped_ptr<ConfigurationPolicyHandlerList> BuildHandlerList( +std::unique_ptr<ConfigurationPolicyHandlerList> BuildHandlerList( const Schema& chrome_schema); } // namespace policy
diff --git a/chrome/browser/policy/javascript_policy_handler_unittest.cc b/chrome/browser/policy/javascript_policy_handler_unittest.cc index 26c35db..1d39f12a 100644 --- a/chrome/browser/policy/javascript_policy_handler_unittest.cc +++ b/chrome/browser/policy/javascript_policy_handler_unittest.cc
@@ -3,6 +3,8 @@ // found in the LICENSE file. #include "chrome/browser/policy/javascript_policy_handler.h" + +#include "base/memory/ptr_util.h" #include "components/content_settings/core/common/content_settings.h" #include "components/content_settings/core/common/pref_names.h" #include "components/policy/core/browser/configuration_policy_pref_store.h" @@ -16,8 +18,8 @@ class JavascriptPolicyHandlerTest : public ConfigurationPolicyPrefStoreTest { void SetUp() override { - handler_list_.AddHandler(make_scoped_ptr<ConfigurationPolicyHandler>( - new JavascriptPolicyHandler)); + handler_list_.AddHandler(base::WrapUnique<ConfigurationPolicyHandler>( + new JavascriptPolicyHandler)); } };
diff --git a/chrome/browser/policy/managed_bookmarks_policy_handler.cc b/chrome/browser/policy/managed_bookmarks_policy_handler.cc index 71eb4ef..3c14424 100644 --- a/chrome/browser/policy/managed_bookmarks_policy_handler.cc +++ b/chrome/browser/policy/managed_bookmarks_policy_handler.cc
@@ -32,7 +32,7 @@ void ManagedBookmarksPolicyHandler::ApplyPolicySettings( const PolicyMap& policies, PrefValueMap* prefs) { - scoped_ptr<base::Value> value; + std::unique_ptr<base::Value> value; if (!CheckAndGetValue(policies, NULL, &value)) return;
diff --git a/chrome/browser/policy/managed_bookmarks_policy_handler_unittest.cc b/chrome/browser/policy/managed_bookmarks_policy_handler_unittest.cc index 6237f66f..87f4da51 100644 --- a/chrome/browser/policy/managed_bookmarks_policy_handler_unittest.cc +++ b/chrome/browser/policy/managed_bookmarks_policy_handler_unittest.cc
@@ -2,10 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/policy/managed_bookmarks_policy_handler.h" + #include <utility> #include "base/json/json_reader.h" -#include "chrome/browser/policy/managed_bookmarks_policy_handler.h" +#include "base/memory/ptr_util.h" #include "components/bookmarks/common/bookmark_pref_names.h" #include "components/policy/core/browser/configuration_policy_pref_store.h" #include "components/policy/core/browser/configuration_policy_pref_store_test.h" @@ -24,7 +26,7 @@ : public ConfigurationPolicyPrefStoreTest { void SetUp() override { Schema chrome_schema = Schema::Wrap(GetChromeSchemaData()); - handler_list_.AddHandler(make_scoped_ptr<ConfigurationPolicyHandler>( + handler_list_.AddHandler(base::WrapUnique<ConfigurationPolicyHandler>( new ManagedBookmarksPolicyHandler(chrome_schema))); } }; @@ -92,7 +94,7 @@ ASSERT_TRUE(folder_value->GetAsString(&folder_name)); EXPECT_EQ("abc 123", folder_name); - scoped_ptr<base::Value> expected( + std::unique_ptr<base::Value> expected( extensions::ListBuilder() .Append(extensions::DictionaryBuilder() .Set("name", "Google") @@ -170,7 +172,7 @@ ASSERT_TRUE(folder_value->GetAsString(&folder_name)); EXPECT_EQ("", folder_name); - scoped_ptr<base::Value> expected( + std::unique_ptr<base::Value> expected( extensions::ListBuilder() .Append(extensions::DictionaryBuilder() .Set("name", "Google") @@ -223,7 +225,7 @@ store_->GetValue(bookmarks::prefs::kManagedBookmarks, &pref_value)); ASSERT_TRUE(pref_value); - scoped_ptr<base::Value> expected( + std::unique_ptr<base::Value> expected( extensions::ListBuilder() .Append(extensions::DictionaryBuilder() .Set("name", "Google") @@ -267,7 +269,7 @@ store_->GetValue(bookmarks::prefs::kManagedBookmarks, &pref_value)); ASSERT_TRUE(pref_value); - scoped_ptr<base::Value> expected( + std::unique_ptr<base::Value> expected( extensions::ListBuilder() .Append(extensions::DictionaryBuilder() .Set("name", "Google")
diff --git a/chrome/browser/policy/policy_browsertest.cc b/chrome/browser/policy/policy_browsertest.cc index 3dafed15..e658b11c 100644 --- a/chrome/browser/policy/policy_browsertest.cc +++ b/chrome/browser/policy/policy_browsertest.cc
@@ -4,7 +4,9 @@ #include <stddef.h> #include <stdint.h> + #include <algorithm> +#include <memory> #include <string> #include <utility> #include <vector> @@ -19,8 +21,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/path_service.h" #include "base/run_loop.h" #include "base/strings/string16.h" @@ -339,12 +341,12 @@ // Filters requests to the |host| such that they fail. Run on IO thread. static void MakeRequestFailOnIO(const std::string& host) { net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); - filter->AddHostnameInterceptor( - "http", host, - scoped_ptr<net::URLRequestInterceptor>(new FailedJobInterceptor())); - filter->AddHostnameInterceptor( - "https", host, - scoped_ptr<net::URLRequestInterceptor>(new FailedJobInterceptor())); + filter->AddHostnameInterceptor("http", host, + std::unique_ptr<net::URLRequestInterceptor>( + new FailedJobInterceptor())); + filter->AddHostnameInterceptor("https", host, + std::unique_ptr<net::URLRequestInterceptor>( + new FailedJobInterceptor())); } // Remove filters for requests to the |host|. Run on IO thread. @@ -443,8 +445,8 @@ } bool IsJavascriptEnabled(content::WebContents* contents) { - scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue( - contents->GetMainFrame(), "123"); + std::unique_ptr<base::Value> value = + content::ExecuteScriptAndGetValue(contents->GetMainFrame(), "123"); int result = 0; if (!value->GetAsInteger(&result)) EXPECT_EQ(base::Value::TYPE_NULL, value->GetType()); @@ -725,7 +727,7 @@ void TestScreenshotFile(bool enabled) { // AddObserver is an ash-specific method, so just replace the screenshot // grabber with one we've created here. - scoped_ptr<ChromeScreenshotGrabber> chrome_screenshot_grabber( + std::unique_ptr<ChromeScreenshotGrabber> chrome_screenshot_grabber( new ChromeScreenshotGrabber); // ScreenshotGrabber doesn't own this observer, so the observer's lifetime // is tied to the test instead. @@ -888,7 +890,7 @@ } MockConfigurationPolicyProvider provider_; - scoped_ptr<extensions::ExtensionCacheFake> test_extension_cache_; + std::unique_ptr<extensions::ExtensionCacheFake> test_extension_cache_; #if defined(OS_CHROMEOS) QuitMessageLoopAfterScreenshot observer_; #endif @@ -1161,7 +1163,8 @@ // It should be removed and replaced with a dictionary. PolicyMap expected; - scoped_ptr<base::DictionaryValue> expected_value(new base::DictionaryValue); + std::unique_ptr<base::DictionaryValue> expected_value( + new base::DictionaryValue); expected_value->SetInteger(key::kProxyServerMode, 3); expected.Set(key::kProxySettings, POLICY_LEVEL_MANDATORY, @@ -1802,7 +1805,7 @@ EXPECT_TRUE(shared_module->is_shared_module()); // Verify the dependency. - scoped_ptr<extensions::ExtensionSet> set = + std::unique_ptr<extensions::ExtensionSet> set = service->shared_module_service()->GetDependentExtensions(shared_module); ASSERT_TRUE(set); EXPECT_EQ(1u, set->size()); @@ -2463,7 +2466,7 @@ #if !defined(USE_AURA) // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly. IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_TranslateEnabled) { - 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()); @@ -2851,7 +2854,7 @@ IN_PROC_BROWSER_TEST_F(PolicyTest, DisableAudioOutput) { // Set up the mock observer. chromeos::CrasAudioHandler* audio_handler = chromeos::CrasAudioHandler::Get(); - scoped_ptr<TestAudioObserver> test_observer(new TestAudioObserver); + std::unique_ptr<TestAudioObserver> test_observer(new TestAudioObserver); audio_handler->AddAudioObserver(test_observer.get()); bool prior_state = audio_handler->IsOutputMuted(); @@ -3498,7 +3501,7 @@ void Accept(const content::MediaStreamDevices& devices, content::MediaStreamRequestResult result, - scoped_ptr<content::MediaStreamUI> ui) { + std::unique_ptr<content::MediaStreamUI> ui) { if (policy_value_ || request_url_allowed_via_whitelist_) { ASSERT_EQ(1U, devices.size()); ASSERT_EQ("fake_dev", devices[0].id); @@ -3878,9 +3881,9 @@ // g_browser_process->variations_service() is null by default in Chromium // builds, so construct a VariationsService locally instead. - scoped_ptr<variations::VariationsService> service = + std::unique_ptr<variations::VariationsService> service = variations::VariationsService::CreateForTesting( - make_scoped_ptr(new ChromeVariationsServiceClient()), + base::WrapUnique(new ChromeVariationsServiceClient()), g_browser_process->local_state()); const GURL url = service->GetVariationsServerURL( @@ -4032,19 +4035,19 @@ fake_session_manager_client_ = new chromeos::FakeSessionManagerClient; fake_session_manager_client_->set_arc_available(true); chromeos::DBusThreadManager::GetSetterForTesting()->SetSessionManagerClient( - scoped_ptr<chromeos::SessionManagerClient>( + std::unique_ptr<chromeos::SessionManagerClient>( fake_session_manager_client_)); fake_arc_bridge_instance_.reset(new arc::FakeArcBridgeInstance); - arc::ArcServiceManager::SetArcBridgeServiceForTesting(make_scoped_ptr( - new arc::ArcBridgeServiceImpl(make_scoped_ptr( - new arc::FakeArcBridgeBootstrap( + arc::ArcServiceManager::SetArcBridgeServiceForTesting( + base::WrapUnique(new arc::ArcBridgeServiceImpl( + base::WrapUnique(new arc::FakeArcBridgeBootstrap( fake_arc_bridge_instance_.get()))))); } private: chromeos::FakeSessionManagerClient *fake_session_manager_client_; - scoped_ptr<arc::FakeArcBridgeInstance> fake_arc_bridge_instance_; + std::unique_ptr<arc::FakeArcBridgeInstance> fake_arc_bridge_instance_; DISALLOW_COPY_AND_ASSIGN(ArcPolicyTest); };
diff --git a/chrome/browser/policy/policy_path_parser_win.cc b/chrome/browser/policy/policy_path_parser_win.cc index 2acadee..7ec15f23 100644 --- a/chrome/browser/policy/policy_path_parser_win.cc +++ b/chrome/browser/policy/policy_path_parser_win.cc
@@ -2,14 +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/policy/policy_path_parser.h" + #include <shlobj.h> #include <stddef.h> #include <wtsapi32.h> -#include "chrome/browser/policy/policy_path_parser.h" +#include <memory> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/utf_string_conversions.h" #include "base/win/registry.h" #include "chrome/common/chrome_switches.h" @@ -93,7 +94,7 @@ DWORD return_length = 0; ::GetUserName(NULL, &return_length); if (return_length != 0) { - scoped_ptr<WCHAR[]> username(new WCHAR[return_length]); + std::unique_ptr<WCHAR[]> username(new WCHAR[return_length]); ::GetUserName(username.get(), &return_length); std::wstring username_string(username.get()); result.replace(position, wcslen(kUserNamePolicyVarName), username_string); @@ -104,7 +105,7 @@ DWORD return_length = 0; ::GetComputerNameEx(ComputerNamePhysicalDnsHostname, NULL, &return_length); if (return_length != 0) { - scoped_ptr<WCHAR[]> machinename(new WCHAR[return_length]); + std::unique_ptr<WCHAR[]> machinename(new WCHAR[return_length]); ::GetComputerNameEx(ComputerNamePhysicalDnsHostname, machinename.get(), &return_length); std::wstring machinename_string(machinename.get());
diff --git a/chrome/browser/policy/policy_prefs_browsertest.cc b/chrome/browser/policy/policy_prefs_browsertest.cc index d4d3f47..15221e8 100644 --- a/chrome/browser/policy/policy_prefs_browsertest.cc +++ b/chrome/browser/policy/policy_prefs_browsertest.cc
@@ -7,6 +7,7 @@ #include <algorithm> #include <cstdlib> #include <map> +#include <memory> #include <sstream> #include <string> #include <vector> @@ -16,7 +17,6 @@ #include "base/json/json_reader.h" #include "base/logging.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h" @@ -85,7 +85,7 @@ bool readonly() const { return readonly_; } private: - scoped_ptr<base::DictionaryValue> policy_; + std::unique_ptr<base::DictionaryValue> policy_; std::string value_; bool readonly_; @@ -236,7 +236,7 @@ int error_code = -1; std::string error_string; base::DictionaryValue* dict = NULL; - scoped_ptr<base::Value> value = base::JSONReader::ReadAndReturnError( + std::unique_ptr<base::Value> value = base::JSONReader::ReadAndReturnError( json, base::JSON_PARSE_RFC, &error_code, &error_string); if (!value.get() || !value->GetAsDictionary(&dict)) { ADD_FAILURE() << "Error parsing policy_test_cases.json: " << error_string; @@ -431,7 +431,7 @@ // |selector| as JSON. ASSERT_TRUE(content::ExecuteScriptAndExtractString(contents, javascript.str(), &json)); - scoped_ptr<base::Value> value_ptr = base::JSONReader::Read(json); + std::unique_ptr<base::Value> value_ptr = base::JSONReader::Read(json); const base::ListValue* indicators = NULL; ASSERT_TRUE(value_ptr.get()); ASSERT_TRUE(value_ptr->GetAsList(&indicators));
diff --git a/chrome/browser/policy/profile_policy_connector.cc b/chrome/browser/policy/profile_policy_connector.cc index e0bccc9..8b177d7 100644 --- a/chrome/browser/policy/profile_policy_connector.cc +++ b/chrome/browser/policy/profile_policy_connector.cc
@@ -131,7 +131,8 @@ #endif } -void ProfilePolicyConnector::InitForTesting(scoped_ptr<PolicyService> service) { +void ProfilePolicyConnector::InitForTesting( + std::unique_ptr<PolicyService> service) { policy_service_ = std::move(service); }
diff --git a/chrome/browser/policy/profile_policy_connector.h b/chrome/browser/policy/profile_policy_connector.h index d6e4fe79..8ef8f22 100644 --- a/chrome/browser/policy/profile_policy_connector.h +++ b/chrome/browser/policy/profile_policy_connector.h
@@ -5,11 +5,11 @@ #ifndef CHROME_BROWSER_POLICY_PROFILE_POLICY_CONNECTOR_H_ #define CHROME_BROWSER_POLICY_PROFILE_POLICY_CONNECTOR_H_ +#include <memory> #include <string> #include <vector> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "build/build_config.h" #include "components/keyed_service/core/keyed_service.h" @@ -38,7 +38,7 @@ SchemaRegistry* schema_registry, CloudPolicyManager* user_cloud_policy_manager); - void InitForTesting(scoped_ptr<PolicyService> service); + void InitForTesting(std::unique_ptr<PolicyService> service); void OverrideIsManagedForTesting(bool is_managed); // KeyedService: @@ -75,10 +75,11 @@ // local state. bool is_primary_user_; - scoped_ptr<ConfigurationPolicyProvider> special_user_policy_provider_; + std::unique_ptr<ConfigurationPolicyProvider> special_user_policy_provider_; #endif // defined(OS_CHROMEOS) - scoped_ptr<ConfigurationPolicyProvider> wrapped_platform_policy_provider_; + std::unique_ptr<ConfigurationPolicyProvider> + wrapped_platform_policy_provider_; CloudPolicyManager* user_cloud_policy_manager_; // |policy_providers_| contains a list of the policy providers available for @@ -91,8 +92,8 @@ // result is true, so take care if a provider overrides that. std::vector<ConfigurationPolicyProvider*> policy_providers_; - scoped_ptr<PolicyService> policy_service_; - scoped_ptr<bool> is_managed_override_; + std::unique_ptr<PolicyService> policy_service_; + std::unique_ptr<bool> is_managed_override_; DISALLOW_COPY_AND_ASSIGN(ProfilePolicyConnector); };
diff --git a/chrome/browser/policy/profile_policy_connector_factory.cc b/chrome/browser/policy/profile_policy_connector_factory.cc index 1bf9210..20c0929 100644 --- a/chrome/browser/policy/profile_policy_connector_factory.cc +++ b/chrome/browser/policy/profile_policy_connector_factory.cc
@@ -42,7 +42,7 @@ } // static -scoped_ptr<ProfilePolicyConnector> +std::unique_ptr<ProfilePolicyConnector> ProfilePolicyConnectorFactory::CreateForBrowserContext( content::BrowserContext* context, bool force_immediate_load) { @@ -91,7 +91,7 @@ return it->second; } -scoped_ptr<ProfilePolicyConnector> +std::unique_ptr<ProfilePolicyConnector> ProfilePolicyConnectorFactory::CreateForBrowserContextInternal( content::BrowserContext* context, bool force_immediate_load) { @@ -117,7 +117,8 @@ UserCloudPolicyManagerFactory::GetForBrowserContext(context); #endif // defined(OS_CHROMEOS) - scoped_ptr<ProfilePolicyConnector> connector(new ProfilePolicyConnector()); + std::unique_ptr<ProfilePolicyConnector> connector( + new ProfilePolicyConnector()); if (test_providers_.empty()) { connector->Init( @@ -129,7 +130,7 @@ PolicyServiceImpl::Providers providers; providers.push_back(test_providers_.front()); test_providers_.pop_front(); - scoped_ptr<PolicyService> service(new PolicyServiceImpl(providers)); + std::unique_ptr<PolicyService> service(new PolicyServiceImpl(providers)); connector->InitForTesting(std::move(service)); }
diff --git a/chrome/browser/policy/profile_policy_connector_factory.h b/chrome/browser/policy/profile_policy_connector_factory.h index b7ea5e9..5e9ec90 100644 --- a/chrome/browser/policy/profile_policy_connector_factory.h +++ b/chrome/browser/policy/profile_policy_connector_factory.h
@@ -7,9 +7,9 @@ #include <list> #include <map> +#include <memory> #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "components/keyed_service/content/browser_context_keyed_base_factory.h" namespace base { @@ -47,7 +47,7 @@ // instance created, as long as it lives. // If |force_immediate_load| is true then policy is loaded synchronously on // startup. - static scoped_ptr<ProfilePolicyConnector> CreateForBrowserContext( + static std::unique_ptr<ProfilePolicyConnector> CreateForBrowserContext( content::BrowserContext* context, bool force_immediate_load); @@ -71,7 +71,7 @@ ProfilePolicyConnector* GetForBrowserContextInternal( content::BrowserContext* context); - scoped_ptr<ProfilePolicyConnector> CreateForBrowserContextInternal( + std::unique_ptr<ProfilePolicyConnector> CreateForBrowserContextInternal( content::BrowserContext* context, bool force_immediate_load);
diff --git a/chrome/browser/policy/profile_policy_connector_unittest.cc b/chrome/browser/policy/profile_policy_connector_unittest.cc index 07cb990..217cae77 100644 --- a/chrome/browser/policy/profile_policy_connector_unittest.cc +++ b/chrome/browser/policy/profile_policy_connector_unittest.cc
@@ -56,7 +56,7 @@ SchemaRegistry schema_registry_; MockConfigurationPolicyProvider mock_provider_; MockCloudPolicyStore cloud_policy_store_; - scoped_ptr<CloudPolicyManager> cloud_policy_manager_; + std::unique_ptr<CloudPolicyManager> cloud_policy_manager_; }; TEST_F(ProfilePolicyConnectorTest, IsManagedForManagedUsers) {
diff --git a/chrome/browser/policy/schema_registry_service.cc b/chrome/browser/policy/schema_registry_service.cc index b4a872e..e86ad53 100644 --- a/chrome/browser/policy/schema_registry_service.cc +++ b/chrome/browser/policy/schema_registry_service.cc
@@ -13,7 +13,7 @@ namespace policy { SchemaRegistryService::SchemaRegistryService( - scoped_ptr<SchemaRegistry> registry, + std::unique_ptr<SchemaRegistry> registry, const Schema& chrome_schema, CombinedSchemaRegistry* global_registry) : registry_(std::move(registry)) {
diff --git a/chrome/browser/policy/schema_registry_service.h b/chrome/browser/policy/schema_registry_service.h index c2acbbf..8e9a4ae 100644 --- a/chrome/browser/policy/schema_registry_service.h +++ b/chrome/browser/policy/schema_registry_service.h
@@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_POLICY_SCHEMA_REGISTRY_SERVICE_H_ #define CHROME_BROWSER_POLICY_SCHEMA_REGISTRY_SERVICE_H_ +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "components/keyed_service/core/keyed_service.h" namespace policy { @@ -21,7 +22,7 @@ // This |registry| will initially contain only the |chrome_schema|, if // it's valid. The optional |global_registry| must outlive this, and will // track |registry|. - SchemaRegistryService(scoped_ptr<SchemaRegistry> registry, + SchemaRegistryService(std::unique_ptr<SchemaRegistry> registry, const Schema& chrome_schema, CombinedSchemaRegistry* global_registry); ~SchemaRegistryService() override; @@ -29,7 +30,7 @@ SchemaRegistry* registry() const { return registry_.get(); } private: - scoped_ptr<SchemaRegistry> registry_; + std::unique_ptr<SchemaRegistry> registry_; DISALLOW_COPY_AND_ASSIGN(SchemaRegistryService); };
diff --git a/chrome/browser/policy/schema_registry_service_factory.cc b/chrome/browser/policy/schema_registry_service_factory.cc index 1d7db134..5e0e4d3c 100644 --- a/chrome/browser/policy/schema_registry_service_factory.cc +++ b/chrome/browser/policy/schema_registry_service_factory.cc
@@ -71,7 +71,7 @@ } // static -scoped_ptr<SchemaRegistryService> +std::unique_ptr<SchemaRegistryService> SchemaRegistryServiceFactory::CreateForContext( content::BrowserContext* context, const Schema& chrome_schema, @@ -99,7 +99,7 @@ return it->second; } -scoped_ptr<SchemaRegistryService> +std::unique_ptr<SchemaRegistryService> SchemaRegistryServiceFactory::CreateForContextInternal( content::BrowserContext* context, const Schema& chrome_schema, @@ -107,7 +107,7 @@ DCHECK(!context->IsOffTheRecord()); DCHECK(registries_.find(context) == registries_.end()); - scoped_ptr<SchemaRegistry> registry; + std::unique_ptr<SchemaRegistry> registry; #if defined(OS_CHROMEOS) DeviceLocalAccountPolicyBroker* broker = GetBroker(context); @@ -123,7 +123,7 @@ if (!registry) registry.reset(new SchemaRegistry); - scoped_ptr<SchemaRegistryService> service(new SchemaRegistryService( + std::unique_ptr<SchemaRegistryService> service(new SchemaRegistryService( std::move(registry), chrome_schema, global_registry)); registries_[context] = service.get(); return service;
diff --git a/chrome/browser/policy/schema_registry_service_factory.h b/chrome/browser/policy/schema_registry_service_factory.h index 5602c7d..56d29565 100644 --- a/chrome/browser/policy/schema_registry_service_factory.h +++ b/chrome/browser/policy/schema_registry_service_factory.h
@@ -6,10 +6,10 @@ #define CHROME_BROWSER_POLICY_SCHEMA_REGISTRY_SERVICE_FACTORY_H_ #include <map> +#include <memory> #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "components/keyed_service/content/browser_context_keyed_base_factory.h" @@ -39,7 +39,7 @@ // Creates a new SchemaRegistryService for |context|, which must be managed // by the caller. Subsequent calls to GetForContext() will return the instance // created, as long as it lives. - static scoped_ptr<SchemaRegistryService> CreateForContext( + static std::unique_ptr<SchemaRegistryService> CreateForContext( content::BrowserContext* context, const Schema& chrome_schema, CombinedSchemaRegistry* global_registry); @@ -53,7 +53,7 @@ SchemaRegistryService* GetForContextInternal( content::BrowserContext* context); - scoped_ptr<SchemaRegistryService> CreateForContextInternal( + std::unique_ptr<SchemaRegistryService> CreateForContextInternal( content::BrowserContext* context, const Schema& chrome_schema, CombinedSchemaRegistry* global_registry);
diff --git a/chrome/browser/policy/test/local_policy_test_server.cc b/chrome/browser/policy/test/local_policy_test_server.cc index 26e1f72..db03d34 100644 --- a/chrome/browser/policy/test/local_policy_test_server.cc +++ b/chrome/browser/policy/test/local_policy_test_server.cc
@@ -118,14 +118,15 @@ const std::string& device_id) { CHECK(server_data_dir_.IsValid()); - scoped_ptr<base::DictionaryValue> client_dict(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> client_dict( + new base::DictionaryValue()); client_dict->SetString(kClientStateKeyDeviceId, device_id); client_dict->SetString(kClientStateKeyDeviceToken, dm_token); client_dict->SetString(kClientStateKeyMachineName, std::string()); client_dict->SetString(kClientStateKeyMachineId, std::string()); // Allow all policy types for now. - scoped_ptr<base::ListValue> types(new base::ListValue()); + std::unique_ptr<base::ListValue> types(new base::ListValue()); types->AppendString(dm_protocol::kChromeDevicePolicyType); types->AppendString(dm_protocol::kChromeUserPolicyType); types->AppendString(dm_protocol::kChromePublicAccountPolicyType);
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 89bf0a7..85082a5f 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu.cc
@@ -14,6 +14,7 @@ #include "base/command_line.h" #include "base/logging.h" #include "base/macros.h" +#include "base/metrics/field_trial.h" #include "base/metrics/histogram.h" #include "base/stl_util.h" #include "base/strings/string_util.h" @@ -454,7 +455,9 @@ void AddGoogleIconToLastMenuItem(ui::SimpleMenuModel* menu) { #if defined(GOOGLE_CHROME_BUILD) if (base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kEnableGoogleBrandedContextMenu)) { + switches::kEnableGoogleBrandedContextMenu) || + base::FieldTrialList::FindFullName("GoogleBrandedContextMenu") == + "branded") { menu->SetIcon( menu->GetItemCount() - 1, ui::ResourceBundle::GetSharedInstance().GetImageNamed(IDR_GOOGLE_ICON));
diff --git a/chrome/browser/resources/md_user_manager/compiled_resources2.gyp b/chrome/browser/resources/md_user_manager/compiled_resources2.gyp index caf1a92..e720b458a 100644 --- a/chrome/browser/resources/md_user_manager/compiled_resources2.gyp +++ b/chrome/browser/resources/md_user_manager/compiled_resources2.gyp
@@ -32,6 +32,10 @@ }, { 'target_name': 'supervised_user_learn_more', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + 'profile_browser_proxy', + ], 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], }, {
diff --git a/chrome/browser/resources/md_user_manager/profile_browser_proxy.js b/chrome/browser/resources/md_user_manager/profile_browser_proxy.js index b65f737..603c992 100644 --- a/chrome/browser/resources/md_user_manager/profile_browser_proxy.js +++ b/chrome/browser/resources/md_user_manager/profile_browser_proxy.js
@@ -91,7 +91,17 @@ */ launchUser: function(profilePath) { assertNotReached(); - } + }, + + /** + * Opens the given url in a new tab in the browser instance of the last + * active profile. Hyperlinks don't work in the user manager since its + * browser instance does not support tabs. + * @param {string} url + */ + openUrlInLastActiveProfileBrowser: function(url) { + assertNotReached(); + }, }; /** @@ -146,7 +156,12 @@ /** @override */ launchUser: function(profilePath) { chrome.send('launchUser', [profilePath]); - } + }, + + /** @override */ + openUrlInLastActiveProfileBrowser: function(url) { + chrome.send('openUrlInLastActiveProfileBrowser', [url]); + }, }; return {
diff --git a/chrome/browser/resources/md_user_manager/supervised_user_learn_more.js b/chrome/browser/resources/md_user_manager/supervised_user_learn_more.js index 1a009388..075b017 100644 --- a/chrome/browser/resources/md_user_manager/supervised_user_learn_more.js +++ b/chrome/browser/resources/md_user_manager/supervised_user_learn_more.js
@@ -10,8 +10,37 @@ Polymer({ is: 'supervised-user-learn-more', + properties: { + /** @private {!signin.ProfileBrowserProxy} */ + browserProxy_: Object + }, + + listeners: { + 'tap': 'onTap_' + }, + + /** @override */ + created: function() { + this.browserProxy_ = signin.ProfileBrowserProxyImpl.getInstance(); + }, + /** - * Handler for the 'Done' button click event. + * General handler for tap event on the host. + * @param {!Event} event + * @private + */ + onTap_: function(event) { + var element = Polymer.dom(event).rootTarget; + + // Handle the tap event only if the target is a '<a>' element. + if (element.nodeName == 'A') { + this.browserProxy_.openUrlInLastActiveProfileBrowser(element.href); + event.preventDefault(); + } + }, + + /** + * Handler for the 'Done' button tap event. * @param {!Event} event * @private */
diff --git a/chrome/browser/resources/options/sync_setup_overlay.css b/chrome/browser/resources/options/sync_setup_overlay.css index 0b79504..8d1c46f 100644 --- a/chrome/browser/resources/options/sync_setup_overlay.css +++ b/chrome/browser/resources/options/sync_setup_overlay.css
@@ -5,7 +5,7 @@ /* TODO(jhawkins): Organize these by page. */ #sync-setup-overlay * h4 { - margin: 5px 0; + margin: 15px 0 5px; } #sync-setup-overlay * form { @@ -80,14 +80,6 @@ color: rgb(255, 0, 0); } -#sync-setup-overlay * hr { - background-color: #ddd; - border: 0; - height: 1px; - text-align: left; - width: 100%; -} - #sync-setup-delete-profile { margin: 10px 0 0 0; } @@ -109,6 +101,29 @@ display: table; } +#customize-sync-encryption-new, +#personalize-google-services { + border-top: 1px solid #ddd; + margin-top: 5px; +} + +#personalize-google-services { + line-height: 1.6em; +} + +#personalize-google-services .title { + align-items: center; + display: flex; + justify-content: space-between; +} + +#googleg-logo { + background-image: url(../../../../ui/webui/resources/images/200-logo_googleg.png); + background-size: cover; + height: 20px; + width: 20px; +} + #passphrase-input { margin-bottom: 5px; margin-top: 5px;
diff --git a/chrome/browser/resources/options/sync_setup_overlay.html b/chrome/browser/resources/options/sync_setup_overlay.html index 8924552..161e90d 100644 --- a/chrome/browser/resources/options/sync_setup_overlay.html +++ b/chrome/browser/resources/options/sync_setup_overlay.html
@@ -115,7 +115,6 @@ i18n-content="learnMore"></a> </div> <div id="customize-sync-encryption-new"> - <hr> <h4 i18n-content="encryptionSectionTitle"></h4> <div id="encryption-section-message" i18n-content="encryptionSectionMessage"></div> @@ -191,6 +190,14 @@ i18n-values=".innerHTML:passphraseRecover" hidden> </div> </div> + <div id="personalize-google-services"> + <div class="title"> + <h4 i18n-content="personalizeGoogleServicesTitle"></h4> + <div id="googleg-logo" class="logo"></div> + </div> + <div i18n-values=".innerHTML:personalizeGoogleServicesMessage"> + </div> + </div> </div> <div class="action-area"> <div class="action-area-link-container">
diff --git a/chrome/browser/resources/options/sync_setup_overlay.js b/chrome/browser/resources/options/sync_setup_overlay.js index 59332d26..84d12ed 100644 --- a/chrome/browser/resources/options/sync_setup_overlay.js +++ b/chrome/browser/resources/options/sync_setup_overlay.js
@@ -144,6 +144,10 @@ $('sync-spinner-cancel').onclick = function() { self.closeOverlay_(); }; + $('activity-controls').onclick = function() { + chrome.metricsPrivate.recordUserAction( + 'Signin_AccountSettings_GoogleActivityControlsClicked'); + }; $('confirm-everything-ok').onclick = function() { self.sendConfiguration_(); }; @@ -643,6 +647,7 @@ // Hide the encryption section. $('customize-sync-encryption-new').hidden = true; + $('personalize-google-services').hidden = true; $('sync-custom-passphrase-container').hidden = true; $('sync-existing-passphrase-container').hidden = true; @@ -702,6 +707,7 @@ $('sync-custom-passphrase-container').hidden = false; $('sync-new-encryption-section-container').hidden = false; $('customize-sync-encryption-new').hidden = !args.encryptAllDataAllowed; + $('personalize-google-services').hidden = false; $('sync-existing-passphrase-container').hidden = true;
diff --git a/chrome/browser/resources/settings/site_settings/site_details_permission.js b/chrome/browser/resources/settings/site_settings/site_details_permission.js index 552ad5b..7ac2f6f5 100644 --- a/chrome/browser/resources/settings/site_settings/site_details_permission.js +++ b/chrome/browser/resources/settings/site_settings/site_details_permission.js
@@ -48,8 +48,8 @@ siteChanged_: function(site) { this.$.details.hidden = true; - var prefsProxy = settings.SiteSettingsPrefsBrowserProxyImpl.getInstance(); - prefsProxy.getExceptionList(this.category).then(function(exceptionList) { + this.browserProxy.getExceptionList(this.category).then( + function(exceptionList) { for (var i = 0; i < exceptionList.length; ++i) { if (exceptionList[i].origin == site.origin) { this.$.permission.selected = exceptionList[i].setting;
diff --git a/chrome/browser/resources/settings/site_settings/site_settings_category.js b/chrome/browser/resources/settings/site_settings/site_settings_category.js index 7016b24..88614f5 100644 --- a/chrome/browser/resources/settings/site_settings/site_settings_category.js +++ b/chrome/browser/resources/settings/site_settings/site_settings_category.js
@@ -54,7 +54,6 @@ this.$.blockList.categorySubtype = settings.PermissionValues.BLOCK; this.$.allowList.categorySubtype = settings.PermissionValues.ALLOW; - this.prefsProxy_ = settings.SiteSettingsPrefsBrowserProxyImpl.getInstance(); this.addWebUIListener('contentSettingCategoryChanged', this.defaultValueForCategoryChanged_.bind(this)); }, @@ -80,7 +79,7 @@ case settings.ContentSettingsTypes.JAVASCRIPT: case settings.ContentSettingsTypes.POPUPS: // "Allowed" vs "Blocked". - this.prefsProxy_.setDefaultValueForContentType( + this.browserProxy.setDefaultValueForContentType( this.category, this.categoryEnabled ? settings.PermissionValues.ALLOW : @@ -91,7 +90,7 @@ case settings.ContentSettingsTypes.CAMERA: case settings.ContentSettingsTypes.MIC: // "Ask" vs "Blocked". - this.prefsProxy_.setDefaultValueForContentType( + this.browserProxy.setDefaultValueForContentType( this.category, this.categoryEnabled ? settings.PermissionValues.ASK : @@ -99,7 +98,7 @@ break; case settings.ContentSettingsTypes.FULLSCREEN: // "Allowed" vs. "Ask first". - this.prefsProxy_.setDefaultValueForContentType( + this.browserProxy.setDefaultValueForContentType( this.category, this.categoryEnabled ? settings.PermissionValues.ALLOW :
diff --git a/chrome/browser/resources/settings/site_settings_page/site_settings_page.html b/chrome/browser/resources/settings/site_settings_page/site_settings_page.html index 0ae0e06..afb909f 100644 --- a/chrome/browser/resources/settings/site_settings_page/site_settings_page.html +++ b/chrome/browser/resources/settings/site_settings_page/site_settings_page.html
@@ -11,7 +11,104 @@ <link rel="import" type="css" href="site_settings_page.css"> <template> <div class="settings-box"> - <div id="list" class="settings-list"></div> + <div id="list" class="settings-list"> + <paper-icon-item category$="[[ALL_SITES]]" + on-tap="onTapCategory"> + <iron-icon icon="list" item-icon=""></iron-icon> + <div class="flex" i18n-content="siteSettingsCategoryAllSites"></div> + </paper-icon-item> + + <paper-icon-item category$="[[ContentSettingsTypes.COOKIES]]" + on-tap="onTapCategory"> + <iron-icon icon="[[computeIconForContentCategory( + ContentSettingsTypes.COOKIES)]]" item-icon=""></iron-icon> + <div class="flex"> + [[computeTitleForContentCategory(ContentSettingsTypes.COOKIES)]] + </div> + <div id="cookies" class="option-value"></div> + </paper-icon-item> + + <paper-icon-item category$="[[ContentSettingsTypes.GEOLOCATION]]" + on-tap="onTapCategory"> + <iron-icon icon="[[computeIconForContentCategory( + ContentSettingsTypes.GEOLOCATION)]]" item-icon=""></iron-icon> + <div class="flex"> + [[computeTitleForContentCategory(ContentSettingsTypes.GEOLOCATION)]] + </div> + <div id="geolocation" class="option-value"></div> + </paper-icon-item> + + <paper-icon-item category$="[[ContentSettingsTypes.CAMERA]]" + on-tap="onTapCategory"> + <iron-icon icon="[[computeIconForContentCategory( + ContentSettingsTypes.CAMERA)]]" item-icon=""></iron-icon> + <div class="flex"> + [[computeTitleForContentCategory(ContentSettingsTypes.CAMERA)]] + </div> + <div id="camera" class="option-value"></div> + </paper-icon-item> + + <paper-icon-item category$="[[ContentSettingsTypes.MIC]]" + on-tap="onTapCategory"> + <iron-icon icon="[[computeIconForContentCategory( + ContentSettingsTypes.MIC)]]" item-icon=""></iron-icon> + <div class="flex"> + [[computeTitleForContentCategory(ContentSettingsTypes.MIC)]] + </div> + <div id="mic" class="option-value"></div> + </paper-icon-item> + + <paper-icon-item category$="[[ContentSettingsTypes.JAVASCRIPT]]" + on-tap="onTapCategory"> + <iron-icon icon="[[computeIconForContentCategory( + ContentSettingsTypes.JAVASCRIPT)]]" item-icon=""></iron-icon> + <div class="flex"> + [[computeTitleForContentCategory(ContentSettingsTypes.JAVASCRIPT)]] + </div> + <div id="javascript" class="option-value"></div> + </paper-icon-item> + + <paper-icon-item category$="[[ContentSettingsTypes.POPUPS]]" + on-tap="onTapCategory"> + <iron-icon icon="[[computeIconForContentCategory( + ContentSettingsTypes.POPUPS)]]" item-icon=""></iron-icon> + <div class="flex"> + [[computeTitleForContentCategory(ContentSettingsTypes.POPUPS)]] + </div> + <div id="popups" class="option-value"></div> + </paper-icon-item> + + <paper-icon-item category$="[[ContentSettingsTypes.FULLSCREEN]]" + on-tap="onTapCategory"> + <iron-icon icon="[[computeIconForContentCategory( + ContentSettingsTypes.FULLSCREEN)]]" item-icon=""></iron-icon> + <div class="flex"> + [[computeTitleForContentCategory(ContentSettingsTypes.FULLSCREEN)]] + </div> + <div id="fullscreen" class="option-value"></div> + </paper-icon-item> + + <paper-icon-item category$="[[ContentSettingsTypes.NOTIFICATIONS]]" + on-tap="onTapCategory"> + <iron-icon icon="[[computeIconForContentCategory( + ContentSettingsTypes.NOTIFICATIONS)]]" item-icon=""></iron-icon> + <div class="flex"> + [[computeTitleForContentCategory( + ContentSettingsTypes.NOTIFICATIONS)]] + </div> + <div id="notifications" class="option-value"></div> + </paper-icon-item> + + <paper-icon-item category$="[[ContentSettingsTypes.IMAGES]]" + on-tap="onTapCategory"> + <iron-icon icon="[[computeIconForContentCategory( + ContentSettingsTypes.IMAGES)]]" item-icon=""></iron-icon> + <div class="flex"> + [[computeTitleForContentCategory(ContentSettingsTypes.IMAGES)]] + </div> + <div id="images" class="option-value"></div> + </paper-icon-item> + </div> </div> </template> <script src="site_settings_page.js"></script>
diff --git a/chrome/browser/resources/settings/site_settings_page/site_settings_page.js b/chrome/browser/resources/settings/site_settings_page/site_settings_page.js index 6734247..d4207d58 100644 --- a/chrome/browser/resources/settings/site_settings_page/site_settings_page.js +++ b/chrome/browser/resources/settings/site_settings_page/site_settings_page.js
@@ -31,82 +31,41 @@ }, ready: function() { - this.addAllSitesCategory_(); - this.addCategory_(settings.ContentSettingsTypes.COOKIES); - this.addCategory_(settings.ContentSettingsTypes.GEOLOCATION); - this.addCategory_(settings.ContentSettingsTypes.CAMERA); - this.addCategory_(settings.ContentSettingsTypes.MIC); - this.addCategory_(settings.ContentSettingsTypes.JAVASCRIPT); - this.addCategory_(settings.ContentSettingsTypes.POPUPS); - this.addCategory_(settings.ContentSettingsTypes.FULLSCREEN); - this.addCategory_(settings.ContentSettingsTypes.NOTIFICATIONS); - this.addCategory_(settings.ContentSettingsTypes.IMAGES); + this.ContentSettingsTypes = settings.ContentSettingsTypes; + this.ALL_SITES = settings.ALL_SITES; + + // Look up the default value for each category and show it. + this.setDefaultValue_(this.ContentSettingsTypes.COOKIES, '#cookies'); + this.setDefaultValue_(this.ContentSettingsTypes.GEOLOCATION, + '#geolocation'); + this.setDefaultValue_(this.ContentSettingsTypes.CAMERA, '#camera'); + this.setDefaultValue_(this.ContentSettingsTypes.MIC, '#mic'); + this.setDefaultValue_(this.ContentSettingsTypes.JAVASCRIPT, + '#javascript'); + this.setDefaultValue_(this.ContentSettingsTypes.POPUPS, '#popups'); + this.setDefaultValue_(this.ContentSettingsTypes.FULLSCREEN, + '#fullscreen'); + this.setDefaultValue_(this.ContentSettingsTypes.NOTIFICATIONS, + '#notifications'); + this.setDefaultValue_(this.ContentSettingsTypes.IMAGES, '#images'); + }, - /** - * Adds the All Sites category to the page. - * @private - */ - addAllSitesCategory_: function() { - var description = loadTimeData.getString('siteSettingsCategoryAllSites'); - this.addCategoryImpl_(-1, 'list', description, ''); - }, - - /** - * Adds a single category to the page. - * @param {number} category The category to add. - * @private - */ - addCategory_: function(category) { - var icon = this.computeIconForContentCategory(category); - var title = this.computeTitleForContentCategory(category); - var prefsProxy = settings.SiteSettingsPrefsBrowserProxyImpl.getInstance(); - prefsProxy.getDefaultValueForContentType( + setDefaultValue_: function(category, id) { + this.browserProxy.getDefaultValueForContentType( category).then(function(enabled) { var description = this.computeCategoryDesc(category, enabled, false); - this.addCategoryImpl_(category, icon, title, description); + this.$$(id).innerText = description; }.bind(this)); }, /** - * Constructs the actual HTML elements for the category. - * @param {number} category The category to add. - * @param {string} icon The icon to show with it. - * @param {string} title The title to show for the category. - * @param {string} defaultValue The default value (permission) for the - * category. - * @private - */ - addCategoryImpl_: function(category, icon, title, defaultValue) { - var root = this.$.list; - var paperIcon = document.createElement('paper-icon-item'); - paperIcon.addEventListener('tap', this.onTapCategory.bind(this, category)); - - var ironIcon = document.createElement('iron-icon'); - ironIcon.setAttribute('icon', icon); - ironIcon.setAttribute('item-icon', ''); - - var description = document.createElement('div'); - description.setAttribute('class', 'flex'); - description.appendChild(document.createTextNode(title)); - var setting = document.createElement('div'); - setting.setAttribute('class', 'option-value'); - - setting.appendChild(document.createTextNode(defaultValue)); - - paperIcon.appendChild(ironIcon); - paperIcon.appendChild(description); - paperIcon.appendChild(setting); - root.appendChild(paperIcon); - }, - - /** * Handles selection of a single category and navigates to the details for * that category. - * @param {number} category The category selected by the user. * @param {!Event} event The tap event. */ - onTapCategory: function(category, event) { + onTapCategory: function(event) { + var category = parseInt(event.currentTarget.getAttribute('category'), 10); if (category == -1) { this.currentRoute = { page: this.currentRoute.page,
diff --git a/chrome/browser/resources/sync_confirmation/sync_confirmation.css b/chrome/browser/resources/sync_confirmation/sync_confirmation.css index 4fedebf..7789779 100644 --- a/chrome/browser/resources/sync_confirmation/sync_confirmation.css +++ b/chrome/browser/resources/sync_confirmation/sync_confirmation.css
@@ -7,11 +7,6 @@ padding: 0; } -a { - color: rgb(85, 149, 254); - text-decoration: none; -} - .picture img { border-radius: 50%; max-height: 100%; @@ -20,29 +15,22 @@ .container { background-color: white; + color: #333; overflow: hidden; width: 448px; } .top-title-bar { - -webkit-padding-start: 24px; align-items: center; border-bottom: 1px solid lightgray; - color: #333; display: flex; font-size: 16px; height: 52px; + padding: 0 24px; } .details { - font-size: 13px; - padding: 20px 24px; -} - -.sync-message { - color: #595959; - line-height: 150%; - padding-bottom: 32px; + padding: 0 24px; } #picture-container { @@ -50,6 +38,7 @@ display: flex; justify-content: center; padding-bottom: 32px; + padding-top: 24px; } .picture { @@ -64,29 +53,71 @@ position: absolute; } -.action-container { - align-items: baseline; +.message-container { display: flex; - justify-content: flex-end; + margin-bottom: 16px; } -paper-button { +.message-container:last-child { + margin-bottom: 32px; +} + +.message-container .logo { + -webkit-margin-end: 20px; + background-size: cover; + flex-shrink: 0; + height: 20px; + position: relative; + top: -2px; + width: 20px; +} + +#chrome-logo { + background-image: url(../../../../ui/webui/resources/images/200-logo_chrome.png); +} + +#googleg-logo { + background-image: url(../../../../ui/webui/resources/images/200-logo_googleg.png); +} + +.message-container .title { + font-weight: 500; + margin-bottom: 4px; +} + +.message-container .body { + color: #646464; +} + +.message-container .text { + line-height: 20px; +} + +.message-container #activityControlsCheckbox { + -webkit-margin-start: 40px; +} + +.action-container { + display: flex; + justify-content: flex-end; + padding: 16px; +} + +#confirmButton, +#undoButton { font-weight: 500; line-height: 16px; margin: 0; padding: 8px 16px; } -paper-button + paper-button { - -webkit-margin-start: 8px; -} - #confirmButton { background-color: rgb(66, 133, 244); color: white; } #undoButton { + -webkit-margin-start: 8px; color: #5A5A5A; }
diff --git a/chrome/browser/resources/sync_confirmation/sync_confirmation.html b/chrome/browser/resources/sync_confirmation/sync_confirmation.html index 5d287a5..5095cb90 100644 --- a/chrome/browser/resources/sync_confirmation/sync_confirmation.html +++ b/chrome/browser/resources/sync_confirmation/sync_confirmation.html
@@ -6,10 +6,16 @@ <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html"> <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css"> <link rel="stylesheet" href="sync_confirmation.css"></link> + <style is="custom-style"> + a { + color: var(--google-blue-700); + text-decoration: none; + } + </style> </head> <body> <div class="container"> - <div class="top-title-bar" i18n-content="syncConfirmationTitle"></div> + <div class="top-title-bar">$i18n{syncConfirmationTitle}</div> <div class="details"> <div id="picture-container"> <div id="illustration"> @@ -38,14 +44,38 @@ </div> </div> </div> - <div class="sync-message" - i18n-values=".innerHTML:syncConfirmationChromeSyncBody"></div> - <div class="action-container"> - <paper-button id="confirmButton" - i18n-content="syncConfirmationConfirmLabel"></paper-button> - <paper-button id="undoButton" - i18n-content="syncConfirmationUndoLabel"></paper-button> + <div class="message-container"> + <div id="chrome-logo" class="logo"></div> + <div> + <div class="title">$i18n{syncConfirmationChromeSyncTitle}</div> + <div class="body text" + i18n-values=".innerHTML:syncConfirmationChromeSyncBody"></div> + </div> </div> + <div class="message-container"> + <div id="googleg-logo" class="logo"></div> + <div> + <div class="title"> + $i18n{syncConfirmationPersonalizeServicesTitle} + </div> + <div class="body text"> + $i18n{syncConfirmationPersonalizeServicesBody} + </div> + </div> + </div> + <div class="message-container"> + <div class="body" + i18n-values=".innerHTML:syncConfirmationSyncSettingsLinkBody"> + </div> + </div> + </div> + <div class="action-container"> + <paper-button id="confirmButton"> + $i18n{syncConfirmationConfirmLabel} + </paper-button> + <paper-button id="undoButton"> + $i18n{syncConfirmationUndoLabel} + </paper-button> </div> </div> </body>
diff --git a/chrome/browser/sessions/session_service.cc b/chrome/browser/sessions/session_service.cc index 323f31a2..43ed6e3 100644 --- a/chrome/browser/sessions/session_service.cc +++ b/chrome/browser/sessions/session_service.cc
@@ -971,19 +971,15 @@ switch (type) { case chrome::NOTIFICATION_SESSION_SERVICE_SAVED : RecordUpdatedSaveTime(delta, use_long_period); - RecordUpdatedSessionNavigationOrTab(delta, use_long_period); break; case content::NOTIFICATION_WEB_CONTENTS_DESTROYED: RecordUpdatedTabClosed(delta, use_long_period); - RecordUpdatedSessionNavigationOrTab(delta, use_long_period); break; case content::NOTIFICATION_NAV_LIST_PRUNED: RecordUpdatedNavListPruned(delta, use_long_period); - RecordUpdatedSessionNavigationOrTab(delta, use_long_period); break; case content::NOTIFICATION_NAV_ENTRY_COMMITTED: RecordUpdatedNavEntryCommit(delta, use_long_period); - RecordUpdatedSessionNavigationOrTab(delta, use_long_period); break; default: NOTREACHED() << "Bad type sent to RecordSessionUpdateHistogramData"; @@ -1069,25 +1065,6 @@ } } -void SessionService::RecordUpdatedSessionNavigationOrTab(base::TimeDelta delta, - bool use_long_period) { - std::string name("SessionRestore.NavOrTabUpdatePeriod"); - UMA_HISTOGRAM_CUSTOM_TIMES(name, - delta, - // 2500ms is the default save delay. - save_delay_in_millis_, - save_delay_in_mins_, - 50); - if (use_long_period) { - std::string long_name_("SessionRestore.NavOrTabUpdateLongPeriod"); - UMA_HISTOGRAM_CUSTOM_TIMES(long_name_, - delta, - save_delay_in_mins_, - save_delay_in_hrs_, - 50); - } -} - void SessionService::MaybeDeleteSessionOnlyData() { // Don't try anything if we're testing. The browser_process is not fully // created and DeleteSession will crash if we actually attempt it.
diff --git a/chrome/browser/sessions/session_service.h b/chrome/browser/sessions/session_service.h index d17a5b0..0986a6e 100644 --- a/chrome/browser/sessions/session_service.h +++ b/chrome/browser/sessions/session_service.h
@@ -327,8 +327,6 @@ void RecordUpdatedNavListPruned(base::TimeDelta delta, bool use_long_period); void RecordUpdatedNavEntryCommit(base::TimeDelta delta, bool use_long_period); void RecordUpdatedSaveTime(base::TimeDelta delta, bool use_long_period); - void RecordUpdatedSessionNavigationOrTab(base::TimeDelta delta, - bool use_long_period); // Deletes session data if no windows are open for the current profile. void MaybeDeleteSessionOnlyData();
diff --git a/chrome/browser/sync/chrome_sync_client.cc b/chrome/browser/sync/chrome_sync_client.cc index b3c5065..59cc4cac 100644 --- a/chrome/browser/sync/chrome_sync_client.cc +++ b/chrome/browser/sync/chrome_sync_client.cc
@@ -9,6 +9,7 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "build/build_config.h" #include "chrome/browser/autofill/personal_data_manager_factory.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" @@ -161,17 +162,17 @@ return window_delegates_getter_.get(); } - scoped_ptr<browser_sync::LocalSessionEventRouter> GetLocalSessionEventRouter() - override { + std::unique_ptr<browser_sync::LocalSessionEventRouter> + GetLocalSessionEventRouter() override { syncer::SyncableService::StartSyncFlare flare( sync_start_util::GetFlareForSyncableService(profile_->GetPath())); - return make_scoped_ptr( + return base::WrapUnique( new NotificationServiceSessionsRouter(profile_, this, flare)); } private: Profile* profile_; - scoped_ptr<SyncedWindowDelegatesGetter> window_delegates_getter_; + std::unique_ptr<SyncedWindowDelegatesGetter> window_delegates_getter_; DISALLOW_COPY_AND_ASSIGN(SyncSessionsClientImpl); }; @@ -478,7 +479,7 @@ } void ChromeSyncClient::SetSyncApiComponentFactoryForTesting( - scoped_ptr<sync_driver::SyncApiComponentFactory> component_factory) { + std::unique_ptr<sync_driver::SyncApiComponentFactory> component_factory) { component_factory_ = std::move(component_factory); }
diff --git a/chrome/browser/sync/chrome_sync_client.h b/chrome/browser/sync/chrome_sync_client.h index 6c2ac4aa..7ceeaf6 100644 --- a/chrome/browser/sync/chrome_sync_client.h +++ b/chrome/browser/sync/chrome_sync_client.h
@@ -63,7 +63,7 @@ void SetBrowsingDataRemoverObserverForTesting( BrowsingDataRemover::Observer* observer); void SetSyncApiComponentFactoryForTesting( - scoped_ptr<sync_driver::SyncApiComponentFactory> component_factory); + std::unique_ptr<sync_driver::SyncApiComponentFactory> component_factory); // Iterates over all of the profiles that have been loaded so far, and // extracts their tracker if present. If some profiles don't have trackers, no @@ -89,14 +89,14 @@ Profile* const profile_; // The sync api component factory in use by this client. - scoped_ptr<sync_driver::SyncApiComponentFactory> component_factory_; + std::unique_ptr<sync_driver::SyncApiComponentFactory> component_factory_; // Members that must be fetched on the UI thread but accessed on their // respective backend threads. scoped_refptr<autofill::AutofillWebDataService> web_data_service_; scoped_refptr<password_manager::PasswordStore> password_store_; - scoped_ptr<sync_sessions::SyncSessionsClient> sync_sessions_client_; + std::unique_ptr<sync_sessions::SyncSessionsClient> sync_sessions_client_; // Generates and monitors the ExtensionsActivity object used by sync. ExtensionsActivityMonitor extensions_activity_monitor_;
diff --git a/chrome/browser/sync/chrome_sync_client_unittest.cc b/chrome/browser/sync/chrome_sync_client_unittest.cc index 41c34a6..2c286aa 100644 --- a/chrome/browser/sync/chrome_sync_client_unittest.cc +++ b/chrome/browser/sync/chrome_sync_client_unittest.cc
@@ -4,7 +4,8 @@ #include "chrome/browser/sync/chrome_sync_client.h" -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "chrome/common/url_constants.h" #include "components/sync_driver/sync_api_component_factory.h" #include "components/sync_sessions/sync_sessions_client.h" @@ -29,7 +30,7 @@ private: content::TestBrowserThreadBundle thread_bundle_; - scoped_ptr<ChromeSyncClient> sync_client_; + std::unique_ptr<ChromeSyncClient> sync_client_; }; TEST_F(ChromeSyncClientTest, ShouldSyncURL) {
diff --git a/chrome/browser/sync/profile_sync_service_android.cc b/chrome/browser/sync/profile_sync_service_android.cc index cb7b4a2c9..81d83b85 100644 --- a/chrome/browser/sync/profile_sync_service_android.cc +++ b/chrome/browser/sync/profile_sync_service_android.cc
@@ -7,6 +7,8 @@ #include <stddef.h> #include <stdint.h> +#include <memory> + #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" @@ -14,7 +16,7 @@ #include "base/i18n/time_formatting.h" #include "base/json/json_writer.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "chrome/browser/browser_process.h" @@ -54,7 +56,7 @@ // results are sent to the Java callback. void NativeGetAllNodesCallback( const base::android::ScopedJavaGlobalRef<jobject>& callback, - scoped_ptr<base::ListValue> result) { + std::unique_ptr<base::ListValue> result) { JNIEnv* env = base::android::AttachCurrentThread(); std::string json_string; if (!result.get() || !base::JSONWriter::Write(*result, &json_string)) { @@ -344,7 +346,7 @@ base::android::ScopedJavaGlobalRef<jobject> java_callback; java_callback.Reset(env, callback); - base::Callback<void(scoped_ptr<base::ListValue>)> native_callback = + base::Callback<void(std::unique_ptr<base::ListValue>)> native_callback = base::Bind(&NativeGetAllNodesCallback, java_callback); sync_service_->GetAllNodes(native_callback); } @@ -454,7 +456,7 @@ const JavaParamRef<jobject>&) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - scoped_ptr<base::DictionaryValue> about_info = + std::unique_ptr<base::DictionaryValue> about_info = sync_driver::sync_ui_util::ConstructAboutInformation( sync_service_, sync_service_->signin(), chrome::GetChannel()); std::string about_info_json; @@ -480,7 +482,7 @@ syncer::NetworkResources* resources = reinterpret_cast<syncer::NetworkResources*>(network_resources); sync_service_->OverrideNetworkResourcesForTest( - make_scoped_ptr<syncer::NetworkResources>(resources)); + base::WrapUnique<syncer::NetworkResources>(resources)); } // static
diff --git a/chrome/browser/sync/profile_sync_service_android.h b/chrome/browser/sync/profile_sync_service_android.h index 9be8bee..4509902 100644 --- a/chrome/browser/sync/profile_sync_service_android.h +++ b/chrome/browser/sync/profile_sync_service_android.h
@@ -193,7 +193,7 @@ // The class that handles getting, setting, and persisting sync // preferences. - scoped_ptr<sync_driver::SyncPrefs> sync_prefs_; + std::unique_ptr<sync_driver::SyncPrefs> sync_prefs_; // Java-side ProfileSyncService object. JavaObjectWeakGlobalRef weak_java_profile_sync_service_;
diff --git a/chrome/browser/sync/profile_sync_service_factory.cc b/chrome/browser/sync/profile_sync_service_factory.cc index 133869ce..b4abcdf 100644 --- a/chrome/browser/sync/profile_sync_service_factory.cc +++ b/chrome/browser/sync/profile_sync_service_factory.cc
@@ -6,6 +6,7 @@ #include <utility> +#include "base/memory/ptr_util.h" #include "base/memory/singleton.h" #include "base/time/time.h" #include "build/build_config.h" @@ -153,7 +154,7 @@ AboutSigninInternalsFactory::GetForProfile(profile); init_params.signin_wrapper = - make_scoped_ptr(new SupervisedUserSigninManagerWrapper(profile, signin)); + base::WrapUnique(new SupervisedUserSigninManagerWrapper(profile, signin)); init_params.oauth2_token_service = ProfileOAuth2TokenServiceFactory::GetForProfile(profile); init_params.gaia_cookie_manager_service = @@ -170,7 +171,7 @@ : ProfileSyncService::MANUAL_START; init_params.sync_client = - make_scoped_ptr(new browser_sync::ChromeSyncClient(profile)); + base::WrapUnique(new browser_sync::ChromeSyncClient(profile)); init_params.network_time_update_callback = base::Bind(&UpdateNetworkTime); init_params.base_directory = profile->GetPath(); @@ -185,7 +186,7 @@ content::BrowserThread::FILE); init_params.blocking_pool = content::BrowserThread::GetBlockingPool(); - auto pss = make_scoped_ptr(new ProfileSyncService(std::move(init_params))); + auto pss = base::WrapUnique(new ProfileSyncService(std::move(init_params))); // Will also initialize the sync client. pss->Initialize();
diff --git a/chrome/browser/sync/profile_sync_service_factory_unittest.cc b/chrome/browser/sync/profile_sync_service_factory_unittest.cc index 0c38068f..4f7ac95 100644 --- a/chrome/browser/sync/profile_sync_service_factory_unittest.cc +++ b/chrome/browser/sync/profile_sync_service_factory_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/sync/profile_sync_service_factory.h" + #include <stddef.h> +#include <memory> + #include "base/command_line.h" -#include "base/memory/scoped_ptr.h" #include "build/build_config.h" -#include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/test/base/testing_profile.h" #include "components/browser_sync/browser/profile_sync_service.h" #include "components/browser_sync/common/browser_sync_switches.h" @@ -98,7 +100,7 @@ private: content::TestBrowserThreadBundle thread_bundle_; - scoped_ptr<Profile> profile_; + std::unique_ptr<Profile> profile_; }; // Verify that the disable sync flag disables creation of the sync service.
diff --git a/chrome/browser/sync/profile_sync_test_util.cc b/chrome/browser/sync/profile_sync_test_util.cc index 8a27ff3..0e8e8769 100644 --- a/chrome/browser/sync/profile_sync_test_util.cc +++ b/chrome/browser/sync/profile_sync_test_util.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 "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" @@ -23,10 +24,10 @@ ProfileSyncService::InitParams CreateProfileSyncServiceParamsForTest( Profile* profile) { auto sync_client = - make_scoped_ptr(new browser_sync::ChromeSyncClient(profile)); + base::WrapUnique(new browser_sync::ChromeSyncClient(profile)); sync_client->SetSyncApiComponentFactoryForTesting( - make_scoped_ptr(new SyncApiComponentFactoryMock())); + base::WrapUnique(new SyncApiComponentFactoryMock())); ProfileSyncService::InitParams init_params = CreateProfileSyncServiceParamsForTest(std::move(sync_client), profile); @@ -35,11 +36,11 @@ } ProfileSyncService::InitParams CreateProfileSyncServiceParamsForTest( - scoped_ptr<sync_driver::SyncClient> sync_client, + std::unique_ptr<sync_driver::SyncClient> sync_client, Profile* profile) { ProfileSyncService::InitParams init_params; - init_params.signin_wrapper = make_scoped_ptr( + init_params.signin_wrapper = base::WrapUnique( new SigninManagerWrapper(SigninManagerFactory::GetForProfile(profile))); init_params.oauth2_token_service = ProfileOAuth2TokenServiceFactory::GetForProfile(profile); @@ -61,16 +62,16 @@ return init_params; } -scoped_ptr<TestingProfile> MakeSignedInTestingProfile() { - auto profile = make_scoped_ptr(new TestingProfile()); +std::unique_ptr<TestingProfile> MakeSignedInTestingProfile() { + auto profile = base::WrapUnique(new TestingProfile()); SigninManagerFactory::GetForProfile(profile.get()) ->SetAuthenticatedAccountInfo("12345", "foo"); return profile; } -scoped_ptr<KeyedService> BuildMockProfileSyncService( +std::unique_ptr<KeyedService> BuildMockProfileSyncService( content::BrowserContext* context) { - return make_scoped_ptr( + return base::WrapUnique( new ProfileSyncServiceMock(CreateProfileSyncServiceParamsForTest( Profile::FromBrowserContext(context)))); }
diff --git a/chrome/browser/sync/profile_sync_test_util.h b/chrome/browser/sync/profile_sync_test_util.h index 78fc05b3..9c665f44 100644 --- a/chrome/browser/sync/profile_sync_test_util.h +++ b/chrome/browser/sync/profile_sync_test_util.h
@@ -5,10 +5,10 @@ #ifndef CHROME_BROWSER_SYNC_PROFILE_SYNC_TEST_UTIL_H_ #define CHROME_BROWSER_SYNC_PROFILE_SYNC_TEST_UTIL_H_ +#include <memory> #include <string> #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "components/browser_sync/browser/profile_sync_service_mock.h" #include "content/public/browser/browser_thread.h" @@ -46,16 +46,16 @@ ProfileSyncService::InitParams CreateProfileSyncServiceParamsForTest( Profile* profile); ProfileSyncService::InitParams CreateProfileSyncServiceParamsForTest( - scoped_ptr<sync_driver::SyncClient> sync_client, + std::unique_ptr<sync_driver::SyncClient> sync_client, Profile* profile); // A utility used by sync tests to create a TestingProfile with a Google // Services username stored in a (Testing)PrefService. -scoped_ptr<TestingProfile> MakeSignedInTestingProfile(); +std::unique_ptr<TestingProfile> MakeSignedInTestingProfile(); // Helper routine to be used in conjunction with // BrowserContextKeyedServiceFactory::SetTestingFactory(). -scoped_ptr<KeyedService> BuildMockProfileSyncService( +std::unique_ptr<KeyedService> BuildMockProfileSyncService( content::BrowserContext* context); #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_TEST_UTIL_H_
diff --git a/chrome/browser/sync/sessions/notification_service_sessions_router.h b/chrome/browser/sync/sessions/notification_service_sessions_router.h index 8cf2db68..d4a2fee 100644 --- a/chrome/browser/sync/sessions/notification_service_sessions_router.h +++ b/chrome/browser/sync/sessions/notification_service_sessions_router.h
@@ -71,8 +71,8 @@ sync_sessions::SyncSessionsClient* const sessions_client_; syncer::SyncableService::StartSyncFlare flare_; - scoped_ptr<base::CallbackList<void(const std::set<GURL>&, - const GURL&)>::Subscription> + std::unique_ptr<base::CallbackList<void(const std::set<GURL>&, + const GURL&)>::Subscription> favicon_changed_subscription_; base::WeakPtrFactory<NotificationServiceSessionsRouter> weak_ptr_factory_;
diff --git a/chrome/browser/sync/sessions/sessions_sync_manager_unittest.cc b/chrome/browser/sync/sessions/sessions_sync_manager_unittest.cc index 750b869..4461cdf 100644 --- a/chrome/browser/sync/sessions/sessions_sync_manager_unittest.cc +++ b/chrome/browser/sync/sessions/sessions_sync_manager_unittest.cc
@@ -261,8 +261,8 @@ void Stop() override {} }; -scoped_ptr<LocalSessionEventRouter> NewDummyRouter() { - return scoped_ptr<LocalSessionEventRouter>(new DummyRouter()); +std::unique_ptr<LocalSessionEventRouter> NewDummyRouter() { + return std::unique_ptr<LocalSessionEventRouter>(new DummyRouter()); } // Provides ability to override SyncedWindowDelegatesGetter. @@ -302,8 +302,8 @@ : sync_sessions_client_->GetSyncedWindowDelegatesGetter(); } - scoped_ptr<browser_sync::LocalSessionEventRouter> GetLocalSessionEventRouter() - override { + std::unique_ptr<browser_sync::LocalSessionEventRouter> + GetLocalSessionEventRouter() override { return sync_sessions_client_->GetLocalSessionEventRouter(); } @@ -345,7 +345,7 @@ sync_prefs_.reset(new sync_driver::SyncPrefs(profile()->GetPrefs())); manager_.reset(new SessionsSyncManager( GetSyncSessionsClient(), sync_prefs_.get(), local_device_.get(), - scoped_ptr<LocalSessionEventRouter>(router), + std::unique_ptr<LocalSessionEventRouter>(router), base::Bind(&SessionNotificationObserver::NotifyOfUpdate, base::Unretained(&observer_)), base::Bind(&SessionNotificationObserver::NotifyOfRefresh, @@ -374,8 +374,8 @@ test_processor_ = new TestSyncProcessorStub(output); syncer::SyncMergeResult result = manager_->MergeDataAndStartSyncing( syncer::SESSIONS, initial_data, - scoped_ptr<syncer::SyncChangeProcessor>(test_processor_), - scoped_ptr<syncer::SyncErrorFactory>( + std::unique_ptr<syncer::SyncChangeProcessor>(test_processor_), + std::unique_ptr<syncer::SyncErrorFactory>( new syncer::SyncErrorFactoryMock())); EXPECT_FALSE(result.error().IsSet()); } @@ -425,14 +425,14 @@ } private: - scoped_ptr<browser_sync::ChromeSyncClient> sync_client_; - scoped_ptr<SyncSessionsClientShim> sessions_client_shim_; - scoped_ptr<sync_driver::SyncPrefs> sync_prefs_; + std::unique_ptr<browser_sync::ChromeSyncClient> sync_client_; + std::unique_ptr<SyncSessionsClientShim> sessions_client_shim_; + std::unique_ptr<sync_driver::SyncPrefs> sync_prefs_; SessionNotificationObserver observer_; - scoped_ptr<SessionsSyncManager> manager_; + std::unique_ptr<SessionsSyncManager> manager_; SessionSyncTestHelper helper_; TestSyncProcessorStub* test_processor_; - scoped_ptr<LocalDeviceInfoProviderMock> local_device_; + std::unique_ptr<LocalDeviceInfoProviderMock> local_device_; }; // Test that the SyncSessionManager can properly fill in a SessionHeader. @@ -488,7 +488,7 @@ current_entry_index_ = i; } - void AppendEntry(scoped_ptr<content::NavigationEntry> entry) { + void AppendEntry(std::unique_ptr<content::NavigationEntry> entry) { entries_.push_back(std::move(entry)); } @@ -537,7 +537,7 @@ void set_blocked_navigations( std::vector<const content::NavigationEntry*>* navs) { for (auto* entry : *navs) { - scoped_ptr<sessions::SerializedNavigationEntry> serialized_entry( + std::unique_ptr<sessions::SerializedNavigationEntry> serialized_entry( new sessions::SerializedNavigationEntry()); *serialized_entry = sessions::ContentSerializedNavigationBuilder::FromNavigationEntry( @@ -588,19 +588,19 @@ TEST_F(SessionsSyncManagerTest, SetSessionTabFromDelegate) { // Create a tab with three valid entries. SyncedTabDelegateFake tab; - scoped_ptr<content::NavigationEntry> entry1( + std::unique_ptr<content::NavigationEntry> entry1( content::NavigationEntry::Create()); GURL url1("http://www.google.com/"); entry1->SetVirtualURL(url1); entry1->SetTimestamp(kTime1); entry1->SetHttpStatusCode(200); - scoped_ptr<content::NavigationEntry> entry2( + std::unique_ptr<content::NavigationEntry> entry2( content::NavigationEntry::Create()); GURL url2("http://www.noodle.com/"); entry2->SetVirtualURL(url2); entry2->SetTimestamp(kTime2); entry2->SetHttpStatusCode(201); - scoped_ptr<content::NavigationEntry> entry3( + std::unique_ptr<content::NavigationEntry> entry3( content::NavigationEntry::Create()); GURL url3("http://www.doodle.com/"); entry3->SetVirtualURL(url3); @@ -658,61 +658,61 @@ // stack gets trucated to +/- 6 entries. TEST_F(SessionsSyncManagerTest, SetSessionTabFromDelegateNavigationIndex) { SyncedTabDelegateFake tab; - scoped_ptr<content::NavigationEntry> entry0( + std::unique_ptr<content::NavigationEntry> entry0( content::NavigationEntry::Create()); GURL url0("http://www.google.com/"); entry0->SetVirtualURL(url0); entry0->SetTimestamp(kTime0); entry0->SetHttpStatusCode(200); - scoped_ptr<content::NavigationEntry> entry1( + std::unique_ptr<content::NavigationEntry> entry1( content::NavigationEntry::Create()); GURL url1("http://www.zoogle.com/"); entry1->SetVirtualURL(url1); entry1->SetTimestamp(kTime1); entry1->SetHttpStatusCode(200); - scoped_ptr<content::NavigationEntry> entry2( + std::unique_ptr<content::NavigationEntry> entry2( content::NavigationEntry::Create()); GURL url2("http://www.noogle.com/"); entry2->SetVirtualURL(url2); entry2->SetTimestamp(kTime2); entry2->SetHttpStatusCode(200); - scoped_ptr<content::NavigationEntry> entry3( + std::unique_ptr<content::NavigationEntry> entry3( content::NavigationEntry::Create()); GURL url3("http://www.doogle.com/"); entry3->SetVirtualURL(url3); entry3->SetTimestamp(kTime3); entry3->SetHttpStatusCode(200); - scoped_ptr<content::NavigationEntry> entry4( + std::unique_ptr<content::NavigationEntry> entry4( content::NavigationEntry::Create()); GURL url4("http://www.yoogle.com/"); entry4->SetVirtualURL(url4); entry4->SetTimestamp(kTime4); entry4->SetHttpStatusCode(200); - scoped_ptr<content::NavigationEntry> entry5( + std::unique_ptr<content::NavigationEntry> entry5( content::NavigationEntry::Create()); GURL url5("http://www.foogle.com/"); entry5->SetVirtualURL(url5); entry5->SetTimestamp(kTime5); entry5->SetHttpStatusCode(200); - scoped_ptr<content::NavigationEntry> entry6( + std::unique_ptr<content::NavigationEntry> entry6( content::NavigationEntry::Create()); GURL url6("http://www.boogle.com/"); entry6->SetVirtualURL(url6); entry6->SetTimestamp(kTime6); entry6->SetHttpStatusCode(200); - scoped_ptr<content::NavigationEntry> entry7( + std::unique_ptr<content::NavigationEntry> entry7( content::NavigationEntry::Create()); GURL url7("http://www.moogle.com/"); entry7->SetVirtualURL(url7); entry7->SetTimestamp(kTime7); entry7->SetHttpStatusCode(200); - scoped_ptr<content::NavigationEntry> entry8( + std::unique_ptr<content::NavigationEntry> entry8( content::NavigationEntry::Create()); GURL url8("http://www.poogle.com/"); entry8->SetVirtualURL(url8); entry8->SetTimestamp(kTime8); entry8->SetHttpStatusCode(200); - scoped_ptr<content::NavigationEntry> entry9( + std::unique_ptr<content::NavigationEntry> entry9( content::NavigationEntry::Create()); GURL url9("http://www.roogle.com/"); entry9->SetVirtualURL(url9); @@ -745,22 +745,22 @@ // stack if the current navigation is invalid. TEST_F(SessionsSyncManagerTest, SetSessionTabFromDelegateCurrentInvalid) { SyncedTabDelegateFake tab; - scoped_ptr<content::NavigationEntry> entry0( + std::unique_ptr<content::NavigationEntry> entry0( content::NavigationEntry::Create()); entry0->SetVirtualURL(GURL("http://www.google.com")); entry0->SetTimestamp(kTime0); entry0->SetHttpStatusCode(200); - scoped_ptr<content::NavigationEntry> entry1( + std::unique_ptr<content::NavigationEntry> entry1( content::NavigationEntry::Create()); entry1->SetVirtualURL(GURL("")); entry1->SetTimestamp(kTime1); entry1->SetHttpStatusCode(200); - scoped_ptr<content::NavigationEntry> entry2( + std::unique_ptr<content::NavigationEntry> entry2( content::NavigationEntry::Create()); entry2->SetVirtualURL(GURL("http://www.noogle.com")); entry2->SetTimestamp(kTime2); entry2->SetHttpStatusCode(200); - scoped_ptr<content::NavigationEntry> entry3( + std::unique_ptr<content::NavigationEntry> entry3( content::NavigationEntry::Create()); entry3->SetVirtualURL(GURL("http://www.doogle.com")); entry3->SetTimestamp(kTime3); @@ -807,19 +807,19 @@ // as such, while regular navigations are marked as allowed. TEST_F(SessionsSyncManagerTest, BlockedNavigations) { SyncedTabDelegateFake tab; - scoped_ptr<content::NavigationEntry> entry1( + std::unique_ptr<content::NavigationEntry> entry1( content::NavigationEntry::Create()); GURL url1("http://www.google.com/"); entry1->SetVirtualURL(url1); entry1->SetTimestamp(kTime1); tab.AppendEntry(std::move(entry1)); - scoped_ptr<content::NavigationEntry> entry2( + std::unique_ptr<content::NavigationEntry> entry2( content::NavigationEntry::Create()); GURL url2("http://blocked.com/foo"); entry2->SetVirtualURL(url2); entry2->SetTimestamp(kTime2); - scoped_ptr<content::NavigationEntry> entry3( + std::unique_ptr<content::NavigationEntry> entry3( content::NavigationEntry::Create()); GURL url3("http://evil.com/"); entry3->SetVirtualURL(url3); @@ -915,10 +915,9 @@ local_device(), NewDummyRouter(), base::Closure(), base::Closure()); syncer::SyncMergeResult result = manager2.MergeDataAndStartSyncing( - syncer::SESSIONS, in, - scoped_ptr<syncer::SyncChangeProcessor>( - new TestSyncProcessorStub(&out)), - scoped_ptr<syncer::SyncErrorFactory>( + syncer::SESSIONS, in, std::unique_ptr<syncer::SyncChangeProcessor>( + new TestSyncProcessorStub(&out)), + std::unique_ptr<syncer::SyncErrorFactory>( new syncer::SyncErrorFactoryMock())); ASSERT_FALSE(result.error().IsSet()); @@ -987,15 +986,14 @@ t2.GetSpecifics().session().tab().tab_id()); std::set<const SyncedWindowDelegate*> delegates; delegates.insert(&window_override); - scoped_ptr<TestSyncedWindowDelegatesGetter> getter( + std::unique_ptr<TestSyncedWindowDelegatesGetter> getter( new TestSyncedWindowDelegatesGetter(delegates)); set_synced_window_getter(getter.get()); syncer::SyncMergeResult result = manager()->MergeDataAndStartSyncing( - syncer::SESSIONS, in, - scoped_ptr<syncer::SyncChangeProcessor>( - new TestSyncProcessorStub(&out)), - scoped_ptr<syncer::SyncErrorFactory>( + syncer::SESSIONS, in, std::unique_ptr<syncer::SyncChangeProcessor>( + new TestSyncProcessorStub(&out)), + std::unique_ptr<syncer::SyncErrorFactory>( new syncer::SyncErrorFactoryMock())); // There should be two changes, one for the fully associated tab, and @@ -1506,10 +1504,9 @@ local_device(), NewDummyRouter(), base::Closure(), base::Closure()); syncer::SyncMergeResult result = manager2.MergeDataAndStartSyncing( - syncer::SESSIONS, in, - scoped_ptr<syncer::SyncChangeProcessor>( - new TestSyncProcessorStub(&changes)), - scoped_ptr<syncer::SyncErrorFactory>( + syncer::SESSIONS, in, std::unique_ptr<syncer::SyncChangeProcessor>( + new TestSyncProcessorStub(&changes)), + std::unique_ptr<syncer::SyncErrorFactory>( new syncer::SyncErrorFactoryMock())); ASSERT_FALSE(result.error().IsSet()); EXPECT_TRUE(FilterOutLocalHeaderChanges(&changes)->empty()); @@ -1962,7 +1959,7 @@ // To simulate WebContents swap during prerendering, create new WebContents // and swap with old WebContents. - scoped_ptr<content::WebContents> old_web_contents; + std::unique_ptr<content::WebContents> old_web_contents; old_web_contents.reset(browser()->tab_strip_model()->GetActiveWebContents()); // Create new WebContents, with the required tab helpers.
diff --git a/chrome/browser/sync/sync_error_notifier_ash_unittest.cc b/chrome/browser/sync/sync_error_notifier_ash_unittest.cc index edc7acc..ddd0ee0 100644 --- a/chrome/browser/sync/sync_error_notifier_ash_unittest.cc +++ b/chrome/browser/sync/sync_error_notifier_ash_unittest.cc
@@ -6,9 +6,11 @@ #include <stddef.h> +#include <memory> + #include "ash/test/ash_test_base.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/notifications/notification.h" @@ -70,9 +72,9 @@ int focus_ui_call_count_; }; -scoped_ptr<KeyedService> BuildMockLoginUIService( +std::unique_ptr<KeyedService> BuildMockLoginUIService( content::BrowserContext* profile) { - return make_scoped_ptr(new FakeLoginUIService()); + return base::WrapUnique(new FakeLoginUIService()); } class SyncErrorNotifierTest : public AshTestBase { @@ -157,12 +159,12 @@ } #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<SyncErrorController> error_controller_; - scoped_ptr<SyncErrorNotifier> error_notifier_; - scoped_ptr<ProfileSyncServiceMock> service_; + std::unique_ptr<TestingProfileManager> profile_manager_; + std::unique_ptr<SyncErrorController> error_controller_; + std::unique_ptr<SyncErrorNotifier> error_notifier_; + std::unique_ptr<ProfileSyncServiceMock> service_; TestingProfile* profile_; FakeLoginUI login_ui_; NotificationUIManager* notification_ui_manager_;
diff --git a/chrome/browser/sync/sync_global_error_unittest.cc b/chrome/browser/sync/sync_global_error_unittest.cc index d35c0af..c1d76d4 100644 --- a/chrome/browser/sync/sync_global_error_unittest.cc +++ b/chrome/browser/sync/sync_global_error_unittest.cc
@@ -4,8 +4,10 @@ #include "chrome/browser/sync/sync_global_error.h" +#include <memory> + #include "base/macros.h" -#include "base/memory/scoped_ptr.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/sync/profile_sync_test_util.h" #include "chrome/browser/sync/sync_global_error_factory.h" @@ -50,9 +52,9 @@ int focus_ui_call_count_; }; -scoped_ptr<KeyedService> BuildMockLoginUIService( +std::unique_ptr<KeyedService> BuildMockLoginUIService( content::BrowserContext* profile) { - return make_scoped_ptr(new FakeLoginUIService()); + return base::WrapUnique(new FakeLoginUIService()); } // Same as BrowserWithTestWindowTest, but uses MockBrowser to test calls to @@ -71,7 +73,7 @@ Profile* profile() { return profile_.get(); } private: - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<TestingProfile> profile_; DISALLOW_COPY_AND_ASSIGN(SyncGlobalErrorTest); };
diff --git a/chrome/browser/sync/sync_startup_tracker_unittest.cc b/chrome/browser/sync/sync_startup_tracker_unittest.cc index f3e8bd0..195c6a6 100644 --- a/chrome/browser/sync/sync_startup_tracker_unittest.cc +++ b/chrome/browser/sync/sync_startup_tracker_unittest.cc
@@ -2,10 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/memory/scoped_ptr.h" +#include "chrome/browser/sync/sync_startup_tracker.h" + +#include <memory> + #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/profile_sync_test_util.h" -#include "chrome/browser/sync/sync_startup_tracker.h" #include "chrome/test/base/testing_profile.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gmock/include/gmock/gmock.h" @@ -61,7 +63,7 @@ content::TestBrowserThreadBundle thread_bundle_; GoogleServiceAuthError no_error_; - scoped_ptr<TestingProfile> profile_; + std::unique_ptr<TestingProfile> profile_; ProfileSyncServiceMock* mock_pss_; MockObserver observer_; };
diff --git a/chrome/browser/sync/sync_ui_util_unittest.cc b/chrome/browser/sync/sync_ui_util_unittest.cc index 4cb7724..7fdf0d1 100644 --- a/chrome/browser/sync/sync_ui_util_unittest.cc +++ b/chrome/browser/sync/sync_ui_util_unittest.cc
@@ -87,7 +87,7 @@ // Test that GetStatusLabelsForSyncGlobalError returns an error if a // passphrase is required. TEST_F(SyncUIUtilTest, PassphraseGlobalError) { - scoped_ptr<Profile> profile = MakeSignedInTestingProfile(); + std::unique_ptr<Profile> profile = MakeSignedInTestingProfile(); ProfileSyncServiceMock service( CreateProfileSyncServiceParamsForTest(profile.get())); browser_sync::SyncBackendHost::Status status; @@ -107,7 +107,7 @@ // Test that GetStatusLabelsForSyncGlobalError returns an error if a // passphrase is required and not for auth errors. TEST_F(SyncUIUtilTest, AuthAndPassphraseGlobalError) { - scoped_ptr<Profile> profile(MakeSignedInTestingProfile()); + std::unique_ptr<Profile> profile(MakeSignedInTestingProfile()); ProfileSyncServiceMock service( CreateProfileSyncServiceParamsForTest(profile.get())); browser_sync::SyncBackendHost::Status status; @@ -135,7 +135,7 @@ // Test that GetStatusLabelsForSyncGlobalError does not indicate errors for // auth errors (these are reported through SigninGlobalError). TEST_F(SyncUIUtilTest, AuthStateGlobalError) { - scoped_ptr<Profile> profile(MakeSignedInTestingProfile()); + std::unique_ptr<Profile> profile(MakeSignedInTestingProfile()); ProfileSyncService::InitParams init_params = CreateProfileSyncServiceParamsForTest(profile.get()); NiceMock<ProfileSyncServiceMock> service(&init_params); @@ -337,7 +337,7 @@ TEST_F(SyncUIUtilTest, DistinctCasesReportUniqueMessageSets) { std::set<base::string16> messages; for (int idx = 0; idx != NUMBER_OF_STATUS_CASES; idx++) { - scoped_ptr<Profile> profile(new TestingProfile()); + std::unique_ptr<Profile> profile(new TestingProfile()); ProfileSyncService::InitParams init_params = CreateProfileSyncServiceParamsForTest(profile.get()); NiceMock<ProfileSyncServiceMock> service(&init_params); @@ -345,7 +345,7 @@ EXPECT_CALL(service, GetAuthError()).WillRepeatedly(ReturnRef(error)); FakeSigninManagerForSyncUIUtilTest signin(profile.get()); signin.SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser); - scoped_ptr<FakeAuthStatusProvider> provider(new FakeAuthStatusProvider( + std::unique_ptr<FakeAuthStatusProvider> provider(new FakeAuthStatusProvider( SigninErrorControllerFactory::GetForProfile(profile.get()))); GetDistinctCase(&service, &signin, provider.get(), idx); base::string16 status_label; @@ -375,7 +375,7 @@ // honored. TEST_F(SyncUIUtilTest, HtmlNotIncludedInStatusIfNotRequested) { for (int idx = 0; idx != NUMBER_OF_STATUS_CASES; idx++) { - scoped_ptr<Profile> profile(MakeSignedInTestingProfile()); + std::unique_ptr<Profile> profile(MakeSignedInTestingProfile()); ProfileSyncService::InitParams init_params = CreateProfileSyncServiceParamsForTest(profile.get()); NiceMock<ProfileSyncServiceMock> service(&init_params); @@ -383,7 +383,7 @@ EXPECT_CALL(service, GetAuthError()).WillRepeatedly(ReturnRef(error)); FakeSigninManagerForSyncUIUtilTest signin(profile.get()); signin.SetAuthenticatedAccountInfo(kTestGaiaId, kTestUser); - scoped_ptr<FakeAuthStatusProvider> provider(new FakeAuthStatusProvider( + std::unique_ptr<FakeAuthStatusProvider> provider(new FakeAuthStatusProvider( SigninErrorControllerFactory::GetForProfile(profile.get()))); GetDistinctCase(&service, &signin, provider.get(), idx); base::string16 status_label;
diff --git a/chrome/browser/sync/test/integration/bookmarks_helper.cc b/chrome/browser/sync/test/integration/bookmarks_helper.cc index a21790c4..264691a 100644 --- a/chrome/browser/sync/test/integration/bookmarks_helper.cc +++ b/chrome/browser/sync/test/integration/bookmarks_helper.cc
@@ -320,8 +320,7 @@ base::WaitableEvent done(false, false); base::CancelableTaskTracker task_tracker; history_service->ScheduleDBTask( - scoped_ptr<history::HistoryDBTask>( - new HistoryEmptyTask(&done)), + std::unique_ptr<history::HistoryDBTask>(new HistoryEmptyTask(&done)), &task_tracker); done.Wait(); }
diff --git a/chrome/browser/sync/test/integration/extension_settings_helper.cc b/chrome/browser/sync/test/integration/extension_settings_helper.cc index f9c09d04..15dc763 100644 --- a/chrome/browser/sync/test/integration/extension_settings_helper.cc +++ b/chrome/browser/sync/test/integration/extension_settings_helper.cc
@@ -4,10 +4,11 @@ #include "chrome/browser/sync/test/integration/extension_settings_helper.h" +#include <memory> + #include "base/bind.h" #include "base/json/json_writer.h" #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/synchronization/waitable_event.h" #include "base/values.h" #include "chrome/browser/profiles/profile.h" @@ -44,10 +45,10 @@ signal->Signal(); } -scoped_ptr<base::DictionaryValue> GetAllSettings( - Profile* profile, const std::string& id) { +std::unique_ptr<base::DictionaryValue> GetAllSettings(Profile* profile, + const std::string& id) { base::WaitableEvent signal(false, false); - scoped_ptr<base::DictionaryValue> settings(new base::DictionaryValue()); + std::unique_ptr<base::DictionaryValue> settings(new base::DictionaryValue()); extensions::StorageFrontend::Get(profile)->RunWithStorage( ExtensionRegistry::Get(profile)->enabled_extensions().GetByID(id), extensions::settings_namespace::SYNC, @@ -70,9 +71,9 @@ it != extensions.end(); ++it) { const std::string& id = (*it)->id(); - scoped_ptr<base::DictionaryValue> expected( + std::unique_ptr<base::DictionaryValue> expected( GetAllSettings(expected_profile, id)); - scoped_ptr<base::DictionaryValue> actual( + std::unique_ptr<base::DictionaryValue> actual( GetAllSettings(actual_profile, id)); if (!expected->Equals(actual.get())) { ADD_FAILURE() <<
diff --git a/chrome/browser/sync/test/integration/preferences_helper.cc b/chrome/browser/sync/test/integration/preferences_helper.cc index 5e76c09..f9f7778 100644 --- a/chrome/browser/sync/test/integration/preferences_helper.cc +++ b/chrome/browser/sync/test/integration/preferences_helper.cc
@@ -266,7 +266,7 @@ } void PrefMatchChecker::RegisterPrefListener(PrefService* pref_service) { - scoped_ptr<PrefChangeRegistrar> registrar(new PrefChangeRegistrar()); + std::unique_ptr<PrefChangeRegistrar> registrar(new PrefChangeRegistrar()); registrar->Init(pref_service); registrar->Add(path_, base::Bind(&PrefMatchChecker::CheckExitCondition,
diff --git a/chrome/browser/sync/test/integration/profile_sync_service_harness.cc b/chrome/browser/sync/test/integration/profile_sync_service_harness.cc index 7cf94c81..b67abffc 100644 --- a/chrome/browser/sync/test/integration/profile_sync_service_harness.cc +++ b/chrome/browser/sync/test/integration/profile_sync_service_harness.cc
@@ -465,7 +465,7 @@ } std::string ProfileSyncServiceHarness::GetServiceStatus() { - scoped_ptr<base::DictionaryValue> value( + std::unique_ptr<base::DictionaryValue> value( sync_driver::sync_ui_util::ConstructAboutInformation( service(), service()->signin(), chrome::GetChannel())); std::string service_status;
diff --git a/chrome/browser/sync/test/integration/single_client_bookmarks_sync_test.cc b/chrome/browser/sync/test/integration/single_client_bookmarks_sync_test.cc index ed696cec..3cebd2e 100644 --- a/chrome/browser/sync/test/integration/single_client_bookmarks_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_bookmarks_sync_test.cc
@@ -352,7 +352,7 @@ GetFakeServer()->GetSyncEntitiesByModelType(syncer::BOOKMARKS); ASSERT_EQ(1ul, server_bookmarks.size()); std::string entity_id = server_bookmarks[0].id_string(); - scoped_ptr<fake_server::FakeServerEntity> tombstone( + std::unique_ptr<fake_server::FakeServerEntity> tombstone( fake_server::TombstoneEntity::Create(entity_id)); GetFakeServer()->InjectEntity(std::move(tombstone));
diff --git a/chrome/browser/sync/test/integration/single_client_extensions_sync_test.cc b/chrome/browser/sync/test/integration/single_client_extensions_sync_test.cc index efb7788a..723c1b1 100644 --- a/chrome/browser/sync/test/integration/single_client_extensions_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_extensions_sync_test.cc
@@ -83,7 +83,7 @@ GetFakeServer()->GetSyncEntitiesByModelType(syncer::EXTENSIONS); ASSERT_EQ(1ul, server_extensions.size()); std::string entity_id = server_extensions[0].id_string(); - scoped_ptr<fake_server::FakeServerEntity> tombstone( + std::unique_ptr<fake_server::FakeServerEntity> tombstone( fake_server::TombstoneEntity::Create(entity_id)); GetFakeServer()->InjectEntity(std::move(tombstone));
diff --git a/chrome/browser/sync/test/integration/single_client_wallet_sync_test.cc b/chrome/browser/sync/test/integration/single_client_wallet_sync_test.cc index 14f4437..8cdf888 100644 --- a/chrome/browser/sync/test/integration/single_client_wallet_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_wallet_sync_test.cc
@@ -4,7 +4,6 @@ #include "base/command_line.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/sync/test/integration/autofill_helper.h"
diff --git a/chrome/browser/sync/test/integration/single_client_wifi_credentials_sync_test.cc b/chrome/browser/sync/test/integration/single_client_wifi_credentials_sync_test.cc index 4744fd1a..f03dd0ad 100644 --- a/chrome/browser/sync/test/integration/single_client_wifi_credentials_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_wifi_credentials_sync_test.cc
@@ -56,7 +56,7 @@ ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; const char ssid[] = "fake-ssid"; - scoped_ptr<WifiCredential> credential = + std::unique_ptr<WifiCredential> credential = wifi_credentials_helper::MakeWifiCredential( ssid, wifi_sync::SECURITY_CLASS_PSK, "fake_passphrase"); ASSERT_TRUE(credential);
diff --git a/chrome/browser/sync/test/integration/sync_app_helper.cc b/chrome/browser/sync/test/integration/sync_app_helper.cc index 6752ed3..dbf3ba4 100644 --- a/chrome/browser/sync/test/integration/sync_app_helper.cc +++ b/chrome/browser/sync/test/integration/sync_app_helper.cc
@@ -89,7 +89,7 @@ AppStateMap GetAppStates(Profile* profile) { AppStateMap app_state_map; - scoped_ptr<const extensions::ExtensionSet> extensions( + std::unique_ptr<const extensions::ExtensionSet> extensions( extensions::ExtensionRegistry::Get(profile) ->GenerateInstalledExtensionsSet()); for (const auto& extension : *extensions) {
diff --git a/chrome/browser/sync/test/integration/sync_extension_helper.cc b/chrome/browser/sync/test/integration/sync_extension_helper.cc index 36edbbe..586d514 100644 --- a/chrome/browser/sync/test/integration/sync_extension_helper.cc +++ b/chrome/browser/sync/test/integration/sync_extension_helper.cc
@@ -103,7 +103,7 @@ Profile* profile) const { std::vector<std::string> names; - scoped_ptr<const extensions::ExtensionSet> extensions( + std::unique_ptr<const extensions::ExtensionSet> extensions( extensions::ExtensionRegistry::Get(profile) ->GenerateInstalledExtensionsSet()); for (extensions::ExtensionSet::const_iterator it = extensions->begin(); @@ -211,7 +211,7 @@ ExtensionStateMap extension_state_map; - scoped_ptr<const extensions::ExtensionSet> extensions( + std::unique_ptr<const extensions::ExtensionSet> extensions( extensions::ExtensionRegistry::Get(profile) ->GenerateInstalledExtensionsSet());
diff --git a/chrome/browser/sync/test/integration/sync_test.cc b/chrome/browser/sync/test/integration/sync_test.cc index 3448e3d..0a3f4d0 100644 --- a/chrome/browser/sync/test/integration/sync_test.cc +++ b/chrome/browser/sync/test/integration/sync_test.cc
@@ -8,14 +8,15 @@ #include <stdint.h> #include <limits> +#include <memory> #include <vector> #include "base/bind.h" #include "base/command_line.h" #include "base/files/scoped_temp_dir.h" #include "base/guid.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/path_service.h" #include "base/process/launch.h" @@ -172,21 +173,21 @@ std::string GetDebugMessage() const override { return "Encryption"; } }; -scoped_ptr<KeyedService> BuildFakeServerProfileInvalidationProvider( +std::unique_ptr<KeyedService> BuildFakeServerProfileInvalidationProvider( content::BrowserContext* context) { - return make_scoped_ptr(new invalidation::ProfileInvalidationProvider( - scoped_ptr<invalidation::InvalidationService>( + return base::WrapUnique(new invalidation::ProfileInvalidationProvider( + std::unique_ptr<invalidation::InvalidationService>( new fake_server::FakeServerInvalidationService))); } -scoped_ptr<KeyedService> BuildP2PProfileInvalidationProvider( +std::unique_ptr<KeyedService> BuildP2PProfileInvalidationProvider( content::BrowserContext* context, syncer::P2PNotificationTarget notification_target) { Profile* profile = static_cast<Profile*>(context); - return make_scoped_ptr(new invalidation::ProfileInvalidationProvider( - scoped_ptr<invalidation::InvalidationService>( + return base::WrapUnique(new invalidation::ProfileInvalidationProvider( + std::unique_ptr<invalidation::InvalidationService>( new invalidation::P2PInvalidationService( - scoped_ptr<IdentityProvider>(new ProfileIdentityProvider( + std::unique_ptr<IdentityProvider>(new ProfileIdentityProvider( SigninManagerFactory::GetForProfile(profile), ProfileOAuth2TokenServiceFactory::GetForProfile(profile), LoginUIServiceFactory::GetShowLoginPopupCallbackForProfile( @@ -194,12 +195,12 @@ profile->GetRequestContext(), notification_target)))); } -scoped_ptr<KeyedService> BuildSelfNotifyingP2PProfileInvalidationProvider( +std::unique_ptr<KeyedService> BuildSelfNotifyingP2PProfileInvalidationProvider( content::BrowserContext* context) { return BuildP2PProfileInvalidationProvider(context, syncer::NOTIFY_ALL); } -scoped_ptr<KeyedService> BuildRealisticP2PProfileInvalidationProvider( +std::unique_ptr<KeyedService> BuildRealisticP2PProfileInvalidationProvider( content::BrowserContext* context) { return BuildP2PProfileInvalidationProvider(context, syncer::NOTIFY_OTHERS); } @@ -537,7 +538,7 @@ if (server_type_ == IN_PROCESS_FAKE_SERVER) { // TODO(pvalenzuela): Run the fake server via EmbeddedTestServer. profile_sync_service->OverrideNetworkResourcesForTest( - make_scoped_ptr<syncer::NetworkResources>( + base::WrapUnique<syncer::NetworkResources>( new fake_server::FakeServerNetworkResources( fake_server_->AsWeakPtr()))); } @@ -972,7 +973,7 @@ std::string sync_url = cl->GetSwitchValueASCII(switches::kSyncServiceURL); GURL sync_url_status(sync_url.append("/healthz")); SyncServerStatusChecker delegate; - scoped_ptr<net::URLFetcher> fetcher = + std::unique_ptr<net::URLFetcher> fetcher = net::URLFetcher::Create(sync_url_status, net::URLFetcher::GET, &delegate); fetcher->SetLoadFlags(net::LOAD_DISABLE_CACHE | net::LOAD_DO_NOT_SEND_COOKIES |
diff --git a/chrome/browser/sync/test/integration/sync_test.h b/chrome/browser/sync/test/integration/sync_test.h index be8b35db..1f5725c 100644 --- a/chrome/browser/sync/test/integration/sync_test.h +++ b/chrome/browser/sync/test/integration/sync_test.h
@@ -5,12 +5,12 @@ #ifndef CHROME_BROWSER_SYNC_TEST_INTEGRATION_SYNC_TEST_H_ #define CHROME_BROWSER_SYNC_TEST_INTEGRATION_SYNC_TEST_H_ +#include <memory> #include <string> #include <vector> #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/process/process.h" #include "chrome/browser/profiles/profile.h" @@ -284,7 +284,7 @@ base::FilePath password_file_; // The FakeServer used in tests with server type IN_PROCESS_FAKE_SERVER. - scoped_ptr<fake_server::FakeServer> fake_server_; + std::unique_ptr<fake_server::FakeServer> fake_server_; private: // Handles Profile creation for given index. Profile's path and type is @@ -372,7 +372,7 @@ syncer::LocalSyncTestServer sync_server_; // Helper class to whitelist the notification port. - scoped_ptr<net::ScopedPortException> xmpp_port_; + std::unique_ptr<net::ScopedPortException> xmpp_port_; // Used to differentiate between single-client and two-client tests as well // as wher the in-process FakeServer is used. @@ -393,7 +393,7 @@ // Collection of profile delegates. Only used for test profiles, which require // a custom profile delegate to ensure initialization happens at the right // time. - std::vector<scoped_ptr<Profile::Delegate>> profile_delegates_; + std::vector<std::unique_ptr<Profile::Delegate>> profile_delegates_; // Collection of profile paths used by a test. Each profile has a unique path // which should be cleaned up at test shutdown. Profile paths inside the @@ -443,16 +443,17 @@ // Sync integration tests need to make live DNS requests for access to // GAIA and sync server URLs under google.com. We use a scoped version // to override the default resolver while the test is active. - scoped_ptr<net::ScopedDefaultHostResolverProc> mock_host_resolver_override_; + std::unique_ptr<net::ScopedDefaultHostResolverProc> + mock_host_resolver_override_; // Used to start and stop the local test server. base::Process test_server_; // Fake URLFetcher factory used to mock out GAIA signin. - scoped_ptr<net::FakeURLFetcherFactory> fake_factory_; + std::unique_ptr<net::FakeURLFetcherFactory> fake_factory_; // The URLFetcherImplFactory instance used to instantiate |fake_factory_|. - scoped_ptr<net::URLFetcherImplFactory> factory_; + std::unique_ptr<net::URLFetcherImplFactory> factory_; // The contents to be written to a profile's Preferences file before the // Profile object is created. If empty, no preexisting file will be written.
diff --git a/chrome/browser/sync/test/integration/two_client_app_list_sync_test.cc b/chrome/browser/sync/test/integration/two_client_app_list_sync_test.cc index d7d94d4..571db0b 100644 --- a/chrome/browser/sync/test/integration/two_client_app_list_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_app_list_sync_test.cc
@@ -72,7 +72,7 @@ service->GetModel()->top_level_item_list()->FindItem(id); ASSERT_TRUE(item); // Ensure local prefs matches the model data. - scoped_ptr<app_list::AppListPrefs::AppListInfo> info = + std::unique_ptr<app_list::AppListPrefs::AppListInfo> info = app_list::AppListPrefs::Get(profile)->GetAppListInfo(id); ASSERT_TRUE(info); EXPECT_EQ(item->name(), info->name);
diff --git a/chrome/browser/sync/test/integration/two_client_wifi_credentials_sync_test.cc b/chrome/browser/sync/test/integration/two_client_wifi_credentials_sync_test.cc index 3a9a96a7..fa106ea 100644 --- a/chrome/browser/sync/test/integration/two_client_wifi_credentials_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_wifi_credentials_sync_test.cc
@@ -54,7 +54,7 @@ ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; const char ssid[] = "fake-ssid"; - scoped_ptr<WifiCredential> credential = + std::unique_ptr<WifiCredential> credential = wifi_credentials_helper::MakeWifiCredential( ssid, wifi_sync::SECURITY_CLASS_PSK, "fake_passphrase"); ASSERT_TRUE(credential);
diff --git a/chrome/browser/sync/test/integration/typed_urls_helper.cc b/chrome/browser/sync/test/integration/typed_urls_helper.cc index bb7a8f9..fafe249 100644 --- a/chrome/browser/sync/test/integration/typed_urls_helper.cc +++ b/chrome/browser/sync/test/integration/typed_urls_helper.cc
@@ -148,10 +148,9 @@ HistoryServiceFactory::GetForProfileWithoutCreating( test()->GetProfile(index)); base::WaitableEvent wait_event(true, false); - service->ScheduleDBTask( - scoped_ptr<history::HistoryDBTask>( - new FlushHistoryDBQueueTask(&wait_event)), - &tracker); + service->ScheduleDBTask(std::unique_ptr<history::HistoryDBTask>( + new FlushHistoryDBQueueTask(&wait_event)), + &tracker); wait_event.Wait(); } @@ -178,10 +177,9 @@ base::CancelableTaskTracker tracker; history::URLRows rows; base::WaitableEvent wait_event(true, false); - service->ScheduleDBTask( - scoped_ptr<history::HistoryDBTask>( - new GetTypedUrlsTask(&rows, &wait_event)), - &tracker); + service->ScheduleDBTask(std::unique_ptr<history::HistoryDBTask>( + new GetTypedUrlsTask(&rows, &wait_event)), + &tracker); wait_event.Wait(); return rows; } @@ -192,10 +190,9 @@ base::CancelableTaskTracker tracker; base::WaitableEvent wait_event(true, false); bool found = false; - service->ScheduleDBTask( - scoped_ptr<history::HistoryDBTask>( - new GetUrlTask(url, row, &found, &wait_event)), - &tracker); + service->ScheduleDBTask(std::unique_ptr<history::HistoryDBTask>( + new GetUrlTask(url, row, &found, &wait_event)), + &tracker); wait_event.Wait(); return found; } @@ -206,10 +203,9 @@ base::CancelableTaskTracker tracker; base::WaitableEvent wait_event(true, false); history::VisitVector visits; - service->ScheduleDBTask( - scoped_ptr<history::HistoryDBTask>( - new GetVisitsTask(id, &visits, &wait_event)), - &tracker); + service->ScheduleDBTask(std::unique_ptr<history::HistoryDBTask>( + new GetVisitsTask(id, &visits, &wait_event)), + &tracker); wait_event.Wait(); return visits; } @@ -218,10 +214,9 @@ const history::VisitVector& visits) { base::CancelableTaskTracker tracker; base::WaitableEvent wait_event(true, false); - service->ScheduleDBTask( - scoped_ptr<history::HistoryDBTask>( - new RemoveVisitsTask(visits, &wait_event)), - &tracker); + service->ScheduleDBTask(std::unique_ptr<history::HistoryDBTask>( + new RemoveVisitsTask(visits, &wait_event)), + &tracker); wait_event.Wait(); }
diff --git a/chrome/browser/sync/test/integration/wifi_credentials_helper.cc b/chrome/browser/sync/test/integration/wifi_credentials_helper.cc index c9146cb..3f5a1150 100644 --- a/chrome/browser/sync/test/integration/wifi_credentials_helper.cc +++ b/chrome/browser/sync/test/integration/wifi_credentials_helper.cc
@@ -129,9 +129,10 @@ return true; } -scoped_ptr<WifiCredential> MakeWifiCredential(const std::string& ssid, - WifiSecurityClass security_class, - const std::string& passphrase) { +std::unique_ptr<WifiCredential> MakeWifiCredential( + const std::string& ssid, + WifiSecurityClass security_class, + const std::string& passphrase) { return WifiCredential::Create(WifiCredential::MakeSsidBytesForTest(ssid), security_class, passphrase);
diff --git a/chrome/browser/sync/test/integration/wifi_credentials_helper.h b/chrome/browser/sync/test/integration/wifi_credentials_helper.h index 6d81149..8ff7d1dca 100644 --- a/chrome/browser/sync/test/integration/wifi_credentials_helper.h +++ b/chrome/browser/sync/test/integration/wifi_credentials_helper.h
@@ -5,9 +5,9 @@ #ifndef CHROME_BROWSER_SYNC_TEST_INTEGRATION_WIFI_CREDENTIALS_HELPER_H_ #define CHROME_BROWSER_SYNC_TEST_INTEGRATION_WIFI_CREDENTIALS_HELPER_H_ +#include <memory> #include <string> -#include "base/memory/scoped_ptr.h" #include "components/wifi_sync/wifi_credential.h" #include "components/wifi_sync/wifi_security_class.h" @@ -39,7 +39,7 @@ bool AllProfilesMatch(); // Returns a new WifiCredential constructed from the given parameters. -scoped_ptr<wifi_sync::WifiCredential> MakeWifiCredential( +std::unique_ptr<wifi_sync::WifiCredential> MakeWifiCredential( const std::string& ssid, wifi_sync::WifiSecurityClass security_class, const std::string& passphrase);
diff --git a/chrome/browser/sync/test/integration/wifi_credentials_helper_chromeos.cc b/chrome/browser/sync/test/integration/wifi_credentials_helper_chromeos.cc index 6f7e3a6..80452ec 100644 --- a/chrome/browser/sync/test/integration/wifi_credentials_helper_chromeos.cc +++ b/chrome/browser/sync/test/integration/wifi_credentials_helper_chromeos.cc
@@ -4,12 +4,12 @@ #include "chrome/browser/sync/test/integration/wifi_credentials_helper_chromeos.h" +#include <memory> #include <string> #include "base/bind.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/stringprintf.h" #include "base/values.h" @@ -36,7 +36,7 @@ void LogCreateConfigurationFailure( const std::string& debug_hint, const std::string& /* network_config_error_message */, - scoped_ptr<base::DictionaryValue> /* network_config_error_data */) { + std::unique_ptr<base::DictionaryValue> /* network_config_error_data */) { LOG(FATAL) << debug_hint; } @@ -102,7 +102,7 @@ const content::BrowserContext* browser_context, const WifiCredential& credential) { DCHECK(browser_context); - scoped_ptr<base::DictionaryValue> onc_properties = + std::unique_ptr<base::DictionaryValue> onc_properties = credential.ToOncProperties(); CHECK(onc_properties) << "Failed to generate ONC properties for " << credential.ToString();
diff --git a/chrome/browser/themes/theme_properties.cc b/chrome/browser/themes/theme_properties.cc index d4fb13a..8d5a8ef 100644 --- a/chrome/browser/themes/theme_properties.cc +++ b/chrome/browser/themes/theme_properties.cc
@@ -71,14 +71,15 @@ const SkColor kDefaultDetachedBookmarkBarBackgroundIncognito[] = { SkColorSetRGB(0xF1, 0xF1, 0xF1), SkColorSetRGB(0x32, 0x32, 0x32)}; -const SkColor kDefaultColorTabText = SK_ColorBLACK; -const SkColor kDefaultColorTabTextIncognito[] = {SK_ColorBLACK, SK_ColorWHITE}; +constexpr SkColor kDefaultColorTabText = SK_ColorBLACK; +constexpr SkColor kDefaultColorTabTextIncognito[] = {kDefaultColorTabText, + SK_ColorWHITE}; #if defined(OS_MACOSX) -const SkColor kDefaultColorBackgroundTabText[] = { - SK_ColorBLACK, SK_ColorBLACK }; -const SkColor kDefaultColorBackgroundTabTextIncognito[] = { - SK_ColorBLACK, SK_ColorWHITE }; +constexpr SkColor kDefaultColorBackgroundTabText[] = {SK_ColorBLACK, + SK_ColorBLACK}; +constexpr SkColor kDefaultColorBackgroundTabTextIncognito[] = { + kDefaultColorBackgroundTabText[0], SK_ColorWHITE}; #else const SkColor kDefaultColorBackgroundTabText[] = { SkColorSetRGB(64, 64, 64), SK_ColorBLACK }; @@ -86,9 +87,9 @@ SkColorSetRGB(64, 64, 64), SK_ColorWHITE }; #endif // OS_MACOSX -const SkColor kDefaultColorBookmarkText = SK_ColorBLACK; -const SkColor kDefaultColorBookmarkTextIncognito[] = {SK_ColorBLACK, - SK_ColorWHITE}; +constexpr SkColor kDefaultColorBookmarkText = SK_ColorBLACK; +constexpr SkColor kDefaultColorBookmarkTextIncognito[] = { + kDefaultColorBookmarkText, SK_ColorWHITE}; #if defined(OS_WIN) const SkColor kDefaultColorNTPBackground = @@ -99,32 +100,31 @@ color_utils::GetSysSkColor(COLOR_HOTLIGHT); #else // TODO(beng): source from theme provider. -const SkColor kDefaultColorNTPBackground = SK_ColorWHITE; -const SkColor kDefaultColorNTPText = SK_ColorBLACK; +constexpr SkColor kDefaultColorNTPBackground = SK_ColorWHITE; +constexpr SkColor kDefaultColorNTPText = SK_ColorBLACK; const SkColor kDefaultColorNTPLink = SkColorSetRGB(6, 55, 116); #endif // OS_WIN const SkColor kDefaultColorNTPHeader = SkColorSetRGB(150, 150, 150); const SkColor kDefaultColorNTPSection = SkColorSetRGB(229, 229, 229); -const SkColor kDefaultColorNTPSectionText = SK_ColorBLACK; +constexpr SkColor kDefaultColorNTPSectionText = SK_ColorBLACK; const SkColor kDefaultColorNTPSectionLink = SkColorSetRGB(6, 55, 116); -const SkColor kDefaultColorButtonBackground = SkColorSetARGB(0, 0, 0, 0); +constexpr SkColor kDefaultColorButtonBackground = SK_ColorTRANSPARENT; // Default tints. -const color_utils::HSL kDefaultTintButtons = {-1, -1, -1}; -// In pre-md, reuse the normal tint for incognito. -const color_utils::HSL kDefaultTintButtonsIncognito[] = {{-1, -1, -1}, - {-1, -1, 0.85}}; -const color_utils::HSL kDefaultTintFrame = {-1, -1, -1}; -const color_utils::HSL kDefaultTintFrameInactive = {-1, -1, 0.75}; -const color_utils::HSL kDefaultTintFrameIncognito = {-1, 0.2, 0.35}; -const color_utils::HSL kDefaultTintFrameIncognitoInactive = {-1, 0.3, 0.6}; -const color_utils::HSL kDefaultTintBackgroundTab = {-1, -1, 0.75}; +constexpr color_utils::HSL kDefaultTintButtons = {-1, -1, -1}; +constexpr color_utils::HSL kDefaultTintButtonsIncognito[] = { + kDefaultTintButtons, {-1, -1, 0.85}}; +constexpr color_utils::HSL kDefaultTintFrame = {-1, -1, -1}; +constexpr color_utils::HSL kDefaultTintFrameInactive = {-1, -1, 0.75}; +constexpr color_utils::HSL kDefaultTintFrameIncognito = {-1, 0.2, 0.35}; +constexpr color_utils::HSL kDefaultTintFrameIncognitoInactive = {-1, 0.3, 0.6}; +constexpr color_utils::HSL kDefaultTintBackgroundTab = {-1, -1, 0.75}; // ---------------------------------------------------------------------------- // Defaults for properties which are not stored in the browser theme pack. -const SkColor kDefaultColorControlBackground = SK_ColorWHITE; +constexpr SkColor kDefaultColorControlBackground = SK_ColorWHITE; const SkColor kDefaultDetachedBookmarkBarSeparator[] = { SkColorSetRGB(170, 170, 171), SkColorSetRGB(182, 180, 182)}; const SkColor kDefaultDetachedBookmarkBarSeparatorIncognito[] = { @@ -159,17 +159,17 @@ // ---------------------------------------------------------------------------- // Strings used in alignment properties. -const char kAlignmentCenter[] = "center"; -const char kAlignmentTop[] = "top"; -const char kAlignmentBottom[] = "bottom"; -const char kAlignmentLeft[] = "left"; -const char kAlignmentRight[] = "right"; +constexpr char kAlignmentCenter[] = "center"; +constexpr char kAlignmentTop[] = "top"; +constexpr char kAlignmentBottom[] = "bottom"; +constexpr char kAlignmentLeft[] = "left"; +constexpr char kAlignmentRight[] = "right"; // Strings used in background tiling repetition properties. -const char kTilingNoRepeat[] = "no-repeat"; -const char kTilingRepeatX[] = "repeat-x"; -const char kTilingRepeatY[] = "repeat-y"; -const char kTilingRepeat[] = "repeat"; +constexpr char kTilingNoRepeat[] = "no-repeat"; +constexpr char kTilingRepeatX[] = "repeat-x"; +constexpr char kTilingRepeatY[] = "repeat-y"; +constexpr char kTilingRepeat[] = "repeat"; // The image resources that will be tinted by the 'button' tint value. // If you change this list, you must increment the version number in @@ -179,17 +179,35 @@ // // TODO(erg): The cocoa port is the last user of the IDR_*_[HP] variants. These // should be removed once the cocoa port no longer uses them. -const int kToolbarButtonIDs[] = { - IDR_BACK, IDR_BACK_D, IDR_BACK_H, IDR_BACK_P, - IDR_FORWARD, IDR_FORWARD_D, IDR_FORWARD_H, IDR_FORWARD_P, - IDR_HOME, IDR_HOME_H, IDR_HOME_P, - IDR_RELOAD, IDR_RELOAD_H, IDR_RELOAD_P, - IDR_STOP, IDR_STOP_D, IDR_STOP_H, IDR_STOP_P, - IDR_BROWSER_ACTIONS_OVERFLOW, IDR_BROWSER_ACTIONS_OVERFLOW_H, - IDR_BROWSER_ACTIONS_OVERFLOW_P, - IDR_TOOLS, IDR_TOOLS_H, IDR_TOOLS_P, - IDR_MENU_DROPARROW, - IDR_TOOLBAR_BEZEL_HOVER, IDR_TOOLBAR_BEZEL_PRESSED, IDR_TOOLS_BAR, +constexpr int kToolbarButtonIDs[] = { + IDR_BACK, + IDR_BACK_D, + IDR_BACK_H, + IDR_BACK_P, + IDR_FORWARD, + IDR_FORWARD_D, + IDR_FORWARD_H, + IDR_FORWARD_P, + IDR_HOME, + IDR_HOME_H, + IDR_HOME_P, + IDR_RELOAD, + IDR_RELOAD_H, + IDR_RELOAD_P, + IDR_STOP, + IDR_STOP_D, + IDR_STOP_H, + IDR_STOP_P, + IDR_BROWSER_ACTIONS_OVERFLOW, + IDR_BROWSER_ACTIONS_OVERFLOW_H, + IDR_BROWSER_ACTIONS_OVERFLOW_P, + IDR_TOOLS, + IDR_TOOLS_H, + IDR_TOOLS_P, + IDR_MENU_DROPARROW, + IDR_TOOLBAR_BEZEL_HOVER, + IDR_TOOLBAR_BEZEL_PRESSED, + IDR_TOOLS_BAR, }; SkColor TintForUnderline(SkColor input) {
diff --git a/chrome/browser/ui/app_list/speech_recognizer.cc b/chrome/browser/ui/app_list/speech_recognizer.cc index 80c9673..d6044746 100644 --- a/chrome/browser/ui/app_list/speech_recognizer.cc +++ b/chrome/browser/ui/app_list/speech_recognizer.cc
@@ -128,7 +128,6 @@ content::SpeechRecognitionSessionConfig config; config.language = locale_; - config.is_legacy_api = false; config.continuous = true; config.interim_results = true; config.max_hypotheses = 1;
diff --git a/chrome/browser/ui/sync/one_click_signin_sync_starter.cc b/chrome/browser/ui/sync/one_click_signin_sync_starter.cc index 079f5b9..8aeb723f 100644 --- a/chrome/browser/ui/sync/one_click_signin_sync_starter.cc +++ b/chrome/browser/ui/sync/one_click_signin_sync_starter.cc
@@ -390,7 +390,7 @@ } void OneClickSigninSyncStarter::OnSyncConfirmationUIClosed( - LoginUIService::SyncConfirmationUIClosedResults results) { + LoginUIService::SyncConfirmationUIClosedResult result) { if (switches::UsePasswordSeparatedSigninFlow()) { // We didn't run this callback in AccountAddedToCookie so do it now. @@ -398,7 +398,7 @@ sync_setup_completed_callback_.Run(SYNC_SETUP_SUCCESS); } - switch (results) { + switch (result) { case LoginUIService::CONFIGURE_SYNC_FIRST: content::RecordAction( base::UserMetricsAction("Signin_Signin_WithAdvancedSyncSettings"));
diff --git a/chrome/browser/ui/sync/one_click_signin_sync_starter.h b/chrome/browser/ui/sync/one_click_signin_sync_starter.h index e95b4bc..a95405c 100644 --- a/chrome/browser/ui/sync/one_click_signin_sync_starter.h +++ b/chrome/browser/ui/sync/one_click_signin_sync_starter.h
@@ -132,7 +132,7 @@ // LoginUIService::Observer override. void OnSyncConfirmationUIClosed( - LoginUIService::SyncConfirmationUIClosedResults results) override; + LoginUIService::SyncConfirmationUIClosedResult result) override; // User input handler for the signin confirmation dialog. class SigninDialogDelegate
diff --git a/chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.cc b/chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.cc index 48c0e83..e2b73c38 100644 --- a/chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.cc +++ b/chrome/browser/ui/views/profiles/signin_view_controller_delegate_views.cc
@@ -22,7 +22,7 @@ const int kPasswordCombinedFixedGaiaViewWidth = 360; const int kFixedGaiaViewHeight = 612; const int kModalDialogWidth = 448; -const int kSyncConfirmationDialogHeight = 351; +const int kSyncConfirmationDialogHeight = 487; SigninViewControllerDelegateViews::SigninViewControllerDelegateViews( SigninViewController* signin_view_controller,
diff --git a/chrome/browser/ui/webui/options/chromeos/bluetooth_options_browsertest.js b/chrome/browser/ui/webui/options/chromeos/bluetooth_options_browsertest.js index bccb3a7..cf1c0e7 100644 --- a/chrome/browser/ui/webui/options/chromeos/bluetooth_options_browsertest.js +++ b/chrome/browser/ui/webui/options/chromeos/bluetooth_options_browsertest.js
@@ -123,7 +123,8 @@ }.bind(this)); }); -TEST_F('BluetoothWebUITestAsync', 'testAddDevice', function() { +// TODO(crbug.com/603499) Test is flaky. +TEST_F('BluetoothWebUITestAsync', 'DISABLED_testAddDevice', function() { assertEquals(this.browsePreload, document.location.href); // Enable bluetooth.
diff --git a/chrome/browser/ui/webui/options/sync_setup_handler.cc b/chrome/browser/ui/webui/options/sync_setup_handler.cc index 32fa457..116af96 100644 --- a/chrome/browser/ui/webui/options/sync_setup_handler.cc +++ b/chrome/browser/ui/webui/options/sync_setup_handler.cc
@@ -201,6 +201,14 @@ "encryptionSectionMessage", GetStringFUTF16(IDS_SYNC_ENCRYPTION_SECTION_MESSAGE, product_name)); localized_strings->SetString( + "personalizeGoogleServicesTitle", + GetStringUTF16(IDS_SYNC_CONFIRMATION_PERSONALIZE_SERVICES_TITLE)); + localized_strings->SetString( + "personalizeGoogleServicesMessage", + GetStringFUTF16( + IDS_SYNC_PERSONALIZE_GOOGLE_SERVICES_MESSAGE, + base::ASCIIToUTF16(chrome::kGoogleAccountActivityControlsURL))); + localized_strings->SetString( "passphraseRecover", GetStringFUTF16( IDS_SYNC_PASSPHRASE_RECOVER,
diff --git a/chrome/browser/ui/webui/signin/login_ui_service.cc b/chrome/browser/ui/webui/signin/login_ui_service.cc index 469bde9e..042f6c72 100644 --- a/chrome/browser/ui/webui/signin/login_ui_service.cc +++ b/chrome/browser/ui/webui/signin/login_ui_service.cc
@@ -45,11 +45,11 @@ } void LoginUIService::SyncConfirmationUIClosed( - SyncConfirmationUIClosedResults results) { + SyncConfirmationUIClosedResult result) { FOR_EACH_OBSERVER( Observer, observer_list_, - OnSyncConfirmationUIClosed(results)); + OnSyncConfirmationUIClosed(result)); } void LoginUIService::UntrustedLoginUIShown() {
diff --git a/chrome/browser/ui/webui/signin/login_ui_service.h b/chrome/browser/ui/webui/signin/login_ui_service.h index ce3ffead..bc789a3 100644 --- a/chrome/browser/ui/webui/signin/login_ui_service.h +++ b/chrome/browser/ui/webui/signin/login_ui_service.h
@@ -33,7 +33,7 @@ // Used when the sync confirmation UI is closed to signify which option was // selected by the user. - enum SyncConfirmationUIClosedResults { + enum SyncConfirmationUIClosedResult { // Start sync immediately. SYNC_WITH_DEFAULT_SETTINGS, // Show the user the sync settings before starting sync. @@ -53,10 +53,10 @@ // |ui| The login UI that was just closed; will never be null. virtual void OnLoginUIClosed(LoginUI* ui) {} - // Called when the sync confirmation UI is closed. |results| indicates the + // Called when the sync confirmation UI is closed. |result| indicates the // option chosen by the user in the confirmation UI. virtual void OnSyncConfirmationUIClosed( - SyncConfirmationUIClosedResults results) {} + SyncConfirmationUIClosedResult result) {} // Called when a confirmation UI for untrusted signin is shown. virtual void OnUntrustedLoginUIShown() {} @@ -85,8 +85,9 @@ // sets current_login_ui() to null. void LoginUIClosed(LoginUI* ui); - // Called when the sync settings confirmation UI is closed. - void SyncConfirmationUIClosed(SyncConfirmationUIClosedResults results); + // Called when the sync confirmation UI is closed. |result| indicates the + // option chosen by the user in the confirmation UI. + void SyncConfirmationUIClosed(SyncConfirmationUIClosedResult result); // Called when a confirmation UI for untrusted signin is shown. void UntrustedLoginUIShown();
diff --git a/chrome/browser/ui/webui/signin/signin_supervised_user_import_handler.cc b/chrome/browser/ui/webui/signin/signin_supervised_user_import_handler.cc index b321a70..9d3f51d 100644 --- a/chrome/browser/ui/webui/signin/signin_supervised_user_import_handler.cc +++ b/chrome/browser/ui/webui/signin/signin_supervised_user_import_handler.cc
@@ -25,14 +25,17 @@ #include "chrome/browser/supervised_user/legacy/supervised_user_sync_service.h" #include "chrome/browser/supervised_user/legacy/supervised_user_sync_service_factory.h" #include "chrome/browser/supervised_user/supervised_user_constants.h" +#include "chrome/browser/ui/browser_finder.h" #include "chrome/common/url_constants.h" #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/signin_error_controller.h" #include "components/signin/core/browser/signin_manager.h" #include "content/public/browser/web_ui.h" +#include "content/public/common/referrer.h" #include "grit/theme_resources.h" #include "ui/base/l10n/l10n_util.h" +#include "url/gurl.h" SigninSupervisedUserImportHandler::SigninSupervisedUserImportHandler() @@ -44,9 +47,12 @@ void SigninSupervisedUserImportHandler::RegisterMessages() { web_ui()->RegisterMessageCallback("getExistingSupervisedUsers", - base::Bind(&SigninSupervisedUserImportHandler:: - GetExistingSupervisedUsers, + base::Bind(&SigninSupervisedUserImportHandler::GetExistingSupervisedUsers, base::Unretained(this))); + web_ui()->RegisterMessageCallback("openUrlInLastActiveProfileBrowser", + base::Bind( + &SigninSupervisedUserImportHandler::OpenUrlInLastActiveProfileBrowser, + base::Unretained(this))); } void SigninSupervisedUserImportHandler::AssignWebUICallbackId( @@ -56,6 +62,25 @@ CHECK(args->GetString(0, &webui_callback_id_)); } +void SigninSupervisedUserImportHandler::OpenUrlInLastActiveProfileBrowser( + const base::ListValue* args) { + CHECK_EQ(1U, args->GetSize()); + std::string url; + bool success = args->GetString(0, &url); + DCHECK(success); + content::OpenURLParams params(GURL(url), + content::Referrer(), + NEW_BACKGROUND_TAB, + ui::PAGE_TRANSITION_LINK, + false); + // Get the browser owned by the last used profile. + Browser* browser = + chrome::FindLastActiveWithProfile(ProfileManager::GetLastUsedProfile()); + DCHECK(browser); + if (browser) + browser->OpenURL(params); +} + void SigninSupervisedUserImportHandler::GetExistingSupervisedUsers( const base::ListValue* args) { CHECK_EQ(2U, args->GetSize());
diff --git a/chrome/browser/ui/webui/signin/signin_supervised_user_import_handler.h b/chrome/browser/ui/webui/signin/signin_supervised_user_import_handler.h index 5c792bd..2f27385 100644 --- a/chrome/browser/ui/webui/signin/signin_supervised_user_import_handler.h +++ b/chrome/browser/ui/webui/signin/signin_supervised_user_import_handler.h
@@ -34,6 +34,12 @@ // has been fulfilled. void AssignWebUICallbackId(const base::ListValue* args); + // Callback for the "openUrlInLastActiveProfileBrowser" message. Opens the + // given url in a new background tab in the browser owned by the last active + // profile. Hyperlinks don't work in the user manager since the system profile + // browser is not tabbed. + void OpenUrlInLastActiveProfileBrowser(const base::ListValue* args); + // Callback for the "getExistingSupervisedUsers" message. // Checks the sign-in status of the custodian and accordingly // sends an update to the WebUI.
diff --git a/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc b/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc index 1202947..9cf12ca0 100644 --- a/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc +++ b/chrome/browser/ui/webui/signin/sync_confirmation_handler.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/ui/webui/signin/sync_confirmation_handler.h" +#include <vector> + #include "base/bind.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/signin/account_tracker_service_factory.h" @@ -89,10 +91,10 @@ } void SyncConfirmationHandler::CloseModalSigninWindow( - LoginUIService::SyncConfirmationUIClosedResults results) { + LoginUIService::SyncConfirmationUIClosedResult result) { Browser* browser = GetDesktopBrowser(); LoginUIServiceFactory::GetForProfile(browser->profile())-> - SyncConfirmationUIClosed(results); + SyncConfirmationUIClosed(result); browser->CloseModalSigninWindow(); }
diff --git a/chrome/browser/ui/webui/signin/sync_confirmation_handler.h b/chrome/browser/ui/webui/signin/sync_confirmation_handler.h index 7ad4a3c8..3de2103c 100644 --- a/chrome/browser/ui/webui/signin/sync_confirmation_handler.h +++ b/chrome/browser/ui/webui/signin/sync_confirmation_handler.h
@@ -56,9 +56,14 @@ virtual void SetUserImageURL(const std::string& url); Browser* GetDesktopBrowser(); - void CloseModalSigninWindow( - LoginUIService::SyncConfirmationUIClosedResults results); + // Closes the modal signin window and calls + // LoginUIService::SyncConfirmationUIClosed with |result|. |result| indicates + // the option chosen by the user in the confirmation UI. + void CloseModalSigninWindow( + LoginUIService::SyncConfirmationUIClosedResult result); + + private: DISALLOW_COPY_AND_ASSIGN(SyncConfirmationHandler); };
diff --git a/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc b/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc index 439a7c11..a3efcfd 100644 --- a/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc +++ b/chrome/browser/ui/webui/signin/sync_confirmation_ui.cc
@@ -33,7 +33,13 @@ source->AddLocalizedString("syncConfirmationChromeSyncTitle", IDS_SYNC_CONFIRMATION_CHROME_SYNC_TITLE); source->AddLocalizedString("syncConfirmationChromeSyncBody", - IDS_SYNC_CONFIRMATION_CHROME_SYNC_BODY); + IDS_SYNC_CONFIRMATION_CHROME_SYNC_MESSAGE); + source->AddLocalizedString("syncConfirmationPersonalizeServicesTitle", + IDS_SYNC_CONFIRMATION_PERSONALIZE_SERVICES_TITLE); + source->AddLocalizedString("syncConfirmationPersonalizeServicesBody", + IDS_SYNC_CONFIRMATION_PERSONALIZE_SERVICES_BODY); + source->AddLocalizedString("syncConfirmationSyncSettingsLinkBody", + IDS_SYNC_CONFIRMATION_SYNC_SETTINGS_LINK_BODY); source->AddLocalizedString("syncConfirmationConfirmLabel", IDS_SYNC_CONFIRMATION_CONFIRM_BUTTON_LABEL); source->AddLocalizedString("syncConfirmationUndoLabel",
diff --git a/chrome/common/url_constants.cc b/chrome/common/url_constants.cc index b7f59c4..545a59cf 100644 --- a/chrome/common/url_constants.cc +++ b/chrome/common/url_constants.cc
@@ -367,6 +367,9 @@ const char kSyncGoogleDashboardURL[] = "https://www.google.com/settings/chrome/sync/"; +const char kGoogleAccountActivityControlsURL[] = + "https://myaccount.google.com/activitycontrols/search"; + const char kPasswordManagerLearnMoreURL[] = #if defined(OS_CHROMEOS) "https://support.google.com/chromebook/?p=settings_password";
diff --git a/chrome/common/url_constants.h b/chrome/common/url_constants.h index f122a1a0..3ec91dc 100644 --- a/chrome/common/url_constants.h +++ b/chrome/common/url_constants.h
@@ -341,6 +341,9 @@ extern const char kSyncGoogleDashboardURL[]; +// URL of the 'Activity controls' section of the privacy settings page. +extern const char kGoogleAccountActivityControlsURL[]; + extern const char kPasswordManagerLearnMoreURL[]; extern const char kUpgradeHelpCenterBaseURL[]; extern const char kSmartLockHelpPage[];
diff --git a/chrome/test/data/extensions/platform_apps/web_view/text_input_state/window.js b/chrome/test/data/extensions/platform_apps/web_view/text_input_state/window.js index e0afe73e..117a3e5 100644 --- a/chrome/test/data/extensions/platform_apps/web_view/text_input_state/window.js +++ b/chrome/test/data/extensions/platform_apps/web_view/text_input_state/window.js
@@ -25,3 +25,14 @@ chrome.test.sendMessage('EMBEDDER-FOCUSED-2'); }); }); + +function detachWebView() { + var webview = document.querySelector('webview'); + if (webview) { + webview.parentNode.removeChild(webview); + chrome.test.sendMessage('detached'); + } else { + chrome.test.sendMessage('failed-to-detach'); + } +} +
diff --git a/components/metrics/metrics_service.cc b/components/metrics/metrics_service.cc index 7215bef..7fc1b188 100644 --- a/components/metrics/metrics_service.cc +++ b/components/metrics/metrics_service.cc
@@ -884,7 +884,7 @@ // upload constrains. bool upload_canceled = false; bool is_cellular_logic = client_->IsUMACellularUploadLogicEnabled(); - if (is_cellular_logic && + if (is_cellular_logic && data_use_tracker_ && !data_use_tracker_->ShouldUploadLogOnCellular( log_manager_.staged_log_hash().size())) { scheduler_->UploadCancelled();
diff --git a/components/ntp_snippets/ntp_snippets_service.h b/components/ntp_snippets/ntp_snippets_service.h index d6ab94c..0ba1efb 100644 --- a/components/ntp_snippets/ntp_snippets_service.h +++ b/components/ntp_snippets/ntp_snippets_service.h
@@ -172,7 +172,7 @@ // Timer that calls us back when the next snippet expires. base::OneShotTimer expiry_timer_; - const ParseJSONCallback parse_json_callback_; + ParseJSONCallback parse_json_callback_; base::WeakPtrFactory<NTPSnippetsService> weak_ptr_factory_;
diff --git a/components/ntp_snippets/ntp_snippets_service_unittest.cc b/components/ntp_snippets/ntp_snippets_service_unittest.cc index dd58c1b..b4700c5d 100644 --- a/components/ntp_snippets/ntp_snippets_service_unittest.cc +++ b/components/ntp_snippets/ntp_snippets_service_unittest.cc
@@ -62,13 +62,34 @@ NTPSnippet::TimeToJsonString(base::Time::Now())); } +std::string GetInvalidJson() { + std::string json_str = GetTestJson(); + // Make the json invalid by removing the final closing brace. + return json_str.substr(0, json_str.size() - 1); +} + +std::string GetIncompleteJson() { + std::string json_str = GetTestJson(); + // Rename the "url" entry. The result is syntactically valid json that will + // fail to parse as snippets. + size_t pos = json_str.find("\"url\""); + if (pos == std::string::npos) { + NOTREACHED(); + return std::string(); + } + json_str[pos + 1] = 'x'; + return json_str; +} + void ParseJson( + bool expect_success, const std::string& json, const ntp_snippets::NTPSnippetsService::SuccessCallback& success_callback, const ntp_snippets::NTPSnippetsService::ErrorCallback& error_callback) { base::JSONReader json_reader; scoped_ptr<base::Value> value = json_reader.ReadToValue(json); - ASSERT_TRUE(value); + bool success = !!value; + EXPECT_EQ(expect_success, success); if (value) { success_callback.Run(std::move(value)); } else { @@ -100,7 +121,7 @@ pref_service_.get(), nullptr, task_runner, std::string("fr"), nullptr, make_scoped_ptr(new NTPSnippetsFetcher( task_runner, std::move(request_context_getter), true)), - base::Bind(&ParseJson))); + base::Bind(&ParseJson, true))); service_->Init(true); } @@ -113,6 +134,10 @@ service_->OnSnippetsDownloaded(json); } + void SetExpectJsonParseSuccess(bool expect_success) { + service_->parse_json_callback_ = base::Bind(&ParseJson, expect_success); + } + private: base::MessageLoop message_loop_; scoped_ptr<TestingPrefServiceSimple> pref_service_; @@ -159,6 +184,36 @@ } } +TEST_F(NTPSnippetsServiceTest, LoadInvalidJson) { + SetExpectJsonParseSuccess(false); + LoadFromJSONString(GetInvalidJson()); + EXPECT_EQ(service()->size(), 0u); +} + +TEST_F(NTPSnippetsServiceTest, LoadInvalidJsonWithExistingSnippets) { + LoadFromJSONString(GetTestJson()); + ASSERT_EQ(service()->size(), 1u); + + SetExpectJsonParseSuccess(false); + LoadFromJSONString(GetInvalidJson()); + // This should not have changed the existing snippets. + EXPECT_EQ(service()->size(), 1u); +} + +TEST_F(NTPSnippetsServiceTest, LoadIncompleteJson) { + LoadFromJSONString(GetIncompleteJson()); + EXPECT_EQ(service()->size(), 0u); +} + +TEST_F(NTPSnippetsServiceTest, LoadIncompleteJsonWithExistingSnippets) { + LoadFromJSONString(GetTestJson()); + ASSERT_EQ(service()->size(), 1u); + + LoadFromJSONString(GetIncompleteJson()); + // This should not have changed the existing snippets. + EXPECT_EQ(service()->size(), 1u); +} + TEST_F(NTPSnippetsServiceTest, Discard) { std::string json_str( "{ \"recos\": [ { \"contentInfo\": { \"url\" : \"http://site.com\" }}]}");
diff --git a/components/page_load_metrics/renderer/metrics_render_frame_observer.cc b/components/page_load_metrics/renderer/metrics_render_frame_observer.cc index 260d3b62..311d857 100644 --- a/components/page_load_metrics/renderer/metrics_render_frame_observer.cc +++ b/components/page_load_metrics/renderer/metrics_render_frame_observer.cc
@@ -41,8 +41,8 @@ void MetricsRenderFrameObserver::DidObserveLoadingBehavior( blink::WebLoadingBehaviorFlag behavior) { - DCHECK(page_timing_metrics_sender_); - page_timing_metrics_sender_->DidObserveLoadingBehavior(behavior); + if (page_timing_metrics_sender_) + page_timing_metrics_sender_->DidObserveLoadingBehavior(behavior); } void MetricsRenderFrameObserver::DidCommitProvisionalLoad(
diff --git a/components/password_manager/content/public/cpp/type_converters.cc b/components/password_manager/content/public/cpp/type_converters.cc index 6076149..a4f9ef2b 100644 --- a/components/password_manager/content/public/cpp/type_converters.cc +++ b/components/password_manager/content/public/cpp/type_converters.cc
@@ -99,10 +99,10 @@ return output; } -scoped_ptr<blink::WebCredential> TypeConverter< - scoped_ptr<blink::WebCredential>, +std::unique_ptr<blink::WebCredential> TypeConverter< + std::unique_ptr<blink::WebCredential>, mojom::CredentialInfoPtr>::Convert(const mojom::CredentialInfoPtr& input) { - scoped_ptr<blink::WebCredential> output; + std::unique_ptr<blink::WebCredential> output; switch (input->type) { case mojom::CredentialType::PASSWORD:
diff --git a/components/password_manager/content/public/cpp/type_converters.h b/components/password_manager/content/public/cpp/type_converters.h index 648114f..4ac7d56 100644 --- a/components/password_manager/content/public/cpp/type_converters.h +++ b/components/password_manager/content/public/cpp/type_converters.h
@@ -5,7 +5,8 @@ #ifndef COMPONENTS_PASSWORD_MANAGER_CONTENT_PUBLIC_CPP_TYPE_CONVERTERS_IMPL_H_ #define COMPONENTS_PASSWORD_MANAGER_CONTENT_PUBLIC_CPP_TYPE_CONVERTERS_IMPL_H_ -#include "base/memory/scoped_ptr.h" +#include <memory> + #include "components/password_manager/content/public/interfaces/credential_manager.mojom.h" namespace blink { @@ -40,9 +41,9 @@ }; template <> -struct TypeConverter<scoped_ptr<blink::WebCredential>, +struct TypeConverter<std::unique_ptr<blink::WebCredential>, password_manager::mojom::CredentialInfoPtr> { - static scoped_ptr<blink::WebCredential> Convert( + static std::unique_ptr<blink::WebCredential> Convert( const password_manager::mojom::CredentialInfoPtr& input); };
diff --git a/components/password_manager/core/browser/password_form_manager.cc b/components/password_manager/core/browser/password_form_manager.cc index 52fe030..a702e61 100644 --- a/components/password_manager/core/browser/password_form_manager.cc +++ b/components/password_manager/core/browser/password_form_manager.cc
@@ -1251,15 +1251,13 @@ if (blacklisted_form.origin.GetOrigin() != observed_form_.origin.GetOrigin()) return false; if (observed_form_.scheme == PasswordForm::SCHEME_HTML) { - if (!AreStringsEqualOrEmpty(blacklisted_form.submit_element, - observed_form_.submit_element)) - return false; - if (!AreStringsEqualOrEmpty(blacklisted_form.password_element, - observed_form_.password_element)) - return false; - if (!AreStringsEqualOrEmpty(blacklisted_form.username_element, - observed_form_.username_element)) - return false; + return (blacklisted_form.origin.path() == observed_form_.origin.path()) || + (AreStringsEqualOrEmpty(blacklisted_form.submit_element, + observed_form_.submit_element) && + AreStringsEqualOrEmpty(blacklisted_form.password_element, + observed_form_.password_element) && + AreStringsEqualOrEmpty(blacklisted_form.username_element, + observed_form_.username_element)); } return true; }
diff --git a/components/password_manager/core/browser/password_form_manager_unittest.cc b/components/password_manager/core/browser/password_form_manager_unittest.cc index fc60ff8..5cf5e62 100644 --- a/components/password_manager/core/browser/password_form_manager_unittest.cc +++ b/components/password_manager/core/browser/password_form_manager_unittest.cc
@@ -762,25 +762,35 @@ blacklisted_not_match.origin = GURL("http://google.com/a/LoginAuth"); blacklisted_not_match.blacklisted_by_user = true; - // Doesn't match because of different username element. + // Doesn't match because of different username element and different page. PasswordForm blacklisted_not_match2 = *observed_form(); + blacklisted_not_match2.origin = GURL("http://accounts.google.com/a/Login123"); blacklisted_not_match2.username_element = ASCIIToUTF16("Element"); blacklisted_not_match2.blacklisted_by_user = true; + // Matches because of same element names, despite different page PasswordForm blacklisted_match = *observed_form(); blacklisted_match.origin = GURL("http://accounts.google.com/a/LoginAuth1234"); blacklisted_match.blacklisted_by_user = true; + // Matches because of same page, despite different element names + PasswordForm blacklisted_match2 = *observed_form(); + blacklisted_match2.origin = GURL("http://accounts.google.com/a/LoginAuth"); + blacklisted_match2.username_element = ASCIIToUTF16("Element"); + blacklisted_match2.blacklisted_by_user = true; + ScopedVector<PasswordForm> result; result.push_back(new PasswordForm(blacklisted_psl)); result.push_back(new PasswordForm(blacklisted_not_match)); result.push_back(new PasswordForm(blacklisted_not_match2)); result.push_back(new PasswordForm(blacklisted_match)); + result.push_back(new PasswordForm(blacklisted_match2)); result.push_back(new PasswordForm(*saved_match())); form_manager.OnGetPasswordStoreResults(std::move(result)); EXPECT_TRUE(form_manager.IsBlacklisted()); - EXPECT_THAT(form_manager.blacklisted_matches(), - ElementsAre(Pointee(blacklisted_match))); + EXPECT_THAT( + form_manager.blacklisted_matches(), + ElementsAre(Pointee(blacklisted_match), Pointee(blacklisted_match2))); EXPECT_EQ(1u, form_manager.best_matches().size()); EXPECT_EQ(*saved_match(), *form_manager.preferred_match()); }
diff --git a/components/test_runner/test_runner.cc b/components/test_runner/test_runner.cc index 9e21c8f..09a0690 100644 --- a/components/test_runner/test_runner.cc +++ b/components/test_runner/test_runner.cc
@@ -1580,6 +1580,7 @@ mock_screen_orientation_client_(new MockScreenOrientationClient), spellcheck_(new SpellCheckClient(this)), chooser_count_(0), + previously_focused_view_(nullptr), weak_factory_(this) {} TestRunner::~TestRunner() {} @@ -2884,7 +2885,22 @@ } void TestRunner::SetWindowIsKey(bool value) { - delegate_->SetFocus(proxy_->web_view(), value); + SetFocus(proxy_->web_view(), value); +} + +void TestRunner::SetFocus(blink::WebView* web_view, bool focus) { + if (focus) { + if (previously_focused_view_ != web_view) { + delegate_->SetFocus(previously_focused_view_, false); + delegate_->SetFocus(web_view, true); + previously_focused_view_ = web_view; + } + } else { + if (previously_focused_view_ == web_view) { + delegate_->SetFocus(web_view, false); + previously_focused_view_ = nullptr; + } + } } std::string TestRunner::PathToLocalResource(const std::string& path) { @@ -2966,6 +2982,8 @@ void TestRunner::ResolveBeforeInstallPromptPromise( int request_id, const std::string& platform) { + if (!test_interfaces_->GetAppBannerClient()) + return; test_interfaces_->GetAppBannerClient()->ResolvePromise(request_id, platform); }
diff --git a/components/test_runner/test_runner.h b/components/test_runner/test_runner.h index eecf7c31..ea3380a 100644 --- a/components/test_runner/test_runner.h +++ b/components/test_runner/test_runner.h
@@ -83,6 +83,7 @@ bool ShouldDumpBackForwardList() const override; blink::WebContentSettingsClient* GetWebContentSettings() const override; void InitializeWebViewWithMocks(blink::WebView* web_view) override; + void SetFocus(blink::WebView* web_view, bool focus) override; // Methods used by WebViewTestClient and WebFrameTestClient. void OnAnimationScheduled(blink::WebView* view); @@ -522,7 +523,7 @@ // Changes the cookie policy from the default to allow all cookies. void SetAlwaysAcceptCookies(bool accept); - // Gives focus to the window. + // Gives focus to the main test window. void SetWindowIsKey(bool value); // Converts a URL starting with file:///tmp/ to the local mapping. @@ -817,6 +818,11 @@ // Captured drag image. blink::WebImage drag_image_; + // View that was focused by a previous call to TestRunner::SetFocus method. + // Note - this can be a dangling pointer to an already destroyed WebView (this + // is ok, because this is taken care of in WebTestDelegate::SetFocus). + blink::WebView* previously_focused_view_; + std::set<blink::WebView*> views_with_scheduled_animations_; base::WeakPtrFactory<TestRunner> weak_factory_;
diff --git a/components/test_runner/web_test_interfaces.cc b/components/test_runner/web_test_interfaces.cc index 7fbd288..032de93e 100644 --- a/components/test_runner/web_test_interfaces.cc +++ b/components/test_runner/web_test_interfaces.cc
@@ -105,9 +105,9 @@ scoped_ptr<WebViewTestClient> WebTestInterfaces::CreateWebViewTestClient( WebTestProxyBase* web_test_proxy_base) { - return make_scoped_ptr(new WebViewTestClient( - interfaces_->GetTestRunner(), interfaces_->GetDelegate(), - interfaces_->GetEventSender(), web_test_proxy_base)); + return make_scoped_ptr(new WebViewTestClient(interfaces_->GetTestRunner(), + interfaces_->GetEventSender(), + web_test_proxy_base)); } } // namespace test_runner
diff --git a/components/test_runner/web_test_proxy.cc b/components/test_runner/web_test_proxy.cc index 16113f9a..ed62aa3 100644 --- a/components/test_runner/web_test_proxy.cc +++ b/components/test_runner/web_test_proxy.cc
@@ -92,10 +92,6 @@ test_interfaces_->WindowOpened(this); } -void WebTestProxyBase::SetDelegate(WebTestDelegate* delegate) { - delegate_ = delegate; -} - std::string WebTestProxyBase::DumpBackForwardLists() { return DumpAllBackForwardLists(test_interfaces_, delegate_); }
diff --git a/components/test_runner/web_test_proxy.h b/components/test_runner/web_test_proxy.h index 14e4952..408ac87 100644 --- a/components/test_runner/web_test_proxy.h +++ b/components/test_runner/web_test_proxy.h
@@ -72,8 +72,14 @@ view_test_client_ = std::move(view_test_client); } + WebTestDelegate* delegate() { return delegate_; } + void set_delegate(WebTestDelegate* delegate) { + DCHECK(delegate); + DCHECK(!delegate_); + delegate_ = delegate; + } + void SetInterfaces(WebTestInterfaces* interfaces); - void SetDelegate(WebTestDelegate* delegate); std::string DumpBackForwardLists();
diff --git a/components/test_runner/web_test_runner.h b/components/test_runner/web_test_runner.h index 28baf62..41b54df 100644 --- a/components/test_runner/web_test_runner.h +++ b/components/test_runner/web_test_runner.h
@@ -79,6 +79,10 @@ // method covers blink::WebCredentialManagerClient and // blink::WebSpellCheckClient. virtual void InitializeWebViewWithMocks(blink::WebView* web_view) = 0; + + // Sets focus on the given view. Internally tracks currently focused view, + // to aid in defocusing previously focused views at the right time. + virtual void SetFocus(blink::WebView* web_view, bool focus) = 0; }; } // namespace test_runner
diff --git a/components/test_runner/web_view_test_client.cc b/components/test_runner/web_view_test_client.cc index c6338b3..50a1b256 100644 --- a/components/test_runner/web_view_test_client.cc +++ b/components/test_runner/web_view_test_client.cc
@@ -28,17 +28,14 @@ namespace test_runner { WebViewTestClient::WebViewTestClient(TestRunner* test_runner, - WebTestDelegate* delegate, EventSender* event_sender, WebTestProxyBase* web_test_proxy_base) : test_runner_(test_runner), - delegate_(delegate), event_sender_(event_sender), web_test_proxy_base_(web_test_proxy_base), animation_scheduled_(false), weak_factory_(this) { DCHECK(test_runner); - DCHECK(delegate); DCHECK(event_sender); DCHECK(web_test_proxy_base); } @@ -53,7 +50,7 @@ animation_scheduled_ = true; test_runner_->OnAnimationScheduled(web_test_proxy_base_->web_view()); - delegate_->PostDelayedTask( + delegate()->PostDelayedTask( new WebCallbackTask(base::Bind(&WebViewTestClient::AnimateNow, weak_factory_.GetWeakPtr())), 1); @@ -93,7 +90,7 @@ void WebViewTestClient::didChangeContents() { if (test_runner_->shouldDumpEditingCallbacks()) - delegate_->PrintMessage( + delegate()->PrintMessage( "EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification\n"); } @@ -105,16 +102,16 @@ blink::WebNavigationPolicy policy, bool suppress_opener) { if (test_runner_->shouldDumpNavigationPolicy()) { - delegate_->PrintMessage("Default policy for createView for '" + - URLDescription(request.url()) + "' is '" + - WebNavigationPolicyToString(policy) + "'\n"); + delegate()->PrintMessage("Default policy for createView for '" + + URLDescription(request.url()) + "' is '" + + WebNavigationPolicyToString(policy) + "'\n"); } if (!test_runner_->canOpenWindows()) return nullptr; if (test_runner_->shouldDumpCreateView()) - delegate_->PrintMessage(std::string("createView(") + - URLDescription(request.url()) + ")\n"); + delegate()->PrintMessage(std::string("createView(") + + URLDescription(request.url()) + ")\n"); // The return value below is used to communicate to WebTestProxy whether it // should forward the createView request to RenderViewImpl or not. The @@ -126,7 +123,7 @@ void WebViewTestClient::setStatusText(const blink::WebString& text) { if (!test_runner_->shouldDumpStatusCallbacks()) return; - delegate_->PrintMessage( + delegate()->PrintMessage( std::string("UI DELEGATE STATUS CALLBACK: setStatusText:") + text.utf8().data() + "\n"); } @@ -144,7 +141,7 @@ bool WebViewTestClient::runFileChooser( const blink::WebFileChooserParams& params, blink::WebFileChooserCompletion* completion) { - delegate_->PrintMessage("Mock: Opening a file chooser.\n"); + delegate()->PrintMessage("Mock: Opening a file chooser.\n"); // FIXME: Add ability to set file names to a file upload control. return false; } @@ -174,10 +171,10 @@ base::i18n::WrapStringWithRTLFormatting(&wrapped_sub_text); } } - delegate_->PrintMessage("ValidationMessageClient: main-message=" + - base::UTF16ToUTF8(wrapped_main_text) + - " sub-message=" + - base::UTF16ToUTF8(wrapped_sub_text) + "\n"); + delegate()->PrintMessage("ValidationMessageClient: main-message=" + + base::UTF16ToUTF8(wrapped_main_text) + + " sub-message=" + + base::UTF16ToUTF8(wrapped_sub_text) + "\n"); } blink::WebSpeechRecognizer* WebViewTestClient::speechRecognizer() { @@ -197,7 +194,7 @@ } void WebViewTestClient::didFocus() { - delegate_->SetFocus(web_test_proxy_base_->web_view(), true); + test_runner_->SetFocus(web_test_proxy_base_->web_view(), true); } void WebViewTestClient::setToolTipText(const blink::WebString& text, @@ -216,4 +213,8 @@ return blink::WebString::fromUTF8(test_runner_->GetAcceptLanguages()); } +WebTestDelegate* WebViewTestClient::delegate() { + return web_test_proxy_base_->delegate(); +} + } // namespace test_runner
diff --git a/components/test_runner/web_view_test_client.h b/components/test_runner/web_view_test_client.h index 701354d..c92e240e 100644 --- a/components/test_runner/web_view_test_client.h +++ b/components/test_runner/web_view_test_client.h
@@ -29,7 +29,6 @@ // Caller has to ensure that all arguments (i.e. |test_runner| and |delegate|) // live longer than |this|. WebViewTestClient(TestRunner* test_runner, - WebTestDelegate* delegate, EventSender* event_sender, WebTestProxyBase* web_test_proxy_base); @@ -70,10 +69,10 @@ private: void AnimateNow(); + WebTestDelegate* delegate(); // Borrowed pointers to other parts of Layout Tests state. TestRunner* test_runner_; - WebTestDelegate* delegate_; EventSender* event_sender_; WebTestProxyBase* web_test_proxy_base_;
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 6ad9f66..db66fc6 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -357,8 +357,6 @@ "speech/endpointer/energy_endpointer.h", "speech/endpointer/energy_endpointer_params.cc", "speech/endpointer/energy_endpointer_params.h", - "speech/google_one_shot_remote_engine.cc", - "speech/google_one_shot_remote_engine.h", "speech/google_streaming_remote_engine.cc", "speech/google_streaming_remote_engine.h", "speech/speech_recognition_engine.cc",
diff --git a/content/browser/browser_plugin/browser_plugin_guest.cc b/content/browser/browser_plugin/browser_plugin_guest.cc index fa72b21..2b8e20d 100644 --- a/content/browser/browser_plugin/browser_plugin_guest.cc +++ b/content/browser/browser_plugin/browser_plugin_guest.cc
@@ -36,6 +36,7 @@ #include "content/common/host_shared_bitmap_manager.h" #include "content/common/input_messages.h" #include "content/common/site_isolation_policy.h" +#include "content/common/text_input_state.h" #include "content/common/view_messages.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_plugin_guest_manager.h" @@ -776,6 +777,14 @@ if (!attached()) return; + // The BrowserPluginGuest loses the link to |owner_web_contents_|. Therefore, + // the RenderWidgetHostViewGuest will not get a chance to update its text + // input state which is tracked by |owner_web_contents_|. + // TODO(ekaramad): We should perform detaching through WebContentsImpl ( + // inner WebContents detaching from outer WebContents). After this is fixed, + // we can remove this call to OnTextInputStateChanged (crbug.com/602640). + OnTextInputStateChanged(TextInputState()); + // This tells BrowserPluginGuest to queue up all IPCs to BrowserPlugin until // it's attached again. attached_ = false;
diff --git a/content/browser/frame_host/navigation_controller_impl_unittest.cc b/content/browser/frame_host/navigation_controller_impl_unittest.cc index eab278b..33f57c8 100644 --- a/content/browser/frame_host/navigation_controller_impl_unittest.cc +++ b/content/browser/frame_host/navigation_controller_impl_unittest.cc
@@ -45,6 +45,7 @@ #include "content/public/test/mock_render_process_host.h" #include "content/public/test/test_notification_tracker.h" #include "content/public/test/test_utils.h" +#include "content/test/browser_side_navigation_test_utils.h" #include "content/test/test_render_frame_host.h" #include "content/test/test_render_view_host.h" #include "content/test/test_web_contents.h" @@ -316,6 +317,17 @@ LoadCommittedDetails details_; }; +// PlzNavigate +// A NavigationControllerTest run with --enable-browser-side-navigation. +class NavigationControllerTestWithBrowserSideNavigation + : public NavigationControllerTest { + public: + void SetUp() override { + EnableBrowserSideNavigation(); + NavigationControllerTest::SetUp(); + } +}; + // ----------------------------------------------------------------------------- TEST_F(NavigationControllerTest, Defaults) { @@ -416,6 +428,14 @@ // is being aborted. This caused the last committed entry to be displayed in // the omnibox, which is the entry before A was created. TEST_F(NavigationControllerTest, DontDiscardWrongPendingEntry) { + if (IsBrowserSideNavigationEnabled()) { + // PlzNavigate: this exact order of events cannot happen in PlzNavigate. A + // similar issue with the wrong pending entry being discarded is tested in + // the PlzNavigate version of the test below. + SUCCEED() << "Test is not applicable with PlzNavigate."; + return; + } + NavigationControllerImpl& controller = controller_impl(); GURL initial_url("http://www.google.com"); GURL url_1("http://foo.com"); @@ -448,6 +468,52 @@ EXPECT_EQ(url_2, controller.GetVisibleEntry()->GetURL()); } +// PlzNavigate: tests a case similar to +// NavigationControllerTest.DontDiscardWrongPendingEntry. +// Tests hat receiving a DidFailProvisionalLoad from the renderer that is +// trying to commit an error page won't reset the pending entry of a navigation +// that just started. +TEST_F(NavigationControllerTestWithBrowserSideNavigation, + DontDiscardWrongPendingEntry) { + NavigationControllerImpl& controller = controller_impl(); + GURL initial_url("http://www.google.com"); + GURL url_1("http://google.com/foo"); + GURL url_2("http://foo2.com"); + + // Navigate inititally. This is the url that could erroneously be the visible + // entry when url_1 fails. + NavigateAndCommit(initial_url); + + // Set the pending entry as url_1 and receive the DidStartProvisionalLoad + // message, creating the NavigationHandle. + controller.LoadURL(url_1, Referrer(), ui::PAGE_TRANSITION_TYPED, + std::string()); + EXPECT_EQ(url_1, controller.GetVisibleEntry()->GetURL()); + main_test_rfh()->SimulateNavigationStart(url_1); + EXPECT_EQ(url_1, controller.GetVisibleEntry()->GetURL()); + + // The navigation fails and needs to show an error page. This resets the + // pending entry. + main_test_rfh()->SimulateNavigationError(url_1, net::ERR_TIMED_OUT); + EXPECT_EQ(initial_url, controller.GetVisibleEntry()->GetURL()); + + // A navigation to url_2 starts, creating a pending navigation entry. + controller.LoadURL(url_2, Referrer(), ui::PAGE_TRANSITION_TYPED, + std::string()); + EXPECT_EQ(url_2, controller.GetVisibleEntry()->GetURL()); + + // The DidFailProvsionalLoad IPC is received from the current RFH that is + // committing an error page. This should not reset the pending entry for the + // new ongoing navigation. + FrameHostMsg_DidFailProvisionalLoadWithError_Params error; + error.error_code = net::ERR_TIMED_OUT; + error.url = url_1; + main_test_rfh()->OnMessageReceived( + FrameHostMsg_DidFailProvisionalLoadWithError( + main_test_rfh()->GetRoutingID(), error)); + EXPECT_EQ(url_2, controller.GetVisibleEntry()->GetURL()); +} + TEST_F(NavigationControllerTest, LoadURL) { NavigationControllerImpl& controller = controller_impl(); TestNotificationTracker notifications;
diff --git a/content/browser/frame_host/navigator_impl.cc b/content/browser/frame_host/navigator_impl.cc index 546b119..009e0135 100644 --- a/content/browser/frame_host/navigator_impl.cc +++ b/content/browser/frame_host/navigator_impl.cc
@@ -227,7 +227,12 @@ // TODO(creis): Find a way to cancel any pending RFH here. } - DiscardPendingEntryOnFailureIfNeeded(render_frame_host->navigation_handle()); + // Discard the pending navigation entry if needed. + // PlzNavigate: the entry has already been discarded in FailedNavigation. + if (!IsBrowserSideNavigationEnabled()) { + DiscardPendingEntryOnFailureIfNeeded( + render_frame_host->navigation_handle()); + } if (delegate_) delegate_->DidFailProvisionalLoadWithError(render_frame_host, params);
diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc index b95afaf..cbd5bc8 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc
@@ -57,6 +57,7 @@ #include "content/common/host_shared_bitmap_manager.h" #include "content/common/input_messages.h" #include "content/common/resize_params.h" +#include "content/common/text_input_state.h" #include "content/common/view_messages.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/notification_service.h" @@ -2056,6 +2057,11 @@ } void RenderWidgetHostImpl::DetachDelegate() { + // If |view_| has active text input state, it will not be able to update the + // |delegate_| about shut down and losing the state (see crbug.com/602144). + if (view_) + view_->TextInputStateChanged(TextInputState()); + delegate_ = NULL; }
diff --git a/content/browser/speech/google_one_shot_remote_engine.cc b/content/browser/speech/google_one_shot_remote_engine.cc deleted file mode 100644 index ec20619..0000000 --- a/content/browser/speech/google_one_shot_remote_engine.cc +++ /dev/null
@@ -1,298 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/speech/google_one_shot_remote_engine.h" - -#include <stddef.h> -#include <stdint.h> - -#include <vector> - -#include "base/json/json_reader.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_util.h" -#include "base/values.h" -#include "content/browser/speech/audio_buffer.h" -#include "content/public/common/speech_recognition_error.h" -#include "content/public/common/speech_recognition_result.h" -#include "google_apis/google_api_keys.h" -#include "net/base/escape.h" -#include "net/base/load_flags.h" -#include "net/url_request/http_user_agent_settings.h" -#include "net/url_request/url_fetcher.h" -#include "net/url_request/url_request_context.h" -#include "net/url_request/url_request_context_getter.h" -#include "net/url_request/url_request_status.h" - -namespace content { -namespace { - -const char kDefaultSpeechRecognitionUrl[] = - "https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&"; -const char kStatusString[] = "status"; -const char kHypothesesString[] = "hypotheses"; -const char kUtteranceString[] = "utterance"; -const char kConfidenceString[] = "confidence"; -const int kWebServiceStatusNoError = 0; -const int kWebServiceStatusNoSpeech = 4; -const int kWebServiceStatusNoMatch = 5; - -bool ParseServerResponse(const std::string& response_body, - SpeechRecognitionResult* result, - SpeechRecognitionError* error) { - if (response_body.empty()) { - LOG(WARNING) << "ParseServerResponse: Response was empty."; - return false; - } - DVLOG(1) << "ParseServerResponse: Parsing response " << response_body; - - // Parse the response, ignoring comments. - std::string error_msg; - std::unique_ptr<base::Value> response_value = - base::JSONReader::ReadAndReturnError(response_body, base::JSON_PARSE_RFC, - NULL, &error_msg); - if (response_value == NULL) { - LOG(WARNING) << "ParseServerResponse: JSONReader failed : " << error_msg; - return false; - } - - if (!response_value->IsType(base::Value::TYPE_DICTIONARY)) { - DVLOG(1) << "ParseServerResponse: Unexpected response type " - << response_value->GetType(); - return false; - } - const base::DictionaryValue* response_object = - static_cast<const base::DictionaryValue*>(response_value.get()); - - // Get the status. - int status; - if (!response_object->GetInteger(kStatusString, &status)) { - DVLOG(1) << "ParseServerResponse: " << kStatusString - << " is not a valid integer value."; - return false; - } - - // Process the status. - switch (status) { - case kWebServiceStatusNoError: - break; - case kWebServiceStatusNoSpeech: - error->code = SPEECH_RECOGNITION_ERROR_NO_SPEECH; - return false; - case kWebServiceStatusNoMatch: - error->code = SPEECH_RECOGNITION_ERROR_NO_MATCH; - return false; - default: - error->code = SPEECH_RECOGNITION_ERROR_NETWORK; - // Other status codes should not be returned by the server. - DVLOG(1) << "ParseServerResponse: unexpected status code " << status; - return false; - } - - // Get the hypotheses. - const base::Value* hypotheses_value = NULL; - if (!response_object->Get(kHypothesesString, &hypotheses_value)) { - DVLOG(1) << "ParseServerResponse: Missing hypotheses attribute."; - return false; - } - - DCHECK(hypotheses_value); - if (!hypotheses_value->IsType(base::Value::TYPE_LIST)) { - DVLOG(1) << "ParseServerResponse: Unexpected hypotheses type " - << hypotheses_value->GetType(); - return false; - } - - const base::ListValue* hypotheses_list = - static_cast<const base::ListValue*>(hypotheses_value); - - // For now we support only single shot recognition, so we are giving only a - // final result, consisting of one fragment (with one or more hypotheses). - size_t index = 0; - for (; index < hypotheses_list->GetSize(); ++index) { - const base::Value* hypothesis = NULL; - if (!hypotheses_list->Get(index, &hypothesis)) { - LOG(WARNING) << "ParseServerResponse: Unable to read hypothesis value."; - break; - } - DCHECK(hypothesis); - if (!hypothesis->IsType(base::Value::TYPE_DICTIONARY)) { - LOG(WARNING) << "ParseServerResponse: Unexpected value type " - << hypothesis->GetType(); - break; - } - - const base::DictionaryValue* hypothesis_value = - static_cast<const base::DictionaryValue*>(hypothesis); - base::string16 utterance; - - if (!hypothesis_value->GetString(kUtteranceString, &utterance)) { - LOG(WARNING) << "ParseServerResponse: Missing utterance value."; - break; - } - - // It is not an error if the 'confidence' field is missing. - double confidence = 0.0; - hypothesis_value->GetDouble(kConfidenceString, &confidence); - result->hypotheses.push_back(SpeechRecognitionHypothesis(utterance, - confidence)); - } - - if (index < hypotheses_list->GetSize()) { - result->hypotheses.clear(); - return false; - } - return true; -} - -} // namespace - -const int GoogleOneShotRemoteEngine::kAudioPacketIntervalMs = 100; -int GoogleOneShotRemoteEngine::url_fetcher_id_for_tests = 0; - -GoogleOneShotRemoteEngine::GoogleOneShotRemoteEngine( - net::URLRequestContextGetter* context) - : url_context_(context) { -} - -GoogleOneShotRemoteEngine::~GoogleOneShotRemoteEngine() {} - -void GoogleOneShotRemoteEngine::SetConfig( - const SpeechRecognitionEngineConfig& config) { - config_ = config; -} - -void GoogleOneShotRemoteEngine::StartRecognition() { - DCHECK(delegate()); - DCHECK(!url_fetcher_.get()); - std::string lang_param = config_.language; - - if (lang_param.empty() && url_context_.get()) { - // If no language is provided then we use the first from the accepted - // language list. If this list is empty then it defaults to "en-US". - // Example of the contents of this list: "es,en-GB;q=0.8", "" - net::URLRequestContext* request_context = - url_context_->GetURLRequestContext(); - DCHECK(request_context); - // TODO(pauljensen): GoogleOneShotRemoteEngine should be constructed with - // a reference to the HttpUserAgentSettings rather than accessing the - // accept language through the URLRequestContext. - if (request_context->http_user_agent_settings()) { - std::string accepted_language_list = - request_context->http_user_agent_settings()->GetAcceptLanguage(); - size_t separator = accepted_language_list.find_first_of(",;"); - lang_param = accepted_language_list.substr(0, separator); - } - } - - if (lang_param.empty()) - lang_param = "en-US"; - - std::vector<std::string> parts; - parts.push_back("lang=" + net::EscapeQueryParamValue(lang_param, true)); - - if (!config_.grammars.empty()) { - DCHECK_EQ(config_.grammars.size(), 1U); - parts.push_back("lm=" + net::EscapeQueryParamValue(config_.grammars[0].url, - true)); - } - - if (!config_.hardware_info.empty()) - parts.push_back("xhw=" + net::EscapeQueryParamValue(config_.hardware_info, - true)); - parts.push_back("maxresults=" + base::UintToString(config_.max_hypotheses)); - parts.push_back(config_.filter_profanities ? "pfilter=2" : "pfilter=0"); - - std::string api_key = google_apis::GetAPIKey(); - parts.push_back("key=" + net::EscapeQueryParamValue(api_key, true)); - - GURL url(std::string(kDefaultSpeechRecognitionUrl) + - base::JoinString(parts, "&")); - - encoder_.reset(new AudioEncoder(config_.audio_sample_rate, - config_.audio_num_bits_per_sample)); - DCHECK(encoder_.get()); - url_fetcher_ = net::URLFetcher::Create(url_fetcher_id_for_tests, url, - net::URLFetcher::POST, this); - url_fetcher_->SetChunkedUpload(encoder_->GetMimeType()); - url_fetcher_->SetRequestContext(url_context_.get()); - url_fetcher_->SetReferrer(config_.origin_url); - - // The speech recognition API does not require user identification as part - // of requests, so we don't send cookies or auth data for these requests to - // prevent any accidental connection between users who are logged into the - // domain for other services (e.g. bookmark sync) with the speech requests. - url_fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES | - net::LOAD_DO_NOT_SEND_COOKIES | - net::LOAD_DO_NOT_SEND_AUTH_DATA); - url_fetcher_->Start(); -} - -void GoogleOneShotRemoteEngine::EndRecognition() { - url_fetcher_.reset(); -} - -void GoogleOneShotRemoteEngine::TakeAudioChunk(const AudioChunk& data) { - DCHECK(url_fetcher_.get()); - DCHECK(encoder_.get()); - DCHECK_EQ(data.bytes_per_sample(), config_.audio_num_bits_per_sample / 8); - encoder_->Encode(data); - scoped_refptr<AudioChunk> encoded_data(encoder_->GetEncodedDataAndClear()); - url_fetcher_->AppendChunkToUpload(encoded_data->AsString(), false); -} - -void GoogleOneShotRemoteEngine::AudioChunksEnded() { - DCHECK(url_fetcher_.get()); - DCHECK(encoder_.get()); - - // UploadAudioChunk requires a non-empty final buffer. So we encode a packet - // of silence in case encoder had no data already. - size_t sample_count = - config_.audio_sample_rate * kAudioPacketIntervalMs / 1000; - scoped_refptr<AudioChunk> dummy_chunk(new AudioChunk( - sample_count * sizeof(int16_t), encoder_->GetBitsPerSample() / 8)); - encoder_->Encode(*dummy_chunk.get()); - encoder_->Flush(); - scoped_refptr<AudioChunk> encoded_dummy_data( - encoder_->GetEncodedDataAndClear()); - DCHECK(!encoded_dummy_data->IsEmpty()); - encoder_.reset(); - - url_fetcher_->AppendChunkToUpload(encoded_dummy_data->AsString(), true); -} - -void GoogleOneShotRemoteEngine::OnURLFetchComplete( - const net::URLFetcher* source) { - DCHECK_EQ(url_fetcher_.get(), source); - SpeechRecognitionResults results; - results.push_back(SpeechRecognitionResult()); - SpeechRecognitionResult& result = results.back(); - SpeechRecognitionError error(SPEECH_RECOGNITION_ERROR_NETWORK); - std::string data; - - // The default error code in case of parse errors is NETWORK_FAILURE, however - // ParseServerResponse can change the error to a more appropriate one. - bool error_occurred = (!source->GetStatus().is_success() || - source->GetResponseCode() != 200 || - !source->GetResponseAsString(&data) || - !ParseServerResponse(data, &result, &error)); - url_fetcher_.reset(); - if (error_occurred) { - DVLOG(1) << "GoogleOneShotRemoteEngine: Network Error " << error.code; - delegate()->OnSpeechRecognitionEngineError(error); - } else { - DVLOG(1) << "GoogleOneShotRemoteEngine: Invoking delegate with result."; - delegate()->OnSpeechRecognitionEngineResults(results); - } -} - -bool GoogleOneShotRemoteEngine::IsRecognitionPending() const { - return url_fetcher_ != NULL; -} - -int GoogleOneShotRemoteEngine::GetDesiredAudioChunkDurationMs() const { - return kAudioPacketIntervalMs; -} - -} // namespace content
diff --git a/content/browser/speech/google_one_shot_remote_engine.h b/content/browser/speech/google_one_shot_remote_engine.h deleted file mode 100644 index c305bee..0000000 --- a/content/browser/speech/google_one_shot_remote_engine.h +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_BROWSER_SPEECH_GOOGLE_ONE_SHOT_REMOTE_ENGINE_H_ -#define CONTENT_BROWSER_SPEECH_GOOGLE_ONE_SHOT_REMOTE_ENGINE_H_ - -#include <memory> -#include <string> - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "content/browser/speech/audio_encoder.h" -#include "content/browser/speech/speech_recognition_engine.h" -#include "content/common/content_export.h" -#include "net/url_request/url_fetcher_delegate.h" - -namespace net { -class URLRequestContextGetter; -} - -namespace content { - -// Implements a SpeechRecognitionEngine by means of remote interaction with -// Google speech recognition webservice. -class CONTENT_EXPORT GoogleOneShotRemoteEngine - : public NON_EXPORTED_BASE(SpeechRecognitionEngine), - public net::URLFetcherDelegate { - public: - // Duration of each audio packet. - static const int kAudioPacketIntervalMs; - // ID passed to URLFetcher::Create(). Used for testing. - static int url_fetcher_id_for_tests; - - explicit GoogleOneShotRemoteEngine(net::URLRequestContextGetter* context); - ~GoogleOneShotRemoteEngine() override; - - // SpeechRecognitionEngine methods. - void SetConfig(const SpeechRecognitionEngineConfig& config) override; - void StartRecognition() override; - void EndRecognition() override; - void TakeAudioChunk(const AudioChunk& data) override; - void AudioChunksEnded() override; - bool IsRecognitionPending() const override; - int GetDesiredAudioChunkDurationMs() const override; - - // net::URLFetcherDelegate methods. - void OnURLFetchComplete(const net::URLFetcher* source) override; - - private: - SpeechRecognitionEngineConfig config_; - std::unique_ptr<net::URLFetcher> url_fetcher_; - scoped_refptr<net::URLRequestContextGetter> url_context_; - std::unique_ptr<AudioEncoder> encoder_; - - DISALLOW_COPY_AND_ASSIGN(GoogleOneShotRemoteEngine); -}; - -} // namespace content - -#endif // CONTENT_BROWSER_SPEECH_GOOGLE_ONE_SHOT_REMOTE_ENGINE_H_
diff --git a/content/browser/speech/google_one_shot_remote_engine_unittest.cc b/content/browser/speech/google_one_shot_remote_engine_unittest.cc deleted file mode 100644 index a78ba3c..0000000 --- a/content/browser/speech/google_one_shot_remote_engine_unittest.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 "base/message_loop/message_loop.h" -#include "base/strings/utf_string_conversions.h" -#include "content/browser/speech/audio_buffer.h" -#include "content/browser/speech/google_one_shot_remote_engine.h" -#include "content/public/common/speech_recognition_error.h" -#include "content/public/common/speech_recognition_result.h" -#include "net/base/net_errors.h" -#include "net/url_request/test_url_fetcher_factory.h" -#include "net/url_request/url_request_context_getter.h" -#include "net/url_request/url_request_status.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace content { - -class GoogleOneShotRemoteEngineTest : public SpeechRecognitionEngineDelegate, - public testing::Test { - public: - GoogleOneShotRemoteEngineTest() - : error_(SPEECH_RECOGNITION_ERROR_NONE) {} - - // Creates a speech recognition request and invokes its URL fetcher delegate - // with the given test data. - void CreateAndTestRequest(bool success, const std::string& http_response); - - // SpeechRecognitionRequestDelegate methods. - void OnSpeechRecognitionEngineResults( - const SpeechRecognitionResults& results) override { - results_ = results; - } - - void OnSpeechRecognitionEngineEndOfUtterance() override { - } - - void OnSpeechRecognitionEngineError( - const SpeechRecognitionError& error) override { - error_ = error.code; - } - - // Accessor for the only result item. - const SpeechRecognitionResult& result() const { - DCHECK_EQ(results_.size(), 1U); - return results_[0]; - } - - protected: - base::MessageLoop message_loop_; - net::TestURLFetcherFactory url_fetcher_factory_; - SpeechRecognitionErrorCode error_; - SpeechRecognitionResults results_; -}; - -void GoogleOneShotRemoteEngineTest::CreateAndTestRequest( - bool success, const std::string& http_response) { - GoogleOneShotRemoteEngine client(NULL); - unsigned char dummy_audio_buffer_data[2] = {'\0', '\0'}; - scoped_refptr<AudioChunk> dummy_audio_chunk( - new AudioChunk(&dummy_audio_buffer_data[0], - sizeof(dummy_audio_buffer_data), - 2 /* bytes per sample */)); - client.set_delegate(this); - client.StartRecognition(); - client.TakeAudioChunk(*dummy_audio_chunk.get()); - client.AudioChunksEnded(); - net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); - - fetcher->set_url(fetcher->GetOriginalURL()); - fetcher->set_status( - net::URLRequestStatus::FromError(success ? net::OK : net::ERR_FAILED)); - fetcher->set_response_code(success ? 200 : 500); - fetcher->SetResponseString(http_response); - - fetcher->delegate()->OnURLFetchComplete(fetcher); - // Parsed response will be available in result(). -} - -TEST_F(GoogleOneShotRemoteEngineTest, BasicTest) { - // Normal success case with one result. - CreateAndTestRequest(true, - "{\"status\":0,\"hypotheses\":" - "[{\"utterance\":\"123456\",\"confidence\":0.9}]}"); - EXPECT_EQ(error_, SPEECH_RECOGNITION_ERROR_NONE); - EXPECT_EQ(1U, result().hypotheses.size()); - EXPECT_EQ(base::ASCIIToUTF16("123456"), result().hypotheses[0].utterance); - EXPECT_EQ(0.9, result().hypotheses[0].confidence); - - // Normal success case with multiple results. - CreateAndTestRequest(true, - "{\"status\":0,\"hypotheses\":[" - "{\"utterance\":\"hello\",\"confidence\":0.9}," - "{\"utterance\":\"123456\",\"confidence\":0.5}]}"); - EXPECT_EQ(error_, SPEECH_RECOGNITION_ERROR_NONE); - EXPECT_EQ(2u, result().hypotheses.size()); - EXPECT_EQ(base::ASCIIToUTF16("hello"), result().hypotheses[0].utterance); - EXPECT_EQ(0.9, result().hypotheses[0].confidence); - EXPECT_EQ(base::ASCIIToUTF16("123456"), result().hypotheses[1].utterance); - EXPECT_EQ(0.5, result().hypotheses[1].confidence); - - // Zero results. - CreateAndTestRequest(true, "{\"status\":0,\"hypotheses\":[]}"); - EXPECT_EQ(error_, SPEECH_RECOGNITION_ERROR_NONE); - EXPECT_EQ(0U, result().hypotheses.size()); - - // Http failure case. - CreateAndTestRequest(false, std::string()); - EXPECT_EQ(error_, SPEECH_RECOGNITION_ERROR_NETWORK); - EXPECT_EQ(0U, result().hypotheses.size()); - - // Invalid status case. - CreateAndTestRequest(true, "{\"status\":\"invalid\",\"hypotheses\":[]}"); - EXPECT_EQ(error_, SPEECH_RECOGNITION_ERROR_NETWORK); - EXPECT_EQ(0U, result().hypotheses.size()); - - // Server-side error case. - CreateAndTestRequest(true, "{\"status\":1,\"hypotheses\":[]}"); - EXPECT_EQ(error_, SPEECH_RECOGNITION_ERROR_NETWORK); - EXPECT_EQ(0U, result().hypotheses.size()); - - // Malformed JSON case. - CreateAndTestRequest(true, "{\"status\":0,\"hypotheses\":" - "[{\"unknownkey\":\"hello\"}]}"); - EXPECT_EQ(error_, SPEECH_RECOGNITION_ERROR_NETWORK); - EXPECT_EQ(0U, result().hypotheses.size()); -} - -} // namespace content
diff --git a/content/browser/speech/speech_recognition_dispatcher_host.cc b/content/browser/speech/speech_recognition_dispatcher_host.cc index 3512aca..a078171 100644 --- a/content/browser/speech/speech_recognition_dispatcher_host.cc +++ b/content/browser/speech/speech_recognition_dispatcher_host.cc
@@ -158,7 +158,6 @@ context.request_id = params.request_id; SpeechRecognitionSessionConfig config; - config.is_legacy_api = false; config.language = params.language; config.grammars = params.grammars; config.max_hypotheses = params.max_hypotheses;
diff --git a/content/browser/speech/speech_recognition_manager_impl.cc b/content/browser/speech/speech_recognition_manager_impl.cc index 47b5995..3b261fc 100644 --- a/content/browser/speech/speech_recognition_manager_impl.cc +++ b/content/browser/speech/speech_recognition_manager_impl.cc
@@ -14,7 +14,6 @@ #include "content/browser/browser_main_loop.h" #include "content/browser/renderer_host/media/media_stream_manager.h" #include "content/browser/renderer_host/media/media_stream_ui_proxy.h" -#include "content/browser/speech/google_one_shot_remote_engine.h" #include "content/browser/speech/google_streaming_remote_engine.h" #include "content/browser/speech/speech_recognition_engine.h" #include "content/browser/speech/speech_recognizer_impl.h" @@ -113,9 +112,6 @@ if (delegate_) delegate_->GetDiagnosticInformation(&can_report_metrics, &hardware_info); - // The legacy api cannot use continuous mode. - DCHECK(!config.is_legacy_api || !config.continuous); - #if !defined(OS_ANDROID) // A SpeechRecognitionEngine (and corresponding Config) is required only // when using SpeechRecognizerImpl, which performs the audio capture and @@ -141,15 +137,8 @@ remote_engine_config.auth_scope = config.auth_scope; remote_engine_config.preamble = config.preamble; - SpeechRecognitionEngine* google_remote_engine; - if (config.is_legacy_api) { - google_remote_engine = - new GoogleOneShotRemoteEngine(config.url_request_context_getter.get()); - } else { - google_remote_engine = new GoogleStreamingRemoteEngine( - config.url_request_context_getter.get()); - } - + SpeechRecognitionEngine* google_remote_engine = + new GoogleStreamingRemoteEngine(config.url_request_context_getter.get()); google_remote_engine->SetConfig(remote_engine_config); session->recognizer = new SpeechRecognizerImpl(
diff --git a/content/browser/speech/speech_recognizer_impl.cc b/content/browser/speech/speech_recognizer_impl.cc index 271675f..d8bfdc9 100644 --- a/content/browser/speech/speech_recognizer_impl.cc +++ b/content/browser/speech/speech_recognizer_impl.cc
@@ -13,7 +13,6 @@ #include "content/browser/browser_main_loop.h" #include "content/browser/media/media_internals.h" #include "content/browser/speech/audio_buffer.h" -#include "content/browser/speech/google_one_shot_remote_engine.h" #include "content/public/browser/speech_recognition_event_listener.h" #include "media/base/audio_converter.h"
diff --git a/content/browser/speech/speech_recognizer_impl_unittest.cc b/content/browser/speech/speech_recognizer_impl_unittest.cc index d93fdcf7..fffc26d 100644 --- a/content/browser/speech/speech_recognizer_impl_unittest.cc +++ b/content/browser/speech/speech_recognizer_impl_unittest.cc
@@ -7,8 +7,10 @@ #include <vector> +#include "base/sys_byteorder.h" #include "content/browser/browser_thread_impl.h" -#include "content/browser/speech/google_one_shot_remote_engine.h" +#include "content/browser/speech/google_streaming_remote_engine.h" +#include "content/browser/speech/proto/google_streaming_api.pb.h" #include "content/browser/speech/speech_recognizer_impl.h" #include "content/public/browser/speech_recognition_event_listener.h" #include "media/audio/audio_manager_base.h" @@ -48,7 +50,7 @@ volume_(-1.0f) { // SpeechRecognizer takes ownership of sr_engine. SpeechRecognitionEngine* sr_engine = - new GoogleOneShotRemoteEngine(NULL /* URLRequestContextGetter */); + new GoogleStreamingRemoteEngine(NULL /* URLRequestContextGetter */); SpeechRecognitionEngineConfig config; config.audio_num_bits_per_sample = SpeechRecognizerImpl::kNumBitsPerAudioSample; @@ -65,7 +67,7 @@ int audio_packet_length_bytes = (SpeechRecognizerImpl::kAudioSampleRate * - GoogleOneShotRemoteEngine::kAudioPacketIntervalMs * + GoogleStreamingRemoteEngine::kAudioPacketIntervalMs * ChannelLayoutToChannelCount(SpeechRecognizerImpl::kChannelLayout) * SpeechRecognizerImpl::kNumBitsPerAudioSample) / (8 * 1000); audio_packet_.resize(audio_packet_length_bytes); @@ -258,16 +260,31 @@ EXPECT_FALSE(result_received_); EXPECT_EQ(SPEECH_RECOGNITION_ERROR_NONE, error_); - // Issue the network callback to complete the process. - net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0); - ASSERT_TRUE(fetcher); + // Create a response string. + proto::SpeechRecognitionEvent proto_event; + proto_event.set_status(proto::SpeechRecognitionEvent::STATUS_SUCCESS); + proto::SpeechRecognitionResult* proto_result = proto_event.add_result(); + proto_result->set_final(true); + proto::SpeechRecognitionAlternative* proto_alternative = + proto_result->add_alternative(); + proto_alternative->set_confidence(0.5f); + proto_alternative->set_transcript("123"); + std::string msg_string; + proto_event.SerializeToString(&msg_string); + uint32_t prefix = + base::HostToNet32(base::checked_cast<uint32_t>(msg_string.size())); + msg_string.insert(0, reinterpret_cast<char*>(&prefix), sizeof(prefix)); + // Issue the network callback to complete the process. + net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID( + GoogleStreamingRemoteEngine::kDownstreamUrlFetcherIdForTesting); + ASSERT_TRUE(fetcher); fetcher->set_url(fetcher->GetOriginalURL()); fetcher->set_status(net::URLRequestStatus()); fetcher->set_response_code(200); - fetcher->SetResponseString( - "{\"status\":0,\"hypotheses\":[{\"utterance\":\"123\"}]}"); + fetcher->SetResponseString(msg_string); fetcher->delegate()->OnURLFetchComplete(fetcher); + base::MessageLoop::current()->RunUntilIdle(); EXPECT_TRUE(recognition_ended_); EXPECT_TRUE(result_received_); @@ -410,7 +427,7 @@ ASSERT_TRUE(controller); int num_packets = (SpeechRecognizerImpl::kNoSpeechTimeoutMs) / - GoogleOneShotRemoteEngine::kAudioPacketIntervalMs + 1; + GoogleStreamingRemoteEngine::kAudioPacketIntervalMs + 1; // The vector is already filled with zero value samples on create. for (int i = 0; i < num_packets; ++i) { controller->event_handler()->OnData(controller, audio_bus_.get()); @@ -437,7 +454,7 @@ ASSERT_TRUE(controller); int num_packets = (SpeechRecognizerImpl::kNoSpeechTimeoutMs) / - GoogleOneShotRemoteEngine::kAudioPacketIntervalMs; + GoogleStreamingRemoteEngine::kAudioPacketIntervalMs; // The vector is already filled with zero value samples on create. for (int i = 0; i < num_packets / 2; ++i) { @@ -474,7 +491,7 @@ // Feed some samples to begin with for the endpointer to do noise estimation. int num_packets = SpeechRecognizerImpl::kEndpointerEstimationTimeMs / - GoogleOneShotRemoteEngine::kAudioPacketIntervalMs; + GoogleStreamingRemoteEngine::kAudioPacketIntervalMs; FillPacketWithNoise(); for (int i = 0; i < num_packets; ++i) { controller->event_handler()->OnData(controller, audio_bus_.get());
diff --git a/content/common/origin_trials/trial_token.cc b/content/common/origin_trials/trial_token.cc index cc91aae..0a137edc 100644 --- a/content/common/origin_trials/trial_token.cc +++ b/content/common/origin_trials/trial_token.cc
@@ -9,13 +9,13 @@ #include <vector> #include "base/base64.h" +#include "base/big_endian.h" +#include "base/json/json_reader.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/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" +#include "base/strings/string_piece.h" #include "base/time/time.h" +#include "base/values.h" #include "url/gurl.h" #include "url/origin.h" @@ -23,84 +23,133 @@ namespace { -// Version 1 is the only token version currently supported -const uint8_t kVersion1 = 1; +// Version is a 1-byte field at offset 0. +const size_t kVersionOffset = 0; +const size_t kVersionSize = 1; -const char kFieldSeparator[] = "|"; +// These constants define the Version 2 field sizes and offsets. +const size_t kSignatureOffset = kVersionOffset + kVersionSize; +const size_t kSignatureSize = 64; +const size_t kPayloadLengthOffset = kSignatureOffset + kSignatureSize; +const size_t kPayloadLengthSize = 4; +const size_t kPayloadOffset = kPayloadLengthOffset + kPayloadLengthSize; + +// Version 2 is the only token version currently supported. Version 1 was +// introduced in Chrome M50, and removed in M51. There were no experiments +// enabled in the stable M50 release which would have used those tokens. +const uint8_t kVersion2 = 2; } // namespace TrialToken::~TrialToken() {} -std::unique_ptr<TrialToken> TrialToken::Parse(const std::string& token_text) { - if (token_text.empty()) { +// static +std::unique_ptr<TrialToken> TrialToken::From(const std::string& token_text, + base::StringPiece public_key) { + std::unique_ptr<std::string> token_payload = Extract(token_text, public_key); + if (!token_payload) { + return nullptr; + } + return Parse(*token_payload); +} + +bool TrialToken::IsValidForFeature(const url::Origin& origin, + base::StringPiece feature_name, + const base::Time& now) const { + return ValidateOrigin(origin) && ValidateFeatureName(feature_name) && + ValidateDate(now); +} + +std::unique_ptr<std::string> TrialToken::Extract( + const std::string& token_payload, + base::StringPiece public_key) { + if (token_payload.empty()) { return nullptr; } - // Extract the version from the token. The version must be the first part of - // the token, separated from the remainder, as: - // version|<version-specific contents> - size_t version_end = token_text.find(kFieldSeparator); - if (version_end == std::string::npos) { + // Token is base64-encoded; decode first. + std::string token_contents; + if (!base::Base64Decode(token_payload, &token_contents)) { return nullptr; } - std::string version_string = token_text.substr(0, version_end); - unsigned int version = 0; - if (!base::StringToUint(version_string, &version) || version > UINT8_MAX) { + // Only version 2 currently supported. + if (token_contents.length() < (kVersionOffset + kVersionSize)) { + return nullptr; + } + uint8_t version = token_contents[kVersionOffset]; + if (version != kVersion2) { return nullptr; } - // Only version 1 currently supported - if (version != kVersion1) { + // Token must be large enough to contain a version, signature, and payload + // length. + if (token_contents.length() < (kPayloadLengthOffset + kPayloadLengthSize)) { return nullptr; } - // Extract the version-specific contents of the token - std::string token_contents = token_text.substr(version_end + 1); + // Extract the length of the signed data (Big-endian). + uint32_t payload_length; + base::ReadBigEndian(&(token_contents[kPayloadLengthOffset]), &payload_length); - // The contents of a valid version 1 token should resemble: - // signature|origin|feature_name|expiry_timestamp - std::vector<std::string> parts = - SplitString(token_contents, kFieldSeparator, base::KEEP_WHITESPACE, - base::SPLIT_WANT_ALL); - if (parts.size() != 4) { + // Validate that the stated length matches the actual payload length. + if (payload_length != token_contents.length() - kPayloadOffset) { return nullptr; } - const std::string& signature = parts[0]; - const std::string& origin_string = parts[1]; - const std::string& feature_name = parts[2]; - const std::string& expiry_string = parts[3]; + // Extract the version-specific contents of the token. + const char* token_bytes = token_contents.data(); + base::StringPiece version_piece(token_bytes + kVersionOffset, kVersionSize); + base::StringPiece signature(token_bytes + kSignatureOffset, kSignatureSize); + base::StringPiece payload_piece(token_bytes + kPayloadLengthOffset, + kPayloadLengthSize + payload_length); - uint64_t expiry_timestamp; - if (!base::StringToUint64(expiry_string, &expiry_timestamp)) { + // The data which is covered by the signature is (version + length + payload). + std::string signed_data = + version_piece.as_string() + payload_piece.as_string(); + + // Validate the signature on the data before proceeding. + if (!TrialToken::ValidateSignature(signature, signed_data, public_key)) { return nullptr; } - // Ensure that the origin is a valid (non-unique) origin URL + // Return just the payload, as a new string. + return base::WrapUnique( + new std::string(token_contents, kPayloadOffset, payload_length)); +} + +std::unique_ptr<TrialToken> TrialToken::Parse(const std::string& token_json) { + std::unique_ptr<base::DictionaryValue> datadict = + base::DictionaryValue::From(base::JSONReader::Read(token_json)); + if (!datadict) { + return nullptr; + } + + std::string origin_string; + std::string feature_name; + int expiry_timestamp = 0; + datadict->GetString("origin", &origin_string); + datadict->GetString("feature", &feature_name); + datadict->GetInteger("expiry", &expiry_timestamp); + + // Ensure that the origin is a valid (non-unique) origin URL. url::Origin origin = url::Origin(GURL(origin_string)); if (origin.unique()) { return nullptr; } - // Signed data is (origin + "|" + feature_name + "|" + expiry). - std::string data = token_contents.substr(signature.length() + 1); + // Ensure that the feature name is a valid string. + if (feature_name.empty()) { + return nullptr; + } - return base::WrapUnique(new TrialToken(version, signature, data, origin, - feature_name, expiry_timestamp)); -} + // Ensure that the expiry timestamp is a valid (positive) integer. + if (expiry_timestamp <= 0) { + return nullptr; + } -bool TrialToken::IsAppropriate(const url::Origin& origin, - base::StringPiece feature_name) const { - return ValidateOrigin(origin) && ValidateFeatureName(feature_name); -} - -bool TrialToken::IsValid(const base::Time& now, - base::StringPiece public_key) const { - // TODO(iclelland): Allow for multiple signing keys, and iterate over all - // active keys here. https://crbug.com/543220 - return ValidateDate(now) && ValidateSignature(public_key); + return base::WrapUnique( + new TrialToken(origin, feature_name, expiry_timestamp)); } bool TrialToken::ValidateOrigin(const url::Origin& origin) const { @@ -115,24 +164,14 @@ return expiry_time_ > now; } -bool TrialToken::ValidateSignature(base::StringPiece public_key) const { - return ValidateSignature(signature_, data_, public_key); -} - // static -bool TrialToken::ValidateSignature(const std::string& signature_text, +bool TrialToken::ValidateSignature(base::StringPiece signature, const std::string& data, base::StringPiece public_key) { // Public key must be 32 bytes long for Ed25519. CHECK_EQ(public_key.length(), 32UL); - std::string signature; - // signature_text is base64-encoded; decode first. - if (!base::Base64Decode(signature_text, &signature)) { - return false; - } - - // Signature must be 64 bytes long + // Signature must be 64 bytes long. if (signature.length() != 64) { return false; } @@ -144,16 +183,10 @@ return (result != 0); } -TrialToken::TrialToken(uint8_t version, - const std::string& signature, - const std::string& data, - const url::Origin& origin, +TrialToken::TrialToken(const url::Origin& origin, const std::string& feature_name, uint64_t expiry_timestamp) - : version_(version), - signature_(signature), - data_(data), - origin_(origin), + : origin_(origin), feature_name_(feature_name), expiry_time_(base::Time::FromDoubleT(expiry_timestamp)) {}
diff --git a/content/common/origin_trials/trial_token.h b/content/common/origin_trials/trial_token.h index 3143a7ef..fa05e37 100644 --- a/content/common/origin_trials/trial_token.h +++ b/content/common/origin_trials/trial_token.h
@@ -32,23 +32,20 @@ public: ~TrialToken(); - // Returns a token object if the string represents a well-formed token, or - // nullptr otherwise. (This does not mean that the token is valid, just that - // it can be parsed.) - static std::unique_ptr<TrialToken> Parse(const std::string& token_text); + // Returns a token object if the string represents a signed well-formed token, + // or nullptr otherwise. (This does not mean that the token is currently + // valid, or appropriate for a given origin / feature, just that it is + // correctly formatted and signed by the supplied public key, and can be + // parsed.) + static std::unique_ptr<TrialToken> From(const std::string& token_text, + base::StringPiece public_key); - // Returns true if this feature is appropriate for use by the given origin, - // for the given feature name. This does not check whether the signature is - // valid, or whether the token itself has expired. - bool IsAppropriate(const url::Origin& origin, - base::StringPiece feature_name) const; + // Returns true if this token is appropriate for use by the given origin, + // for the given feature name, and has not yet expired. + bool IsValidForFeature(const url::Origin& origin, + base::StringPiece feature_name, + const base::Time& now) const; - // Returns true if this token has a valid signature, and has not expired. - bool IsValid(const base::Time& now, base::StringPiece public_key) const; - - uint8_t version() { return version_; } - std::string signature() { return signature_; } - std::string data() { return data_; } url::Origin origin() { return origin_; } std::string feature_name() { return feature_name_; } base::Time expiry_time() { return expiry_time_; } @@ -56,44 +53,28 @@ protected: friend class TrialTokenTest; + // Returns the payload of a signed token, or nullptr if the token is not + // properly signed, or is not well-formed. + static std::unique_ptr<std::string> Extract(const std::string& token_text, + base::StringPiece public_key); + + // Returns a token object if the string represents a well-formed JSON token + // payload, or nullptr otherwise. + static std::unique_ptr<TrialToken> Parse(const std::string& token_json); + bool ValidateOrigin(const url::Origin& origin) const; bool ValidateFeatureName(base::StringPiece feature_name) const; bool ValidateDate(const base::Time& now) const; - bool ValidateSignature(base::StringPiece public_key) const; - static bool ValidateSignature(const std::string& signature_text, + static bool ValidateSignature(base::StringPiece signature_text, const std::string& data, base::StringPiece public_key); private: - TrialToken(uint8_t version, - const std::string& signature, - const std::string& data, - const url::Origin& origin, + TrialToken(const url::Origin& origin, const std::string& feature_name, uint64_t expiry_timestamp); - // The version number for this token. The version identifies the structure of - // the token, as well as the algorithm used to generate/validate the token. - // The version number is only incremented when incompatible changes are made - // to either the structure (e.g. adding a field), or the algorithm (e.g. - // changing the hash or signing algorithm). - // NOTE: The version number is not part of the token signature and validation. - // Thus it is possible to modify a token to use a different version from - // that used to generate the signature. To mitigate cross-version - // attacks, the signing key(s) should be changed whenever there are - // changes to the token structure or algorithms. - uint8_t version_; - - // The base64-encoded-signature portion of the token. For the token to be - // valid, this must be a valid signature for the data portion of the token, as - // verified by the public key in trial_token.cc. - std::string signature_; - - // The portion of the token string which is signed, and whose signature is - // contained in the signature_ member. - std::string data_; - // The origin for which this token is valid. Must be a secure origin. url::Origin origin_;
diff --git a/content/common/origin_trials/trial_token_unittest.cc b/content/common/origin_trials/trial_token_unittest.cc index f5a2527a..ebb5b05 100644 --- a/content/common/origin_trials/trial_token_unittest.cc +++ b/content/common/origin_trials/trial_token_unittest.cc
@@ -49,14 +49,14 @@ }; // This is a good trial token, signed with the above test private key. +// Generate this token with the command (in tools/origin_trials): +// generate_token.py valid.example.com Frobulate --expire-timestamp=1458766277 const char* kSampleToken = - "1|UsEO0cNxoUtBnHDJdGPWTlXuLENjXcEIPL7Bs7sbvicPCcvAtyqhQuTJ9h/u1R3VZpWigtI+" - "SdUwk7Dyk/qbDw==|https://valid.example.com|Frobulate|1458766277"; -const uint8_t kExpectedVersion = 1; -const char* kExpectedSignature = - "UsEO0cNxoUtBnHDJdGPWTlXuLENjXcEIPL7Bs7sbvicPCcvAtyqhQuTJ9h/u1R3VZpWigtI+S" - "dUwk7Dyk/qbDw=="; -const char* kExpectedData = "https://valid.example.com|Frobulate|1458766277"; + "Ap+Q/Qm0ELadZql+dlEGSwnAVsFZKgCEtUZg8idQC3uekkIeSZIY1tftoYdrwhqj" + "7FO5L22sNvkZZnacLvmfNwsAAABZeyJvcmlnaW4iOiAiaHR0cHM6Ly92YWxpZC5l" + "eGFtcGxlLmNvbTo0NDMiLCAiZmVhdHVyZSI6ICJGcm9idWxhdGUiLCAiZXhwaXJ5" + "IjogMTQ1ODc2NjI3N30="; + const char* kExpectedFeatureName = "Frobulate"; const char* kExpectedOrigin = "https://valid.example.com"; const uint64_t kExpectedExpiry = 1458766277; @@ -75,49 +75,76 @@ // Well-formed trial token with an invalid signature. const char* kInvalidSignatureToken = - "1|CO8hDne98QeFeOJ0DbRZCBN3uE0nyaPgaLlkYhSWnbRoDfEAg+TXELaYfQPfEvKYFauBg/" - "hnxmba765hz0mXMc==|https://valid.example.com|Frobulate|1458766277"; + "AYeNXSDktgG9p4ns5B1WKsLq2TytMxfR4whfbi+oyT0rXyzh+qXYfxbDMGmyjU2Z" + "lEJ16vQObMXJoOaYUqd8xwkAAABZeyJvcmlnaW4iOiAiaHR0cHM6Ly92YWxpZC5l" + "eGFtcGxlLmNvbTo0NDMiLCAiZmVhdHVyZSI6ICJGcm9idWxhdGUiLCAiZXhwaXJ5" + "IjogMTQ1ODc2NjI3N30="; + +// Trial token truncated in the middle of the length field; too short to +// possibly be valid. +const char kTruncatedToken[] = + "Ap+Q/Qm0ELadZql+dlEGSwnAVsFZKgCEtUZg8idQC3uekkIeSZIY1tftoYdrwhqj" + "7FO5L22sNvkZZnacLvmfNwsA"; + +// Trial token with an incorrectly-declared length, but with a valid signature. +const char kIncorrectLengthToken[] = + "Ao06eNl/CZuM88qurWKX4RfoVEpHcVHWxdOTrEXZkaC1GUHyb/8L4sthADiVWdc9" + "kXFyF1BW5bbraqp6MBVr3wEAAABaeyJvcmlnaW4iOiAiaHR0cHM6Ly92YWxpZC5l" + "eGFtcGxlLmNvbTo0NDMiLCAiZmVhdHVyZSI6ICJGcm9idWxhdGUiLCAiZXhwaXJ5" + "IjogMTQ1ODc2NjI3N30="; + +// Trial token with a misidentified version (42). +const char kIncorrectVersionToken[] = + "KlH8wVLT5o59uDvlJESorMDjzgWnvG1hmIn/GiT9Ng3f45ratVeiXCNTeaJheOaG" + "A6kX4ir4Amv8aHVC+OJHZQkAAABZeyJvcmlnaW4iOiAiaHR0cHM6Ly92YWxpZC5l" + "eGFtcGxlLmNvbTo0NDMiLCAiZmVhdHVyZSI6ICJGcm9idWxhdGUiLCAiZXhwaXJ5" + "IjogMTQ1ODc2NjI3N30="; + +const char kSampleTokenJSON[] = + "{\"origin\": \"https://valid.example.com:443\", \"feature\": " + "\"Frobulate\", \"expiry\": 1458766277}"; // Various ill-formed trial tokens. These should all fail to parse. const char* kInvalidTokens[] = { - // Invalid - only one part + // Invalid - Not JSON at all "abcde", - // Not enough parts - "https://valid.example.com|FeatureName|1458766277", - "Signature|https://valid.example.com|FeatureName|1458766277", - // Non-numeric version - "a|Signature|https://valid.example.com|FeatureName|1458766277", - "1x|Signature|https://valid.example.com|FeatureName|1458766277", - // Unsupported version (< min, > max, negative, overflow) - "0|Signature|https://valid.example.com|FeatureName|1458766277", - "2|Signature|https://valid.example.com|FeatureName|1458766277", - "-1|Signature|https://valid.example.com|FeatureName|1458766277", - "99999|Signature|https://valid.example.com|FeatureName|1458766277", - // Delimiter in feature name - "1|Signature|https://valid.example.com|Feature|Name|1458766277", - // Extra string field - "1|Signature|https://valid.example.com|FeatureName|1458766277|ExtraField", - // Extra numeric field - "1|Signature|https://valid.example.com|FeatureName|1458766277|1458766277", - // Non-numeric expiry timestamp - "1|Signature|https://valid.example.com|FeatureName|abcdefghij", - "1|Signature|https://valid.example.com|FeatureName|1458766277x", + // Invalid JSON + "{", + // Not an object + "\"abcde\"", + "123.4", + "[0, 1, 2]", + // Missing keys + "{}", + "{\"something\": 1}", + "{\"origin\": \"https://a.a\"}", + "{\"origin\": \"https://a.a\", \"feature\": \"a\"}" + "{\"origin\": \"https://a.a\", \"expiry\": 1458766277}", + "{\"feature\": \"FeatureName\", \"expiry\": 1458766277}", + // Incorrect types + "{\"origin\": 1, \"feature\": \"a\", \"expiry\": 1458766277}", + "{\"origin\": \"https://a.a\", \"feature\": 1, \"expiry\": 1458766277}", + "{\"origin\": \"https://a.a\", \"feature\": \"a\", \"expiry\": \"1\"}", // Negative expiry timestamp - "1|Signature|https://valid.example.com|FeatureName|-1458766277", + "{\"origin\": \"https://a.a\", \"feature\": \"a\", \"expiry\": -1}", // Origin not a proper origin URL - "1|Signature|abcdef|FeatureName|1458766277", - "1|Signature|data:text/plain,abcdef|FeatureName|1458766277", - "1|Signature|javascript:alert(1)|FeatureName|1458766277"}; -const size_t kNumInvalidTokens = arraysize(kInvalidTokens); + "{\"origin\": \"abcdef\", \"feature\": \"a\", \"expiry\": 1458766277}", + "{\"origin\": \"data:text/plain,abcdef\", \"feature\": \"a\", \"expiry\": " + "1458766277}", + "{\"origin\": \"javascript:alert(1)\", \"feature\": \"a\", \"expiry\": " + "1458766277}"}; } // namespace -class TrialTokenTest : public testing::Test { +class TrialTokenTest : public testing::TestWithParam<const char*> { public: TrialTokenTest() : expected_origin_(GURL(kExpectedOrigin)), invalid_origin_(GURL(kInvalidOrigin)), insecure_origin_(GURL(kInsecureOrigin)), + expected_expiry_(base::Time::FromDoubleT(kExpectedExpiry)), + valid_timestamp_(base::Time::FromDoubleT(kValidTimestamp)), + invalid_timestamp_(base::Time::FromDoubleT(kInvalidTimestamp)), correct_public_key_( base::StringPiece(reinterpret_cast<const char*>(kTestPublicKey), arraysize(kTestPublicKey))), @@ -126,6 +153,14 @@ arraysize(kTestPublicKey2))) {} protected: + std::unique_ptr<std::string> Extract(const std::string& token_text, + base::StringPiece public_key) { + return TrialToken::Extract(token_text, public_key); + } + std::unique_ptr<TrialToken> Parse(const std::string& token_payload) { + return TrialToken::Parse(token_payload); + } + bool ValidateOrigin(TrialToken* token, const url::Origin origin) { return token->ValidateOrigin(origin); } @@ -138,11 +173,6 @@ return token->ValidateDate(now); } - bool ValidateSignature(TrialToken* token, - const base::StringPiece& public_key) { - return token->ValidateSignature(public_key); - } - base::StringPiece correct_public_key() { return correct_public_key_; } base::StringPiece incorrect_public_key() { return incorrect_public_key_; } @@ -150,38 +180,88 @@ const url::Origin invalid_origin_; const url::Origin insecure_origin_; + const base::Time expected_expiry_; + const base::Time valid_timestamp_; + const base::Time invalid_timestamp_; + private: base::StringPiece correct_public_key_; base::StringPiece incorrect_public_key_; }; +// Test the extraction of the signed payload from token strings. This includes +// checking the included version identifier, payload length, and cryptographic +// signature. + +// Test verification of signature and extraction of token JSON from signed +// token. +TEST_F(TrialTokenTest, ValidateValidSignature) { + std::unique_ptr<std::string> token_payload = + Extract(kSampleToken, correct_public_key()); + ASSERT_TRUE(token_payload); + EXPECT_STREQ(kSampleTokenJSON, token_payload.get()->c_str()); +} + +TEST_F(TrialTokenTest, ValidateInvalidSignature) { + std::unique_ptr<std::string> token_payload = + Extract(kInvalidSignatureToken, correct_public_key()); + ASSERT_FALSE(token_payload); +} + +TEST_F(TrialTokenTest, ValidateSignatureWithIncorrectKey) { + std::unique_ptr<std::string> token_payload = + Extract(kSampleToken, incorrect_public_key()); + ASSERT_FALSE(token_payload); +} + +TEST_F(TrialTokenTest, ValidateEmptyToken) { + std::unique_ptr<std::string> token_payload = + Extract("", correct_public_key()); + ASSERT_FALSE(token_payload); +} + +TEST_F(TrialTokenTest, ValidateShortToken) { + std::unique_ptr<std::string> token_payload = + Extract(kTruncatedToken, correct_public_key()); + ASSERT_FALSE(token_payload); +} + +TEST_F(TrialTokenTest, ValidateUnsupportedVersion) { + std::unique_ptr<std::string> token_payload = + Extract(kIncorrectVersionToken, correct_public_key()); + ASSERT_FALSE(token_payload); +} + +TEST_F(TrialTokenTest, ValidateSignatureWithIncorrectLength) { + std::unique_ptr<std::string> token_payload = + Extract(kIncorrectLengthToken, correct_public_key()); + ASSERT_FALSE(token_payload); +} + +// Test parsing of fields from JSON token. + TEST_F(TrialTokenTest, ParseEmptyString) { - std::unique_ptr<TrialToken> empty_token = TrialToken::Parse(""); + std::unique_ptr<TrialToken> empty_token = Parse(""); EXPECT_FALSE(empty_token); } -TEST_F(TrialTokenTest, ParseInvalidStrings) { - for (size_t i = 0; i < kNumInvalidTokens; ++i) { - std::unique_ptr<TrialToken> empty_token = - TrialToken::Parse(kInvalidTokens[i]); - EXPECT_FALSE(empty_token) << "Invalid trial token should not parse: " - << kInvalidTokens[i]; - } +TEST_P(TrialTokenTest, ParseInvalidString) { + std::unique_ptr<TrialToken> empty_token = Parse(GetParam()); + EXPECT_FALSE(empty_token) << "Invalid trial token should not parse."; } +INSTANTIATE_TEST_CASE_P(, TrialTokenTest, ::testing::ValuesIn(kInvalidTokens)); + TEST_F(TrialTokenTest, ParseValidToken) { - std::unique_ptr<TrialToken> token = TrialToken::Parse(kSampleToken); + std::unique_ptr<TrialToken> token = Parse(kSampleTokenJSON); ASSERT_TRUE(token); - EXPECT_EQ(kExpectedVersion, token->version()); EXPECT_EQ(kExpectedFeatureName, token->feature_name()); - EXPECT_EQ(kExpectedSignature, token->signature()); - EXPECT_EQ(kExpectedData, token->data()); EXPECT_EQ(expected_origin_, token->origin()); - EXPECT_EQ(base::Time::FromDoubleT(kExpectedExpiry), token->expiry_time()); + EXPECT_EQ(expected_expiry_, token->expiry_time()); } TEST_F(TrialTokenTest, ValidateValidToken) { - std::unique_ptr<TrialToken> token = TrialToken::Parse(kSampleToken); + std::unique_ptr<TrialToken> token = Parse(kSampleTokenJSON); ASSERT_TRUE(token); EXPECT_TRUE(ValidateOrigin(token.get(), expected_origin_)); EXPECT_FALSE(ValidateOrigin(token.get(), invalid_origin_)); @@ -192,54 +272,29 @@ token.get(), base::ToUpperASCII(kExpectedFeatureName).c_str())); EXPECT_FALSE(ValidateFeatureName( token.get(), base::ToLowerASCII(kExpectedFeatureName).c_str())); - EXPECT_TRUE( - ValidateDate(token.get(), base::Time::FromDoubleT(kValidTimestamp))); - EXPECT_FALSE( - ValidateDate(token.get(), base::Time::FromDoubleT(kInvalidTimestamp))); + EXPECT_TRUE(ValidateDate(token.get(), valid_timestamp_)); + EXPECT_FALSE(ValidateDate(token.get(), invalid_timestamp_)); } -TEST_F(TrialTokenTest, TokenIsAppropriateForOriginAndFeature) { - std::unique_ptr<TrialToken> token = TrialToken::Parse(kSampleToken); +TEST_F(TrialTokenTest, TokenIsValidForFeature) { + std::unique_ptr<TrialToken> token = Parse(kSampleTokenJSON); ASSERT_TRUE(token); - EXPECT_TRUE(token->IsAppropriate(expected_origin_, kExpectedFeatureName)); - EXPECT_FALSE(token->IsAppropriate(expected_origin_, - base::ToUpperASCII(kExpectedFeatureName))); - EXPECT_FALSE(token->IsAppropriate(expected_origin_, - base::ToLowerASCII(kExpectedFeatureName))); - EXPECT_FALSE(token->IsAppropriate(invalid_origin_, kExpectedFeatureName)); - EXPECT_FALSE(token->IsAppropriate(insecure_origin_, kExpectedFeatureName)); - EXPECT_FALSE(token->IsAppropriate(expected_origin_, kInvalidFeatureName)); -} - -TEST_F(TrialTokenTest, ValidateValidSignature) { - std::unique_ptr<TrialToken> token = TrialToken::Parse(kSampleToken); - ASSERT_TRUE(token); - EXPECT_TRUE(ValidateSignature(token.get(), correct_public_key())); -} - -TEST_F(TrialTokenTest, ValidateInvalidSignature) { - std::unique_ptr<TrialToken> token = TrialToken::Parse(kInvalidSignatureToken); - ASSERT_TRUE(token); - EXPECT_FALSE(ValidateSignature(token.get(), correct_public_key())); -} - -TEST_F(TrialTokenTest, ValidateTokenWithCorrectKey) { - std::unique_ptr<TrialToken> token = TrialToken::Parse(kSampleToken); - ASSERT_TRUE(token); - EXPECT_TRUE(token->IsValid(base::Time::FromDoubleT(kValidTimestamp), - correct_public_key())); -} - -TEST_F(TrialTokenTest, ValidateSignatureWithIncorrectKey) { - std::unique_ptr<TrialToken> token = TrialToken::Parse(kSampleToken); - ASSERT_TRUE(token); - EXPECT_FALSE(token->IsValid(base::Time::FromDoubleT(kValidTimestamp), - incorrect_public_key())); -} - -TEST_F(TrialTokenTest, ValidateWhenNotExpired) { - std::unique_ptr<TrialToken> token = TrialToken::Parse(kSampleToken); - ASSERT_TRUE(token); + EXPECT_TRUE(token->IsValidForFeature(expected_origin_, kExpectedFeatureName, + valid_timestamp_)); + EXPECT_FALSE(token->IsValidForFeature( + expected_origin_, base::ToUpperASCII(kExpectedFeatureName), + valid_timestamp_)); + EXPECT_FALSE(token->IsValidForFeature( + expected_origin_, base::ToLowerASCII(kExpectedFeatureName), + valid_timestamp_)); + EXPECT_FALSE(token->IsValidForFeature(invalid_origin_, kExpectedFeatureName, + valid_timestamp_)); + EXPECT_FALSE(token->IsValidForFeature(insecure_origin_, kExpectedFeatureName, + valid_timestamp_)); + EXPECT_FALSE(token->IsValidForFeature(expected_origin_, kInvalidFeatureName, + valid_timestamp_)); + EXPECT_FALSE(token->IsValidForFeature(expected_origin_, kExpectedFeatureName, + invalid_timestamp_)); } } // namespace content
diff --git a/content/common/origin_trials/trial_token_validator.cc b/content/common/origin_trials/trial_token_validator.cc index 2dd4d8aa..6eef75a5 100644 --- a/content/common/origin_trials/trial_token_validator.cc +++ b/content/common/origin_trials/trial_token_validator.cc
@@ -12,17 +12,19 @@ bool TrialTokenValidator::ValidateToken(const std::string& token, const url::Origin& origin, - base::StringPiece featureName) { - std::unique_ptr<TrialToken> trial_token = TrialToken::Parse(token); - + base::StringPiece feature_name) { // TODO(iclelland): Allow for multiple signing keys, and iterate over all // active keys here. https://crbug.com/543220 ContentClient* content_client = GetContentClient(); base::StringPiece public_key = content_client->GetOriginTrialPublicKey(); + if (public_key.empty()) { + return false; + } + std::unique_ptr<TrialToken> trial_token = TrialToken::From(token, public_key); - return !public_key.empty() && trial_token && - trial_token->IsAppropriate(origin, featureName) && - trial_token->IsValid(base::Time::Now(), public_key); + return trial_token && + trial_token->IsValidForFeature(origin, feature_name, + base::Time::Now()); } } // namespace content
diff --git a/content/common/origin_trials/trial_token_validator.h b/content/common/origin_trials/trial_token_validator.h index d19c112..a840635 100644 --- a/content/common/origin_trials/trial_token_validator.h +++ b/content/common/origin_trials/trial_token_validator.h
@@ -17,7 +17,7 @@ // This method is thread-safe. CONTENT_EXPORT bool ValidateToken(const std::string& token, const url::Origin& origin, - base::StringPiece featureName); + base::StringPiece feature_name); } // namespace TrialTokenValidator
diff --git a/content/common/origin_trials/trial_token_validator_unittest.cc b/content/common/origin_trials/trial_token_validator_unittest.cc index e54a8d5..59011e78 100644 --- a/content/common/origin_trials/trial_token_validator_unittest.cc +++ b/content/common/origin_trials/trial_token_validator_unittest.cc
@@ -48,9 +48,13 @@ // This is a good trial token, signed with the above test private key. // TODO(iclelland): This token expires in 2033. Update it or find a way // to autogenerate it before then. +// Generate this token with the command (in tools/origin_trials): +// generate_token.py valid.example.com Frobulate --expire-timestamp=2000000000 const char kSampleToken[] = - "1|w694328Rl8l2vd96nkbAumpwvOOnvhWTj9/pfBRkvcWMDAsmiMEhZGEPzdBRy5Yao6il5qC" - "OyS6Ah7uuHf7JAQ==|https://valid.example.com|Frobulate|2000000000"; + "AuR/1mg+/w5ROLN54Ok20rApK3opgR7Tq9ZfzhATQmnCa+BtPA1RRw4Nigf336r+" + "O4fM3Sa+MEd+5JcIgSZafw8AAABZeyJvcmlnaW4iOiAiaHR0cHM6Ly92YWxpZC5l" + "eGFtcGxlLmNvbTo0NDMiLCAiZmVhdHVyZSI6ICJGcm9idWxhdGUiLCAiZXhwaXJ5" + "IjogMjAwMDAwMDAwMH0="; // The token should be valid for this origin and for this feature. const char kAppropriateOrigin[] = "https://valid.example.com"; @@ -61,14 +65,21 @@ const char kInsecureOrigin[] = "http://valid.example.com"; // Well-formed trial token with an invalid signature. +// This token is a corruption of the above valid token. const char kInvalidSignatureToken[] = - "1|CO8hDne98QeFeOJ0DbRZCBN3uE0nyaPgaLlkYhSWnbRoDfEAg+TXELaYfQPfEvKYFauBg/h" - "nxmba765hz0mXMc==|https://valid.example.com|Frobulate|2000000000"; + "AuR/1mg+/w5ROLN54Ok20rApK3opgR7Tq9ZfzhATQmnCa+BtPA1RRw4Nigf336r+" + "RrOtlAwa0gPqqn+A8GTD3AQAAABZeyJvcmlnaW4iOiAiaHR0cHM6Ly92YWxpZC5l" + "eGFtcGxlLmNvbTo0NDMiLCAiZmVhdHVyZSI6ICJGcm9idWxhdGUiLCAiZXhwaXJ5" + "IjogMjAwMDAwMDAwMH0="; // Well-formed, but expired, trial token. (Expired in 2001) +// Generate this token with the command (in tools/origin_trials): +// generate_token.py valid.example.com Frobulate --expire-timestamp=1000000000 const char kExpiredToken[] = - "1|Vtzq/H0qMxsMXPThIgGEvI13d3Fd8K3W11/0E+FrJJXqBpx6n/dFkeFkEUsPaP3KeT8PCPF" - "1zpZ7kVgWYRLpAA==|https://valid.example.com|Frobulate|1000000000"; + "AmHPUIXMaXe9jWW8kJeDFXolVjT93p4XMnK4+jMYd2pjqtFcYB1bUmdD8PunQKM+" + "RrOtlAwa0gPqqn+A8GTD3AQAAABZeyJvcmlnaW4iOiAiaHR0cHM6Ly92YWxpZC5l" + "eGFtcGxlLmNvbTo0NDMiLCAiZmVhdHVyZSI6ICJGcm9idWxhdGUiLCAiZXhwaXJ5" + "IjogMTAwMDAwMDAwMH0="; const char kUnparsableToken[] = "abcde";
diff --git a/content/content_browser.gypi b/content/content_browser.gypi index 2605347..cc0a776a 100644 --- a/content/content_browser.gypi +++ b/content/content_browser.gypi
@@ -1519,8 +1519,6 @@ 'browser/speech/endpointer/energy_endpointer.h', 'browser/speech/endpointer/energy_endpointer_params.cc', 'browser/speech/endpointer/energy_endpointer_params.h', - 'browser/speech/google_one_shot_remote_engine.cc', - 'browser/speech/google_one_shot_remote_engine.h', 'browser/speech/google_streaming_remote_engine.cc', 'browser/speech/google_streaming_remote_engine.h', 'browser/speech/speech_recognition_dispatcher_host.cc',
diff --git a/content/content_tests.gypi b/content/content_tests.gypi index 4399cbb1..fa0038e 100644 --- a/content/content_tests.gypi +++ b/content/content_tests.gypi
@@ -741,7 +741,6 @@ 'content_unittests_speech_sources': [ 'browser/speech/chunked_byte_buffer_unittest.cc', 'browser/speech/endpointer/endpointer_unittest.cc', - 'browser/speech/google_one_shot_remote_engine_unittest.cc', 'browser/speech/google_streaming_remote_engine_unittest.cc', 'browser/speech/speech_recognizer_impl_unittest.cc', ],
diff --git a/content/public/browser/speech_recognition_session_config.cc b/content/public/browser/speech_recognition_session_config.cc index 74392a1..289df82 100644 --- a/content/public/browser/speech_recognition_session_config.cc +++ b/content/public/browser/speech_recognition_session_config.cc
@@ -11,8 +11,7 @@ namespace content { SpeechRecognitionSessionConfig::SpeechRecognitionSessionConfig() - : is_legacy_api(true), - filter_profanities(false), + : filter_profanities(false), continuous(false), interim_results(false), max_hypotheses(kDefaultMaxHypotheses) {
diff --git a/content/public/browser/speech_recognition_session_config.h b/content/public/browser/speech_recognition_session_config.h index da2b011..d3bea186 100644 --- a/content/public/browser/speech_recognition_session_config.h +++ b/content/public/browser/speech_recognition_session_config.h
@@ -27,9 +27,6 @@ SpeechRecognitionSessionConfig(const SpeechRecognitionSessionConfig& other); ~SpeechRecognitionSessionConfig(); - // TODO(hans): The legacy API is dead; remove this flag (crbug.com/223198). - bool is_legacy_api; - std::string language; SpeechRecognitionGrammarArray grammars; std::string origin_url;
diff --git a/content/public/test/browser_test_utils.h b/content/public/test/browser_test_utils.h index 494d30e..9229059e 100644 --- a/content/public/test/browser_test_utils.h +++ b/content/public/test/browser_test_utils.h
@@ -79,17 +79,15 @@ bool IsLastCommittedEntryOfPageType(WebContents* web_contents, content::PageType page_type); -// Waits for a load stop for the specified |web_contents|'s controller, if the -// tab is currently web_contents. Otherwise returns immediately. Tests should -// use WaitForLoadStop instead and check that last navigation succeeds, and -// this function should only be used if the navigation leads to web_contents -// being destroyed. +// Waits for |web_contents| to stop loading. If |web_contents| is not loading +// returns immediately. Tests should use WaitForLoadStop instead and check that +// last navigation succeeds, and this function should only be used if the +// navigation leads to web_contents being destroyed. void WaitForLoadStopWithoutSuccessCheck(WebContents* web_contents); -// Waits for a load stop for the specified |web_contents|'s controller, if the -// tab is currently web_contents. Otherwise returns immediately. Returns true -// if the last navigation succeeded (resulted in a committed navigation entry -// of type PAGE_TYPE_NORMAL). +// Waits for |web_contents| to stop loading. If |web_contents| is not loading +// returns immediately. Returns true if the last navigation succeeded (resulted +// in a committed navigation entry of type PAGE_TYPE_NORMAL). // TODO(alexmos): tests that use this function to wait for successful // navigations should be refactored to do EXPECT_TRUE(WaitForLoadStop()). bool WaitForLoadStop(WebContents* web_contents);
diff --git a/content/renderer/render_process_impl.cc b/content/renderer/render_process_impl.cc index c9d0d53..6463fb9 100644 --- a/content/renderer/render_process_impl.cc +++ b/content/renderer/render_process_impl.cc
@@ -28,6 +28,9 @@ "V8_ES2015_TailCalls", base::FEATURE_DISABLED_BY_DEFAULT }; +const base::Feature kV8_ES2016_ExplicitTailCalls_Feature{ + "V8_ES2016_ExplicitTailCalls", base::FEATURE_DISABLED_BY_DEFAULT}; + const base::Feature kV8SerializeEagerFeature{"V8_Serialize_Eager", base::FEATURE_DISABLED_BY_DEFAULT}; @@ -76,6 +79,8 @@ } SetV8FlagIfFeature(kV8_ES2015_TailCalls_Feature, "--harmony-tailcalls"); + SetV8FlagIfFeature(kV8_ES2016_ExplicitTailCalls_Feature, + "--harmony-explicit-tailcalls"); SetV8FlagIfFeature(kV8SerializeEagerFeature, "--serialize_eager"); SetV8FlagIfFeature(kV8SerializeAgeCodeFeature, "--serialize_age_code"); SetV8FlagIfHasSwitch(switches::kDisableJavaScriptHarmonyShipping,
diff --git a/content/shell/renderer/layout_test/blink_test_runner.cc b/content/shell/renderer/layout_test/blink_test_runner.cc index 1ce0bf9..c48fe32a 100644 --- a/content/shell/renderer/layout_test/blink_test_runner.cc +++ b/content/shell/renderer/layout_test/blink_test_runner.cc
@@ -208,7 +208,6 @@ : RenderViewObserver(render_view), RenderViewObserverTracker<BlinkTestRunner>(render_view), proxy_(NULL), - focused_view_(NULL), is_main_window_(false), focus_on_next_commit_(false), leak_detector_(new LeakDetector(this)) { @@ -491,28 +490,8 @@ void BlinkTestRunner::SetFocus(blink::WebView* web_view, bool focus) { RenderView* render_view = RenderView::FromWebView(web_view); - if (!render_view) { - NOTREACHED(); - return; - } - - // Check whether the focused view was closed meanwhile. - if (!BlinkTestRunner::Get(focused_view_)) - focused_view_ = NULL; - - if (focus) { - if (focused_view_ != render_view) { - if (focused_view_) - SetFocusAndActivate(focused_view_, false); - SetFocusAndActivate(render_view, true); - focused_view_ = render_view; - } - } else { - if (focused_view_ == render_view) { - SetFocusAndActivate(render_view, false); - focused_view_ = NULL; - } - } + if (render_view) // Check whether |web_view| has been already closed. + SetFocusAndActivate(render_view, focus); } void BlinkTestRunner::SetAcceptAllCookies(bool accept) { @@ -941,7 +920,10 @@ ForceResizeRenderView( render_view(), WebSize(params.initial_size.width(), params.initial_size.height())); - SetFocus(proxy_->web_view(), true); + LayoutTestRenderProcessObserver::GetInstance() + ->test_interfaces() + ->TestRunner() + ->SetFocus(render_view()->GetWebView(), true); } void BlinkTestRunner::OnSessionHistory(
diff --git a/content/shell/renderer/layout_test/blink_test_runner.h b/content/shell/renderer/layout_test/blink_test_runner.h index 20b5e36..7729f591 100644 --- a/content/shell/renderer/layout_test/blink_test_runner.h +++ b/content/shell/renderer/layout_test/blink_test_runner.h
@@ -199,8 +199,6 @@ test_runner::WebTestProxyBase* proxy_; - RenderView* focused_view_; - test_runner::TestPreferences prefs_; ShellTestConfiguration test_config_;
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 e3aa0d0..526d2d9 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
@@ -53,6 +53,8 @@ test_runner::WebTestProxyBase* proxy) { BlinkTestRunner* test_runner = new BlinkTestRunner(render_view); test_runner->set_proxy(proxy); + proxy->set_delegate(test_runner); + if (!LayoutTestRenderProcessObserver::GetInstance()->test_delegate()) { LayoutTestRenderProcessObserver::GetInstance()->SetTestDelegate( test_runner); @@ -62,8 +64,6 @@ ->CreateWebViewTestClient(proxy)); proxy->SetInterfaces( LayoutTestRenderProcessObserver::GetInstance()->test_interfaces()); - test_runner->proxy()->SetDelegate( - LayoutTestRenderProcessObserver::GetInstance()->test_delegate()); } void WebFrameTestProxyCreated(RenderFrame* render_frame,
diff --git a/device/usb/BUILD.gn b/device/usb/BUILD.gn index 0d3795bf..db154526 100644 --- a/device/usb/BUILD.gn +++ b/device/usb/BUILD.gn
@@ -59,6 +59,10 @@ if (is_android) { deps += [ ":jni_headers" ] + sources += [ + "usb_device_handle_usbfs.cc", + "usb_device_handle_usbfs.h", + ] } else { sources += [ "usb_context.cc", @@ -76,6 +80,17 @@ deps += [ "//third_party/libusb" ] } + if (is_linux || is_chromeos) { + sources += [ + "usb_device_handle_usbfs.cc", + "usb_device_handle_usbfs.h", + ] + sources -= [ + "usb_device_handle_impl.cc", + "usb_device_handle_impl.h", + ] + } + if (is_chromeos) { deps += [ "//chromeos",
diff --git a/device/usb/usb.gyp b/device/usb/usb.gyp index ef2cf89..bdac4ff9 100644 --- a/device/usb/usb.gyp +++ b/device/usb/usb.gyp
@@ -103,6 +103,10 @@ 'dependencies!': [ '../../third_party/libusb/libusb.gyp:libusb', ], + 'sources': [ + 'usb_device_handle_usbfs.cc', + 'usb_device_handle_usbfs.h', + ], # These sources are libusb-specific. 'sources!': [ 'usb_context.cc', @@ -122,6 +126,16 @@ '../../chromeos/chromeos.gyp:chromeos', ], }], + ['OS=="linux"', { + 'sources': [ + 'usb_device_handle_usbfs.cc', + 'usb_device_handle_usbfs.h', + ], + 'sources!': [ + 'usb_device_handle_impl.cc', + 'usb_device_handle_impl.h', + ] + }] ] }, {
diff --git a/device/usb/usb_device_handle.h b/device/usb/usb_device_handle.h index 7222964..32d25f3 100644 --- a/device/usb/usb_device_handle.h +++ b/device/usb/usb_device_handle.h
@@ -120,7 +120,6 @@ friend class base::RefCountedThreadSafe<UsbDeviceHandle>; UsbDeviceHandle(); - virtual ~UsbDeviceHandle(); private:
diff --git a/device/usb/usb_device_handle_unittest.cc b/device/usb/usb_device_handle_unittest.cc index 410f5ad..f98b2e4 100644 --- a/device/usb/usb_device_handle_unittest.cc +++ b/device/usb/usb_device_handle_unittest.cc
@@ -253,6 +253,36 @@ handle->Close(); } +TEST_F(UsbDeviceHandleTest, ControlTransfer) { + if (!UsbTestGadget::IsTestEnabled()) + return; + + scoped_ptr<UsbTestGadget> gadget = + UsbTestGadget::Claim(io_thread_->task_runner()); + ASSERT_TRUE(gadget.get()); + + TestOpenCallback open_device; + gadget->GetDevice()->Open(open_device.callback()); + scoped_refptr<UsbDeviceHandle> handle = open_device.WaitForResult(); + ASSERT_TRUE(handle.get()); + + scoped_refptr<net::IOBufferWithSize> buffer(new net::IOBufferWithSize(255)); + TestCompletionCallback completion; + handle->ControlTransfer(USB_DIRECTION_INBOUND, UsbDeviceHandle::STANDARD, + UsbDeviceHandle::DEVICE, 0x06, 0x0301, 0x0409, buffer, + buffer->size(), 0, completion.callback()); + completion.WaitForResult(); + ASSERT_EQ(USB_TRANSFER_COMPLETED, completion.status()); + const char expected_str[] = "\x18\x03G\0o\0o\0g\0l\0e\0 \0I\0n\0c\0.\0"; + EXPECT_EQ(sizeof(expected_str) - 1, completion.transferred()); + for (size_t i = 0; i < completion.transferred(); ++i) { + EXPECT_EQ(expected_str[i], buffer->data()[i]) << "Mismatch at index " << i + << "."; + } + + handle->Close(); +} + TEST_F(UsbDeviceHandleTest, SetInterfaceAlternateSetting) { if (!UsbTestGadget::IsTestEnabled()) { return;
diff --git a/device/usb/usb_device_handle_usbfs.cc b/device/usb/usb_device_handle_usbfs.cc new file mode 100644 index 0000000..693b21e --- /dev/null +++ b/device/usb/usb_device_handle_usbfs.cc
@@ -0,0 +1,800 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "device/usb/usb_device_handle_usbfs.h" + +#if defined(OS_ANDROID) && __ANDROID_API__ < 21 +#include <linux/usb_ch9.h> +#else +#include <linux/usb/ch9.h> +#endif + +#include <linux/usbdevice_fs.h> +#include <sys/ioctl.h> + +#include <numeric> + +#include "base/bind.h" +#include "base/cancelable_callback.h" +#include "base/logging.h" +#include "base/message_loop/message_loop.h" +#include "base/message_loop/message_pump_libevent.h" +#include "base/posix/eintr_wrapper.h" +#include "base/stl_util.h" +#include "base/thread_task_runner_handle.h" +#include "base/threading/thread_restrictions.h" +#include "components/device_event_log/device_event_log.h" +#include "device/usb/usb_device_impl.h" +#include "net/base/io_buffer.h" + +namespace device { + +namespace { + +uint8_t ConvertEndpointDirection(UsbEndpointDirection direction) { + switch (direction) { + case USB_DIRECTION_INBOUND: + return USB_DIR_IN; + case USB_DIRECTION_OUTBOUND: + return USB_DIR_OUT; + } + NOTREACHED(); + return 0; +} + +uint8_t ConvertRequestType(UsbDeviceHandle::TransferRequestType request_type) { + switch (request_type) { + case UsbDeviceHandle::STANDARD: + return USB_TYPE_STANDARD; + case UsbDeviceHandle::CLASS: + return USB_TYPE_CLASS; + case UsbDeviceHandle::VENDOR: + return USB_TYPE_VENDOR; + case UsbDeviceHandle::RESERVED: + return USB_TYPE_RESERVED; + } + NOTREACHED(); + return 0; +} + +uint8_t ConvertRecipient(UsbDeviceHandle::TransferRecipient recipient) { + switch (recipient) { + case UsbDeviceHandle::DEVICE: + return USB_RECIP_DEVICE; + case UsbDeviceHandle::INTERFACE: + return USB_RECIP_INTERFACE; + case UsbDeviceHandle::ENDPOINT: + return USB_RECIP_ENDPOINT; + case UsbDeviceHandle::OTHER: + return USB_RECIP_OTHER; + } + NOTREACHED(); + return 0; +} + +scoped_refptr<net::IOBuffer> BuildControlTransferBuffer( + UsbEndpointDirection direction, + UsbDeviceHandle::TransferRequestType request_type, + UsbDeviceHandle::TransferRecipient recipient, + uint8_t request, + uint16_t value, + uint16_t index, + scoped_refptr<net::IOBuffer> original_buffer, + size_t length) { + scoped_refptr<net::IOBuffer> new_buffer( + new net::IOBuffer(length + sizeof(usb_ctrlrequest))); + usb_ctrlrequest* setup = + reinterpret_cast<usb_ctrlrequest*>(new_buffer->data()); + setup->bRequestType = ConvertEndpointDirection(direction) | + ConvertRequestType(request_type) | + ConvertRecipient(recipient); + setup->bRequest = request; + setup->wValue = value; + setup->wIndex = index; + setup->wLength = length; + memcpy(new_buffer->data() + sizeof(usb_ctrlrequest), original_buffer->data(), + length); + return new_buffer; +} + +uint8_t ConvertTransferType(UsbTransferType type) { + switch (type) { + case USB_TRANSFER_CONTROL: + return USBDEVFS_URB_TYPE_CONTROL; + case USB_TRANSFER_ISOCHRONOUS: + return USBDEVFS_URB_TYPE_ISO; + case USB_TRANSFER_BULK: + return USBDEVFS_URB_TYPE_BULK; + case USB_TRANSFER_INTERRUPT: + return USBDEVFS_URB_TYPE_INTERRUPT; + } + NOTREACHED(); + return 0; +} + +UsbTransferStatus ConvertTransferResult(int rc) { + switch (rc) { + case 0: + return USB_TRANSFER_COMPLETED; + case EPIPE: + return USB_TRANSFER_STALLED; + case ENODEV: + case ESHUTDOWN: + return USB_TRANSFER_DISCONNECT; + default: + // TODO(reillyg): Add a specific error message whenever one of the cases + // above fails to match. + USB_LOG(ERROR) << "Unknown system error: " + << logging::SystemErrorCodeToString(rc); + return USB_TRANSFER_ERROR; + } +} + +} // namespace + +class UsbDeviceHandleUsbfs::FileThreadHelper + : public base::MessagePumpLibevent::Watcher, + public base::MessageLoop::DestructionObserver { + public: + FileThreadHelper(int fd, + scoped_refptr<UsbDeviceHandleUsbfs> device_handle, + scoped_refptr<base::SequencedTaskRunner> task_runner); + ~FileThreadHelper() override; + + static void Start(scoped_ptr<FileThreadHelper> self); + + // base::MessagePumpLibevent::Watcher overrides. + void OnFileCanReadWithoutBlocking(int fd) override; + void OnFileCanWriteWithoutBlocking(int fd) override; + + // base::MessageLoop::DestructionObserver overrides. + void WillDestroyCurrentMessageLoop() override; + + private: + int fd_; + scoped_refptr<UsbDeviceHandleUsbfs> device_handle_; + scoped_refptr<base::SequencedTaskRunner> task_runner_; + base::MessagePumpLibevent::FileDescriptorWatcher file_watcher_; + base::ThreadChecker thread_checker_; + + DISALLOW_COPY_AND_ASSIGN(FileThreadHelper); +}; + +UsbDeviceHandleUsbfs::FileThreadHelper::FileThreadHelper( + int fd, + scoped_refptr<UsbDeviceHandleUsbfs> device_handle, + scoped_refptr<base::SequencedTaskRunner> task_runner) + : fd_(fd), device_handle_(device_handle), task_runner_(task_runner) {} + +UsbDeviceHandleUsbfs::FileThreadHelper::~FileThreadHelper() { + DCHECK(thread_checker_.CalledOnValidThread()); + base::MessageLoop::current()->RemoveDestructionObserver(this); +} + +// static +void UsbDeviceHandleUsbfs::FileThreadHelper::Start( + scoped_ptr<FileThreadHelper> self) { + base::ThreadRestrictions::AssertIOAllowed(); + self->thread_checker_.DetachFromThread(); + + // Linux indicates that URBs are available to reap by marking the file + // descriptor writable. + if (!base::MessageLoopForIO::current()->WatchFileDescriptor( + self->fd_, true, base::MessageLoopForIO::WATCH_WRITE, + &self->file_watcher_, self.get())) { + USB_LOG(ERROR) << "Failed to start watching device file descriptor."; + } + + // |self| is now owned by the current message loop. + base::MessageLoop::current()->AddDestructionObserver(self.release()); +} + +void UsbDeviceHandleUsbfs::FileThreadHelper::OnFileCanReadWithoutBlocking( + int fd) { + NOTREACHED(); // Only listening for writability. +} + +void UsbDeviceHandleUsbfs::FileThreadHelper::OnFileCanWriteWithoutBlocking( + int fd) { + DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_EQ(fd_, fd); + + const size_t MAX_URBS_PER_EVENT = 10; + std::vector<usbdevfs_urb*> urbs; + urbs.reserve(MAX_URBS_PER_EVENT); + for (size_t i = 0; i < MAX_URBS_PER_EVENT; ++i) { + usbdevfs_urb* urb; + int rc = HANDLE_EINTR(ioctl(fd_, USBDEVFS_REAPURBNDELAY, &urb)); + if (rc) { + if (errno == EAGAIN) + break; + USB_PLOG(DEBUG) << "Failed to reap urbs"; + } else { + urbs.push_back(urb); + } + } + + task_runner_->PostTask( + FROM_HERE, + base::Bind(&UsbDeviceHandleUsbfs::ReapedUrbs, device_handle_, urbs)); +} + +void UsbDeviceHandleUsbfs::FileThreadHelper::WillDestroyCurrentMessageLoop() { + DCHECK(thread_checker_.CalledOnValidThread()); + delete this; +} + +struct UsbDeviceHandleUsbfs::Transfer { + Transfer() = delete; + Transfer(scoped_refptr<net::IOBuffer> buffer, + const TransferCallback& callback); + Transfer(scoped_refptr<net::IOBuffer> buffer, + const IsochronousTransferCallback& callback); + ~Transfer(); + + void* operator new(std::size_t size, size_t number_of_iso_packets); + + scoped_refptr<net::IOBuffer> control_transfer_buffer; + scoped_refptr<net::IOBuffer> buffer; + TransferCallback callback; + IsochronousTransferCallback isoc_callback; + base::CancelableClosure timeout_closure; + bool timed_out = false; + + // The |urb| field must be the last in the struct so that the extra space + // allocated by the overridden new function above extends the length of its + // |iso_frame_desc| field. + usbdevfs_urb urb; + + private: + DISALLOW_COPY_AND_ASSIGN(Transfer); +}; + +UsbDeviceHandleUsbfs::Transfer::Transfer(scoped_refptr<net::IOBuffer> buffer, + const TransferCallback& callback) + : buffer(buffer), callback(callback) { + memset(&urb, 0, sizeof(urb)); + urb.usercontext = this; + urb.buffer = buffer->data(); +} + +UsbDeviceHandleUsbfs::Transfer::Transfer( + scoped_refptr<net::IOBuffer> buffer, + const IsochronousTransferCallback& callback) + : buffer(buffer), isoc_callback(callback) { + memset(&urb, 0, sizeof(urb) + + sizeof(usbdevfs_iso_packet_desc) * urb.number_of_packets); + urb.usercontext = this; + urb.buffer = buffer->data(); +} + +UsbDeviceHandleUsbfs::Transfer::~Transfer() = default; + +void* UsbDeviceHandleUsbfs::Transfer::operator new( + std::size_t size, + size_t number_of_iso_packets) { + void* p = ::operator new( + size + sizeof(usbdevfs_iso_packet_desc) * number_of_iso_packets); + Transfer* transfer = static_cast<Transfer*>(p); + transfer->urb.number_of_packets = number_of_iso_packets; + return p; +} + +UsbDeviceHandleUsbfs::UsbDeviceHandleUsbfs( + scoped_refptr<UsbDevice> device, + base::ScopedFD fd, + scoped_refptr<base::SequencedTaskRunner> blocking_task_runner) + : device_(device), + fd_(std::move(fd)), + blocking_task_runner_(blocking_task_runner) { + DCHECK(device_); + DCHECK(fd_.is_valid()); + DCHECK(blocking_task_runner_); + + task_runner_ = base::ThreadTaskRunnerHandle::Get(); + + scoped_ptr<FileThreadHelper> helper( + new FileThreadHelper(fd_.get(), this, task_runner_)); + helper_ = helper.get(); + blocking_task_runner_->PostTask( + FROM_HERE, base::Bind(&FileThreadHelper::Start, base::Passed(&helper))); +} + +scoped_refptr<UsbDevice> UsbDeviceHandleUsbfs::GetDevice() const { + return device_; +} + +void UsbDeviceHandleUsbfs::Close() { + // On the |task_runner_| thread check |device_| to see if the handle is + // closed. On the |blocking_task_runner_| thread check |fd_.is_valid()| to + // see if the handle is closed. + DCHECK(device_); +#if !defined(OS_ANDROID) + static_cast<UsbDeviceImpl*>(device_.get())->HandleClosed(this); +#endif + device_ = nullptr; + blocking_task_runner_->PostTask( + FROM_HERE, base::Bind(&UsbDeviceHandleUsbfs::CloseBlocking, this)); +} + +void UsbDeviceHandleUsbfs::SetConfiguration(int configuration_value, + const ResultCallback& callback) { + // USBDEVFS_SETCONFIGURATION synchronously issues a SET_CONFIGURATION request + // to the device so it must be performed on a thread where it is okay to + // block. + blocking_task_runner_->PostTask( + FROM_HERE, base::Bind(&UsbDeviceHandleUsbfs::SetConfigurationBlocking, + this, configuration_value, callback)); +} + +void UsbDeviceHandleUsbfs::ClaimInterface(int interface_number, + const ResultCallback& callback) { + if (!device_) { + task_runner_->PostTask(FROM_HERE, base::Bind(callback, false)); + return; + } + + if (ContainsKey(interfaces_, interface_number)) { + USB_LOG(DEBUG) << "Interface " << interface_number << " already claimed."; + task_runner_->PostTask(FROM_HERE, base::Bind(callback, false)); + return; + } + + // It appears safe to assume that this ioctl will not block. + int rc = HANDLE_EINTR( + ioctl(fd_.get(), USBDEVFS_CLAIMINTERFACE, &interface_number)); + if (rc) { + USB_PLOG(DEBUG) << "Failed to claim interface " << interface_number; + } else { + interfaces_[interface_number].alternate_setting = 0; + RefreshEndpointInfo(); + } + task_runner_->PostTask(FROM_HERE, base::Bind(callback, rc == 0)); +} + +void UsbDeviceHandleUsbfs::ReleaseInterface(int interface_number, + const ResultCallback& callback) { + // USBDEVFS_RELEASEINTERFACE may issue a SET_INTERFACE request to the + // device to restore alternate setting 0 so it must be performed on a thread + // where it is okay to block. + blocking_task_runner_->PostTask( + FROM_HERE, base::Bind(&UsbDeviceHandleUsbfs::ReleaseInterfaceBlocking, + this, interface_number, callback)); +} + +void UsbDeviceHandleUsbfs::SetInterfaceAlternateSetting( + int interface_number, + int alternate_setting, + const ResultCallback& callback) { + // USBDEVFS_SETINTERFACE is synchronous because it issues a SET_INTERFACE + // request to the device so it must be performed on a thread where it is okay + // to block. + blocking_task_runner_->PostTask( + FROM_HERE, base::Bind(&UsbDeviceHandleUsbfs::SetInterfaceBlocking, this, + interface_number, alternate_setting, callback)); +} + +void UsbDeviceHandleUsbfs::ResetDevice(const ResultCallback& callback) { + // USBDEVFS_RESET is synchronous because it waits for the port to be reset + // and the device re-enumerated so it must be performed on a thread where it + // is okay to block. + blocking_task_runner_->PostTask( + FROM_HERE, + base::Bind(&UsbDeviceHandleUsbfs::ResetDeviceBlocking, this, callback)); +} + +void UsbDeviceHandleUsbfs::ClearHalt(uint8_t endpoint_address, + const ResultCallback& callback) { + // USBDEVFS_CLEAR_HALT is synchronous because it issues a CLEAR_FEATURE + // request to the device so it must be performed on a thread where it is okay + // to block. + blocking_task_runner_->PostTask( + FROM_HERE, base::Bind(&UsbDeviceHandleUsbfs::ClearHaltBlocking, this, + endpoint_address, callback)); +} + +void UsbDeviceHandleUsbfs::ControlTransfer(UsbEndpointDirection direction, + TransferRequestType request_type, + TransferRecipient recipient, + uint8_t request, + uint16_t value, + uint16_t index, + scoped_refptr<net::IOBuffer> buffer, + size_t length, + unsigned int timeout, + const TransferCallback& callback) { + if (!device_) { + task_runner_->PostTask( + FROM_HERE, base::Bind(callback, USB_TRANSFER_DISCONNECT, nullptr, 0)); + return; + } + + scoped_ptr<Transfer> transfer(new (0) Transfer(buffer, callback)); + transfer->control_transfer_buffer = + BuildControlTransferBuffer(direction, request_type, recipient, request, + value, index, buffer, length); + transfer->urb.type = USBDEVFS_URB_TYPE_CONTROL; + transfer->urb.endpoint = 0; + transfer->urb.buffer = transfer->control_transfer_buffer->data(); + transfer->urb.buffer_length = 8 + length; + + // USBDEVFS_SUBMITURB appears to be non-blocking as completion is reported + // by USBDEVFS_REAPURBNDELAY. + int rc = HANDLE_EINTR(ioctl(fd_.get(), USBDEVFS_SUBMITURB, &transfer->urb)); + if (rc) { + rc = logging::GetLastSystemErrorCode(); + USB_PLOG(DEBUG) << "Failed to submit control transfer"; + task_runner_->PostTask( + FROM_HERE, base::Bind(callback, ConvertTransferResult(rc), nullptr, 0)); + } else { + SetUpTimeoutCallback(transfer.get(), timeout); + transfers_.push_back(std::move(transfer)); + } +} + +void UsbDeviceHandleUsbfs::IsochronousTransferIn( + uint8_t endpoint_number, + const std::vector<uint32_t>& packet_lengths, + unsigned int timeout, + const IsochronousTransferCallback& callback) { + uint8_t endpoint_address = USB_DIR_IN | endpoint_number; + size_t total_length = + std::accumulate(packet_lengths.begin(), packet_lengths.end(), 0u); + IsochronousTransferInternal(endpoint_address, new net::IOBuffer(total_length), + total_length, packet_lengths, timeout, callback); +} + +void UsbDeviceHandleUsbfs::IsochronousTransferOut( + uint8_t endpoint_number, + scoped_refptr<net::IOBuffer> buffer, + const std::vector<uint32_t>& packet_lengths, + unsigned int timeout, + const IsochronousTransferCallback& callback) { + uint8_t endpoint_address = USB_DIR_OUT | endpoint_number; + size_t total_length = + std::accumulate(packet_lengths.begin(), packet_lengths.end(), 0u); + IsochronousTransferInternal(endpoint_address, buffer, total_length, + packet_lengths, timeout, callback); +} + +void UsbDeviceHandleUsbfs::GenericTransfer(UsbEndpointDirection direction, + uint8_t endpoint_number, + scoped_refptr<net::IOBuffer> buffer, + size_t length, + unsigned int timeout, + const TransferCallback& callback) { + if (!device_) { + task_runner_->PostTask( + FROM_HERE, base::Bind(callback, USB_TRANSFER_DISCONNECT, nullptr, 0)); + return; + } + + uint8_t endpoint_address = + ConvertEndpointDirection(direction) | endpoint_number; + auto it = endpoints_.find(endpoint_address); + if (it == endpoints_.end()) { + USB_LOG(USER) << "Endpoint address " << static_cast<int>(endpoint_address) + << " is not part of a claimed interface."; + task_runner_->PostTask( + FROM_HERE, base::Bind(callback, USB_TRANSFER_ERROR, nullptr, 0)); + return; + } + + scoped_ptr<Transfer> transfer(new (0) Transfer(buffer, callback)); + transfer->urb.endpoint = endpoint_address; + transfer->urb.buffer_length = length; + transfer->urb.type = ConvertTransferType(it->second.type); + + // USBDEVFS_SUBMITURB appears to be non-blocking as completion is reported + // by USBDEVFS_REAPURBNDELAY. This code assumes a recent kernel that can + // accept arbitrarily large transfer requests, hopefully also using a scatter- + // gather list. + int rc = HANDLE_EINTR(ioctl(fd_.get(), USBDEVFS_SUBMITURB, &transfer->urb)); + if (rc) { + rc = logging::GetLastSystemErrorCode(); + USB_PLOG(DEBUG) << "Failed to submit transfer"; + task_runner_->PostTask( + FROM_HERE, base::Bind(callback, ConvertTransferResult(rc), nullptr, 0)); + } else { + SetUpTimeoutCallback(transfer.get(), timeout); + transfers_.push_back(std::move(transfer)); + } +} + +const UsbInterfaceDescriptor* UsbDeviceHandleUsbfs::FindInterfaceByEndpoint( + uint8_t endpoint_address) { + auto it = endpoints_.find(endpoint_address); + if (it != endpoints_.end()) + return it->second.interface; + return nullptr; +} + +UsbDeviceHandleUsbfs::~UsbDeviceHandleUsbfs() { + DCHECK(!device_) << "Handle must be closed before it is destroyed."; +} + +void UsbDeviceHandleUsbfs::CloseBlocking() { + fd_.reset(-1); + delete helper_; +} + +void UsbDeviceHandleUsbfs::SetConfigurationBlocking( + int configuration_value, + const ResultCallback& callback) { + if (!fd_.is_valid()) { + task_runner_->PostTask(FROM_HERE, base::Bind(callback, false)); + return; + } + + int rc = HANDLE_EINTR( + ioctl(fd_.get(), USBDEVFS_SETCONFIGURATION, &configuration_value)); + if (rc) + USB_PLOG(DEBUG) << "Failed to set configuration " << configuration_value; + task_runner_->PostTask( + FROM_HERE, base::Bind(&UsbDeviceHandleUsbfs::SetConfigurationComplete, + this, configuration_value, rc == 0, callback)); +} + +void UsbDeviceHandleUsbfs::SetConfigurationComplete( + int configuration_value, + bool success, + const ResultCallback& callback) { + if (success && device_) { +#if !defined(OS_ANDROID) + static_cast<UsbDeviceImpl*>(device_.get()) + ->ActiveConfigurationChanged(configuration_value); +#endif + // TODO(reillyg): If all interfaces are unclaimed before a new configuration + // is set then this will do nothing. Investigate. + RefreshEndpointInfo(); + } + callback.Run(success); +} + +void UsbDeviceHandleUsbfs::ReleaseInterfaceBlocking( + int interface_number, + const ResultCallback& callback) { + if (!fd_.is_valid()) { + task_runner_->PostTask(FROM_HERE, base::Bind(callback, false)); + return; + } + + int rc = HANDLE_EINTR( + ioctl(fd_.get(), USBDEVFS_RELEASEINTERFACE, &interface_number)); + if (rc) { + USB_PLOG(DEBUG) << "Failed to release interface " << interface_number; + task_runner_->PostTask(FROM_HERE, base::Bind(callback, false)); + } else { + task_runner_->PostTask( + FROM_HERE, base::Bind(&UsbDeviceHandleUsbfs::ReleaseInterfaceComplete, + this, interface_number, callback)); + } +} + +void UsbDeviceHandleUsbfs::ReleaseInterfaceComplete( + int interface_number, + const ResultCallback& callback) { + auto it = interfaces_.find(interface_number); + DCHECK(it != interfaces_.end()); + interfaces_.erase(it); + RefreshEndpointInfo(); + callback.Run(true); +} + +void UsbDeviceHandleUsbfs::SetInterfaceBlocking( + int interface_number, + int alternate_setting, + const ResultCallback& callback) { + if (!fd_.is_valid()) { + task_runner_->PostTask(FROM_HERE, base::Bind(callback, false)); + return; + } + + usbdevfs_setinterface cmd = {0}; + cmd.interface = interface_number; + cmd.altsetting = alternate_setting; + int rc = HANDLE_EINTR(ioctl(fd_.get(), USBDEVFS_SETINTERFACE, &cmd)); + if (rc) { + USB_PLOG(DEBUG) << "Failed to set interface " << interface_number + << " to alternate setting " << alternate_setting; + } + task_runner_->PostTask(FROM_HERE, base::Bind(callback, rc == 0)); +} + +void UsbDeviceHandleUsbfs::ResetDeviceBlocking(const ResultCallback& callback) { + if (!fd_.is_valid()) { + task_runner_->PostTask(FROM_HERE, base::Bind(callback, false)); + return; + } + + // TODO(reillyg): libusb releases interfaces before and then reclaims + // interfaces after a reset. We should probably do this too or document that + // callers have to call ClaimInterface as well. + int rc = HANDLE_EINTR(ioctl(fd_.get(), USBDEVFS_RESET, nullptr)); + if (rc) + USB_PLOG(DEBUG) << "Failed to reset the device"; + task_runner_->PostTask(FROM_HERE, base::Bind(callback, rc == 0)); +} + +void UsbDeviceHandleUsbfs::ClearHaltBlocking(uint8_t endpoint_address, + const ResultCallback& callback) { + if (!fd_.is_valid()) { + task_runner_->PostTask(FROM_HERE, base::Bind(callback, false)); + return; + } + + int tmp_endpoint = endpoint_address; + int rc = HANDLE_EINTR(ioctl(fd_.get(), USBDEVFS_CLEAR_HALT, &tmp_endpoint)); + if (rc) { + USB_PLOG(DEBUG) << "Failed to clear the stall condition on endpoint " + << static_cast<int>(endpoint_address); + } + task_runner_->PostTask(FROM_HERE, base::Bind(callback, rc == 0)); +} + +void UsbDeviceHandleUsbfs::IsochronousTransferInternal( + uint8_t endpoint_address, + scoped_refptr<net::IOBuffer> buffer, + size_t total_length, + const std::vector<uint32_t>& packet_lengths, + unsigned int timeout, + const IsochronousTransferCallback& callback) { + if (!device_) { + ReportIsochronousError(packet_lengths, callback, USB_TRANSFER_DISCONNECT); + return; + } + + auto it = endpoints_.find(endpoint_address); + if (it == endpoints_.end()) { + USB_LOG(USER) << "Endpoint address " << static_cast<int>(endpoint_address) + << " is not part of a claimed interface."; + ReportIsochronousError(packet_lengths, callback, USB_TRANSFER_ERROR); + return; + } + + scoped_ptr<Transfer> transfer(new (packet_lengths.size()) + Transfer(buffer, callback)); + transfer->urb.type = USBDEVFS_URB_TYPE_ISO; + transfer->urb.endpoint = endpoint_address; + transfer->urb.buffer_length = total_length; + + for (size_t i = 0; i < packet_lengths.size(); ++i) + transfer->urb.iso_frame_desc[i].length = packet_lengths[i]; + + // USBDEVFS_SUBMITURB appears to be non-blocking as completion is reported + // by USBDEVFS_REAPURBNDELAY. This code assumes a recent kernel that can + // accept arbitrarily large transfer requests, hopefully also using a scatter- + // gather list. + int rc = HANDLE_EINTR(ioctl(fd_.get(), USBDEVFS_SUBMITURB, &transfer->urb)); + if (rc) { + rc = logging::GetLastSystemErrorCode(); + USB_PLOG(DEBUG) << "Failed to submit transfer"; + ReportIsochronousError(packet_lengths, callback, ConvertTransferResult(rc)); + } else { + SetUpTimeoutCallback(transfer.get(), timeout); + transfers_.push_back(std::move(transfer)); + } +} + +void UsbDeviceHandleUsbfs::ReapedUrbs(const std::vector<usbdevfs_urb*>& urbs) { + for (const auto& urb : urbs) { + Transfer* this_transfer = static_cast<Transfer*>(urb->usercontext); + DCHECK_EQ(urb, &this_transfer->urb); + auto it = std::find_if( + transfers_.begin(), transfers_.end(), + [this_transfer](const scoped_ptr<Transfer>& transfer) -> bool { + return transfer.get() == this_transfer; + }); + DCHECK(it != transfers_.end()); + scoped_ptr<Transfer> transfer = std::move(*it); + transfers_.erase(it); + TransferComplete(std::move(transfer)); + } +} + +void UsbDeviceHandleUsbfs::TransferComplete(scoped_ptr<Transfer> transfer) { + if (transfer->timed_out) + return; + + // The transfer will soon be freed. Cancel the timeout callback so that the + // raw pointer it holds to |transfer| is not used. + transfer->timeout_closure.Cancel(); + + if (transfer->urb.type == USBDEVFS_URB_TYPE_ISO) { + std::vector<IsochronousPacket> packets(transfer->urb.number_of_packets); + for (size_t i = 0; i < packets.size(); ++i) { + packets[i].length = transfer->urb.iso_frame_desc[i].length; + packets[i].transferred_length = + transfer->urb.iso_frame_desc[i].actual_length; + packets[i].status = ConvertTransferResult( + transfer->urb.status == 0 ? transfer->urb.iso_frame_desc[i].status + : transfer->urb.status); + } + + transfer->isoc_callback.Run(transfer->buffer, packets); + } else { + if (transfer->urb.status == 0 && + transfer->urb.type == USBDEVFS_URB_TYPE_CONTROL) { + // Copy the result of the control transfer back into the original buffer. + memcpy(transfer->buffer->data(), + transfer->control_transfer_buffer->data() + 8, + transfer->urb.actual_length); + } + + transfer->callback.Run(ConvertTransferResult(-transfer->urb.status), + transfer->buffer, transfer->urb.actual_length); + } +} + +void UsbDeviceHandleUsbfs::RefreshEndpointInfo() { + endpoints_.clear(); + + const UsbConfigDescriptor* config = device_->GetActiveConfiguration(); + if (!config) + return; + + for (const auto& entry : interfaces_) { + auto interface_it = std::find_if( + config->interfaces.begin(), config->interfaces.end(), + [entry](const UsbInterfaceDescriptor& interface) { + uint8_t interface_number = entry.first; + uint8_t alternate_setting = entry.second.alternate_setting; + return interface.interface_number == interface_number && + interface.alternate_setting == alternate_setting; + }); + DCHECK(interface_it != config->interfaces.end()); + + for (const auto& endpoint : interface_it->endpoints) { + EndpointInfo& info = endpoints_[endpoint.address]; + info.type = endpoint.transfer_type; + info.interface = &*interface_it; + } + } +} + +void UsbDeviceHandleUsbfs::ReportIsochronousError( + const std::vector<uint32_t>& packet_lengths, + const UsbDeviceHandle::IsochronousTransferCallback& callback, + UsbTransferStatus status) { + std::vector<UsbDeviceHandle::IsochronousPacket> packets( + packet_lengths.size()); + for (size_t i = 0; i < packet_lengths.size(); ++i) { + packets[i].length = packet_lengths[i]; + packets[i].transferred_length = 0; + packets[i].status = status; + } + task_runner_->PostTask(FROM_HERE, base::Bind(callback, nullptr, packets)); +} + +void UsbDeviceHandleUsbfs::SetUpTimeoutCallback(Transfer* transfer, + unsigned int timeout) { + if (timeout > 0) { + transfer->timeout_closure.Reset( + base::Bind(&UsbDeviceHandleUsbfs::TransferTimedOut, transfer)); + task_runner_->PostDelayedTask(FROM_HERE, + transfer->timeout_closure.callback(), + base::TimeDelta::FromMilliseconds(timeout)); + } +} + +// static +void UsbDeviceHandleUsbfs::TransferTimedOut(Transfer* transfer) { + // |transfer| must stay in |transfers_| as it is still being processed by the + // kernel and will be reaped later. Just tell the caller that the timeout + // elapsed. + transfer->timed_out = true; + if (transfer->urb.type == USBDEVFS_URB_TYPE_ISO) { + std::vector<IsochronousPacket> packets(transfer->urb.number_of_packets); + for (size_t i = 0; i < packets.size(); ++i) { + packets[i].length = transfer->urb.iso_frame_desc[i].length; + packets[i].transferred_length = 0; + packets[i].status = USB_TRANSFER_TIMEOUT; + } + transfer->isoc_callback.Run(transfer->buffer, packets); + } else { + transfer->callback.Run(USB_TRANSFER_TIMEOUT, transfer->buffer, 0); + } +} + +} // namespace device
diff --git a/device/usb/usb_device_handle_usbfs.h b/device/usb/usb_device_handle_usbfs.h new file mode 100644 index 0000000..c3800c1 --- /dev/null +++ b/device/usb/usb_device_handle_usbfs.h
@@ -0,0 +1,151 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEVICE_USB_USB_DEVICE_HANDLE_USBFS_H_ +#define DEVICE_USB_USB_DEVICE_HANDLE_USBFS_H_ + +#include <list> +#include <map> +#include <vector> + +#include "base/files/scoped_file.h" +#include "base/memory/scoped_ptr.h" +#include "device/usb/usb_device_handle.h" + +struct usbdevfs_urb; + +namespace base { +class SequencedTaskRunner; +} + +namespace device { + +// Implementation of a USB device handle on top of the Linux USBFS ioctl +// interface available on Linux, Chrome OS and Android. +class UsbDeviceHandleUsbfs : public UsbDeviceHandle { + public: + // Constructs a new device handle from an existing |device| and open file + // descriptor to that device. |blocking_task_runner| must have a + // MessageLoopForIO. + UsbDeviceHandleUsbfs( + scoped_refptr<UsbDevice> device, + base::ScopedFD fd, + scoped_refptr<base::SequencedTaskRunner> blocking_task_runner); + + // UsbDeviceHandle implementation. + scoped_refptr<UsbDevice> GetDevice() const override; + void Close() override; + void SetConfiguration(int configuration_value, + const ResultCallback& callback) override; + void ClaimInterface(int interface_number, + const ResultCallback& callback) override; + void ReleaseInterface(int interface_number, + const ResultCallback& callback) override; + void SetInterfaceAlternateSetting(int interface_number, + int alternate_setting, + const ResultCallback& callback) override; + void ResetDevice(const ResultCallback& callback) override; + void ClearHalt(uint8_t endpoint, const ResultCallback& callback) override; + void ControlTransfer(UsbEndpointDirection direction, + TransferRequestType request_type, + TransferRecipient recipient, + uint8_t request, + uint16_t value, + uint16_t index, + scoped_refptr<net::IOBuffer> buffer, + size_t length, + unsigned int timeout, + const TransferCallback& callback) override; + void IsochronousTransferIn( + uint8_t endpoint_number, + const std::vector<uint32_t>& packet_lengths, + unsigned int timeout, + const IsochronousTransferCallback& callback) override; + + void IsochronousTransferOut( + uint8_t endpoint_number, + scoped_refptr<net::IOBuffer> buffer, + const std::vector<uint32_t>& packet_lengths, + unsigned int timeout, + const IsochronousTransferCallback& callback) override; + void GenericTransfer(UsbEndpointDirection direction, + uint8_t endpoint_number, + scoped_refptr<net::IOBuffer> buffer, + size_t length, + unsigned int timeout, + const TransferCallback& callback) override; + const UsbInterfaceDescriptor* FindInterfaceByEndpoint( + uint8_t endpoint_address) override; + + private: + class FileThreadHelper; + struct Transfer; + struct InterfaceInfo { + uint8_t alternate_setting; + }; + struct EndpointInfo { + UsbTransferType type; + const UsbInterfaceDescriptor* interface; + }; + + ~UsbDeviceHandleUsbfs() override; + void CloseBlocking(); + void SetConfigurationBlocking(int configuration_value, + const ResultCallback& callback); + void SetConfigurationComplete(int configuration_value, + bool success, + const ResultCallback& callback); + void ReleaseInterfaceBlocking(int interface_number, + const ResultCallback& callback); + void ReleaseInterfaceComplete(int interface_number, + const ResultCallback& callback); + void SetInterfaceBlocking(int interface_number, + int alternate_setting, + const ResultCallback& callback); + void ResetDeviceBlocking(const ResultCallback& callback); + void ClearHaltBlocking(uint8_t endpoint_address, + const ResultCallback& callback); + void IsochronousTransferInternal(uint8_t endpoint_address, + scoped_refptr<net::IOBuffer> buffer, + size_t total_length, + const std::vector<uint32_t>& packet_lengths, + unsigned int timeout, + const IsochronousTransferCallback& callback); + void ReapedUrbs(const std::vector<usbdevfs_urb*>& urbs); + void TransferComplete(scoped_ptr<Transfer> transfer); + void RefreshEndpointInfo(); + void ReportIsochronousError( + const std::vector<uint32_t>& packet_lengths, + const UsbDeviceHandle::IsochronousTransferCallback& callback, + UsbTransferStatus status); + void SetUpTimeoutCallback(Transfer* transfer, unsigned int timeout); + + static void TransferTimedOut(Transfer* transfer); + + scoped_refptr<UsbDevice> device_; + base::ScopedFD fd_; + scoped_refptr<base::SequencedTaskRunner> task_runner_; + scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_; + base::ThreadChecker thread_checker_; + + // Maps claimed interfaces by interface number to their current alternate + // setting. + std::map<uint8_t, InterfaceInfo> interfaces_; + + // Maps endpoints (by endpoint address) to the interface they are a part of. + // Only endpoints of currently claimed and selected interface alternates are + // included in the map. + std::map<uint8_t, EndpointInfo> endpoints_; + + // Helper object owned by the blocking task thread. It will be freed if that + // thread's message loop is destroyed but can also be freed by this class on + // destruction. + FileThreadHelper* helper_; + + std::list<scoped_ptr<Transfer>> transfers_; +}; + +} // namespace device + +#endif // DEVICE_USB_USB_DEVICE_HANDLE_USBFS_H_
diff --git a/device/usb/usb_device_impl.cc b/device/usb/usb_device_impl.cc index 4a134bf..520b9ef 100644 --- a/device/usb/usb_device_impl.cc +++ b/device/usb/usb_device_impl.cc
@@ -4,12 +4,14 @@ #include "device/usb/usb_device_impl.h" +#include <fcntl.h> #include <stddef.h> #include <algorithm> #include "base/bind.h" #include "base/location.h" +#include "base/posix/eintr_wrapper.h" #include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" @@ -18,10 +20,15 @@ #include "components/device_event_log/device_event_log.h" #include "device/usb/usb_context.h" #include "device/usb/usb_descriptors.h" -#include "device/usb/usb_device_handle_impl.h" #include "device/usb/usb_error.h" #include "third_party/libusb/src/libusb/libusb.h" +#if defined(OS_ANDROID) || defined(OS_CHROMEOS) || defined(OS_LINUX) +#include "device/usb/usb_device_handle_usbfs.h" +#else +#include "device/usb/usb_device_handle_impl.h" +#endif + #if defined(OS_CHROMEOS) #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/permission_broker_client.h" @@ -201,9 +208,9 @@ #endif // defined(OS_CHROMEOS) } -void UsbDeviceImpl::HandleClosed(scoped_refptr<UsbDeviceHandle> handle) { +void UsbDeviceImpl::HandleClosed(UsbDeviceHandle* handle) { DCHECK(thread_checker_.CalledOnValidThread()); - handles_.remove(handle.get()); + handles_.remove(handle); } const UsbConfigDescriptor* UsbDeviceImpl::GetActiveConfiguration() const { @@ -250,6 +257,15 @@ } } +void UsbDeviceImpl::ActiveConfigurationChanged(int configuration_value) { + for (const auto& config : configurations_) { + if (config.configuration_value == configuration_value) { + active_configuration_ = &config; + return; + } + } +} + void UsbDeviceImpl::RefreshActiveConfiguration() { active_configuration_ = nullptr; libusb_config_descriptor* platform_config; @@ -261,13 +277,7 @@ return; } - for (const auto& config : configurations_) { - if (config.configuration_value == platform_config->bConfigurationValue) { - active_configuration_ = &config; - break; - } - } - + ActiveConfigurationChanged(platform_config->bConfigurationValue); libusb_free_config_descriptor(platform_config); } @@ -291,21 +301,32 @@ void UsbDeviceImpl::OpenOnBlockingThreadWithFd(dbus::FileDescriptor fd, const OpenCallback& callback) { fd.CheckValidity(); - DCHECK(fd.is_valid()); - - PlatformUsbDeviceHandle handle; - const int rv = libusb_open_fd(platform_device_, fd.TakeValue(), &handle); - if (LIBUSB_SUCCESS == rv) { - task_runner_->PostTask( - FROM_HERE, base::Bind(&UsbDeviceImpl::Opened, this, handle, callback)); + if (fd.is_valid()) { + base::ScopedFD scoped_fd(fd.TakeValue()); + task_runner_->PostTask(FROM_HERE, + base::Bind(&UsbDeviceImpl::Opened, this, + base::Passed(&scoped_fd), callback)); } else { - USB_LOG(EVENT) << "Failed to open device: " - << ConvertPlatformUsbErrorToString(rv); + USB_LOG(EVENT) << "Did not get valid device handle from permission broker."; task_runner_->PostTask(FROM_HERE, base::Bind(callback, nullptr)); } } -#endif // defined(OS_CHROMEOS) +#else +#if defined(OS_LINUX) + +void UsbDeviceImpl::OpenOnBlockingThread(const OpenCallback& callback) { + base::ScopedFD fd(HANDLE_EINTR(open(device_path_.c_str(), O_RDWR))); + if (fd.is_valid()) { + task_runner_->PostTask(FROM_HERE, base::Bind(&UsbDeviceImpl::Opened, this, + base::Passed(&fd), callback)); + } else { + USB_PLOG(EVENT) << "Failed to open device"; + task_runner_->PostTask(FROM_HERE, base::Bind(callback, nullptr)); + } +} + +#else void UsbDeviceImpl::OpenOnBlockingThread(const OpenCallback& callback) { PlatformUsbDeviceHandle handle; @@ -316,17 +337,33 @@ } else { USB_LOG(EVENT) << "Failed to open device: " << ConvertPlatformUsbErrorToString(rv); - task_runner_->PostTask(FROM_HERE, base::Bind(callback, nullptr)); } } +#endif // defined(OS_LINUX) +#endif // defined(OS_CHROMEOS) + +#if defined(OS_LINUX) + +void UsbDeviceImpl::Opened(base::ScopedFD fd, const OpenCallback& callback) { + DCHECK(thread_checker_.CalledOnValidThread()); + scoped_refptr<UsbDeviceHandle> device_handle = + new UsbDeviceHandleUsbfs(this, std::move(fd), blocking_task_runner_); + handles_.push_back(device_handle.get()); + callback.Run(device_handle); +} + +#else + void UsbDeviceImpl::Opened(PlatformUsbDeviceHandle platform_handle, const OpenCallback& callback) { DCHECK(thread_checker_.CalledOnValidThread()); - scoped_refptr<UsbDeviceHandleImpl> device_handle = new UsbDeviceHandleImpl( + scoped_refptr<UsbDeviceHandle> device_handle = new UsbDeviceHandleImpl( context_, this, platform_handle, blocking_task_runner_); handles_.push_back(device_handle.get()); callback.Run(device_handle); } +#endif // defined(OS_LINUX) + } // namespace device
diff --git a/device/usb/usb_device_impl.h b/device/usb/usb_device_impl.h index aea9b54..a5f36ba 100644 --- a/device/usb/usb_device_impl.h +++ b/device/usb/usb_device_impl.h
@@ -13,6 +13,7 @@ #include <utility> #include "base/callback.h" +#include "base/files/scoped_file.h" #include "base/macros.h" #include "base/threading/thread_checker.h" #include "build/build_config.h" @@ -74,6 +75,7 @@ protected: friend class UsbServiceImpl; friend class UsbDeviceHandleImpl; + friend class UsbDeviceHandleUsbfs; // Called by UsbServiceImpl only; UsbDeviceImpl(scoped_refptr<UsbContext> context, @@ -90,7 +92,8 @@ void ReadAllConfigurations(); // Called by UsbDeviceHandleImpl. - void HandleClosed(scoped_refptr<UsbDeviceHandle> handle); + void HandleClosed(UsbDeviceHandle* handle); + void ActiveConfigurationChanged(int configuration_value); void RefreshActiveConfiguration(); private: @@ -103,10 +106,15 @@ const std::string& error_message); void OpenOnBlockingThreadWithFd(dbus::FileDescriptor fd, const OpenCallback& callback); -#endif +#else void OpenOnBlockingThread(const OpenCallback& callback); +#endif // defined(OS_CHROMEOS) +#if defined(OS_LINUX) + void Opened(base::ScopedFD fd, const OpenCallback& callback); +#else void Opened(PlatformUsbDeviceHandle platform_handle, const OpenCallback& callback); +#endif // defined(OS_LINUX) base::ThreadChecker thread_checker_; PlatformUsbDevice platform_device_;
diff --git a/gpu/config/gpu_driver_bug_list_json.cc b/gpu/config/gpu_driver_bug_list_json.cc index 0219d67..32d0ceb5 100644 --- a/gpu/config/gpu_driver_bug_list_json.cc +++ b/gpu/config/gpu_driver_bug_list_json.cc
@@ -19,7 +19,7 @@ { "name": "gpu driver bug list", // Please update the version number whenever you change this file. - "version": "8.61", + "version": "8.62", "entries": [ { "id": 1, @@ -1912,6 +1912,73 @@ "features": [ "disable_overlay_ca_layers" ] + }, + { + "id": 159, + "cr_bugs": [570897], + "description": "Framebuffer discarding can hurt performance on non-tilers", + "os": { + "type": "linux" + }, + "vendor_id": "0x10de", + "gl_vendor": "NVIDIA.*", + "gl_type": "gl", + "features": [ + "disable_discard_framebuffer" + ] + }, + { + "id": 160, + "cr_bugs": [601753], + "description": "Framebuffer discarding not useful on NVIDIA Kepler architecture and later", + "os": { + "type": "linux" + }, + "vendor_id": "0x10de", + "gl_vendor": "NVIDIA.*", + "gl_type": "gles", + "gl_version": { + "op": ">=", + "value": "3.0" + }, + "features": [ + "disable_discard_framebuffer" + ] + }, + { + "id": 161, + "cr_bugs": [601753], + "description": "Framebuffer discarding not useful on NVIDIA Kepler architecture and later", + "os": { + "type": "chromeos" + }, + "vendor_id": "0x10de", + "gl_vendor": "NVIDIA.*", + "gl_type": "gles", + "gl_version": { + "op": ">=", + "value": "3.0" + }, + "features": [ + "disable_discard_framebuffer" + ] + }, + { + "id": 162, + "cr_bugs": [601753], + "description": "Framebuffer discarding not useful on NVIDIA Kepler architecture and later", + "os": { + "type": "android" + }, + "gl_vendor": "NVIDIA.*", + "gl_type": "gles", + "gl_version": { + "op": ">=", + "value": "3.0" + }, + "features": [ + "disable_discard_framebuffer" + ] } ] }
diff --git a/net/base/io_buffer.h b/net/base/io_buffer.h index 9285791a..1d00cd1 100644 --- a/net/base/io_buffer.h +++ b/net/base/io_buffer.h
@@ -81,7 +81,7 @@ explicit IOBuffer(int buffer_size); explicit IOBuffer(size_t buffer_size); - char* data() { return data_; } + char* data() const { return data_; } protected: friend class base::RefCountedThreadSafe<IOBuffer>;
diff --git a/remoting/android/BUILD.gn b/remoting/android/BUILD.gn index a7eff91f6..ee4e40b 100644 --- a/remoting/android/BUILD.gn +++ b/remoting/android/BUILD.gn
@@ -29,6 +29,8 @@ "//ui/gfx", ] sources = [ + "//remoting/client/audio_player_android.cc", + "//remoting/client/audio_player_android.h", "//remoting/client/jni/android_keymap.cc", "//remoting/client/jni/android_keymap.h", "//remoting/client/jni/chromoting_jni_instance.cc", @@ -45,6 +47,7 @@ "//remoting/client/jni/remoting_jni_registrar.cc", "//remoting/client/jni/remoting_jni_registrar.h", ] + libs = [ "OpenSLES" ] configs += [ "//remoting:enable_webrtc_remoting_client" ] }
diff --git a/remoting/client/audio_player.cc b/remoting/client/audio_player.cc index 249c20d..5fc00b7 100644 --- a/remoting/client/audio_player.cc +++ b/remoting/client/audio_player.cc
@@ -9,11 +9,6 @@ #include "base/logging.h" #include "base/stl_util.h" -// The number of channels in the audio stream (only supporting stereo audio -// for now). -const int kChannels = 2; -const int kSampleSizeBytes = 2; - // If queue grows bigger than 150ms we start dropping packets. const int kMaxQueueLatencyMs = 150; @@ -35,8 +30,8 @@ CHECK_EQ(1, packet->data_size()); DCHECK_EQ(AudioPacket::ENCODING_RAW, packet->encoding()); DCHECK_NE(AudioPacket::SAMPLING_RATE_INVALID, packet->sampling_rate()); - DCHECK_EQ(kSampleSizeBytes, packet->bytes_per_sample()); - DCHECK_EQ(static_cast<int>(kChannels), packet->channels()); + DCHECK_EQ(kSampleSizeBytes, static_cast<int>(packet->bytes_per_sample())); + DCHECK_EQ(kChannels, static_cast<int>(packet->channels())); DCHECK_EQ(packet->data(0).size() % (kChannels * kSampleSizeBytes), 0u); // No-op if the Pepper player won't start.
diff --git a/remoting/client/audio_player.h b/remoting/client/audio_player.h index f88e6633..ea0b789 100644 --- a/remoting/client/audio_player.h +++ b/remoting/client/audio_player.h
@@ -19,6 +19,11 @@ class AudioPlayer { public: + // The number of channels in the audio stream (only supporting stereo audio + // for now). + static const int kChannels = 2; + static const int kSampleSizeBytes = 2; + virtual ~AudioPlayer(); void ProcessAudioPacket(std::unique_ptr<AudioPacket> packet); @@ -38,13 +43,16 @@ uint32_t buffer_size, void* data); + // Function called by the subclass when it needs more audio samples to fill + // its buffer. Will fill the buffer with 0's if no sample is available. + void FillWithSamples(void* samples, uint32_t buffer_size); + private: friend class AudioPlayerTest; typedef std::list<AudioPacket*> AudioPacketQueue; void ResetQueue(); - void FillWithSamples(void* samples, uint32_t buffer_size); AudioPacket::SamplingRate sampling_rate_;
diff --git a/remoting/client/audio_player_android.cc b/remoting/client/audio_player_android.cc new file mode 100644 index 0000000..cd49096 --- /dev/null +++ b/remoting/client/audio_player_android.cc
@@ -0,0 +1,153 @@ +// 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 "remoting/client/audio_player_android.h" + +#include "base/logging.h" + +namespace remoting { + +const int kFrameSizeMs = 40; +const int kNumOfBuffers = 1; + +static_assert(AudioPlayer::kChannels == 2, + "AudioPlayer must be feeding 2 channels data."); +const int kChannelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; + +AudioPlayerAndroid::AudioPlayerAndroid() { + if (slCreateEngine(&engine_object_, 0, nullptr, 0, nullptr, nullptr) != + SL_RESULT_SUCCESS || + (*engine_object_)->Realize(engine_object_, SL_BOOLEAN_FALSE) != + SL_RESULT_SUCCESS || + (*engine_object_) + ->GetInterface(engine_object_, SL_IID_ENGINE, &engine_) != + SL_RESULT_SUCCESS || + (*engine_)->CreateOutputMix(engine_, &output_mix_object_, 0, nullptr, + nullptr) != SL_RESULT_SUCCESS || + (*output_mix_object_)->Realize(output_mix_object_, SL_BOOLEAN_FALSE) != + SL_RESULT_SUCCESS) { + LOG(ERROR) << "Failed to initialize OpenSL ES."; + } +} + +AudioPlayerAndroid::~AudioPlayerAndroid() { + DestroyPlayer(); + if (output_mix_object_) { + (*output_mix_object_)->Destroy(output_mix_object_); + } + if (engine_object_) { + (*engine_object_)->Destroy(engine_object_); + } +} + +uint32_t AudioPlayerAndroid::GetSamplesPerFrame() { + return sample_per_frame_; +} + +bool AudioPlayerAndroid::ResetAudioPlayer( + AudioPacket::SamplingRate sampling_rate) { + if (!output_mix_object_) { + // output mixer not successfully created in ctor. + return false; + } + DestroyPlayer(); + sample_per_frame_ = + kFrameSizeMs * sampling_rate / base::Time::kMillisecondsPerSecond; + buffer_size_ = kChannels * kSampleSizeBytes * sample_per_frame_; + frame_buffer_.reset(new uint8_t[buffer_size_]); + FillWithSamples(frame_buffer_.get(), buffer_size_); + SLDataLocator_AndroidSimpleBufferQueue locator_bufqueue; + locator_bufqueue.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; + locator_bufqueue.numBuffers = kNumOfBuffers; + SLDataFormat_PCM format = CreatePcmFormat(sampling_rate); + SLDataSource source = {&locator_bufqueue, &format}; + SLDataLocator_OutputMix locator_out; + locator_out.locatorType = SL_DATALOCATOR_OUTPUTMIX; + locator_out.outputMix = output_mix_object_; + SLDataSink sink; + sink.pLocator = &locator_out; + sink.pFormat = nullptr; + + const SLInterfaceID ids[] = {SL_IID_BUFFERQUEUE}; + const SLboolean reqs[] = {SL_BOOLEAN_TRUE}; + + if ((*engine_)->CreateAudioPlayer(engine_, &player_object_, &source, &sink, + arraysize(ids), ids, + reqs) != SL_RESULT_SUCCESS || + (*player_object_)->Realize(player_object_, SL_BOOLEAN_FALSE) != + SL_RESULT_SUCCESS || + (*player_object_)->GetInterface(player_object_, SL_IID_PLAY, &player_) != + SL_RESULT_SUCCESS || + (*player_object_) + ->GetInterface(player_object_, SL_IID_BUFFERQUEUE, + &buffer_queue_) != SL_RESULT_SUCCESS || + (*buffer_queue_) + ->RegisterCallback(buffer_queue_, + &AudioPlayerAndroid::BufferQueueCallback, + this) != SL_RESULT_SUCCESS || + (*player_)->SetPlayState(player_, SL_PLAYSTATE_PLAYING) != + SL_RESULT_SUCCESS || + + // The player will only ask for more data after it consumes all its + // buffers. Having an empty queue will not trigger it to ask for more + // data. + (*buffer_queue_) + ->Enqueue(buffer_queue_, frame_buffer_.get(), buffer_size_) != + SL_RESULT_SUCCESS) { + LOG(ERROR) << "Failed to initialize the player."; + return false; + } + return true; +} + +// static +void AudioPlayerAndroid::BufferQueueCallback( + SLAndroidSimpleBufferQueueItf caller, + void* args) { + AudioPlayerAndroid* player = static_cast<AudioPlayerAndroid*>(args); + player->FillWithSamples(player->frame_buffer_.get(), player->buffer_size_); + if ((*caller)->Enqueue(caller, player->frame_buffer_.get(), + player->buffer_size_) != SL_RESULT_SUCCESS) { + LOG(ERROR) << "Failed to enqueue the frame."; + } +} + +// static +SLDataFormat_PCM AudioPlayerAndroid::CreatePcmFormat(int sampling_rate) { + SLDataFormat_PCM format; + format.formatType = SL_DATAFORMAT_PCM; + format.numChannels = kChannels; + switch (sampling_rate) { + case AudioPacket::SAMPLING_RATE_44100: + format.samplesPerSec = SL_SAMPLINGRATE_44_1; + break; + case AudioPacket::SAMPLING_RATE_48000: + format.samplesPerSec = SL_SAMPLINGRATE_48; + break; + default: + LOG(FATAL) << "Unsupported audio sampling rate: " << sampling_rate; + } // samplesPerSec is in mHz. OpenSL doesn't name this field well. + format.bitsPerSample = kSampleSizeBytes * 8; + format.containerSize = kSampleSizeBytes * 8; +#if defined(ARCH_CPU_LITTLE_ENDIAN) + format.endianness = SL_BYTEORDER_LITTLEENDIAN; +#else + format.endianness = SL_BYTEORDER_BIGENDIAN; +#endif + format.channelMask = kChannelMask; + return format; +} + +void AudioPlayerAndroid::DestroyPlayer() { + if (player_object_) { + (*player_object_)->Destroy(player_object_); + player_object_ = nullptr; + } + frame_buffer_.reset(); + buffer_size_ = 0; + player_ = nullptr; + buffer_queue_ = nullptr; +} + +} // namespace remoting
diff --git a/remoting/client/audio_player_android.h b/remoting/client/audio_player_android.h new file mode 100644 index 0000000..1c062938 --- /dev/null +++ b/remoting/client/audio_player_android.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 REMOTING_CLIENT_AUDIO_PLAYER_ANDROID_H_ +#define REMOTING_CLIENT_AUDIO_PLAYER_ANDROID_H_ + +#include <SLES/OpenSLES.h> +#include <SLES/OpenSLES_Android.h> + +#include "base/macros.h" +#include "remoting/client/audio_player.h" + +namespace remoting { + +class AudioPlayerAndroid : public AudioPlayer { + public: + AudioPlayerAndroid(); + ~AudioPlayerAndroid() override; + + // AudioPlayer overrides. + uint32_t GetSamplesPerFrame() override; + bool ResetAudioPlayer(AudioPacket::SamplingRate sampling_rate) override; + + private: + // Called when new data is needed for the buffer queue. + static void BufferQueueCallback(SLAndroidSimpleBufferQueueItf caller, + void* args); + static SLDataFormat_PCM CreatePcmFormat(int sampling_rate); + + // Destroys the player and releases the buffer. Do nothing if the player is + // nullptr. + void DestroyPlayer(); + + SLObjectItf engine_object_ = nullptr; + SLEngineItf engine_ = nullptr; + SLObjectItf output_mix_object_ = nullptr; + SLObjectItf player_object_ = nullptr; + SLPlayItf player_ = nullptr; + SLAndroidSimpleBufferQueueItf buffer_queue_ = nullptr; + std::unique_ptr<uint8_t[]> frame_buffer_; + size_t buffer_size_ = 0; + uint32_t sample_per_frame_ = 0; + + DISALLOW_COPY_AND_ASSIGN(AudioPlayerAndroid); +}; + +} // namespace remoting + +#endif // REMOTING_CLIENT_AUDIO_PLAYER_ANDROID_H_
diff --git a/remoting/client/jni/chromoting_jni_instance.cc b/remoting/client/jni/chromoting_jni_instance.cc index bbdda97..b16c92f 100644 --- a/remoting/client/jni/chromoting_jni_instance.cc +++ b/remoting/client/jni/chromoting_jni_instance.cc
@@ -17,7 +17,7 @@ #include "jingle/glue/thread_wrapper.h" #include "net/socket/client_socket_factory.h" #include "remoting/base/chromium_url_request.h" -#include "remoting/client/audio_player.h" +#include "remoting/client/audio_player_android.h" #include "remoting/client/client_status_logger.h" #include "remoting/client/jni/android_keymap.h" #include "remoting/client/jni/chromoting_jni_runtime.h" @@ -396,8 +396,9 @@ video_renderer_.reset(new SoftwareVideoRenderer( client_context_->decode_task_runner(), view_.get(), perf_tracker_.get())); - client_.reset(new ChromotingClient(client_context_.get(), this, - video_renderer_.get(), nullptr)); + client_.reset( + new ChromotingClient(client_context_.get(), this, video_renderer_.get(), + make_scoped_ptr(new AudioPlayerAndroid()))); signaling_.reset( new XmppSignalStrategy(net::ClientSocketFactory::GetDefaultFactory(),
diff --git a/remoting/host/input_injector_android.cc b/remoting/host/input_injector_android.cc index f21f3a24..8288f32 100644 --- a/remoting/host/input_injector_android.cc +++ b/remoting/host/input_injector_android.cc
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/logging.h" #include "base/memory/ptr_util.h" #include "remoting/host/input_injector.h"
diff --git a/remoting/protocol/channel_socket_adapter_unittest.cc b/remoting/protocol/channel_socket_adapter_unittest.cc index 5ddd559..4e6aa55 100644 --- a/remoting/protocol/channel_socket_adapter_unittest.cc +++ b/remoting/protocol/channel_socket_adapter_unittest.cc
@@ -54,13 +54,11 @@ MOCK_METHOD1(GetSslCipher, bool(std::string* cipher)); MOCK_CONST_METHOD0(GetLocalCertificate, rtc::scoped_refptr<rtc::RTCCertificate>()); - MOCK_CONST_METHOD1(GetRemoteSSLCertificate, - bool(rtc::SSLCertificate** cert)); // This can't be a real mock method because gmock doesn't support move-only // return values. - virtual rtc::scoped_ptr<rtc::SSLCertificate> GetRemoteSSLCertificate() - const { + rtc::scoped_ptr<rtc::SSLCertificate> GetRemoteSSLCertificate() + const override { EXPECT_TRUE(false); // Never called. return nullptr; }
diff --git a/remoting/remoting_android.gypi b/remoting/remoting_android.gypi index 5c5d797..fbd0fa4 100644 --- a/remoting/remoting_android.gypi +++ b/remoting/remoting_android.gypi
@@ -42,6 +42,8 @@ '../ui/gfx/gfx.gyp:gfx', ], 'sources': [ + 'client/audio_player_android.cc', + 'client/audio_player_android.h', 'client/jni/android_keymap.cc', 'client/jni/android_keymap.h', 'client/jni/chromoting_jni_instance.cc', @@ -65,6 +67,11 @@ ] }] ], + 'link_settings': { + 'libraries': [ + '-lOpenSLES', + ], + }, }, # end of target 'remoting_client_jni' { 'target_name': 'remoting_android_resources',
diff --git a/styleguide/c++/c++11.html b/styleguide/c++/c++11.html index 72ec6d8..1dba165 100644 --- a/styleguide/c++/c++11.html +++ b/styleguide/c++/c++11.html
@@ -110,6 +110,14 @@ </tr> <tr> +<td>Constant Expressions</td> +<td><code>constexpr</code></td> +<td>Compile-time constant expressions</td> +<td><a href="http://en.cppreference.com/w/cpp/language/constexpr">constexpr specifier</a></td> +<td>Prefer to <code>const</code> for variables where possible. Use cautiously on functions. Don't go out of the way to convert existing code. <a href="https://google.github.io/styleguide/cppguide.html#Use_of_constexpr">Google Style Guide</a></td> +</tr> + +<tr> <td>Declared Type Accessor</td> <td><code>decltype(<i>expression</i>)</code></td> <td>Provides a means to determine the type of an expression at compile-time, @@ -560,17 +568,6 @@ </tr> <tr> -<td>Constant Expressions</td> -<td><code>constexpr</code></td> -<td>Compile-time constant expressions</td> -<td><a href="http://en.cppreference.com/w/cpp/language/constexpr"> -constexpr specifier</a></td> -<td>Doesn't work in MSVS2013. Reevalute once it does. <a -href="https://google.github.io/styleguide/cppguide.html#Use_of_constexpr">Google -Style Guide on <code>constexpr</code></a></td> -</tr> - -<tr> <td>Function Local Variable</td> <td><code>__func__</code></td> <td>Provides a local variable of the name of the enclosing
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index 68387f22..61ff1738 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -363,8 +363,7 @@ }, { "args": [ - "--enable-browser-side-navigation", - "--test-launcher-filter-file=src/testing/buildbot/filters/browser-side-navigation.linux.content_unittests.filter" + "--enable-browser-side-navigation" ], "swarming": { "can_use_on_swarming_builders": true
diff --git a/testing/buildbot/chromium.mojo.json b/testing/buildbot/chromium.mojo.json index 2642def..91b51fc 100644 --- a/testing/buildbot/chromium.mojo.json +++ b/testing/buildbot/chromium.mojo.json
@@ -19,7 +19,8 @@ "args": [ "--override-use-gl-with-osmesa-for-tests", "--run-in-mash", - "--test-launcher-filter-file=src/testing/buildbot/filters/mojo.fyi.browser_tests.filter" + "--test-launcher-filter-file=src/testing/buildbot/filters/mojo.fyi.browser_tests.filter", + "--use-x11-test-config" ], "test": "browser_tests" },
diff --git a/testing/buildbot/filters/browser-side-navigation.linux.content_unittests.filter b/testing/buildbot/filters/browser-side-navigation.linux.content_unittests.filter deleted file mode 100644 index 3209420d..0000000 --- a/testing/buildbot/filters/browser-side-navigation.linux.content_unittests.filter +++ /dev/null
@@ -1 +0,0 @@ --NavigationControllerTest.DontDiscardWrongPendingEntry
diff --git a/testing/variations/fieldtrial_testing_config_android.json b/testing/variations/fieldtrial_testing_config_android.json index 432d4cdc..3001678f 100644 --- a/testing/variations/fieldtrial_testing_config_android.json +++ b/testing/variations/fieldtrial_testing_config_android.json
@@ -172,7 +172,6 @@ { "group_name": "Enabled5", "params": { - "country": "IN", "version": "5" } }
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index 67b86f7..0ebfbf0 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -1244,8 +1244,6 @@ crbug.com/568867 [ Win Debug ] transforms/3d/point-mapping/3d-point-mapping-deep.html [ Failure ] crbug.com/568867 [ Win Debug ] transforms/3d/point-mapping/3d-point-mapping-preserve-3d.html [ Failure ] -crbug.com/569811 inspector-protocol/debugger/updateCallFrameScopes.html [ Pass Failure ] - crbug.com/571376 http/tests/webfont/font-display-intervention.html [ Pass Failure ] crbug.com/320139 fast/repaint/block-layout-inline-children-replaced.html [ Pass Failure ]
diff --git a/third_party/WebKit/LayoutTests/app_banner/testrunner-resolve-crash.html b/third_party/WebKit/LayoutTests/app_banner/testrunner-resolve-crash.html new file mode 100644 index 0000000..bea62b8 --- /dev/null +++ b/third_party/WebKit/LayoutTests/app_banner/testrunner-resolve-crash.html
@@ -0,0 +1,8 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +<script> +test(function() { + testRunner.resolveBeforeInstallPromptPromise(0, 'foo'); +}, 'Test that calling resolveBeforeInstallPromptPromise does not crash'); +</script>
diff --git a/third_party/WebKit/LayoutTests/fast/css/getComputedStyle/computed-style-empty-font-family-expected.txt b/third_party/WebKit/LayoutTests/fast/css/getComputedStyle/computed-style-empty-font-family-expected.txt index 053e4fa..73795256 100644 --- a/third_party/WebKit/LayoutTests/fast/css/getComputedStyle/computed-style-empty-font-family-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/css/getComputedStyle/computed-style-empty-font-family-expected.txt
@@ -8,5 +8,6 @@ font-style: normal; font-variant: normal; font-variant-ligatures: normal; +font-variant-caps: normal; font-weight: normal;
diff --git a/third_party/WebKit/LayoutTests/fast/css/getComputedStyle/computed-style-font-family-expected.txt b/third_party/WebKit/LayoutTests/fast/css/getComputedStyle/computed-style-font-family-expected.txt index b4005b4..a7700c6 100644 --- a/third_party/WebKit/LayoutTests/fast/css/getComputedStyle/computed-style-font-family-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/css/getComputedStyle/computed-style-font-family-expected.txt
@@ -8,5 +8,6 @@ font-style: normal; font-variant: normal; font-variant-ligatures: normal; +font-variant-caps: normal; font-weight: normal;
diff --git a/third_party/WebKit/LayoutTests/fast/css/getComputedStyle/computed-style-listing-expected.txt b/third_party/WebKit/LayoutTests/fast/css/getComputedStyle/computed-style-listing-expected.txt index 89f9422..17477a12 100644 --- a/third_party/WebKit/LayoutTests/fast/css/getComputedStyle/computed-style-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/css/getComputedStyle/computed-style-listing-expected.txt
@@ -160,6 +160,7 @@ font-stretch: normal font-style: normal font-variant: normal +font-variant-caps: normal font-variant-ligatures: normal font-weight: normal grid-auto-columns: auto
diff --git a/third_party/WebKit/LayoutTests/fast/css/getComputedStyle/computed-style-without-renderer-listing-expected.txt b/third_party/WebKit/LayoutTests/fast/css/getComputedStyle/computed-style-without-renderer-listing-expected.txt index badbd6b..9801ee7 100644 --- a/third_party/WebKit/LayoutTests/fast/css/getComputedStyle/computed-style-without-renderer-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/css/getComputedStyle/computed-style-without-renderer-listing-expected.txt
@@ -160,6 +160,7 @@ font-stretch: normal font-style: normal font-variant: normal +font-variant-caps: normal font-variant-ligatures: normal font-weight: normal grid-auto-columns: auto
diff --git a/third_party/WebKit/LayoutTests/fast/encoding/unlabelled-non-ascii-utf8-expected.html b/third_party/WebKit/LayoutTests/fast/encoding/unlabelled-non-ascii-utf8-expected.html deleted file mode 100644 index 511c0fbc..0000000 --- a/third_party/WebKit/LayoutTests/fast/encoding/unlabelled-non-ascii-utf8-expected.html +++ /dev/null
@@ -1,48 +0,0 @@ -<!DOCTYPE html> -<html> -<head> -<title>Unlabelled UTF-8</title> -<meta charset="utf-8"> -</head> -<body> - <p>UTF-8 page without a proper label. UTF-8 encoding detector - should come into action to detect the right encoding, hence - all the non-ASCII chars should be rendered as expected without - being garbled.</p> - <pre> - För var vers, jag gör, - Lovar du en kyss mig giva; - Arket fullt jag borde skriva, - Mindre har jag skrivit för. - Men man måste hålla måtta, - Jag med vers, med kyssar du. - Låt mig räkna: Där är sju! - En därtill det gör mig åtta. - - Numro åtta är fatal, - Greklands sångmör voro nio, - Och en svensk därtill gör tio. — - Elva var apostelns tal, - Ty jag räknar icke Judas, - Honom, som i vänners lag - Kysste falskt; det gör ej jag, - Helst när vackra läppar bjudas. - - Huru står min räkning här? - Aderton; det är dock något. - Nitton — rimmet gör besvär, - Därföre jag fyller tjoget. - Strofen är ej full som jag, - In i hamnen vill jag styra, - Därföre till godo tag - Denna gång med tjugofyra. - - 'Kyssarna' ('The kisses'), Esaias Tegnér, 1782-1846 - - int main(void) - { - return 0; - } - </pre> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/fast/encoding/unlabelled-non-ascii-utf8.html b/third_party/WebKit/LayoutTests/fast/encoding/unlabelled-non-ascii-utf8.html deleted file mode 100644 index aeddfef..0000000 --- a/third_party/WebKit/LayoutTests/fast/encoding/unlabelled-non-ascii-utf8.html +++ /dev/null
@@ -1,47 +0,0 @@ -<!DOCTYPE html> -<html> -<head> -<title>Unlabelled UTF-8</title> -</head> -<body> - <p>UTF-8 page without a proper label. UTF-8 encoding detector - should come into action to detect the right encoding, hence - all the non-ASCII chars should be rendered as expected without - being garbled.</p> - <pre> - För var vers, jag gör, - Lovar du en kyss mig giva; - Arket fullt jag borde skriva, - Mindre har jag skrivit för. - Men man måste hålla måtta, - Jag med vers, med kyssar du. - Låt mig räkna: Där är sju! - En därtill det gör mig åtta. - - Numro åtta är fatal, - Greklands sångmör voro nio, - Och en svensk därtill gör tio. — - Elva var apostelns tal, - Ty jag räknar icke Judas, - Honom, som i vänners lag - Kysste falskt; det gör ej jag, - Helst när vackra läppar bjudas. - - Huru står min räkning här? - Aderton; det är dock något. - Nitton — rimmet gör besvär, - Därföre jag fyller tjoget. - Strofen är ej full som jag, - In i hamnen vill jag styra, - Därföre till godo tag - Denna gång med tjugofyra. - - 'Kyssarna' ('The kisses'), Esaias Tegnér, 1782-1846 - - int main(void) - { - return 0; - } - </pre> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/fast/mediastream/getusermedia-constraints.html b/third_party/WebKit/LayoutTests/fast/mediastream/getusermedia-constraints.html index 880fc28d..6649d89 100644 --- a/third_party/WebKit/LayoutTests/fast/mediastream/getusermedia-constraints.html +++ b/third_party/WebKit/LayoutTests/fast/mediastream/getusermedia-constraints.html
@@ -102,6 +102,11 @@ 'Using both mandatory and height should give TypeError', {'mandatory': {'height': '270'}, 'height': '270'}, 'TypeError'); +// Shows that the advanced element is not ignored. +check_constraints( + 'Advanced constraints with illegal content gives TypeError', + {'advanced': [{'height': 270}]}, 'TypeError'); + </script> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-enabled.html b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-enabled.html index bcad26b..6b9ed43 100644 --- a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-enabled.html +++ b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-enabled.html
@@ -3,8 +3,10 @@ <!-- TODO(iclelland): Generate this sample token during the build. The token below will expire in 2033, but it would be better to always have a token which is guaranteed to be valid when the tests are run. --> -<meta http-equiv="origin-trial" content="1|tZPW/JJ2Sxm4z7k/Eb1/upMsppozWpTwEuGwhgQko0zWS6ebvjQ+EXPP/ftoMX8/PCoDgOS3xlrXElMgDDvbCg==|http://127.0.0.1:8000|Frobulate|2000000000"> -<title>Test Sample API when trial is enabled</title> +<!-- Generate this token with the command: +generate_token.py http://127.0.0.1:8000 Frobulate -expire-timestamp=2000000000 +--> +<meta http-equiv="origin-trial" content="AlCoOPbezqtrGMzSzbLQC4c+oPqO6yuioemcBPjgcXajF8jtmZr4B8tJRPAARPbsX6hDeVyXCKHzEJfpBXvZgQEAAABReyJvcmlnaW4iOiAiaHR0cDovLzEyNy4wLjAuMTo4MDAwIiwgImZlYXR1cmUiOiAiRnJvYnVsYXRlIiwgImV4cGlyeSI6IDIwMDAwMDAwMDB9" /> <script src="../resources/testharness.js"></script> <script src="../resources/testharness-helpers.js"></script> <script src="../resources/testharnessreport.js"></script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-expired.html b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-expired.html index 53641c5..acdae4d 100644 --- a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-expired.html +++ b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-expired.html
@@ -4,7 +4,10 @@ below has a valid signature for the current signing key, but it would be better to always have a token which is guaranteed to be valid when the tests are run. --> -<meta http-equiv="origin-trial" content="1|W5OpLTgzFacJn++BqWVqbeyfxdbimq4hqMg65lHYlmod6ZB2Jl5pfNWlHtRJBOl88/paQB5wqWq5e3z870tfCw==|http://127.0.0.1:8000|Frobulate|1000000000" /> +<!-- Generate this token with the command: +generate_token.py http://127.0.0.1:8000 Frobulate -expire-timestamp=1000000000 +--> +<meta http-equiv="origin-trial" content="AtA29m1y4Qfx7TACfDcePevArXCxKUObQS+TTb2bOi5YumkWgcWB5O0MasQU4cY4qZXXAQmbMBf7OtBh6qI2qA4AAABReyJvcmlnaW4iOiAiaHR0cDovLzEyNy4wLjAuMTo4MDAwIiwgImZlYXR1cmUiOiAiRnJvYnVsYXRlIiwgImV4cGlyeSI6IDEwMDAwMDAwMDB9" /> <title>Test Sample API when trial has expired</title> <script src="../resources/testharness.js"></script> <script src="../resources/testharness-helpers.js"></script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-multiple-tokens.html b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-multiple-tokens.html index 40ad0f1..cc8a98b9 100644 --- a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-multiple-tokens.html +++ b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-multiple-tokens.html
@@ -3,9 +3,14 @@ <!-- TODO(iclelland): Generate these sample tokens during the build. The tokens below will expire in 2033, but it would be better to always have tokens which are guaranteed to be valid when the tests are run. --> -<meta http-equiv="origin-trial" content="1|umr41cAPVTw49gYvZb5zQc+lIy6ixCQkC/QyuDBkDNnAbZQjXe7YM/Pb8d0nHCY7xhRq37ZGP7DhLSCp0aOeDA==|http://127.0.0.1:8000|Grokalyze|2000000000" /> -<meta http-equiv="origin-trial" content="1|tZPW/JJ2Sxm4z7k/Eb1/upMsppozWpTwEuGwhgQko0zWS6ebvjQ+EXPP/ftoMX8/PCoDgOS3xlrXElMgDDvbCg==|http://127.0.0.1:8000|Frobulate|2000000000" /> -<meta http-equiv="origin-trial" content="1|Z+D6g2JZrstb1O6ztVoTi6bWXYGFCdd9v2lu23Doj2RP+q9gHZqhs7RUp1vfUQ0IVt0p5jzVX/OOrwenvktyBA==|http://127.0.0.1:8000|EnableMarqueeTag|2000000000" /> +<!-- Generate these token with the commands: +generate_token.py http://127.0.0.1:8000 Grokalyze -expire-timestamp=2000000000 +generate_token.py http://127.0.0.1:8000 Frobulate -expire-timestamp=2000000000 +generate_token.py http://127.0.0.1:8000 EnableMarqueeTag -expire-timestamp=2000000000 +--> +<meta http-equiv="origin-trial" content="Am5nmX0C/DpiE2xRlcZ6D4wvTiO5ydK4ATI0aUDxpIXD4MIoll0XEsIT8Qgdq4+tEYxOeJo/Y0QtkpYwRNWScw4AAABReyJvcmlnaW4iOiAiaHR0cDovLzEyNy4wLjAuMTo4MDAwIiwgImZlYXR1cmUiOiAiR3Jva2FseXplIiwgImV4cGlyeSI6IDIwMDAwMDAwMDB9" /> +<meta http-equiv="origin-trial" content="AlCoOPbezqtrGMzSzbLQC4c+oPqO6yuioemcBPjgcXajF8jtmZr4B8tJRPAARPbsX6hDeVyXCKHzEJfpBXvZgQEAAABReyJvcmlnaW4iOiAiaHR0cDovLzEyNy4wLjAuMTo4MDAwIiwgImZlYXR1cmUiOiAiRnJvYnVsYXRlIiwgImV4cGlyeSI6IDIwMDAwMDAwMDB9" /> +<meta http-equiv="origin-trial" content="Avs0tgQGv771bXLAScGOi5VpjYdIW/nbb00qk3rH8T6/+7NVTlBosCz05fCg9Yb3N3P9h2IuadgfNtPTMMpirQwAAABYeyJvcmlnaW4iOiAiaHR0cDovLzEyNy4wLjAuMTo4MDAwIiwgImZlYXR1cmUiOiAiRW5hYmxlTWFycXVlZVRhZyIsICJleHBpcnkiOiAyMDAwMDAwMDAwfQ==" /> <title>Test Sample API when trial is enabled and multiple tokens are present</title> <script src="../resources/testharness.js"></script> <script src="../resources/testharness-helpers.js"></script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-stolen.html b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-stolen.html index 50e60a3..44a4af7 100644 --- a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-stolen.html +++ b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-stolen.html
@@ -3,7 +3,10 @@ <!-- TODO(iclelland): Generate this sample token during the build. The token below will expire in 2033, but it would be better to always have a token which is guaranteed to be valid when the tests are run. --> -<meta http-equiv="origin-trial" content="1|ak4CUgJ69tforMyzN7lgxhWaaIny/lGqtLjIqJjMXBA2b8lqul1KhyyLmKZ38+tJnZDLXZmQUn5ZjMFE/SmNDw==|https://invalid.example.com|Frobulate|2000000000" /> +<!-- Generate this token with the command: +generate_token.py invalid.example.com Frobulate -expire-timestamp=2000000000 +--> +<meta http-equiv="origin-trial" content="AqIqd5EqkNMJncc7Klowr3EI/hk7Aw8VecWqlGxZN145I+d1A4nUu7QeN8bj0zjpMhTbNHoESXE4Ec+pTECLQgUAAABbeyJvcmlnaW4iOiAiaHR0cHM6Ly9pbnZhbGlkLmV4YW1wbGUuY29tOjQ0MyIsICJmZWF0dXJlIjogIkZyb2J1bGF0ZSIsICJleHBpcnkiOiAyMDAwMDAwMDAwfQ==" /> <title>Test Sample API when token is present for a different origin</title> <script src="../resources/testharness.js"></script> <script src="../resources/testharness-helpers.js"></script>
diff --git a/third_party/WebKit/LayoutTests/platform/android/fast/css/getComputedStyle/computed-style-empty-font-family-expected.txt b/third_party/WebKit/LayoutTests/platform/android/fast/css/getComputedStyle/computed-style-empty-font-family-expected.txt new file mode 100644 index 0000000..053e4fa --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/android/fast/css/getComputedStyle/computed-style-empty-font-family-expected.txt
@@ -0,0 +1,12 @@ +Font attributes. The font-family should list the empty string: + +font-family: ""; +font-kerning: auto; +font-size: 16px; +font-size-adjust: none; +font-stretch: normal; +font-style: normal; +font-variant: normal; +font-variant-ligatures: normal; +font-weight: normal; +
diff --git a/third_party/WebKit/LayoutTests/platform/android/fast/css/getComputedStyle/computed-style-font-family-expected.txt b/third_party/WebKit/LayoutTests/platform/android/fast/css/getComputedStyle/computed-style-font-family-expected.txt new file mode 100644 index 0000000..b4005b4 --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/android/fast/css/getComputedStyle/computed-style-font-family-expected.txt
@@ -0,0 +1,12 @@ +Font attributes. The font-family should list three families: + +font-family: monospace, "Lucida Grande", sans-serif; +font-kerning: auto; +font-size: 16px; +font-size-adjust: none; +font-stretch: normal; +font-style: normal; +font-variant: normal; +font-variant-ligatures: normal; +font-weight: normal; +
diff --git a/third_party/WebKit/LayoutTests/platform/android/fast/css/getComputedStyle/computed-style-listing-expected.txt b/third_party/WebKit/LayoutTests/platform/android/fast/css/getComputedStyle/computed-style-listing-expected.txt new file mode 100644 index 0000000..89f9422 --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/android/fast/css/getComputedStyle/computed-style-listing-expected.txt
@@ -0,0 +1,305 @@ +This test documents all computed styles on a div element. + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +-webkit-app-region: no-drag +-webkit-appearance: none +-webkit-background-clip: border-box +-webkit-background-origin: padding-box +-webkit-border-horizontal-spacing: 0px +-webkit-border-image: none +-webkit-border-vertical-spacing: 0px +-webkit-box-align: stretch +-webkit-box-decoration-break: slice +-webkit-box-direction: normal +-webkit-box-flex: 0 +-webkit-box-flex-group: 1 +-webkit-box-lines: single +-webkit-box-ordinal-group: 1 +-webkit-box-orient: horizontal +-webkit-box-pack: start +-webkit-box-reflect: none +-webkit-clip-path: none +-webkit-filter: none +-webkit-font-smoothing: auto +-webkit-highlight: none +-webkit-hyphenate-character: auto +-webkit-line-break: auto +-webkit-line-clamp: none +-webkit-locale: auto +-webkit-margin-after-collapse: collapse +-webkit-margin-before-collapse: collapse +-webkit-mask-box-image: none +-webkit-mask-box-image-outset: 0px +-webkit-mask-box-image-repeat: stretch +-webkit-mask-box-image-slice: 0 fill +-webkit-mask-box-image-source: none +-webkit-mask-box-image-width: auto +-webkit-mask-clip: border-box +-webkit-mask-composite: source-over +-webkit-mask-image: none +-webkit-mask-origin: border-box +-webkit-mask-position: 0% 0% +-webkit-mask-position-x: 0% +-webkit-mask-position-y: 0% +-webkit-mask-repeat: repeat +-webkit-mask-size: auto +-webkit-print-color-adjust: economy +-webkit-rtl-ordering: logical +-webkit-text-combine: none +-webkit-text-decorations-in-effect: none +-webkit-text-emphasis-color: rgb(0, 0, 0) +-webkit-text-emphasis-position: over +-webkit-text-emphasis-style: none +-webkit-text-fill-color: rgb(0, 0, 0) +-webkit-text-orientation: vertical-right +-webkit-text-security: none +-webkit-text-stroke-color: rgb(0, 0, 0) +-webkit-text-stroke-width: 0px +-webkit-user-drag: auto +-webkit-user-modify: read-only +-webkit-user-select: text +-webkit-writing-mode: horizontal-tb +align-content: normal +align-items: start +align-self: start +alignment-baseline: auto +animation-delay: 0s +animation-direction: normal +animation-duration: 0s +animation-fill-mode: none +animation-iteration-count: 1 +animation-name: none +animation-play-state: running +animation-timing-function: ease +backdrop-filter: none +backface-visibility: visible +background-attachment: scroll +background-blend-mode: normal +background-clip: border-box +background-color: rgba(0, 0, 0, 0) +background-image: none +background-origin: padding-box +background-position: 0% 0% +background-position-x: 0% +background-position-y: 0% +background-repeat: repeat +background-size: auto +baseline-shift: 0px +border-bottom-color: rgb(0, 0, 0) +border-bottom-left-radius: 0px +border-bottom-right-radius: 0px +border-bottom-style: none +border-bottom-width: 0px +border-collapse: separate +border-image-outset: 0px +border-image-repeat: stretch +border-image-slice: 100% +border-image-source: none +border-image-width: 1 +border-left-color: rgb(0, 0, 0) +border-left-style: none +border-left-width: 0px +border-right-color: rgb(0, 0, 0) +border-right-style: none +border-right-width: 0px +border-spacing: 0px 0px +border-top-color: rgb(0, 0, 0) +border-top-left-radius: 0px +border-top-right-radius: 0px +border-top-style: none +border-top-width: 0px +bottom: auto +box-shadow: none +box-sizing: content-box +break-after: auto +break-before: auto +break-inside: auto +buffered-rendering: auto +caption-side: top +clear: none +clip: auto +clip-path: none +clip-rule: nonzero +color: rgb(0, 0, 0) +color-interpolation: sRGB +color-interpolation-filters: linearRGB +color-rendering: auto +column-count: auto +column-gap: normal +column-rule-color: rgb(0, 0, 0) +column-rule-style: none +column-rule-width: 0px +column-span: none +column-width: auto +content: normal +cursor: auto +cx: 0px +cy: 0px +d: none +direction: ltr +display: block +dominant-baseline: auto +empty-cells: show +fill: rgb(0, 0, 0) +fill-opacity: 1 +fill-rule: nonzero +filter: none +flex-basis: auto +flex-direction: row +flex-grow: 0 +flex-shrink: 1 +flex-wrap: nowrap +float: none +flood-color: rgb(0, 0, 0) +flood-opacity: 1 +font-kerning: auto +font-size: 16px +font-size-adjust: none +font-stretch: normal +font-style: normal +font-variant: normal +font-variant-ligatures: normal +font-weight: normal +grid-auto-columns: auto +grid-auto-flow: row +grid-auto-rows: auto +grid-column-end: auto +grid-column-gap: 0px +grid-column-start: auto +grid-row-end: auto +grid-row-gap: 0px +grid-row-start: auto +grid-template-areas: none +grid-template-columns: none +grid-template-rows: none +height: 0px +image-orientation: 0deg +image-rendering: auto +isolation: auto +justify-content: normal +justify-items: start +justify-self: start +left: auto +letter-spacing: normal +lighting-color: rgb(255, 255, 255) +line-height: normal +list-style-image: none +list-style-position: outside +list-style-type: disc +margin-bottom: 0px +margin-left: 0px +margin-right: 0px +margin-top: 0px +marker-end: none +marker-mid: none +marker-start: none +mask: none +mask-source-type: alpha +mask-type: luminance +max-height: none +max-width: none +min-height: 0px +min-width: 0px +mix-blend-mode: normal +motion-offset: 0px +motion-path: none +motion-rotation: auto 0deg +object-fit: fill +object-position: 50% 50% +opacity: 1 +order: 0 +orphans: auto +outline-color: rgb(0, 0, 0) +outline-offset: 0px +outline-style: none +outline-width: 0px +overflow: visible +overflow-wrap: normal +overflow-x: visible +overflow-y: visible +padding-bottom: 0px +padding-left: 0px +padding-right: 0px +padding-top: 0px +paint-order: fill stroke markers +perspective: none +perspective-origin: 384.5px 0px +pointer-events: auto +position: static +r: 0px +resize: none +right: auto +rotate: 0deg +rx: 0px +ry: 0px +scale: 1 +scroll-behavior: auto +scroll-snap-coordinate: none +scroll-snap-destination: 0px 0px +scroll-snap-points-x: none +scroll-snap-points-y: none +scroll-snap-type: none +shape-image-threshold: 0 +shape-margin: 0px +shape-outside: none +shape-rendering: auto +snap-height: 0px +speak: normal +stop-color: rgb(0, 0, 0) +stop-opacity: 1 +stroke: none +stroke-dasharray: none +stroke-dashoffset: 0px +stroke-linecap: butt +stroke-linejoin: miter +stroke-miterlimit: 4 +stroke-opacity: 1 +stroke-width: 1px +tab-size: 8 +table-layout: auto +text-align: start +text-align-last: auto +text-anchor: start +text-decoration: none solid rgb(0, 0, 0) +text-decoration-color: rgb(0, 0, 0) +text-decoration-line: none +text-decoration-style: solid +text-indent: 0px +text-justify: auto +text-overflow: clip +text-rendering: auto +text-shadow: none +text-transform: none +text-underline-position: auto +top: auto +touch-action: auto +transform: none +transform-origin: 384.5px 0px +transform-style: flat +transition-delay: 0s +transition-duration: 0s +transition-property: all +transition-timing-function: ease +translate: 0px +unicode-bidi: normal +vector-effect: none +vertical-align: baseline +visibility: visible +white-space: normal +widows: 1 +width: 769px +will-change: auto +word-break: normal +word-spacing: 0px +word-wrap: normal +writing-mode: horizontal-tb +x: 0px +y: 0px +z-index: auto +zoom: 1 +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/platform/android/fast/css/getComputedStyle/computed-style-without-renderer-listing-expected.txt b/third_party/WebKit/LayoutTests/platform/android/fast/css/getComputedStyle/computed-style-without-renderer-listing-expected.txt new file mode 100644 index 0000000..badbd6b --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/android/fast/css/getComputedStyle/computed-style-without-renderer-listing-expected.txt
@@ -0,0 +1,305 @@ +This test documents all computed styles on a display: none element. + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +-webkit-app-region: no-drag +-webkit-appearance: none +-webkit-background-clip: border-box +-webkit-background-origin: padding-box +-webkit-border-horizontal-spacing: 0px +-webkit-border-image: none +-webkit-border-vertical-spacing: 0px +-webkit-box-align: stretch +-webkit-box-decoration-break: slice +-webkit-box-direction: normal +-webkit-box-flex: 0 +-webkit-box-flex-group: 1 +-webkit-box-lines: single +-webkit-box-ordinal-group: 1 +-webkit-box-orient: horizontal +-webkit-box-pack: start +-webkit-box-reflect: none +-webkit-clip-path: none +-webkit-filter: none +-webkit-font-smoothing: auto +-webkit-highlight: none +-webkit-hyphenate-character: auto +-webkit-line-break: auto +-webkit-line-clamp: none +-webkit-locale: auto +-webkit-margin-after-collapse: collapse +-webkit-margin-before-collapse: collapse +-webkit-mask-box-image: none +-webkit-mask-box-image-outset: 0px +-webkit-mask-box-image-repeat: stretch +-webkit-mask-box-image-slice: 0 fill +-webkit-mask-box-image-source: none +-webkit-mask-box-image-width: auto +-webkit-mask-clip: border-box +-webkit-mask-composite: source-over +-webkit-mask-image: none +-webkit-mask-origin: border-box +-webkit-mask-position: 0% 0% +-webkit-mask-position-x: 0% +-webkit-mask-position-y: 0% +-webkit-mask-repeat: repeat +-webkit-mask-size: auto +-webkit-print-color-adjust: economy +-webkit-rtl-ordering: logical +-webkit-text-combine: none +-webkit-text-decorations-in-effect: none +-webkit-text-emphasis-color: rgb(0, 0, 0) +-webkit-text-emphasis-position: over +-webkit-text-emphasis-style: none +-webkit-text-fill-color: rgb(0, 0, 0) +-webkit-text-orientation: vertical-right +-webkit-text-security: none +-webkit-text-stroke-color: rgb(0, 0, 0) +-webkit-text-stroke-width: 0px +-webkit-user-drag: auto +-webkit-user-modify: read-only +-webkit-user-select: text +-webkit-writing-mode: horizontal-tb +align-content: normal +align-items: start +align-self: start +alignment-baseline: auto +animation-delay: 0s +animation-direction: normal +animation-duration: 0s +animation-fill-mode: none +animation-iteration-count: 1 +animation-name: none +animation-play-state: running +animation-timing-function: ease +backdrop-filter: none +backface-visibility: visible +background-attachment: scroll +background-blend-mode: normal +background-clip: border-box +background-color: rgba(0, 0, 0, 0) +background-image: none +background-origin: padding-box +background-position: 0% 0% +background-position-x: 0% +background-position-y: 0% +background-repeat: repeat +background-size: auto +baseline-shift: 0px +border-bottom-color: rgb(0, 0, 0) +border-bottom-left-radius: 0px +border-bottom-right-radius: 0px +border-bottom-style: none +border-bottom-width: 0px +border-collapse: separate +border-image-outset: 0px +border-image-repeat: stretch +border-image-slice: 100% +border-image-source: none +border-image-width: 1 +border-left-color: rgb(0, 0, 0) +border-left-style: none +border-left-width: 0px +border-right-color: rgb(0, 0, 0) +border-right-style: none +border-right-width: 0px +border-spacing: 0px 0px +border-top-color: rgb(0, 0, 0) +border-top-left-radius: 0px +border-top-right-radius: 0px +border-top-style: none +border-top-width: 0px +bottom: auto +box-shadow: none +box-sizing: content-box +break-after: auto +break-before: auto +break-inside: auto +buffered-rendering: auto +caption-side: top +clear: none +clip: auto +clip-path: none +clip-rule: nonzero +color: rgb(0, 0, 0) +color-interpolation: sRGB +color-interpolation-filters: linearRGB +color-rendering: auto +column-count: auto +column-gap: normal +column-rule-color: rgb(0, 0, 0) +column-rule-style: none +column-rule-width: 0px +column-span: none +column-width: auto +content: normal +cursor: auto +cx: 0px +cy: 0px +d: none +direction: ltr +display: none +dominant-baseline: auto +empty-cells: show +fill: rgb(0, 0, 0) +fill-opacity: 1 +fill-rule: nonzero +filter: none +flex-basis: auto +flex-direction: row +flex-grow: 0 +flex-shrink: 1 +flex-wrap: nowrap +float: none +flood-color: rgb(0, 0, 0) +flood-opacity: 1 +font-kerning: auto +font-size: 16px +font-size-adjust: none +font-stretch: normal +font-style: normal +font-variant: normal +font-variant-ligatures: normal +font-weight: normal +grid-auto-columns: auto +grid-auto-flow: row +grid-auto-rows: auto +grid-column-end: auto +grid-column-gap: 0px +grid-column-start: auto +grid-row-end: auto +grid-row-gap: 0px +grid-row-start: auto +grid-template-areas: none +grid-template-columns: none +grid-template-rows: none +height: auto +image-orientation: 0deg +image-rendering: auto +isolation: auto +justify-content: normal +justify-items: start +justify-self: start +left: auto +letter-spacing: normal +lighting-color: rgb(255, 255, 255) +line-height: normal +list-style-image: none +list-style-position: outside +list-style-type: disc +margin-bottom: 0px +margin-left: 0px +margin-right: 0px +margin-top: 0px +marker-end: none +marker-mid: none +marker-start: none +mask: none +mask-source-type: alpha +mask-type: luminance +max-height: none +max-width: none +min-height: 0px +min-width: 0px +mix-blend-mode: normal +motion-offset: 0px +motion-path: none +motion-rotation: auto 0deg +object-fit: fill +object-position: 50% 50% +opacity: 1 +order: 0 +orphans: auto +outline-color: rgb(0, 0, 0) +outline-offset: 0px +outline-style: none +outline-width: 0px +overflow: visible +overflow-wrap: normal +overflow-x: visible +overflow-y: visible +padding-bottom: 0px +padding-left: 0px +padding-right: 0px +padding-top: 0px +paint-order: fill stroke markers +perspective: none +perspective-origin: 50% 50% +pointer-events: auto +position: static +r: 0px +resize: none +right: auto +rotate: 0deg +rx: 0px +ry: 0px +scale: 1 +scroll-behavior: auto +scroll-snap-coordinate: none +scroll-snap-destination: 0px 0px +scroll-snap-points-x: none +scroll-snap-points-y: none +scroll-snap-type: none +shape-image-threshold: 0 +shape-margin: 0px +shape-outside: none +shape-rendering: auto +snap-height: 0px +speak: normal +stop-color: rgb(0, 0, 0) +stop-opacity: 1 +stroke: none +stroke-dasharray: none +stroke-dashoffset: 0px +stroke-linecap: butt +stroke-linejoin: miter +stroke-miterlimit: 4 +stroke-opacity: 1 +stroke-width: 1px +tab-size: 8 +table-layout: auto +text-align: start +text-align-last: auto +text-anchor: start +text-decoration: none solid rgb(0, 0, 0) +text-decoration-color: rgb(0, 0, 0) +text-decoration-line: none +text-decoration-style: solid +text-indent: 0px +text-justify: auto +text-overflow: clip +text-rendering: auto +text-shadow: none +text-transform: none +text-underline-position: auto +top: auto +touch-action: auto +transform: none +transform-origin: 50% 50% +transform-style: flat +transition-delay: 0s +transition-duration: 0s +transition-property: all +transition-timing-function: ease +translate: 0px +unicode-bidi: normal +vector-effect: none +vertical-align: baseline +visibility: visible +white-space: normal +widows: 1 +width: auto +will-change: auto +word-break: normal +word-spacing: 0px +word-wrap: normal +writing-mode: horizontal-tb +x: 0px +y: 0px +z-index: auto +zoom: 1 +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/platform/android/svg/css/getComputedStyle-listing-expected.txt b/third_party/WebKit/LayoutTests/platform/android/svg/css/getComputedStyle-listing-expected.txt new file mode 100644 index 0000000..4726e9b --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/android/svg/css/getComputedStyle-listing-expected.txt
@@ -0,0 +1,305 @@ +This test documents all computed styles on an SVG rect element. + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +-webkit-app-region: no-drag +-webkit-appearance: none +-webkit-background-clip: border-box +-webkit-background-origin: padding-box +-webkit-border-horizontal-spacing: 0px +-webkit-border-image: none +-webkit-border-vertical-spacing: 0px +-webkit-box-align: stretch +-webkit-box-decoration-break: slice +-webkit-box-direction: normal +-webkit-box-flex: 0 +-webkit-box-flex-group: 1 +-webkit-box-lines: single +-webkit-box-ordinal-group: 1 +-webkit-box-orient: horizontal +-webkit-box-pack: start +-webkit-box-reflect: none +-webkit-clip-path: none +-webkit-filter: none +-webkit-font-smoothing: auto +-webkit-highlight: none +-webkit-hyphenate-character: auto +-webkit-line-break: auto +-webkit-line-clamp: none +-webkit-locale: auto +-webkit-margin-after-collapse: collapse +-webkit-margin-before-collapse: collapse +-webkit-mask-box-image: none +-webkit-mask-box-image-outset: 0px +-webkit-mask-box-image-repeat: stretch +-webkit-mask-box-image-slice: 0 fill +-webkit-mask-box-image-source: none +-webkit-mask-box-image-width: auto +-webkit-mask-clip: border-box +-webkit-mask-composite: source-over +-webkit-mask-image: none +-webkit-mask-origin: border-box +-webkit-mask-position: 0% 0% +-webkit-mask-position-x: 0% +-webkit-mask-position-y: 0% +-webkit-mask-repeat: repeat +-webkit-mask-size: auto +-webkit-print-color-adjust: economy +-webkit-rtl-ordering: logical +-webkit-text-combine: none +-webkit-text-decorations-in-effect: none +-webkit-text-emphasis-color: rgb(0, 0, 0) +-webkit-text-emphasis-position: over +-webkit-text-emphasis-style: none +-webkit-text-fill-color: rgb(0, 0, 0) +-webkit-text-orientation: vertical-right +-webkit-text-security: none +-webkit-text-stroke-color: rgb(0, 0, 0) +-webkit-text-stroke-width: 0px +-webkit-user-drag: auto +-webkit-user-modify: read-only +-webkit-user-select: text +-webkit-writing-mode: horizontal-tb +align-content: normal +align-items: start +align-self: start +alignment-baseline: auto +animation-delay: 0s +animation-direction: normal +animation-duration: 0s +animation-fill-mode: none +animation-iteration-count: 1 +animation-name: none +animation-play-state: running +animation-timing-function: ease +backdrop-filter: none +backface-visibility: visible +background-attachment: scroll +background-blend-mode: normal +background-clip: border-box +background-color: rgba(0, 0, 0, 0) +background-image: none +background-origin: padding-box +background-position: 0% 0% +background-position-x: 0% +background-position-y: 0% +background-repeat: repeat +background-size: auto +baseline-shift: 0px +border-bottom-color: rgb(0, 0, 0) +border-bottom-left-radius: 0px +border-bottom-right-radius: 0px +border-bottom-style: none +border-bottom-width: 0px +border-collapse: separate +border-image-outset: 0px +border-image-repeat: stretch +border-image-slice: 100% +border-image-source: none +border-image-width: 1 +border-left-color: rgb(0, 0, 0) +border-left-style: none +border-left-width: 0px +border-right-color: rgb(0, 0, 0) +border-right-style: none +border-right-width: 0px +border-spacing: 0px 0px +border-top-color: rgb(0, 0, 0) +border-top-left-radius: 0px +border-top-right-radius: 0px +border-top-style: none +border-top-width: 0px +bottom: auto +box-shadow: none +box-sizing: content-box +break-after: auto +break-before: auto +break-inside: auto +buffered-rendering: auto +caption-side: top +clear: none +clip: auto +clip-path: none +clip-rule: nonzero +color: rgb(0, 0, 0) +color-interpolation: sRGB +color-interpolation-filters: linearRGB +color-rendering: auto +column-count: auto +column-gap: normal +column-rule-color: rgb(0, 0, 0) +column-rule-style: none +column-rule-width: 0px +column-span: none +column-width: auto +content: normal +cursor: auto +cx: 0px +cy: 0px +d: none +direction: ltr +display: inline +dominant-baseline: auto +empty-cells: show +fill: rgb(0, 128, 0) +fill-opacity: 1 +fill-rule: nonzero +filter: none +flex-basis: auto +flex-direction: row +flex-grow: 0 +flex-shrink: 1 +flex-wrap: nowrap +float: none +flood-color: rgb(0, 0, 0) +flood-opacity: 1 +font-kerning: auto +font-size: 16px +font-size-adjust: none +font-stretch: normal +font-style: normal +font-variant: normal +font-variant-ligatures: normal +font-weight: normal +grid-auto-columns: auto +grid-auto-flow: row +grid-auto-rows: auto +grid-column-end: auto +grid-column-gap: 0px +grid-column-start: auto +grid-row-end: auto +grid-row-gap: 0px +grid-row-start: auto +grid-template-areas: none +grid-template-columns: none +grid-template-rows: none +height: auto +image-orientation: 0deg +image-rendering: auto +isolation: auto +justify-content: normal +justify-items: start +justify-self: start +left: auto +letter-spacing: normal +lighting-color: rgb(255, 255, 255) +line-height: normal +list-style-image: none +list-style-position: outside +list-style-type: disc +margin-bottom: 0px +margin-left: 0px +margin-right: 0px +margin-top: 0px +marker-end: none +marker-mid: none +marker-start: none +mask: none +mask-source-type: alpha +mask-type: luminance +max-height: none +max-width: none +min-height: 0px +min-width: 0px +mix-blend-mode: normal +motion-offset: 0px +motion-path: none +motion-rotation: auto 0deg +object-fit: fill +object-position: 50% 50% +opacity: 1 +order: 0 +orphans: auto +outline-color: rgb(0, 0, 0) +outline-offset: 0px +outline-style: none +outline-width: 0px +overflow: visible +overflow-wrap: normal +overflow-x: visible +overflow-y: visible +padding-bottom: 0px +padding-left: 0px +padding-right: 0px +padding-top: 0px +paint-order: fill stroke markers +perspective: none +perspective-origin: 0px 0px +pointer-events: auto +position: static +r: 0px +resize: none +right: auto +rotate: 0deg +rx: 0px +ry: 0px +scale: 1 +scroll-behavior: auto +scroll-snap-coordinate: none +scroll-snap-destination: 0px 0px +scroll-snap-points-x: none +scroll-snap-points-y: none +scroll-snap-type: none +shape-image-threshold: 0 +shape-margin: 0px +shape-outside: none +shape-rendering: auto +snap-height: 0px +speak: normal +stop-color: rgb(0, 0, 0) +stop-opacity: 1 +stroke: none +stroke-dasharray: none +stroke-dashoffset: 0px +stroke-linecap: butt +stroke-linejoin: miter +stroke-miterlimit: 4 +stroke-opacity: 1 +stroke-width: 1px +tab-size: 8 +table-layout: auto +text-align: start +text-align-last: auto +text-anchor: start +text-decoration: none solid rgb(0, 0, 0) +text-decoration-color: rgb(0, 0, 0) +text-decoration-line: none +text-decoration-style: solid +text-indent: 0px +text-justify: auto +text-overflow: clip +text-rendering: auto +text-shadow: none +text-transform: none +text-underline-position: auto +top: auto +touch-action: auto +transform: none +transform-origin: 0px 0px +transform-style: flat +transition-delay: 0s +transition-duration: 0s +transition-property: all +transition-timing-function: ease +translate: 0px +unicode-bidi: normal +vector-effect: none +vertical-align: baseline +visibility: visible +white-space: normal +widows: 1 +width: auto +will-change: auto +word-break: normal +word-spacing: 0px +word-wrap: normal +writing-mode: horizontal-tb +x: 0px +y: 0px +z-index: auto +zoom: 1 +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/platform/android/virtual/stable/webexposed/css-properties-as-js-properties-expected.txt b/third_party/WebKit/LayoutTests/platform/android/virtual/stable/webexposed/css-properties-as-js-properties-expected.txt new file mode 100644 index 0000000..96e5586 --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/android/virtual/stable/webexposed/css-properties-as-js-properties-expected.txt
@@ -0,0 +1,372 @@ +This test (crudely) documents Blink's web-exposed CSS properties. All changes to this list should go through Blink's feature review process: http://www.chromium.org/blink#new-features + +alignContent +alignItems +alignSelf +alignmentBaseline +all +animation +animationDelay +animationDirection +animationDuration +animationFillMode +animationIterationCount +animationName +animationPlayState +animationTimingFunction +backfaceVisibility +background +backgroundAttachment +backgroundBlendMode +backgroundClip +backgroundColor +backgroundImage +backgroundOrigin +backgroundPosition +backgroundPositionX +backgroundPositionY +backgroundRepeat +backgroundRepeatX +backgroundRepeatY +backgroundSize +baselineShift +border +borderBottom +borderBottomColor +borderBottomLeftRadius +borderBottomRightRadius +borderBottomStyle +borderBottomWidth +borderCollapse +borderColor +borderImage +borderImageOutset +borderImageRepeat +borderImageSlice +borderImageSource +borderImageWidth +borderLeft +borderLeftColor +borderLeftStyle +borderLeftWidth +borderRadius +borderRight +borderRightColor +borderRightStyle +borderRightWidth +borderSpacing +borderStyle +borderTop +borderTopColor +borderTopLeftRadius +borderTopRightRadius +borderTopStyle +borderTopWidth +borderWidth +bottom +boxShadow +boxSizing +breakAfter +breakBefore +breakInside +bufferedRendering +captionSide +clear +clip +clipPath +clipRule +color +colorInterpolation +colorInterpolationFilters +colorRendering +columnCount +columnFill +columnGap +columnRule +columnRuleColor +columnRuleStyle +columnRuleWidth +columnSpan +columnWidth +columns +content +counterIncrement +counterReset +cssFloat +cssText +cursor +cx +cy +direction +display +dominantBaseline +emptyCells +fill +fillOpacity +fillRule +filter +flex +flexBasis +flexDirection +flexFlow +flexGrow +flexShrink +flexWrap +float +floodColor +floodOpacity +font +fontFamily +fontFeatureSettings +fontKerning +fontSize +fontStretch +fontStyle +fontVariant +fontVariantLigatures +fontWeight +getPropertyPriority +getPropertyValue +height +imageRendering +isolation +item +justifyContent +left +length +letterSpacing +lightingColor +lineHeight +listStyle +listStyleImage +listStylePosition +listStyleType +margin +marginBottom +marginLeft +marginRight +marginTop +marker +markerEnd +markerMid +markerStart +mask +maskType +maxHeight +maxWidth +maxZoom +minHeight +minWidth +minZoom +mixBlendMode +motion +motionOffset +motionPath +motionRotation +objectFit +objectPosition +opacity +order +orientation +orphans +outline +outlineColor +outlineOffset +outlineStyle +outlineWidth +overflow +overflowWrap +overflowX +overflowY +padding +paddingBottom +paddingLeft +paddingRight +paddingTop +page +pageBreakAfter +pageBreakBefore +pageBreakInside +paintOrder +parentRule +perspective +perspectiveOrigin +pointerEvents +position +quotes +r +removeProperty +resize +right +rx +ry +setProperty +shapeImageThreshold +shapeMargin +shapeOutside +shapeRendering +size +speak +src +stopColor +stopOpacity +stroke +strokeDasharray +strokeDashoffset +strokeLinecap +strokeLinejoin +strokeMiterlimit +strokeOpacity +strokeWidth +tabSize +tableLayout +textAlign +textAlignLast +textAnchor +textCombineUpright +textDecoration +textIndent +textOrientation +textOverflow +textRendering +textShadow +textTransform +top +touchAction +transform +transformOrigin +transformStyle +transition +transitionDelay +transitionDuration +transitionProperty +transitionTimingFunction +unicodeBidi +unicodeRange +userZoom +vectorEffect +verticalAlign +visibility +webkitAppRegion +webkitAppearance +webkitBackgroundClip +webkitBackgroundOrigin +webkitBorderAfter +webkitBorderAfterColor +webkitBorderAfterStyle +webkitBorderAfterWidth +webkitBorderBefore +webkitBorderBeforeColor +webkitBorderBeforeStyle +webkitBorderBeforeWidth +webkitBorderEnd +webkitBorderEndColor +webkitBorderEndStyle +webkitBorderEndWidth +webkitBorderHorizontalSpacing +webkitBorderImage +webkitBorderStart +webkitBorderStartColor +webkitBorderStartStyle +webkitBorderStartWidth +webkitBorderVerticalSpacing +webkitBoxAlign +webkitBoxDecorationBreak +webkitBoxDirection +webkitBoxFlex +webkitBoxFlexGroup +webkitBoxLines +webkitBoxOrdinalGroup +webkitBoxOrient +webkitBoxPack +webkitBoxReflect +webkitClipPath +webkitColumnBreakAfter +webkitColumnBreakBefore +webkitColumnBreakInside +webkitFilter +webkitFontSizeDelta +webkitFontSmoothing +webkitHighlight +webkitHyphenateCharacter +webkitLineBreak +webkitLineClamp +webkitLocale +webkitLogicalHeight +webkitLogicalWidth +webkitMarginAfter +webkitMarginAfterCollapse +webkitMarginBefore +webkitMarginBeforeCollapse +webkitMarginBottomCollapse +webkitMarginCollapse +webkitMarginEnd +webkitMarginStart +webkitMarginTopCollapse +webkitMask +webkitMaskBoxImage +webkitMaskBoxImageOutset +webkitMaskBoxImageRepeat +webkitMaskBoxImageSlice +webkitMaskBoxImageSource +webkitMaskBoxImageWidth +webkitMaskClip +webkitMaskComposite +webkitMaskImage +webkitMaskOrigin +webkitMaskPosition +webkitMaskPositionX +webkitMaskPositionY +webkitMaskRepeat +webkitMaskRepeatX +webkitMaskRepeatY +webkitMaskSize +webkitMaxLogicalHeight +webkitMaxLogicalWidth +webkitMinLogicalHeight +webkitMinLogicalWidth +webkitPaddingAfter +webkitPaddingBefore +webkitPaddingEnd +webkitPaddingStart +webkitPerspectiveOriginX +webkitPerspectiveOriginY +webkitPrintColorAdjust +webkitRtlOrdering +webkitRubyPosition +webkitTapHighlightColor +webkitTextCombine +webkitTextDecorationsInEffect +webkitTextEmphasis +webkitTextEmphasisColor +webkitTextEmphasisPosition +webkitTextEmphasisStyle +webkitTextFillColor +webkitTextOrientation +webkitTextSecurity +webkitTextStroke +webkitTextStrokeColor +webkitTextStrokeWidth +webkitTransformOriginX +webkitTransformOriginY +webkitTransformOriginZ +webkitUserDrag +webkitUserModify +webkitUserSelect +webkitWritingMode +whiteSpace +widows +width +willChange +wordBreak +wordSpacing +wordWrap +writingMode +x +y +zIndex +zoom +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/platform/android/webexposed/css-properties-as-js-properties-expected.txt b/third_party/WebKit/LayoutTests/platform/android/webexposed/css-properties-as-js-properties-expected.txt new file mode 100644 index 0000000..7f7f25e --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/android/webexposed/css-properties-as-js-properties-expected.txt
@@ -0,0 +1,414 @@ +This test (crudely) documents Blink's web-exposed CSS properties. All changes to this list should go through Blink's feature review process: http://www.chromium.org/blink#new-features + +alignContent +alignItems +alignSelf +alignmentBaseline +all +animation +animationDelay +animationDirection +animationDuration +animationFillMode +animationIterationCount +animationName +animationPlayState +animationTimingFunction +backdropFilter +backfaceVisibility +background +backgroundAttachment +backgroundBlendMode +backgroundClip +backgroundColor +backgroundImage +backgroundOrigin +backgroundPosition +backgroundPositionX +backgroundPositionY +backgroundRepeat +backgroundRepeatX +backgroundRepeatY +backgroundSize +baselineShift +border +borderBottom +borderBottomColor +borderBottomLeftRadius +borderBottomRightRadius +borderBottomStyle +borderBottomWidth +borderCollapse +borderColor +borderImage +borderImageOutset +borderImageRepeat +borderImageSlice +borderImageSource +borderImageWidth +borderLeft +borderLeftColor +borderLeftStyle +borderLeftWidth +borderRadius +borderRight +borderRightColor +borderRightStyle +borderRightWidth +borderSpacing +borderStyle +borderTop +borderTopColor +borderTopLeftRadius +borderTopRightRadius +borderTopStyle +borderTopWidth +borderWidth +bottom +boxShadow +boxSizing +breakAfter +breakBefore +breakInside +bufferedRendering +captionSide +clear +clip +clipPath +clipRule +color +colorInterpolation +colorInterpolationFilters +colorRendering +columnCount +columnFill +columnGap +columnRule +columnRuleColor +columnRuleStyle +columnRuleWidth +columnSpan +columnWidth +columns +contain +content +counterIncrement +counterReset +cssFloat +cssText +cursor +cx +cy +d +direction +display +dominantBaseline +emptyCells +fill +fillOpacity +fillRule +filter +flex +flexBasis +flexDirection +flexFlow +flexGrow +flexShrink +flexWrap +float +floodColor +floodOpacity +font +fontDisplay +fontFamily +fontFeatureSettings +fontKerning +fontSize +fontSizeAdjust +fontStretch +fontStyle +fontVariant +fontVariantLigatures +fontWeight +getPropertyPriority +getPropertyValue +grid +gridArea +gridAutoColumns +gridAutoFlow +gridAutoRows +gridColumn +gridColumnEnd +gridColumnGap +gridColumnStart +gridGap +gridRow +gridRowEnd +gridRowGap +gridRowStart +gridTemplate +gridTemplateAreas +gridTemplateColumns +gridTemplateRows +height +imageOrientation +imageRendering +isolation +item +justifyContent +justifyItems +justifySelf +left +length +letterSpacing +lightingColor +lineHeight +listStyle +listStyleImage +listStylePosition +listStyleType +margin +marginBottom +marginLeft +marginRight +marginTop +marker +markerEnd +markerMid +markerStart +mask +maskSourceType +maskType +maxHeight +maxWidth +maxZoom +minHeight +minWidth +minZoom +mixBlendMode +motion +motionOffset +motionPath +motionRotation +objectFit +objectPosition +opacity +order +orientation +orphans +outline +outlineColor +outlineOffset +outlineStyle +outlineWidth +overflow +overflowWrap +overflowX +overflowY +padding +paddingBottom +paddingLeft +paddingRight +paddingTop +page +pageBreakAfter +pageBreakBefore +pageBreakInside +paintOrder +parentRule +perspective +perspectiveOrigin +pointerEvents +position +quotes +r +removeProperty +resize +right +rotate +rx +ry +scale +scrollBehavior +scrollSnapCoordinate +scrollSnapDestination +scrollSnapPointsX +scrollSnapPointsY +scrollSnapType +setProperty +shapeImageThreshold +shapeMargin +shapeOutside +shapeRendering +size +snapHeight +speak +src +stopColor +stopOpacity +stroke +strokeDasharray +strokeDashoffset +strokeLinecap +strokeLinejoin +strokeMiterlimit +strokeOpacity +strokeWidth +tabSize +tableLayout +textAlign +textAlignLast +textAnchor +textCombineUpright +textDecoration +textDecorationColor +textDecorationLine +textDecorationStyle +textIndent +textJustify +textOrientation +textOverflow +textRendering +textShadow +textTransform +textUnderlinePosition +top +touchAction +transform +transformOrigin +transformStyle +transition +transitionDelay +transitionDuration +transitionProperty +transitionTimingFunction +translate +unicodeBidi +unicodeRange +userZoom +vectorEffect +verticalAlign +visibility +webkitAppRegion +webkitAppearance +webkitBackgroundClip +webkitBackgroundOrigin +webkitBorderAfter +webkitBorderAfterColor +webkitBorderAfterStyle +webkitBorderAfterWidth +webkitBorderBefore +webkitBorderBeforeColor +webkitBorderBeforeStyle +webkitBorderBeforeWidth +webkitBorderEnd +webkitBorderEndColor +webkitBorderEndStyle +webkitBorderEndWidth +webkitBorderHorizontalSpacing +webkitBorderImage +webkitBorderStart +webkitBorderStartColor +webkitBorderStartStyle +webkitBorderStartWidth +webkitBorderVerticalSpacing +webkitBoxAlign +webkitBoxDecorationBreak +webkitBoxDirection +webkitBoxFlex +webkitBoxFlexGroup +webkitBoxLines +webkitBoxOrdinalGroup +webkitBoxOrient +webkitBoxPack +webkitBoxReflect +webkitClipPath +webkitColumnBreakAfter +webkitColumnBreakBefore +webkitColumnBreakInside +webkitFilter +webkitFontSizeDelta +webkitFontSmoothing +webkitHighlight +webkitHyphenateCharacter +webkitLineBreak +webkitLineClamp +webkitLocale +webkitLogicalHeight +webkitLogicalWidth +webkitMarginAfter +webkitMarginAfterCollapse +webkitMarginBefore +webkitMarginBeforeCollapse +webkitMarginBottomCollapse +webkitMarginCollapse +webkitMarginEnd +webkitMarginStart +webkitMarginTopCollapse +webkitMask +webkitMaskBoxImage +webkitMaskBoxImageOutset +webkitMaskBoxImageRepeat +webkitMaskBoxImageSlice +webkitMaskBoxImageSource +webkitMaskBoxImageWidth +webkitMaskClip +webkitMaskComposite +webkitMaskImage +webkitMaskOrigin +webkitMaskPosition +webkitMaskPositionX +webkitMaskPositionY +webkitMaskRepeat +webkitMaskRepeatX +webkitMaskRepeatY +webkitMaskSize +webkitMaxLogicalHeight +webkitMaxLogicalWidth +webkitMinLogicalHeight +webkitMinLogicalWidth +webkitPaddingAfter +webkitPaddingBefore +webkitPaddingEnd +webkitPaddingStart +webkitPerspectiveOriginX +webkitPerspectiveOriginY +webkitPrintColorAdjust +webkitRtlOrdering +webkitRubyPosition +webkitTapHighlightColor +webkitTextCombine +webkitTextDecorationsInEffect +webkitTextEmphasis +webkitTextEmphasisColor +webkitTextEmphasisPosition +webkitTextEmphasisStyle +webkitTextFillColor +webkitTextOrientation +webkitTextSecurity +webkitTextStroke +webkitTextStrokeColor +webkitTextStrokeWidth +webkitTransformOriginX +webkitTransformOriginY +webkitTransformOriginZ +webkitUserDrag +webkitUserModify +webkitUserSelect +webkitWritingMode +whiteSpace +widows +width +willChange +wordBreak +wordSpacing +wordWrap +writingMode +x +y +zIndex +zoom +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/svg/css/getComputedStyle-listing-expected.txt b/third_party/WebKit/LayoutTests/svg/css/getComputedStyle-listing-expected.txt index 4726e9b..7cab910 100644 --- a/third_party/WebKit/LayoutTests/svg/css/getComputedStyle-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/svg/css/getComputedStyle-listing-expected.txt
@@ -160,6 +160,7 @@ font-stretch: normal font-style: normal font-variant: normal +font-variant-caps: normal font-variant-ligatures: normal font-weight: normal grid-auto-columns: auto
diff --git a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/css-properties-as-js-properties-expected.txt b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/css-properties-as-js-properties-expected.txt index 96e5586..9d3b43e 100644 --- a/third_party/WebKit/LayoutTests/virtual/stable/webexposed/css-properties-as-js-properties-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/stable/webexposed/css-properties-as-js-properties-expected.txt
@@ -123,6 +123,7 @@ fontStretch fontStyle fontVariant +fontVariantCaps fontVariantLigatures fontWeight getPropertyPriority
diff --git a/third_party/WebKit/LayoutTests/webexposed/css-properties-as-js-properties-expected.txt b/third_party/WebKit/LayoutTests/webexposed/css-properties-as-js-properties-expected.txt index 7f7f25e..67688c4a 100644 --- a/third_party/WebKit/LayoutTests/webexposed/css-properties-as-js-properties-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/css-properties-as-js-properties-expected.txt
@@ -128,6 +128,7 @@ fontStretch fontStyle fontVariant +fontVariantCaps fontVariantLigatures fontWeight getPropertyPriority
diff --git a/third_party/WebKit/Source/bindings/core/v8/CustomElementConstructorBuilder.cpp b/third_party/WebKit/Source/bindings/core/v8/CustomElementConstructorBuilder.cpp index 23714e2..a02a26c5 100644 --- a/third_party/WebKit/Source/bindings/core/v8/CustomElementConstructorBuilder.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/CustomElementConstructorBuilder.cpp
@@ -125,7 +125,7 @@ return true; } -RawPtr<CustomElementLifecycleCallbacks> CustomElementConstructorBuilder::createCallbacks() +CustomElementLifecycleCallbacks* CustomElementConstructorBuilder::createCallbacks() { ASSERT(!m_prototype.IsEmpty());
diff --git a/third_party/WebKit/Source/bindings/core/v8/CustomElementConstructorBuilder.h b/third_party/WebKit/Source/bindings/core/v8/CustomElementConstructorBuilder.h index a3655ad4..be6817a 100644 --- a/third_party/WebKit/Source/bindings/core/v8/CustomElementConstructorBuilder.h +++ b/third_party/WebKit/Source/bindings/core/v8/CustomElementConstructorBuilder.h
@@ -65,7 +65,7 @@ bool isFeatureAllowed() const; bool validateOptions(const AtomicString& type, QualifiedName& tagName, ExceptionState&); - RawPtr<CustomElementLifecycleCallbacks> createCallbacks(); + CustomElementLifecycleCallbacks* createCallbacks(); bool createConstructor(Document*, CustomElementDefinition*, ExceptionState&); bool didRegisterDefinition() const;
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScheduledAction.cpp b/third_party/WebKit/Source/bindings/core/v8/ScheduledAction.cpp index d94c8b2..fa7d16e 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScheduledAction.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScheduledAction.cpp
@@ -45,13 +45,13 @@ namespace blink { -RawPtr<ScheduledAction> ScheduledAction::create(ScriptState* scriptState, const ScriptValue& handler, const Vector<ScriptValue>& arguments) +ScheduledAction* ScheduledAction::create(ScriptState* scriptState, const ScriptValue& handler, const Vector<ScriptValue>& arguments) { ASSERT(handler.isFunction()); return new ScheduledAction(scriptState, handler, arguments); } -RawPtr<ScheduledAction> ScheduledAction::create(ScriptState* scriptState, const String& handler) +ScheduledAction* ScheduledAction::create(ScriptState* scriptState, const String& handler) { return new ScheduledAction(scriptState, handler); }
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScheduledAction.h b/third_party/WebKit/Source/bindings/core/v8/ScheduledAction.h index 816eab1a..4e9d863 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScheduledAction.h +++ b/third_party/WebKit/Source/bindings/core/v8/ScheduledAction.h
@@ -48,8 +48,8 @@ class ScheduledAction final : public GarbageCollectedFinalized<ScheduledAction> { WTF_MAKE_NONCOPYABLE(ScheduledAction); public: - static RawPtr<ScheduledAction> create(ScriptState*, const ScriptValue& handler, const Vector<ScriptValue>& arguments); - static RawPtr<ScheduledAction> create(ScriptState*, const String& handler); + static ScheduledAction* create(ScriptState*, const ScriptValue& handler, const Vector<ScriptValue>& arguments); + static ScheduledAction* create(ScriptState*, const String& handler); ~ScheduledAction(); DECLARE_TRACE();
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptController.cpp b/third_party/WebKit/Source/bindings/core/v8/ScriptController.cpp index ae4beb6a..f272198 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptController.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptController.cpp
@@ -98,11 +98,7 @@ void ScriptController::clearForClose() { - double start = currentTime(); m_windowProxyManager->clearForClose(); - double end = currentTime(); - DEFINE_STATIC_LOCAL(CustomCountHistogram, clearForCloseHistogram, ("WebCore.ScriptController.clearForClose", 0, 10000, 50)); - clearForCloseHistogram.count((end - start) * 1000); } void ScriptController::updateSecurityOrigin(SecurityOrigin* origin) @@ -255,13 +251,7 @@ { // V8 binding expects ScriptController::clearWindowProxy only be called // when a frame is loading a new page. This creates a new context for the new page. - - double start = currentTime(); - m_windowProxyManager->clearForNavigation(); - double end = currentTime(); - DEFINE_STATIC_LOCAL(CustomCountHistogram, clearWindowProxyHistogram, ("WebCore.ScriptController.clearWindowProxy", 0, 10000, 50)); - clearWindowProxyHistogram.count((end - start) * 1000); } void ScriptController::setCaptureCallStackForUncaughtExceptions(v8::Isolate* isolate, bool value)
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptController.h b/third_party/WebKit/Source/bindings/core/v8/ScriptController.h index 325ffc4..e5ae8c1 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptController.h +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptController.h
@@ -72,7 +72,7 @@ DoNotExecuteScriptWhenScriptsDisabled }; - static RawPtr<ScriptController> create(LocalFrame* frame) + static ScriptController* create(LocalFrame* frame) { return new ScriptController(frame); }
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptEventListener.cpp b/third_party/WebKit/Source/bindings/core/v8/ScriptEventListener.cpp index e080825..f491043 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptEventListener.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptEventListener.cpp
@@ -44,7 +44,7 @@ namespace blink { -RawPtr<V8LazyEventListener> createAttributeEventListener(Node* node, const QualifiedName& name, const AtomicString& value, const AtomicString& eventParameterName) +V8LazyEventListener* createAttributeEventListener(Node* node, const QualifiedName& name, const AtomicString& value, const AtomicString& eventParameterName) { ASSERT(node); if (value.isNull()) @@ -69,7 +69,7 @@ return V8LazyEventListener::create(name.localName(), eventParameterName, value, sourceURL, position, node, isolate); } -RawPtr<V8LazyEventListener> createAttributeEventListener(LocalFrame* frame, const QualifiedName& name, const AtomicString& value, const AtomicString& eventParameterName) +V8LazyEventListener* createAttributeEventListener(LocalFrame* frame, const QualifiedName& name, const AtomicString& value, const AtomicString& eventParameterName) { if (!frame) return nullptr;
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptEventListener.h b/third_party/WebKit/Source/bindings/core/v8/ScriptEventListener.h index 6abc1530..68d92b5 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptEventListener.h +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptEventListener.h
@@ -43,8 +43,8 @@ class Node; class QualifiedName; -RawPtr<V8LazyEventListener> createAttributeEventListener(Node*, const QualifiedName&, const AtomicString& value, const AtomicString& eventParameterName); -RawPtr<V8LazyEventListener> createAttributeEventListener(LocalFrame*, const QualifiedName&, const AtomicString& value, const AtomicString& eventParameterName); +V8LazyEventListener* createAttributeEventListener(Node*, const QualifiedName&, const AtomicString& value, const AtomicString& eventParameterName); +V8LazyEventListener* createAttributeEventListener(LocalFrame*, const QualifiedName&, const AtomicString& value, const AtomicString& eventParameterName); v8::Local<v8::Object> eventListenerHandler(ExecutionContext*, EventListener*); v8::Local<v8::Function> eventListenerEffectiveFunction(v8::Isolate*, v8::Local<v8::Object> handler); void getFunctionLocation(v8::Local<v8::Function>, String& scriptId, int& lineNumber, int& columnNumber);
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptPromiseResolverTest.cpp b/third_party/WebKit/Source/bindings/core/v8/ScriptPromiseResolverTest.cpp index 23f2b2a..183f0fa6 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptPromiseResolverTest.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptPromiseResolverTest.cpp
@@ -239,11 +239,11 @@ resolver = ScriptPromiseResolverKeepAlive::create(getScriptState()); } resolver->keepAliveWhilePending(); - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); ASSERT_TRUE(ScriptPromiseResolverKeepAlive::isAlive()); resolver->resolve("hello"); - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); EXPECT_FALSE(ScriptPromiseResolverKeepAlive::isAlive()); } @@ -256,11 +256,11 @@ resolver = ScriptPromiseResolverKeepAlive::create(getScriptState()); } resolver->keepAliveWhilePending(); - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); ASSERT_TRUE(ScriptPromiseResolverKeepAlive::isAlive()); resolver->reject("hello"); - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); EXPECT_FALSE(ScriptPromiseResolverKeepAlive::isAlive()); } @@ -273,11 +273,11 @@ resolver = ScriptPromiseResolverKeepAlive::create(getScriptState()); } resolver->keepAliveWhilePending(); - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); EXPECT_TRUE(ScriptPromiseResolverKeepAlive::isAlive()); getExecutionContext()->stopActiveDOMObjects(); - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); EXPECT_FALSE(ScriptPromiseResolverKeepAlive::isAlive()); } @@ -290,16 +290,16 @@ resolver = ScriptPromiseResolverKeepAlive::create(getScriptState()); } resolver->keepAliveWhilePending(); - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); ASSERT_TRUE(ScriptPromiseResolverKeepAlive::isAlive()); getExecutionContext()->suspendActiveDOMObjects(); resolver->resolve("hello"); - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); EXPECT_TRUE(ScriptPromiseResolverKeepAlive::isAlive()); getExecutionContext()->stopActiveDOMObjects(); - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); EXPECT_FALSE(ScriptPromiseResolverKeepAlive::isAlive()); }
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptSourceCode.cpp b/third_party/WebKit/Source/bindings/core/v8/ScriptSourceCode.cpp index e42fbf4..be6b8d8 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptSourceCode.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptSourceCode.cpp
@@ -34,7 +34,7 @@ treatNullSourceAsEmpty(); } -ScriptSourceCode::ScriptSourceCode(RawPtr<ScriptStreamer> streamer, ScriptResource* resource) +ScriptSourceCode::ScriptSourceCode(ScriptStreamer* streamer, ScriptResource* resource) : m_source(resource->script()) , m_resource(resource) , m_streamer(streamer)
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptSourceCode.h b/third_party/WebKit/Source/bindings/core/v8/ScriptSourceCode.h index 13143ce..0347d2eb 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptSourceCode.h +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptSourceCode.h
@@ -50,7 +50,7 @@ explicit ScriptSourceCode(ScriptResource*); ScriptSourceCode(const String&, const KURL& = KURL(), const TextPosition& startPosition = TextPosition::minimumPosition()); ScriptSourceCode(const CompressibleString&, const KURL& = KURL(), const TextPosition& startPosition = TextPosition::minimumPosition()); - ScriptSourceCode(RawPtr<ScriptStreamer>, ScriptResource*); + ScriptSourceCode(ScriptStreamer*, ScriptResource*); ~ScriptSourceCode(); DECLARE_TRACE();
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptStreamer.h b/third_party/WebKit/Source/bindings/core/v8/ScriptStreamer.h index 1dcceadb..bf02e5b7 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptStreamer.h +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptStreamer.h
@@ -98,7 +98,7 @@ // streamed. Non-const for testing. static size_t s_smallScriptThreshold; - static RawPtr<ScriptStreamer> create(PendingScript* script, Type scriptType, ScriptState* scriptState, v8::ScriptCompiler::CompileOptions compileOptions, WebTaskRunner* loadingTaskRunner) + static ScriptStreamer* create(PendingScript* script, Type scriptType, ScriptState* scriptState, v8::ScriptCompiler::CompileOptions compileOptions, WebTaskRunner* loadingTaskRunner) { return new ScriptStreamer(script, scriptType, scriptState, compileOptions, loadingTaskRunner); }
diff --git a/third_party/WebKit/Source/bindings/core/v8/ToV8.h b/third_party/WebKit/Source/bindings/core/v8/ToV8.h index 0dce33d..39ad5dd 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ToV8.h +++ b/third_party/WebKit/Source/bindings/core/v8/ToV8.h
@@ -56,7 +56,7 @@ CORE_EXPORT v8::Local<v8::Value> toV8(EventTarget*, v8::Local<v8::Object> creationContext, v8::Isolate*); v8::Local<v8::Value> toV8(WorkerOrWorkletGlobalScope*, v8::Local<v8::Object> creationContext, v8::Isolate*); -// PassRefPtr, RawPtr and RefPtr +// PassRefPtr and RefPtr template<typename T> inline v8::Local<v8::Value> toV8(PassRefPtr<T> impl, v8::Local<v8::Object> creationContext, v8::Isolate* isolate) @@ -65,12 +65,6 @@ } template<typename T> -inline v8::Local<v8::Value> toV8(RawPtr<T> impl, v8::Local<v8::Object> creationContext, v8::Isolate* isolate) -{ - return toV8(impl.get(), creationContext, isolate); -} - -template<typename T> inline v8::Local<v8::Value> toV8(const RefPtr<T>& impl, v8::Local<v8::Object> creationContext, v8::Isolate* isolate) { return toV8(impl.get(), creationContext, isolate);
diff --git a/third_party/WebKit/Source/bindings/core/v8/ToV8Test.cpp b/third_party/WebKit/Source/bindings/core/v8/ToV8Test.cpp index d43dc0d..e4ac84c 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ToV8Test.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ToV8Test.cpp
@@ -67,7 +67,6 @@ OffHeapGarbageCollectedHolder offHeapHolder(object); TEST_TOV8("world", object); - TEST_TOV8("world", RawPtr<GarbageCollectedScriptWrappable>(object)); TEST_TOV8("world", holder.m_scriptWrappable); TEST_TOV8("world", offHeapHolder.m_scriptWrappable); @@ -76,7 +75,6 @@ offHeapHolder.m_scriptWrappable = nullptr; TEST_TOV8("null", object); - TEST_TOV8("null", RawPtr<GarbageCollectedScriptWrappable>(object)); TEST_TOV8("null", holder.m_scriptWrappable); TEST_TOV8("null", offHeapHolder.m_scriptWrappable); }
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8Binding.cpp b/third_party/WebKit/Source/bindings/core/v8/V8Binding.cpp index 9a0d1ec..2c25d690 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8Binding.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8Binding.cpp
@@ -92,7 +92,7 @@ exceptionState.throwTypeError(ExceptionMessages::notEnoughArguments(expected, provided)); } -RawPtr<NodeFilter> toNodeFilter(v8::Local<v8::Value> callback, v8::Local<v8::Object> creationContext, ScriptState* scriptState) +NodeFilter* toNodeFilter(v8::Local<v8::Value> callback, v8::Local<v8::Object> creationContext, ScriptState* scriptState) { if (callback->IsNull()) return nullptr;
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8Binding.h b/third_party/WebKit/Source/bindings/core/v8/V8Binding.h index 6a452c6..f7129e1 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8Binding.h +++ b/third_party/WebKit/Source/bindings/core/v8/V8Binding.h
@@ -241,12 +241,6 @@ v8SetReturnValue(callbackInfo, impl.get()); } -template<typename CallbackInfo, typename T> -inline void v8SetReturnValue(const CallbackInfo& callbackInfo, RawPtr<T> impl) -{ - v8SetReturnValue(callbackInfo, impl.get()); -} - template<typename CallbackInfo> inline void v8SetReturnValueForMainWorld(const CallbackInfo& callbackInfo, ScriptWrappable* impl) { @@ -311,12 +305,6 @@ v8SetReturnValueForMainWorld(callbackInfo, impl.get()); } -template<typename CallbackInfo, typename T> -inline void v8SetReturnValueForMainWorld(const CallbackInfo& callbackInfo, RawPtr<T> impl) -{ - v8SetReturnValueForMainWorld(callbackInfo, impl.get()); -} - template<typename CallbackInfo> inline void v8SetReturnValueFast(const CallbackInfo& callbackInfo, ScriptWrappable* impl, const ScriptWrappable* wrappable) { @@ -369,12 +357,6 @@ v8SetReturnValueFast(callbackInfo, impl.get(), wrappable); } -template<typename CallbackInfo, typename T, typename Wrappable> -inline void v8SetReturnValueFast(const CallbackInfo& callbackInfo, RawPtr<T> impl, const Wrappable* wrappable) -{ - v8SetReturnValueFast(callbackInfo, impl.get(), wrappable); -} - // Convert v8::String to a WTF::String. If the V8 string is not already // an external string then it is transformed into an external string at this // point to avoid repeated conversions. @@ -592,7 +574,7 @@ } // FIXME: Remove the special casing for NodeFilter and XPathNSResolver. -RawPtr<NodeFilter> toNodeFilter(v8::Local<v8::Value>, v8::Local<v8::Object>, ScriptState*); +NodeFilter* toNodeFilter(v8::Local<v8::Value>, v8::Local<v8::Object>, ScriptState*); XPathNSResolver* toXPathNSResolver(ScriptState*, v8::Local<v8::Value>); bool toV8Sequence(v8::Local<v8::Value>, uint32_t& length, v8::Isolate*, ExceptionState&);
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8CustomElementLifecycleCallbacks.cpp b/third_party/WebKit/Source/bindings/core/v8/V8CustomElementLifecycleCallbacks.cpp index 20e06183..7a2b0b0 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8CustomElementLifecycleCallbacks.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8CustomElementLifecycleCallbacks.cpp
@@ -48,7 +48,7 @@ V(detached, DetachedCallback) \ V(attributeChanged, AttributeChangedCallback) -RawPtr<V8CustomElementLifecycleCallbacks> V8CustomElementLifecycleCallbacks::create(ScriptState* scriptState, v8::Local<v8::Object> prototype, v8::MaybeLocal<v8::Function> created, v8::MaybeLocal<v8::Function> attached, v8::MaybeLocal<v8::Function> detached, v8::MaybeLocal<v8::Function> attributeChanged) +V8CustomElementLifecycleCallbacks* V8CustomElementLifecycleCallbacks::create(ScriptState* scriptState, v8::Local<v8::Object> prototype, v8::MaybeLocal<v8::Function> created, v8::MaybeLocal<v8::Function> attached, v8::MaybeLocal<v8::Function> detached, v8::MaybeLocal<v8::Function> attributeChanged) { v8::Isolate* isolate = scriptState->isolate(); // A given object can only be used as a Custom Element prototype
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8CustomElementLifecycleCallbacks.h b/third_party/WebKit/Source/bindings/core/v8/V8CustomElementLifecycleCallbacks.h index 00077ccc..14c4d9c1 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8CustomElementLifecycleCallbacks.h +++ b/third_party/WebKit/Source/bindings/core/v8/V8CustomElementLifecycleCallbacks.h
@@ -48,7 +48,7 @@ class V8CustomElementLifecycleCallbacks final : public CustomElementLifecycleCallbacks, public ContextLifecycleObserver { USING_GARBAGE_COLLECTED_MIXIN(V8CustomElementLifecycleCallbacks); public: - static RawPtr<V8CustomElementLifecycleCallbacks> create(ScriptState*, v8::Local<v8::Object> prototype, v8::MaybeLocal<v8::Function> created, v8::MaybeLocal<v8::Function> attached, v8::MaybeLocal<v8::Function> detached, v8::MaybeLocal<v8::Function> attributeChanged); + static V8CustomElementLifecycleCallbacks* create(ScriptState*, v8::Local<v8::Object> prototype, v8::MaybeLocal<v8::Function> created, v8::MaybeLocal<v8::Function> attached, v8::MaybeLocal<v8::Function> detached, v8::MaybeLocal<v8::Function> attributeChanged); ~V8CustomElementLifecycleCallbacks() override;
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8DOMWrapper.h b/third_party/WebKit/Source/bindings/core/v8/V8DOMWrapper.h index 5cb815b..e411219 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8DOMWrapper.h +++ b/third_party/WebKit/Source/bindings/core/v8/V8DOMWrapper.h
@@ -37,7 +37,6 @@ #include "bindings/core/v8/V8Binding.h" #include "core/CoreExport.h" #include "wtf/PassRefPtr.h" -#include "wtf/RawPtr.h" #include "wtf/text/AtomicString.h" #include <v8.h>
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8ErrorHandler.h b/third_party/WebKit/Source/bindings/core/v8/V8ErrorHandler.h index c32502f..c27be9e 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8ErrorHandler.h +++ b/third_party/WebKit/Source/bindings/core/v8/V8ErrorHandler.h
@@ -41,7 +41,7 @@ class V8ErrorHandler final : public V8EventListener { public: - static RawPtr<V8ErrorHandler> create(v8::Local<v8::Object> listener, bool isInline, ScriptState* scriptState) + static V8ErrorHandler* create(v8::Local<v8::Object> listener, bool isInline, ScriptState* scriptState) { V8ErrorHandler* eventListener = new V8ErrorHandler(isInline, scriptState); eventListener->setListenerObject(listener);
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8EventListener.h b/third_party/WebKit/Source/bindings/core/v8/V8EventListener.h index 86a397f..25f5756 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8EventListener.h +++ b/third_party/WebKit/Source/bindings/core/v8/V8EventListener.h
@@ -43,7 +43,7 @@ // that can handle the event. class V8EventListener : public V8AbstractEventListener { public: - static RawPtr<V8EventListener> create(v8::Local<v8::Object> listener, bool isAttribute, ScriptState* scriptState) + static V8EventListener* create(v8::Local<v8::Object> listener, bool isAttribute, ScriptState* scriptState) { V8EventListener* eventListener = new V8EventListener(isAttribute, scriptState); eventListener->setListenerObject(listener);
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8EventListenerList.cpp b/third_party/WebKit/Source/bindings/core/v8/V8EventListenerList.cpp index 06904c6f..387ca17 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8EventListenerList.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8EventListenerList.cpp
@@ -36,7 +36,7 @@ namespace blink { -RawPtr<EventListener> V8EventListenerList::getEventListener(ScriptState* scriptState, v8::Local<v8::Value> value, bool isAttribute, ListenerLookupType lookup) +EventListener* V8EventListenerList::getEventListener(ScriptState* scriptState, v8::Local<v8::Value> value, bool isAttribute, ListenerLookupType lookup) { if (lookup == ListenerFindOnly) { // Used by EventTarget::removeEventListener, specifically
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8EventListenerList.h b/third_party/WebKit/Source/bindings/core/v8/V8EventListenerList.h index d3bd1c7..63f2817 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8EventListenerList.h +++ b/third_party/WebKit/Source/bindings/core/v8/V8EventListenerList.h
@@ -48,7 +48,7 @@ class V8EventListenerList { STATIC_ONLY(V8EventListenerList); public: - static RawPtr<V8EventListener> findWrapper(v8::Local<v8::Value> value, ScriptState* scriptState) + static V8EventListener* findWrapper(v8::Local<v8::Value> value, ScriptState* scriptState) { ASSERT(scriptState->isolate()->InContext()); if (!value->IsObject()) @@ -59,9 +59,9 @@ } template<typename WrapperType> - static RawPtr<V8EventListener> findOrCreateWrapper(v8::Local<v8::Value>, bool isAttribute, ScriptState*); + static V8EventListener* findOrCreateWrapper(v8::Local<v8::Value>, bool isAttribute, ScriptState*); - CORE_EXPORT static RawPtr<EventListener> getEventListener(ScriptState*, v8::Local<v8::Value>, bool isAttribute, ListenerLookupType); + CORE_EXPORT static EventListener* getEventListener(ScriptState*, v8::Local<v8::Value>, bool isAttribute, ListenerLookupType); private: static V8EventListener* doFindWrapper(v8::Local<v8::Object> object, v8::Local<v8::String> wrapperProperty, ScriptState* scriptState) @@ -81,7 +81,7 @@ }; template<typename WrapperType> -RawPtr<V8EventListener> V8EventListenerList::findOrCreateWrapper(v8::Local<v8::Value> value, bool isAttribute, ScriptState* scriptState) +V8EventListener* V8EventListenerList::findOrCreateWrapper(v8::Local<v8::Value> value, bool isAttribute, ScriptState* scriptState) { v8::Isolate* isolate = scriptState->isolate(); ASSERT(isolate->InContext());
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8GCController.cpp b/third_party/WebKit/Source/bindings/core/v8/V8GCController.cpp index 810e3fa..f110bad 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8GCController.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8GCController.cpp
@@ -356,7 +356,7 @@ // to collect all garbage, you need to wait until the next event loop. // Regarding (2), it would be OK in practice to trigger only one GC per gcEpilogue, because // GCController.collectAll() forces multiple V8's GC. - Heap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); // Forces a precise GC at the end of the current event loop. if (ThreadState::current()) { @@ -369,7 +369,7 @@ // low memory notifications. if (flags & v8::kGCCallbackFlagCollectAllAvailableGarbage) { // This single GC is not enough. See the above comment. - Heap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); // Do not force a precise GC at the end of the current event loop. // According to UMA stats, the collection rate of the precise GC
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8LazyEventListener.h b/third_party/WebKit/Source/bindings/core/v8/V8LazyEventListener.h index 146d11dc..3e877f9 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8LazyEventListener.h +++ b/third_party/WebKit/Source/bindings/core/v8/V8LazyEventListener.h
@@ -45,7 +45,7 @@ // A V8LazyEventListener is either a HTML or SVG event handler. class V8LazyEventListener final : public V8AbstractEventListener { public: - static RawPtr<V8LazyEventListener> create(const AtomicString& functionName, const AtomicString& eventParameterName, const String& code, const String& sourceURL, const TextPosition& position, Node* node, v8::Isolate* isolate) + static V8LazyEventListener* create(const AtomicString& functionName, const AtomicString& eventParameterName, const String& code, const String& sourceURL, const TextPosition& position, Node* node, v8::Isolate* isolate) { return new V8LazyEventListener(isolate, functionName, eventParameterName, code, sourceURL, position, node); }
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8MutationCallback.h b/third_party/WebKit/Source/bindings/core/v8/V8MutationCallback.h index 75be8c1..beb9cda 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8MutationCallback.h +++ b/third_party/WebKit/Source/bindings/core/v8/V8MutationCallback.h
@@ -41,7 +41,7 @@ class V8MutationCallback final : public MutationCallback, public ActiveDOMCallback { USING_GARBAGE_COLLECTED_MIXIN(V8MutationCallback); public: - static RawPtr<V8MutationCallback> create(v8::Local<v8::Function> callback, v8::Local<v8::Object> owner, ScriptState* scriptState) + static V8MutationCallback* create(v8::Local<v8::Function> callback, v8::Local<v8::Object> owner, ScriptState* scriptState) { return new V8MutationCallback(callback, owner, scriptState); }
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8NodeFilterCondition.h b/third_party/WebKit/Source/bindings/core/v8/V8NodeFilterCondition.h index 859b5fa..b3aa199 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8NodeFilterCondition.h +++ b/third_party/WebKit/Source/bindings/core/v8/V8NodeFilterCondition.h
@@ -62,7 +62,7 @@ // (V8) class V8NodeFilterCondition final : public NodeFilterCondition { public: - static RawPtr<V8NodeFilterCondition> create(v8::Local<v8::Value> filter, v8::Local<v8::Object> owner, ScriptState* scriptState) + static V8NodeFilterCondition* create(v8::Local<v8::Value> filter, v8::Local<v8::Object> owner, ScriptState* scriptState) { return new V8NodeFilterCondition(filter, owner, scriptState); }
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8WorkerGlobalScopeEventListener.h b/third_party/WebKit/Source/bindings/core/v8/V8WorkerGlobalScopeEventListener.h index 4463bf2..eb513d89 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8WorkerGlobalScopeEventListener.h +++ b/third_party/WebKit/Source/bindings/core/v8/V8WorkerGlobalScopeEventListener.h
@@ -41,7 +41,7 @@ class V8WorkerGlobalScopeEventListener final : public V8EventListener { public: - static RawPtr<V8WorkerGlobalScopeEventListener> create(v8::Local<v8::Object> listener, bool isInline, ScriptState* scriptState) + static V8WorkerGlobalScopeEventListener* create(v8::Local<v8::Object> listener, bool isInline, ScriptState* scriptState) { V8WorkerGlobalScopeEventListener* eventListener = new V8WorkerGlobalScopeEventListener(isInline, scriptState); eventListener->setListenerObject(listener);
diff --git a/third_party/WebKit/Source/bindings/core/v8/WindowProxy.cpp b/third_party/WebKit/Source/bindings/core/v8/WindowProxy.cpp index fb18985..66ce71a 100644 --- a/third_party/WebKit/Source/bindings/core/v8/WindowProxy.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/WindowProxy.cpp
@@ -76,7 +76,7 @@ ASSERT(V8Document::toImpl(wrapper) == document); } -RawPtr<WindowProxy> WindowProxy::create(v8::Isolate* isolate, Frame* frame, DOMWrapperWorld& world) +WindowProxy* WindowProxy::create(v8::Isolate* isolate, Frame* frame, DOMWrapperWorld& world) { return new WindowProxy(frame, &world, isolate); } @@ -311,8 +311,6 @@ if (globalTemplate.IsEmpty()) return; - double contextCreationStartInSeconds = currentTime(); - // FIXME: It's not clear what the right thing to do for remote frames is. // The extensions registered don't generally seem to make sense for remote // frames, so skip it for now. @@ -337,15 +335,6 @@ if (context.IsEmpty()) return; m_scriptState = ScriptState::create(context, m_world); - - double contextCreationDurationInMilliseconds = (currentTime() - contextCreationStartInSeconds) * 1000; - if (!m_world->isMainWorld()) { - DEFINE_STATIC_LOCAL(CustomCountHistogram, isolatedWorldHistogram, ("WebCore.WindowProxy.createContext.IsolatedWorld", 0, 10000, 50)); - isolatedWorldHistogram.count(contextCreationDurationInMilliseconds); - } else { - DEFINE_STATIC_LOCAL(CustomCountHistogram, mainWorldHistogram, ("WebCore.WindowProxy.createContext.MainWorld", 0, 10000, 50)); - mainWorldHistogram.count(contextCreationDurationInMilliseconds); - } } static v8::Local<v8::Object> toInnerGlobalObject(v8::Local<v8::Context> context)
diff --git a/third_party/WebKit/Source/bindings/core/v8/WindowProxy.h b/third_party/WebKit/Source/bindings/core/v8/WindowProxy.h index 9ea6a37..3c59be55 100644 --- a/third_party/WebKit/Source/bindings/core/v8/WindowProxy.h +++ b/third_party/WebKit/Source/bindings/core/v8/WindowProxy.h
@@ -52,7 +52,7 @@ // persist between navigations. class WindowProxy final : public GarbageCollectedFinalized<WindowProxy> { public: - static RawPtr<WindowProxy> create(v8::Isolate*, Frame*, DOMWrapperWorld&); + static WindowProxy* create(v8::Isolate*, Frame*, DOMWrapperWorld&); ~WindowProxy(); DECLARE_TRACE();
diff --git a/third_party/WebKit/Source/bindings/core/v8/WindowProxyManager.cpp b/third_party/WebKit/Source/bindings/core/v8/WindowProxyManager.cpp index ace0c48..5c10211 100644 --- a/third_party/WebKit/Source/bindings/core/v8/WindowProxyManager.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/WindowProxyManager.cpp
@@ -10,7 +10,7 @@ namespace blink { -RawPtr<WindowProxyManager> WindowProxyManager::create(Frame& frame) +WindowProxyManager* WindowProxyManager::create(Frame& frame) { return new WindowProxyManager(frame); }
diff --git a/third_party/WebKit/Source/bindings/core/v8/WindowProxyManager.h b/third_party/WebKit/Source/bindings/core/v8/WindowProxyManager.h index 294c978..ae9f3fa 100644 --- a/third_party/WebKit/Source/bindings/core/v8/WindowProxyManager.h +++ b/third_party/WebKit/Source/bindings/core/v8/WindowProxyManager.h
@@ -21,7 +21,7 @@ class CORE_EXPORT WindowProxyManager final : public GarbageCollectedFinalized<WindowProxyManager> { public: - static RawPtr<WindowProxyManager> create(Frame&); + static WindowProxyManager* create(Frame&); ~WindowProxyManager(); DECLARE_TRACE();
diff --git a/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.cpp b/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.cpp index 14915be..43079ab 100644 --- a/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.cpp
@@ -102,7 +102,7 @@ ExecutionState* m_outerState; }; -RawPtr<WorkerOrWorkletScriptController> WorkerOrWorkletScriptController::create(WorkerOrWorkletGlobalScope* globalScope, v8::Isolate* isolate) +WorkerOrWorkletScriptController* WorkerOrWorkletScriptController::create(WorkerOrWorkletGlobalScope* globalScope, v8::Isolate* isolate) { return new WorkerOrWorkletScriptController(globalScope, isolate); } @@ -312,7 +312,7 @@ m_disableEvalPending = errorMessage; } -void WorkerOrWorkletScriptController::rethrowExceptionFromImportedScript(RawPtr<ErrorEvent> errorEvent, ExceptionState& exceptionState) +void WorkerOrWorkletScriptController::rethrowExceptionFromImportedScript(ErrorEvent* errorEvent, ExceptionState& exceptionState) { const String& errorMessage = errorEvent->message(); if (m_executionState)
diff --git a/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.h b/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.h index 7f0ad02..4da92c9 100644 --- a/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.h +++ b/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.h
@@ -54,7 +54,7 @@ class CORE_EXPORT WorkerOrWorkletScriptController : public GarbageCollectedFinalized<WorkerOrWorkletScriptController> { WTF_MAKE_NONCOPYABLE(WorkerOrWorkletScriptController); public: - static RawPtr<WorkerOrWorkletScriptController> create(WorkerOrWorkletGlobalScope*, v8::Isolate*); + static WorkerOrWorkletScriptController* create(WorkerOrWorkletGlobalScope*, v8::Isolate*); virtual ~WorkerOrWorkletScriptController(); void dispose(); @@ -78,7 +78,7 @@ void willScheduleExecutionTermination(); // Used by WorkerGlobalScope: - void rethrowExceptionFromImportedScript(RawPtr<ErrorEvent>, ExceptionState&); + void rethrowExceptionFromImportedScript(ErrorEvent*, ExceptionState&); void disableEval(const String&); // Used by Inspector agents:
diff --git a/third_party/WebKit/Source/bindings/core/v8/WrapperTypeInfo.h b/third_party/WebKit/Source/bindings/core/v8/WrapperTypeInfo.h index 6700f008..bc9c48a7 100644 --- a/third_party/WebKit/Source/bindings/core/v8/WrapperTypeInfo.h +++ b/third_party/WebKit/Source/bindings/core/v8/WrapperTypeInfo.h
@@ -122,12 +122,12 @@ void wrapperCreated() const { - Heap::heapStats().increaseWrapperCount(1); + ThreadHeap::heapStats().increaseWrapperCount(1); } void wrapperDestroyed() const { - ThreadHeapStats& heapStats = Heap::heapStats(); + ThreadHeapStats& heapStats = ThreadHeap::heapStats(); heapStats.decreaseWrapperCount(1); heapStats.increaseCollectedWrapperCount(1); }
diff --git a/third_party/WebKit/Source/bindings/scripts/v8_types.py b/third_party/WebKit/Source/bindings/scripts/v8_types.py index dc18cf24..a7b97ce 100644 --- a/third_party/WebKit/Source/bindings/scripts/v8_types.py +++ b/third_party/WebKit/Source/bindings/scripts/v8_types.py
@@ -111,6 +111,7 @@ 'Date': 'double', 'Dictionary': 'Dictionary', 'EventHandler': 'EventListener*', + 'EventListener': 'EventListener*', 'NodeFilter': 'NodeFilter*', 'Promise': 'ScriptPromise', 'ScriptValue': 'ScriptValue', @@ -179,7 +180,7 @@ if base_idl_type in CPP_SPECIAL_CONVERSION_RULES: return CPP_SPECIAL_CONVERSION_RULES[base_idl_type] - if base_idl_type in NON_WRAPPER_TYPES: + if base_idl_type == 'SerializedScriptValue': return ('PassRefPtr<%s>' if used_as_rvalue_type else 'RefPtr<%s>') % base_idl_type if idl_type.is_string_type: if not raw_type:
diff --git a/third_party/WebKit/Source/bindings/templates/interface.cpp b/third_party/WebKit/Source/bindings/templates/interface.cpp index 3e522fa..b4b2ede1 100644 --- a/third_party/WebKit/Source/bindings/templates/interface.cpp +++ b/third_party/WebKit/Source/bindings/templates/interface.cpp
@@ -688,13 +688,7 @@ {% if not is_array_buffer_or_view %} v8::Local<v8::FunctionTemplate> {{v8_class}}::domTemplate(v8::Isolate* isolate) { - {% if has_partial_interface %} - {% set installTemplateFunction = '%s::install%sTemplateFunction' % (v8_class, v8_class) %} - ASSERT({{installTemplateFunction}} != {{v8_class}}::install{{v8_class}}Template); - {% else %} - {% set installTemplateFunction = 'install%sTemplate' % v8_class %} - {% endif %} -{% set installTemplateFunction = '%s::install%sTemplateFunction' % (v8_class, v8_class) if has_partial_interface else 'install%sTemplate' % v8_class %} + {% set installTemplateFunction = '%s::install%sTemplateFunction' % (v8_class, v8_class) if has_partial_interface else 'install%sTemplate' % v8_class %} return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), {{installTemplateFunction}}); }
diff --git a/third_party/WebKit/Source/bindings/templates/interface_base.cpp b/third_party/WebKit/Source/bindings/templates/interface_base.cpp index d18affc..323ce43 100644 --- a/third_party/WebKit/Source/bindings/templates/interface_base.cpp +++ b/third_party/WebKit/Source/bindings/templates/interface_base.cpp
@@ -91,7 +91,7 @@ {% endfor %} {##############################################################################} {% block security_check_functions %} -{% if has_access_check_callbacks %} +{% if has_access_check_callbacks and not is_partial %} bool securityCheck(v8::Local<v8::Context> accessingContext, v8::Local<v8::Object> accessedObject, v8::Local<v8::Value> data) { // TODO(jochen): Take accessingContext into account. @@ -298,12 +298,12 @@ } // if ({{runtime_enabled_function}}()) {% endif %} - {%- if has_access_check_callbacks %}{{newline}} + {%- if has_access_check_callbacks and not is_partial %}{{newline}} // Cross-origin access check instanceTemplate->SetAccessCheckCallback({{cpp_class}}V8Internal::securityCheck, v8::External::New(isolate, const_cast<WrapperTypeInfo*>(&{{v8_class}}::wrapperTypeInfo))); {% endif %} - {%- if has_array_iterator and not is_global %}{{newline}} + {%- if has_array_iterator and not is_partial and not is_global %}{{newline}} // Array iterator prototypeTemplate->SetIntrinsicDataProperty(v8::Symbol::GetIterator(isolate), v8::kArrayProto_values, v8::DontEnum); {% endif %} @@ -336,11 +336,11 @@ } {% endfor %} - {%- if indexed_property_getter %}{{newline}} + {%- if indexed_property_getter and not is_partial %}{{newline}} // Indexed properties {{install_indexed_property_handler('instanceTemplate') | indent}} {% endif %} - {% if named_property_getter and not has_named_properties_object %} + {% if named_property_getter and not is_partial and not has_named_properties_object %} // Named properties {{install_named_property_handler('instanceTemplate') | indent}} {% endif %} @@ -355,11 +355,11 @@ {% endfilter %} {% endif %} - {%- if has_custom_legacy_call_as_function %}{{newline}} + {%- if has_custom_legacy_call_as_function and not is_partial %}{{newline}} instanceTemplate->SetCallAsFunctionHandler({{v8_class}}::legacyCallCustom); {% endif %} - {%- if interface_name == 'HTMLAllCollection' %}{{newline}} + {%- if interface_name == 'HTMLAllCollection' and not is_partial %}{{newline}} // Needed for legacy support of document.all instanceTemplate->MarkAsUndetectable(); {% endif %}
diff --git a/third_party/WebKit/Source/bindings/templates/methods.cpp b/third_party/WebKit/Source/bindings/templates/methods.cpp index 3a9742f..71753c3 100644 --- a/third_party/WebKit/Source/bindings/templates/methods.cpp +++ b/third_party/WebKit/Source/bindings/templates/methods.cpp
@@ -83,7 +83,7 @@ {######################################} {% macro generate_arguments(method, world_suffix) %} {% for argument in method.arguments %} -{{generate_argument_var_declaration(argument)}}; +{{argument.cpp_type}} {{argument.name}}; {% endfor %} { {% if method.has_optional_argument_without_default_value %} @@ -113,17 +113,6 @@ {######################################} -{% macro generate_argument_var_declaration(argument) %} -{# FIXME: remove EventListener special case #} -{% if argument.idl_type == 'EventListener' %} -RawPtr<{{argument.idl_type}}> {{argument.name}} -{%- else %} -{{argument.cpp_type}} {{argument.name}} -{%- endif %}{# argument.idl_type == 'EventListener' #} -{% endmacro %} - - -{######################################} {% macro generate_argument(method, argument, world_suffix) %} {% if argument.is_optional_without_default_value %} {# Optional arguments without a default value generate an early call with
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface.cpp index 5475383..0fb5804 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface.cpp
@@ -2168,7 +2168,6 @@ v8::Local<v8::FunctionTemplate> V8TestInterface::domTemplate(v8::Isolate* isolate) { - ASSERT(V8TestInterface::installV8TestInterfaceTemplateFunction != V8TestInterface::installV8TestInterfaceTemplate); return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), V8TestInterface::installV8TestInterfaceTemplateFunction); }
diff --git a/third_party/WebKit/Source/bindings/tests/results/modules/V8TestInterfacePartial.cpp b/third_party/WebKit/Source/bindings/tests/results/modules/V8TestInterfacePartial.cpp index 12682c9..a3b131a 100644 --- a/third_party/WebKit/Source/bindings/tests/results/modules/V8TestInterfacePartial.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/modules/V8TestInterfacePartial.cpp
@@ -310,8 +310,6 @@ V8DOMConfiguration::installConstants(isolate, interfaceTemplate, prototypeTemplate, V8TestInterfaceConstants, WTF_ARRAY_LENGTH(V8TestInterfaceConstants)); V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceMethods, WTF_ARRAY_LENGTH(V8TestInterfaceMethods)); } // if (RuntimeEnabledFeatures::featureNameEnabled()) - - instanceTemplate->SetCallAsFunctionHandler(V8TestInterface::legacyCallCustom); } void V8TestInterfacePartial::preparePrototypeAndInterfaceObject(v8::Local<v8::Context> context, v8::Local<v8::Object> prototypeObject, v8::Local<v8::Function> interfaceObject, v8::Local<v8::FunctionTemplate> interfaceTemplate)
diff --git a/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl b/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl index fea1904e..c6cafb9 100644 --- a/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl +++ b/third_party/WebKit/Source/build/scripts/templates/ElementFactory.cpp.tmpl
@@ -21,7 +21,7 @@ using namespace {{namespace}}Names; -typedef RawPtr<{{namespace}}Element> (*ConstructorFunction)( +typedef {{namespace}}Element* (*ConstructorFunction)( Document&, {% if namespace == 'HTML' %} HTMLFormElement*, @@ -33,7 +33,7 @@ static FunctionMap* g_constructors = 0; {% for tag in tags|sort if not tag.noConstructor %} -static RawPtr<{{namespace}}Element> {{tag|symbol}}Constructor( +static {{namespace}}Element* {{tag|symbol}}Constructor( Document& document, {% if namespace == 'HTML' %} HTMLFormElement* formElement, @@ -73,7 +73,7 @@ g_constructors->set(data[i].tag.localName(), data[i].func); } -RawPtr<{{namespace}}Element> {{namespace}}ElementFactory::create{{namespace}}Element( +{{namespace}}Element* {{namespace}}ElementFactory::create{{namespace}}Element( const AtomicString& localName, Document& document, {% if namespace == 'HTML' %}
diff --git a/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl b/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl index c80229e..0d26c33 100644 --- a/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl +++ b/third_party/WebKit/Source/build/scripts/templates/ElementFactory.h.tmpl
@@ -18,7 +18,7 @@ class {{namespace}}ElementFactory { public: - static RawPtr<{{namespace}}Element> create{{namespace}}Element( + static {{namespace}}Element* create{{namespace}}Element( const AtomicString& localName, Document&, {% if namespace == 'HTML' %}
diff --git a/third_party/WebKit/Source/core/animation/AnimationInputHelpersTest.cpp b/third_party/WebKit/Source/core/animation/AnimationInputHelpersTest.cpp index f659d4e..e272e35 100644 --- a/third_party/WebKit/Source/core/animation/AnimationInputHelpersTest.cpp +++ b/third_party/WebKit/Source/core/animation/AnimationInputHelpersTest.cpp
@@ -49,7 +49,7 @@ void TearDown() override { document.release(); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); } OwnPtr<DummyPageHolder> pageHolder;
diff --git a/third_party/WebKit/Source/core/animation/AnimationStackTest.cpp b/third_party/WebKit/Source/core/animation/AnimationStackTest.cpp index 4939000..bdccc72d 100644 --- a/third_party/WebKit/Source/core/animation/AnimationStackTest.cpp +++ b/third_party/WebKit/Source/core/animation/AnimationStackTest.cpp
@@ -142,28 +142,28 @@ ActiveInterpolationsMap interpolations; updateTimeline(11); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); interpolations = AnimationStack::activeInterpolations(&element->elementAnimations()->animationStack(), nullptr, nullptr, KeyframeEffect::DefaultPriority); EXPECT_EQ(1u, interpolations.size()); EXPECT_TRUE(interpolationValue(interpolations, CSSPropertyFontSize)->equals(AnimatableDouble::create(3).get())); EXPECT_EQ(3u, sampledEffectCount()); updateTimeline(13); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); interpolations = AnimationStack::activeInterpolations(&element->elementAnimations()->animationStack(), nullptr, nullptr, KeyframeEffect::DefaultPriority); EXPECT_EQ(1u, interpolations.size()); EXPECT_TRUE(interpolationValue(interpolations, CSSPropertyFontSize)->equals(AnimatableDouble::create(3).get())); EXPECT_EQ(3u, sampledEffectCount()); updateTimeline(15); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); interpolations = AnimationStack::activeInterpolations(&element->elementAnimations()->animationStack(), nullptr, nullptr, KeyframeEffect::DefaultPriority); EXPECT_EQ(1u, interpolations.size()); EXPECT_TRUE(interpolationValue(interpolations, CSSPropertyFontSize)->equals(AnimatableDouble::create(3).get())); EXPECT_EQ(2u, sampledEffectCount()); updateTimeline(17); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); interpolations = AnimationStack::activeInterpolations(&element->elementAnimations()->animationStack(), nullptr, nullptr, KeyframeEffect::DefaultPriority); EXPECT_EQ(1u, interpolations.size()); EXPECT_TRUE(interpolationValue(interpolations, CSSPropertyFontSize)->equals(AnimatableDouble::create(3).get()));
diff --git a/third_party/WebKit/Source/core/animation/AnimationTest.cpp b/third_party/WebKit/Source/core/animation/AnimationTest.cpp index 8501943..8fa8467 100644 --- a/third_party/WebKit/Source/core/animation/AnimationTest.cpp +++ b/third_party/WebKit/Source/core/animation/AnimationTest.cpp
@@ -737,7 +737,7 @@ timeline->serviceAnimations(TimingUpdateForAnimationFrame); EXPECT_EQ(1U, element->elementAnimations()->animations().find(animation)->value); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_TRUE(element->elementAnimations()->animations().isEmpty()); }
diff --git a/third_party/WebKit/Source/core/animation/AnimationTimelineTest.cpp b/third_party/WebKit/Source/core/animation/AnimationTimelineTest.cpp index 0e07673587..7e39d16 100644 --- a/third_party/WebKit/Source/core/animation/AnimationTimelineTest.cpp +++ b/third_party/WebKit/Source/core/animation/AnimationTimelineTest.cpp
@@ -76,7 +76,7 @@ document.release(); element.release(); timeline.release(); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); } void updateClockAndService(double time)
diff --git a/third_party/WebKit/Source/core/animation/CompositorAnimationsTest.cpp b/third_party/WebKit/Source/core/animation/CompositorAnimationsTest.cpp index f8e57ab4..54471a0 100644 --- a/third_party/WebKit/Source/core/animation/CompositorAnimationsTest.cpp +++ b/third_party/WebKit/Source/core/animation/CompositorAnimationsTest.cpp
@@ -1227,7 +1227,7 @@ element->setLayoutObject(nullptr); LayoutObjectProxy::dispose(layoutObject); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_TRUE(element->elementAnimations()->animations().isEmpty()); }
diff --git a/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp b/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp index e0c94ee..793fd3a 100644 --- a/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp +++ b/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp
@@ -110,6 +110,7 @@ CSSPropertyFontStyle, CSSPropertyFontVariant, CSSPropertyFontVariantLigatures, + CSSPropertyFontVariantCaps, CSSPropertyFontWeight, CSSPropertyHeight, CSSPropertyImageOrientation,
diff --git a/third_party/WebKit/Source/core/css/CSSProperties.in b/third_party/WebKit/Source/core/css/CSSProperties.in index 4dcb2ea..f7e42e1 100644 --- a/third_party/WebKit/Source/core/css/CSSProperties.in +++ b/third_party/WebKit/Source/core/css/CSSProperties.in
@@ -103,6 +103,7 @@ font-style inherited, font, type_name=FontStyle, name_for_methods=Style font-variant inherited, font, type_name=FontVariant, name_for_methods=Variant font-variant-ligatures inherited, font, type_name=VariantLigatures, name_for_methods=VariantLigatures, converter=convertFontVariantLigatures +font-variant-caps inherited, font, name_for_methods=VariantCaps, converter=convertFontVariantCaps font-weight interpolable, inherited, font, type_name=FontWeight, name_for_methods=Weight, converter=convertFontWeight font-feature-settings inherited, font, name_for_methods=FeatureSettings, converter=convertFontFeatureSettings -webkit-font-smoothing inherited, font, type_name=FontSmoothingMode
diff --git a/third_party/WebKit/Source/core/css/CSSStyleSheetResourceTest.cpp b/third_party/WebKit/Source/core/css/CSSStyleSheetResourceTest.cpp index 6144596..8ee2ea5 100644 --- a/third_party/WebKit/Source/core/css/CSSStyleSheetResourceTest.cpp +++ b/third_party/WebKit/Source/core/css/CSSStyleSheetResourceTest.cpp
@@ -112,7 +112,7 @@ } ASSERT_TRUE(memoryCache()->isInSameLRUListForTest(cssResource, imageResource)); } - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); // This operation should not lead to crash! memoryCache()->pruneAll(); }
diff --git a/third_party/WebKit/Source/core/css/CSSValue.h b/third_party/WebKit/Source/core/css/CSSValue.h index 854ee05..05d37db 100644 --- a/third_party/WebKit/Source/core/css/CSSValue.h +++ b/third_party/WebKit/Source/core/css/CSSValue.h
@@ -43,7 +43,7 @@ { ThreadState* state = ThreadStateFor<ThreadingTrait<CSSValue>::Affinity>::state(); const char typeName[] = "blink::CSSValue"; - return Heap::allocateOnArenaIndex(state, size, isEager ? BlinkGC::EagerSweepArenaIndex : BlinkGC::CSSValueArenaIndex, GCInfoTrait<CSSValue>::index(), typeName); + return ThreadHeap::allocateOnArenaIndex(state, size, isEager ? BlinkGC::EagerSweepArenaIndex : BlinkGC::CSSValueArenaIndex, GCInfoTrait<CSSValue>::index(), typeName); } String cssText() const;
diff --git a/third_party/WebKit/Source/core/css/CSSValueKeywords.in b/third_party/WebKit/Source/core/css/CSSValueKeywords.in index 4b33b01..079326d9 100644 --- a/third_party/WebKit/Source/core/css/CSSValueKeywords.in +++ b/third_party/WebKit/Source/core/css/CSSValueKeywords.in
@@ -66,6 +66,16 @@ contextual no-contextual +// font-variant-caps: +// +// normal +small-caps +all-small-caps +petite-caps +all-petite-caps +unicase +titling-caps + // // font-weigth //
diff --git a/third_party/WebKit/Source/core/css/ComputedStyleCSSValueMapping.cpp b/third_party/WebKit/Source/core/css/ComputedStyleCSSValueMapping.cpp index 9ec10b7..4b9e74e5 100644 --- a/third_party/WebKit/Source/core/css/ComputedStyleCSSValueMapping.cpp +++ b/third_party/WebKit/Source/core/css/ComputedStyleCSSValueMapping.cpp
@@ -2167,6 +2167,25 @@ valueList->append(cssValuePool().createIdentifierValue(contextualLigaturesState == FontDescription::DisabledLigaturesState ? CSSValueNoContextual : CSSValueContextual)); return valueList; } + case CSSPropertyFontVariantCaps: { + FontDescription::FontVariantCaps variantCaps = style.getFontDescription().variantCaps(); + switch (variantCaps) { + case FontDescription::CapsNormal: + return cssValuePool().createIdentifierValue(CSSValueNormal); + case FontDescription::SmallCaps: + return cssValuePool().createIdentifierValue(CSSValueSmallCaps); + case FontDescription::AllSmallCaps: + return cssValuePool().createIdentifierValue(CSSValueAllSmallCaps); + case FontDescription::PetiteCaps: + return cssValuePool().createIdentifierValue(CSSValuePetiteCaps); + case FontDescription::AllPetiteCaps: + return cssValuePool().createIdentifierValue(CSSValueAllPetiteCaps); + case FontDescription::Unicase: + return cssValuePool().createIdentifierValue(CSSValueUnicase); + case FontDescription::TitlingCaps: + return cssValuePool().createIdentifierValue(CSSValueTitlingCaps); + } + } case CSSPropertyZIndex: if (style.hasAutoZIndex()) return cssValuePool().createIdentifierValue(CSSValueAuto);
diff --git a/third_party/WebKit/Source/core/css/StylePropertySet.cpp b/third_party/WebKit/Source/core/css/StylePropertySet.cpp index 6cf1349..008e293 100644 --- a/third_party/WebKit/Source/core/css/StylePropertySet.cpp +++ b/third_party/WebKit/Source/core/css/StylePropertySet.cpp
@@ -48,7 +48,7 @@ ImmutableStylePropertySet* ImmutableStylePropertySet::create(const CSSProperty* properties, unsigned count, CSSParserMode cssParserMode) { ASSERT(count <= MaxArraySize); - void* slot = Heap::allocate<StylePropertySet>(sizeForImmutableStylePropertySetWithPropertyCount(count)); + void* slot = ThreadHeap::allocate<StylePropertySet>(sizeForImmutableStylePropertySetWithPropertyCount(count)); return new (slot) ImmutableStylePropertySet(properties, count, cssParserMode); }
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp index eab4066..1de21d2 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp
@@ -501,6 +501,13 @@ return ligatureValues; } +static CSSValue* consumeFontVariantCaps(CSSParserTokenRange& range) +{ + return consumeIdent<CSSValueNormal, CSSValueSmallCaps, CSSValueAllSmallCaps, + CSSValuePetiteCaps, CSSValueAllPetiteCaps, + CSSValueUnicase, CSSValueTitlingCaps>(range); +} + static CSSPrimitiveValue* consumeFontVariant(CSSParserTokenRange& range) { return consumeIdent<CSSValueNormal, CSSValueSmallCaps>(range); @@ -3443,6 +3450,8 @@ return consumeQuotes(m_range); case CSSPropertyWebkitHighlight: return consumeWebkitHighlight(m_range); + case CSSPropertyFontVariantCaps: + return consumeFontVariantCaps(m_range); case CSSPropertyFontVariantLigatures: return consumeFontVariantLigatures(m_range); case CSSPropertyFontFeatureSettings: @@ -3982,6 +3991,7 @@ } if (!fontVariant) { // Font variant in the shorthand is particular, it only accepts normal or small-caps. + // TODO: Make consumeFontVariant only accept the css21 values. fontVariant = consumeFontVariant(m_range); if (fontVariant) continue;
diff --git a/third_party/WebKit/Source/core/css/resolver/CSSPropertyPriority.h b/third_party/WebKit/Source/core/css/resolver/CSSPropertyPriority.h index 1b2ec8e..7a0c08e 100644 --- a/third_party/WebKit/Source/core/css/resolver/CSSPropertyPriority.h +++ b/third_party/WebKit/Source/core/css/resolver/CSSPropertyPriority.h
@@ -55,7 +55,7 @@ template<> inline CSSPropertyID CSSPropertyPriorityData<HighPropertyPriority>::last() { - static_assert(CSSPropertyZoom == CSSPropertyColor + 19, "CSSPropertyZoom should be the end of the high priority property range"); + static_assert(CSSPropertyZoom == CSSPropertyColor + 20, "CSSPropertyZoom should be the end of the high priority property range"); static_assert(CSSPropertyTextRendering == CSSPropertyZoom - 1, "CSSPropertyTextRendering should be immediately before CSSPropertyZoom"); return CSSPropertyZoom; }
diff --git a/third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp b/third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp index 4dcf29c..e10f73b 100644 --- a/third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp +++ b/third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp
@@ -162,6 +162,13 @@ m_fontDescription.setVariant(smallCaps); } +void FontBuilder::setVariantCaps(FontDescription::FontVariantCaps caps) +{ + set(PropertySetFlag::VariantCaps); + + m_fontDescription.setVariantCaps(caps); +} + void FontBuilder::setVariantLigatures(const FontDescription::VariantLigatures& ligatures) { set(PropertySetFlag::VariantLigatures); @@ -369,6 +376,8 @@ description.setStyle(m_fontDescription.style()); if (isSet(PropertySetFlag::Variant)) description.setVariant(m_fontDescription.variant()); + if (isSet(PropertySetFlag::VariantCaps)) + description.setVariantCaps(m_fontDescription.variantCaps()); if (isSet(PropertySetFlag::VariantLigatures)) description.setVariantLigatures(m_fontDescription.getVariantLigatures()); if (isSet(PropertySetFlag::TextRendering))
diff --git a/third_party/WebKit/Source/core/css/resolver/FontBuilder.h b/third_party/WebKit/Source/core/css/resolver/FontBuilder.h index 21ee8bfb..ee5c4f2f 100644 --- a/third_party/WebKit/Source/core/css/resolver/FontBuilder.h +++ b/third_party/WebKit/Source/core/css/resolver/FontBuilder.h
@@ -63,6 +63,7 @@ void setLocale(const AtomicString&); void setStyle(FontStyle); void setVariant(FontVariant); + void setVariantCaps(FontDescription::FontVariantCaps); void setVariantLigatures(const FontDescription::VariantLigatures&); void setTextRendering(TextRenderingMode); void setKerning(FontDescription::Kerning); @@ -82,6 +83,7 @@ static float initialSizeAdjust() { return FontSizeAdjustNone; } static TextRenderingMode initialTextRendering() { return AutoTextRendering; } static FontVariant initialVariant() { return FontVariantNormal; } + static FontDescription::FontVariantCaps initialVariantCaps() { return FontDescription::CapsNormal; } static FontDescription::VariantLigatures initialVariantLigatures() { return FontDescription::VariantLigatures(); } static const AtomicString& initialLocale() { return nullAtom; } static FontStyle initialStyle() { return FontStyleNormal; } @@ -116,6 +118,7 @@ Style, SizeAdjust, Variant, + VariantCaps, VariantLigatures, TextRendering, Kerning,
diff --git a/third_party/WebKit/Source/core/css/resolver/FontBuilderTest.cpp b/third_party/WebKit/Source/core/css/resolver/FontBuilderTest.cpp index e4cab366..e4c72e1c8 100644 --- a/third_party/WebKit/Source/core/css/resolver/FontBuilderTest.cpp +++ b/third_party/WebKit/Source/core/css/resolver/FontBuilderTest.cpp
@@ -112,6 +112,9 @@ static void fontVariantBase(FontDescription& d) { d.setVariant(FontVariantSmallCaps); } static void fontVariantValue(FontBuilder& b) { b.setVariant(FontVariantNormal); } +static void fontVariantCapsBase(FontDescription& d) { d.setVariantCaps(FontDescription::SmallCaps); } +static void fontVariantCapsValue(FontBuilder& b) { b.setVariantCaps(FontDescription::CapsNormal); } + static void fontVariantLigaturesBase(FontDescription& d) { d.setVariantLigatures(FontDescription::VariantLigatures(FontDescription::EnabledLigaturesState)); } static void fontVariantLigaturesValue(FontBuilder& b) { b.setVariantLigatures(FontDescription::VariantLigatures(FontDescription::DisabledLigaturesState)); } @@ -152,6 +155,7 @@ FunctionPair(fontFeatureSettingsBase, fontFeatureSettingsValue), FunctionPair(fontStyleBase, fontStyleValue), FunctionPair(fontVariantBase, fontVariantValue), + FunctionPair(fontVariantCapsBase, fontVariantCapsValue), FunctionPair(fontVariantLigaturesBase, fontVariantLigaturesValue), FunctionPair(fontTextRenderingBase, fontTextRenderingValue), FunctionPair(fontKerningBase, fontKerningValue),
diff --git a/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.h b/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.h index 0a18808..831c038 100644 --- a/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.h +++ b/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.h
@@ -65,7 +65,7 @@ // in the CachedMatchedProperties value contain a dead "properties" field. // If there is a dead field the entire cache entry is removed. for (const auto& matchedProperties : cachedProperties->matchedProperties) { - if (!Heap::isHeapObjectAlive(matchedProperties.properties)) { + if (!ThreadHeap::isHeapObjectAlive(matchedProperties.properties)) { // For now report the cache entry as dead. This might not // be the final result if in a subsequent call for this entry, // the "properties" field has been marked via another path. @@ -77,7 +77,7 @@ // had a dead "properties" field so trace CachedMatchedProperties strongly. // FIXME: traceInCollection is also called from WeakProcessing to check if the entry is dead. // Avoid calling trace in that case by only calling trace when cachedProperties is not yet marked. - if (!Heap::isHeapObjectAlive(cachedProperties)) + if (!ThreadHeap::isHeapObjectAlive(cachedProperties)) visitor->trace(cachedProperties); return false; }
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp b/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp index 1a3da35..364dc72 100644 --- a/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp +++ b/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp
@@ -263,6 +263,30 @@ } } +FontDescription::FontVariantCaps StyleBuilderConverter::convertFontVariantCaps(StyleResolverState&, const CSSValue& value) +{ + ASSERT_WITH_SECURITY_IMPLICATION(value.isPrimitiveValue()); + CSSValueID valueID = toCSSPrimitiveValue(value).getValueID(); + switch (valueID) { + case CSSValueNormal: + return FontDescription::CapsNormal; + case CSSValueSmallCaps: + return FontDescription::SmallCaps; + case CSSValueAllSmallCaps: + return FontDescription::AllSmallCaps; + case CSSValuePetiteCaps: + return FontDescription::PetiteCaps; + case CSSValueAllPetiteCaps: + return FontDescription::AllPetiteCaps; + case CSSValueUnicase: + return FontDescription::Unicase; + case CSSValueTitlingCaps: + return FontDescription::TitlingCaps; + default: + return FontDescription::CapsNormal; + } +} + FontDescription::VariantLigatures StyleBuilderConverter::convertFontVariantLigatures(StyleResolverState&, const CSSValue& value) { if (value.isValueList()) {
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.h b/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.h index 7c7fbe5..a36ad442 100644 --- a/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.h +++ b/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.h
@@ -66,6 +66,7 @@ static FontDescription::Size convertFontSize(StyleResolverState&, const CSSValue&); static float convertFontSizeAdjust(StyleResolverState&, const CSSValue&); static FontWeight convertFontWeight(StyleResolverState&, const CSSValue&); + static FontDescription::FontVariantCaps convertFontVariantCaps(StyleResolverState&, const CSSValue&); static FontDescription::VariantLigatures convertFontVariantLigatures(StyleResolverState&, const CSSValue&); static StyleSelfAlignmentData convertSelfOrDefaultAlignmentData(StyleResolverState&, const CSSValue&); static StyleContentAlignmentData convertContentAlignmentData(StyleResolverState&, const CSSValue&);
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp b/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp index 2538ce5..44e1ea7 100644 --- a/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp +++ b/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp
@@ -1276,6 +1276,7 @@ case CSSPropertyFontStretch: case CSSPropertyFontStyle: case CSSPropertyFontVariant: + case CSSPropertyFontVariantCaps: case CSSPropertyFontVariantLigatures: case CSSPropertyFontWeight: case CSSPropertyLetterSpacing:
diff --git a/third_party/WebKit/Source/core/dom/CrossThreadTaskTest.cpp b/third_party/WebKit/Source/core/dom/CrossThreadTaskTest.cpp index 9685906..3cc25959 100644 --- a/third_party/WebKit/Source/core/dom/CrossThreadTaskTest.cpp +++ b/third_party/WebKit/Source/core/dom/CrossThreadTaskTest.cpp
@@ -36,7 +36,7 @@ } void TearDown() override { - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); ASSERT_EQ(0, GCObject::s_counter); } }; @@ -45,7 +45,7 @@ { OwnPtr<ExecutionContextTask> task1 = createCrossThreadTask(&GCObject::run, new GCObject, new GCObject); OwnPtr<ExecutionContextTask> task2 = createCrossThreadTask(&GCObject::run, new GCObject, new GCObject); - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); EXPECT_EQ(4, GCObject::s_counter); } @@ -53,7 +53,7 @@ { OwnPtr<ExecutionContextTask> task1 = createCrossThreadTask(&functionWithGarbageCollected, new GCObject); OwnPtr<ExecutionContextTask> task2 = createCrossThreadTask(&functionWithGarbageCollected, new GCObject); - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); EXPECT_EQ(2, GCObject::s_counter); } @@ -61,7 +61,7 @@ { OwnPtr<ExecutionContextTask> task1 = createCrossThreadTask(&functionWithExecutionContext, new GCObject); OwnPtr<ExecutionContextTask> task2 = createCrossThreadTask(&functionWithExecutionContext, new GCObject); - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); EXPECT_EQ(2, GCObject::s_counter); }
diff --git a/third_party/WebKit/Source/core/dom/DocumentParserTiming.cpp b/third_party/WebKit/Source/core/dom/DocumentParserTiming.cpp index 506daea..795a22aa 100644 --- a/third_party/WebKit/Source/core/dom/DocumentParserTiming.cpp +++ b/third_party/WebKit/Source/core/dom/DocumentParserTiming.cpp
@@ -7,7 +7,6 @@ #include "core/dom/Document.h" #include "core/loader/DocumentLoader.h" #include "platform/TraceEvent.h" -#include "wtf/RawPtr.h" namespace blink {
diff --git a/third_party/WebKit/Source/core/dom/DocumentStatisticsCollectorTest.cpp b/third_party/WebKit/Source/core/dom/DocumentStatisticsCollectorTest.cpp index 952ee7d2..b41df27 100644 --- a/third_party/WebKit/Source/core/dom/DocumentStatisticsCollectorTest.cpp +++ b/third_party/WebKit/Source/core/dom/DocumentStatisticsCollectorTest.cpp
@@ -30,7 +30,7 @@ #if ENABLE(OILPAN) void TearDown() override { - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); } #endif
diff --git a/third_party/WebKit/Source/core/dom/DocumentTest.cpp b/third_party/WebKit/Source/core/dom/DocumentTest.cpp index f6a596c..d96b440d 100644 --- a/third_party/WebKit/Source/core/dom/DocumentTest.cpp +++ b/third_party/WebKit/Source/core/dom/DocumentTest.cpp
@@ -51,7 +51,7 @@ #if ENABLE(OILPAN) void TearDown() override { - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); } #endif
diff --git a/third_party/WebKit/Source/core/dom/DocumentTiming.cpp b/third_party/WebKit/Source/core/dom/DocumentTiming.cpp index 65784a6b..ae2448d 100644 --- a/third_party/WebKit/Source/core/dom/DocumentTiming.cpp +++ b/third_party/WebKit/Source/core/dom/DocumentTiming.cpp
@@ -7,7 +7,6 @@ #include "core/dom/Document.h" #include "core/loader/DocumentLoader.h" #include "platform/TraceEvent.h" -#include "wtf/RawPtr.h" namespace blink {
diff --git a/third_party/WebKit/Source/core/dom/ElementData.cpp b/third_party/WebKit/Source/core/dom/ElementData.cpp index 923a5bd0..ccae12f2e 100644 --- a/third_party/WebKit/Source/core/dom/ElementData.cpp +++ b/third_party/WebKit/Source/core/dom/ElementData.cpp
@@ -163,7 +163,7 @@ ShareableElementData* ShareableElementData::createWithAttributes(const Vector<Attribute>& attributes) { - void* slot = Heap::allocate<ElementData>(sizeForShareableElementDataWithAttributeCount(attributes.size())); + void* slot = ThreadHeap::allocate<ElementData>(sizeForShareableElementDataWithAttributeCount(attributes.size())); return new (slot) ShareableElementData(attributes); } @@ -199,7 +199,7 @@ ShareableElementData* UniqueElementData::makeShareableCopy() const { - void* slot = Heap::allocate<ElementData>(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size())); + void* slot = ThreadHeap::allocate<ElementData>(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size())); return new (slot) ShareableElementData(*this); }
diff --git a/third_party/WebKit/Source/core/dom/ElementData.h b/third_party/WebKit/Source/core/dom/ElementData.h index a396ed7..4683290d 100644 --- a/third_party/WebKit/Source/core/dom/ElementData.h +++ b/third_party/WebKit/Source/core/dom/ElementData.h
@@ -135,7 +135,7 @@ // Add support for placement new as ShareableElementData is not allocated // with a fixed size. Instead the allocated memory size is computed based on - // the number of attributes. This requires us to use Heap::allocate directly + // the number of attributes. This requires us to use ThreadHeap::allocate directly // with the computed size and subsequently call placement new with the // allocated memory address. void* operator new(std::size_t, void* location)
diff --git a/third_party/WebKit/Source/core/dom/IntersectionObserver.cpp b/third_party/WebKit/Source/core/dom/IntersectionObserver.cpp index 9b02dfa..5fff24b7 100644 --- a/third_party/WebKit/Source/core/dom/IntersectionObserver.cpp +++ b/third_party/WebKit/Source/core/dom/IntersectionObserver.cpp
@@ -154,7 +154,7 @@ #if ENABLE(OILPAN) void IntersectionObserver::clearWeakMembers(Visitor* visitor) { - if (Heap::isHeapObjectAlive(m_root)) + if (ThreadHeap::isHeapObjectAlive(m_root)) return; disconnect(); m_root = nullptr;
diff --git a/third_party/WebKit/Source/core/dom/Node.h b/third_party/WebKit/Source/core/dom/Node.h index a2699fa..794aefb 100644 --- a/third_party/WebKit/Source/core/dom/Node.h +++ b/third_party/WebKit/Source/core/dom/Node.h
@@ -182,7 +182,7 @@ { ThreadState* state = ThreadStateFor<ThreadingTrait<Node>::Affinity>::state(); const char typeName[] = "blink::Node"; - return Heap::allocateOnArenaIndex(state, size, isEager ? BlinkGC::EagerSweepArenaIndex : BlinkGC::NodeArenaIndex, GCInfoTrait<EventTarget>::index(), typeName); + return ThreadHeap::allocateOnArenaIndex(state, size, isEager ? BlinkGC::EagerSweepArenaIndex : BlinkGC::NodeArenaIndex, GCInfoTrait<EventTarget>::index(), typeName); } #else // !ENABLE(OILPAN) // All Nodes are placed in their own heap partition for security.
diff --git a/third_party/WebKit/Source/core/dom/ScriptRunnerTest.cpp b/third_party/WebKit/Source/core/dom/ScriptRunnerTest.cpp index 38565aae..003ba1fe 100644 --- a/third_party/WebKit/Source/core/dom/ScriptRunnerTest.cpp +++ b/third_party/WebKit/Source/core/dom/ScriptRunnerTest.cpp
@@ -437,7 +437,7 @@ m_scriptRunner.release(); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); // m_scriptRunner is gone. We need to make sure that ScriptRunner::Task do not access dead object. EXPECT_CALL(*scriptLoader1, execute()).Times(0);
diff --git a/third_party/WebKit/Source/core/editing/markers/DocumentMarkerControllerTest.cpp b/third_party/WebKit/Source/core/editing/markers/DocumentMarkerControllerTest.cpp index 5982612..6e88c299 100644 --- a/third_party/WebKit/Source/core/editing/markers/DocumentMarkerControllerTest.cpp +++ b/third_party/WebKit/Source/core/editing/markers/DocumentMarkerControllerTest.cpp
@@ -101,7 +101,7 @@ anotherDocument->adoptNode(parent, ASSERT_NO_EXCEPTION); // No more reference to marked node. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(0u, markerController().markers().size()); EXPECT_EQ(0u, anotherDocument->markers().markers().size()); } @@ -117,7 +117,7 @@ parent->normalize(); } // No more reference to marked node. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(1u, markerController().markers().size()); } @@ -129,7 +129,7 @@ EXPECT_EQ(1u, markerController().markers().size()); parent->removeChildren(); // No more reference to marked node. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(0u, markerController().markers().size()); } @@ -143,7 +143,7 @@ parent->removeChild(parent->firstChild()); } // No more reference to marked node. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(0u, markerController().markers().size()); } @@ -157,7 +157,7 @@ parent->parentNode()->parentNode()->removeChild(parent->parentNode()); } // No more reference to marked node. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(0u, markerController().markers().size()); } @@ -171,7 +171,7 @@ parent->parentNode()->removeChild(parent); } // No more reference to marked node. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(0u, markerController().markers().size()); } @@ -185,7 +185,7 @@ parent->replaceChild(createTextNode("bar"), parent->firstChild()); } // No more reference to marked node. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(0u, markerController().markers().size()); } @@ -199,7 +199,7 @@ setBodyInnerHTML(""); } // No more reference to marked node. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(0u, markerController().markers().size()); }
diff --git a/third_party/WebKit/Source/core/frame/EventHandlerRegistry.cpp b/third_party/WebKit/Source/core/frame/EventHandlerRegistry.cpp index 5bf13bd2..e437f50 100644 --- a/third_party/WebKit/Source/core/frame/EventHandlerRegistry.cpp +++ b/third_party/WebKit/Source/core/frame/EventHandlerRegistry.cpp
@@ -255,9 +255,9 @@ for (const auto& eventTarget : *targets) { Node* node = eventTarget.key->toNode(); LocalDOMWindow* window = eventTarget.key->toDOMWindow(); - if (node && !Heap::isHeapObjectAlive(node)) { + if (node && !ThreadHeap::isHeapObjectAlive(node)) { deadTargets.append(node); - } else if (window && !Heap::isHeapObjectAlive(window)) { + } else if (window && !ThreadHeap::isHeapObjectAlive(window)) { deadTargets.append(window); } }
diff --git a/third_party/WebKit/Source/core/frame/Frame.cpp b/third_party/WebKit/Source/core/frame/Frame.cpp index 4cb5f44..bf5ad89 100644 --- a/third_party/WebKit/Source/core/frame/Frame.cpp +++ b/third_party/WebKit/Source/core/frame/Frame.cpp
@@ -43,6 +43,8 @@ #include "core/loader/FrameLoaderClient.h" #include "core/page/FocusController.h" #include "core/page/Page.h" +#include "platform/Histogram.h" +#include "platform/UserGestureIndicator.h" #include "wtf/PassOwnPtr.h" namespace blink { @@ -186,10 +188,29 @@ bool Frame::canNavigate(const Frame& targetFrame) { - // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag. - if (!securityContext()->isSandboxed(SandboxTopNavigation) && targetFrame == tree().top()) - return true; + String errorReason; + bool isAllowedNavigation = canNavigateWithoutFramebusting(targetFrame, errorReason); + // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag. + if (targetFrame != this && !securityContext()->isSandboxed(SandboxTopNavigation) && targetFrame == tree().top()) { + DEFINE_STATIC_LOCAL(EnumerationHistogram, framebustHistogram, ("WebCore.Framebust", 4)); + const unsigned userGestureBit = 0x1; + const unsigned allowedBit = 0x2; + unsigned framebustParams = 0; + if (UserGestureIndicator::processingUserGesture()) + framebustParams |= userGestureBit; + if (isAllowedNavigation) + framebustParams |= allowedBit; + framebustHistogram.count(framebustParams); + return true; + } + if (!isAllowedNavigation && !errorReason.isNull()) + printNavigationErrorMessage(targetFrame, errorReason.latin1().data()); + return isAllowedNavigation; +} + +bool Frame::canNavigateWithoutFramebusting(const Frame& targetFrame, String& reason) +{ if (securityContext()->isSandboxed(SandboxNavigation)) { // Sandboxed frames can navigate their own children. if (targetFrame.tree().isDescendantOf(this)) @@ -200,11 +221,10 @@ return true; // Otherwise, block the navigation. - const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors."; if (securityContext()->isSandboxed(SandboxTopNavigation) && targetFrame == tree().top()) reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set."; - - printNavigationErrorMessage(targetFrame, reason); + else + reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors."; return false; } @@ -239,7 +259,7 @@ return true; } - printNavigationErrorMessage(targetFrame, "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener."); + reason = "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener."; return false; }
diff --git a/third_party/WebKit/Source/core/frame/Frame.h b/third_party/WebKit/Source/core/frame/Frame.h index ebba79e2..6a78800 100644 --- a/third_party/WebKit/Source/core/frame/Frame.h +++ b/third_party/WebKit/Source/core/frame/Frame.h
@@ -141,6 +141,8 @@ Member<FrameOwner> m_owner; private: + bool canNavigateWithoutFramebusting(const Frame&, String& errorReason); + Member<FrameClient> m_client; // Needed to identify Frame Timing requests. int64_t m_frameID;
diff --git a/third_party/WebKit/Source/core/frame/ImageBitmapTest.cpp b/third_party/WebKit/Source/core/frame/ImageBitmapTest.cpp index 1c299018..680b60b 100644 --- a/third_party/WebKit/Source/core/frame/ImageBitmapTest.cpp +++ b/third_party/WebKit/Source/core/frame/ImageBitmapTest.cpp
@@ -69,7 +69,7 @@ // Garbage collection is required prior to switching out the // test's memory cache; image resources are released, evicting // them from the cache. - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); replaceMemoryCacheForTesting(m_globalMemoryCache.release()); }
diff --git a/third_party/WebKit/Source/core/frame/UseCounter.cpp b/third_party/WebKit/Source/core/frame/UseCounter.cpp index 795dfc8..10e2f86 100644 --- a/third_party/WebKit/Source/core/frame/UseCounter.cpp +++ b/third_party/WebKit/Source/core/frame/UseCounter.cpp
@@ -565,6 +565,7 @@ case CSSPropertyColumnWidth: return 530; case CSSPropertyColumns: return 531; case CSSPropertyApplyAtRule: return 532; + case CSSPropertyFontVariantCaps: return 533; // 1. Add new features above this line (don't change the assigned numbers of the existing // items). @@ -581,7 +582,7 @@ return 0; } -static int maximumCSSSampleId() { return 532; } +static int maximumCSSSampleId() { return 533; } static EnumerationHistogram& featureObserverHistogram() {
diff --git a/third_party/WebKit/Source/core/html/AutoplayExperimentTest.cpp b/third_party/WebKit/Source/core/html/AutoplayExperimentTest.cpp index dc83244..7f92c66 100644 --- a/third_party/WebKit/Source/core/html/AutoplayExperimentTest.cpp +++ b/third_party/WebKit/Source/core/html/AutoplayExperimentTest.cpp
@@ -124,7 +124,7 @@ // causing a test failure. m_helper.clear(); m_client.clear(); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); } Persistent<MockAutoplayClient> m_client;
diff --git a/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp b/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp index 10a307e..fc47d2e 100644 --- a/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp
@@ -3762,7 +3762,7 @@ void HTMLMediaElement::clearWeakMembers(Visitor* visitor) { - if (!Heap::isHeapObjectAlive(m_audioSourceNode)) + if (!ThreadHeap::isHeapObjectAlive(m_audioSourceNode)) getAudioSourceProvider().setClient(nullptr); }
diff --git a/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp b/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp index 7705bf88..49897d7c 100644 --- a/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp +++ b/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.cpp
@@ -28,7 +28,6 @@ #include "wtf/StringExtras.h" #include "wtf/text/TextCodec.h" #include "wtf/text/TextEncodingRegistry.h" -#include "wtf/text/UTF8.h" using namespace WTF; @@ -350,6 +349,23 @@ return; } +// We use the encoding detector in two cases: +// 1. Encoding detector is turned ON and no other encoding source is +// available (that is, it's DefaultEncoding). +// 2. Encoding detector is turned ON and the encoding is set to +// the encoding of the parent frame, which is also auto-detected. +// Note that condition #2 is NOT satisfied unless parent-child frame +// relationship is compliant to the same-origin policy. If they're from +// different domains, |m_source| would not be set to EncodingFromParentFrame +// in the first place. +bool TextResourceDecoder::shouldAutoDetect() const +{ + // Just checking m_hintEncoding suffices here because it's only set + // in setHintEncoding when the source is AutoDetectedEncoding. + return m_encodingDetectionOption == UseAllAutoDetection + && (m_source == DefaultEncoding || (m_source == EncodingFromParentFrame && m_hintEncoding)); +} + String TextResourceDecoder::decode(const char* data, size_t len) { size_t lengthOfBOM = 0; @@ -386,7 +402,11 @@ if (m_contentType == HTMLContent && !m_checkedForMetaCharset) checkForMetaCharset(dataForDecode, lengthForDecode); - detectTextEncoding(data, len); + if (shouldAutoDetect()) { + WTF::TextEncoding detectedEncoding; + if (detectTextEncoding(data, len, m_hintEncoding, &detectedEncoding)) + setEncoding(detectedEncoding, EncodingFromContentSniffing); + } ASSERT(m_encoding.isValid()); @@ -399,46 +419,16 @@ return result; } -// We use the encoding detector in following cases: -// 1. Encoding detector is turned ON and no other encoding source is -// available (that is, it's DefaultEncoding). -// 2. Encoding detector is turned ON and the encoding is set to -// the encoding of the parent frame, which is also auto-detected. -// Note that condition #2 is NOT satisfied unless parent-child frame -// relationship is compliant to the same-origin policy. If they're from -// different domains, |m_source| would not be set to EncodingFromParentFrame -// in the first place. -void TextResourceDecoder::detectTextEncoding(const char* data, size_t len) -{ - if (!shouldDetectEncoding()) - return; - - if (WTF::Unicode::isUTF8andNotASCII(data, len)) { - setEncoding(UTF8Encoding(), EncodingFromContentSniffing); - return; - } - if (m_encodingDetectionOption == UseAllAutoDetection) { - WTF::TextEncoding detectedEncoding; - if (detectTextEncodingUniversal(data, len, m_hintEncoding, &detectedEncoding)) - setEncoding(detectedEncoding, EncodingFromContentSniffing); - } -} - -bool TextResourceDecoder::shouldDetectEncoding() const -{ - // Just checking m_hintEncoding suffices here because it's only set - // in setHintEncoding when the source is AutoDetectedEncoding. - return m_source == DefaultEncoding || (m_source == EncodingFromParentFrame && m_hintEncoding); -} - String TextResourceDecoder::flush() { // If we can not identify the encoding even after a document is completely // loaded, we need to detect the encoding if other conditions for // autodetection is satisfied. - if (m_buffer.size() + if (m_buffer.size() && shouldAutoDetect() && ((!m_checkedForXMLCharset && (m_contentType == HTMLContent || m_contentType == XMLContent)) || (!m_checkedForCSSCharset && (m_contentType == CSSContent)))) { - detectTextEncoding(m_buffer.data(), m_buffer.size()); + WTF::TextEncoding detectedEncoding; + if (detectTextEncoding(m_buffer.data(), m_buffer.size(), m_hintEncoding, &detectedEncoding)) + setEncoding(detectedEncoding, EncodingFromContentSniffing); } if (!m_codec)
diff --git a/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.h b/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.h index bdfa0d6..82411a7 100644 --- a/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.h +++ b/third_party/WebKit/Source/core/html/parser/TextResourceDecoder.h
@@ -79,18 +79,16 @@ private: - // TextResourceDecoder does four kinds of encoding detection: + // TextResourceDecoder does three kind of encoding detection: // 1. By BOM, // 2. By Content if |m_contentType| is not |PlainTextContext| - // (e.g. <meta> tag for HTML), - // 3. By isUTF8Encoded() to detect if the document - // is of UTF-8, and - // 4. By detectTextEncodingUniversal(). + // (e.g. <meta> tag for HTML), and + // 3. By detectTextEncoding(). enum EncodingDetectionOption { - // Use 1. + 2. + 4. + // Use 1. + 2. + 3. UseAllAutoDetection, - // Use 1. + 2. + 3. + // Use 1. + 2. UseContentAndBOMBasedDetection, // Use None of them. @@ -110,8 +108,7 @@ bool checkForCSSCharset(const char*, size_t, bool& movedDataToBuffer); bool checkForXMLCharset(const char*, size_t, bool& movedDataToBuffer); void checkForMetaCharset(const char*, size_t); - void detectTextEncoding(const char*, size_t); - bool shouldDetectEncoding() const; + bool shouldAutoDetect() const; ContentType m_contentType; WTF::TextEncoding m_encoding;
diff --git a/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp b/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp index 5ee318d..21949b93 100644 --- a/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp +++ b/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp
@@ -45,6 +45,8 @@ #include "core/layout/api/LayoutSliderItem.h" #include "platform/Histogram.h" #include "platform/RuntimeEnabledFeatures.h" +#include "public/platform/Platform.h" +#include "public/platform/UserMetricsAction.h" namespace blink { @@ -254,6 +256,11 @@ void MediaControlMuteButtonElement::defaultEventHandler(Event* event) { if (event->type() == EventTypeNames::click) { + if (mediaElement().muted()) + Platform::current()->recordAction(UserMetricsAction("Media.Controls.Unmute")); + else + Platform::current()->recordAction(UserMetricsAction("Media.Controls.Mute")); + mediaElement().setMuted(!mediaElement().muted()); event->setDefaultHandled(); } @@ -285,6 +292,11 @@ void MediaControlPlayButtonElement::defaultEventHandler(Event* event) { if (event->type() == EventTypeNames::click) { + if (mediaElement().paused()) + Platform::current()->recordAction(UserMetricsAction("Media.Controls.Play")); + else + Platform::current()->recordAction(UserMetricsAction("Media.Controls.Pause")); + // Allow play attempts for plain src= media to force a reload in the error state. This allows potential // recovery for transient network and decoder resource issues. const String& url = mediaElement().currentSrc().getString(); @@ -322,6 +334,7 @@ void MediaControlOverlayPlayButtonElement::defaultEventHandler(Event* event) { if (event->type() == EventTypeNames::click && mediaElement().paused()) { + Platform::current()->recordAction(UserMetricsAction("Media.Controls.PlayOverlay")); mediaElement().play(); updateDisplayType(); event->setDefaultHandled(); @@ -366,6 +379,10 @@ void MediaControlToggleClosedCaptionsButtonElement::defaultEventHandler(Event* event) { if (event->type() == EventTypeNames::click) { + if (mediaElement().closedCaptionsVisible()) + Platform::current()->recordAction(UserMetricsAction("Media.Controls.ClosedCaptionHide")); + else + Platform::current()->recordAction(UserMetricsAction("Media.Controls.ClosedCaptionShow")); mediaElement().setClosedCaptionsVisible(!mediaElement().closedCaptionsVisible()); setChecked(mediaElement().closedCaptionsVisible()); updateDisplayType(); @@ -400,11 +417,15 @@ if (!inShadowIncludingDocument() || !document().isActive()) return; - if (event->type() == EventTypeNames::mousedown) + if (event->type() == EventTypeNames::mousedown) { + Platform::current()->recordAction(UserMetricsAction("Media.Controls.ScrubbingBegin")); mediaControls().beginScrubbing(); + } - if (event->type() == EventTypeNames::mouseup) + if (event->type() == EventTypeNames::mouseup) { + Platform::current()->recordAction(UserMetricsAction("Media.Controls.ScrubbingEnd")); mediaControls().endScrubbing(); + } MediaControlInputElement::defaultEventHandler(event); @@ -481,6 +502,12 @@ if (event->type() == EventTypeNames::mouseover || event->type() == EventTypeNames::mouseout || event->type() == EventTypeNames::mousemove) return; + if (event->type() == EventTypeNames::mousedown) + Platform::current()->recordAction(UserMetricsAction("Media.Controls.VolumeChangeBegin")); + + if (event->type() == EventTypeNames::mouseup) + Platform::current()->recordAction(UserMetricsAction("Media.Controls.VolumeChangeEnd")); + double volume = value().toDouble(); mediaElement().setVolume(volume, ASSERT_NO_EXCEPTION); mediaElement().setMuted(false); @@ -533,10 +560,13 @@ void MediaControlFullscreenButtonElement::defaultEventHandler(Event* event) { if (event->type() == EventTypeNames::click) { - if (mediaElement().isFullscreen()) + if (mediaElement().isFullscreen()) { + Platform::current()->recordAction(UserMetricsAction("Media.Controls.ExitFullscreen")); mediaElement().exitFullscreen(); - else + } else { + Platform::current()->recordAction(UserMetricsAction("Media.Controls.EnterFullscreen")); mediaElement().enterFullscreen(); + } event->setDefaultHandled(); } HTMLInputElement::defaultEventHandler(event); @@ -568,6 +598,11 @@ void MediaControlCastButtonElement::defaultEventHandler(Event* event) { if (event->type() == EventTypeNames::click) { + if (m_isOverlayButton) + Platform::current()->recordAction(UserMetricsAction("Media.Controls.CastOverlay")); + else + Platform::current()->recordAction(UserMetricsAction("Media.Controls.Cast")); + if (m_isOverlayButton && !m_clickUseCounted) { m_clickUseCounted = true; recordMetrics(CastOverlayMetrics::Clicked);
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGInlineText.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGInlineText.cpp index 3154e73..27da507 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGInlineText.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGInlineText.cpp
@@ -207,7 +207,7 @@ namespace { -inline bool characterStartsSurrogatePair(const TextRun& run, unsigned index) +inline bool isValidSurrogatePair(const TextRun& run, unsigned index) { if (!U16_IS_LEAD(run[index])) return false; @@ -216,57 +216,7 @@ return U16_IS_TRAIL(run[index + 1]); } -class SVGTextMetricsCalculator { -public: - SVGTextMetricsCalculator(LayoutSVGInlineText&); - ~SVGTextMetricsCalculator(); - - bool advancePosition(); - unsigned currentPosition() const { return m_currentPosition; } - - SVGTextMetrics currentCharacterMetrics(); - - // TODO(pdr): Character-based iteration is ambiguous and error-prone. It - // should be unified under a single concept. See: https://crbug.com/593570 - bool currentCharacterStartsSurrogatePair() const - { - return characterStartsSurrogatePair(m_run, m_currentPosition); - } - bool currentCharacterIsWhiteSpace() const - { - return m_run[m_currentPosition] == ' '; - } - unsigned characterCount() const - { - return static_cast<unsigned>(m_run.charactersLength()); - } - -private: - void setupBidiRuns(); - - static TextRun constructTextRun(LayoutSVGInlineText&, unsigned position, unsigned length, TextDirection); - - // Ensure |m_subrunRanges| is updated for the current bidi run, or the - // complete m_run if no bidi runs are present. Returns the current position - // in the subrun which can be used to index into |m_subrunRanges|. - unsigned updateSubrunRangesForCurrentPosition(); - - // Current character position in m_text. - unsigned m_currentPosition; - - LayoutSVGInlineText& m_text; - float m_fontScalingFactor; - float m_cachedFontHeight; - TextRun m_run; - - BidiCharacterRun* m_bidiRun; - BidiResolver<TextRunIterator, BidiCharacterRun> m_bidiResolver; - - // Ranges for the current bidi run if present, or the entire run otherwise. - Vector<CharacterRange> m_subrunRanges; -}; - -TextRun SVGTextMetricsCalculator::constructTextRun(LayoutSVGInlineText& text, unsigned position, unsigned length, TextDirection textDirection) +TextRun constructTextRun(LayoutSVGInlineText& text, unsigned position, unsigned length, TextDirection textDirection) { const ComputedStyle& style = text.styleRef(); @@ -294,56 +244,12 @@ return run; } -SVGTextMetricsCalculator::SVGTextMetricsCalculator(LayoutSVGInlineText& text) - : m_currentPosition(0) - , m_text(text) - , m_fontScalingFactor(m_text.scalingFactor()) - , m_cachedFontHeight(m_text.scaledFont().getFontMetrics().floatHeight() / m_fontScalingFactor) - , m_run(constructTextRun(m_text, 0, m_text.textLength(), m_text.styleRef().direction())) - , m_bidiRun(nullptr) -{ - setupBidiRuns(); -} - -SVGTextMetricsCalculator::~SVGTextMetricsCalculator() -{ - m_bidiResolver.runs().deleteRuns(); -} - -void SVGTextMetricsCalculator::setupBidiRuns() -{ - BidiRunList<BidiCharacterRun>& bidiRuns = m_bidiResolver.runs(); - bool bidiOverride = isOverride(m_text.styleRef().unicodeBidi()); - BidiStatus status(LTR, bidiOverride); - if (m_run.is8Bit() || bidiOverride) { - WTF::Unicode::CharDirection direction = WTF::Unicode::LeftToRight; - // If BiDi override is in effect, use the specified direction. - if (bidiOverride && !m_text.styleRef().isLeftToRightDirection()) - direction = WTF::Unicode::RightToLeft; - bidiRuns.addRun(new BidiCharacterRun(0, m_run.charactersLength(), status.context.get(), direction)); - } else { - status.last = status.lastStrong = WTF::Unicode::OtherNeutral; - m_bidiResolver.setStatus(status); - m_bidiResolver.setPositionIgnoringNestedIsolates(TextRunIterator(&m_run, 0)); - const bool hardLineBreak = false; - const bool reorderRuns = false; - m_bidiResolver.createBidiRunsForLine(TextRunIterator(&m_run, m_run.length()), NoVisualOverride, hardLineBreak, reorderRuns); - } - m_bidiRun = bidiRuns.firstRun(); -} - -bool SVGTextMetricsCalculator::advancePosition() -{ - m_currentPosition += currentCharacterStartsSurrogatePair() ? 2 : 1; - return m_currentPosition < characterCount(); -} - // TODO(pdr): We only have per-glyph data so we need to synthesize per-grapheme // data. E.g., if 'fi' is shaped into a single glyph, we do not know the 'i' // position. The code below synthesizes an average glyph width when characters // share a single position. This will incorrectly split combining diacritics. // See: https://crbug.com/473476. -static void synthesizeGraphemeWidths(const TextRun& run, Vector<CharacterRange>& ranges) +void synthesizeGraphemeWidths(const TextRun& run, Vector<CharacterRange>& ranges) { unsigned distributeCount = 0; for (int rangeIndex = static_cast<int>(ranges.size()) - 1; rangeIndex >= 0; --rangeIndex) { @@ -352,7 +258,7 @@ distributeCount++; } else if (distributeCount != 0) { // Only count surrogate pairs as a single character. - bool surrogatePair = characterStartsSurrogatePair(run, rangeIndex); + bool surrogatePair = isValidSurrogatePair(run, rangeIndex); if (!surrogatePair) distributeCount++; @@ -373,39 +279,39 @@ } } -unsigned SVGTextMetricsCalculator::updateSubrunRangesForCurrentPosition() -{ - ASSERT(m_bidiRun); - if (m_currentPosition >= static_cast<unsigned>(m_bidiRun->stop())) { - m_bidiRun = m_bidiRun->next(); - // Ensure new subrange ranges are computed below. - m_subrunRanges.clear(); - } - ASSERT(m_bidiRun); - ASSERT(static_cast<int>(m_currentPosition) < m_bidiRun->stop()); - - unsigned positionInRun = m_currentPosition - m_bidiRun->start(); - if (positionInRun >= m_subrunRanges.size()) { - TextRun subRun = constructTextRun(m_text, m_bidiRun->start(), - m_bidiRun->stop() - m_bidiRun->start(), m_bidiRun->direction()); - m_subrunRanges = m_text.scaledFont().individualCharacterRanges(subRun); - synthesizeGraphemeWidths(subRun, m_subrunRanges); - } - - ASSERT(m_subrunRanges.size() && positionInRun < m_subrunRanges.size()); - return positionInRun; -} - -SVGTextMetrics SVGTextMetricsCalculator::currentCharacterMetrics() -{ - unsigned currentSubrunPosition = updateSubrunRangesForCurrentPosition(); - unsigned length = currentCharacterStartsSurrogatePair() ? 2 : 1; - float width = m_subrunRanges[currentSubrunPosition].width(); - return SVGTextMetrics(length, width / m_fontScalingFactor, m_cachedFontHeight); -} - } // namespace +void LayoutSVGInlineText::addMetricsFromRun( + const TextRun& run, bool& lastCharacterWasWhiteSpace) +{ + Vector<CharacterRange> charRanges = scaledFont().individualCharacterRanges(run); + synthesizeGraphemeWidths(run, charRanges); + + const float cachedFontHeight = scaledFont().getFontMetrics().floatHeight() / m_scalingFactor; + const bool preserveWhiteSpace = styleRef().whiteSpace() == PRE; + const unsigned runLength = static_cast<unsigned>(run.length()); + + // TODO(pdr): Character-based iteration is ambiguous and error-prone. It + // should be unified under a single concept. See: https://crbug.com/593570 + unsigned characterIndex = 0; + while (characterIndex < runLength) { + bool currentCharacterIsWhiteSpace = run[characterIndex] == ' '; + if (!preserveWhiteSpace && lastCharacterWasWhiteSpace && currentCharacterIsWhiteSpace) { + m_metrics.append(SVGTextMetrics(SVGTextMetrics::SkippedSpaceMetrics)); + characterIndex++; + continue; + } + + unsigned length = isValidSurrogatePair(run, characterIndex) ? 2 : 1; + float width = charRanges[characterIndex].width() / m_scalingFactor; + + m_metrics.append(SVGTextMetrics(length, width, cachedFontHeight)); + + lastCharacterWasWhiteSpace = currentCharacterIsWhiteSpace; + characterIndex += length; + } +} + void LayoutSVGInlineText::updateMetricsList(bool& lastCharacterWasWhiteSpace) { m_metrics.clear(); @@ -413,23 +319,33 @@ if (!textLength()) return; - // TODO(pdr): This loop is too tightly coupled to SVGTextMetricsCalculator. - // We should refactor SVGTextMetricsCalculator to be a simple bidi run - // iterator and move all subrun logic to a single function. - SVGTextMetricsCalculator calculator(*this); - bool preserveWhiteSpace = styleRef().whiteSpace() == PRE; - do { - bool currentCharacterIsWhiteSpace = calculator.currentCharacterIsWhiteSpace(); - if (!preserveWhiteSpace && lastCharacterWasWhiteSpace && currentCharacterIsWhiteSpace) { - m_metrics.append(SVGTextMetrics(SVGTextMetrics::SkippedSpaceMetrics)); - ASSERT(calculator.currentCharacterMetrics().length() == 1); - continue; - } + TextRun run = constructTextRun(*this, 0, textLength(), styleRef().direction()); + BidiResolver<TextRunIterator, BidiCharacterRun> bidiResolver; + BidiRunList<BidiCharacterRun>& bidiRuns = bidiResolver.runs(); + bool bidiOverride = isOverride(styleRef().unicodeBidi()); + BidiStatus status(LTR, bidiOverride); + if (run.is8Bit() || bidiOverride) { + WTF::Unicode::CharDirection direction = WTF::Unicode::LeftToRight; + // If BiDi override is in effect, use the specified direction. + if (bidiOverride && !styleRef().isLeftToRightDirection()) + direction = WTF::Unicode::RightToLeft; + bidiRuns.addRun(new BidiCharacterRun(0, run.charactersLength(), status.context.get(), direction)); + } else { + status.last = status.lastStrong = WTF::Unicode::OtherNeutral; + bidiResolver.setStatus(status); + bidiResolver.setPositionIgnoringNestedIsolates(TextRunIterator(&run, 0)); + const bool hardLineBreak = false; + const bool reorderRuns = false; + bidiResolver.createBidiRunsForLine(TextRunIterator(&run, run.length()), NoVisualOverride, hardLineBreak, reorderRuns); + } - m_metrics.append(calculator.currentCharacterMetrics()); + for (const BidiCharacterRun* bidiRun = bidiRuns.firstRun(); bidiRun; bidiRun = bidiRun->next()) { + TextRun subRun = constructTextRun(*this, bidiRun->start(), bidiRun->stop() - bidiRun->start(), + bidiRun->direction()); + addMetricsFromRun(subRun, lastCharacterWasWhiteSpace); + } - lastCharacterWasWhiteSpace = currentCharacterIsWhiteSpace; - } while (calculator.advancePosition()); + bidiResolver.runs().deleteRuns(); } void LayoutSVGInlineText::updateScaledFont()
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGInlineText.h b/third_party/WebKit/Source/core/layout/svg/LayoutSVGInlineText.h index b073878..7ef1f3b4 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGInlineText.h +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGInlineText.h
@@ -56,6 +56,8 @@ void setTextInternal(PassRefPtr<StringImpl>) override; void styleDidChange(StyleDifference, const ComputedStyle*) override; + void addMetricsFromRun(const TextRun&, bool& lastCharacterWasWhiteSpace); + FloatRect objectBoundingBox() const override { return floatLinesBoundingBox(); } bool isOfType(LayoutObjectType type) const override { return type == LayoutObjectSVG || type == LayoutObjectSVGInlineText || LayoutText::isOfType(type); }
diff --git a/third_party/WebKit/Source/core/loader/DocumentLoadTiming.cpp b/third_party/WebKit/Source/core/loader/DocumentLoadTiming.cpp index 878eff4..6c5b7cea 100644 --- a/third_party/WebKit/Source/core/loader/DocumentLoadTiming.cpp +++ b/third_party/WebKit/Source/core/loader/DocumentLoadTiming.cpp
@@ -28,7 +28,6 @@ #include "core/loader/DocumentLoader.h" #include "platform/TraceEvent.h" #include "platform/weborigin/SecurityOrigin.h" -#include "wtf/RawPtr.h" #include "wtf/RefPtr.h" namespace blink {
diff --git a/third_party/WebKit/Source/core/paint/PaintTiming.cpp b/third_party/WebKit/Source/core/paint/PaintTiming.cpp index 9fffec3f..7ff505a 100644 --- a/third_party/WebKit/Source/core/paint/PaintTiming.cpp +++ b/third_party/WebKit/Source/core/paint/PaintTiming.cpp
@@ -7,7 +7,6 @@ #include "core/dom/Document.h" #include "core/loader/DocumentLoader.h" #include "platform/TraceEvent.h" -#include "wtf/RawPtr.h" namespace blink {
diff --git a/third_party/WebKit/Source/core/svg/SVGElementRareData.cpp b/third_party/WebKit/Source/core/svg/SVGElementRareData.cpp index f30f5b53..24a2bae2 100644 --- a/third_party/WebKit/Source/core/svg/SVGElementRareData.cpp +++ b/third_party/WebKit/Source/core/svg/SVGElementRareData.cpp
@@ -46,10 +46,10 @@ void SVGElementRareData::processWeakMembers(Visitor* visitor) { ASSERT(m_owner); - if (!Heap::isHeapObjectAlive(m_cursorElement)) + if (!ThreadHeap::isHeapObjectAlive(m_cursorElement)) m_cursorElement = nullptr; - if (!Heap::isHeapObjectAlive(m_cursorImageValue)) { + if (!ThreadHeap::isHeapObjectAlive(m_cursorImageValue)) { // The owning SVGElement is still alive and if it is pointing to an SVGCursorElement // we unregister it when the CSSCursorImageValue dies. if (m_cursorElement) { @@ -58,8 +58,8 @@ } m_cursorImageValue = nullptr; } - ASSERT(!m_cursorElement || Heap::isHeapObjectAlive(m_cursorElement)); - ASSERT(!m_cursorImageValue || Heap::isHeapObjectAlive(m_cursorImageValue)); + ASSERT(!m_cursorElement || ThreadHeap::isHeapObjectAlive(m_cursorElement)); + ASSERT(!m_cursorImageValue || ThreadHeap::isHeapObjectAlive(m_cursorImageValue)); } AffineTransform* SVGElementRareData::animateMotionTransform()
diff --git a/third_party/WebKit/Source/core/svg/graphics/SVGImageChromeClient.cpp b/third_party/WebKit/Source/core/svg/graphics/SVGImageChromeClient.cpp index 5d9de61..808438d 100644 --- a/third_party/WebKit/Source/core/svg/graphics/SVGImageChromeClient.cpp +++ b/third_party/WebKit/Source/core/svg/graphics/SVGImageChromeClient.cpp
@@ -94,7 +94,7 @@ // // TODO(Oilpan): move (SVG)Image to the Oilpan heap, and avoid // this explicit lifetime check. - if (Heap::willObjectBeLazilySwept(m_image->getImageObserver())) + if (ThreadHeap::willObjectBeLazilySwept(m_image->getImageObserver())) return; // serviceScriptedAnimations runs requestAnimationFrame callbacks, but SVG
diff --git a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp index bd4b897..9de6192 100644 --- a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp +++ b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp
@@ -1544,11 +1544,8 @@ if (m_responseTypeCode == ResponseTypeJSON) return TextResourceDecoder::create("application/json", "UTF-8"); - if (!m_finalResponseCharset.isEmpty()) { - OwnPtr<TextResourceDecoder> decoder(TextResourceDecoder::create("text/plain")); - decoder->setEncoding(WTF::TextEncoding(m_finalResponseCharset), TextResourceDecoder::EncodingFromHTTPHeader); - return decoder.release(); - } + if (!m_finalResponseCharset.isEmpty()) + return TextResourceDecoder::create("text/plain", m_finalResponseCharset); // allow TextResourceDecoder to look inside the m_response if it's XML or HTML if (responseIsXML()) {
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineModel.js b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineModel.js index 70686f5..289b2dc 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineModel.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineModel.js
@@ -156,7 +156,7 @@ ImplSideFling: "InputHandlerProxy::HandleGestureFling::started", GCIdleLazySweep: "ThreadState::performIdleLazySweep", GCCompleteSweep: "ThreadState::completeSweep", - GCCollectGarbage: "Heap::collectGarbage", + GCCollectGarbage: "BlinkGCMarking", // CpuProfile is a virtual event created on frontend to support // serialization of CPU Profiles within tracing timeline data.
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DTest.cpp b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DTest.cpp index e708cf6b..65d43de 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DTest.cpp +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DTest.cpp
@@ -170,7 +170,7 @@ void CanvasRenderingContext2DTest::TearDown() { - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); replaceMemoryCacheForTesting(m_globalMemoryCache.release()); }
diff --git a/third_party/WebKit/Source/modules/csspaint/PaintWorkletTest.cpp b/third_party/WebKit/Source/modules/csspaint/PaintWorkletTest.cpp index 8a23cae2..43612f8 100644 --- a/third_party/WebKit/Source/modules/csspaint/PaintWorkletTest.cpp +++ b/third_party/WebKit/Source/modules/csspaint/PaintWorkletTest.cpp
@@ -64,7 +64,7 @@ ASSERT(handle.isWeak()); // Run a GC, persistent shouldn't have been collected yet. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); V8GCController::collectAllGarbageForTesting(isolate); ASSERT(!handle.isEmpty()); @@ -72,7 +72,7 @@ m_page.clear(); // Run a GC, the persistent should have been collected. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); V8GCController::collectAllGarbageForTesting(isolate); ASSERT(handle.isEmpty()); }
diff --git a/third_party/WebKit/Source/modules/fetch/BodyStreamBufferTest.cpp b/third_party/WebKit/Source/modules/fetch/BodyStreamBufferTest.cpp index 7525582..ffe1121 100644 --- a/third_party/WebKit/Source/modules/fetch/BodyStreamBufferTest.cpp +++ b/third_party/WebKit/Source/modules/fetch/BodyStreamBufferTest.cpp
@@ -269,7 +269,7 @@ Persistent<BodyStreamBuffer> buffer = new BodyStreamBuffer(createFetchDataConsumerHandleFromWebHandle(handle.release())); buffer->startLoading(getExecutionContext(), FetchDataLoader::createLoaderAsString(), client); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); checkpoint.Call(1); testing::runPendingTasks(); checkpoint.Call(2);
diff --git a/third_party/WebKit/Source/modules/fetch/CrossThreadHolder.h b/third_party/WebKit/Source/modules/fetch/CrossThreadHolder.h index 20ad171..be28fae 100644 --- a/third_party/WebKit/Source/modules/fetch/CrossThreadHolder.h +++ b/third_party/WebKit/Source/modules/fetch/CrossThreadHolder.h
@@ -65,12 +65,12 @@ private: // Object graph: // +------+ +-----------------+ - // T <-OwnPtr- |Bridge| ---------RawPtr--------> |CrossThreadHolder| + // T <-OwnPtr- |Bridge| ---------*-------------> |CrossThreadHolder| // | | <-CrossThreadPersistent- | | // +------+ +-----------------+ // | | // +--RefPtr--> MutexWrapper <--RefPtr--+ - // The CrossThreadPersistent/RawPtr between CrossThreadHolder and Bridge + // The CrossThreadPersistent<T>/T* between CrossThreadHolder and Bridge // are protected by MutexWrapper // and cleared when CrossThreadHolder::clearInternal() is called, i.e.: // [1] when |executionContext| is stopped, or
diff --git a/third_party/WebKit/Source/modules/fetch/DataConsumerTeeTest.cpp b/third_party/WebKit/Source/modules/fetch/DataConsumerTeeTest.cpp index f60c4a575..1f746d10 100644 --- a/third_party/WebKit/Source/modules/fetch/DataConsumerTeeTest.cpp +++ b/third_party/WebKit/Source/modules/fetch/DataConsumerTeeTest.cpp
@@ -320,7 +320,7 @@ dest2 = nullptr; // Collect garbage to finalize the source reader. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); context->detached()->wait(); }
diff --git a/third_party/WebKit/Source/modules/fetch/FetchBlobDataConsumerHandleTest.cpp b/third_party/WebKit/Source/modules/fetch/FetchBlobDataConsumerHandleTest.cpp index fa67bd3..759b52e 100644 --- a/third_party/WebKit/Source/modules/fetch/FetchBlobDataConsumerHandleTest.cpp +++ b/third_party/WebKit/Source/modules/fetch/FetchBlobDataConsumerHandleTest.cpp
@@ -81,7 +81,7 @@ { m_dummyPageHolder = nullptr; // We need this to collect garbage-collected mocks. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); } Document& document() { return m_dummyPageHolder->document(); } @@ -200,7 +200,7 @@ handle = nullptr; reader = nullptr; checkpoint.Call(3); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); checkpoint.Call(4); }
diff --git a/third_party/WebKit/Source/modules/indexeddb/IDBTransactionTest.cpp b/third_party/WebKit/Source/modules/indexeddb/IDBTransactionTest.cpp index 8fb436a6..2695044 100644 --- a/third_party/WebKit/Source/modules/indexeddb/IDBTransactionTest.cpp +++ b/third_party/WebKit/Source/modules/indexeddb/IDBTransactionTest.cpp
@@ -101,13 +101,13 @@ PersistentHeapHashSet<WeakMember<IDBTransaction>> set; set.add(transaction); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(1u, set.size()); Persistent<IDBRequest> request = IDBRequest::create(getScriptState(), IDBAny::createUndefined(), transaction.get()); deactivateNewTransactions(); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(1u, set.size()); // This will generate an abort() call to the back end which is dropped by the fake proxy, @@ -116,7 +116,7 @@ transaction->onAbort(DOMException::create(AbortError, "Aborted")); transaction.clear(); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(0u, set.size()); } @@ -136,17 +136,17 @@ PersistentHeapHashSet<WeakMember<IDBTransaction>> set; set.add(transaction); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(1u, set.size()); deactivateNewTransactions(); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(1u, set.size()); transaction.clear(); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(1u, set.size()); // Stop the context, so events don't get queued (which would keep the transaction alive). @@ -157,7 +157,7 @@ db->onAbort(transactionId, DOMException::create(AbortError, "Aborted")); // onAbort() should have cleared the transaction's reference to the database. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(0u, set.size()); }
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaConstraintsImpl.cpp b/third_party/WebKit/Source/modules/mediastream/MediaConstraintsImpl.cpp index 1369ede..2426219 100644 --- a/third_party/WebKit/Source/modules/mediastream/MediaConstraintsImpl.cpp +++ b/third_party/WebKit/Source/modules/mediastream/MediaConstraintsImpl.cpp
@@ -37,7 +37,7 @@ #include "core/dom/ExecutionContext.h" #include "core/frame/UseCounter.h" #include "core/inspector/ConsoleMessage.h" -#include "modules/mediastream/MediaTrackConstraintSet.h" +#include "modules/mediastream/MediaTrackConstraints.h" #include "platform/Logging.h" #include "platform/RuntimeEnabledFeatures.h" #include "wtf/HashMap.h" @@ -243,7 +243,7 @@ return true; } -static bool parse(const MediaTrackConstraintSet& constraintsIn, WebVector<WebMediaConstraint>& optional, WebVector<WebMediaConstraint>& mandatory) +static bool parse(const MediaTrackConstraints& constraintsIn, WebVector<WebMediaConstraint>& optional, WebVector<WebMediaConstraint>& mandatory) { Vector<WebMediaConstraint> mandatoryConstraintsVector; if (constraintsIn.hasMandatory()) { @@ -554,17 +554,24 @@ } } -WebMediaConstraints create(ExecutionContext* context, const MediaTrackConstraintSet& constraintsIn, MediaErrorState& errorState) +WebMediaConstraints create(ExecutionContext* context, const MediaTrackConstraints& constraintsIn, MediaErrorState& errorState) { WebMediaConstraints constraints; WebMediaTrackConstraintSet constraintBuffer; - WebVector<WebMediaTrackConstraintSet> advancedBuffer; + Vector<WebMediaTrackConstraintSet> advancedBuffer; copyConstraints(constraintsIn, constraintBuffer); + if (constraintsIn.hasAdvanced()) { + for (const auto& element : constraintsIn.advanced()) { + WebMediaTrackConstraintSet advancedElement; + copyConstraints(element, advancedElement); + advancedBuffer.append(advancedElement); + } + } // TODO(hta): Add initialization of advanced constraints once present. // https://crbug.com/253412 if (constraintsIn.hasOptional() || constraintsIn.hasMandatory()) { - if (!constraintBuffer.isEmpty()) { - errorState.throwTypeError("Malformed constraint: Cannot use both optional/mandatory and specific constraints."); + if (!constraintBuffer.isEmpty() || constraintsIn.hasAdvanced()) { + errorState.throwTypeError("Malformed constraint: Cannot use both optional/mandatory and specific or advanced constraints."); return WebMediaConstraints(); } WebVector<WebMediaConstraint> optional;
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaConstraintsImpl.h b/third_party/WebKit/Source/modules/mediastream/MediaConstraintsImpl.h index 9e8d1486..00f16a0 100644 --- a/third_party/WebKit/Source/modules/mediastream/MediaConstraintsImpl.h +++ b/third_party/WebKit/Source/modules/mediastream/MediaConstraintsImpl.h
@@ -39,13 +39,13 @@ class Dictionary; class ExceptionState; -class MediaTrackConstraintSet; +class MediaTrackConstraints; namespace MediaConstraintsImpl { WebMediaConstraints create(); WebMediaConstraints create(ExecutionContext*, const Dictionary&, MediaErrorState&); -WebMediaConstraints create(ExecutionContext*, const MediaTrackConstraintSet&, MediaErrorState&); +WebMediaConstraints create(ExecutionContext*, const MediaTrackConstraints&, MediaErrorState&); }
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaStreamConstraints.idl b/third_party/WebKit/Source/modules/mediastream/MediaStreamConstraints.idl index b5a8fee4..4ca74de6 100644 --- a/third_party/WebKit/Source/modules/mediastream/MediaStreamConstraints.idl +++ b/third_party/WebKit/Source/modules/mediastream/MediaStreamConstraints.idl
@@ -5,6 +5,6 @@ // https://w3c.github.io/mediacapture-main/getusermedia.html#idl-def-MediaStreamConstraints dictionary MediaStreamConstraints { - (boolean or MediaTrackConstraintSet) video; - (boolean or MediaTrackConstraintSet) audio; + (boolean or MediaTrackConstraints) video; + (boolean or MediaTrackConstraints) audio; };
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaTrackConstraints.idl b/third_party/WebKit/Source/modules/mediastream/MediaTrackConstraints.idl new file mode 100644 index 0000000..3aa2601 --- /dev/null +++ b/third_party/WebKit/Source/modules/mediastream/MediaTrackConstraints.idl
@@ -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. + +// https://w3c.github.io/mediacapture-main/getusermedia.html#idl-def-MediaTrackConstraints + +dictionary MediaTrackConstraints : MediaTrackConstraintSet { + sequence<MediaTrackConstraintSet> advanced; +};
diff --git a/third_party/WebKit/Source/modules/mediastream/UserMediaRequest.cpp b/third_party/WebKit/Source/modules/mediastream/UserMediaRequest.cpp index 58bfe79..d2ddce91 100644 --- a/third_party/WebKit/Source/modules/mediastream/UserMediaRequest.cpp +++ b/third_party/WebKit/Source/modules/mediastream/UserMediaRequest.cpp
@@ -41,22 +41,22 @@ #include "modules/mediastream/MediaConstraintsImpl.h" #include "modules/mediastream/MediaStream.h" #include "modules/mediastream/MediaStreamConstraints.h" -#include "modules/mediastream/MediaTrackConstraintSet.h" +#include "modules/mediastream/MediaTrackConstraints.h" #include "modules/mediastream/UserMediaController.h" #include "platform/mediastream/MediaStreamCenter.h" #include "platform/mediastream/MediaStreamDescriptor.h" namespace blink { -static WebMediaConstraints parseOptions(ExecutionContext* context, const BooleanOrMediaTrackConstraintSet& options, MediaErrorState& errorState) +static WebMediaConstraints parseOptions(ExecutionContext* context, const BooleanOrMediaTrackConstraints& options, MediaErrorState& errorState) { WebMediaConstraints constraints; Dictionary constraintsDictionary; if (options.isNull()) { // Do nothing. - } else if (options.isMediaTrackConstraintSet()) { - constraints = MediaConstraintsImpl::create(context, options.getAsMediaTrackConstraintSet(), errorState); + } else if (options.isMediaTrackConstraints()) { + constraints = MediaConstraintsImpl::create(context, options.getAsMediaTrackConstraints(), errorState); } else { DCHECK(options.isBoolean()); if (options.getAsBoolean()) {
diff --git a/third_party/WebKit/Source/modules/modules.gypi b/third_party/WebKit/Source/modules/modules.gypi index 78cfea3..faaf3a7 100644 --- a/third_party/WebKit/Source/modules/modules.gypi +++ b/third_party/WebKit/Source/modules/modules.gypi
@@ -489,6 +489,7 @@ 'mediastream/MediaStreamConstraints.idl', 'mediastream/MediaStreamEventInit.idl', 'mediastream/MediaTrackConstraintSet.idl', + 'mediastream/MediaTrackConstraints.idl', 'mediastream/MediaTrackSupportedConstraints.idl', 'mediastream/RTCAnswerOptions.idl', 'mediastream/RTCDTMFToneChangeEventInit.idl', @@ -632,6 +633,8 @@ '<(blink_modules_output_dir)/mediastream/MediaStreamEventInit.h', '<(blink_modules_output_dir)/mediastream/MediaTrackConstraintSet.cpp', '<(blink_modules_output_dir)/mediastream/MediaTrackConstraintSet.h', + '<(blink_modules_output_dir)/mediastream/MediaTrackConstraints.cpp', + '<(blink_modules_output_dir)/mediastream/MediaTrackConstraints.h', '<(blink_modules_output_dir)/mediastream/MediaTrackSupportedConstraints.cpp', '<(blink_modules_output_dir)/mediastream/MediaTrackSupportedConstraints.h', '<(blink_modules_output_dir)/mediastream/RTCAnswerOptions.cpp',
diff --git a/third_party/WebKit/Source/platform/CrossThreadCopier.h b/third_party/WebKit/Source/platform/CrossThreadCopier.h index acb12a5..17c7a80 100644 --- a/third_party/WebKit/Source/platform/CrossThreadCopier.h +++ b/third_party/WebKit/Source/platform/CrossThreadCopier.h
@@ -37,7 +37,6 @@ #include "wtf/Forward.h" #include "wtf/PassOwnPtr.h" #include "wtf/PassRefPtr.h" -#include "wtf/RawPtr.h" #include "wtf/RefPtr.h" #include "wtf/ThreadSafeRefCounted.h" #include "wtf/TypeTraits.h" @@ -100,7 +99,7 @@ struct CrossThreadCopierBase<T, false, false, true> { STATIC_ONLY(CrossThreadCopierBase); typedef typename std::remove_pointer<T>::type TypeWithoutPointer; - typedef RawPtr<TypeWithoutPointer> Type; + typedef TypeWithoutPointer* Type; static Type copy(const T& ptr) { return ptr; @@ -202,21 +201,10 @@ }; template <typename T> -struct CrossThreadCopier<RawPtr<T>> { - STATIC_ONLY(CrossThreadCopier); - static_assert(IsGarbageCollectedType<T>::value, "T must be a garbage-collected type."); - typedef RawPtr<T> Type; - static Type copy(const Type& ptr) - { - return ptr; - } -}; - -template <typename T> struct CrossThreadCopier<Member<T>> { STATIC_ONLY(CrossThreadCopier); static_assert(IsGarbageCollectedType<T>::value, "T must be a garbage-collected type."); - typedef RawPtr<T> Type; + typedef T* Type; static Type copy(const Member<T>& ptr) { return ptr; @@ -227,7 +215,7 @@ struct CrossThreadCopier<WeakMember<T>> { STATIC_ONLY(CrossThreadCopier); static_assert(IsGarbageCollectedType<T>::value, "T must be a garbage-collected type."); - typedef RawPtr<T> Type; + typedef T* Type; static Type copy(const WeakMember<T>& ptr) { return ptr;
diff --git a/third_party/WebKit/Source/platform/LifecycleContextTest.cpp b/third_party/WebKit/Source/platform/LifecycleContextTest.cpp index 7dcbd72..8835ab96 100644 --- a/third_party/WebKit/Source/platform/LifecycleContextTest.cpp +++ b/third_party/WebKit/Source/platform/LifecycleContextTest.cpp
@@ -102,7 +102,7 @@ EXPECT_FALSE(observer->contextDestroyedCalled()); context->notifyContextDestroyed(); context = nullptr; - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(observer->lifecycleContext(), static_cast<DummyContext*>(0)); EXPECT_TRUE(observer->contextDestroyedCalled()); } @@ -114,7 +114,7 @@ observer->unobserve(); context->notifyContextDestroyed(); context = nullptr; - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(observer->lifecycleContext(), static_cast<DummyContext*>(0)); EXPECT_FALSE(observer->contextDestroyedCalled()); } @@ -136,7 +136,7 @@ context->notifyContextDestroyed(); EXPECT_EQ(observer->innerObserver(), nullptr); context = nullptr; - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_EQ(observer->lifecycleContext(), static_cast<DummyContext*>(0)); EXPECT_TRUE(observer->contextDestroyedCalled()); }
diff --git a/third_party/WebKit/Source/platform/Timer.h b/third_party/WebKit/Source/platform/Timer.h index 6afec7d..87e8aae 100644 --- a/third_party/WebKit/Source/platform/Timer.h +++ b/third_party/WebKit/Source/platform/Timer.h
@@ -150,7 +150,7 @@ public: static bool isHeapObjectAlive(T* objectPointer) { - return !Heap::willObjectBeLazilySwept(objectPointer); + return !ThreadHeap::willObjectBeLazilySwept(objectPointer); } };
diff --git a/third_party/WebKit/Source/platform/blink_platform.gypi b/third_party/WebKit/Source/platform/blink_platform.gypi index 7d3a46f..88fd03b 100644 --- a/third_party/WebKit/Source/platform/blink_platform.gypi +++ b/third_party/WebKit/Source/platform/blink_platform.gypi
@@ -659,8 +659,6 @@ 'graphics/StaticBitmapImage.h', 'graphics/StrokeData.cpp', 'graphics/StrokeData.h', - 'graphics/ThreadSafeDataTransport.cpp', - 'graphics/ThreadSafeDataTransport.h', 'graphics/UnacceleratedImageBufferSurface.cpp', 'graphics/UnacceleratedImageBufferSurface.h', 'graphics/compositing/PaintArtifactCompositor.cpp', @@ -806,6 +804,8 @@ 'image-decoders/ImageDecoder.h', 'image-decoders/ImageFrame.cpp', 'image-decoders/ImageFrame.h', + 'image-decoders/SegmentReader.cpp', + 'image-decoders/SegmentReader.h', 'image-decoders/bmp/BMPImageDecoder.cpp', 'image-decoders/bmp/BMPImageDecoder.h', 'image-decoders/bmp/BMPImageReader.cpp', @@ -1159,7 +1159,6 @@ 'fonts/android/FontCacheAndroidTest.cpp', 'fonts/mac/FontFamilyMatcherMacTest.mm', 'fonts/opentype/OpenTypeVerticalDataTest.cpp', - 'fonts/opentype/OpenTypeCapsSupportTest.cpp', 'fonts/shaping/CachingWordShaperTest.cpp', 'fonts/shaping/HarfBuzzShaperTest.cpp', 'fonts/shaping/RunSegmenterTest.cpp', @@ -1180,9 +1179,9 @@ 'graphics/CompositorMutableStateTest.cpp', 'graphics/CompositorMutatorClientTest.cpp', 'graphics/ContiguousContainerTest.cpp', + 'graphics/DeferredImageDecoderTestWoPlatform.cpp', 'graphics/GraphicsContextTest.cpp', 'graphics/RecordingImageBufferSurfaceTest.cpp', - 'graphics/ThreadSafeDataTransportTest.cpp', 'graphics/compositing/PaintArtifactCompositorTest.cpp', 'graphics/filters/FilterOperationsTest.cpp', 'graphics/filters/ImageFilterBuilderTest.cpp',
diff --git a/third_party/WebKit/Source/platform/blink_platform_unittests.isolate b/third_party/WebKit/Source/platform/blink_platform_unittests.isolate index 873a72550..2e344787 100644 --- a/third_party/WebKit/Source/platform/blink_platform_unittests.isolate +++ b/third_party/WebKit/Source/platform/blink_platform_unittests.isolate
@@ -6,8 +6,6 @@ 'files': [ # Required by some font tests. 'testing/data/', - '../../LayoutTests/third_party/Libertine/', - '../../LayoutTests/third_party/MEgalopolis/', # Required by some image decoder tests. 'image-decoders/testing/', '../../LayoutTests/fast/images/resources/',
diff --git a/third_party/WebKit/Source/platform/exported/Platform.cpp b/third_party/WebKit/Source/platform/exported/Platform.cpp index 7fb6e41..dfed33d 100644 --- a/third_party/WebKit/Source/platform/exported/Platform.cpp +++ b/third_party/WebKit/Source/platform/exported/Platform.cpp
@@ -91,7 +91,7 @@ WTF::Partitions::initialize(maxObservedSizeFunction); WTF::initialize(callOnMainThreadFunction); - Heap::init(); + ThreadHeap::init(); ThreadState::attachMainThread(); @@ -123,7 +123,7 @@ // so that the main thread won't get involved in a GC during the shutdown. ThreadState::detachMainThread(); - Heap::shutdown(); + ThreadHeap::shutdown(); WTF::shutdown(); WTF::Partitions::shutdown();
diff --git a/third_party/WebKit/Source/platform/fonts/FontDescription.h b/third_party/WebKit/Source/platform/fonts/FontDescription.h index 0232c312..1833496c 100644 --- a/third_party/WebKit/Source/platform/fonts/FontDescription.h +++ b/third_party/WebKit/Source/platform/fonts/FontDescription.h
@@ -73,6 +73,7 @@ m_fields.m_widthVariant = RegularWidth; m_fields.m_style = FontStyleNormal; m_fields.m_variant = FontVariantNormal; + m_fields.m_variantCaps = CapsNormal; m_fields.m_isAbsoluteSize = false; m_fields.m_weight = FontWeightNormal; m_fields.m_stretch = FontStretchNormal; @@ -148,6 +149,7 @@ FontStyle style() const { return static_cast<FontStyle>(m_fields.m_style); } int computedPixelSize() const { return int(m_computedSize + 0.5f); } FontVariant variant() const { return static_cast<FontVariant>(m_fields.m_variant); } + FontVariantCaps variantCaps() const { return static_cast<FontVariantCaps>(m_fields.m_variantCaps); } bool isAbsoluteSize() const { return m_fields.m_isAbsoluteSize; } FontWeight weight() const { return static_cast<FontWeight>(m_fields.m_weight); } FontStretch stretch() const { return static_cast<FontStretch>(m_fields.m_stretch); } @@ -198,6 +200,7 @@ void setSizeAdjust(float aspect) { m_sizeAdjust = clampTo<float>(aspect); } void setStyle(FontStyle i) { m_fields.m_style = i; } void setVariant(FontVariant c) { m_fields.m_variant = c; } + void setVariantCaps(FontVariantCaps variantCaps) { m_fields.m_variantCaps = variantCaps; } void setVariantLigatures(const VariantLigatures&); void setIsAbsoluteSize(bool s) { m_fields.m_isAbsoluteSize = s; } void setWeight(FontWeight w) { m_fields.m_weight = w; } @@ -263,6 +266,7 @@ unsigned m_style : 2; // FontStyle unsigned m_variant : 1; // FontVariant + unsigned m_variantCaps : 3; // FontVariantCaps unsigned m_isAbsoluteSize : 1; // Whether or not CSS specified an explicit size // (logical sizes like "medium" don't count). unsigned m_weight : 4; // FontWeight
diff --git a/third_party/WebKit/Source/platform/fonts/FontTraits.h b/third_party/WebKit/Source/platform/fonts/FontTraits.h index 9fa46b1..be8bc58f 100644 --- a/third_party/WebKit/Source/platform/fonts/FontTraits.h +++ b/third_party/WebKit/Source/platform/fonts/FontTraits.h
@@ -66,6 +66,10 @@ FontStyleItalic = 2 }; +// TODO(drott): crbug.com/516673 Move this from here to FontDescription, +// what's the spec equivalent of FontTraits? +// Variant is not used for font matching and should probably +// not be part of FontTraits. enum FontVariant { FontVariantNormal = 0, FontVariantSmallCaps = 1
diff --git a/third_party/WebKit/Source/platform/fonts/opentype/OpenTypeCapsSupportTest.cpp b/third_party/WebKit/Source/platform/fonts/opentype/OpenTypeCapsSupportTest.cpp deleted file mode 100644 index 5cfa615..0000000 --- a/third_party/WebKit/Source/platform/fonts/opentype/OpenTypeCapsSupportTest.cpp +++ /dev/null
@@ -1,113 +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 "platform/fonts/opentype/OpenTypeCapsSupport.h" - -#include "platform/fonts/Font.h" -#include "platform/testing/FontTestHelpers.h" -#include "platform/testing/UnitTestHelpers.h" -#include "testing/gtest/include/gtest/gtest.h" - -using blink::testing::createTestFont; - -namespace blink { - -static inline String layoutTestsFontPath(String relativePath) -{ - return testing::blinkRootDir() - + String("/LayoutTests/third_party/") - + relativePath; -} - -TEST(OpenTypeCapsSupportTest, LibertineSmcpC2scSupported) -{ - Font font = createTestFont("Libertine", layoutTestsFontPath("Libertine/LinLibertine_R.woff"), 16); - const FontPlatformData& platformData = font.primaryFont()->platformData(); - - OpenTypeCapsSupport capsSupport(platformData.harfBuzzFace(), FontDescription::SmallCaps, HB_SCRIPT_LATIN); - EXPECT_FALSE(capsSupport.needsRunCaseSplitting()); - EXPECT_FALSE(capsSupport.needsSyntheticFont(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_FALSE(capsSupport.needsSyntheticFont(SmallCapsIterator::SmallCapsUppercaseNeeded)); - EXPECT_EQ(CaseMapIntend::KeepSameCase, capsSupport.needsCaseChange(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_EQ(CaseMapIntend::KeepSameCase, capsSupport.needsCaseChange(SmallCapsIterator::SmallCapsUppercaseNeeded)); - EXPECT_EQ(FontDescription::SmallCaps, capsSupport.fontFeatureToUse(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_EQ(FontDescription::SmallCaps, capsSupport.fontFeatureToUse(SmallCapsIterator::SmallCapsUppercaseNeeded)); -} - -TEST(OpenTypeCapsSupportTest, LibertineIgnoreMissingTitling) -{ - Font font = createTestFont("Libertine", layoutTestsFontPath("Libertine/LinLibertine_R.woff"), 16); - const FontPlatformData& platformData = font.primaryFont()->platformData(); - - OpenTypeCapsSupport capsSupport(platformData.harfBuzzFace(), FontDescription::TitlingCaps, HB_SCRIPT_LATIN); - EXPECT_FALSE(capsSupport.needsRunCaseSplitting()); - EXPECT_FALSE(capsSupport.needsSyntheticFont(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_FALSE(capsSupport.needsSyntheticFont(SmallCapsIterator::SmallCapsUppercaseNeeded)); - EXPECT_EQ(CaseMapIntend::KeepSameCase, capsSupport.needsCaseChange(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_EQ(CaseMapIntend::KeepSameCase, capsSupport.needsCaseChange(SmallCapsIterator::SmallCapsUppercaseNeeded)); - EXPECT_EQ(FontDescription::CapsNormal, capsSupport.fontFeatureToUse(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_EQ(FontDescription::CapsNormal, capsSupport.fontFeatureToUse(SmallCapsIterator::SmallCapsUppercaseNeeded)); -} - -TEST(OpenTypeCapsSupportTest, LibertineAllPetiteSynthesis) -{ - Font font = createTestFont("Libertine", layoutTestsFontPath("Libertine/LinLibertine_R.woff"), 16); - const FontPlatformData& platformData = font.primaryFont()->platformData(); - - OpenTypeCapsSupport capsSupport(platformData.harfBuzzFace(), FontDescription::AllPetiteCaps, HB_SCRIPT_LATIN); - EXPECT_TRUE(capsSupport.needsRunCaseSplitting()); - EXPECT_FALSE(capsSupport.needsSyntheticFont(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_FALSE(capsSupport.needsSyntheticFont(SmallCapsIterator::SmallCapsUppercaseNeeded)); - EXPECT_EQ(CaseMapIntend::KeepSameCase, capsSupport.needsCaseChange(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_EQ(CaseMapIntend::KeepSameCase, capsSupport.needsCaseChange(SmallCapsIterator::SmallCapsUppercaseNeeded)); - EXPECT_EQ(FontDescription::AllSmallCaps, capsSupport.fontFeatureToUse(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_EQ(FontDescription::AllSmallCaps, capsSupport.fontFeatureToUse(SmallCapsIterator::SmallCapsUppercaseNeeded)); -} - -TEST(OpenTypeCapsSupportTest, MEgalopolisSmallCapsSynthetic) -{ - Font font = createTestFont("MEgalopolis", layoutTestsFontPath("MEgalopolis/MEgalopolisExtra.woff"), 16); - const FontPlatformData& platformData = font.primaryFont()->platformData(); - - OpenTypeCapsSupport capsSupport(platformData.harfBuzzFace(), FontDescription::SmallCaps, HB_SCRIPT_LATIN); - EXPECT_TRUE(capsSupport.needsRunCaseSplitting()); - EXPECT_FALSE(capsSupport.needsSyntheticFont(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_TRUE(capsSupport.needsSyntheticFont(SmallCapsIterator::SmallCapsUppercaseNeeded)); - EXPECT_EQ(CaseMapIntend::KeepSameCase, capsSupport.needsCaseChange(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_EQ(CaseMapIntend::UpperCase, capsSupport.needsCaseChange(SmallCapsIterator::SmallCapsUppercaseNeeded)); - EXPECT_EQ(FontDescription::CapsNormal, capsSupport.fontFeatureToUse(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_EQ(FontDescription::CapsNormal, capsSupport.fontFeatureToUse(SmallCapsIterator::SmallCapsUppercaseNeeded)); -} - -TEST(OpenTypeCapsSupportTest, MEgalopolisUnicaseSynthetic) -{ - Font font = createTestFont("MEgalopolis", layoutTestsFontPath("MEgalopolis/MEgalopolisExtra.woff"), 16); - const FontPlatformData& platformData = font.primaryFont()->platformData(); - - OpenTypeCapsSupport capsSupport(platformData.harfBuzzFace(), FontDescription::Unicase, HB_SCRIPT_LATIN); - EXPECT_TRUE(capsSupport.needsRunCaseSplitting()); - EXPECT_TRUE(capsSupport.needsSyntheticFont(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_FALSE(capsSupport.needsSyntheticFont(SmallCapsIterator::SmallCapsUppercaseNeeded)); - EXPECT_EQ(CaseMapIntend::KeepSameCase, capsSupport.needsCaseChange(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_EQ(CaseMapIntend::KeepSameCase, capsSupport.needsCaseChange(SmallCapsIterator::SmallCapsUppercaseNeeded)); - EXPECT_EQ(FontDescription::CapsNormal, capsSupport.fontFeatureToUse(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_EQ(FontDescription::CapsNormal, capsSupport.fontFeatureToUse(SmallCapsIterator::SmallCapsUppercaseNeeded)); -} - -TEST(OpenTypeCapsSupportTest, LibertineUnicaseFallback) -{ - Font font = createTestFont("Libertine", layoutTestsFontPath("Libertine/LinLibertine_R.woff"), 16); - const FontPlatformData& platformData = font.primaryFont()->platformData(); - - OpenTypeCapsSupport capsSupport(platformData.harfBuzzFace(), FontDescription::Unicase, HB_SCRIPT_LATIN); - EXPECT_TRUE(capsSupport.needsRunCaseSplitting()); - EXPECT_FALSE(capsSupport.needsSyntheticFont(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_FALSE(capsSupport.needsSyntheticFont(SmallCapsIterator::SmallCapsUppercaseNeeded)); - EXPECT_EQ(CaseMapIntend::LowerCase, capsSupport.needsCaseChange(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_EQ(CaseMapIntend::KeepSameCase, capsSupport.needsCaseChange(SmallCapsIterator::SmallCapsUppercaseNeeded)); - EXPECT_EQ(FontDescription::SmallCaps, capsSupport.fontFeatureToUse(SmallCapsIterator::SmallCapsSameCase)); - EXPECT_EQ(FontDescription::CapsNormal, capsSupport.fontFeatureToUse(SmallCapsIterator::SmallCapsUppercaseNeeded)); -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.cpp b/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.cpp index d857ae67..2d2dc26 100644 --- a/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.cpp +++ b/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.cpp
@@ -30,15 +30,17 @@ #include "platform/TraceEvent.h" #include "platform/graphics/ImageFrameGenerator.h" #include "platform/image-decoders/ImageDecoder.h" +#include "platform/image-decoders/SegmentReader.h" #include "third_party/skia/include/core/SkData.h" namespace blink { -DecodingImageGenerator::DecodingImageGenerator(PassRefPtr<ImageFrameGenerator> frameGenerator, const SkImageInfo& info, size_t index) +DecodingImageGenerator::DecodingImageGenerator(PassRefPtr<ImageFrameGenerator> frameGenerator, const SkImageInfo& info, PassRefPtr<SegmentReader> data, bool allDataReceived, size_t index) : SkImageGenerator(info) , m_frameGenerator(frameGenerator) + , m_data(data) + , m_allDataReceived(allDataReceived) , m_frameIndex(index) - , m_generationId(0) , m_canYUVDecode(false) { } @@ -51,7 +53,7 @@ { TRACE_EVENT0("blink", "DecodingImageGenerator::refEncodedData"); - return m_frameGenerator->refEncodedData(); + return m_allDataReceived ? m_data->getAsSkData().leakRef() : nullptr; } bool DecodingImageGenerator::onGetPixels(const SkImageInfo& info, void* pixels, size_t rowBytes, SkPMColor table[], int* tableCount) @@ -68,8 +70,8 @@ return false; } - PlatformInstrumentation::willDecodeLazyPixelRef(m_generationId); - bool decoded = m_frameGenerator->decodeAndScale(m_frameIndex, getInfo(), pixels, rowBytes); + PlatformInstrumentation::willDecodeLazyPixelRef(uniqueID()); + bool decoded = m_frameGenerator->decodeAndScale(m_data.get(), m_allDataReceived, m_frameIndex, getInfo(), pixels, rowBytes); PlatformInstrumentation::didDecodeLazyPixelRef(); return decoded; @@ -77,7 +79,8 @@ bool DecodingImageGenerator::onQueryYUV8(SkYUVSizeInfo* sizeInfo, SkYUVColorSpace* colorSpace) const { - if (!m_canYUVDecode) + // YUV decoding does not currently support progressive decoding. See comment in ImageFrameGenerator.h. + if (!m_canYUVDecode || !m_allDataReceived) return false; TRACE_EVENT1("blink", "DecodingImageGenerator::queryYUV8", "sizes", static_cast<int>(m_frameIndex)); @@ -85,17 +88,18 @@ if (colorSpace) *colorSpace = kJPEG_SkYUVColorSpace; - return m_frameGenerator->getYUVComponentSizes(sizeInfo); + return m_frameGenerator->getYUVComponentSizes(m_data.get(), sizeInfo); } bool DecodingImageGenerator::onGetYUV8Planes(const SkYUVSizeInfo& sizeInfo, void* planes[3]) { - ASSERT(m_canYUVDecode); + // YUV decoding does not currently support progressive decoding. See comment in ImageFrameGenerator.h. + ASSERT(m_canYUVDecode && m_allDataReceived); TRACE_EVENT1("blink", "DecodingImageGenerator::getYUV8Planes", "frame index", static_cast<int>(m_frameIndex)); - PlatformInstrumentation::willDecodeLazyPixelRef(m_generationId); - bool decoded = m_frameGenerator->decodeToYUV(m_frameIndex, sizeInfo.fSizes, planes, sizeInfo.fWidthBytes); + PlatformInstrumentation::willDecodeLazyPixelRef(uniqueID()); + bool decoded = m_frameGenerator->decodeToYUV(m_data.get(), m_frameIndex, sizeInfo.fSizes, planes, sizeInfo.fWidthBytes); PlatformInstrumentation::didDecodeLazyPixelRef(); return decoded; @@ -103,26 +107,26 @@ SkImageGenerator* DecodingImageGenerator::create(SkData* data) { - RefPtr<SharedBuffer> buffer = SharedBuffer::create(data->bytes(), data->size()); - // We just need the size of the image, so we have to temporarily create an ImageDecoder. Since // we only need the size, it doesn't really matter about premul or not, or gamma settings. - OwnPtr<ImageDecoder> decoder = ImageDecoder::create(*buffer.get(), ImageDecoder::AlphaPremultiplied, ImageDecoder::GammaAndColorProfileApplied); + OwnPtr<ImageDecoder> decoder = ImageDecoder::create(static_cast<const char*>(data->data()), data->size(), + ImageDecoder::AlphaPremultiplied, ImageDecoder::GammaAndColorProfileApplied); if (!decoder) return 0; - decoder->setData(buffer.get(), true); + RefPtr<SegmentReader> segmentReader = SegmentReader::createFromSkData(data); + decoder->setData(segmentReader.get(), true); if (!decoder->isSizeAvailable()) return 0; const IntSize size = decoder->size(); const SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height()); - RefPtr<ImageFrameGenerator> frame = ImageFrameGenerator::create(SkISize::Make(size.width(), size.height()), buffer, true, false); + RefPtr<ImageFrameGenerator> frame = ImageFrameGenerator::create(SkISize::Make(size.width(), size.height()), false); if (!frame) return 0; - return new DecodingImageGenerator(frame, info, 0); + return new DecodingImageGenerator(frame, info, segmentReader.release(), true, 0); } } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.h b/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.h index 65407af..a77fdb2 100644 --- a/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.h +++ b/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.h
@@ -27,10 +27,12 @@ #define DecodingImageGenerator_h #include "platform/PlatformExport.h" +#include "platform/image-decoders/SegmentReader.h" #include "third_party/skia/include/core/SkImageGenerator.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "wtf/Allocator.h" #include "wtf/Noncopyable.h" +#include "wtf/PassRefPtr.h" #include "wtf/RefPtr.h" class SkData; @@ -48,10 +50,9 @@ public: static SkImageGenerator* create(SkData*); - DecodingImageGenerator(PassRefPtr<ImageFrameGenerator>, const SkImageInfo&, size_t index); + DecodingImageGenerator(PassRefPtr<ImageFrameGenerator>, const SkImageInfo&, PassRefPtr<SegmentReader>, bool allDataReceived, size_t index); ~DecodingImageGenerator() override; - void setGenerationId(size_t id) { m_generationId = id; } void setCanYUVDecode(bool yes) { m_canYUVDecode = yes; } protected: @@ -65,8 +66,9 @@ private: RefPtr<ImageFrameGenerator> m_frameGenerator; - size_t m_frameIndex; - size_t m_generationId; + const RefPtr<SegmentReader> m_data; // Data source. + const bool m_allDataReceived; + const size_t m_frameIndex; bool m_canYUVDecode; };
diff --git a/third_party/WebKit/Source/platform/graphics/DeferredImageDecoder.cpp b/third_party/WebKit/Source/platform/graphics/DeferredImageDecoder.cpp index f1d76fd8..9ea87b7 100644 --- a/third_party/WebKit/Source/platform/graphics/DeferredImageDecoder.cpp +++ b/third_party/WebKit/Source/platform/graphics/DeferredImageDecoder.cpp
@@ -26,10 +26,12 @@ #include "platform/graphics/DeferredImageDecoder.h" #include "platform/RuntimeEnabledFeatures.h" +#include "platform/SharedBuffer.h" #include "platform/graphics/DecodingImageGenerator.h" #include "platform/graphics/FrameData.h" #include "platform/graphics/ImageDecodingStore.h" #include "platform/graphics/ImageFrameGenerator.h" +#include "platform/image-decoders/SegmentReader.h" #include "third_party/skia/include/core/SkImage.h" #include "wtf/PassOwnPtr.h" @@ -54,7 +56,6 @@ DeferredImageDecoder::DeferredImageDecoder(PassOwnPtr<ImageDecoder> actualDecoder) : m_allDataReceived(false) - , m_lastDataSize(0) , m_actualDecoder(std::move(actualDecoder)) , m_repetitionCount(cAnimationNone) , m_hasColorProfile(false) @@ -114,15 +115,20 @@ void DeferredImageDecoder::setData(SharedBuffer& data, bool allDataReceived) { if (m_actualDecoder) { - m_data = RefPtr<SharedBuffer>(data); - m_lastDataSize = data.size(); m_allDataReceived = allDataReceived; m_actualDecoder->setData(&data, allDataReceived); prepareLazyDecodedFrames(); } - if (m_frameGenerator) - m_frameGenerator->setData(&data, allDataReceived); + if (m_frameGenerator) { + if (!m_rwBuffer) + m_rwBuffer = adoptPtr(new SkRWBuffer(data.size())); + + const char* segment = 0; + for (size_t length = data.getSomeData(segment, m_rwBuffer->size()); + length; length = data.getSomeData(segment, m_rwBuffer->size())) + m_rwBuffer->append(segment, length); + } } bool DeferredImageDecoder::isSizeAvailable() @@ -230,7 +236,8 @@ m_hasColorProfile = m_actualDecoder->hasColorProfile(); const bool isSingleFrame = m_actualDecoder->repetitionCount() == cAnimationNone || (m_allDataReceived && m_actualDecoder->frameCount() == 1u); - m_frameGenerator = ImageFrameGenerator::create(SkISize::Make(m_actualDecoder->decodedSize().width(), m_actualDecoder->decodedSize().height()), m_data, m_allDataReceived, !isSingleFrame); + const SkISize decodedSize = SkISize::Make(m_actualDecoder->decodedSize().width(), m_actualDecoder->decodedSize().height()); + m_frameGenerator = ImageFrameGenerator::create(decodedSize, !isSingleFrame); } void DeferredImageDecoder::prepareLazyDecodedFrames() @@ -267,7 +274,7 @@ if (m_allDataReceived) { m_repetitionCount = m_actualDecoder->repetitionCount(); m_actualDecoder.clear(); - m_data = nullptr; + // Hold on to m_rwBuffer, which is still needed by createFrameAtIndex. } } @@ -282,12 +289,13 @@ ASSERT(decodedSize.width() > 0); ASSERT(decodedSize.height() > 0); - DecodingImageGenerator* generator = new DecodingImageGenerator(m_frameGenerator, imageInfoFrom(decodedSize, knownToBeOpaque), index); + RefPtr<SkROBuffer> roBuffer = adoptRef(m_rwBuffer->newRBufferSnapshot()); + RefPtr<SegmentReader> segmentReader = SegmentReader::createFromSkROBuffer(roBuffer.release()); + DecodingImageGenerator* generator = new DecodingImageGenerator(m_frameGenerator, imageInfoFrom(decodedSize, knownToBeOpaque), segmentReader.release(), m_allDataReceived, index); RefPtr<SkImage> image = adoptRef(SkImage::NewFromGenerator(generator)); // SkImage takes ownership of the generator. if (!image) return nullptr; - generator->setGenerationId(image->uniqueID()); generator->setCanYUVDecode(m_canYUVDecode); return image.release();
diff --git a/third_party/WebKit/Source/platform/graphics/DeferredImageDecoder.h b/third_party/WebKit/Source/platform/graphics/DeferredImageDecoder.h index 3338d4a..d6084c91 100644 --- a/third_party/WebKit/Source/platform/graphics/DeferredImageDecoder.h +++ b/third_party/WebKit/Source/platform/graphics/DeferredImageDecoder.h
@@ -31,6 +31,7 @@ #include "platform/image-decoders/ImageDecoder.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkPixelRef.h" +#include "third_party/skia/include/core/SkRWBuffer.h" #include "wtf/Allocator.h" #include "wtf/Forward.h" #include "wtf/OwnPtr.h" @@ -88,9 +89,10 @@ PassRefPtr<SkImage> createFrameImageAtIndex(size_t index, bool knownToBeOpaque) const; - RefPtr<SharedBuffer> m_data; + // Copy of the data that is passed in, used by deferred decoding. + // Allows creating readonly snapshots that may be read in another thread. + OwnPtr<SkRWBuffer> m_rwBuffer; bool m_allDataReceived; - unsigned m_lastDataSize; OwnPtr<ImageDecoder> m_actualDecoder; String m_filenameExtension;
diff --git a/third_party/WebKit/Source/platform/graphics/DeferredImageDecoderTestWoPlatform.cpp b/third_party/WebKit/Source/platform/graphics/DeferredImageDecoderTestWoPlatform.cpp new file mode 100644 index 0000000..82288a48 --- /dev/null +++ b/third_party/WebKit/Source/platform/graphics/DeferredImageDecoderTestWoPlatform.cpp
@@ -0,0 +1,82 @@ +// 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/DeferredImageDecoder.h" + +#include "platform/SharedBuffer.h" +#include "platform/image-decoders/ImageDecoderTestHelpers.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/skia/include/core/SkImage.h" +#include "wtf/RefPtr.h" + +namespace blink { + +/** + * Used to test decoding SkImages out of order. + * e.g. + * SkImage* imageA = decoder.createFrameAtIndex(0); + * // supply more (but not all) data to the decoder + * SkImage* imageB = decoder.createFrameAtIndex(laterFrame); + * imageB->preroll(); + * imageA->preroll(); + * + * This results in using the same ImageDecoder (in the ImageDecodingStore) to + * decode less data the second time. This test ensures that it is safe to do + * so. + * + * @param fileName File to decode + * @param bytesForFirstFrame Number of bytes needed to return an SkImage + * @param laterFrame Frame to decode with almost complete data. Can be 0. + */ +static void mixImages(const char* fileName, size_t bytesForFirstFrame, size_t laterFrame) +{ + RefPtr<SharedBuffer> file = readFile(fileName); + ASSERT_NE(file, nullptr); + + OwnPtr<DeferredImageDecoder> decoder = DeferredImageDecoder::create(*file.get(), ImageDecoder::AlphaPremultiplied, ImageDecoder::GammaAndColorProfileIgnored); + ASSERT_TRUE(decoder.get()); + + RefPtr<SharedBuffer> partialFile = SharedBuffer::create(file->data(), bytesForFirstFrame); + decoder->setData(*partialFile.get(), false); + RefPtr<SkImage> partialImage = decoder->createFrameAtIndex(0); + + RefPtr<SharedBuffer> almostCompleteFile = SharedBuffer::create(file->data(), file->size() - 1); + decoder->setData(*almostCompleteFile.get(), false); + RefPtr<SkImage> imageWithMoreData = decoder->createFrameAtIndex(laterFrame); + + imageWithMoreData->preroll(); + partialImage->preroll(); +} + +TEST(DeferredImageDecoderTestWoPlatform, mixImagesGif) +{ + mixImages("/LayoutTests/fast/images/resources/animated.gif", 818u, 1u); +} + +TEST(DeferredImageDecoderTestWoPlatform, mixImagesPng) +{ + mixImages("/LayoutTests/fast/images/resources/mu.png", 910u, 0u); +} + +TEST(DeferredImageDecoderTestWoPlatform, mixImagesJpg) +{ + mixImages("/LayoutTests/fast/images/resources/2-dht.jpg", 177u, 0u); +} + +TEST(DeferredImageDecoderTestWoPlatform, mixImagesWebp) +{ + mixImages("/LayoutTests/fast/images/resources/webp-animated.webp", 142u, 1u); +} + +TEST(DeferredImageDecoderTestWoPlatform, mixImagesBmp) +{ + mixImages("/LayoutTests/fast/images/resources/lenna.bmp", 122u, 0u); +} + +TEST(DeferredImageDecoderTestWoPlatform, mixImagesIco) +{ + mixImages("/LayoutTests/fast/images/resources/1bit.ico", 70u, 0u); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/ImageDecodingStoreTest.cpp b/third_party/WebKit/Source/platform/graphics/ImageDecodingStoreTest.cpp index bfea0da..1fa2cce 100644 --- a/third_party/WebKit/Source/platform/graphics/ImageDecodingStoreTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/ImageDecodingStoreTest.cpp
@@ -25,7 +25,6 @@ #include "platform/graphics/ImageDecodingStore.h" -#include "platform/SharedBuffer.h" #include "platform/graphics/ImageFrameGenerator.h" #include "platform/graphics/test/MockImageDecoder.h" #include "testing/gtest/include/gtest/gtest.h" @@ -37,8 +36,7 @@ void SetUp() override { ImageDecodingStore::instance().setCacheLimitInBytes(1024 * 1024); - m_data = SharedBuffer::create(); - m_generator = ImageFrameGenerator::create(SkISize::Make(100, 100), m_data, true); + m_generator = ImageFrameGenerator::create(SkISize::Make(100, 100), true); m_decodersDestroyed = 0; } @@ -77,7 +75,6 @@ ImageDecodingStore::instance().setCacheLimitInBytes(0); } - RefPtr<SharedBuffer> m_data; RefPtr<ImageFrameGenerator> m_generator; int m_decodersDestroyed; };
diff --git a/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.cpp b/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.cpp index 437b453..cd29a64 100644 --- a/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.cpp +++ b/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.cpp
@@ -26,7 +26,6 @@ #include "platform/graphics/ImageFrameGenerator.h" #include "SkData.h" -#include "platform/SharedBuffer.h" #include "platform/TraceEvent.h" #include "platform/graphics/ImageDecodingStore.h" #include "platform/image-decoders/ImageDecoder.h" @@ -52,7 +51,7 @@ // Creates a SkPixelRef such that the memory for pixels is given by an external body. // This is used to write directly to the memory given by Skia during decoding. -class ImageFrameGenerator::ExternalMemoryAllocator final : public SkBitmap::Allocator { +class ExternalMemoryAllocator final : public SkBitmap::Allocator { USING_FAST_MALLOC(ExternalMemoryAllocator); WTF_MAKE_NONCOPYABLE(ExternalMemoryAllocator); public: @@ -101,105 +100,39 @@ return true; } -ImageFrameGenerator::ImageFrameGenerator(const SkISize& fullSize, PassRefPtr<SharedBuffer> data, bool allDataReceived, bool isMultiFrame) +ImageFrameGenerator::ImageFrameGenerator(const SkISize& fullSize, bool isMultiFrame) : m_fullSize(fullSize) - , m_data(adoptRef(new ThreadSafeDataTransport())) , m_isMultiFrame(isMultiFrame) , m_decodeFailed(false) , m_yuvDecodingFailed(false) , m_frameCount(0) - , m_encodedData(nullptr) { - setData(data.get(), allDataReceived); } ImageFrameGenerator::~ImageFrameGenerator() { - if (m_encodedData) - m_encodedData->unref(); ImageDecodingStore::instance().removeCacheIndexedByGenerator(this); } -void ImageFrameGenerator::setData(PassRefPtr<SharedBuffer> data, bool allDataReceived) +bool ImageFrameGenerator::decodeAndScale(SegmentReader* data, bool allDataReceived, size_t index, const SkImageInfo& info, void* pixels, size_t rowBytes) { - m_data->setData(data.get(), allDataReceived); -} - -static void sharedSkDataReleaseCallback(const void* address, void* context) -{ - // This gets called when m_encodedData reference count becomes 0 - and it could happen in - // ImageFrameGenerator destructor or later when m_encodedData gets dereferenced. - // In this method, we deref ThreadSafeDataTransport, as ThreadSafeDataTransport is the owner - // of data returned via refEncodedData. - - ThreadSafeDataTransport* dataTransport = static_cast<ThreadSafeDataTransport*>(context); -#if ENABLE(ASSERT) - ASSERT(dataTransport); - SharedBuffer* buffer = 0; - bool allDataReceived = false; - dataTransport->data(&buffer, &allDataReceived); - ASSERT(allDataReceived && buffer && buffer->data() == address); -#endif - // Dereference m_data now. - dataTransport->deref(); -} - -SkData* ImageFrameGenerator::refEncodedData() -{ - // SkData is returned only when full image (encoded) data is received. This is important - // since DeferredImageDecoder::setData is called only once with allDataReceived set to true, - // and after that m_data->m_readBuffer.data() is not changed. See also RELEASE_ASSERT used in - // ThreadSafeDataTransport::data(). - SharedBuffer* buffer = 0; - bool allDataReceived = false; - m_data->data(&buffer, &allDataReceived); - if (!allDataReceived) - return nullptr; - - { - // Prevents concurrent access to m_encodedData creation. - MutexLocker lock(m_decodeMutex); - if (m_encodedData) { - m_encodedData->ref(); - return m_encodedData; - } - // m_encodedData is created with initial reference count == 1. ImageFrameGenerator always holds one - // reference to m_encodedData, as it prevents write access in SkData::writable_data. - m_encodedData = SkData::NewWithProc(buffer->data(), buffer->size(), sharedSkDataReleaseCallback, m_data.get()); - // While m_encodedData is referenced, prevent disposing m_data and its content. - // it is dereferenced in sharedSkDataReleaseCallback, called when m_encodedData gets dereferenced. - m_data->ref(); - } - // Increase the reference, caller must decrease it. One reference is always kept by ImageFrameGenerator and released - // in destructor. - m_encodedData->ref(); - return m_encodedData; -} - -bool ImageFrameGenerator::decodeAndScale(size_t index, const SkImageInfo& info, void* pixels, size_t rowBytes) -{ - // Prevent concurrent decode or scale operations on the same image data. - MutexLocker lock(m_decodeMutex); - if (m_decodeFailed) return false; TRACE_EVENT1("blink", "ImageFrameGenerator::decodeAndScale", "frame index", static_cast<int>(index)); - m_externalAllocator = adoptPtr(new ExternalMemoryAllocator(info, pixels, rowBytes)); + RefPtr<ExternalMemoryAllocator> externalAllocator = adoptRef(new ExternalMemoryAllocator(info, pixels, rowBytes)); // This implementation does not support scaling so check the requested size. SkISize scaledSize = SkISize::Make(info.width(), info.height()); ASSERT(m_fullSize == scaledSize); - SkBitmap bitmap = tryToResumeDecode(index, scaledSize); + // TODO (scroggo): Convert tryToResumeDecode() and decode() to take a + // PassRefPtr<SkBitmap::Allocator> instead of a bare pointer. + SkBitmap bitmap = tryToResumeDecode(data, allDataReceived, index, scaledSize, externalAllocator.get()); if (bitmap.isNull()) return false; - // Don't keep the allocator because it contains a pointer to memory - // that we do not own. - m_externalAllocator.clear(); - // Check to see if the decoder has written directly to the pixel memory // provided. If not, make a copy. ASSERT(bitmap.width() == scaledSize.width()); @@ -210,11 +143,10 @@ return true; } -bool ImageFrameGenerator::decodeToYUV(size_t index, const SkISize componentSizes[3], void* planes[3], const size_t rowBytes[3]) +bool ImageFrameGenerator::decodeToYUV(SegmentReader* data, size_t index, const SkISize componentSizes[3], void* planes[3], const size_t rowBytes[3]) { - // Prevent concurrent decode or scale operations on the same image data. - MutexLocker lock(m_decodeMutex); - + // TODO (scroggo): The only interesting thing this uses from the ImageFrameGenerator is m_decodeFailed. + // Move this into DecodingImageGenerator, which is the only class that calls it. if (m_decodeFailed) return false; @@ -225,18 +157,11 @@ return false; } - SharedBuffer* data = 0; - bool allDataReceived = false; - m_data->data(&data, &allDataReceived); - - // FIXME: YUV decoding does not currently support progressive decoding. - ASSERT(allDataReceived); - OwnPtr<ImageDecoder> decoder = ImageDecoder::create(*data, ImageDecoder::AlphaPremultiplied, ImageDecoder::GammaAndColorProfileApplied); - if (!decoder) - return false; + // getYUVComponentSizes was already called and was successful, so ImageDecoder::create must succeed. + ASSERT(decoder); - decoder->setData(data, allDataReceived); + decoder->setData(data, true); OwnPtr<ImagePlanes> imagePlanes = adoptPtr(new ImagePlanes(planes, rowBytes)); decoder->setImagePlanes(imagePlanes.release()); @@ -253,16 +178,19 @@ return false; } -SkBitmap ImageFrameGenerator::tryToResumeDecode(size_t index, const SkISize& scaledSize) +SkBitmap ImageFrameGenerator::tryToResumeDecode(SegmentReader* data, bool allDataReceived, size_t index, const SkISize& scaledSize, SkBitmap::Allocator* allocator) { TRACE_EVENT1("blink", "ImageFrameGenerator::tryToResumeDecode", "frame index", static_cast<int>(index)); ImageDecoder* decoder = 0; + + // Lock the mutex, so only one thread can use the decoder at once. + MutexLocker lock(m_decodeMutex); const bool resumeDecoding = ImageDecodingStore::instance().lockDecoder(this, m_fullSize, &decoder); ASSERT(!resumeDecoding || decoder); SkBitmap fullSizeImage; - bool complete = decode(index, &decoder, &fullSizeImage); + bool complete = decode(data, allDataReceived, index, &decoder, &fullSizeImage, allocator); if (!decoder) return SkBitmap(); @@ -322,14 +250,11 @@ m_hasAlpha[index] = hasAlpha; } -bool ImageFrameGenerator::decode(size_t index, ImageDecoder** decoder, SkBitmap* bitmap) +bool ImageFrameGenerator::decode(SegmentReader* data, bool allDataReceived, size_t index, ImageDecoder** decoder, SkBitmap* bitmap, SkBitmap::Allocator* allocator) { + ASSERT(m_decodeMutex.locked()); TRACE_EVENT2("blink", "ImageFrameGenerator::decode", "width", m_fullSize.width(), "height", m_fullSize.height()); - SharedBuffer* data = 0; - bool allDataReceived = false; - m_data->data(&data, &allDataReceived); - // Try to create an ImageDecoder if we are not given one. ASSERT(decoder); bool newDecoder = false; @@ -348,8 +273,8 @@ if (!m_isMultiFrame && newDecoder && allDataReceived) { // If we're using an external memory allocator that means we're decoding // directly into the output memory and we can save one memcpy. - ASSERT(m_externalAllocator.get()); - (*decoder)->setMemoryAllocator(m_externalAllocator.get()); + ASSERT(allocator); + (*decoder)->setMemoryAllocator(allocator); } (*decoder)->setData(data, allDataReceived); @@ -362,7 +287,7 @@ if (allDataReceived) m_frameCount = (*decoder)->frameCount(); - (*decoder)->setData(0, false); // Unref SharedBuffer from ImageDecoder. + (*decoder)->setData(PassRefPtr<SegmentReader>(nullptr), false); // Unref SegmentReader from ImageDecoder. (*decoder)->clearCacheExceptFrame(index); (*decoder)->setMemoryAllocator(0); @@ -392,27 +317,19 @@ return true; } -bool ImageFrameGenerator::getYUVComponentSizes(SkYUVSizeInfo* sizeInfo) +bool ImageFrameGenerator::getYUVComponentSizes(SegmentReader* data, SkYUVSizeInfo* sizeInfo) { TRACE_EVENT2("blink", "ImageFrameGenerator::getYUVComponentSizes", "width", m_fullSize.width(), "height", m_fullSize.height()); if (m_yuvDecodingFailed) return false; - SharedBuffer* data = 0; - bool allDataReceived = false; - m_data->data(&data, &allDataReceived); - - // FIXME: YUV decoding does not currently support progressive decoding. - if (!allDataReceived) - return false; - OwnPtr<ImageDecoder> decoder = ImageDecoder::create(*data, ImageDecoder::AlphaPremultiplied, ImageDecoder::GammaAndColorProfileApplied); if (!decoder) return false; // Setting a dummy ImagePlanes object signals to the decoder that we want to do YUV decoding. - decoder->setData(data, allDataReceived); + decoder->setData(data, true); OwnPtr<ImagePlanes> dummyImagePlanes = adoptPtr(new ImagePlanes); decoder->setImagePlanes(dummyImagePlanes.release());
diff --git a/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.h b/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.h index 73ac628..4b31634 100644 --- a/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.h +++ b/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.h
@@ -27,7 +27,7 @@ #define ImageFrameGenerator_h #include "platform/PlatformExport.h" -#include "platform/graphics/ThreadSafeDataTransport.h" +#include "platform/image-decoders/SegmentReader.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkSize.h" #include "third_party/skia/include/core/SkTypes.h" @@ -47,7 +47,6 @@ namespace blink { class ImageDecoder; -class SharedBuffer; class PLATFORM_EXPORT ImageDecoderFactory { USING_FAST_MALLOC(ImageDecoderFactory); @@ -61,27 +60,23 @@ class PLATFORM_EXPORT ImageFrameGenerator final : public ThreadSafeRefCounted<ImageFrameGenerator> { WTF_MAKE_NONCOPYABLE(ImageFrameGenerator); public: - static PassRefPtr<ImageFrameGenerator> create(const SkISize& fullSize, PassRefPtr<SharedBuffer> data, bool allDataReceived, bool isMultiFrame = false) + static PassRefPtr<ImageFrameGenerator> create(const SkISize& fullSize, bool isMultiFrame = false) { - return adoptRef(new ImageFrameGenerator(fullSize, data, allDataReceived, isMultiFrame)); + return adoptRef(new ImageFrameGenerator(fullSize, isMultiFrame)); } ~ImageFrameGenerator(); - void setData(PassRefPtr<SharedBuffer>, bool allDataReceived); - - // Return our encoded image data. Caller takes ownership and must unref the data - // according to the contract SkImageGenerator::refEncodedData. Returns null if - // the data is has not been fully received. - SkData* refEncodedData(); - // Decodes and scales the specified frame at |index|. The dimensions and output // format are given in SkImageInfo. Decoded pixels are written into |pixels| with // a stride of |rowBytes|. Returns true if decoding was successful. - bool decodeAndScale(size_t index, const SkImageInfo&, void* pixels, size_t rowBytes); + bool decodeAndScale(SegmentReader*, bool allDataReceived, size_t index, const SkImageInfo&, void* pixels, size_t rowBytes); // Decodes YUV components directly into the provided memory planes. - bool decodeToYUV(size_t index, const SkISize componentSizes[3], void* planes[3], const size_t rowBytes[3]); + // Must not be called unless getYUVComponentSizes has been called and returned true. + // YUV decoding does not currently support progressive decoding. In order to support it, ImageDecoder needs something + // analagous to its ImageFrame cache to hold partial planes, and the GPU code needs to handle them. + bool decodeToYUV(SegmentReader*, size_t index, const SkISize componentSizes[3], void* planes[3], const size_t rowBytes[3]); const SkISize& getFullSize() const { return m_fullSize; } @@ -90,10 +85,12 @@ bool hasAlpha(size_t index); - bool getYUVComponentSizes(SkYUVSizeInfo*); + // Must not be called unless the SkROBuffer has all the data. + // YUV decoding does not currently support progressive decoding. See comment above on decodeToYUV. + bool getYUVComponentSizes(SegmentReader*, SkYUVSizeInfo*); private: - ImageFrameGenerator(const SkISize& fullSize, PassRefPtr<SharedBuffer>, bool allDataReceived, bool isMultiFrame); + ImageFrameGenerator(const SkISize& fullSize, bool isMultiFrame); friend class ImageFrameGeneratorTest; friend class DeferredImageDecoderTest; @@ -102,26 +99,18 @@ void setHasAlpha(size_t index, bool hasAlpha); - // These methods are called while m_decodeMutex is locked. - SkBitmap tryToResumeDecode(size_t index, const SkISize& scaledSize); - bool decode(size_t index, ImageDecoder**, SkBitmap*); + SkBitmap tryToResumeDecode(SegmentReader*, bool allDataReceived, size_t index, const SkISize& scaledSize, SkBitmap::Allocator*); + // This method should only be called while m_decodeMutex is locked. + bool decode(SegmentReader*, bool allDataReceived, size_t index, ImageDecoder**, SkBitmap*, SkBitmap::Allocator*); - SkISize m_fullSize; + const SkISize m_fullSize; - // ThreadSafeDataTransport is referenced by this class and m_encodedData. - // In case that ImageFrameGenerator get's deleted before m_encodedData, - // m_encodedData would hold the reference to it (and underlying data). - RefPtr<ThreadSafeDataTransport> m_data; - - bool m_isMultiFrame; + const bool m_isMultiFrame; bool m_decodeFailed; bool m_yuvDecodingFailed; size_t m_frameCount; Vector<bool> m_hasAlpha; - class ExternalMemoryAllocator; - OwnPtr<ExternalMemoryAllocator> m_externalAllocator; - OwnPtr<ImageDecoderFactory> m_imageDecoderFactory; // Prevents multiple decode operations on the same data. @@ -129,13 +118,6 @@ // Protect concurrent access to m_hasAlpha. Mutex m_alphaMutex; - - // Our encoded image data returned in refEncodedData. - SkData* m_encodedData; - -#if COMPILER(MSVC) - friend struct ::WTF::OwnedPtrDeleter<ExternalMemoryAllocator>; -#endif }; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/ImageFrameGeneratorTest.cpp b/third_party/WebKit/Source/platform/graphics/ImageFrameGeneratorTest.cpp index aef5863c..4b9d1b7 100644 --- a/third_party/WebKit/Source/platform/graphics/ImageFrameGeneratorTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/ImageFrameGeneratorTest.cpp
@@ -29,6 +29,7 @@ #include "platform/ThreadSafeFunctional.h" #include "platform/graphics/ImageDecodingStore.h" #include "platform/graphics/test/MockImageDecoder.h" +#include "platform/image-decoders/SegmentReader.h" #include "public/platform/Platform.h" #include "public/platform/WebTaskRunner.h" #include "public/platform/WebThread.h" @@ -54,8 +55,9 @@ void SetUp() override { ImageDecodingStore::instance().setCacheLimitInBytes(1024 * 1024); + m_generator = ImageFrameGenerator::create(fullSize(), false); m_data = SharedBuffer::create(); - m_generator = ImageFrameGenerator::create(fullSize(), m_data, false); + m_segmentReader = SegmentReader::createFromSharedBuffer(m_data); useMockImageDecoderFactory(); m_decodersDestroyed = 0; m_decodeRequestCount = 0; @@ -101,10 +103,9 @@ m_generator->setImageDecoderFactory(MockImageDecoderFactory::create(this, fullSize())); } - void addNewData(bool allDataReceived = false) + void addNewData() { m_data->append("g", 1u); - m_generator->setData(m_data, allDataReceived); } void setFrameStatus(ImageFrame::Status status) { m_status = m_nextFrameStatus = status; } @@ -114,12 +115,13 @@ m_frameCount = count; if (count > 1) { m_generator.clear(); - m_generator = ImageFrameGenerator::create(fullSize(), m_data, true, true); + m_generator = ImageFrameGenerator::create(fullSize(), true); useMockImageDecoderFactory(); } } RefPtr<SharedBuffer> m_data; + RefPtr<SegmentReader> m_segmentReader; RefPtr<ImageFrameGenerator> m_generator; int m_decodersDestroyed; int m_decodeRequestCount; @@ -134,11 +136,11 @@ setFrameStatus(ImageFrame::FramePartial); char buffer[100 * 100 * 4]; - m_generator->decodeAndScale(0, imageInfo(), buffer, 100 * 4); + m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(1, m_decodeRequestCount); addNewData(); - m_generator->decodeAndScale(0, imageInfo(), buffer, 100 * 4); + m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(2, m_decodeRequestCount); EXPECT_EQ(0, m_decodersDestroyed); } @@ -148,35 +150,26 @@ setFrameStatus(ImageFrame::FramePartial); char buffer[100 * 100 * 4]; - m_generator->decodeAndScale(0, imageInfo(), buffer, 100 * 4); + m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(1, m_decodeRequestCount); EXPECT_EQ(0, m_decodersDestroyed); setFrameStatus(ImageFrame::FrameComplete); addNewData(); - m_generator->decodeAndScale(0, imageInfo(), buffer, 100 * 4); + m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(2, m_decodeRequestCount); EXPECT_EQ(1, m_decodersDestroyed); // Decoder created again. - m_generator->decodeAndScale(0, imageInfo(), buffer, 100 * 4); + m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(3, m_decodeRequestCount); } -static void decodeThreadMain(ImageFrameGenerator* generator) +static void decodeThreadMain(ImageFrameGenerator* generator, SegmentReader* segmentReader) { char buffer[100 * 100 * 4]; - generator->decodeAndScale(0, imageInfo(), buffer, 100 * 4); -} - -static void decodeThreadWithRefEncodedMain(ImageFrameGenerator* generator) -{ - // Image must be complete - refEncodedData otherwise returns null. - char buffer[100 * 100 * 4]; - SkData* data = generator->refEncodedData(); - generator->decodeAndScale(0, imageInfo(), buffer, 100 * 4); - data->unref(); + generator->decodeAndScale(segmentReader, false, 0, imageInfo(), buffer, 100 * 4); } TEST_F(ImageFrameGeneratorTest, incompleteDecodeBecomesCompleteMultiThreaded) @@ -184,52 +177,27 @@ setFrameStatus(ImageFrame::FramePartial); char buffer[100 * 100 * 4]; - m_generator->decodeAndScale(0, imageInfo(), buffer, 100 * 4); + m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(1, m_decodeRequestCount); EXPECT_EQ(0, m_decodersDestroyed); - SkData* data = m_generator->refEncodedData(); - EXPECT_EQ(nullptr, data); // LocalFrame can now be decoded completely. setFrameStatus(ImageFrame::FrameComplete); addNewData(); - // addNewData is calling m_generator->setData with allDataReceived == false, which means that - // refEncodedData should return null. - data = m_generator->refEncodedData(); - EXPECT_EQ(nullptr, data); OwnPtr<WebThread> thread = adoptPtr(Platform::current()->createThread("DecodeThread")); - thread->getWebTaskRunner()->postTask(BLINK_FROM_HERE, threadSafeBind(&decodeThreadMain, AllowCrossThreadAccess(m_generator.get()))); + thread->getWebTaskRunner()->postTask(BLINK_FROM_HERE, threadSafeBind(&decodeThreadMain, AllowCrossThreadAccess(m_generator.get()), AllowCrossThreadAccess(m_segmentReader.get()))); thread.clear(); EXPECT_EQ(2, m_decodeRequestCount); EXPECT_EQ(1, m_decodersDestroyed); // Decoder created again. - m_generator->decodeAndScale(0, imageInfo(), buffer, 100 * 4); + m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(3, m_decodeRequestCount); - addNewData(true); - data = m_generator->refEncodedData(); - ASSERT_TRUE(data); - // To prevent data writting, SkData::unique() should be false. - ASSERT_TRUE(!data->unique()); + addNewData(); - // Thread will also ref and unref the data. - thread = adoptPtr(Platform::current()->createThread("RefEncodedDataThread")); - thread->getWebTaskRunner()->postTask(BLINK_FROM_HERE, threadSafeBind(&decodeThreadWithRefEncodedMain, AllowCrossThreadAccess(m_generator.get()))); - thread.clear(); - EXPECT_EQ(4, m_decodeRequestCount); - - data->unref(); - // m_generator is holding the only reference to SkData now. - ASSERT_TRUE(data->unique()); - - data = m_generator->refEncodedData(); - ASSERT_TRUE(data && !data->unique()); - - // Delete generator, and SkData should have the only reference. + // Delete generator. m_generator = nullptr; - ASSERT_TRUE(data->unique()); - data->unref(); } TEST_F(ImageFrameGeneratorTest, frameHasAlpha) @@ -237,7 +205,7 @@ setFrameStatus(ImageFrame::FramePartial); char buffer[100 * 100 * 4]; - m_generator->decodeAndScale(0, imageInfo(), buffer, 100 * 4); + m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_TRUE(m_generator->hasAlpha(0)); EXPECT_EQ(1, m_decodeRequestCount); @@ -249,7 +217,7 @@ EXPECT_EQ(2, m_decodeRequestCount); setFrameStatus(ImageFrame::FrameComplete); - m_generator->decodeAndScale(0, imageInfo(), buffer, 100 * 4); + m_generator->decodeAndScale(m_segmentReader.get(), false, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(3, m_decodeRequestCount); EXPECT_FALSE(m_generator->hasAlpha(0)); } @@ -260,14 +228,14 @@ setFrameStatus(ImageFrame::FrameComplete); char buffer[100 * 100 * 4]; - m_generator->decodeAndScale(0, imageInfo(), buffer, 100 * 4); + m_generator->decodeAndScale(m_segmentReader.get(), true, 0, imageInfo(), buffer, 100 * 4); EXPECT_EQ(1, m_decodeRequestCount); EXPECT_EQ(0, m_decodersDestroyed); EXPECT_EQ(0U, m_requestedClearExceptFrame); setFrameStatus(ImageFrame::FrameComplete); - m_generator->decodeAndScale(1, imageInfo(), buffer, 100 * 4); + m_generator->decodeAndScale(m_segmentReader.get(), true, 1, imageInfo(), buffer, 100 * 4); EXPECT_EQ(2, m_decodeRequestCount); EXPECT_EQ(0, m_decodersDestroyed); EXPECT_EQ(1U, m_requestedClearExceptFrame); @@ -277,7 +245,7 @@ // Decoding the last frame of a multi-frame images should trigger clearing // all the frame data, but not destroying the decoder. See comments in // ImageFrameGenerator::tryToResumeDecode(). - m_generator->decodeAndScale(2, imageInfo(), buffer, 100 * 4); + m_generator->decodeAndScale(m_segmentReader.get(), true, 2, imageInfo(), buffer, 100 * 4); EXPECT_EQ(3, m_decodeRequestCount); EXPECT_EQ(0, m_decodersDestroyed); EXPECT_EQ(kNotFound, m_requestedClearExceptFrame);
diff --git a/third_party/WebKit/Source/platform/graphics/PictureSnapshot.cpp b/third_party/WebKit/Source/platform/graphics/PictureSnapshot.cpp index 2034450..3e9e7da 100644 --- a/third_party/WebKit/Source/platform/graphics/PictureSnapshot.cpp +++ b/third_party/WebKit/Source/platform/graphics/PictureSnapshot.cpp
@@ -38,7 +38,9 @@ #include "platform/graphics/skia/ImagePixelLocker.h" #include "platform/image-decoders/ImageDecoder.h" #include "platform/image-decoders/ImageFrame.h" +#include "platform/image-decoders/SegmentReader.h" #include "platform/image-encoders/skia/PNGImageEncoder.h" +#include "third_party/skia/include/core/SkData.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkPictureRecorder.h" #include "third_party/skia/include/core/SkStream.h" @@ -56,11 +58,14 @@ static bool decodeBitmap(const void* data, size_t length, SkBitmap* result) { - RefPtr<SharedBuffer> buffer = SharedBuffer::create(static_cast<const char*>(data), length); - OwnPtr<ImageDecoder> imageDecoder = ImageDecoder::create(*buffer, ImageDecoder::AlphaPremultiplied, ImageDecoder::GammaAndColorProfileIgnored); + OwnPtr<ImageDecoder> imageDecoder = ImageDecoder::create(static_cast<const char*>(data), length, + ImageDecoder::AlphaPremultiplied, ImageDecoder::GammaAndColorProfileIgnored); if (!imageDecoder) return false; - imageDecoder->setData(buffer.get(), true); + + // No need to copy the data; this decodes immediately. + RefPtr<SegmentReader> segmentReader = SegmentReader::createFromSkData(adoptRef(SkData::NewWithoutCopy(data, length))); + imageDecoder->setData(segmentReader.release(), true); ImageFrame* frame = imageDecoder->frameBufferAtIndex(0); if (!frame) return true;
diff --git a/third_party/WebKit/Source/platform/graphics/ThreadSafeDataTransport.cpp b/third_party/WebKit/Source/platform/graphics/ThreadSafeDataTransport.cpp deleted file mode 100644 index f191017a..0000000 --- a/third_party/WebKit/Source/platform/graphics/ThreadSafeDataTransport.cpp +++ /dev/null
@@ -1,85 +0,0 @@ -/* - * Copyright (C) 2012 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 "platform/graphics/ThreadSafeDataTransport.h" - -#include "platform/SharedBuffer.h" - -namespace blink { - -ThreadSafeDataTransport::ThreadSafeDataTransport() - : m_readBuffer(SharedBuffer::create()) - , m_allDataReceived(false) - , m_readPosition(0) -{ -} - -ThreadSafeDataTransport::~ThreadSafeDataTransport() -{ -} - -void ThreadSafeDataTransport::setData(SharedBuffer* buffer, bool allDataReceived) -{ - ASSERT(buffer->size() >= m_readPosition); - Vector<RefPtr<SharedBuffer>> newBufferQueue; - - const char* segment = 0; - while (size_t length = buffer->getSomeData(segment, m_readPosition)) { - m_readPosition += length; - newBufferQueue.append(SharedBuffer::create(segment, length)); - } - - MutexLocker locker(m_mutex); - - // If all data was previously received, don't append more to it. - RELEASE_ASSERT(!(m_allDataReceived && newBufferQueue.size())); - - m_newBufferQueue.appendVector(newBufferQueue); - newBufferQueue.clear(); - m_allDataReceived = allDataReceived; -} - -void ThreadSafeDataTransport::data(SharedBuffer** buffer, bool* allDataReceived) -{ - ASSERT(buffer); - ASSERT(allDataReceived); - Vector<RefPtr<SharedBuffer>> newBufferQueue; - { - MutexLocker lock(m_mutex); - m_newBufferQueue.swap(newBufferQueue); - *allDataReceived = m_allDataReceived; - } - for (size_t i = 0; i < newBufferQueue.size(); ++i) - m_readBuffer->append(newBufferQueue[i].get()); - *buffer = m_readBuffer.get(); -} - -bool ThreadSafeDataTransport::hasNewData() -{ - MutexLocker lock(m_mutex); - return !m_newBufferQueue.isEmpty(); -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/ThreadSafeDataTransport.h b/third_party/WebKit/Source/platform/graphics/ThreadSafeDataTransport.h deleted file mode 100644 index 3aae947..0000000 --- a/third_party/WebKit/Source/platform/graphics/ThreadSafeDataTransport.h +++ /dev/null
@@ -1,78 +0,0 @@ -/* - * Copyright (C) 2012 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. - */ - -#ifndef ThreadSafeDataTransport_h -#define ThreadSafeDataTransport_h - -#include "platform/PlatformExport.h" -#include "wtf/Allocator.h" -#include "wtf/Noncopyable.h" -#include "wtf/OwnPtr.h" -#include "wtf/PassOwnPtr.h" -#include "wtf/RefPtr.h" -#include "wtf/ThreadSafeRefCounted.h" -#include "wtf/ThreadingPrimitives.h" -#include "wtf/Vector.h" - -namespace blink { - -class SharedBuffer; - -// The purpose of this class is to allow the transfer of data stored in -// SharedBuffer in a thread-safe manner, and to minimize memory copies -// and thread contention. -// -// This class is designed such that there is only one producer and -// one consumer. - -class PLATFORM_EXPORT ThreadSafeDataTransport final : public ThreadSafeRefCounted<ThreadSafeDataTransport> { - WTF_MAKE_NONCOPYABLE(ThreadSafeDataTransport); -public: - ThreadSafeDataTransport(); - ~ThreadSafeDataTransport(); - - // This method is being called subsequently with an expanding - // SharedBuffer. - void setData(SharedBuffer*, bool allDataReceived); - - // Get the data submitted to this class so far. - void data(SharedBuffer**, bool* allDataReceived); - - // Return true of there is new data submitted to this class - // since last time data() was called. - bool hasNewData(); - -private: - Mutex m_mutex; - - Vector<RefPtr<SharedBuffer>> m_newBufferQueue; - RefPtr<SharedBuffer> m_readBuffer; - bool m_allDataReceived; - size_t m_readPosition; -}; - -} // namespace blink - -#endif
diff --git a/third_party/WebKit/Source/platform/graphics/ThreadSafeDataTransportTest.cpp b/third_party/WebKit/Source/platform/graphics/ThreadSafeDataTransportTest.cpp deleted file mode 100644 index 69462ec..0000000 --- a/third_party/WebKit/Source/platform/graphics/ThreadSafeDataTransportTest.cpp +++ /dev/null
@@ -1,75 +0,0 @@ -/* - * Copyright (C) 2012 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 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 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 "platform/graphics/ThreadSafeDataTransport.h" - -#include "platform/SharedBuffer.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace blink { - -TEST(ThreadSafeDataTransportTest, hasNewData) -{ - ThreadSafeDataTransport transport; - - const char testString[] = "123456789"; - RefPtr<SharedBuffer> buffer = SharedBuffer::create(testString, sizeof(testString)); - - transport.setData(buffer.get(), false); - EXPECT_TRUE(transport.hasNewData()); - - SharedBuffer* tempBuffer = 0; - bool allDataReceived = false; - transport.data(&tempBuffer, &allDataReceived); - EXPECT_FALSE(transport.hasNewData()); - - transport.setData(buffer.get(), false); - EXPECT_FALSE(transport.hasNewData()); -} - -TEST(ThreadSafeDataTransportTest, setData) -{ - ThreadSafeDataTransport transport; - - const char testString1[] = "123"; - RefPtr<SharedBuffer> buffer1 = SharedBuffer::create(testString1, sizeof(testString1) - 1); - const char testString2[] = "12345"; - RefPtr<SharedBuffer> buffer2 = SharedBuffer::create(testString2, sizeof(testString2) - 1); - const char testString3[] = "1234567890"; - RefPtr<SharedBuffer> buffer3 = SharedBuffer::create(testString3, sizeof(testString3) - 1); - - transport.setData(buffer1.get(), false); - transport.setData(buffer2.get(), false); - transport.setData(buffer3.get(), true); - EXPECT_TRUE(transport.hasNewData()); - - SharedBuffer* tempBuffer = 0; - bool allDataReceived = false; - transport.data(&tempBuffer, &allDataReceived); - EXPECT_TRUE(allDataReceived); - EXPECT_FALSE(memcmp(testString3, tempBuffer->data(), tempBuffer->size())); -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/platform/heap/BlinkGC.h b/third_party/WebKit/Source/platform/heap/BlinkGC.h index ca91efe3..54a7e017 100644 --- a/third_party/WebKit/Source/platform/heap/BlinkGC.h +++ b/third_party/WebKit/Source/platform/heap/BlinkGC.h
@@ -50,9 +50,9 @@ enum GCType { // Both of the marking task and the sweeping task run in - // Heap::collectGarbage(). + // ThreadHeap::collectGarbage(). GCWithSweep, - // Only the marking task runs in Heap::collectGarbage(). + // Only the marking task runs in ThreadHeap::collectGarbage(). // The sweeping task is split into chunks and scheduled lazily. GCWithoutSweep, // Only the marking task runs just to take a heap snapshot.
diff --git a/third_party/WebKit/Source/platform/heap/BlinkGCAPIReference.md b/third_party/WebKit/Source/platform/heap/BlinkGCAPIReference.md index 1881237..e946a05 100644 --- a/third_party/WebKit/Source/platform/heap/BlinkGCAPIReference.md +++ b/third_party/WebKit/Source/platform/heap/BlinkGCAPIReference.md
@@ -177,7 +177,7 @@ A pre-finalizer must have the following function signature: `void preFinalizer()`. You can change the function name. A pre-finalizer must be registered in the constructor by using the following statement: -"`ThreadState::current()->registerPreFinalizer(preFinalizerName);`". +"`ThreadState::current()->registerPreFinalizer(this);`". ```c++ class YourClass : public GarbageCollectedFinalized<YourClass> { @@ -185,7 +185,7 @@ public: YourClass() { - ThreadState::current()->registerPreFinalizer(dispose); + ThreadState::current()->registerPreFinalizer(this); } void dispose() { @@ -231,12 +231,6 @@ // OK to leave the object behind. The Blink GC system will free it up when it becomes unused. ``` -*** aside -*Transitional only* - -`RawPtr<T>` is a simple wrapper of a raw pointer `T*` used in the transitional period. -Most`RawPtr<T>`s will be replaced with raw pointers. - ### Member, WeakMember In a garbage-collected class, on-heap objects must be retained by `Member<T>` or `WeakMember<T>`, depending on
diff --git a/third_party/WebKit/Source/platform/heap/BlinkGCMemoryDumpProvider.cpp b/third_party/WebKit/Source/platform/heap/BlinkGCMemoryDumpProvider.cpp index e627183..eea1e74 100644 --- a/third_party/WebKit/Source/platform/heap/BlinkGCMemoryDumpProvider.cpp +++ b/third_party/WebKit/Source/platform/heap/BlinkGCMemoryDumpProvider.cpp
@@ -26,7 +26,7 @@ dumpName.append("/allocated_objects"); WebMemoryAllocatorDump* objectsDump = memoryDump->createMemoryAllocatorDump(dumpName); - // Heap::markedObjectSize() can be underestimated if we're still in the + // ThreadHeap::markedObjectSize() can be underestimated if we're still in the // process of lazy sweeping. objectsDump->addScalar("size", "bytes", ProcessHeap::totalAllocatedObjectSize() + ProcessHeap::totalMarkedObjectSize()); } @@ -58,7 +58,7 @@ // In the case of a detailed dump perform a mark-only GC pass to collect // more detailed stats. if (levelOfDetail == WebMemoryDumpLevelOfDetail::Detailed) - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::TakeSnapshot, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::TakeSnapshot, BlinkGC::ForcedGC); dumpMemoryTotals(memoryDump); if (m_isHeapProfilingEnabled) { @@ -76,7 +76,7 @@ memoryDump->dumpHeapUsage(bytesByContext, overhead, "blink_gc"); } - // Merge all dumps collected by Heap::collectGarbage. + // Merge all dumps collected by ThreadHeap::collectGarbage. if (levelOfDetail == WebMemoryDumpLevelOfDetail::Detailed) memoryDump->takeAllDumpsFrom(m_currentProcessMemoryDump.get()); return true;
diff --git a/third_party/WebKit/Source/platform/heap/GarbageCollected.h b/third_party/WebKit/Source/platform/heap/GarbageCollected.h index 34be299..95804041 100644 --- a/third_party/WebKit/Source/platform/heap/GarbageCollected.h +++ b/third_party/WebKit/Source/platform/heap/GarbageCollected.h
@@ -204,7 +204,7 @@ public: \ bool isHeapObjectAlive() const override \ { \ - return Heap::isHeapObjectAlive(this); \ + return ThreadHeap::isHeapObjectAlive(this); \ } \ private:
diff --git a/third_party/WebKit/Source/platform/heap/Handle.h b/third_party/WebKit/Source/platform/heap/Handle.h index 41fb5f8..210d88c 100644 --- a/third_party/WebKit/Source/platform/heap/Handle.h +++ b/third_party/WebKit/Source/platform/heap/Handle.h
@@ -43,7 +43,6 @@ #include "wtf/Functional.h" #include "wtf/HashFunctions.h" #include "wtf/Locker.h" -#include "wtf/RawPtr.h" #include "wtf/RefCounted.h" #include "wtf/TypeTraits.h" @@ -118,13 +117,6 @@ checkPointer(); } - template<typename U> - PersistentBase(const RawPtr<U>& other) : m_raw(other.get()) - { - initialize(); - checkPointer(); - } - ~PersistentBase() { uninitialize(); @@ -154,7 +146,6 @@ T& operator*() const { return *m_raw; } bool operator!() const { return !m_raw; } operator T*() const { return m_raw; } - operator RawPtr<T>() const { return m_raw; } T* operator->() const { return *this; } T* get() const { return m_raw; } @@ -191,13 +182,6 @@ return *this; } - template<typename U> - PersistentBase& operator=(const RawPtr<U>& other) - { - assign(other); - return *this; - } - #if defined(LEAK_SANITIZER) PersistentBase* registerAsStaticReference() { @@ -274,15 +258,15 @@ if (!m_raw) return; - // Heap::isHeapObjectAlive(m_raw) checks that m_raw is a traceable + // ThreadHeap::isHeapObjectAlive(m_raw) checks that m_raw is a traceable // object. In other words, it checks that the pointer is either of: // // (a) a pointer to the head of an on-heap object. // (b) a pointer to the head of an on-heap mixin object. // - // Otherwise, Heap::isHeapObjectAlive will crash when it calls + // Otherwise, ThreadHeap::isHeapObjectAlive will crash when it calls // header->checkHeader(). - Heap::isHeapObjectAlive(m_raw); + ThreadHeap::isHeapObjectAlive(m_raw); #endif } @@ -313,8 +297,6 @@ Persistent(const Persistent<U>& other) : Parent(other) { } template<typename U> Persistent(const Member<U>& other) : Parent(other) { } - template<typename U> - Persistent(const RawPtr<U>& other) : Parent(other.get()) { } template<typename U> Persistent& operator=(U* other) @@ -348,13 +330,6 @@ Parent::operator=(other); return *this; } - - template<typename U> - Persistent& operator=(const RawPtr<U>& other) - { - Parent::operator=(other); - return *this; - } }; // WeakPersistent is a way to create a weak pointer from an off-heap object @@ -381,8 +356,6 @@ WeakPersistent(const WeakPersistent<U>& other) : Parent(other) { } template<typename U> WeakPersistent(const Member<U>& other) : Parent(other) { } - template<typename U> - WeakPersistent(const RawPtr<U>& other) : Parent(other.get()) { } template<typename U> WeakPersistent& operator=(U* other) @@ -416,13 +389,6 @@ Parent::operator=(other); return *this; } - - template<typename U> - WeakPersistent& operator=(const RawPtr<U>& other) - { - Parent::operator=(other); - return *this; - } }; // Unlike Persistent, we can destruct a CrossThreadPersistent in a thread @@ -440,8 +406,6 @@ CrossThreadPersistent(const CrossThreadPersistent<U>& other) : Parent(other) { } template<typename U> CrossThreadPersistent(const Member<U>& other) : Parent(other) { } - template<typename U> - CrossThreadPersistent(const RawPtr<U>& other) : Parent(other.get()) { } T* atomicGet() { return Parent::atomicGet(); } @@ -477,13 +441,6 @@ Parent::operator=(other); return *this; } - - template<typename U> - CrossThreadPersistent& operator=(const RawPtr<U>& other) - { - Parent::operator=(other); - return *this; - } }; // Combines the behavior of CrossThreadPersistent and WeakPersistent. @@ -500,8 +457,6 @@ CrossThreadWeakPersistent(const CrossThreadWeakPersistent<U>& other) : Parent(other) { } template<typename U> CrossThreadWeakPersistent(const Member<U>& other) : Parent(other) { } - template<typename U> - CrossThreadWeakPersistent(const RawPtr<U>& other) : Parent(other.get()) { } template<typename U> CrossThreadWeakPersistent& operator=(U* other) @@ -535,13 +490,6 @@ Parent::operator=(other); return *this; } - - template<typename U> - CrossThreadWeakPersistent& operator=(const RawPtr<U>& other) - { - Parent::operator=(other); - return *this; - } }; template<typename Collection> @@ -731,12 +679,6 @@ checkPointer(); } - template<typename U> - Member(const RawPtr<U>& other) : m_raw(other.get()) - { - checkPointer(); - } - Member(WTF::HashTableDeletedValueType) : m_raw(reinterpret_cast<T*>(-1)) { } @@ -773,8 +715,6 @@ T* operator->() const { return m_raw; } T& operator*() const { return *m_raw; } - template<typename U> - operator RawPtr<U>() const { return m_raw; } template<typename U> Member& operator=(const Persistent<U>& other) @@ -800,14 +740,6 @@ return *this; } - template<typename U> - Member& operator=(RawPtr<U> other) - { - m_raw = other; - checkPointer(); - return *this; - } - Member& operator=(std::nullptr_t) { m_raw = nullptr; @@ -844,7 +776,7 @@ // (a) a pointer to the head of an on-heap object. // (b) a pointer to the head of an on-heap mixin object. // - // We can check it by calling Heap::isHeapObjectAlive(m_raw), + // We can check it by calling ThreadHeap::isHeapObjectAlive(m_raw), // but we cannot call it here because it requires to include T.h. // So we currently only try to implement the check for (a), but do // not insist that T's definition is in scope. @@ -907,14 +839,6 @@ return *this; } - template<typename U> - WeakMember& operator=(const RawPtr<U>& other) - { - this->m_raw = other; - this->checkPointer(); - return *this; - } - WeakMember& operator=(std::nullptr_t) { this->m_raw = nullptr; @@ -945,9 +869,6 @@ UntracedMember(T* raw) : Member<T>(raw) { } template<typename U> - UntracedMember(const RawPtr<U>& other) : Member<T>(other) { } - - template<typename U> UntracedMember(const Persistent<U>& other) : Member<T>(other) { } template<typename U> @@ -979,14 +900,6 @@ return *this; } - template<typename U> - UntracedMember& operator=(const RawPtr<U>& other) - { - this->m_raw = other; - this->checkPointer(); - return *this; - } - UntracedMember& operator=(std::nullptr_t) { this->m_raw = nullptr; @@ -1009,7 +922,7 @@ class RawPtrOrMemberTrait { STATIC_ONLY(RawPtrOrMemberTrait) public: - using Type = RawPtr<T>; + using Type = T*; }; template<typename T> @@ -1260,12 +1173,6 @@ }; template<typename T> -struct ParamStorageTraits<RawPtr<T>> : public PointerParamStorageTraits<T*, blink::IsGarbageCollectedType<T>::value> { - STATIC_ONLY(ParamStorageTraits); - static_assert(sizeof(T), "T must be fully defined"); -}; - -template<typename T> struct ParamStorageTraits<blink::WeakPersistentThisPointer<T>> { STATIC_ONLY(ParamStorageTraits); static_assert(sizeof(T), "T must be fully defined");
diff --git a/third_party/WebKit/Source/platform/heap/Heap.cpp b/third_party/WebKit/Source/platform/heap/Heap.cpp index daf927f..a916993e 100644 --- a/third_party/WebKit/Source/platform/heap/Heap.cpp +++ b/third_party/WebKit/Source/platform/heap/Heap.cpp
@@ -30,7 +30,6 @@ #include "platform/heap/Heap.h" -#include "base/debug/alias.h" #include "base/sys_info.h" #include "platform/Histogram.h" #include "platform/ScriptForbiddenScope.h" @@ -66,7 +65,7 @@ bool parkThreads(ThreadState* state) { - TRACE_EVENT0("blink_gc", "Heap::ParkThreadsScope"); + TRACE_EVENT0("blink_gc", "ThreadHeap::ParkThreadsScope"); const char* samplingState = TRACE_EVENT_GET_SAMPLING_STATE(); if (state->isMainThread()) TRACE_EVENT_SET_SAMPLING_STATE("blink_gc", "BlinkGCWaiting"); @@ -99,7 +98,7 @@ bool m_shouldResumeThreads; }; -void Heap::flushHeapDoesNotContainCache() +void ThreadHeap::flushHeapDoesNotContainCache() { s_heapDoesNotContainCache->flush(); } @@ -118,7 +117,7 @@ s_totalMarkedObjectSize = 0; } -void Heap::init() +void ThreadHeap::init() { ThreadState::init(); ProcessHeap::init(); @@ -138,7 +137,7 @@ Platform::current()->registerMemoryDumpProvider(BlinkGCMemoryDumpProvider::instance(), "BlinkGC"); } -void Heap::shutdown() +void ThreadHeap::shutdown() { ASSERT(s_markingStack); @@ -164,7 +163,7 @@ s_ephemeronStack = nullptr; GCInfoTable::shutdown(); ThreadState::shutdown(); - ASSERT(Heap::heapStats().allocatedSpace() == 0); + ASSERT(ThreadHeap::heapStats().allocatedSpace() == 0); } CrossThreadPersistentRegion& ProcessHeap::crossThreadPersistentRegion() @@ -246,7 +245,7 @@ } #if ENABLE(ASSERT) -BasePage* Heap::findPageFromAddress(Address address) +BasePage* ThreadHeap::findPageFromAddress(Address address) { MutexLocker lock(ThreadState::threadAttachMutex()); for (ThreadState* state : ThreadState::attachedThreads()) { @@ -257,7 +256,7 @@ } #endif -Address Heap::checkAndMarkPointer(Visitor* visitor, Address address) +Address ThreadHeap::checkAndMarkPointer(Visitor* visitor, Address address) { ASSERT(ThreadState::current()->isInGC()); @@ -283,17 +282,17 @@ return nullptr; } -void Heap::pushTraceCallback(void* object, TraceCallback callback) +void ThreadHeap::pushTraceCallback(void* object, TraceCallback callback) { ASSERT(ThreadState::current()->isInGC()); // Trace should never reach an orphaned page. - ASSERT(!Heap::getOrphanedPagePool()->contains(object)); + ASSERT(!ThreadHeap::getOrphanedPagePool()->contains(object)); CallbackStack::Item* slot = s_markingStack->allocateEntry(); *slot = CallbackStack::Item(object, callback); } -bool Heap::popAndInvokeTraceCallback(Visitor* visitor) +bool ThreadHeap::popAndInvokeTraceCallback(Visitor* visitor) { CallbackStack::Item* item = s_markingStack->pop(); if (!item) @@ -302,17 +301,17 @@ return true; } -void Heap::pushPostMarkingCallback(void* object, TraceCallback callback) +void ThreadHeap::pushPostMarkingCallback(void* object, TraceCallback callback) { ASSERT(ThreadState::current()->isInGC()); // Trace should never reach an orphaned page. - ASSERT(!Heap::getOrphanedPagePool()->contains(object)); + ASSERT(!ThreadHeap::getOrphanedPagePool()->contains(object)); CallbackStack::Item* slot = s_postMarkingCallbackStack->allocateEntry(); *slot = CallbackStack::Item(object, callback); } -bool Heap::popAndInvokePostMarkingCallback(Visitor* visitor) +bool ThreadHeap::popAndInvokePostMarkingCallback(Visitor* visitor) { if (CallbackStack::Item* item = s_postMarkingCallbackStack->pop()) { item->call(visitor); @@ -321,27 +320,27 @@ return false; } -void Heap::pushGlobalWeakCallback(void** cell, WeakCallback callback) +void ThreadHeap::pushGlobalWeakCallback(void** cell, WeakCallback callback) { ASSERT(ThreadState::current()->isInGC()); // Trace should never reach an orphaned page. - ASSERT(!Heap::getOrphanedPagePool()->contains(cell)); + ASSERT(!ThreadHeap::getOrphanedPagePool()->contains(cell)); CallbackStack::Item* slot = s_globalWeakCallbackStack->allocateEntry(); *slot = CallbackStack::Item(cell, callback); } -void Heap::pushThreadLocalWeakCallback(void* closure, void* object, WeakCallback callback) +void ThreadHeap::pushThreadLocalWeakCallback(void* closure, void* object, WeakCallback callback) { ASSERT(ThreadState::current()->isInGC()); // Trace should never reach an orphaned page. - ASSERT(!Heap::getOrphanedPagePool()->contains(object)); + ASSERT(!ThreadHeap::getOrphanedPagePool()->contains(object)); ThreadState* state = pageFromObject(object)->arena()->getThreadState(); state->pushThreadLocalWeakCallback(closure, callback); } -bool Heap::popAndInvokeGlobalWeakCallback(Visitor* visitor) +bool ThreadHeap::popAndInvokeGlobalWeakCallback(Visitor* visitor) { if (CallbackStack::Item* item = s_globalWeakCallbackStack->pop()) { item->call(visitor); @@ -350,12 +349,12 @@ return false; } -void Heap::registerWeakTable(void* table, EphemeronCallback iterationCallback, EphemeronCallback iterationDoneCallback) +void ThreadHeap::registerWeakTable(void* table, EphemeronCallback iterationCallback, EphemeronCallback iterationDoneCallback) { ASSERT(ThreadState::current()->isInGC()); // Trace should never reach an orphaned page. - ASSERT(!Heap::getOrphanedPagePool()->contains(table)); + ASSERT(!ThreadHeap::getOrphanedPagePool()->contains(table)); CallbackStack::Item* slot = s_ephemeronStack->allocateEntry(); *slot = CallbackStack::Item(table, iterationCallback); @@ -365,14 +364,14 @@ } #if ENABLE(ASSERT) -bool Heap::weakTableRegistered(const void* table) +bool ThreadHeap::weakTableRegistered(const void* table) { ASSERT(s_ephemeronStack); return s_ephemeronStack->hasCallbackForObject(table); } #endif -void Heap::decommitCallbackStacks() +void ThreadHeap::decommitCallbackStacks() { s_markingStack->decommit(); s_postMarkingCallbackStack->decommit(); @@ -380,21 +379,21 @@ s_ephemeronStack->decommit(); } -void Heap::preGC() +void ThreadHeap::preGC() { ASSERT(!ThreadState::current()->isInGC()); for (ThreadState* state : ThreadState::attachedThreads()) state->preGC(); } -void Heap::postGC(BlinkGC::GCType gcType) +void ThreadHeap::postGC(BlinkGC::GCType gcType) { ASSERT(ThreadState::current()->isInGC()); for (ThreadState* state : ThreadState::attachedThreads()) state->postGC(gcType); } -const char* Heap::gcReasonString(BlinkGC::GCReason reason) +const char* ThreadHeap::gcReasonString(BlinkGC::GCReason reason) { switch (reason) { case BlinkGC::IdleGC: @@ -415,7 +414,7 @@ return "<Unknown>"; } -void Heap::collectGarbage(BlinkGC::StackState stackState, BlinkGC::GCType gcType, BlinkGC::GCReason reason) +void ThreadHeap::collectGarbage(BlinkGC::StackState stackState, BlinkGC::GCType gcType, BlinkGC::GCReason reason) { ASSERT(gcType != BlinkGC::ThreadTerminationGC); @@ -424,11 +423,6 @@ RELEASE_ASSERT(!state->isGCForbidden()); state->completeSweep(); - size_t debugAllocatedObjectSize = Heap::heapStats().allocatedObjectSize(); - base::debug::Alias(&debugAllocatedObjectSize); - size_t debugWrapperCount = Heap::heapStats().wrapperCount(); - base::debug::Alias(&debugWrapperCount); - OwnPtr<Visitor> visitor = Visitor::create(state, gcType); SafePointScope safePointScope(stackState, state); @@ -442,7 +436,7 @@ ScriptForbiddenIfMainThreadScope scriptForbidden; - TRACE_EVENT2("blink_gc,devtools.timeline", "Heap::collectGarbage", + TRACE_EVENT2("blink_gc,devtools.timeline", "BlinkGCMarking", "lazySweeping", gcType == BlinkGC::GCWithoutSweep, "gcReason", gcReasonString(reason)); TRACE_EVENT_SCOPED_SAMPLING_STATE("blink_gc", "BlinkGC"); @@ -459,9 +453,9 @@ StackFrameDepthScope stackDepthScope; - size_t totalObjectSize = Heap::heapStats().allocatedObjectSize() + Heap::heapStats().markedObjectSize(); + size_t totalObjectSize = ThreadHeap::heapStats().allocatedObjectSize() + ThreadHeap::heapStats().markedObjectSize(); if (gcType != BlinkGC::TakeSnapshot) - Heap::resetHeapCounters(); + ThreadHeap::resetHeapCounters(); // 1. Trace persistent roots. ThreadState::visitPersistentRoots(visitor.get()); @@ -482,10 +476,10 @@ getOrphanedPagePool()->decommitOrphanedPages(); double markingTimeInMilliseconds = WTF::currentTimeMS() - startTime; - Heap::heapStats().setEstimatedMarkingTimePerByte(totalObjectSize ? (markingTimeInMilliseconds / 1000 / totalObjectSize) : 0); + ThreadHeap::heapStats().setEstimatedMarkingTimePerByte(totalObjectSize ? (markingTimeInMilliseconds / 1000 / totalObjectSize) : 0); #if PRINT_HEAP_STATS - dataLogF("Heap::collectGarbage (gcReason=%s, lazySweeping=%d, time=%.1lfms)\n", gcReasonString(reason), gcType == BlinkGC::GCWithoutSweep, markingTimeInMilliseconds); + dataLogF("ThreadHeap::collectGarbage (gcReason=%s, lazySweeping=%d, time=%.1lfms)\n", gcReasonString(reason), gcType == BlinkGC::GCWithoutSweep, markingTimeInMilliseconds); #endif DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, markingTimeHistogram, new CustomCountHistogram("BlinkGC.CollectGarbage", 0, 10 * 1000, 50)); @@ -499,14 +493,14 @@ s_lastGCReason = reason; - Heap::reportMemoryUsageHistogram(); + ThreadHeap::reportMemoryUsageHistogram(); WTF::Partitions::reportMemoryUsageHistogram(); postGC(gcType); - Heap::decommitCallbackStacks(); + ThreadHeap::decommitCallbackStacks(); } -void Heap::collectGarbageForTerminatingThread(ThreadState* state) +void ThreadHeap::collectGarbageForTerminatingThread(ThreadState* state) { { // A thread-specific termination GC must not allow other global GCs to go @@ -539,26 +533,26 @@ globalWeakProcessing(visitor.get()); state->postGC(BlinkGC::GCWithSweep); - Heap::decommitCallbackStacks(); + ThreadHeap::decommitCallbackStacks(); } state->preSweep(); } -void Heap::processMarkingStack(Visitor* visitor) +void ThreadHeap::processMarkingStack(Visitor* visitor) { // Ephemeron fixed point loop. do { { // Iteratively mark all objects that are reachable from the objects // currently pushed onto the marking stack. - TRACE_EVENT0("blink_gc", "Heap::processMarkingStackSingleThreaded"); + TRACE_EVENT0("blink_gc", "ThreadHeap::processMarkingStackSingleThreaded"); while (popAndInvokeTraceCallback(visitor)) { } } { // Mark any strong pointers that have now become reachable in // ephemeron maps. - TRACE_EVENT0("blink_gc", "Heap::processEphemeronStack"); + TRACE_EVENT0("blink_gc", "ThreadHeap::processEphemeronStack"); s_ephemeronStack->invokeEphemeronCallbacks(visitor); } @@ -566,9 +560,9 @@ } while (!s_markingStack->isEmpty()); } -void Heap::postMarkingProcessing(Visitor* visitor) +void ThreadHeap::postMarkingProcessing(Visitor* visitor) { - TRACE_EVENT0("blink_gc", "Heap::postMarkingProcessing"); + TRACE_EVENT0("blink_gc", "ThreadHeap::postMarkingProcessing"); // Call post-marking callbacks including: // 1. the ephemeronIterationDone callbacks on weak tables to do cleanup // (specifically to clear the queued bits for weak hash tables), and @@ -582,9 +576,9 @@ ASSERT(s_markingStack->isEmpty()); } -void Heap::globalWeakProcessing(Visitor* visitor) +void ThreadHeap::globalWeakProcessing(Visitor* visitor) { - TRACE_EVENT0("blink_gc", "Heap::globalWeakProcessing"); + TRACE_EVENT0("blink_gc", "ThreadHeap::globalWeakProcessing"); double startTime = WTF::currentTimeMS(); // Call weak callbacks on objects that may now be pointing to dead objects. @@ -599,20 +593,20 @@ globalWeakTimeHistogram.count(timeForGlobalWeakProcessing); } -void Heap::collectAllGarbage() +void ThreadHeap::collectAllGarbage() { // We need to run multiple GCs to collect a chain of persistent handles. size_t previousLiveObjects = 0; for (int i = 0; i < 5; ++i) { collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); - size_t liveObjects = Heap::heapStats().markedObjectSize(); + size_t liveObjects = ThreadHeap::heapStats().markedObjectSize(); if (liveObjects == previousLiveObjects) break; previousLiveObjects = liveObjects; } } -void Heap::reportMemoryUsageHistogram() +void ThreadHeap::reportMemoryUsageHistogram() { static size_t supportedMaxSizeInMB = 4 * 1024; static size_t observedMaxSizeInMB = 0; @@ -621,7 +615,7 @@ if (!isMainThread()) return; // +1 is for rounding up the sizeInMB. - size_t sizeInMB = Heap::heapStats().allocatedSpace() / 1024 / 1024 + 1; + size_t sizeInMB = ThreadHeap::heapStats().allocatedSpace() / 1024 / 1024 + 1; if (sizeInMB >= supportedMaxSizeInMB) sizeInMB = supportedMaxSizeInMB - 1; if (sizeInMB > observedMaxSizeInMB) { @@ -633,10 +627,10 @@ } } -void Heap::reportMemoryUsageForTracing() +void ThreadHeap::reportMemoryUsageForTracing() { #if PRINT_HEAP_STATS - // dataLogF("allocatedSpace=%ldMB, allocatedObjectSize=%ldMB, markedObjectSize=%ldMB, partitionAllocSize=%ldMB, wrapperCount=%ld, collectedWrapperCount=%ld\n", Heap::allocatedSpace() / 1024 / 1024, Heap::allocatedObjectSize() / 1024 / 1024, Heap::markedObjectSize() / 1024 / 1024, WTF::Partitions::totalSizeOfCommittedPages() / 1024 / 1024, Heap::wrapperCount(), Heap::collectedWrapperCount()); + // dataLogF("allocatedSpace=%ldMB, allocatedObjectSize=%ldMB, markedObjectSize=%ldMB, partitionAllocSize=%ldMB, wrapperCount=%ld, collectedWrapperCount=%ld\n", ThreadHeap::allocatedSpace() / 1024 / 1024, ThreadHeap::allocatedObjectSize() / 1024 / 1024, ThreadHeap::markedObjectSize() / 1024 / 1024, WTF::Partitions::totalSizeOfCommittedPages() / 1024 / 1024, ThreadHeap::wrapperCount(), ThreadHeap::collectedWrapperCount()); #endif bool gcTracingEnabled; @@ -646,19 +640,19 @@ // These values are divided by 1024 to avoid overflow in practical cases (TRACE_COUNTER values are 32-bit ints). // They are capped to INT_MAX just in case. - TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "Heap::allocatedObjectSizeKB", std::min(Heap::heapStats().allocatedObjectSize() / 1024, static_cast<size_t>(INT_MAX))); - TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "Heap::markedObjectSizeKB", std::min(Heap::heapStats().markedObjectSize() / 1024, static_cast<size_t>(INT_MAX))); - TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "Heap::markedObjectSizeAtLastCompleteSweepKB", std::min(Heap::heapStats().markedObjectSizeAtLastCompleteSweep() / 1024, static_cast<size_t>(INT_MAX))); - TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "Heap::allocatedSpaceKB", std::min(Heap::heapStats().allocatedSpace() / 1024, static_cast<size_t>(INT_MAX))); - TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "Heap::objectSizeAtLastGCKB", std::min(Heap::heapStats().objectSizeAtLastGC() / 1024, static_cast<size_t>(INT_MAX))); - TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "Heap::wrapperCount", std::min(Heap::heapStats().wrapperCount(), static_cast<size_t>(INT_MAX))); - TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "Heap::heapStats().wrapperCountAtLastGC", std::min(Heap::heapStats().wrapperCountAtLastGC(), static_cast<size_t>(INT_MAX))); - TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "Heap::collectedWrapperCount", std::min(Heap::heapStats().collectedWrapperCount(), static_cast<size_t>(INT_MAX))); - TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "Heap::partitionAllocSizeAtLastGCKB", std::min(Heap::heapStats().partitionAllocSizeAtLastGC() / 1024, static_cast<size_t>(INT_MAX))); + TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::allocatedObjectSizeKB", std::min(ThreadHeap::heapStats().allocatedObjectSize() / 1024, static_cast<size_t>(INT_MAX))); + TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::markedObjectSizeKB", std::min(ThreadHeap::heapStats().markedObjectSize() / 1024, static_cast<size_t>(INT_MAX))); + TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::markedObjectSizeAtLastCompleteSweepKB", std::min(ThreadHeap::heapStats().markedObjectSizeAtLastCompleteSweep() / 1024, static_cast<size_t>(INT_MAX))); + TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::allocatedSpaceKB", std::min(ThreadHeap::heapStats().allocatedSpace() / 1024, static_cast<size_t>(INT_MAX))); + TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::objectSizeAtLastGCKB", std::min(ThreadHeap::heapStats().objectSizeAtLastGC() / 1024, static_cast<size_t>(INT_MAX))); + TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::wrapperCount", std::min(ThreadHeap::heapStats().wrapperCount(), static_cast<size_t>(INT_MAX))); + TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::heapStats().wrapperCountAtLastGC", std::min(ThreadHeap::heapStats().wrapperCountAtLastGC(), static_cast<size_t>(INT_MAX))); + TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::collectedWrapperCount", std::min(ThreadHeap::heapStats().collectedWrapperCount(), static_cast<size_t>(INT_MAX))); + TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadHeap::partitionAllocSizeAtLastGCKB", std::min(ThreadHeap::heapStats().partitionAllocSizeAtLastGC() / 1024, static_cast<size_t>(INT_MAX))); TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "Partitions::totalSizeOfCommittedPagesKB", std::min(WTF::Partitions::totalSizeOfCommittedPages() / 1024, static_cast<size_t>(INT_MAX))); } -size_t Heap::objectPayloadSizeForTesting() +size_t ThreadHeap::objectPayloadSizeForTesting() { size_t objectPayloadSize = 0; for (ThreadState* state : ThreadState::attachedThreads()) { @@ -672,49 +666,48 @@ return objectPayloadSize; } -RegionTree* Heap::getRegionTree() +RegionTree* ThreadHeap::getRegionTree() { DEFINE_THREAD_SAFE_STATIC_LOCAL(RegionTree, tree, new RegionTree); return &tree; } -BasePage* Heap::lookup(Address address) +BasePage* ThreadHeap::lookup(Address address) { ASSERT(ThreadState::current()->isInGC()); - if (PageMemoryRegion* region = Heap::getRegionTree()->lookup(address)) { + if (PageMemoryRegion* region = ThreadHeap::getRegionTree()->lookup(address)) { BasePage* page = region->pageFromAddress(address); return page && !page->orphaned() ? page : nullptr; } return nullptr; } -void Heap::resetHeapCounters() +void ThreadHeap::resetHeapCounters() { ASSERT(ThreadState::current()->isInGC()); - Heap::reportMemoryUsageForTracing(); + ThreadHeap::reportMemoryUsageForTracing(); ProcessHeap::resetHeapCounters(); - Heap::heapStats().reset(); + ThreadHeap::heapStats().reset(); for (ThreadState* state : ThreadState::attachedThreads()) state->resetHeapCounters(); } -// TODO(keishi): Make this a member of ThreadHeap. -ThreadHeapStats& Heap::heapStats() +ThreadHeapStats& ThreadHeap::heapStats() { DEFINE_THREAD_SAFE_STATIC_LOCAL(ThreadHeapStats, stats, new ThreadHeapStats()); return stats; } -CallbackStack* Heap::s_markingStack; -CallbackStack* Heap::s_postMarkingCallbackStack; -CallbackStack* Heap::s_globalWeakCallbackStack; -CallbackStack* Heap::s_ephemeronStack; -HeapDoesNotContainCache* Heap::s_heapDoesNotContainCache; -FreePagePool* Heap::s_freePagePool; -OrphanedPagePool* Heap::s_orphanedPagePool; +CallbackStack* ThreadHeap::s_markingStack; +CallbackStack* ThreadHeap::s_postMarkingCallbackStack; +CallbackStack* ThreadHeap::s_globalWeakCallbackStack; +CallbackStack* ThreadHeap::s_ephemeronStack; +HeapDoesNotContainCache* ThreadHeap::s_heapDoesNotContainCache; +FreePagePool* ThreadHeap::s_freePagePool; +OrphanedPagePool* ThreadHeap::s_orphanedPagePool; -BlinkGC::GCReason Heap::s_lastGCReason = BlinkGC::NumberOfGCReason; +BlinkGC::GCReason ThreadHeap::s_lastGCReason = BlinkGC::NumberOfGCReason; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/heap/Heap.h b/third_party/WebKit/Source/platform/heap/Heap.h index 0d268b0..e03e1e1e 100644 --- a/third_party/WebKit/Source/platform/heap/Heap.h +++ b/third_party/WebKit/Source/platform/heap/Heap.h
@@ -171,8 +171,8 @@ double m_estimatedMarkingTimePerByte; }; -class PLATFORM_EXPORT Heap { - STATIC_ONLY(Heap); +class PLATFORM_EXPORT ThreadHeap { + STATIC_ONLY(ThreadHeap); public: static void init(); static void shutdown(); @@ -211,9 +211,9 @@ return isHeapObjectAlive(member.get()); } template<typename T> - static inline bool isHeapObjectAlive(const RawPtr<T>& ptr) + static inline bool isHeapObjectAlive(const T*& ptr) { - return isHeapObjectAlive(ptr.get()); + return isHeapObjectAlive(ptr); } // Is the finalizable GC object still alive, but slated for lazy sweeping? @@ -234,7 +234,7 @@ return false; ASSERT(page->arena()->getThreadState()->isSweepingInProgress()); - return !Heap::isHeapObjectAlive(const_cast<T*>(objectPointer)); + return !ThreadHeap::isHeapObjectAlive(const_cast<T*>(objectPointer)); } // Push a trace callback on the marking stack. @@ -411,7 +411,7 @@ static void* allocateObject(size_t size, bool eagerlySweep) { - return Heap::allocate<T>(size, eagerlySweep); + return ThreadHeap::allocate<T>(size, eagerlySweep); } void operator delete(void* p) @@ -444,7 +444,7 @@ // for a class. // -inline int Heap::arenaIndexForObjectSize(size_t size) +inline int ThreadHeap::arenaIndexForObjectSize(size_t size) { if (size < 64) { if (size < 32) @@ -456,7 +456,7 @@ return BlinkGC::NormalPage4ArenaIndex; } -inline bool Heap::isNormalArenaIndex(int index) +inline bool ThreadHeap::isNormalArenaIndex(int index) { return index >= BlinkGC::NormalPage1ArenaIndex && index <= BlinkGC::NormalPage4ArenaIndex; } @@ -496,7 +496,7 @@ #define EAGERLY_FINALIZE() typedef int IsEagerlyFinalizedMarker #endif -inline Address Heap::allocateOnArenaIndex(ThreadState* state, size_t size, int arenaIndex, size_t gcInfoIndex, const char* typeName) +inline Address ThreadHeap::allocateOnArenaIndex(ThreadState* state, size_t size, int arenaIndex, size_t gcInfoIndex, const char* typeName) { ASSERT(state->isAllocationAllowed()); ASSERT(arenaIndex != BlinkGC::LargeObjectArenaIndex); @@ -507,15 +507,15 @@ } template<typename T> -Address Heap::allocate(size_t size, bool eagerlySweep) +Address ThreadHeap::allocate(size_t size, bool eagerlySweep) { ThreadState* state = ThreadStateFor<ThreadingTrait<T>::Affinity>::state(); const char* typeName = WTF_HEAP_PROFILER_TYPE_NAME(T); - return Heap::allocateOnArenaIndex(state, size, eagerlySweep ? BlinkGC::EagerSweepArenaIndex : Heap::arenaIndexForObjectSize(size), GCInfoTrait<T>::index(), typeName); + return ThreadHeap::allocateOnArenaIndex(state, size, eagerlySweep ? BlinkGC::EagerSweepArenaIndex : ThreadHeap::arenaIndexForObjectSize(size), GCInfoTrait<T>::index(), typeName); } template<typename T> -Address Heap::reallocate(void* previous, size_t size) +Address ThreadHeap::reallocate(void* previous, size_t size) { // Not intended to be a full C realloc() substitute; // realloc(nullptr, size) is not a supported alias for malloc(size). @@ -537,11 +537,11 @@ arenaIndex = arenaIndexForObjectSize(size); // TODO(haraken): We don't support reallocate() for finalizable objects. - ASSERT(!Heap::gcInfo(previousHeader->gcInfoIndex())->hasFinalizer()); + ASSERT(!ThreadHeap::gcInfo(previousHeader->gcInfoIndex())->hasFinalizer()); ASSERT(previousHeader->gcInfoIndex() == GCInfoTrait<T>::index()); const char* typeName = WTF_HEAP_PROFILER_TYPE_NAME(T); HeapAllocHooks::freeHookIfEnabled(static_cast<Address>(previous)); - Address address = Heap::allocateOnArenaIndex(state, size, arenaIndex, GCInfoTrait<T>::index(), typeName); + Address address = ThreadHeap::allocateOnArenaIndex(state, size, arenaIndex, GCInfoTrait<T>::index(), typeName); size_t copySize = previousHeader->payloadSize(); if (copySize > size) copySize = size;
diff --git a/third_party/WebKit/Source/platform/heap/HeapAllocator.h b/third_party/WebKit/Source/platform/heap/HeapAllocator.h index 8261f0e..11cd004c 100644 --- a/third_party/WebKit/Source/platform/heap/HeapAllocator.h +++ b/third_party/WebKit/Source/platform/heap/HeapAllocator.h
@@ -33,7 +33,7 @@ static size_t quantizedSize(size_t count) { RELEASE_ASSERT(count <= maxHeapObjectSize / sizeof(T)); - return Heap::allocationSizeFromSize(count * sizeof(T)) - sizeof(HeapObjectHeader); + return ThreadHeap::allocationSizeFromSize(count * sizeof(T)) - sizeof(HeapObjectHeader); } template <typename T> static T* allocateVectorBacking(size_t size) @@ -42,7 +42,7 @@ ASSERT(state->isAllocationAllowed()); size_t gcInfoIndex = GCInfoTrait<HeapVectorBacking<T, VectorTraits<T>>>::index(); NormalPageArena* arena = static_cast<NormalPageArena*>(state->vectorBackingArena(gcInfoIndex)); - return reinterpret_cast<T*>(arena->allocateObject(Heap::allocationSizeFromSize(size), gcInfoIndex)); + return reinterpret_cast<T*>(arena->allocateObject(ThreadHeap::allocationSizeFromSize(size), gcInfoIndex)); } template <typename T> static T* allocateExpandedVectorBacking(size_t size) @@ -51,7 +51,7 @@ ASSERT(state->isAllocationAllowed()); size_t gcInfoIndex = GCInfoTrait<HeapVectorBacking<T, VectorTraits<T>>>::index(); NormalPageArena* arena = static_cast<NormalPageArena*>(state->expandedVectorBackingArena(gcInfoIndex)); - return reinterpret_cast<T*>(arena->allocateObject(Heap::allocationSizeFromSize(size), gcInfoIndex)); + return reinterpret_cast<T*>(arena->allocateObject(ThreadHeap::allocationSizeFromSize(size), gcInfoIndex)); } static void freeVectorBacking(void*); static bool expandVectorBacking(void*, size_t); @@ -64,7 +64,7 @@ #define COMMA , const char* typeName = WTF_HEAP_PROFILER_TYPE_NAME(HeapVectorBacking<T COMMA VectorTraits<T>>); #undef COMMA - return reinterpret_cast<T*>(Heap::allocateOnArenaIndex(state, size, BlinkGC::InlineVectorArenaIndex, gcInfoIndex, typeName)); + return reinterpret_cast<T*>(ThreadHeap::allocateOnArenaIndex(state, size, BlinkGC::InlineVectorArenaIndex, gcInfoIndex, typeName)); } static void freeInlineVectorBacking(void*); static bool expandInlineVectorBacking(void*, size_t); @@ -76,7 +76,7 @@ size_t gcInfoIndex = GCInfoTrait<HeapHashTableBacking<HashTable>>::index(); ThreadState* state = ThreadStateFor<ThreadingTrait<T>::Affinity>::state(); const char* typeName = WTF_HEAP_PROFILER_TYPE_NAME(HeapHashTableBacking<HashTable>); - return reinterpret_cast<T*>(Heap::allocateOnArenaIndex(state, size, BlinkGC::HashTableArenaIndex, gcInfoIndex, typeName)); + return reinterpret_cast<T*>(ThreadHeap::allocateOnArenaIndex(state, size, BlinkGC::HashTableArenaIndex, gcInfoIndex, typeName)); } template <typename T, typename HashTable> static T* allocateZeroedHashTableBacking(size_t size) @@ -89,7 +89,7 @@ template <typename Return, typename Metadata> static Return malloc(size_t size, const char* typeName) { - return reinterpret_cast<Return>(Heap::allocate<Metadata>(size, IsEagerlyFinalizedType<Metadata>::value)); + return reinterpret_cast<Return>(ThreadHeap::allocate<Metadata>(size, IsEagerlyFinalizedType<Metadata>::value)); } static void free(void* address) { } template<typename T> @@ -112,7 +112,7 @@ template<typename T> static bool isHeapObjectAlive(T* object) { - return Heap::isHeapObjectAlive(object); + return ThreadHeap::isHeapObjectAlive(object); } template<typename VisitorDispatcher> @@ -466,8 +466,8 @@ // types can be merged into PassInType. // FIXME: Implement proper const'ness for iterator types. Requires support // in the marking Visitor. - using PeekInType = RawPtr<T>; - using PassInType = RawPtr<T>; + using PeekInType = T*; + using PassInType = T*; using IteratorGetType = blink::Member<T>*; using IteratorConstGetType = const blink::Member<T>*; using IteratorReferenceType = blink::Member<T>&; @@ -494,8 +494,8 @@ // types can be merged into PassInType. // FIXME: Implement proper const'ness for iterator types. Requires support // in the marking Visitor. - using PeekInType = RawPtr<T>; - using PassInType = RawPtr<T>; + using PeekInType = T*; + using PassInType = T*; using IteratorGetType = blink::WeakMember<T>*; using IteratorConstGetType = const blink::WeakMember<T>*; using IteratorReferenceType = blink::WeakMember<T>&; @@ -520,7 +520,7 @@ visitor->trace(weakMember.get()); // Strongified visit. return false; } - return !blink::Heap::isHeapObjectAlive(weakMember); + return !blink::ThreadHeap::isHeapObjectAlive(weakMember); } }; @@ -531,8 +531,8 @@ // the sake of the reference counting handles. When they are gone the two // types can be merged into PassInType. // FIXME: Implement proper const'ness for iterator types. - using PeekInType = RawPtr<T>; - using PassInType = RawPtr<T>; + using PeekInType = T*; + using PassInType = T*; using IteratorGetType = blink::UntracedMember<T>*; using IteratorConstGetType = const blink::UntracedMember<T>*; using IteratorReferenceType = blink::UntracedMember<T>&;
diff --git a/third_party/WebKit/Source/platform/heap/HeapPage.cpp b/third_party/WebKit/Source/platform/heap/HeapPage.cpp index 7a580eb..85c34148c 100644 --- a/third_party/WebKit/Source/platform/heap/HeapPage.cpp +++ b/third_party/WebKit/Source/platform/heap/HeapPage.cpp
@@ -98,7 +98,7 @@ void HeapObjectHeader::finalize(Address object, size_t objectSize) { HeapAllocHooks::freeHookIfEnabled(object); - const GCInfo* gcInfo = Heap::gcInfo(gcInfoIndex()); + const GCInfo* gcInfo = ThreadHeap::gcInfo(gcInfoIndex()); if (gcInfo->hasFinalizer()) gcInfo->m_finalize(object); @@ -126,8 +126,8 @@ ASSERT(!m_firstUnsweptPage); // Add the BaseArena's pages to the orphanedPagePool. for (BasePage* page = m_firstPage; page; page = page->next()) { - Heap::heapStats().decreaseAllocatedSpace(page->size()); - Heap::getOrphanedPagePool()->addOrphanedPage(arenaIndex(), page); + ThreadHeap::heapStats().decreaseAllocatedSpace(page->size()); + ThreadHeap::getOrphanedPagePool()->addOrphanedPage(arenaIndex(), page); } m_firstPage = nullptr; } @@ -282,7 +282,7 @@ double startTime = WTF::currentTimeMS(); Address result = lazySweepPages(allocationSize, gcInfoIndex); getThreadState()->accumulateSweepingTime(WTF::currentTimeMS() - startTime); - Heap::reportMemoryUsageForTracing(); + ThreadHeap::reportMemoryUsageForTracing(); return result; } @@ -320,13 +320,13 @@ if (pageCount % deadlineCheckInterval == 0) { if (deadlineSeconds <= monotonicallyIncreasingTime()) { // Deadline has come. - Heap::reportMemoryUsageForTracing(); + ThreadHeap::reportMemoryUsageForTracing(); return !m_firstUnsweptPage; } } pageCount++; } - Heap::reportMemoryUsageForTracing(); + ThreadHeap::reportMemoryUsageForTracing(); return true; } @@ -339,7 +339,7 @@ while (m_firstUnsweptPage) { sweepUnsweptPage(); } - Heap::reportMemoryUsageForTracing(); + ThreadHeap::reportMemoryUsageForTracing(); } NormalPageArena::NormalPageArena(ThreadState* state, int index) @@ -398,7 +398,7 @@ void NormalPageArena::allocatePage() { getThreadState()->shouldFlushHeapDoesNotContainCache(); - PageMemory* pageMemory = Heap::getFreePagePool()->takeFreePage(arenaIndex()); + PageMemory* pageMemory = ThreadHeap::getFreePagePool()->takeFreePage(arenaIndex()); if (!pageMemory) { // Allocate a memory region for blinkPagesPerRegion pages that @@ -406,7 +406,7 @@ // // [ guard os page | ... payload ... | guard os page ] // ^---{ aligned to blink page size } - PageMemoryRegion* region = PageMemoryRegion::allocateNormalPages(Heap::getRegionTree()); + PageMemoryRegion* region = PageMemoryRegion::allocateNormalPages(ThreadHeap::getRegionTree()); // Setup the PageMemory object for each of the pages in the region. for (size_t i = 0; i < blinkPagesPerRegion; ++i) { @@ -421,7 +421,7 @@ RELEASE_ASSERT(result); pageMemory = memory; } else { - Heap::getFreePagePool()->addFreePage(arenaIndex(), memory); + ThreadHeap::getFreePagePool()->addFreePage(arenaIndex(), memory); } } } @@ -429,7 +429,7 @@ NormalPage* page = new (pageMemory->writableStart()) NormalPage(pageMemory, this); page->link(&m_firstPage); - Heap::heapStats().increaseAllocatedSpace(page->size()); + ThreadHeap::heapStats().increaseAllocatedSpace(page->size()); #if ENABLE(ASSERT) || defined(LEAK_SANITIZER) || defined(ADDRESS_SANITIZER) // Allow the following addToFreeList() to add the newly allocated memory // to the free list. @@ -444,7 +444,7 @@ void NormalPageArena::freePage(NormalPage* page) { - Heap::heapStats().decreaseAllocatedSpace(page->size()); + ThreadHeap::heapStats().decreaseAllocatedSpace(page->size()); if (page->terminating()) { // The thread is shutting down and this page is being removed as a part @@ -455,11 +455,11 @@ // ensures that tracing the dangling pointer in the next global GC just // crashes instead of causing use-after-frees. After the next global // GC, the orphaned pages are removed. - Heap::getOrphanedPagePool()->addOrphanedPage(arenaIndex(), page); + ThreadHeap::getOrphanedPagePool()->addOrphanedPage(arenaIndex(), page); } else { PageMemory* memory = page->storage(); page->~NormalPage(); - Heap::getFreePagePool()->addFreePage(arenaIndex(), memory); + ThreadHeap::getFreePagePool()->addFreePage(arenaIndex(), memory); } } @@ -565,7 +565,7 @@ ASSERT(header->checkHeader()); if (header->payloadSize() >= newSize) return true; - size_t allocationSize = Heap::allocationSizeFromSize(newSize); + size_t allocationSize = ThreadHeap::allocationSizeFromSize(newSize); ASSERT(allocationSize > header->size()); size_t expandSize = allocationSize - header->size(); if (isObjectAllocatedAtAllocationPoint(header) && expandSize <= m_remainingAllocationSize) { @@ -585,7 +585,7 @@ { ASSERT(header->checkHeader()); ASSERT(header->payloadSize() > newSize); - size_t allocationSize = Heap::allocationSizeFromSize(newSize); + size_t allocationSize = ThreadHeap::allocationSizeFromSize(newSize); ASSERT(header->size() > allocationSize); size_t shrinkSize = header->size() - allocationSize; if (isObjectAllocatedAtAllocationPoint(header)) { @@ -796,7 +796,7 @@ #endif getThreadState()->shouldFlushHeapDoesNotContainCache(); - PageMemory* pageMemory = PageMemory::allocate(largeObjectSize, Heap::getRegionTree()); + PageMemory* pageMemory = PageMemory::allocate(largeObjectSize, ThreadHeap::getRegionTree()); Address largeObjectAddress = pageMemory->writableStart(); Address headerAddress = largeObjectAddress + LargeObjectPage::pageHeaderSize(); #if ENABLE(ASSERT) @@ -817,7 +817,7 @@ largeObject->link(&m_firstPage); - Heap::heapStats().increaseAllocatedSpace(largeObject->size()); + ThreadHeap::heapStats().increaseAllocatedSpace(largeObject->size()); getThreadState()->increaseAllocatedObjectSize(largeObject->size()); return result; } @@ -826,7 +826,7 @@ { ASAN_UNPOISON_MEMORY_REGION(object->payload(), object->payloadSize()); object->heapObjectHeader()->finalize(object->payload(), object->payloadSize()); - Heap::heapStats().decreaseAllocatedSpace(object->size()); + ThreadHeap::heapStats().decreaseAllocatedSpace(object->size()); // Unpoison the object header and allocationGranularity bytes after the // object before freeing. @@ -843,7 +843,7 @@ // ensures that tracing the dangling pointer in the next global GC just // crashes instead of causing use-after-frees. After the next global // GC, the orphaned pages are removed. - Heap::getOrphanedPagePool()->addOrphanedPage(arenaIndex(), object); + ThreadHeap::getOrphanedPagePool()->addOrphanedPage(arenaIndex(), object); } else { ASSERT(!ThreadState::current()->isTerminating()); PageMemory* memory = object->storage(); @@ -1318,7 +1318,7 @@ static void markPointer(Visitor* visitor, HeapObjectHeader* header) { ASSERT(header->checkHeader()); - const GCInfo* gcInfo = Heap::gcInfo(header->gcInfoIndex()); + const GCInfo* gcInfo = ThreadHeap::gcInfo(header->gcInfoIndex()); if (gcInfo->hasVTable() && !vTableInitialized(header->payload())) { // We hit this branch when a GC strikes before GarbageCollected<>'s // constructor runs.
diff --git a/third_party/WebKit/Source/platform/heap/HeapPage.h b/third_party/WebKit/Source/platform/heap/HeapPage.h index ce60de3..91dc1703 100644 --- a/third_party/WebKit/Source/platform/heap/HeapPage.h +++ b/third_party/WebKit/Source/platform/heap/HeapPage.h
@@ -85,7 +85,7 @@ const uint8_t reuseForbiddenZapValue = 0x2c; // In non-production builds, memory is zapped when it's freed. The zapped -// memory is zeroed out when the memory is reused in Heap::allocateObject(). +// memory is zeroed out when the memory is reused in ThreadHeap::allocateObject(). // In production builds, memory is not zapped (for performance). The memory // is just zeroed out when it is added to the free list. #if defined(MEMORY_SANITIZER)
diff --git a/third_party/WebKit/Source/platform/heap/HeapTerminatedArray.h b/third_party/WebKit/Source/platform/heap/HeapTerminatedArray.h index e87ba2c..ad7147a 100644 --- a/third_party/WebKit/Source/platform/heap/HeapTerminatedArray.h +++ b/third_party/WebKit/Source/platform/heap/HeapTerminatedArray.h
@@ -30,16 +30,21 @@ struct Allocator final { STATIC_ONLY(Allocator); typedef HeapTerminatedArray* PassPtr; - typedef RawPtr<HeapTerminatedArray> Ptr; + typedef HeapTerminatedArray* Ptr; + + static PassPtr release(Ptr ptr) + { + return ptr; + } static PassPtr create(size_t capacity) { - return reinterpret_cast<HeapTerminatedArray*>(Heap::allocate<HeapTerminatedArray>(capacity * sizeof(T), IsEagerlyFinalizedType<T>::value)); + return reinterpret_cast<HeapTerminatedArray*>(ThreadHeap::allocate<HeapTerminatedArray>(capacity * sizeof(T), IsEagerlyFinalizedType<T>::value)); } static PassPtr resize(PassPtr ptr, size_t capacity) { - return reinterpret_cast<HeapTerminatedArray*>(Heap::reallocate<HeapTerminatedArray>(ptr, capacity * sizeof(T))); + return reinterpret_cast<HeapTerminatedArray*>(ThreadHeap::reallocate<HeapTerminatedArray>(ptr, capacity * sizeof(T))); } };
diff --git a/third_party/WebKit/Source/platform/heap/HeapTest.cpp b/third_party/WebKit/Source/platform/heap/HeapTest.cpp index 9d11b2e..7e480912 100644 --- a/third_party/WebKit/Source/platform/heap/HeapTest.cpp +++ b/third_party/WebKit/Source/platform/heap/HeapTest.cpp
@@ -48,12 +48,12 @@ static void preciselyCollectGarbage() { - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); } static void conservativelyCollectGarbage() { - Heap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); } class IntWrapper : public GarbageCollectedFinalized<IntWrapper> { @@ -157,11 +157,11 @@ bool traceInCollection(VisitorDispatcher visitor, WTF::ShouldWeakPointersBeMarkedStrongly strongify) { visitor->traceInCollection(second, strongify); - if (!Heap::isHeapObjectAlive(second)) + if (!ThreadHeap::isHeapObjectAlive(second)) return true; // FIXME: traceInCollection is also called from WeakProcessing to check if the entry is dead. // The below if avoids calling trace in that case by only calling trace when |first| is not yet marked. - if (!Heap::isHeapObjectAlive(first)) + if (!ThreadHeap::isHeapObjectAlive(first)) visitor->trace(first); return false; } @@ -245,7 +245,7 @@ { ASSERT(m_state->checkThread()); if (LIKELY(ThreadState::stopThreads())) { - Heap::preGC(); + ThreadHeap::preGC(); m_parkedAllThreads = true; } } @@ -257,7 +257,7 @@ // Only cleanup if we parked all threads in which case the GC happened // and we need to resume the other threads. if (LIKELY(m_parkedAllThreads)) { - Heap::postGC(BlinkGC::GCWithSweep); + ThreadHeap::postGC(BlinkGC::GCWithSweep); ThreadState::resumeThreads(); } } @@ -415,9 +415,9 @@ static void clearOutOldGarbage() { while (true) { - size_t used = Heap::objectPayloadSizeForTesting(); + size_t used = ThreadHeap::objectPayloadSizeForTesting(); preciselyCollectGarbage(); - if (Heap::objectPayloadSizeForTesting() >= used) + if (ThreadHeap::objectPayloadSizeForTesting() >= used) break; } } @@ -544,7 +544,7 @@ // Taking snapshot shouldn't have any bad side effect. // TODO(haraken): This snapshot GC causes crashes, so disable // it at the moment. Fix the crash and enable it. - // Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::TakeSnapshot, BlinkGC::ForcedGC); + // ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::TakeSnapshot, BlinkGC::ForcedGC); preciselyCollectGarbage(); EXPECT_EQ(wrapper->value(), 0x0bbac0de); EXPECT_EQ((*globalPersistent)->value(), 0x0ed0cabb); @@ -599,7 +599,7 @@ // Taking snapshot shouldn't have any bad side effect. // TODO(haraken): This snapshot GC causes crashes, so disable // it at the moment. Fix the crash and enable it. - // Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::TakeSnapshot, BlinkGC::ForcedGC); + // ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::TakeSnapshot, BlinkGC::ForcedGC); preciselyCollectGarbage(); EXPECT_TRUE(weakMap->isEmpty()); EXPECT_TRUE(weakMap2.isEmpty()); @@ -720,11 +720,11 @@ DEFINE_INLINE_TRACE() { - EXPECT_TRUE(Heap::isHeapObjectAlive(this)); + EXPECT_TRUE(ThreadHeap::isHeapObjectAlive(this)); if (!traceCount()) - EXPECT_FALSE(Heap::isHeapObjectAlive(m_traceCounter)); + EXPECT_FALSE(ThreadHeap::isHeapObjectAlive(m_traceCounter)); else - EXPECT_TRUE(Heap::isHeapObjectAlive(m_traceCounter)); + EXPECT_TRUE(ThreadHeap::isHeapObjectAlive(m_traceCounter)); visitor->trace(m_traceCounter); } @@ -776,7 +776,7 @@ { ThreadState* state = ThreadState::current(); const char* typeName = WTF_HEAP_PROFILER_TYPE_NAME(IntNode); - return Heap::allocateOnArenaIndex(state, size, BlinkGC::NodeArenaIndex, GCInfoTrait<IntNode>::index(), typeName); + return ThreadHeap::allocateOnArenaIndex(state, size, BlinkGC::NodeArenaIndex, GCInfoTrait<IntNode>::index(), typeName); } static IntNode* create(int i) @@ -1100,7 +1100,7 @@ void zapWeakMembers(Visitor* visitor) { - if (!Heap::isHeapObjectAlive(m_weakBar)) + if (!ThreadHeap::isHeapObjectAlive(m_weakBar)) m_weakBar = 0; } @@ -1295,7 +1295,7 @@ void zapWeakMembers(Visitor* visitor) { - if (m_data && !Heap::isHeapObjectAlive(m_data)) { + if (m_data && !ThreadHeap::isHeapObjectAlive(m_data)) { m_data->willFinalize(); m_data = nullptr; m_didCallWillFinalize = true; @@ -1617,7 +1617,7 @@ public: static DynamicallySizedObject* create(size_t size) { - void* slot = Heap::allocate<DynamicallySizedObject>(size); + void* slot = ThreadHeap::allocate<DynamicallySizedObject>(size); return new (slot) DynamicallySizedObject(); } @@ -1763,7 +1763,7 @@ TEST(HeapTest, BasicFunctionality) { clearOutOldGarbage(); - size_t initialObjectPayloadSize = Heap::objectPayloadSizeForTesting(); + size_t initialObjectPayloadSize = ThreadHeap::objectPayloadSizeForTesting(); { size_t slack = 0; @@ -1772,7 +1772,7 @@ size_t baseLevel = initialObjectPayloadSize; bool testPagesAllocated = !baseLevel; if (testPagesAllocated) - EXPECT_EQ(Heap::heapStats().allocatedSpace(), 0ul); + EXPECT_EQ(ThreadHeap::heapStats().allocatedSpace(), 0ul); // This allocates objects on the general heap which should add a page of memory. DynamicallySizedObject* alloc32 = DynamicallySizedObject::create(32); @@ -1784,9 +1784,9 @@ size_t total = 96; - CheckWithSlack(baseLevel + total, Heap::objectPayloadSizeForTesting(), slack); + CheckWithSlack(baseLevel + total, ThreadHeap::objectPayloadSizeForTesting(), slack); if (testPagesAllocated) - EXPECT_EQ(Heap::heapStats().allocatedSpace(), blinkPageSize * 2); + EXPECT_EQ(ThreadHeap::heapStats().allocatedSpace(), blinkPageSize * 2); EXPECT_EQ(alloc32->get(0), 40); EXPECT_EQ(alloc32->get(31), 40); @@ -1804,10 +1804,10 @@ clearOutOldGarbage(); size_t total = 0; size_t slack = 0; - size_t baseLevel = Heap::objectPayloadSizeForTesting(); + size_t baseLevel = ThreadHeap::objectPayloadSizeForTesting(); bool testPagesAllocated = !baseLevel; if (testPagesAllocated) - EXPECT_EQ(Heap::heapStats().allocatedSpace(), 0ul); + EXPECT_EQ(ThreadHeap::heapStats().allocatedSpace(), 0ul); size_t big = 1008; Persistent<DynamicallySizedObject> bigArea = DynamicallySizedObject::create(big); @@ -1823,9 +1823,9 @@ total += size; persistents[persistentCount++] = new Persistent<DynamicallySizedObject>(DynamicallySizedObject::create(size)); slack += 4; - CheckWithSlack(baseLevel + total, Heap::objectPayloadSizeForTesting(), slack); + CheckWithSlack(baseLevel + total, ThreadHeap::objectPayloadSizeForTesting(), slack); if (testPagesAllocated) - EXPECT_EQ(0ul, Heap::heapStats().allocatedSpace() & (blinkPageSize - 1)); + EXPECT_EQ(0ul, ThreadHeap::heapStats().allocatedSpace() & (blinkPageSize - 1)); } { @@ -1838,16 +1838,16 @@ EXPECT_TRUE(alloc32b != alloc64b); total += 96; - CheckWithSlack(baseLevel + total, Heap::objectPayloadSizeForTesting(), slack); + CheckWithSlack(baseLevel + total, ThreadHeap::objectPayloadSizeForTesting(), slack); if (testPagesAllocated) - EXPECT_EQ(0ul, Heap::heapStats().allocatedSpace() & (blinkPageSize - 1)); + EXPECT_EQ(0ul, ThreadHeap::heapStats().allocatedSpace() & (blinkPageSize - 1)); } clearOutOldGarbage(); total -= 96; slack -= 8; if (testPagesAllocated) - EXPECT_EQ(0ul, Heap::heapStats().allocatedSpace() & (blinkPageSize - 1)); + EXPECT_EQ(0ul, ThreadHeap::heapStats().allocatedSpace() & (blinkPageSize - 1)); // Clear the persistent, so that the big area will be garbage collected. bigArea.release(); @@ -1855,42 +1855,42 @@ total -= big; slack -= 4; - CheckWithSlack(baseLevel + total, Heap::objectPayloadSizeForTesting(), slack); + CheckWithSlack(baseLevel + total, ThreadHeap::objectPayloadSizeForTesting(), slack); if (testPagesAllocated) - EXPECT_EQ(0ul, Heap::heapStats().allocatedSpace() & (blinkPageSize - 1)); + EXPECT_EQ(0ul, ThreadHeap::heapStats().allocatedSpace() & (blinkPageSize - 1)); - CheckWithSlack(baseLevel + total, Heap::objectPayloadSizeForTesting(), slack); + CheckWithSlack(baseLevel + total, ThreadHeap::objectPayloadSizeForTesting(), slack); if (testPagesAllocated) - EXPECT_EQ(0ul, Heap::heapStats().allocatedSpace() & (blinkPageSize - 1)); + EXPECT_EQ(0ul, ThreadHeap::heapStats().allocatedSpace() & (blinkPageSize - 1)); for (size_t i = 0; i < persistentCount; i++) { delete persistents[i]; persistents[i] = 0; } - uint8_t* address = reinterpret_cast<uint8_t*>(Heap::allocate<DynamicallySizedObject>(100)); + uint8_t* address = reinterpret_cast<uint8_t*>(ThreadHeap::allocate<DynamicallySizedObject>(100)); for (int i = 0; i < 100; i++) address[i] = i; - address = reinterpret_cast<uint8_t*>(Heap::reallocate<DynamicallySizedObject>(address, 100000)); + address = reinterpret_cast<uint8_t*>(ThreadHeap::reallocate<DynamicallySizedObject>(address, 100000)); for (int i = 0; i < 100; i++) EXPECT_EQ(address[i], i); - address = reinterpret_cast<uint8_t*>(Heap::reallocate<DynamicallySizedObject>(address, 50)); + address = reinterpret_cast<uint8_t*>(ThreadHeap::reallocate<DynamicallySizedObject>(address, 50)); for (int i = 0; i < 50; i++) EXPECT_EQ(address[i], i); // This should be equivalent to free(address). - EXPECT_EQ(reinterpret_cast<uintptr_t>(Heap::reallocate<DynamicallySizedObject>(address, 0)), 0ul); + EXPECT_EQ(reinterpret_cast<uintptr_t>(ThreadHeap::reallocate<DynamicallySizedObject>(address, 0)), 0ul); // This should be equivalent to malloc(0). - EXPECT_EQ(reinterpret_cast<uintptr_t>(Heap::reallocate<DynamicallySizedObject>(0, 0)), 0ul); + EXPECT_EQ(reinterpret_cast<uintptr_t>(ThreadHeap::reallocate<DynamicallySizedObject>(0, 0)), 0ul); } TEST(HeapTest, SimpleAllocation) { clearOutOldGarbage(); - EXPECT_EQ(0ul, Heap::objectPayloadSizeForTesting()); + EXPECT_EQ(0ul, ThreadHeap::objectPayloadSizeForTesting()); // Allocate an object in the heap. HeapAllocatedArray* array = new HeapAllocatedArray(); - EXPECT_TRUE(Heap::objectPayloadSizeForTesting() >= sizeof(HeapAllocatedArray)); + EXPECT_TRUE(ThreadHeap::objectPayloadSizeForTesting() >= sizeof(HeapAllocatedArray)); // Sanity check of the contents in the heap. EXPECT_EQ(0, array->at(0)); @@ -1967,7 +1967,7 @@ EXPECT_EQ(0, SimpleFinalizedObject::s_destructorCalls); for (int i = 0; i < 1000; i++) SimpleFinalizedObject::create(); - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::ForcedGC); EXPECT_EQ(0, SimpleFinalizedObject::s_destructorCalls); for (int i = 0; i < 10000; i++) SimpleFinalizedObject::create(); @@ -1994,7 +1994,7 @@ EXPECT_EQ(0, LargeHeapObject::s_destructorCalls); for (int i = 0; i < 10; i++) LargeHeapObject::create(); - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::ForcedGC); EXPECT_EQ(0, LargeHeapObject::s_destructorCalls); for (int i = 0; i < 10; i++) { LargeHeapObject::create(); @@ -2003,7 +2003,7 @@ LargeHeapObject::create(); LargeHeapObject::create(); EXPECT_EQ(10, LargeHeapObject::s_destructorCalls); - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::ForcedGC); EXPECT_EQ(10, LargeHeapObject::s_destructorCalls); preciselyCollectGarbage(); EXPECT_EQ(22, LargeHeapObject::s_destructorCalls); @@ -2078,7 +2078,7 @@ SimpleFinalizedEagerObject::create(); for (int i = 0; i < 100; i++) SimpleFinalizedObjectInstanceOfTemplate::create(); - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::ForcedGC); EXPECT_EQ(0, SimpleFinalizedObject::s_destructorCalls); EXPECT_EQ(100, SimpleFinalizedEagerObject::s_destructorCalls); EXPECT_EQ(100, SimpleFinalizedObjectInstanceOfTemplate::s_destructorCalls); @@ -2221,7 +2221,7 @@ IntWrapper::s_destructorCalls = 0; clearOutOldGarbage(); - size_t initialObjectPayloadSize = Heap::objectPayloadSizeForTesting(); + size_t initialObjectPayloadSize = ThreadHeap::objectPayloadSizeForTesting(); { typedef HeapHashMap< Member<IntWrapper>, @@ -2233,11 +2233,11 @@ Persistent<HeapObjectIdentityMap> map = new HeapObjectIdentityMap(); map->clear(); - size_t afterSetWasCreated = Heap::objectPayloadSizeForTesting(); + size_t afterSetWasCreated = ThreadHeap::objectPayloadSizeForTesting(); EXPECT_TRUE(afterSetWasCreated > initialObjectPayloadSize); preciselyCollectGarbage(); - size_t afterGC = Heap::objectPayloadSizeForTesting(); + size_t afterGC = ThreadHeap::objectPayloadSizeForTesting(); EXPECT_EQ(afterGC, afterSetWasCreated); // If the additions below cause garbage collections, these @@ -2247,7 +2247,7 @@ map->add(one, one); - size_t afterOneAdd = Heap::objectPayloadSizeForTesting(); + size_t afterOneAdd = ThreadHeap::objectPayloadSizeForTesting(); EXPECT_TRUE(afterOneAdd > afterGC); HeapObjectIdentityMap::iterator it(map->begin()); @@ -2264,7 +2264,7 @@ // stack scanning as that could find a pointer to the // old backing. preciselyCollectGarbage(); - size_t afterAddAndGC = Heap::objectPayloadSizeForTesting(); + size_t afterAddAndGC = ThreadHeap::objectPayloadSizeForTesting(); EXPECT_TRUE(afterAddAndGC >= afterOneAdd); EXPECT_EQ(map->size(), 2u); // Two different wrappings of '1' are distinct. @@ -2277,7 +2277,7 @@ EXPECT_EQ(gotten->value(), one->value()); EXPECT_EQ(gotten, one); - size_t afterGC2 = Heap::objectPayloadSizeForTesting(); + size_t afterGC2 = ThreadHeap::objectPayloadSizeForTesting(); EXPECT_EQ(afterGC2, afterAddAndGC); IntWrapper* dozen = 0; @@ -2289,7 +2289,7 @@ if (i == 12) dozen = iWrapper; } - size_t afterAdding1000 = Heap::objectPayloadSizeForTesting(); + size_t afterAdding1000 = ThreadHeap::objectPayloadSizeForTesting(); EXPECT_TRUE(afterAdding1000 > afterGC2); IntWrapper* gross(map->get(dozen)); @@ -2297,34 +2297,34 @@ // This should clear out any junk backings created by all the adds. preciselyCollectGarbage(); - size_t afterGC3 = Heap::objectPayloadSizeForTesting(); + size_t afterGC3 = ThreadHeap::objectPayloadSizeForTesting(); EXPECT_TRUE(afterGC3 <= afterAdding1000); } preciselyCollectGarbage(); // The objects 'one', anotherOne, and the 999 other pairs. EXPECT_EQ(IntWrapper::s_destructorCalls, 2000); - size_t afterGC4 = Heap::objectPayloadSizeForTesting(); + size_t afterGC4 = ThreadHeap::objectPayloadSizeForTesting(); EXPECT_EQ(afterGC4, initialObjectPayloadSize); } TEST(HeapTest, NestedAllocation) { clearOutOldGarbage(); - size_t initialObjectPayloadSize = Heap::objectPayloadSizeForTesting(); + size_t initialObjectPayloadSize = ThreadHeap::objectPayloadSizeForTesting(); { Persistent<ConstructorAllocation> constructorAllocation = ConstructorAllocation::create(); } clearOutOldGarbage(); - size_t afterFree = Heap::objectPayloadSizeForTesting(); + size_t afterFree = ThreadHeap::objectPayloadSizeForTesting(); EXPECT_TRUE(initialObjectPayloadSize == afterFree); } TEST(HeapTest, LargeHeapObjects) { clearOutOldGarbage(); - size_t initialObjectPayloadSize = Heap::objectPayloadSizeForTesting(); - size_t initialAllocatedSpace = Heap::heapStats().allocatedSpace(); + size_t initialObjectPayloadSize = ThreadHeap::objectPayloadSizeForTesting(); + size_t initialAllocatedSpace = ThreadHeap::heapStats().allocatedSpace(); IntWrapper::s_destructorCalls = 0; LargeHeapObject::s_destructorCalls = 0; { @@ -2333,15 +2333,15 @@ ASSERT(ThreadState::current()->findPageFromAddress(object)); ASSERT(ThreadState::current()->findPageFromAddress(reinterpret_cast<char*>(object.get()) + sizeof(LargeHeapObject) - 1)); clearOutOldGarbage(); - size_t afterAllocation = Heap::heapStats().allocatedSpace(); + size_t afterAllocation = ThreadHeap::heapStats().allocatedSpace(); { object->set(0, 'a'); EXPECT_EQ('a', object->get(0)); object->set(object->length() - 1, 'b'); EXPECT_EQ('b', object->get(object->length() - 1)); - size_t expectedLargeHeapObjectPayloadSize = Heap::allocationSizeFromSize(sizeof(LargeHeapObject)); + size_t expectedLargeHeapObjectPayloadSize = ThreadHeap::allocationSizeFromSize(sizeof(LargeHeapObject)); size_t expectedObjectPayloadSize = expectedLargeHeapObjectPayloadSize + sizeof(IntWrapper); - size_t actualObjectPayloadSize = Heap::objectPayloadSizeForTesting() - initialObjectPayloadSize; + size_t actualObjectPayloadSize = ThreadHeap::objectPayloadSizeForTesting() - initialObjectPayloadSize; CheckWithSlack(expectedObjectPayloadSize, actualObjectPayloadSize, slack); // There is probably space for the IntWrapper in a heap page without // allocating extra pages. However, the IntWrapper allocation might cause @@ -2357,13 +2357,13 @@ object = LargeHeapObject::create(); } clearOutOldGarbage(); - EXPECT_TRUE(Heap::heapStats().allocatedSpace() == afterAllocation); + EXPECT_TRUE(ThreadHeap::heapStats().allocatedSpace() == afterAllocation); EXPECT_EQ(10, IntWrapper::s_destructorCalls); EXPECT_EQ(10, LargeHeapObject::s_destructorCalls); } clearOutOldGarbage(); - EXPECT_TRUE(initialObjectPayloadSize == Heap::objectPayloadSizeForTesting()); - EXPECT_TRUE(initialAllocatedSpace == Heap::heapStats().allocatedSpace()); + EXPECT_TRUE(initialObjectPayloadSize == ThreadHeap::objectPayloadSizeForTesting()); + EXPECT_TRUE(initialAllocatedSpace == ThreadHeap::heapStats().allocatedSpace()); EXPECT_EQ(11, IntWrapper::s_destructorCalls); EXPECT_EQ(11, LargeHeapObject::s_destructorCalls); preciselyCollectGarbage(); @@ -3779,15 +3779,15 @@ TestGCScope scope(BlinkGC::HeapPointersOnStack); CountingVisitor visitor(ThreadState::current()); EXPECT_TRUE(scope.allThreadsParked()); // Fail the test if we could not park all threads. - Heap::flushHeapDoesNotContainCache(); + ThreadHeap::flushHeapDoesNotContainCache(); for (size_t i = 0; i < objectAddresses.size(); i++) { - EXPECT_TRUE(Heap::checkAndMarkPointer(&visitor, objectAddresses[i])); - EXPECT_TRUE(Heap::checkAndMarkPointer(&visitor, endAddresses[i])); + EXPECT_TRUE(ThreadHeap::checkAndMarkPointer(&visitor, objectAddresses[i])); + EXPECT_TRUE(ThreadHeap::checkAndMarkPointer(&visitor, endAddresses[i])); } EXPECT_EQ(objectAddresses.size() * 2, visitor.count()); visitor.reset(); - EXPECT_TRUE(Heap::checkAndMarkPointer(&visitor, largeObjectAddress)); - EXPECT_TRUE(Heap::checkAndMarkPointer(&visitor, largeObjectEndAddress)); + EXPECT_TRUE(ThreadHeap::checkAndMarkPointer(&visitor, largeObjectAddress)); + EXPECT_TRUE(ThreadHeap::checkAndMarkPointer(&visitor, largeObjectEndAddress)); EXPECT_EQ(2ul, visitor.count()); visitor.reset(); } @@ -3799,7 +3799,7 @@ TestGCScope scope(BlinkGC::HeapPointersOnStack); CountingVisitor visitor(ThreadState::current()); EXPECT_TRUE(scope.allThreadsParked()); - Heap::flushHeapDoesNotContainCache(); + ThreadHeap::flushHeapDoesNotContainCache(); for (size_t i = 0; i < objectAddresses.size(); i++) { // We would like to assert that checkAndMarkPointer returned false // here because the pointers no longer point into a valid object @@ -3808,12 +3808,12 @@ // whether it points at a valid object (this ensures the // correctness of the page-based on-heap address caches), so we // can't make that assert. - Heap::checkAndMarkPointer(&visitor, objectAddresses[i]); - Heap::checkAndMarkPointer(&visitor, endAddresses[i]); + ThreadHeap::checkAndMarkPointer(&visitor, objectAddresses[i]); + ThreadHeap::checkAndMarkPointer(&visitor, endAddresses[i]); } EXPECT_EQ(0ul, visitor.count()); - Heap::checkAndMarkPointer(&visitor, largeObjectAddress); - Heap::checkAndMarkPointer(&visitor, largeObjectEndAddress); + ThreadHeap::checkAndMarkPointer(&visitor, largeObjectAddress); + ThreadHeap::checkAndMarkPointer(&visitor, largeObjectEndAddress); EXPECT_EQ(0ul, visitor.count()); } // This round of GC is important to make sure that the object start @@ -4314,13 +4314,6 @@ } } -TEST(HeapTest, RawPtrInHash) -{ - rawPtrInHashHelper<HashSet<RawPtr<int>>>(); - rawPtrInHashHelper<ListHashSet<RawPtr<int>>>(); - rawPtrInHashHelper<LinkedHashSet<RawPtr<int>>>(); -} - TEST(HeapTest, HeapTerminatedArray) { clearOutOldGarbage(); @@ -4982,17 +4975,12 @@ TEST(HeapTest, Bind) { OwnPtr<SameThreadClosure> closure = bind(static_cast<void (Bar::*)(Visitor*)>(&Bar::trace), Bar::create(), static_cast<Visitor*>(0)); + // OffHeapInt* should not make Persistent. + OwnPtr<SameThreadClosure> closure2 = bind(&OffHeapInt::voidFunction, OffHeapInt::create(1)); preciselyCollectGarbage(); // The closure should have a persistent handle to the Bar. EXPECT_EQ(1u, Bar::s_live); - OwnPtr<SameThreadClosure> closure2 = bind(static_cast<void (Bar::*)(Visitor*)>(&Bar::trace), RawPtr<Bar>(Bar::create()), static_cast<Visitor*>(0)); - preciselyCollectGarbage(); - // The closure should have a persistent handle to the Bar. - EXPECT_EQ(2u, Bar::s_live); - // RawPtr<OffHeapInt> should not make Persistent. - OwnPtr<SameThreadClosure> closure3 = bind(&OffHeapInt::voidFunction, RawPtr<OffHeapInt>(OffHeapInt::create(1).get())); - UseMixin::s_traceCount = 0; Mixin* mixin = UseMixin::create(); OwnPtr<SameThreadClosure> mixinClosure = bind(static_cast<void (Mixin::*)(Visitor*)>(&Mixin::trace), mixin, static_cast<Visitor*>(0)); @@ -5012,7 +5000,7 @@ bool liveEntriesFound = false; WeakSet::iterator end = set.end(); for (WeakSet::iterator it = set.begin(); it != end; ++it) { - if (Heap::isHeapObjectAlive(*it)) { + if (ThreadHeap::isHeapObjectAlive(*it)) { liveEntriesFound = true; break; } @@ -5940,7 +5928,7 @@ { AllocInSuperConstructorArgument* object = new AllocInSuperConstructorArgument(); EXPECT_TRUE(object); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); } class NonNodeAllocatingNodeInDestructor : public GarbageCollectedFinalized<NonNodeAllocatingNodeInDestructor> { @@ -5978,7 +5966,6 @@ static_assert(TraceEagerlyTrait<TraceTypeEagerly1>::value, "should be true"); static_assert(TraceEagerlyTrait<Member<TraceTypeEagerly1>>::value, "should be true"); static_assert(TraceEagerlyTrait<WeakMember<TraceTypeEagerly1>>::value, "should be true"); - static_assert(TraceEagerlyTrait<RawPtr<TraceTypeEagerly1>>::value, "should be true"); static_assert(TraceEagerlyTrait<HeapVector<Member<TraceTypeEagerly1>>>::value, "should be true"); static_assert(TraceEagerlyTrait<HeapVector<WeakMember<TraceTypeEagerly1>>>::value, "should be true"); static_assert(TraceEagerlyTrait<HeapHashSet<Member<TraceTypeEagerly1>>>::value, "should be true"); @@ -6392,7 +6379,7 @@ parkWorkerThread(); // Step 4: Run a GC. - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); wakeMainThread(); parkWorkerThread();
diff --git a/third_party/WebKit/Source/platform/heap/MarkingVisitorImpl.h b/third_party/WebKit/Source/platform/heap/MarkingVisitorImpl.h index cc320a7..76c5519 100644 --- a/third_party/WebKit/Source/platform/heap/MarkingVisitorImpl.h +++ b/third_party/WebKit/Source/platform/heap/MarkingVisitorImpl.h
@@ -44,7 +44,7 @@ header->mark(); if (callback) - Heap::pushTraceCallback(const_cast<void*>(objectPointer), callback); + ThreadHeap::pushTraceCallback(const_cast<void*>(objectPointer), callback); } inline void mark(const void* objectPointer, TraceCallback callback) @@ -58,7 +58,7 @@ inline void registerDelayedMarkNoTracing(const void* objectPointer) { ASSERT(toDerived()->getMarkingMode() != Visitor::WeakProcessing); - Heap::pushPostMarkingCallback(const_cast<void*>(objectPointer), &markNoTracingCallback); + ThreadHeap::pushPostMarkingCallback(const_cast<void*>(objectPointer), &markNoTracingCallback); } inline void registerWeakMembers(const void* closure, const void* objectPointer, WeakCallback callback) @@ -67,19 +67,19 @@ // We don't want to run weak processings when taking a snapshot. if (toDerived()->getMarkingMode() == Visitor::SnapshotMarking) return; - Heap::pushThreadLocalWeakCallback(const_cast<void*>(closure), const_cast<void*>(objectPointer), callback); + ThreadHeap::pushThreadLocalWeakCallback(const_cast<void*>(closure), const_cast<void*>(objectPointer), callback); } inline void registerWeakTable(const void* closure, EphemeronCallback iterationCallback, EphemeronCallback iterationDoneCallback) { ASSERT(toDerived()->getMarkingMode() != Visitor::WeakProcessing); - Heap::registerWeakTable(const_cast<void*>(closure), iterationCallback, iterationDoneCallback); + ThreadHeap::registerWeakTable(const_cast<void*>(closure), iterationCallback, iterationDoneCallback); } #if ENABLE(ASSERT) inline bool weakTableRegistered(const void* closure) { - return Heap::weakTableRegistered(closure); + return ThreadHeap::weakTableRegistered(closure); } #endif @@ -117,7 +117,7 @@ // We don't want to run weak processings when taking a snapshot. if (toDerived()->getMarkingMode() == Visitor::SnapshotMarking) return; - Heap::pushGlobalWeakCallback(cell, callback); + ThreadHeap::pushGlobalWeakCallback(cell, callback); } private:
diff --git a/third_party/WebKit/Source/platform/heap/PagePool.cpp b/third_party/WebKit/Source/platform/heap/PagePool.cpp index acb5fa3..da9e3fb 100644 --- a/third_party/WebKit/Source/platform/heap/PagePool.cpp +++ b/third_party/WebKit/Source/platform/heap/PagePool.cpp
@@ -101,7 +101,7 @@ } else { page->~BasePage(); clearMemory(memory); - Heap::getFreePagePool()->addFreePage(index, memory); + ThreadHeap::getFreePagePool()->addFreePage(index, memory); } PoolEntry* deadEntry = entry;
diff --git a/third_party/WebKit/Source/platform/heap/RunAllTests.cpp b/third_party/WebKit/Source/platform/heap/RunAllTests.cpp index 210fc2a..3fceabe 100644 --- a/third_party/WebKit/Source/platform/heap/RunAllTests.cpp +++ b/third_party/WebKit/Source/platform/heap/RunAllTests.cpp
@@ -54,7 +54,7 @@ BlinkTestEnvironmentScope blinkTestEnvironment; blink::ThreadState::current()->registerTraceDOMWrappers(0, 0); int result = testSuite->Run(); - blink::Heap::collectAllGarbage(); + blink::ThreadHeap::collectAllGarbage(); return result; }
diff --git a/third_party/WebKit/Source/platform/heap/ThreadState.cpp b/third_party/WebKit/Source/platform/heap/ThreadState.cpp index 873baa3..6d2f295 100644 --- a/third_party/WebKit/Source/platform/heap/ThreadState.cpp +++ b/third_party/WebKit/Source/platform/heap/ThreadState.cpp
@@ -222,7 +222,7 @@ // not scanned by LSan due to being held in non-global storage // ("static" references inside functions/methods.) releaseStaticPersistentNodes(); - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); #endif // Finish sweeping before shutting down V8. Otherwise, some destructor @@ -305,7 +305,7 @@ int currentCount = getPersistentRegion()->numberOfPersistents(); ASSERT(currentCount >= 0); while (currentCount != oldCount) { - Heap::collectGarbageForTerminatingThread(this); + ThreadHeap::collectGarbageForTerminatingThread(this); oldCount = currentCount; currentCount = getPersistentRegion()->numberOfPersistents(); } @@ -371,7 +371,7 @@ // within the stack range that we need to scan so we need // to visit the values in the fake frame. for (Address* p = fakeFrameStart; p < fakeFrameEnd; ++p) - Heap::checkAndMarkPointer(visitor, *p); + ThreadHeap::checkAndMarkPointer(visitor, *p); } } #endif @@ -407,7 +407,7 @@ // variable because we don't want to unpoison the original stack. __msan_unpoison(&ptr, sizeof(ptr)); #endif - Heap::checkAndMarkPointer(visitor, ptr); + ThreadHeap::checkAndMarkPointer(visitor, ptr); visitAsanFakeStackForPointer(visitor, ptr); } @@ -416,7 +416,7 @@ // See the comment above. __msan_unpoison(&ptr, sizeof(ptr)); #endif - Heap::checkAndMarkPointer(visitor, ptr); + ThreadHeap::checkAndMarkPointer(visitor, ptr); visitAsanFakeStackForPointer(visitor, ptr); } } @@ -451,7 +451,7 @@ // pages are not traced and thus objects on those pages are never be // registered as objects on orphaned pages. We cannot assert this here since // we might have an off-heap collection. We assert it in - // Heap::pushThreadLocalWeakCallback. + // ThreadHeap::pushThreadLocalWeakCallback. if (CallbackStack::Item* item = m_threadLocalWeakCallbackStack->pop()) { // Note that the thread-local weak processing can be called for // an already dead object (for which isHeapObjectAlive(object) can @@ -517,18 +517,18 @@ size_t ThreadState::totalMemorySize() { - return Heap::heapStats().allocatedObjectSize() + Heap::heapStats().markedObjectSize() + WTF::Partitions::totalSizeOfCommittedPages(); + return ThreadHeap::heapStats().allocatedObjectSize() + ThreadHeap::heapStats().markedObjectSize() + WTF::Partitions::totalSizeOfCommittedPages(); } size_t ThreadState::estimatedLiveSize(size_t estimationBaseSize, size_t sizeAtLastGC) { - if (Heap::heapStats().wrapperCountAtLastGC() == 0) { + if (ThreadHeap::heapStats().wrapperCountAtLastGC() == 0) { // We'll reach here only before hitting the first GC. return 0; } // (estimated size) = (estimation base size) - (heap size at the last GC) / (# of persistent handles at the last GC) * (# of persistent handles collected since the last GC); - size_t sizeRetainedByCollectedPersistents = static_cast<size_t>(1.0 * sizeAtLastGC / Heap::heapStats().wrapperCountAtLastGC() * Heap::heapStats().collectedWrapperCount()); + size_t sizeRetainedByCollectedPersistents = static_cast<size_t>(1.0 * sizeAtLastGC / ThreadHeap::heapStats().wrapperCountAtLastGC() * ThreadHeap::heapStats().collectedWrapperCount()); if (estimationBaseSize < sizeRetainedByCollectedPersistents) return 0; return estimationBaseSize - sizeRetainedByCollectedPersistents; @@ -536,8 +536,8 @@ double ThreadState::heapGrowingRate() { - size_t currentSize = Heap::heapStats().allocatedObjectSize() + Heap::heapStats().markedObjectSize(); - size_t estimatedSize = estimatedLiveSize(Heap::heapStats().markedObjectSizeAtLastCompleteSweep(), Heap::heapStats().markedObjectSizeAtLastCompleteSweep()); + size_t currentSize = ThreadHeap::heapStats().allocatedObjectSize() + ThreadHeap::heapStats().markedObjectSize(); + size_t estimatedSize = estimatedLiveSize(ThreadHeap::heapStats().markedObjectSizeAtLastCompleteSweep(), ThreadHeap::heapStats().markedObjectSizeAtLastCompleteSweep()); // If the estimatedSize is 0, we set a high growing rate to trigger a GC. double growingRate = estimatedSize > 0 ? 1.0 * currentSize / estimatedSize : 100; @@ -549,7 +549,7 @@ double ThreadState::partitionAllocGrowingRate() { size_t currentSize = WTF::Partitions::totalSizeOfCommittedPages(); - size_t estimatedSize = estimatedLiveSize(currentSize, Heap::heapStats().partitionAllocSizeAtLastGC()); + size_t estimatedSize = estimatedLiveSize(currentSize, ThreadHeap::heapStats().partitionAllocSizeAtLastGC()); // If the estimatedSize is 0, we set a high growing rate to trigger a GC. double growingRate = estimatedSize > 0 ? 1.0 * currentSize / estimatedSize : 100; @@ -563,7 +563,7 @@ bool ThreadState::judgeGCThreshold(size_t totalMemorySizeThreshold, double heapGrowingRateThreshold) { // If the allocated object size or the total memory size is small, don't trigger a GC. - if (Heap::heapStats().allocatedObjectSize() < 100 * 1024 || totalMemorySize() < totalMemorySizeThreshold) + if (ThreadHeap::heapStats().allocatedObjectSize() < 100 * 1024 || totalMemorySize() < totalMemorySizeThreshold) return false; // If the growing rate of Oilpan's heap or PartitionAlloc is high enough, // trigger a GC. @@ -611,7 +611,7 @@ void ThreadState::scheduleV8FollowupGCIfNeeded(BlinkGC::V8GCType gcType) { ASSERT(checkThread()); - Heap::reportMemoryUsageForTracing(); + ThreadHeap::reportMemoryUsageForTracing(); #if PRINT_HEAP_STATS dataLogF("ThreadState::scheduleV8FollowupGCIfNeeded (gcType=%s)\n", gcType == BlinkGC::V8MajorGC ? "MajorGC" : "MinorGC"); @@ -659,7 +659,7 @@ void ThreadState::schedulePageNavigationGCIfNeeded(float estimatedRemovalRatio) { ASSERT(checkThread()); - Heap::reportMemoryUsageForTracing(); + ThreadHeap::reportMemoryUsageForTracing(); #if PRINT_HEAP_STATS dataLogF("ThreadState::schedulePageNavigationGCIfNeeded (estimatedRemovalRatio=%.2lf)\n", estimatedRemovalRatio); @@ -679,7 +679,7 @@ #if PRINT_HEAP_STATS dataLogF("Scheduled MemoryPressureGC\n"); #endif - Heap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::MemoryPressureGC); + ThreadHeap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::MemoryPressureGC); return; } if (shouldSchedulePageNavigationGC(estimatedRemovalRatio)) { @@ -700,7 +700,7 @@ void ThreadState::scheduleGCIfNeeded() { ASSERT(checkThread()); - Heap::reportMemoryUsageForTracing(); + ThreadHeap::reportMemoryUsageForTracing(); #if PRINT_HEAP_STATS dataLogF("ThreadState::scheduleGCIfNeeded\n"); @@ -723,7 +723,7 @@ #if PRINT_HEAP_STATS dataLogF("Scheduled MemoryPressureGC\n"); #endif - Heap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::MemoryPressureGC); + ThreadHeap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::MemoryPressureGC); return; } } @@ -734,7 +734,7 @@ #if PRINT_HEAP_STATS dataLogF("Scheduled ConservativeGC\n"); #endif - Heap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::ConservativeGC); + ThreadHeap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::ConservativeGC); return; } } @@ -757,15 +757,15 @@ return; double idleDeltaInSeconds = deadlineSeconds - monotonicallyIncreasingTime(); - TRACE_EVENT2("blink_gc", "ThreadState::performIdleGC", "idleDeltaInSeconds", idleDeltaInSeconds, "estimatedMarkingTime", Heap::heapStats().estimatedMarkingTime()); - if (idleDeltaInSeconds <= Heap::heapStats().estimatedMarkingTime() && !Platform::current()->currentThread()->scheduler()->canExceedIdleDeadlineIfRequired()) { + TRACE_EVENT2("blink_gc", "ThreadState::performIdleGC", "idleDeltaInSeconds", idleDeltaInSeconds, "estimatedMarkingTime", ThreadHeap::heapStats().estimatedMarkingTime()); + if (idleDeltaInSeconds <= ThreadHeap::heapStats().estimatedMarkingTime() && !Platform::current()->currentThread()->scheduler()->canExceedIdleDeadlineIfRequired()) { // If marking is estimated to take longer than the deadline and we can't // exceed the deadline, then reschedule for the next idle period. scheduleIdleGC(); return; } - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::IdleGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::IdleGC); } void ThreadState::performIdleLazySweep(double deadlineSeconds) @@ -941,13 +941,13 @@ switch (gcState()) { case FullGCScheduled: - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); break; case PreciseGCScheduled: - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::PreciseGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithoutSweep, BlinkGC::PreciseGC); break; case PageNavigationGCScheduled: - Heap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::PageNavigationGC); + ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::PageNavigationGC); break; case IdleGCScheduled: // Idle time GC will be scheduled by Blink Scheduler. @@ -960,7 +960,7 @@ void ThreadState::flushHeapDoesNotContainCacheIfNeeded() { if (m_shouldFlushHeapDoesNotContainCache) { - Heap::flushHeapDoesNotContainCache(); + ThreadHeap::flushHeapDoesNotContainCache(); m_shouldFlushHeapDoesNotContainCache = false; } } @@ -1123,26 +1123,26 @@ void ThreadState::postSweep() { ASSERT(checkThread()); - Heap::reportMemoryUsageForTracing(); + ThreadHeap::reportMemoryUsageForTracing(); if (isMainThread()) { double collectionRate = 0; - if (Heap::heapStats().objectSizeAtLastGC() > 0) - collectionRate = 1 - 1.0 * Heap::heapStats().markedObjectSize() / Heap::heapStats().objectSizeAtLastGC(); + if (ThreadHeap::heapStats().objectSizeAtLastGC() > 0) + collectionRate = 1 - 1.0 * ThreadHeap::heapStats().markedObjectSize() / ThreadHeap::heapStats().objectSizeAtLastGC(); TRACE_COUNTER1(TRACE_DISABLED_BY_DEFAULT("blink_gc"), "ThreadState::collectionRate", static_cast<int>(100 * collectionRate)); #if PRINT_HEAP_STATS dataLogF("ThreadState::postSweep (collectionRate=%d%%)\n", static_cast<int>(100 * collectionRate)); #endif - // Heap::markedObjectSize() may be underestimated here if any other + // ThreadHeap::markedObjectSize() may be underestimated here if any other // thread has not yet finished lazy sweeping. - Heap::heapStats().setMarkedObjectSizeAtLastCompleteSweep(Heap::heapStats().markedObjectSize()); + ThreadHeap::heapStats().setMarkedObjectSizeAtLastCompleteSweep(ThreadHeap::heapStats().markedObjectSize()); DEFINE_STATIC_LOCAL(CustomCountHistogram, objectSizeBeforeGCHistogram, ("BlinkGC.ObjectSizeBeforeGC", 1, 4 * 1024 * 1024, 50)); - objectSizeBeforeGCHistogram.count(Heap::heapStats().objectSizeAtLastGC() / 1024); + objectSizeBeforeGCHistogram.count(ThreadHeap::heapStats().objectSizeAtLastGC() / 1024); DEFINE_STATIC_LOCAL(CustomCountHistogram, objectSizeAfterGCHistogram, ("BlinkGC.ObjectSizeAfterGC", 1, 4 * 1024 * 1024, 50)); - objectSizeAfterGCHistogram.count(Heap::heapStats().markedObjectSize() / 1024); + objectSizeAfterGCHistogram.count(ThreadHeap::heapStats().markedObjectSize() / 1024); DEFINE_STATIC_LOCAL(CustomCountHistogram, collectionRateHistogram, ("BlinkGC.CollectionRate", 1, 100, 20)); collectionRateHistogram.count(static_cast<int>(100 * collectionRate)); DEFINE_STATIC_LOCAL(CustomCountHistogram, timeForSweepHistogram, ("BlinkGC.TimeForSweepingAllObjects", 1, 10 * 1000, 50)); @@ -1157,7 +1157,7 @@ break; \ } - switch (Heap::lastGCReason()) { + switch (ThreadHeap::lastGCReason()) { COUNT_COLLECTION_RATE_HISTOGRAM_BY_GC_REASON(IdleGC) COUNT_COLLECTION_RATE_HISTOGRAM_BY_GC_REASON(PreciseGC) COUNT_COLLECTION_RATE_HISTOGRAM_BY_GC_REASON(ConservativeGC) @@ -1224,7 +1224,7 @@ void ThreadState::safePoint(BlinkGC::StackState stackState) { ASSERT(checkThread()); - Heap::reportMemoryUsageForTracing(); + ThreadHeap::reportMemoryUsageForTracing(); runScheduledGC(stackState); ASSERT(!m_atSafePoint); @@ -1308,19 +1308,19 @@ void ThreadState::increaseAllocatedObjectSize(size_t delta) { m_allocatedObjectSize += delta; - Heap::heapStats().increaseAllocatedObjectSize(delta); + ThreadHeap::heapStats().increaseAllocatedObjectSize(delta); } void ThreadState::decreaseAllocatedObjectSize(size_t delta) { m_allocatedObjectSize -= delta; - Heap::heapStats().decreaseAllocatedObjectSize(delta); + ThreadHeap::heapStats().decreaseAllocatedObjectSize(delta); } void ThreadState::increaseMarkedObjectSize(size_t delta) { m_markedObjectSize += delta; - Heap::heapStats().increaseMarkedObjectSize(delta); + ThreadHeap::heapStats().increaseMarkedObjectSize(delta); } void ThreadState::copyStackUntilSafePointScope()
diff --git a/third_party/WebKit/Source/platform/heap/ThreadState.h b/third_party/WebKit/Source/platform/heap/ThreadState.h index 6d3bd0a..82c0691 100644 --- a/third_party/WebKit/Source/platform/heap/ThreadState.h +++ b/third_party/WebKit/Source/platform/heap/ThreadState.h
@@ -92,7 +92,7 @@ // public: // Foo() // { -// ThreadState::current()->registerPreFinalizer(dispose); +// ThreadState::current()->registerPreFinalizer(this); // } // private: // void dispose() @@ -106,7 +106,7 @@ static bool invokePreFinalizer(void* object) \ { \ Class* self = reinterpret_cast<Class*>(object); \ - if (Heap::isHeapObjectAlive(self)) \ + if (ThreadHeap::isHeapObjectAlive(self)) \ return false; \ self->Class::preFinalizer(); \ return true; \ @@ -255,7 +255,7 @@ // // 1) All threads park at safe points. // 2) The GCing thread calls preGC() for all ThreadStates. - // 3) The GCing thread calls Heap::collectGarbage(). + // 3) The GCing thread calls ThreadHeap::collectGarbage(). // This does marking but doesn't do sweeping. // 4) The GCing thread calls postGC() for all ThreadStates. // 5) The GCing thread resume all threads.
diff --git a/third_party/WebKit/Source/platform/heap/TraceTraits.h b/third_party/WebKit/Source/platform/heap/TraceTraits.h index cd672c4..acef177 100644 --- a/third_party/WebKit/Source/platform/heap/TraceTraits.h +++ b/third_party/WebKit/Source/platform/heap/TraceTraits.h
@@ -339,13 +339,12 @@ template <typename T> struct RemoveHeapPointerWrapperTypes { STATIC_ONLY(RemoveHeapPointerWrapperTypes); - using Type = typename WTF::RemoveTemplate<typename WTF::RemoveTemplate<typename WTF::RemoveTemplate<T, Member>::Type, WeakMember>::Type, RawPtr>::Type; + using Type = typename WTF::RemoveTemplate<typename WTF::RemoveTemplate<T, Member>::Type, WeakMember>::Type; }; // FIXME: Oilpan: TraceIfNeeded should be implemented ala: // NeedsTracing<T>::value || IsWeakMember<T>::value. It should not need to test -// raw pointer types. To remove these tests, we may need support for -// instantiating a template with a RawPtrOrMember'ish template. +// raw pointer types. template<typename T> struct TraceIfNeeded : public TraceIfEnabled<T, WTF::NeedsTracing<T>::value || IsGarbageCollectedType<typename RemoveHeapPointerWrapperTypes<typename std::remove_pointer<T>::type>::Type>::value> { STATIC_ONLY(TraceIfNeeded);
diff --git a/third_party/WebKit/Source/platform/image-decoders/FastSharedBufferReader.cpp b/third_party/WebKit/Source/platform/image-decoders/FastSharedBufferReader.cpp index 63a380a..ba2f2390 100644 --- a/third_party/WebKit/Source/platform/image-decoders/FastSharedBufferReader.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/FastSharedBufferReader.cpp
@@ -32,7 +32,7 @@ namespace blink { -FastSharedBufferReader::FastSharedBufferReader(PassRefPtr<SharedBuffer> data) +FastSharedBufferReader::FastSharedBufferReader(PassRefPtr<SegmentReader> data) : m_data(data) , m_segment(0) , m_segmentLength(0) @@ -40,7 +40,7 @@ { } -void FastSharedBufferReader::setData(PassRefPtr<SharedBuffer> data) +void FastSharedBufferReader::setData(PassRefPtr<SegmentReader> data) { if (data == m_data) return;
diff --git a/third_party/WebKit/Source/platform/image-decoders/FastSharedBufferReader.h b/third_party/WebKit/Source/platform/image-decoders/FastSharedBufferReader.h index c1bf3f91..e82beaa 100644 --- a/third_party/WebKit/Source/platform/image-decoders/FastSharedBufferReader.h +++ b/third_party/WebKit/Source/platform/image-decoders/FastSharedBufferReader.h
@@ -32,7 +32,7 @@ #define FastSharedBufferReader_h #include "platform/PlatformExport.h" -#include "platform/SharedBuffer.h" +#include "platform/image-decoders/SegmentReader.h" #include "wtf/Allocator.h" #include "wtf/Noncopyable.h" #include "wtf/PassRefPtr.h" @@ -48,9 +48,9 @@ DISALLOW_NEW(); WTF_MAKE_NONCOPYABLE(FastSharedBufferReader); public: - FastSharedBufferReader(PassRefPtr<SharedBuffer> data); + FastSharedBufferReader(PassRefPtr<SegmentReader> data); - void setData(PassRefPtr<SharedBuffer>); + void setData(PassRefPtr<SegmentReader>); // Returns a consecutive buffer that carries the data starting // at |dataPosition| with |length| bytes. @@ -60,7 +60,7 @@ // Caller must ensure there are enough bytes in |m_data| and |buffer|. const char* getConsecutiveData(size_t dataPosition, size_t length, char* buffer) const; - // Wraps SharedBuffer::getSomeData(). + // Wraps SegmentReader::getSomeData(). size_t getSomeData(const char*& someData, size_t dataPosition) const; // Returns a byte at |dataPosition|. @@ -76,14 +76,14 @@ } // This class caches the last access for faster subsequent reads. This - // method clears that cache in case the SharedBuffer has been modified - // (i.e. with mergeSegmentsIntoBuffer). + // method clears that cache in case the SegmentReader has been modified + // (e.g. with mergeSegmentsIntoBuffer on a wrapped SharedBuffer). void clearCache(); private: void getSomeDataInternal(size_t dataPosition) const; - RefPtr<SharedBuffer> m_data; + RefPtr<SegmentReader> m_data; // Caches the last segment of |m_data| accessed, since subsequent reads are // likely to re-access it.
diff --git a/third_party/WebKit/Source/platform/image-decoders/FastSharedBufferReaderTest.cpp b/third_party/WebKit/Source/platform/image-decoders/FastSharedBufferReaderTest.cpp index 3ea9aa0..2e74a89 100644 --- a/third_party/WebKit/Source/platform/image-decoders/FastSharedBufferReaderTest.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/FastSharedBufferReaderTest.cpp
@@ -29,6 +29,7 @@ */ #include "platform/image-decoders/FastSharedBufferReader.h" +#include "platform/image-decoders/SegmentReader.h" #include "testing/gtest/include/gtest/gtest.h" @@ -44,6 +45,34 @@ buffer[i] = static_cast<char>(i); } +PassRefPtr<SegmentReader> copyToROBufferSegmentReader(PassRefPtr<SegmentReader> input) +{ + SkRWBuffer rwBuffer; + const char* segment = 0; + size_t position = 0; + while (size_t length = input->getSomeData(segment, position)) { + rwBuffer.append(segment, length); + position += length; + } + return SegmentReader::createFromSkROBuffer(adoptRef(rwBuffer.newRBufferSnapshot())); +} + +PassRefPtr<SegmentReader> copyToDataSegmentReader(PassRefPtr<SegmentReader> input) +{ + return SegmentReader::createFromSkData(input->getAsSkData()); +} + +struct SegmentReaders { + RefPtr<SegmentReader> segmentReaders[3]; + + SegmentReaders(PassRefPtr<SharedBuffer> input) + { + segmentReaders[0] = SegmentReader::createFromSharedBuffer(input); + segmentReaders[1] = copyToROBufferSegmentReader(segmentReaders[0]); + segmentReaders[2] = copyToDataSegmentReader(segmentReaders[0]); + } +}; + } // namespace TEST(FastSharedBufferReaderTest, nonSequentialReads) @@ -53,15 +82,17 @@ RefPtr<SharedBuffer> data = SharedBuffer::create(); data->append(referenceData, sizeof(referenceData)); - FastSharedBufferReader reader(data); - - // Read size is prime such there will be a segment-spanning - // read eventually. - char tempBuffer[17]; - for (size_t dataPosition = 0; dataPosition + sizeof(tempBuffer) < sizeof(referenceData); dataPosition += sizeof(tempBuffer)) { - const char* block = reader.getConsecutiveData( - dataPosition, sizeof(tempBuffer), tempBuffer); - ASSERT_FALSE(memcmp(block, referenceData + dataPosition, sizeof(tempBuffer))); + SegmentReaders readerStruct(data); + for (auto segmentReader : readerStruct.segmentReaders) { + FastSharedBufferReader reader(segmentReader); + // Read size is prime such there will be a segment-spanning + // read eventually. + char tempBuffer[17]; + for (size_t dataPosition = 0; dataPosition + sizeof(tempBuffer) < sizeof(referenceData); dataPosition += sizeof(tempBuffer)) { + const char* block = reader.getConsecutiveData( + dataPosition, sizeof(tempBuffer), tempBuffer); + ASSERT_FALSE(memcmp(block, referenceData + dataPosition, sizeof(tempBuffer))); + } } } @@ -72,15 +103,17 @@ RefPtr<SharedBuffer> data = SharedBuffer::create(); data->append(referenceData, sizeof(referenceData)); - FastSharedBufferReader reader(data); - - // Read size is prime such there will be a segment-spanning - // read eventually. - char tempBuffer[17]; - for (size_t dataOffset = sizeof(tempBuffer); dataOffset < sizeof(referenceData); dataOffset += sizeof(tempBuffer)) { - const char* block = reader.getConsecutiveData( - sizeof(referenceData) - dataOffset, sizeof(tempBuffer), tempBuffer); - ASSERT_FALSE(memcmp(block, referenceData + sizeof(referenceData) - dataOffset, sizeof(tempBuffer))); + SegmentReaders readerStruct(data); + for (auto segmentReader : readerStruct.segmentReaders) { + FastSharedBufferReader reader(segmentReader); + // Read size is prime such there will be a segment-spanning + // read eventually. + char tempBuffer[17]; + for (size_t dataOffset = sizeof(tempBuffer); dataOffset < sizeof(referenceData); dataOffset += sizeof(tempBuffer)) { + const char* block = reader.getConsecutiveData( + sizeof(referenceData) - dataOffset, sizeof(tempBuffer), tempBuffer); + ASSERT_FALSE(memcmp(block, referenceData + sizeof(referenceData) - dataOffset, sizeof(tempBuffer))); + } } } @@ -91,9 +124,12 @@ RefPtr<SharedBuffer> data = SharedBuffer::create(); data->append(referenceData, sizeof(referenceData)); - FastSharedBufferReader reader(data); - for (size_t i = 0; i < sizeof(referenceData); ++i) { - ASSERT_EQ(referenceData[i], reader.getOneByte(i)); + SegmentReaders readerStruct(data); + for (auto segmentReader : readerStruct.segmentReaders) { + FastSharedBufferReader reader(segmentReader); + for (size_t i = 0; i < sizeof(referenceData); ++i) { + ASSERT_EQ(referenceData[i], reader.getOneByte(i)); + } } } @@ -107,11 +143,97 @@ RefPtr<SharedBuffer> data = SharedBuffer::create(); data->append(referenceData, dataSize); - char buffer[dataSize]; - FastSharedBufferReader reader(data); - reader.getConsecutiveData(0, dataSize, buffer); + SegmentReaders readerStruct(data); + for (auto segmentReader : readerStruct.segmentReaders) { + FastSharedBufferReader reader(segmentReader); + char buffer[dataSize]; + reader.getConsecutiveData(0, dataSize, buffer); + ASSERT_FALSE(memcmp(buffer, referenceData, dataSize)); + } +} - ASSERT_FALSE(memcmp(buffer, referenceData, dataSize)); +// Verify that reading past the end of the buffer does not break future reads. +TEST(SegmentReaderTest, readPastEndThenRead) +{ + const unsigned dataSize = 2 * SharedBuffer::kSegmentSize; + char referenceData[dataSize]; + prepareReferenceData(referenceData, dataSize); + RefPtr<SharedBuffer> data = SharedBuffer::create(); + data->append(referenceData, dataSize); + + SegmentReaders readerStruct(data); + for (auto segmentReader : readerStruct.segmentReaders) { + const char* contents; + size_t length = segmentReader->getSomeData(contents, dataSize); + EXPECT_EQ(0u, length); + + length = segmentReader->getSomeData(contents, 0); + EXPECT_LE(SharedBuffer::kSegmentSize, length); + } +} + +TEST(SegmentReaderTest, getAsSkData) +{ + const unsigned dataSize = 4 * SharedBuffer::kSegmentSize; + char referenceData[dataSize]; + prepareReferenceData(referenceData, dataSize); + RefPtr<SharedBuffer> data = SharedBuffer::create(); + data->append(referenceData, dataSize); + + SegmentReaders readerStruct(data); + for (auto segmentReader : readerStruct.segmentReaders) { + RefPtr<SkData> skdata = segmentReader->getAsSkData(); + EXPECT_EQ(data->size(), skdata->size()); + + const char* segment; + size_t position = 0; + for (size_t length = segmentReader->getSomeData(segment, position); + length; length = segmentReader->getSomeData(segment, position)) { + ASSERT_FALSE(memcmp(segment, skdata->bytes() + position, length)); + position += length; + } + EXPECT_EQ(position, dataSize); + } +} + +TEST(SegmentReaderTest, variableSegments) +{ + const size_t dataSize = 3.5 * SharedBuffer::kSegmentSize; + char referenceData[dataSize]; + prepareReferenceData(referenceData, dataSize); + + RefPtr<SegmentReader> segmentReader; + { + // Create a SegmentReader with difference sized segments, to test that + // the SkROBuffer implementation works when two consecutive segments + // are not the same size. This test relies on knowledge of the + // internals of SkRWBuffer: it ensures that each segment is at least + // 4096 (though the actual data may be smaller, if it has not been + // written to yet), but when appending a larger amount it may create a + // larger segment. + SkRWBuffer rwBuffer; + rwBuffer.append(referenceData, SharedBuffer::kSegmentSize); + rwBuffer.append(referenceData + SharedBuffer::kSegmentSize, 2 * SharedBuffer::kSegmentSize); + rwBuffer.append(referenceData + 3 * SharedBuffer::kSegmentSize, .5 * SharedBuffer::kSegmentSize); + + segmentReader = SegmentReader::createFromSkROBuffer(adoptRef(rwBuffer.newRBufferSnapshot())); + } + + const char* segment; + size_t position = 0; + size_t lastLength = 0; + for (size_t length = segmentReader->getSomeData(segment, position); + length; length = segmentReader->getSomeData(segment, position)) { + // It is not a bug to have consecutive segments of the same length, but + // it does mean that the following test does not actually test what it + // is intended to test. + ASSERT_NE(length, lastLength); + lastLength = length; + + ASSERT_FALSE(memcmp(segment, referenceData + position, length)); + position += length; + } + EXPECT_EQ(position, dataSize); } } // namespace blink
diff --git a/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.cpp b/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.cpp index f0c888e8..70de782 100644 --- a/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.cpp
@@ -32,67 +32,51 @@ namespace blink { -static size_t copyFromSharedBuffer(char* buffer, size_t bufferLength, const SharedBuffer& sharedBuffer, size_t offset) -{ - size_t bytesExtracted = 0; - const char* moreData; - while (size_t moreDataLength = sharedBuffer.getSomeData(moreData, offset)) { - size_t bytesToCopy = std::min(bufferLength - bytesExtracted, moreDataLength); - memcpy(buffer + bytesExtracted, moreData, bytesToCopy); - bytesExtracted += bytesToCopy; - if (bytesExtracted == bufferLength) - break; - offset += bytesToCopy; - } - return bytesExtracted; -} - -inline bool matchesJPEGSignature(char* contents) +inline bool matchesJPEGSignature(const char* contents) { return !memcmp(contents, "\xFF\xD8\xFF", 3); } -inline bool matchesPNGSignature(char* contents) +inline bool matchesPNGSignature(const char* contents) { return !memcmp(contents, "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 8); } -inline bool matchesGIFSignature(char* contents) +inline bool matchesGIFSignature(const char* contents) { return !memcmp(contents, "GIF87a", 6) || !memcmp(contents, "GIF89a", 6); } -inline bool matchesWebPSignature(char* contents) +inline bool matchesWebPSignature(const char* contents) { return !memcmp(contents, "RIFF", 4) && !memcmp(contents + 8, "WEBPVP", 6); } -inline bool matchesICOSignature(char* contents) +inline bool matchesICOSignature(const char* contents) { return !memcmp(contents, "\x00\x00\x01\x00", 4); } -inline bool matchesCURSignature(char* contents) +inline bool matchesCURSignature(const char* contents) { return !memcmp(contents, "\x00\x00\x02\x00", 4); } -inline bool matchesBMPSignature(char* contents) +inline bool matchesBMPSignature(const char* contents) { return !memcmp(contents, "BM", 2); } -PassOwnPtr<ImageDecoder> ImageDecoder::create(const SharedBuffer& data, AlphaOption alphaOption, GammaAndColorProfileOption colorOptions) +PassOwnPtr<ImageDecoder> ImageDecoder::create(const char* contents, size_t length, AlphaOption alphaOption, GammaAndColorProfileOption colorOptions) { const size_t longestSignatureLength = sizeof("RIFF????WEBPVP") - 1; ASSERT(longestSignatureLength == 14); - size_t maxDecodedBytes = Platform::current() ? Platform::current()->maxDecodedImageBytes() : noDecodedImageByteLimit; - - char contents[longestSignatureLength]; - if (copyFromSharedBuffer(contents, longestSignatureLength, data, 0) < longestSignatureLength) + if (length < longestSignatureLength) return nullptr; + size_t maxDecodedBytes = Platform::current() ? Platform::current()->maxDecodedImageBytes() : noDecodedImageByteLimit; + if (matchesJPEGSignature(contents)) return adoptPtr(new JPEGImageDecoder(alphaOption, colorOptions, maxDecodedBytes)); @@ -114,6 +98,20 @@ return nullptr; } +PassOwnPtr<ImageDecoder> ImageDecoder::create(const SharedBuffer& data, AlphaOption alphaOption, GammaAndColorProfileOption colorOptions) +{ + const char* contents; + const size_t length = data.getSomeData<size_t>(contents); + return create(contents, length, alphaOption, colorOptions); +} + +PassOwnPtr<ImageDecoder> ImageDecoder::create(const SegmentReader& data, AlphaOption alphaOption, GammaAndColorProfileOption colorOptions) +{ + const char* contents; + const size_t length = data.getSomeData(contents, 0); + return create(contents, length, alphaOption, colorOptions); +} + size_t ImageDecoder::frameCount() { const size_t oldSize = m_frameBufferCache.size();
diff --git a/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.h b/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.h index 55eec65..7da3b9b 100644 --- a/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.h +++ b/third_party/WebKit/Source/platform/image-decoders/ImageDecoder.h
@@ -33,6 +33,7 @@ #include "platform/graphics/ImageOrientation.h" #include "platform/image-decoders/ImageAnimation.h" #include "platform/image-decoders/ImageFrame.h" +#include "platform/image-decoders/SegmentReader.h" #include "public/platform/Platform.h" #include "wtf/Assertions.h" #include "wtf/PassOwnPtr.h" @@ -122,22 +123,29 @@ // we can't sniff a supported type from the provided data (possibly // because there isn't enough data yet). // Sets m_maxDecodedBytes to Platform::maxImageDecodedBytes(). - static PassOwnPtr<ImageDecoder> create(const SharedBuffer& data, AlphaOption, GammaAndColorProfileOption); + static PassOwnPtr<ImageDecoder> create(const char* data, size_t length, AlphaOption, GammaAndColorProfileOption); + static PassOwnPtr<ImageDecoder> create(const SharedBuffer&, AlphaOption, GammaAndColorProfileOption); + static PassOwnPtr<ImageDecoder> create(const SegmentReader&, AlphaOption, GammaAndColorProfileOption); virtual String filenameExtension() const = 0; bool isAllDataReceived() const { return m_isAllDataReceived; } - void setData(SharedBuffer* data, bool allDataReceived) + void setData(PassRefPtr<SegmentReader> data, bool allDataReceived) { if (m_failed) return; m_data = data; m_isAllDataReceived = allDataReceived; - onSetData(data); + onSetData(m_data.get()); } - virtual void onSetData(SharedBuffer* data) { } + void setData(PassRefPtr<SharedBuffer> data, bool allDataReceived) + { + setData(SegmentReader::createFromSharedBuffer(data), allDataReceived); + } + + virtual void onSetData(SegmentReader* data) { } bool isSizeAvailable() { @@ -310,7 +318,7 @@ // Decodes the requested frame. virtual void decode(size_t) = 0; - RefPtr<SharedBuffer> m_data; // The encoded data. + RefPtr<SegmentReader> m_data; // The encoded data. Vector<ImageFrame, 1> m_frameBufferCache; bool m_premultiplyAlpha; bool m_ignoreGammaAndColorProfile;
diff --git a/third_party/WebKit/Source/platform/image-decoders/SegmentReader.cpp b/third_party/WebKit/Source/platform/image-decoders/SegmentReader.cpp new file mode 100644 index 0000000..4a2e6b2 --- /dev/null +++ b/third_party/WebKit/Source/platform/image-decoders/SegmentReader.cpp
@@ -0,0 +1,200 @@ +// 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/image-decoders/SegmentReader.h" + +#include "platform/SharedBuffer.h" +#include "third_party/skia/include/core/SkData.h" +#include "wtf/Assertions.h" +#include "wtf/Noncopyable.h" +#include "wtf/PassRefPtr.h" +#include "wtf/RefPtr.h" +#include "wtf/ThreadingPrimitives.h" + +namespace blink { + +// SharedBufferSegmentReader --------------------------------------------------- + +// Interface for ImageDecoder to read a SharedBuffer. +class SharedBufferSegmentReader final : public SegmentReader { + WTF_MAKE_NONCOPYABLE(SharedBufferSegmentReader); +public: + SharedBufferSegmentReader(PassRefPtr<SharedBuffer>); + size_t size() const override; + size_t getSomeData(const char*& data, size_t position) const override; + PassRefPtr<SkData> getAsSkData() const override; +private: + RefPtr<SharedBuffer> m_sharedBuffer; +}; + +SharedBufferSegmentReader::SharedBufferSegmentReader(PassRefPtr<SharedBuffer> buffer) + : m_sharedBuffer(buffer) {} + +size_t SharedBufferSegmentReader::size() const +{ + return m_sharedBuffer->size(); +} + +size_t SharedBufferSegmentReader::getSomeData(const char*& data, size_t position) const +{ + return m_sharedBuffer->getSomeData(data, position); +} + +PassRefPtr<SkData> SharedBufferSegmentReader::getAsSkData() const +{ + return m_sharedBuffer->getAsSkData(); +} + +// DataSegmentReader ----------------------------------------------------------- + +// Interface for ImageDecoder to read an SkData. +class DataSegmentReader final : public SegmentReader { + WTF_MAKE_NONCOPYABLE(DataSegmentReader); +public: + DataSegmentReader(PassRefPtr<SkData>); + size_t size() const override; + size_t getSomeData(const char*& data, size_t position) const override; + PassRefPtr<SkData> getAsSkData() const override; +private: + RefPtr<SkData> m_data; +}; + +DataSegmentReader::DataSegmentReader(PassRefPtr<SkData> data) + : m_data(data) {} + +size_t DataSegmentReader::size() const +{ + return m_data->size(); +} + +size_t DataSegmentReader::getSomeData(const char*& data, size_t position) const +{ + if (position >= m_data->size()) + return 0; + + data = reinterpret_cast<const char*>(m_data->bytes() + position); + return m_data->size() - position; +} + +PassRefPtr<SkData> DataSegmentReader::getAsSkData() const +{ + return m_data.get(); +} + +// ROBufferSegmentReader ------------------------------------------------------- + +class ROBufferSegmentReader final : public SegmentReader { + WTF_MAKE_NONCOPYABLE(ROBufferSegmentReader); +public: + ROBufferSegmentReader(PassRefPtr<SkROBuffer>); + + size_t size() const override; + size_t getSomeData(const char*& data, size_t position) const override; + PassRefPtr<SkData> getAsSkData() const override; + +private: + RefPtr<SkROBuffer> m_roBuffer; + // Protects access to mutable fields. + mutable Mutex m_readMutex; + // Position of the first char in the current block of m_iter. + mutable size_t m_positionOfBlock; + mutable SkROBuffer::Iter m_iter; +}; + +ROBufferSegmentReader::ROBufferSegmentReader(PassRefPtr<SkROBuffer> buffer) + : m_roBuffer(buffer) + , m_positionOfBlock(0) + , m_iter(m_roBuffer.get()) + {} + +size_t ROBufferSegmentReader::size() const +{ + return m_roBuffer ? m_roBuffer->size() : 0; +} + +size_t ROBufferSegmentReader::getSomeData(const char*& data, size_t position) const +{ + if (!m_roBuffer) + return 0; + + MutexLocker lock(m_readMutex); + + if (position < m_positionOfBlock) { + // SkROBuffer::Iter only iterates forwards. Start from the beginning. + m_iter.reset(m_roBuffer.get()); + m_positionOfBlock = 0; + } + + for (size_t sizeOfBlock = m_iter.size(); sizeOfBlock != 0; m_positionOfBlock += sizeOfBlock, sizeOfBlock = m_iter.size()) { + ASSERT(m_positionOfBlock <= position); + + if (m_positionOfBlock + sizeOfBlock > position) { + // |position| is in this block. + const size_t positionInBlock = position - m_positionOfBlock; + data = static_cast<const char*>(m_iter.data()) + positionInBlock; + return sizeOfBlock - positionInBlock; + } + + // Move to next block. + if (!m_iter.next()) { + // Reset to the beginning, so future calls can succeed. + m_iter.reset(m_roBuffer.get()); + m_positionOfBlock = 0; + return 0; + } + } + + return 0; +} + +static void unrefROBuffer(const void* ptr, void* context) +{ + static_cast<SkROBuffer*>(context)->unref(); +} + +PassRefPtr<SkData> ROBufferSegmentReader::getAsSkData() const +{ + if (!m_roBuffer) + return nullptr; + + // Check to see if the data is already contiguous. + SkROBuffer::Iter iter(m_roBuffer.get()); + const bool multipleBlocks = iter.next(); + iter.reset(m_roBuffer.get()); + + if (!multipleBlocks) { + // Contiguous data. No need to copy. + m_roBuffer->ref(); + return adoptRef(SkData::NewWithProc(iter.data(), iter.size(), &unrefROBuffer, m_roBuffer.get())); + } + + RefPtr<SkData> data = adoptRef(SkData::NewUninitialized(m_roBuffer->size())); + char* dst = static_cast<char*>(data->writable_data()); + do { + size_t size = iter.size(); + memcpy(dst, iter.data(), size); + dst += size; + } while (iter.next()); + return data.release(); +} + +// SegmentReader --------------------------------------------------------------- + +PassRefPtr<SegmentReader> SegmentReader::createFromSharedBuffer(PassRefPtr<SharedBuffer> buffer) +{ + return adoptRef(new SharedBufferSegmentReader(buffer)); +} + +PassRefPtr<SegmentReader> SegmentReader::createFromSkData(PassRefPtr<SkData> data) +{ + return adoptRef(new DataSegmentReader(data)); +} + +PassRefPtr<SegmentReader> SegmentReader::createFromSkROBuffer(PassRefPtr<SkROBuffer> buffer) +{ + return adoptRef(new ROBufferSegmentReader(buffer)); +} + +} // namespace blink +
diff --git a/third_party/WebKit/Source/platform/image-decoders/SegmentReader.h b/third_party/WebKit/Source/platform/image-decoders/SegmentReader.h new file mode 100644 index 0000000..13c28ce --- /dev/null +++ b/third_party/WebKit/Source/platform/image-decoders/SegmentReader.h
@@ -0,0 +1,48 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef SegmentReader_h +#define SegmentReader_h + +#include "platform/SharedBuffer.h" +#include "third_party/skia/include/core/SkData.h" +#include "third_party/skia/include/core/SkRWBuffer.h" +#include "wtf/Noncopyable.h" +#include "wtf/PassRefPtr.h" +#include "wtf/ThreadSafeRefCounted.h" + +namespace blink { + +// Interface that looks like SharedBuffer. Used by ImageDecoders to use various +// sources of input including: +// - SharedBuffer +// - for when the caller already has a SharedBuffer +// - SkData +// - for when the caller already has an SkData +// - SkROBuffer +// - for when the caller wants to read/write in different threads +// +// Unlike SharedBuffer, this is a read-only interface. There is no way to +// modify the underlying data source. +class PLATFORM_EXPORT SegmentReader : public ThreadSafeRefCounted<SegmentReader> { + WTF_MAKE_NONCOPYABLE(SegmentReader); +public: + // This version is thread-safe so long as no thread is modifying the + // underlying SharedBuffer. This class does not modify it, so that would + // mean modifying it in another way. + static PassRefPtr<SegmentReader> createFromSharedBuffer(PassRefPtr<SharedBuffer>); + + // These versions use thread-safe input, so they are always thread-safe. + static PassRefPtr<SegmentReader> createFromSkData(PassRefPtr<SkData>); + static PassRefPtr<SegmentReader> createFromSkROBuffer(PassRefPtr<SkROBuffer>); + + SegmentReader() {} + virtual ~SegmentReader() {} + virtual size_t size() const = 0; + virtual size_t getSomeData(const char*& data, size_t position) const = 0; + virtual PassRefPtr<SkData> getAsSkData() const = 0; +}; + +} // namespace blink +#endif // SegmentReader_h
diff --git a/third_party/WebKit/Source/platform/image-decoders/bmp/BMPImageDecoder.cpp b/third_party/WebKit/Source/platform/image-decoders/bmp/BMPImageDecoder.cpp index 998faac6..01815ab 100644 --- a/third_party/WebKit/Source/platform/image-decoders/bmp/BMPImageDecoder.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/bmp/BMPImageDecoder.cpp
@@ -46,7 +46,7 @@ { } -void BMPImageDecoder::onSetData(SharedBuffer* data) +void BMPImageDecoder::onSetData(SegmentReader* data) { if (m_reader) m_reader->setData(data);
diff --git a/third_party/WebKit/Source/platform/image-decoders/bmp/BMPImageDecoder.h b/third_party/WebKit/Source/platform/image-decoders/bmp/BMPImageDecoder.h index c2053a5..e4a6bd1 100644 --- a/third_party/WebKit/Source/platform/image-decoders/bmp/BMPImageDecoder.h +++ b/third_party/WebKit/Source/platform/image-decoders/bmp/BMPImageDecoder.h
@@ -43,7 +43,7 @@ // ImageDecoder: String filenameExtension() const override { return "bmp"; } - void onSetData(SharedBuffer*) override; + void onSetData(SegmentReader*) override; // CAUTION: setFailed() deletes |m_reader|. Be careful to avoid // accessing deleted memory, especially when calling this from inside // BMPImageReader!
diff --git a/third_party/WebKit/Source/platform/image-decoders/bmp/BMPImageReader.h b/third_party/WebKit/Source/platform/image-decoders/bmp/BMPImageReader.h index 7bfa563..d150a56 100644 --- a/third_party/WebKit/Source/platform/image-decoders/bmp/BMPImageReader.h +++ b/third_party/WebKit/Source/platform/image-decoders/bmp/BMPImageReader.h
@@ -65,7 +65,7 @@ BMPImageReader(ImageDecoder* parent, size_t decodedAndHeaderOffset, size_t imgDataOffset, bool isInICO); void setBuffer(ImageFrame* buffer) { m_buffer = buffer; } - void setData(SharedBuffer* data) + void setData(SegmentReader* data) { m_data = data; m_fastReader.setData(data); @@ -290,7 +290,7 @@ ImageFrame* m_buffer; // The file to decode. - RefPtr<SharedBuffer> m_data; + RefPtr<SegmentReader> m_data; FastSharedBufferReader m_fastReader; // An index into |m_data| representing how much we've already decoded.
diff --git a/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.cpp b/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.cpp index 824764c5..457666d2 100644 --- a/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.cpp
@@ -42,7 +42,7 @@ { } -void GIFImageDecoder::onSetData(SharedBuffer* data) +void GIFImageDecoder::onSetData(SegmentReader* data) { if (m_reader) m_reader->setData(data);
diff --git a/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.h b/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.h index f9aa02c4..98941e68 100644 --- a/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.h +++ b/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageDecoder.h
@@ -47,7 +47,7 @@ // ImageDecoder: String filenameExtension() const override { return "gif"; } - void onSetData(SharedBuffer* data) override; + void onSetData(SegmentReader* data) override; int repetitionCount() const override; bool frameIsCompleteAtIndex(size_t) const override; float frameDurationAtIndex(size_t) const override;
diff --git a/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageReader.cpp b/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageReader.cpp index 4c6631d..103d6d3 100644 --- a/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageReader.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageReader.cpp
@@ -387,7 +387,15 @@ bool GIFImageReader::parse(GIFImageDecoder::GIFParseQuery query) { - ASSERT(m_bytesRead <= m_data->size()); + if (m_bytesRead >= m_data->size()) { + // This data has already been parsed. For example, in deferred + // decoding, a DecodingImageGenerator with more data may have already + // used this same ImageDecoder to decode. This can happen if two + // SkImages created by a DeferredImageDecoder are drawn/prerolled + // out of order (with respect to how much data they had at creation + // time). + return !m_client->failed(); + } return parseData(m_bytesRead, m_data->size() - m_bytesRead, query); }
diff --git a/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageReader.h b/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageReader.h index 6172377..bfa9897 100644 --- a/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageReader.h +++ b/third_party/WebKit/Source/platform/image-decoders/gif/GIFImageReader.h
@@ -40,7 +40,6 @@ // Define ourselves as the clientPtr. Mozilla just hacked their C++ callback class into this old C decoder, // so we will too. -#include "platform/SharedBuffer.h" #include "platform/image-decoders/FastSharedBufferReader.h" #include "platform/image-decoders/gif/GIFImageDecoder.h" #include "wtf/Allocator.h" @@ -299,7 +298,7 @@ { } - void setData(PassRefPtr<blink::SharedBuffer> data) { m_data = data; } + void setData(PassRefPtr<blink::SegmentReader> data) { m_data = data; } bool parse(blink::GIFImageDecoder::GIFParseQuery); bool decode(size_t frameIndex); @@ -356,7 +355,7 @@ Vector<OwnPtr<GIFFrameContext>> m_frames; - RefPtr<blink::SharedBuffer> m_data; + RefPtr<blink::SegmentReader> m_data; bool m_parseCompleted; };
diff --git a/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoder.cpp b/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoder.cpp index 592eb96..a189f81 100644 --- a/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoder.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoder.cpp
@@ -54,7 +54,7 @@ { } -void ICOImageDecoder::onSetData(SharedBuffer* data) +void ICOImageDecoder::onSetData(SegmentReader* data) { m_fastReader.setData(data);
diff --git a/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoder.h b/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoder.h index 73759ba..3df9ba1 100644 --- a/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoder.h +++ b/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoder.h
@@ -46,7 +46,7 @@ // ImageDecoder: String filenameExtension() const override { return "ico"; } - void onSetData(SharedBuffer*) override; + void onSetData(SegmentReader*) override; IntSize size() const override; IntSize frameSizeAtIndex(size_t) const override; bool setSize(unsigned width, unsigned height) override;
diff --git a/third_party/WebKit/Source/platform/image-decoders/jpeg/JPEGImageDecoder.cpp b/third_party/WebKit/Source/platform/image-decoders/jpeg/JPEGImageDecoder.cpp index 79434ab..03b465d8 100644 --- a/third_party/WebKit/Source/platform/image-decoders/jpeg/JPEGImageDecoder.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/jpeg/JPEGImageDecoder.cpp
@@ -361,19 +361,19 @@ return true; } - void setData(SharedBuffer* data) + void setData(SegmentReader* data) { if (m_data.get() == data) return; m_data = data; - // If a restart is needed, the next call to fillBuffer will read from the new SharedBuffer. + // If a restart is needed, the next call to fillBuffer will read from the new SegmentReader. if (m_needsRestart) return; // Otherwise, empty the buffer, and leave the position the same, so fillBuffer continues - // reading from the same position in the new SharedBuffer. + // reading from the same position in the new SegmentReader. m_nextReadPosition -= m_info.src->bytes_in_buffer; clearBuffer(); } @@ -637,7 +637,7 @@ m_lastSetByte = nullptr; } - RefPtr<SharedBuffer> m_data; + RefPtr<SegmentReader> m_data; JPEGImageDecoder* m_decoder; // Input reading: True if we need to back up to m_restartPosition. @@ -723,7 +723,7 @@ return true; } -void JPEGImageDecoder::onSetData(SharedBuffer* data) +void JPEGImageDecoder::onSetData(SegmentReader* data) { if (m_reader) m_reader->setData(data);
diff --git a/third_party/WebKit/Source/platform/image-decoders/jpeg/JPEGImageDecoder.h b/third_party/WebKit/Source/platform/image-decoders/jpeg/JPEGImageDecoder.h index 5063b8c..0dc93f1 100644 --- a/third_party/WebKit/Source/platform/image-decoders/jpeg/JPEGImageDecoder.h +++ b/third_party/WebKit/Source/platform/image-decoders/jpeg/JPEGImageDecoder.h
@@ -40,7 +40,7 @@ // ImageDecoder: String filenameExtension() const override { return "jpg"; } - void onSetData(SharedBuffer* data) override; + void onSetData(SegmentReader* data) override; IntSize decodedSize() const override { return m_decodedSize; } bool setSize(unsigned width, unsigned height) override; IntSize decodedYUVSize(int component) const override;
diff --git a/third_party/WebKit/Source/platform/image-decoders/png/PNGImageDecoder.cpp b/third_party/WebKit/Source/platform/image-decoders/png/PNGImageDecoder.cpp index bff97c2..5f787b5 100644 --- a/third_party/WebKit/Source/platform/image-decoders/png/PNGImageDecoder.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/png/PNGImageDecoder.cpp
@@ -110,7 +110,7 @@ m_readOffset = 0; } - bool decode(const SharedBuffer& data, bool sizeOnly) + bool decode(const SegmentReader& data, bool sizeOnly) { m_decodingSizeOnly = sizeOnly;
diff --git a/third_party/WebKit/Source/platform/image-decoders/webp/WEBPImageDecoder.cpp b/third_party/WebKit/Source/platform/image-decoders/webp/WEBPImageDecoder.cpp index 2672862d..fae908a7 100644 --- a/third_party/WebKit/Source/platform/image-decoders/webp/WEBPImageDecoder.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/webp/WEBPImageDecoder.cpp
@@ -144,6 +144,7 @@ { WebPDemuxDelete(m_demux); m_demux = 0; + m_consolidatedData.clear(); clearDecoder(); } @@ -155,7 +156,7 @@ m_frameBackgroundHasAlpha = false; } -void WEBPImageDecoder::onSetData(SharedBuffer*) +void WEBPImageDecoder::onSetData(SegmentReader*) { m_haveAlreadyParsedThisData = false; } @@ -195,10 +196,14 @@ return false; // Await VP8X header so WebPDemuxPartial succeeds. WebPDemuxDelete(m_demux); - WebPData inputData = { reinterpret_cast<const uint8_t*>(m_data->data()), m_data->size() }; + m_consolidatedData = m_data->getAsSkData(); + WebPData inputData = { reinterpret_cast<const uint8_t*>(m_consolidatedData->data()), m_consolidatedData->size() }; m_demux = WebPDemuxPartial(&inputData, &m_demuxState); - if (!m_demux || (isAllDataReceived() && m_demuxState != WEBP_DEMUX_DONE)) + if (!m_demux || (isAllDataReceived() && m_demuxState != WEBP_DEMUX_DONE)) { + if (!m_demux) + m_consolidatedData.clear(); return setFailed(); + } ASSERT(m_demuxState > WEBP_DEMUX_PARSING_HEADER); if (!WebPDemuxGetI(m_demux, WEBP_FF_FRAME_COUNT))
diff --git a/third_party/WebKit/Source/platform/image-decoders/webp/WEBPImageDecoder.h b/third_party/WebKit/Source/platform/image-decoders/webp/WEBPImageDecoder.h index c991671..718ae30 100644 --- a/third_party/WebKit/Source/platform/image-decoders/webp/WEBPImageDecoder.h +++ b/third_party/WebKit/Source/platform/image-decoders/webp/WEBPImageDecoder.h
@@ -30,8 +30,10 @@ #define WEBPImageDecoder_h #include "platform/image-decoders/ImageDecoder.h" +#include "third_party/skia/include/core/SkData.h" #include "webp/decode.h" #include "webp/demux.h" +#include "wtf/RefPtr.h" namespace blink { @@ -43,7 +45,7 @@ // ImageDecoder: String filenameExtension() const override { return "webp"; } - void onSetData(SharedBuffer* data) override; + void onSetData(SegmentReader* data) override; int repetitionCount() const override; bool frameIsCompleteAtIndex(size_t) const override; float frameDurationAtIndex(size_t) const override; @@ -83,6 +85,9 @@ void clear(); void clearDecoder(); + + // FIXME: Update libwebp's API so it does not require copying the data on each update. + RefPtr<SkData> m_consolidatedData; }; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollAnimatorTest.cpp b/third_party/WebKit/Source/platform/scroll/ScrollAnimatorTest.cpp index aafe7f9..87cdcad 100644 --- a/third_party/WebKit/Source/platform/scroll/ScrollAnimatorTest.cpp +++ b/third_party/WebKit/Source/platform/scroll/ScrollAnimatorTest.cpp
@@ -514,7 +514,7 @@ reset(*scrollAnimator); // Forced GC in order to finalize objects depending on the mock object. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); } } // namespace blink
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollableAreaTest.cpp b/third_party/WebKit/Source/platform/scroll/ScrollableAreaTest.cpp index fac33c1..4c1e682 100644 --- a/third_party/WebKit/Source/platform/scroll/ScrollableAreaTest.cpp +++ b/third_party/WebKit/Source/platform/scroll/ScrollableAreaTest.cpp
@@ -146,7 +146,7 @@ EXPECT_TRUE(scrollbar->thumbNeedsRepaint()); // Forced GC in order to finalize objects depending on the mock object. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); } TEST_F(ScrollableAreaTest, ScrollbarGraphicsLayerInvalidation) @@ -167,7 +167,7 @@ EXPECT_TRUE(graphicsLayer.hasTrackedPaintInvalidations()); // Forced GC in order to finalize objects depending on the mock object. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); } TEST_F(ScrollableAreaTest, InvalidatesNonCompositedScrollbarsWhenThumbMoves) @@ -199,7 +199,7 @@ scrollableArea->clearNeedsPaintInvalidationForScrollControls(); // Forced GC in order to finalize objects depending on the mock object. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); } TEST_F(ScrollableAreaTest, InvalidatesCompositedScrollbarsIfPartsNeedRepaint) @@ -266,7 +266,7 @@ EXPECT_FALSE(verticalScrollbar->thumbNeedsRepaint()); // Forced GC in order to finalize objects depending on the mock object. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); } TEST_F(ScrollableAreaTest, RecalculatesScrollbarOverlayIfBackgroundChanges)
diff --git a/third_party/WebKit/Source/platform/testing/RunAllTests.cpp b/third_party/WebKit/Source/platform/testing/RunAllTests.cpp index 01aec52..ccb0d227 100644 --- a/third_party/WebKit/Source/platform/testing/RunAllTests.cpp +++ b/third_party/WebKit/Source/platform/testing/RunAllTests.cpp
@@ -61,7 +61,7 @@ int runTestSuite(base::TestSuite* testSuite) { int result = testSuite->Run(); - blink::Heap::collectAllGarbage(); + blink::ThreadHeap::collectAllGarbage(); return result; } @@ -95,7 +95,7 @@ platformConfig.compositorSupport = &compositorSupport; blink::TestingPlatformSupport platform(platformConfig); - blink::Heap::init(); + blink::ThreadHeap::init(); blink::ThreadState::attachMainThread(); blink::ThreadState::current()->registerTraceDOMWrappers(nullptr, nullptr); blink::EventTracer::initialize(); @@ -109,7 +109,7 @@ result = base::LaunchUnitTests(argc, argv, base::Bind(runTestSuite, base::Unretained(&testSuite))); blink::ThreadState::detachMainThread(); - blink::Heap::shutdown(); + blink::ThreadHeap::shutdown(); } blink::CompositorFactory::shutdown(); WTF::shutdown();
diff --git a/third_party/WebKit/Source/platform/text/TextEncodingDetector.cpp b/third_party/WebKit/Source/platform/text/TextEncodingDetector.cpp index 476d992..616aac0 100644 --- a/third_party/WebKit/Source/platform/text/TextEncodingDetector.cpp +++ b/third_party/WebKit/Source/platform/text/TextEncodingDetector.cpp
@@ -36,7 +36,7 @@ namespace blink { -bool detectTextEncodingUniversal(const char* data, size_t length, +bool detectTextEncoding(const char* data, size_t length, const char* hintEncodingName, WTF::TextEncoding* detectedEncoding) { *detectedEncoding = WTF::TextEncoding();
diff --git a/third_party/WebKit/Source/platform/text/TextEncodingDetector.h b/third_party/WebKit/Source/platform/text/TextEncodingDetector.h index dd6b774a..12f4890 100644 --- a/third_party/WebKit/Source/platform/text/TextEncodingDetector.h +++ b/third_party/WebKit/Source/platform/text/TextEncodingDetector.h
@@ -44,9 +44,9 @@ // hintEncodingName, detect the most likely character encoding. // The way hintEncodingName is used is up to an implementation. // Currently, the only caller sets it to the parent frame encoding. -PLATFORM_EXPORT bool detectTextEncodingUniversal(const char* data, - size_t length, const char* hintEncodingName, - WTF::TextEncoding* detectedEncoding); +PLATFORM_EXPORT bool detectTextEncoding(const char* data, size_t length, + const char* hintEncodingName, WTF::TextEncoding* detectedEncoding); + } // namespace blink #endif
diff --git a/third_party/WebKit/Source/web/WebFrame.cpp b/third_party/WebKit/Source/web/WebFrame.cpp index a3c3b6b..a65d50d 100644 --- a/third_party/WebKit/Source/web/WebFrame.cpp +++ b/third_party/WebKit/Source/web/WebFrame.cpp
@@ -313,9 +313,9 @@ return true; if (frame->isWebLocalFrame()) - return Heap::isHeapObjectAlive(toWebLocalFrameImpl(frame)); + return ThreadHeap::isHeapObjectAlive(toWebLocalFrameImpl(frame)); - return Heap::isHeapObjectAlive(toWebRemoteFrameImpl(frame)); + return ThreadHeap::isHeapObjectAlive(toWebRemoteFrameImpl(frame)); } template <typename VisitorDispatcher>
diff --git a/third_party/WebKit/Source/web/WebHeap.cpp b/third_party/WebKit/Source/web/WebHeap.cpp index f7caabe3..b711d46 100644 --- a/third_party/WebKit/Source/web/WebHeap.cpp +++ b/third_party/WebKit/Source/web/WebHeap.cpp
@@ -47,12 +47,12 @@ void WebHeap::collectGarbageForTesting() { - Heap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + ThreadHeap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); } void WebHeap::collectAllGarbageForTesting() { - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); } } // namespace blink
diff --git a/third_party/WebKit/Source/web/WebSpeechRecognitionResult.cpp b/third_party/WebKit/Source/web/WebSpeechRecognitionResult.cpp index 1b86dcb..bcf9592 100644 --- a/third_party/WebKit/Source/web/WebSpeechRecognitionResult.cpp +++ b/third_party/WebKit/Source/web/WebSpeechRecognitionResult.cpp
@@ -28,9 +28,6 @@ #include "modules/speech/SpeechRecognitionAlternative.h" #include "modules/speech/SpeechRecognitionResult.h" #include "platform/heap/Handle.h" -#include "wtf/PassRefPtr.h" -#include "wtf/RawPtr.h" -#include "wtf/RefPtr.h" #include "wtf/Vector.h" namespace blink {
diff --git a/third_party/WebKit/Source/web/tests/WebViewTest.cpp b/third_party/WebKit/Source/web/tests/WebViewTest.cpp index 84015c6..9dd1cc8 100644 --- a/third_party/WebKit/Source/web/tests/WebViewTest.cpp +++ b/third_party/WebKit/Source/web/tests/WebViewTest.cpp
@@ -2495,7 +2495,7 @@ // checking below. We do a precise GC (collectAllGarbage does not scan the stack) // to ensure the div element dies. This is also why the Document is in a Persistent // since we want that to stay around. - Heap::collectAllGarbage(); + ThreadHeap::collectAllGarbage(); EXPECT_FALSE(registry.hasEventHandlers(EventHandlerRegistry::ScrollEvent)); }
diff --git a/third_party/WebKit/Source/wtf/HashFunctions.h b/third_party/WebKit/Source/wtf/HashFunctions.h index 1d02ceee..3d76ba5 100644 --- a/third_party/WebKit/Source/wtf/HashFunctions.h +++ b/third_party/WebKit/Source/wtf/HashFunctions.h
@@ -155,16 +155,6 @@ }; template <typename T> -struct RawPtrHash : PtrHash<T> { - using PtrHash<T>::hash; - static unsigned hash(const RawPtr<T>& key) { return hash(key.get()); } - using PtrHash<T>::equal; - static bool equal(const RawPtr<T>& a, const RawPtr<T>& b) { return a == b; } - static bool equal(T* a, const RawPtr<T>& b) { return a == b; } - static bool equal(const RawPtr<T>& a, T* b) { return a == b; } -}; - -template <typename T> struct OwnPtrHash : PtrHash<T> { using PtrHash<T>::hash; static unsigned hash(const OwnPtr<T>& key) { return hash(key.get()); } @@ -230,10 +220,6 @@ using Hash = RefPtrHash<T>; }; template <typename T> -struct DefaultHash<RawPtr<T>> { - using Hash = RawPtrHash<T>; -}; -template <typename T> struct DefaultHash<OwnPtr<T>> { using Hash = OwnPtrHash<T>; };
diff --git a/third_party/WebKit/Source/wtf/HashTraits.h b/third_party/WebKit/Source/wtf/HashTraits.h index 92e1060e..d1c393d 100644 --- a/third_party/WebKit/Source/wtf/HashTraits.h +++ b/third_party/WebKit/Source/wtf/HashTraits.h
@@ -210,8 +210,6 @@ static PeekOutType peek(std::nullptr_t) { return 0; } }; -template <typename T> struct HashTraits<RawPtr<T>> : HashTraits<T*> { }; - template <typename T> struct HashTraits<std::unique_ptr<T>> : SimpleClassHashTraits<std::unique_ptr<T>> { using EmptyValueType = std::nullptr_t;
diff --git a/third_party/WebKit/Source/wtf/PassRefPtr.h b/third_party/WebKit/Source/wtf/PassRefPtr.h index 60c91e6..38dd9c9 100644 --- a/third_party/WebKit/Source/wtf/PassRefPtr.h +++ b/third_party/WebKit/Source/wtf/PassRefPtr.h
@@ -23,7 +23,6 @@ #include "wtf/Allocator.h" #include "wtf/Assertions.h" -#include "wtf/RawPtr.h" #include "wtf/TypeTraits.h" namespace WTF { @@ -62,7 +61,6 @@ PassRefPtr() : m_ptr(nullptr) {} PassRefPtr(std::nullptr_t) : m_ptr(nullptr) {} PassRefPtr(T* ptr) : m_ptr(ptr) { refIfNotNull(ptr); } - template <typename U> PassRefPtr(const RawPtr<U>& ptr, EnsurePtrConvertibleArgDecl(U, T)) : m_ptr(ptr.get()) { refIfNotNull(m_ptr); } explicit PassRefPtr(T& ptr) : m_ptr(&ptr) { m_ptr->ref(); } // It somewhat breaks the type system to allow transfer of ownership out of // a const PassRefPtr. However, it makes it much easier to work with @@ -144,16 +142,6 @@ return a == b.get(); } -template <typename T, typename U> inline bool operator==(const PassRefPtr<T>& a, const RawPtr<U>& b) -{ - return a.get() == b.get(); -} - -template <typename T, typename U> inline bool operator==(const RawPtr<T>& a, const PassRefPtr<U>& b) -{ - return a.get() == b.get(); -} - template <typename T, typename U> inline bool operator!=(const PassRefPtr<T>& a, const PassRefPtr<U>& b) { return a.get() != b.get(); @@ -179,16 +167,6 @@ return a != b.get(); } -template <typename T, typename U> inline bool operator!=(const PassRefPtr<T>& a, const RawPtr<U>& b) -{ - return a.get() != b.get(); -} - -template <typename T, typename U> inline bool operator!=(const RawPtr<T>& a, const PassRefPtr<U>& b) -{ - return a.get() != b.get(); -} - template <typename T> PassRefPtr<T> adoptRef(T* p) { adopted(p);
diff --git a/third_party/WebKit/Source/wtf/RawPtr.h b/third_party/WebKit/Source/wtf/RawPtr.h deleted file mode 100644 index a666873..0000000 --- a/third_party/WebKit/Source/wtf/RawPtr.h +++ /dev/null
@@ -1,150 +0,0 @@ -/* - * Copyright (C) 2014 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WTF_RawPtr_h -#define WTF_RawPtr_h - -#include "wtf/Allocator.h" -#include "wtf/HashTableDeletedValueType.h" -#include "wtf/TypeTraits.h" -#include <algorithm> -#include <stdint.h> -#include <utility> - -// RawPtr is a simple wrapper for a raw pointer that provides the -// interface (get, clear) of other pointer types such as RefPtr, -// Persistent and Member. This is used for the Blink garbage -// collection work in order to be able to write shared code that will -// use reference counting or garbage collection based on a -// compile-time flag. - -namespace WTF { - -template<typename T> -class RawPtr { - USING_FAST_MALLOC(RawPtr); -public: - RawPtr() - { -#if ENABLE(ASSERT) - m_ptr = reinterpret_cast<T*>(rawPtrZapValue); -#endif - } - RawPtr(std::nullptr_t) : m_ptr(0) { } - RawPtr(T* ptr) : m_ptr(ptr) { } - explicit RawPtr(T& reference) : m_ptr(&reference) { } - RawPtr(const RawPtr& other) - : m_ptr(other.get()) - { - } - - template<typename U> - RawPtr(const RawPtr<U>& other, EnsurePtrConvertibleArgDecl(U, T)) - : m_ptr(other.get()) - { - } - - // Hash table deleted values, which are only constructed and never copied or destroyed. - RawPtr(HashTableDeletedValueType) : m_ptr(hashTableDeletedValue()) { } - bool isHashTableDeletedValue() const { return m_ptr == hashTableDeletedValue(); } - - T* get() const { return m_ptr; } - void clear() { m_ptr = 0; } - RawPtr<T> release() - { - RawPtr<T> tmp = m_ptr; - m_ptr = 0; - return tmp; - } - T* leakRef() - { - T* ptr = m_ptr; - m_ptr = 0; - return ptr; - } - T* leakPtr() - { - T* ptr = m_ptr; - m_ptr = 0; - return ptr; - } - - template<typename U> - RawPtr& operator=(U* ptr) - { - m_ptr = ptr; - return *this; - } - - template<typename U> - RawPtr& operator=(RawPtr<U> ptr) - { - m_ptr = ptr.get(); - return *this; - } - - RawPtr& operator=(std::nullptr_t) - { - m_ptr = 0; - return *this; - } - - operator T*() const { return m_ptr; } - T& operator*() const { return *m_ptr; } - T* operator->() const { return m_ptr; } - bool operator!() const { return !m_ptr; } - - void swap(RawPtr& o) - { - std::swap(m_ptr, o.m_ptr); - } - - static T* hashTableDeletedValue() { return reinterpret_cast<T*>(-1); } - -private: - static const uintptr_t rawPtrZapValue = 0x3a3a3a3a; - T* m_ptr; -}; - -template<typename T, typename U> inline RawPtr<T> static_pointer_cast(const RawPtr<U>& p) -{ - return RawPtr<T>(static_cast<T*>(p.get())); -} - -template<typename T> inline T* getPtr(const RawPtr<T>& p) -{ - return p.get(); -} - -} // namespace WTF - -using WTF::RawPtr; - -#endif
diff --git a/third_party/WebKit/Source/wtf/RefPtr.h b/third_party/WebKit/Source/wtf/RefPtr.h index 1737fad..4ed3ea5 100644 --- a/third_party/WebKit/Source/wtf/RefPtr.h +++ b/third_party/WebKit/Source/wtf/RefPtr.h
@@ -26,7 +26,6 @@ #include "wtf/Allocator.h" #include "wtf/HashTableDeletedValueType.h" #include "wtf/PassRefPtr.h" -#include "wtf/RawPtr.h" #include <algorithm> #include <utility> @@ -41,7 +40,6 @@ ALWAYS_INLINE RefPtr() : m_ptr(nullptr) {} ALWAYS_INLINE RefPtr(std::nullptr_t) : m_ptr(nullptr) {} ALWAYS_INLINE RefPtr(T* ptr) : m_ptr(ptr) { refIfNotNull(ptr); } - template <typename U> RefPtr(const RawPtr<U>& ptr, EnsurePtrConvertibleArgDecl(U, T)) : m_ptr(ptr.get()) { refIfNotNull(m_ptr); } ALWAYS_INLINE explicit RefPtr(T& ref) : m_ptr(&ref) { m_ptr->ref(); } ALWAYS_INLINE RefPtr(const RefPtr& o) : m_ptr(o.m_ptr) { refIfNotNull(m_ptr); } template <typename U> RefPtr(const RefPtr<U>& o, EnsurePtrConvertibleArgDecl(U, T)) : m_ptr(o.get()) { refIfNotNull(m_ptr); }
diff --git a/third_party/WebKit/Source/wtf/TerminatedArray.h b/third_party/WebKit/Source/wtf/TerminatedArray.h index 3134c258..a20cbeec 100644 --- a/third_party/WebKit/Source/wtf/TerminatedArray.h +++ b/third_party/WebKit/Source/wtf/TerminatedArray.h
@@ -77,12 +77,17 @@ typedef PassOwnPtr<TerminatedArray> PassPtr; typedef OwnPtr<TerminatedArray> Ptr; + static PassPtr release(Ptr& ptr) + { + return ptr.release(); + } + static PassPtr create(size_t capacity) { return adoptPtr(static_cast<TerminatedArray*>(WTF::Partitions::fastMalloc(capacity * sizeof(T), WTF_HEAP_PROFILER_TYPE_NAME(T)))); } - static PassPtr resize(PassPtr ptr, size_t capacity) + static PassPtr resize(Ptr ptr, size_t capacity) { return adoptPtr(static_cast<TerminatedArray*>(WTF::Partitions::fastRealloc(ptr.leakPtr(), capacity * sizeof(T), WTF_HEAP_PROFILER_TYPE_NAME(T)))); }
diff --git a/third_party/WebKit/Source/wtf/TerminatedArrayBuilder.h b/third_party/WebKit/Source/wtf/TerminatedArrayBuilder.h index eec01310..a7ec330 100644 --- a/third_party/WebKit/Source/wtf/TerminatedArrayBuilder.h +++ b/third_party/WebKit/Source/wtf/TerminatedArrayBuilder.h
@@ -35,7 +35,7 @@ } else { ASSERT(m_array->at(m_count - 1).isLastInArray()); m_capacity += count; - m_array = ArrayType<T>::Allocator::resize(m_array.release(), m_capacity); + m_array = ArrayType<T>::Allocator::resize(ArrayType<T>::Allocator::release(m_array), m_capacity); m_array->at(m_count - 1).setLastInArray(false); } m_array->at(m_capacity - 1).setLastInArray(true); @@ -54,7 +54,7 @@ { RELEASE_ASSERT(m_count == m_capacity); assertValid(); - return m_array.release(); + return ArrayType<T>::Allocator::release(m_array); } private:
diff --git a/third_party/WebKit/Source/wtf/TypeTraits.h b/third_party/WebKit/Source/wtf/TypeTraits.h index 4b9fef3..e3c9119 100644 --- a/third_party/WebKit/Source/wtf/TypeTraits.h +++ b/third_party/WebKit/Source/wtf/TypeTraits.h
@@ -37,8 +37,6 @@ return WTF_PRETTY_FUNCTION; } -template<typename T> class RawPtr; - template <typename T> struct IsWeak { static const bool value = false; }; @@ -331,11 +329,6 @@ public: static const bool value = IsGarbageCollectedType<T>::value; }; -template<typename T> -class IsPointerToGarbageCollectedType<RawPtr<T>> { -public: - static const bool value = IsGarbageCollectedType<T>::value; -}; } // namespace WTF
diff --git a/third_party/WebKit/Source/wtf/text/UTF8.cpp b/third_party/WebKit/Source/wtf/text/UTF8.cpp index a258db8..0beca10 100644 --- a/third_party/WebKit/Source/wtf/text/UTF8.cpp +++ b/third_party/WebKit/Source/wtf/text/UTF8.cpp
@@ -442,23 +442,5 @@ return equalWithUTF8Internal(a, aEnd, b, bEnd); } -bool isUTF8andNotASCII(const char* data, size_t length) -{ - // This cast is necessary because U8_NEXT uses int32_ts. - int32_t srcLen = static_cast<int32_t>(length); - int32_t charIndex = 0; - bool isASCIIOnly = true; - - while (charIndex < srcLen) { - int32_t codePoint; - if (static_cast<uint8_t>(data[charIndex]) >= 0x80) - isASCIIOnly = false; - U8_NEXT(data, charIndex, srcLen, codePoint); - if (!U_IS_UNICODE_CHAR(codePoint)) - return false; - } - return !isASCIIOnly; -} - } // namespace Unicode } // namespace WTF
diff --git a/third_party/WebKit/Source/wtf/text/UTF8.h b/third_party/WebKit/Source/wtf/text/UTF8.h index b0ba7dbd..eda26334 100644 --- a/third_party/WebKit/Source/wtf/text/UTF8.h +++ b/third_party/WebKit/Source/wtf/text/UTF8.h
@@ -70,12 +70,6 @@ WTF_EXPORT bool equalUTF16WithUTF8(const UChar* a, const UChar* aEnd, const char* b, const char* bEnd); WTF_EXPORT bool equalLatin1WithUTF8(const LChar* a, const LChar* aEnd, const char* b, const char* bEnd); - -// Given a sequence of bytes in |data| of length |len|, check if the content is -// encoded in UTF-8. Pure ASCII text is not regarded as UTF-8 in order to -// respect the default encoding since it can be of any encoding. -WTF_EXPORT bool isUTF8andNotASCII(const char* data, size_t length); - } // namespace Unicode } // namespace WTF
diff --git a/third_party/WebKit/Source/wtf/text/UTF8Test.cpp b/third_party/WebKit/Source/wtf/text/UTF8Test.cpp deleted file mode 100644 index 65c27ee..0000000 --- a/third_party/WebKit/Source/wtf/text/UTF8Test.cpp +++ /dev/null
@@ -1,63 +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 "wtf/text/UTF8.h" - -#include "testing/gtest/include/gtest/gtest.h" - -namespace WTF { -namespace Unicode { - -TEST(UTF8Test, IsUTF8andNotASCII) -{ - EXPECT_TRUE(isUTF8andNotASCII("\xc2\x81", 2)); - EXPECT_TRUE(isUTF8andNotASCII("\xe1\x80\xbf", 3)); - EXPECT_TRUE(isUTF8andNotASCII("\xf1\x80\xa0\xbf", 4)); - EXPECT_TRUE(isUTF8andNotASCII("a\xc2\x81\xe1\x80\xbf\xf1\x80\xa0\xbf", 10)); - - // Surrogate code points - EXPECT_FALSE(isUTF8andNotASCII("\xed\xa0\x80\xed\xbf\xbf", 6)); - EXPECT_FALSE(isUTF8andNotASCII("\xed\xa0\x8f", 3)); - EXPECT_FALSE(isUTF8andNotASCII("\xed\xbf\xbf", 3)); - - // Overlong sequences - EXPECT_FALSE(isUTF8andNotASCII("\xc0\x80", 2)); // U+0000 - EXPECT_FALSE(isUTF8andNotASCII("\xc1\x80\xc1\x81", 4)); // "AB" - EXPECT_FALSE(isUTF8andNotASCII("\xe0\x80\x80", 3)); // U+0000 - EXPECT_FALSE(isUTF8andNotASCII("\xe0\x82\x80", 3)); // U+0080 - EXPECT_FALSE(isUTF8andNotASCII("\xe0\x9f\xbf", 3)); // U+07ff - EXPECT_FALSE(isUTF8andNotASCII("\xf0\x80\x80\x8D", 4)); // U+000D - EXPECT_FALSE(isUTF8andNotASCII("\xf0\x80\x82\x91", 4)); // U+0091 - EXPECT_FALSE(isUTF8andNotASCII("\xf0\x80\xa0\x80", 4)); // U+0800 - EXPECT_FALSE(isUTF8andNotASCII("\xf0\x8f\xbb\xbf", 4)); // U+FEFF (BOM) - EXPECT_FALSE(isUTF8andNotASCII("\xf8\x80\x80\x80\xbf", 5)); // U+003F - EXPECT_FALSE(isUTF8andNotASCII("\xfc\x80\x80\x80\xa0\xa5", 6)); // U+00A5 - - // Beyond U+10FFFF (the upper limit of Unicode codespace) - EXPECT_FALSE(isUTF8andNotASCII("\xf4\x90\x80\x80", 4)); // U+110000 - EXPECT_FALSE(isUTF8andNotASCII("\xf8\xa0\xbf\x80\xbf", 5)); // 5 bytes - EXPECT_FALSE(isUTF8andNotASCII("\xfc\x9c\xbf\x80\xbf\x80", 6)); // 6 bytes - - // Non-characters : U+xxFFF[EF] where xx is 0x00 through 0x10 and <FDD0,FDEF> - EXPECT_FALSE(isUTF8andNotASCII("\xef\xbf\xbe", 3)); // U+FFFE - EXPECT_FALSE(isUTF8andNotASCII("\xf0\x8f\xbf\xbe", 4)); // U+1FFFE - EXPECT_FALSE(isUTF8andNotASCII("\xf3\xbf\xbf\xbf", 4)); // U+10FFFF - EXPECT_FALSE(isUTF8andNotASCII("\xef\xb7\x90", 3)); // U+FDD0 - EXPECT_FALSE(isUTF8andNotASCII("\xef\xb7\xaf", 3)); // U+FDEF - - // Strings in legacy encodings. - EXPECT_FALSE(isUTF8andNotASCII("caf\xe9", 4)); // cafe with U+00E9 in ISO-8859-1 - EXPECT_FALSE(isUTF8andNotASCII("\xb0\xa1\xb0\xa2", 4)); // U+AC00, U+AC001 in EUC-KR - EXPECT_FALSE(isUTF8andNotASCII("\xa7\x41\xa6\x6e", 4)); // U+4F60 U+597D in Big5 - // "abc" with U+201[CD] in windows-125[0-8] - EXPECT_FALSE(isUTF8andNotASCII("\x93" "abc\x94", 4)); - // U+0639 U+064E U+0644 U+064E in ISO-8859-6 - EXPECT_FALSE(isUTF8andNotASCII("\xd9\xee\xe4\xee", 4)); - // U+03B3 U+03B5 U+03B9 U+03AC in ISO-8859-7 - EXPECT_FALSE(isUTF8andNotASCII("\xe3\xe5\xe9\xdC", 4)); - EXPECT_FALSE(isUTF8andNotASCII("abc", 3)); // plain ASCII -} - -} // namespace Unicode -} // namespace WTF
diff --git a/third_party/WebKit/Source/wtf/wtf.gypi b/third_party/WebKit/Source/wtf/wtf.gypi index 1a65dfe..fe778a0 100644 --- a/third_party/WebKit/Source/wtf/wtf.gypi +++ b/third_party/WebKit/Source/wtf/wtf.gypi
@@ -225,7 +225,6 @@ 'text/StringOperatorsTest.cpp', 'text/TextCodecReplacementTest.cpp', 'text/TextCodecUTF8Test.cpp', - "text/UTF8Test.cpp", 'text/WTFStringTest.cpp', 'typed_arrays/ArrayBufferBuilderTest.cpp', ],
diff --git a/third_party/WebKit/public/platform/WebPrivatePtr.h b/third_party/WebKit/public/platform/WebPrivatePtr.h index 6080e14..0ff0258 100644 --- a/third_party/WebKit/public/platform/WebPrivatePtr.h +++ b/third_party/WebKit/public/platform/WebPrivatePtr.h
@@ -143,7 +143,7 @@ template<typename T, WebPrivatePtrDestruction crossThreadDestruction, WebPrivatePtrStrength strongOrWeak> class PtrStorageImpl<T, crossThreadDestruction, strongOrWeak, GarbageCollectedLifetime> { public: - void assign(const RawPtr<T>& val) + void assign(T* val) { if (!val) { release(); @@ -156,8 +156,7 @@ (*m_handle) = val; } - void assign(T* ptr) { assign(RawPtr<T>(ptr)); } - template<typename U> void assign(const RawPtr<U>& val) { assign(RawPtr<T>(val)); } + template<typename U> void assign(U* val) { assign(static_cast<T*>(val)); } void assign(const PtrStorageImpl& other) { assign(other.get()); } @@ -176,7 +175,7 @@ template<typename T, WebPrivatePtrDestruction crossThreadDestruction, WebPrivatePtrStrength strongOrWeak> class PtrStorageImpl<T, crossThreadDestruction, strongOrWeak, RefCountedGarbageCollectedLifetime> : public PtrStorageImpl<T, crossThreadDestruction, strongOrWeak, GarbageCollectedLifetime> { public: - void assign(const RawPtr<T>& val) { PtrStorageImpl<T, crossThreadDestruction, strongOrWeak, GarbageCollectedLifetime>::assign(val.get()); } + void assign(T* val) { PtrStorageImpl<T, crossThreadDestruction, strongOrWeak, GarbageCollectedLifetime>::assign(val); } void assign(const PtrStorageImpl& other) { PtrStorageImpl<T, crossThreadDestruction, strongOrWeak, GarbageCollectedLifetime>::assign(other.get()); } };
diff --git a/tools/android/loading/sandwich_misc.py b/tools/android/loading/sandwich_misc.py index 13988c3..e7b00c6 100644 --- a/tools/android/loading/sandwich_misc.py +++ b/tools/android/loading/sandwich_misc.py
@@ -15,10 +15,10 @@ REDIRECTED_MAIN_DISCOVERER = 'redirected-main' # All resources which are fetched from the main document and their redirections. -PARSER_DISCOVERER = 'parser', +PARSER_DISCOVERER = 'parser' # Simulation of HTMLPreloadScanner on the main document and their redirections. -HTML_PRELOAD_SCANNER_DISCOVERER = 'html-scanner', +HTML_PRELOAD_SCANNER_DISCOVERER = 'html-scanner' SUBRESOURCE_DISCOVERERS = set([ REDIRECTED_MAIN_DISCOVERER,
diff --git a/tools/mb/mb.py b/tools/mb/mb.py index ae7de3f2..b1ecae2d 100755 --- a/tools/mb/mb.py +++ b/tools/mb/mb.py
@@ -81,6 +81,12 @@ '(default is //tools/mb/mb_config.pyl)') subp.add_argument('-g', '--goma-dir', help='path to goma directory') + subp.add_argument('--android-version-code', + help='Sets GN arg android_default_version_code and ' + 'GYP_DEFINE app_manifest_version_code') + subp.add_argument('--android-version-name', + help='Sets GN arg android_default_version_name and ' + 'GYP_DEFINE app_manifest_version_name') subp.add_argument('-n', '--dryrun', action='store_true', help='Do a dry run (i.e., do nothing, just print ' 'the commands that will run)') @@ -880,6 +886,14 @@ if self.args.goma_dir: gn_args += ' goma_dir="%s"' % self.args.goma_dir + android_version_code = self.args.android_version_code + if android_version_code: + gn_args += ' android_default_version_code="%s"' % android_version_code + + android_version_name = self.args.android_version_name + if android_version_name: + gn_args += ' android_default_version_name="%s"' % android_version_name + # Canonicalize the arg string into a sorted, newline-separated list # of key-value pairs, and de-dup the keys if need be so that only # the last instance of each arg is listed. @@ -1042,6 +1056,14 @@ if goma_dir: gyp_defines += ' gomadir=%s' % goma_dir + android_version_code = self.args.android_version_code + if android_version_code: + gyp_defines += ' app_manifest_version_code=%s' % android_version_code + + android_version_name = self.args.android_version_name + if android_version_name: + gyp_defines += ' app_manifest_version_name=%s' % android_version_name + cmd = [ self.executable, self.PathJoin('build', 'gyp_chromium'),
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index eb23a45..d044e3c 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -214,6 +214,9 @@ 'WinClang': 'win_clang_debug_bot', 'Windows Browser (DrMemory light) (1)': 'none', 'Windows Browser (DrMemory light) (2)': 'none', + + 'Linux Kitchen (kitchen_run)': 'swarming_gn_release_bot', + 'Linux Kitchen (annotated_run)': 'swarming_gn_release_bot', }, 'chromium.gpu': {
diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index f7e9c7a..3cb1d1a 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml
@@ -7903,6 +7903,93 @@ <description>A tab is no longer audible.</description> </action> +<action name="Media.Controls.Cast"> + <owner>mlamouri@chromium.org</owner> + <description>The user clicked on the cast controls button.</description> +</action> + +<action name="Media.Controls.CastOverlay"> + <owner>mlamouri@chromium.org</owner> + <description>The user clicked on the cast overlay button.</description> +</action> + +<action name="Media.Controls.ClosedCaptionHide"> + <owner>mlamouri@chromium.org</owner> + <description>The user hid the closed caption from the controls.</description> +</action> + +<action name="Media.Controls.ClosedCaptionShow"> + <owner>mlamouri@chromium.org</owner> + <description> + The user showed the closed caption from the controls. + </description> +</action> + +<action name="Media.Controls.EnterFullscreen"> + <owner>mlamouri@chromium.org</owner> + <description>The user entered fullscreen mode from the controls.</description> +</action> + +<action name="Media.Controls.ExitFullscreen"> + <owner>mlamouri@chromium.org</owner> + <description>The user left fullscreen mode from the controls.</description> +</action> + +<action name="Media.Controls.Mute"> + <owner>mlamouri@chromium.org</owner> + <description>The user muted a media element from the controls.</description> +</action> + +<action name="Media.Controls.Pause"> + <owner>mlamouri@chromium.org</owner> + <description>The user paused a media element from the controls.</description> +</action> + +<action name="Media.Controls.Play"> + <owner>mlamouri@chromium.org</owner> + <description>The user played a media element from the controls.</description> +</action> + +<action name="Media.Controls.PlayOverlay"> + <owner>mlamouri@chromium.org</owner> + <description> + The user played a media element from the play overlay button. + </description> +</action> + +<action name="Media.Controls.ScrubbingBegin"> + <owner>mlamouri@chromium.org</owner> + <description> + The user started to interact with the control's scrubber. + </description> +</action> + +<action name="Media.Controls.ScrubbingEnd"> + <owner>mlamouri@chromium.org</owner> + <description> + The user stopped interacting with the control's scrubber. + </description> +</action> + +<action name="Media.Controls.Unmute"> + <owner>mlamouri@chromium.org</owner> + <description>The user unmuted a media element from the controls.</description> +</action> + +<action name="Media.Controls.VolumeChangeBegin"> + <owner>mlamouri@chromium.org</owner> + <description> + The user started to interact with the control's volume slider. + </description> +</action> + +<action name="Media.Controls.VolumeChangeEnd"> + <owner>mlamouri@chromium.org</owner> + <description> + The user stopped interacting with the control's volume slider. + </description> +</action> + <action name="MediaContextMenu_Controls"> <owner>Please list the metric's owners. Add more owner tags as needed.</owner> <description>Please enter the description of this user action.</description> @@ -12544,6 +12631,14 @@ <description>Please enter the description of this user action.</description> </action> +<action name="Signin_AccountSettings_GoogleActivityControlsClicked"> + <owner>mahmadi@chromium.org</owner> + <description> + Recorded when the user clicks the "Google Activity Controls" link + in the account settings page. + </description> +</action> + <action name="Signin_AddAccountToDevice"> <owner>gogerald@chromium.org</owner> <description>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 33990e76..4e83b0c 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -57444,6 +57444,16 @@ </details> </histogram> +<histogram name="WebCore.Framebust" enum="FramebustPermissions"> + <owner>japhet@chromium.org</owner> + <summary> + Records instances of child frames navigating the top frame. Includes whether + or not the navigation would have been permitted if not for our special case + for 'framebusting', the practice of ensuring a given document is never + displayed in a frame. + </summary> +</histogram> + <histogram name="WebCore.IndexedDB.BackingStore.ConsistencyError" enum="IDBLevelDBBackingStoreInternalErrorType"> <owner>dgrogan@chromium.org</owner> @@ -71710,6 +71720,13 @@ <int value="5" label="GNOME failure"/> </enum> +<enum name="FramebustPermissions" type="int"> + <int value="0" label="Only permitted for framebusting, no user gesture"/> + <int value="1" label="Only permitted for framebusting, user gesture"/> + <int value="2" label="Allowed navigation, no user gesture"/> + <int value="3" label="Allowed navigation, user gesture"/> +</enum> + <enum name="FtpDataConnectionError" type="int"> <int value="0">Data connection successful</int> <int value="1">Local firewall blocked the connection</int> @@ -76230,6 +76247,8 @@ <int value="529" label="column-span"/> <int value="530" label="column-width"/> <int value="531" label="columns"/> + <int value="532" label="apply-at-rule"/> + <int value="533" label="font-variant-caps"/> </enum> <enum name="MappedEditingCommands" type="int">
diff --git a/tools/origin_trials/generate_token.py b/tools/origin_trials/generate_token.py index 54e61c64..3b4447bb 100755 --- a/tools/origin_trials/generate_token.py +++ b/tools/origin_trials/generate_token.py
@@ -14,8 +14,10 @@ """ import argparse import base64 +import json import re import os +import struct import sys import time import urlparse @@ -29,6 +31,9 @@ # no longer than 63 ASCII characters) DNS_LABEL_REGEX = re.compile(r"^(?!-)[a-z\d-]{1,63}(?<!-)$", re.IGNORECASE) +# This script generates Version 2 tokens. +VERSION = "\x02" + def HostnameFromArg(arg): """Determines whether a string represents a valid hostname. @@ -75,13 +80,19 @@ return (int(time.time()) + (int(args.expire_days) * 86400)) def GenerateTokenData(origin, api_name, expiry): - return "{0}|{1}|{2}".format(origin, api_name, expiry) + return json.dumps({"origin": origin, + "feature": api_name, + "expiry": expiry}).encode('utf-8') + +def GenerateDataToSign(version, data): + return version + struct.pack(">I",len(data)) + data def Sign(private_key, data): return ed25519.signature(data, private_key[:32], private_key[32:]) def FormatToken(version, signature, data): - return version + "|" + base64.b64encode(signature) + "|" + data + return base64.b64encode(version + signature + + struct.pack(">I",len(data)) + data) def main(): parser = argparse.ArgumentParser( @@ -123,11 +134,12 @@ sys.exit(1) token_data = GenerateTokenData(args.origin, args.trial_name, expiry) - signature = Sign(private_key, token_data) + data_to_sign = GenerateDataToSign(VERSION, token_data) + signature = Sign(private_key, data_to_sign) # Verify that that the signature is correct before printing it. try: - ed25519.checkvalid(signature, token_data, private_key[32:]) + ed25519.checkvalid(signature, data_to_sign, private_key[32:]) except Exception, exc: print "There was an error generating the signature." print "(The original error was: %s)" % exc @@ -135,7 +147,7 @@ # Output a properly-formatted token. Version 1 is hard-coded, as it is # the only defined token version. - print FormatToken("1", signature, token_data) + print FormatToken(VERSION, signature, token_data) if __name__ == "__main__": main()
diff --git a/tools/perf/benchmarks/v8.py b/tools/perf/benchmarks/v8.py index 873fdc65..fcd997c 100644 --- a/tools/perf/benchmarks/v8.py +++ b/tools/perf/benchmarks/v8.py
@@ -242,7 +242,7 @@ category_filter.AddIncludedCategory('v8') category_filter.AddIncludedCategory('blink.console') options = timeline_based_measurement.Options(category_filter) - options.SetLegacyTimelineBasedMetrics([v8_execution.V8ExecutionMetric()]) + options.SetTimelineBasedMetric('executionMetric') return options def CreateStorySet(self, options):
diff --git a/tools/perf/measurements/oilpan_gc_times.py b/tools/perf/measurements/oilpan_gc_times.py index ea753333..8bdaf93b 100644 --- a/tools/perf/measurements/oilpan_gc_times.py +++ b/tools/perf/measurements/oilpan_gc_times.py
@@ -72,7 +72,7 @@ if event.name == 'ThreadHeap::coalesce': values['oilpan_coalesce'].append(duration) continue - if event.name == 'Heap::collectGarbage': + if event.name == 'BlinkGCMarking': if reason is not None: values['oilpan_%s_mark' % reason].append(mark_time) values['oilpan_%s_lazy_sweep' % reason].append(lazy_sweep_time)
diff --git a/tools/perf/measurements/oilpan_gc_times_unittest.py b/tools/perf/measurements/oilpan_gc_times_unittest.py index dd129b58d..06dc9c5d 100644 --- a/tools/perf/measurements/oilpan_gc_times_unittest.py +++ b/tools/perf/measurements/oilpan_gc_times_unittest.py
@@ -75,7 +75,7 @@ that all metrics were added to the results. The test is purely functional, i.e. it only checks if the metrics are present and non-zero. """ - _KEY_MARK = 'Heap::collectGarbage' + _KEY_MARK = 'BlinkGCMarking' _KEY_LAZY_SWEEP = 'ThreadHeap::lazySweepPages' _KEY_COMPLETE_SWEEP = 'ThreadState::completeSweep' _KEY_COALESCE = 'ThreadHeap::coalesce'
diff --git a/tools/roll_webrtc.py b/tools/roll_webrtc.py index f016fb3..94f421c 100755 --- a/tools/roll_webrtc.py +++ b/tools/roll_webrtc.py
@@ -38,6 +38,9 @@ WEBRTC_PATH = os.path.join('third_party', 'webrtc') 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,' + 'tryserver.chromium.mac:mac_chromium_archive_rel_ng') # Result codes from build/third_party/buildbot_8_4p1/buildbot/status/results.py # plus the -1 code which is used when there's no result yet. @@ -184,6 +187,7 @@ description.extend(['-m', libjingle_str]) description.extend(['-m', 'Changes: %s' % libjingle_changelog_url]) description.extend(['-m', 'TBR=']) + description.extend(['-m', 'CQ_EXTRA_TRYBOTS=%s' % EXTRA_TRYBOTS]) return description
diff --git a/ui/app_list/app_list_constants.cc b/ui/app_list/app_list_constants.cc index b9590a3..9471460 100644 --- a/ui/app_list/app_list_constants.cc +++ b/ui/app_list/app_list_constants.cc
@@ -126,7 +126,7 @@ const size_t kNumFolderTopItems = 4; // Maximum length of the folder name in chars. -const size_t kMaxFolderNameChars = 40; +const size_t kMaxFolderNameChars = 80; // Font style for app item labels. const ui::ResourceBundle::FontStyle kItemTextFontStyle =
diff --git a/ui/file_manager/audio_player/elements/audio_player.js b/ui/file_manager/audio_player/elements/audio_player.js index fa1213a..cbfd66c 100644 --- a/ui/file_manager/audio_player/elements/audio_player.js +++ b/ui/file_manager/audio_player/elements/audio_player.js
@@ -5,6 +5,14 @@ Polymer({ is: 'audio-player', + listeners: { + 'toggle-pause-event': 'onTogglePauseEvent_', + 'small-forward-skip-event': 'onSmallForwardSkipEvent_', + 'small-backword-skip-event': 'onSmallBackwordSkipEvent_', + 'big-forward-skip-event': 'onBigForwardSkipEvent_', + 'big-backword-skip-event': 'onBigBackwordSkipEvent_', + }, + properties: { /** * Flag whether the audio is playing or paused. True if playing, or false @@ -443,5 +451,45 @@ */ computeAudioVolume_: function(volume) { return volume / 100; - } + }, + + /** + * Toggle pause. + * @private + */ + onTogglePauseEvent_: function(event) { + this.$.audioController.playClick(); + }, + + /** + * Small skip forward. + * @private + */ + onSmallForwardSkipEvent_: function(event) { + this.$.audioController.smallSkip(true); + }, + + /** + * Small skip backword. + * @private + */ + onSmallBackwordSkipEvent_: function(event) { + this.$.audioController.smallSkip(false); + }, + + /** + * Big skip forward. + * @private + */ + onBigForwardSkipEvent_: function(event) { + this.$.audioController.bigSkip(true); + }, + + /** + * Big skip backword. + * @private + */ + onBigBackwordSkipEvent_: function(event) { + this.$.audioController.bigSkip(false); + }, });
diff --git a/ui/file_manager/audio_player/elements/control_panel.js b/ui/file_manager/audio_player/elements/control_panel.js index a07a136..ff36640a 100644 --- a/ui/file_manager/audio_player/elements/control_panel.js +++ b/ui/file_manager/audio_player/elements/control_panel.js
@@ -211,7 +211,8 @@ /** * Skips forward/backword. - * @param {number} sec Seconds to skip. Set negative value to skip backword. + * @param {number} millis Milliseconds to skip. Set negative value to skip + * backword. * @private */ skip_: function(millis) {
diff --git a/ui/file_manager/audio_player/js/audio_player.js b/ui/file_manager/audio_player/js/audio_player.js index 2397eda..cb05f2e 100644 --- a/ui/file_manager/audio_player/js/audio_player.js +++ b/ui/file_manager/audio_player/js/audio_player.js
@@ -371,23 +371,23 @@ case 'U+0020': // Space case 'U+004B': // K - this.player_.$.audioController.playClick(); + this.player_.dispatchEvent(new Event('toggle-pause-event')); break; case 'Up': case 'Right': if (event.target.id !== 'volumeSlider') - this.player_.$.audioController.smallSkip(true); + this.player_.dispatchEvent(new Event('small-forward-skip-event')); break; case 'Down': case 'Left': if (event.target.id !== 'volumeSlider') - this.player_.$.audioController.smallSkip(false); + this.player_.dispatchEvent(new Event('small-backword-skip-event')); break; case 'U+004C': // L - this.player_.$.audioController.bigSkip(true); + this.player_.dispatchEvent(new Event('big-forward-skip-event')); break; case 'U+004A': // J - this.player_.$.audioController.bigSkip(false); + this.player_.dispatchEvent(new Event('big-backword-skip-event')); break; } };
diff --git a/ui/file_manager/externs/files_elements.js b/ui/file_manager/externs/files_elements.js index 757efacd..fb43176 100644 --- a/ui/file_manager/externs/files_elements.js +++ b/ui/file_manager/externs/files_elements.js
@@ -42,49 +42,3 @@ */ FilesToast.prototype.hide = function() {}; -/** - * @constructor - * @struct - * @extends {PolymerElement} - */ -function AudioPlayerElement() {} - -/** @type {boolean} */ -AudioPlayerElement.prototype.playing; - -/** @type {number} */ -AudioPlayerElement.prototype.time; - -/** @type {boolean} */ -AudioPlayerElement.prototype.shuffule; - -/** @type {boolean} */ -AudioPlayerElement.prototype.repeat; - -/** @type {number} */ -AudioPlayerElement.prototype.volume; - -/** @type {boolean} */ -AudioPlayerElement.prototype.expanded; - -/** @type {number} */ -AudioPlayerElement.prototype.currentTrackIndex; - -/** @type {string} */ -AudioPlayerElement.prototype.currenttrackurl; - -/** @type {number} */ -AudioPlayerElement.prototype.playcount; - -/** @type {Array<!Object>} */ -AudioPlayerElement.prototype.tracks; - -/** @type {Object} */ -AudioPlayerElement.prototype.model; - -/** @type {boolean} */ -AudioPlayerElement.prototype.volumeSliderShown; - -AudioPlayerElement.prototype.onPageUnload = function() {}; - -AudioPlayerElement.prototype.onAudioError = function() {};
diff --git a/ui/gfx/color_palette.h b/ui/gfx/color_palette.h index cb7271a..6117d07 100644 --- a/ui/gfx/color_palette.h +++ b/ui/gfx/color_palette.h
@@ -11,7 +11,7 @@ // A placeholder value for unset colors. This should never be visible and is red // as a visual flag for misbehaving code. -const SkColor kPlaceholderColor = SK_ColorRED; +constexpr SkColor kPlaceholderColor = SK_ColorRED; const SkColor kChromeIconGrey = SkColorSetRGB(0x5A, 0x5A, 0x5A);
diff --git a/ui/ozone/ozone.gyp b/ui/ozone/ozone.gyp index 0458cf34..39216b5 100644 --- a/ui/ozone/ozone.gyp +++ b/ui/ozone/ozone.gyp
@@ -115,6 +115,7 @@ '<(DEPTH)/ui/events/ozone/events_ozone.gyp:events_ozone', '<(DEPTH)/ui/gfx/gfx.gyp:gfx', '<(DEPTH)/ui/gfx/gfx.gyp:gfx_geometry', + '<(DEPTH)/ui/gfx/ipc/gfx_ipc.gyp:gfx_ipc', '<(DEPTH)/ui/gfx/ipc/skia/gfx_ipc_skia.gyp:gfx_ipc_skia', '<@(external_ozone_platform_deps)', '<@(internal_ozone_platform_deps)',
diff --git a/ui/views/mus/aura_init.cc b/ui/views/mus/aura_init.cc index 0b44e720..c3217f84 100644 --- a/ui/views/mus/aura_init.cc +++ b/ui/views/mus/aura_init.cc
@@ -14,6 +14,7 @@ #include "services/shell/public/cpp/connector.h" #include "ui/aura/env.h" #include "ui/base/ime/input_method_initializer.h" +#include "ui/base/material_design/material_design_controller.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_paths.h" #include "ui/views/views_delegate.h" @@ -55,6 +56,7 @@ : resource_file_(resource_file), env_(aura::Env::CreateInstance()), views_delegate_(new MusViewsDelegate) { + ui::MaterialDesignController::Initialize(); InitializeResources(connector); ui::InitializeInputMethodForTesting();
diff --git a/ui/webui/resources/images/200-logo_chrome.png b/ui/webui/resources/images/200-logo_chrome.png new file mode 100644 index 0000000..c283720 --- /dev/null +++ b/ui/webui/resources/images/200-logo_chrome.png Binary files differ
diff --git a/ui/webui/resources/images/200-logo_googleg.png b/ui/webui/resources/images/200-logo_googleg.png new file mode 100644 index 0000000..85f92c0 --- /dev/null +++ b/ui/webui/resources/images/200-logo_googleg.png Binary files differ